#!/usr/bin/env python3
r"""Nonplanar T_4 for qqbar -> W+W- (two loops, exact top mass): standalone evaluator.

The 79 components (76 master integrals + 3 auxiliaries) of the nonplanar
double-box branch of two-loop q qbar -> W+ W- — the branch (fig 1d) that the
planar computation of arXiv:2409.08879 did not treat — on the kinematic line
(x, z) = (17/2, 5/3) with y free. Construction and verification: the
qqww-t4 results page and Sec. 2.18 of the portfolio paper (both link this
bundle); the closed forms are written out in qqww-t4-expression.md and the
boundary constants in qqww-t4-boundary.json beside this script.
The two Kira reductions withheld from this line's fit ship under row35_L1/
and `--verify-exact` (on the default line, L1) re-verifies the connection
against them entry by entry in exact arithmetic; the same connection
reconstructed exactly along a SECOND line, L2 = (17/2, 7/4), ships under
row35_L2/ with its own two withheld reductions, and `--line L2
--verify-exact` does the same there (EXACT VERIFICATION below).
The value tiers are the first line's and refuse on L2 by name.  On each
line the canonical-basis census of the connection's diagonal blocks ships
as row35_<line>/blocks_epsform.json and `--line L1|L2 --canonical-blocks`
re-checks it exactly (CANONICAL BLOCKS below).  The Mellin-Barnes
representations of the three corner rows of the boundary (69, 42, 43)
ship as provenance objects under vendor_row35_mb_corner/ and
`--mb-corner-provenance` prints them with their certificates, read from
those files by key (MB CORNER ROWS below); no digit of theirs enters
--check or any other served gate.

REQUIREMENTS: python3 with the mpmath and python-flint libraries. Nothing
else — no network, no computer-algebra system, no reduction software.

SHIPPED BESIDE THIS SCRIPT (all read relative to the script's directory):
  row35_data.json          the exact 79x79 line connection A(d,y) (1240
                           rational entries N(d,y)/Q(d,y)), the independent
                           reference values at y=1/2 and y=3/5, the
                           step-control pole list, and legacy boundary
                           Laurent strings (compare-cache only — checked at
                           load, never a value source)
  row35_reference_im.json  the imaginary parts of the same independent
                           reference values at y=1/2 and y=3/5 (midpoint
                           strings per row and eps-order, the 36 complex
                           rows named; sha256-pinned in this script,
                           PINS_IM); read by --gate-im only, never by a
                           value tier
  row35_radical_feed.json  certified closed forms of radical sectors
                           417/449/482 (masters 27-29, 45-47, 60-62)
  row35_nodes.tar.gz       the certified boundary node bank: 48 fresh
                           boundary solves (24 primes x two precisions,
                           two-precision certificate min 124.2 digits),
                           re-verified against its sha manifest at EVERY
                           load. Unpack it so row35_nodes/ sits beside this
                           script: tar xzf row35_nodes.tar.gz
  vopclose_vendored.py     closed-form container engine (mpmath + flint)
  epsfan_vendored.py       certified eps-fan extraction engine
  qqww-t4-sector487.json   the sector-487 exact rational basis (consumed by
                           --check-expression)
  qqww-t4-expression.md    the written-out form of record (79 rows, blocks,
                           alphabet, bases, the X0(2) anchor derivation)
  qqww-t4-boundary.json    the 395 boundary constants as digit strings
  qqww-t4-tower12-layers.json  first two eps-layers of the main GPL tower
  row35_L2/                the SECOND LINE L2 = (17/2, 7/4): connection_L2.json
                           (the exact 79x79 connection reconstructed along
                           that line; the same 1240-entry form as
                           row35_data.json), the two withheld Kira
                           reductions withheld_y296o101.json and
                           withheld_y306o103.json (the record objects, byte
                           for byte), points.json (the 91-point set: every
                           y, its role, its reduction's sha256, the d-nodes)
                           and lines.json (both lines by their kinematics
                           with the record's verdicts and the first
                           line's withheld-reduction provenance); every
                           file sha256-pinned in this script (PINS_L2)
  row35_L1/                the FIRST line's two withheld Kira reductions,
                           withheld_y29o211.json and withheld_y17o139.json
                           (y = 29/211 and 17/139 at (x, z) = (17/2, 5/3);
                           the record objects, byte for byte; sha256-pinned
                           in this script, PINS_L1); consumed by
                           --verify-exact on the default line
  row35_L1/blocks_epsform.json, row35_L2/blocks_epsform.json
                           the canonical-basis census of each line's 35
                           non-elliptic diagonal blocks: per block the
                           sector, size, rows, masters, the engine's
                           verdict, the stop string verbatim for the 6
                           stopped blocks and, for the 29 factorised
                           blocks, the rotation T(eps, y) and the dlog
                           connection Atilde(y) as the engine's strings,
                           the letters (rational poles named by their
                           alphabet letter, the quadratic letter) and the
                           exact residue matrices; consumed by
                           --canonical-blocks on the line
  row35_L2/canonical_gauge_L1_L2.json
                           the constant gauge G relating the two lines'
                           block forms letter by letter (G = identity on
                           24 blocks, nontrivial on 227, 321, 327, 355,
                           485) with the matched residue pairs; the
                           three files sha256-pinned in this script
                           (PINS_CANON)
  vendor_row35_mb_corner/  the Mellin-Barnes corner rows of the boundary as
                           provenance objects, 17 files (row69/, row42/,
                           row43/ and MB_CORNER_MANIFEST.sha256, every one
                           sha256-pinned in this script, PINS_MB_CORNER): the
                           record's written representations of rows 69 and
                           42 (mb_row69.py, mb_row42.py, read as text), the
                           written representation of row 43
                           (ROW43_MB_REPRESENTATION.json), the row-69 gates
                           at eps = 1/1013 and 1/1117 and its collapse
                           certificates, the row-42 pilot certificates, the
                           independent collapsed-integrand libraries
                           (r69_lib.py, r42_lib.py; imported only under
                           --mb-corner-provenance --rederive) and their
                           producers as text; consumed by
                           --mb-corner-provenance, never by a value tier

HOSTED SEPARATELY IN THIS BUNDLE (unpack beside the script):
  row35_chain.tar.gz — the boundary-regeneration chain (the gate driver,
  the production driver that solved the node bank, their python
  dependencies, the exact boundary tables, the fixed-d0 oracle and the
  recorded gate reports). --boundary-recompute needs it and RUNS when
  row35_chain/ is unpacked beside this script (every member verified
  against the chain's own sha manifest first); absent, the mode refuses
  with exit code 4 and prints the container's name, sha256 and size.

NOT HOSTED WITH THIS BUNDLE (named for honesty; CONTAINERS.md beside this
script lists each one by file name, sha256 and byte size, and its machine-
readable twin containers.json is what this script checks against):
  row35_radical_feed_b421.json / row35_radical_feed_b453.json — the
  closed-form containers of sectors 421/453 run to about a gigabyte
  together and are not hosted. Without them the six masters 33-35/48-50
  are evaluated by transport like every other non-folded row (same
  certificates, same comparison against the reference values); if the two
  files are placed beside the script they are loaded automatically, after
  a size + sha256 check against containers.json (a mismatch refuses with
  exit code 3). Cost while loaded (measured): about 22 GB of memory per
  fold pass (two passes per block, up to four at once at the default
  --jobs; --jobs 1 runs them one at a time) and tens of minutes per pass.
  --nodes-source fresh:DIR and --e4-extract stay outside this download
  (their consumer code is not included); each refuses with a one-line
  message naming what it needs.  `python3 eval_row35.py --containers`
  prints the status of every container as found beside the script.

WHAT A RUN COMPUTES LIVE (stored verdicts are never trusted):
  1. The exact connection A(d,y) is evaluated exactly (Fraction arithmetic)
     at 24 fixed dimensions d0 = 4 - 2/q, q prime.
  2. For each q the 79-vector I(eps=1/q, y) is transported from the base
     point y=1/3 to the target y by arb (python-flint) Taylor jets with
     complex-pole clearance and measured-geometric-tail step control.
  3. The eps-Laurent coefficients c_{-2}..c_{1} at the target are
     re-extracted by a Vandermonde solve with interleaved verify nodes;
     the verify-node residual is the printed self-consistency error bar.
  4. Radical sectors 417/449/482 are evaluated directly from their
     certified closed forms instead of the transport.
  At load, four checks all refuse on failure (nonzero exit): the node-bank
  sha manifest, the bank's two-precision certificate, the legacy-string
  compare-cache, and the closed-form boundary-constant refresh with its
  producer-vs-certifier cross-check. --mutate perturbs one bank node value
  by a relative 1e-30 and must make the run refuse — the shipped control.

DEFAULT RUN (no flags): y = 1/2 at dps 40 with the small master subset
  0,3,60 (its DE dependency closure; one classical, one coupled dlog, one
  closed-form radical master), each compared against the independent
  reference values with a printed digits-of-agreement line per master.
  Exit 0 only if every check passes. The reference values were produced by
  an independent evaluator and were never used in any fit.
  The full suite is --gate-full: all 79 rows at both reference points
  y=1/2 and y=3/5 (long — measured at 2963 s on 48 cores; scale up wall
  accordingly on fewer cores).

EXACT VERIFICATION (--verify-exact; --line L1, the default, or --line L2):
  On each line the connection's exact y-dependence was reconstructed from
  91 Kira differential-equation points (on L2, 89 in the fit and the two
  of largest y withheld); on either line the plain fit closes 1220 of the
  1240 entries and the same known-denominator rescue fit closes the twenty
  of masters 75-78 (row35_L2/points.json names them). `--verify-exact`
  evaluates every entry of the line's shipped connection at a d outside
  the fit's d-nodes and at the line's two withheld y in exact Fraction
  arithmetic and compares it entry by entry with the withheld Kira
  reduction at that y, which is evaluated exactly at the same d from its
  record strings:
    --line L1 (the default): row35_data.json at d = 890/223 and y = 29/211,
      17/139 against row35_L1/ (the first line's two withheld reductions,
      re-reduced 2026-09-06 with the line's own harness; row35_L2/lines.json
      carries their provenance). Measured wall 2.29 s (one core).
    --line L2: row35_L2/connection_L2.json at d = 7/3 and y = 296/101,
      306/103 against the two reductions withheld from the L2 fit.
      Measured wall 5.14 s (one core).
  1240/1240 exact at both points is the pass line (rc 0); every mismatched
  or unclosed entry is named (rc 1). No transport, no node bank, no
  floating point. `--mutate` on either tier changes one digit of one
  vendored connection entry in memory and must FAIL by name. Exit codes on
  these tiers: 0 PASS / 1 FAIL / 2 refused / 3 a pinned file's sha256 or a
  header differs / 4 a pinned file missing. The pins: PINS_L1 (the two
  row35_L1/ files) and PINS_L2 (every row35_L2/ file); the first line's
  connection row35_data.json is checked against the sha256 that
  row35_L2/lines.json records for it, and the master hash the two lines
  share is read from row35_L2/connection_L2.json.
  The value tiers (default, --point, --gate-full, --master, --check,
  --cached) and --check-expression are the FIRST line's: the certified
  node bank, the base point y = 1/3, the compare-cache strings and the
  reference values were all computed at (x, z) = (17/2, 5/3), and the
  record holds no boundary data on L2 -- under --line L2 they refuse by
  name (rc 2). --line L1 (the default) leaves every value tier exactly as
  it was. Both tiers are exactness checks of the one-variable
  reconstruction on a line, not a statement about the two-variable
  function, which remains open.

CANONICAL BLOCKS (--canonical-blocks; --line L1, the default, or --line L2):
  On each line the 36 diagonal blocks of the connection were run through
  the eps-factoriser one at a time (sector 481 was not run through it:
  its maximal-cut curve is elliptic, j non-constant in z5, while its
  eps^0 block is reducible to first order -- six exact hyperexponential
  factors, the sector_481 entry of the census file -- and its full block
  is regular singular with the exponent -3/2 at the chain's two conic
  letters, so no rational-letter eps-form exists on the line): 29 admit a rational rotation
  T(eps, y) to an eps-factorised dlog form eps * Atilde(y) on either
  line (28 in the Laporta basis of this count and sector 487 in the
  basis with [1,1,1,-1,-1,1,1,1,1] in place of [1,1,1,-2,0,1,1,1,1]:
  its census entry carries the transformation from the served basis,
  the served stop kept beside), and the same six sectors stop on both
  lines -- 417, 449 Moser-irreducible (the input is not Fuchsian and
  the Moser reduction stalls) and 421, 453, 482, 483 at the eps^0
  obstruction (Fuchsian, the balances exhaust, no constant
  eps-decoupling).  The 29 block forms of the two lines are related
  letter by letter, through the restriction of the 36-letter alphabet to
  each line, by a constant gauge G (identity on 24 blocks, nontrivial
  on 227, 321, 327, 355, 485).  The tier re-checks
  the shipped census live: pins first (the line's blocks_epsform.json,
  the gauge file and row35_L2/lines.json against the script's tables, the
  line's connection against its pin), then for every factorised block
    T A T^-1 + (dT/dy) T^-1 == eps * Atilde
  entrywise in exact Fraction arithmetic -- A the block of the line's
  shipped connection at d = 4 - 2 eps, dT/dy by dual numbers on the
  engine's strings -- at (eps, y) = (1/223, 29/211) and (5/6, 17/139),
  Atilde eps-free (re-evaluated at eps + 1/97), the dlog form
  Atilde == sum_p R_p/(y - p) + (U y + V)/q(y) from the shipped residues
  at both y, the residue at infinity, and the gauge: the line's residues
  against its side of every matched pair and G R1 G^-1 == R2 on every
  pair.  Every block prints its sector, size, rows, its verdict or its
  stop class by name, its letters as restrictions of the alphabet and its
  gauge; the census line '29 OK / 6 stopped (2 Moser-irreducible + 4
  eps^0) / 1 elliptic' closes the run.  Measured wall 2.51 s
  (L1) / 2.53 s (L2) (one core).  --verbose adds the engine's
  stop strings verbatim and the residue pairs of the nontrivial-G blocks;
  --mutate changes one digit of one T entry in memory and must FAIL
  naming the block.  Exit codes: 0 PASS / 1 FAIL (the failing blocks
  named) / 2 refused (a usage error) / 3 a pinned file's sha256 or a
  header differs / 4 a pinned file missing.  A statement about each
  line's blocks by themselves, not about the two-variable function.

MB CORNER ROWS (--mb-corner-provenance [--row 69|42|43|all] [--rederive]
  [--dps D]):
  Three rows of the boundary basis -- 69 (sector 484), 42 and 43 (sector
  227) -- are the corner rows whose Mellin-Barnes representations were
  written as explicit five-fold integrals (13 numerator Gammas over 4 or 3
  denominator Gammas, the bases W = 5/3, S = 17/2 and, for rows 42 and
  43, the single phase-carrying base U' = u e^{-i pi}, u = 11/2) at the
  base point of this line.  They are PROVENANCE objects: the value path of
  every tier above is the eta-transport from the certified node bank, and
  nothing printed here enters it.  Established by object, and printed by
  the tier from the files under vendor_row35_mb_corner/ (each figure read
  by key and named with its source file and sha256):
    row 69: the written representation (mb_row69.py) has independent
      evaluations by a collapsed route (s3 -> 2F1, s4 -> Meijer G, the
      w fold as a residue series, s1 and s2 by quadrature): at the
      record's eps = 1/1013 (GATE_row69_q1013.json, matched digits
      against the node bank at two bank precisions) and at eps = 1/1117
      at two working precisions (GATE_row69_q1117_dps20/dps30.json,
      each with a planted-digit control that FAILS by name); the two
      precisions' values are compared here (the roundoff floor of the
      pair, not its truncation floor); the collapse certificates at the
      record test point (CERTS_row69_collapse.json); the evaluator's
      refusal of a point the bank does not hold (r69_gate_v2.py, rc 5).
    row 42: the written representation (mb_row42.py); the certified
      collapses of its inner folds at the record test point
      (PILOT_R42.json: s3 -> 2F1, b2 -> Meijer G with the u-channel
      phase, the wrong-phase control, the continuation control), the
      growth of every residue closure of b1 (quadrature, then), the
      power-law upper s2 tail and the exponential decay of a rotated ray
      (RAYSCAN.json), the s2 residue closure converging only as a power
      law (PILOT_R42_CLOSURE.json).  NOT EVALUATED: no bank digit.
    row 43: the representation written from the record's recipe
      (ROW43_MB_REPRESENTATION.json: 13 + 3 Gammas, the powers, the
      exact factor -1-s1, the pinches, the delta-regulated defining
      point and the pole-crossing walk it needs; the recipe of record in
      MB_ROWS.json and the record's relabel note).  WRITTEN, NOT
      EVALUATED: no straight-contour defining point at any eps; the
      pinch argument sums -eps and eps + delta.
  Not established by these objects: any bank digit of rows 42 and 43;
  the deeper first-point runs of row 69 are not shipped here.
  --rederive re-derives, at the objects' own working precision, the three
  seconds-class certificates (row 69 s3 -> 2F1 by the vendored producer's
  own contour and breakpoints read from its text; row 42 s3 -> 2F1 and
  b2 -> Meijer G with the wrong-phase control by the vendored library)
  and compares each with the record's figure within 0.1 digits, PASS or
  FAIL by name (rc 1 on FAIL) -- still no effect on --check.  --dps D
  sets that working precision; the comparison is made only at the
  record's (30).  Pins first: every vendored file against
  PINS_MB_CORNER before any print (rc 3 / rc 4 by name); the value tiers
  check the same pins on every run (the download is one bundle).  Exit
  codes: 0 PASS / 1 a re-derivation FAIL or a record inconsistency
  (named) / 2 refused (a usage error; the tier combines with no other
  flag) / 3 a pinned file's sha256 differs / 4 a pinned file missing.
  WALLS (measured, one core, this host at load ~100-140): the tier
  0.22 s (every row, by object); --rederive
  3.54 s; the certificates alone: row 69 s3 -> 2F1
  0.96 s, row 42 s3 -> 2F1 0.72 s, row 42 b2 -> Meijer G
  with its control 1.86 s.

USAGE:
  python3 eval_row35.py                        # quick default (see above)
  python3 eval_row35.py --verify-exact         # first line: exact check against row35_L1/
  python3 eval_row35.py --verify-exact --mutate    # control: MUST fail
  python3 eval_row35.py --line L2 --verify-exact   # second line: exact check
  python3 eval_row35.py --line L2 --verify-exact --mutate  # control: MUST fail
  python3 eval_row35.py --canonical-blocks     # first line: the canonical-basis census, checked exactly
  python3 eval_row35.py --canonical-blocks --mutate   # control: MUST fail
  python3 eval_row35.py --line L2 --canonical-blocks  # second line: the same
  python3 eval_row35.py --line L2 --canonical-blocks --verbose  # + the stop strings verbatim
  python3 eval_row35.py --mb-corner-provenance   # the corner rows 69/42/43: representations + certificates by object
  python3 eval_row35.py --mb-corner-provenance --row 69   # one row (69 | 42 | 43 | all)
  python3 eval_row35.py --mb-corner-provenance --rederive   # + the three seconds-class re-derivations (dps 30)
  python3 eval_row35.py --gate-full            # full 79-row, both points
  python3 eval_row35.py --gate-im              # the imaginary parts of the 36 complex rows, both points
  python3 eval_row35.py --gate-im --im-point y12   # one reference point (y12 | y35)
  python3 eval_row35.py --gate-im --im-control # control: MUST fail naming row 54
  python3 eval_row35.py --point 17/40          # any rational y in (0,1)
  python3 eval_row35.py --master 33 --point 1/2   # one master, printed
  python3 eval_row35.py --mutate               # control: MUST exit nonzero
  python3 eval_row35.py --check                # rerun at dps+60 and diff
  python3 eval_row35.py --containers           # status of the containers listed in containers.json
  python3 eval_row35.py --boundary-recompute   # chain replay gate (needs row35_chain/)

HONESTY NOTES (read before quoting numbers):
  * The reference-value comparisons of the served tiers are real-part
    comparisons; 36 of the 79 rows are complex on the line (rows 19-22, 27-29,
    33-35, 39-44, 54-59, 63-68, 70-73, 75-78), and their imaginary parts are
    compared separately against the complex reference values (--gate-im below;
    the connection is real-rational, so Re and Im solve the same equation).
  * The default value path's accuracy ceiling is the shipped node bank
    (two-precision certificate 124.2 d; certified-fan claim capped at 40 d
    = the measured 24-node capacity; the cap lifts when the containers are
    distributable and a deeper bank is regenerated from the chain,
    --boundary-recompute --regenerate-node). Runs at --dps > ~109 refuse;
    deeper node banks are not part of this download. --cached retains the
    legacy strings' ~57 d ceiling.
  * Compared eps-orders: every oracle order below eps^2 (eps^-3..eps^1;
    eps^-3 is present on 11 rows and is compared uncapped); the E4 certified-fan
    sub-window stays -2..1. Higher orders come out of the same solve but carry
    no independent reference here and are not compared.

IMAGINARY PARTS (--gate-im [--im-point y12|y35|both] [--im-control]; the
  first line, like every value tier):
  The line connection is real-rational, so the imaginary part of the
  79-vector solves the same differential equation as its real part. The
  value tiers above seed the transport with the node bank's real parts
  and compare real parts. --gate-im seeds the same transport (24 legs per
  point, one per bank prime, at the value path's own precision and Taylor
  order) with the bank's IMAGINARY parts, re-extracts the Laurent coefficients
  with the same 20 + 4 node design, and compares, on the 36 complex rows,
  every reference order below eps^2 (eps^-3..eps^1) with the imaginary
  parts of the same independent reference values (row35_reference_im.json,
  sha256-pinned; the real parts are the strings row35_data.json carries).
  Relative digits per (row, order); a reference imaginary part below
  1e-40 gscale (gscale = the row's largest real reference coefficient
  below eps^2) is a zero-class order, where no digits are quoted and the
  transported |Im|/gscale must sit below 1e-30, the served absolute zero
  floor; on the 43 real rows the transported |Im|/gscale must sit below
  the same floor. Pass = every complex row at or above 37 digits (the
  default tier's bar) at each point run and every floor held: rc 0; else
  rc 1 with the rows named. Measured on these bytes: worst 42.46 d at
  y = 1/2 and 42.14 d at y = 3/5 (row 73, eps^1, both points; per order at
  y = 1/2: eps^-3 59.65 / eps^-2 55.55 / eps^-1 50.38 / eps^0 46.67 / eps^1 42.46);
  30 zero-class orders per point, at most 1.7e-52 of gscale; the 43
  real rows at most 1.3e-147 of gscale; the verify-node self-consistency
  of the complex rows at least 52.9 d. Walls
  (measured, one core per leg on a loaded host): 20-23 s per leg to
  y = 1/2 (15 steps) and 35-56 s to y = 3/5 (24 steps); the 24
  legs of a point run --jobs at a time; the extraction takes seconds.
  --im-control negates the imaginary seed of row 54 (sector 481) at the
  q = 1013 node before the transport: the tier must FAIL naming row 54
  (measured -4.68 d at y = 1/2 and -4.69 d at y = 3/5; the 20 complex rows
  54-59, 63-68, 70-73 and 75-78 -- sector 481 and the rows coupled to it
  downstream -- fail with it, the other 16 complex rows pass
  unchanged). --im-point runs
  one reference point. The tier combines with --dps, --jobs and --order
  only (rc 2 otherwise; --mutate is the bank control of the value tiers)
  and refuses --line L2 like every value tier. The pin is checked on
  every value run (one download). Exit codes: 0 PASS / 1 FAIL (the rows
  named) / 2 refused / 3 the pinned file's sha256 differs or its tables
  disagree with the script's / 4 the pinned file missing.

DOCUMENTED DOMAIN: y rational in (0,1) (the only singularities of A on the
real segment are y=0 and y=1; verified root scan of all 1240 denominators).
Recommended band [1/20, 19/20] (step control slows near the edges).
Reference points y=1/2, y=3/5; base point y=1/3.
"""
import argparse, json, os, sys, time
from fractions import Fraction as F
from multiprocessing import Pool

import flint
import mpmath as mp

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import vopclose_vendored as V   # vendored VoP container engine (mpmath+flint only)
import epsfan_vendored as EFAN  # E4 certified eps-fan extraction engine

DATA = None  # loaded in main(); fork-shared with workers
MUTATE = False  # --mutate control: perturb one bank node at load

# ---- second line L2 = (17/2, 7/4): the exact-verify tier (--line L2 --verify-exact) ----
L2_DIR = 'row35_L2'
L2_FRESH_D = F(7, 3)     # the withheld-verification dimension: outside the fit's
                         # 24 fit + 3 check d-nodes and the known-denominator
                         # closure's 40 + 4 d-samples (row35_L2/points.json)
L2_WITHHELD = (('296/101', 'withheld_y296o101.json'),
               ('306/103', 'withheld_y306o103.json'))
L2_ENTRIES = 1240        # the pass line: every entry of the reduction's support
L2_VERIFY_WALL_S = '5.14'   # measured wall of the tier (one core;
                         # script-emitted from the build's capture)
PINS_L2 = {
    "row35_L2/connection_L2.json": "fd83c63b685adb69364b936f26672543581ad0aa45d2f6f8d85d31458596d9bb",
    "row35_L2/lines.json": "f56f0fe7009dddb13c7e53a2ba9930e557ecd46c36fb3b985e6d7de67464a8e7",
    "row35_L2/points.json": "da4389cf099c5f2ac99298118a042dbf86e3f57fd5c34a924b5a8ad4194783b2",
    "row35_L2/withheld_y296o101.json": "c214d927c2c16db240107b258c1beaa11a641a1b2592abc8d92bad2f5e071636",
    "row35_L2/withheld_y306o103.json": "15d2af53d7687182f6a56162596c1e0a5d6c6e6ae5ef8b9043a30e6f22306ac1",
}

# ---- first line L1 = (17/2, 5/3): the exact-verify tier (--verify-exact on the default line) ----
L1_DIR = 'row35_L1'
L1_FRESH_D = F(890, 223)  # the withheld-verification dimension of the first
                          # line's record: outside the fit's 24 fit + 3 check
                          # d-nodes (row35_L2/lines.json; the same d-nodes on
                          # both lines)
L1_WITHHELD = (('29/211', 'withheld_y29o211.json'),
               ('17/139', 'withheld_y17o139.json'))
L1_ENTRIES = L2_ENTRIES   # the same 1240-entry support on both lines
L1_VERIFY_WALL_S = '2.29'   # measured wall of the tier (one core;
                          # script-emitted from the build's capture)
PINS_L1 = {
    "row35_L1/withheld_y17o139.json": "ccf6e06a7f6fb7a0f860827b7f282cec1a5904bf809bdcd9e80dbec274fca623",
    "row35_L1/withheld_y29o211.json": "cad512ab6abedc629782ab05a0279cc2329539880fcf4ea03709e0fef3c4dcce",
}

# ---- the canonical-basis census of the two lines (--canonical-blocks; --line L1 or --line L2) ----
CANON_FILE = {'L1': 'row35_L1/blocks_epsform.json', 'L2': 'row35_L2/blocks_epsform.json'}
CANON_GAUGE = 'row35_L2/canonical_gauge_L1_L2.json'
CANON_POINTS = ((F(1, 223), F(29, 211)), (F(5, 6), F(17, 139)))   # the check points (eps, y): d = 4 - 2 eps
                                                                    # = 890/223 and 7/3, the record's fresh dimensions,
                                                                    # y the two withheld points of the first line
CANON_EPS_SHIFT = F(1, 97)   # Atilde is re-evaluated at eps + 1/97 and must not move (eps-free)
CANON_STOP_CLASSES = {'Moser-irreducible': (417, 449),           # the input is not Fuchsian; the Moser reduction stalls
                      'eps^0 obstruction': (421, 453, 482, 483)}   # Fuchsian; the balances exhaust; no constant
                                                                   # eps-decoupling (the engine's higher-Poincare-rank class)
CANON_NONTRIVIAL_G = (321, 327, 355, 227, 485)   # the blocks whose L1 and L2 forms differ by a nontrivial constant G
CANON_ELLIPTIC = 481          # rows 54-59: the maximal-cut curve is elliptic; the eps^0 block is reducible to first order
                              # (the census file's sector_481 entry); not run through the eps-factoriser
CANON_WALL_S = {'L1': '2.51', 'L2': '2.53'}   # measured walls of the tier (one core;
                                                                       # script-emitted from the build's captures)
PINS_CANON = {
    "row35_L1/blocks_epsform.json": "edbc1f375f48699bf32231cbd0111febe0f5737a8df212e238b1a32222a596e3",
    "row35_L2/blocks_epsform.json": "90bc8a28c9fa2cd85b1c38f75d5c5f7253fa58bba69b809c21685f2e42d025b8",
    "row35_L2/canonical_gauge_L1_L2.json": "58ed5dfa4f2fc92b7b9a2cc48992a11b409f3d39ea3c9b5fde583b91e51a0776",
}

# ---- the Mellin-Barnes corner rows of the boundary (--mb-corner-provenance): provenance objects, never a value source ----
MBC_DIR = 'vendor_row35_mb_corner'
MBC_MANIFEST = MBC_DIR + '/MB_CORNER_MANIFEST.sha256'
MBC_ROWS = (69, 42, 43)
MBC_FILES = {69: {'rep': 'row69/mb_row69.py', 'gate_record': 'row69/GATE_row69_q1013.json',
                  'gate_q1117_dps20': 'row69/GATE_row69_q1117_dps20.json', 'gate_q1117_dps30': 'row69/GATE_row69_q1117_dps30.json',
                  'certs': 'row69/CERTS_row69_collapse.json', 'certs_producer': 'row69/r69_collapse_certs.py',
                  'lib': 'row69/r69_lib.py', 'gate_producer': 'row69/r69_gate_v2.py'},
             42: {'rep': 'row42/mb_row42.py', 'lib': 'row42/r42_lib.py', 'pilot': 'row42/PILOT_R42.json',
                  'closure': 'row42/PILOT_R42_CLOSURE.json', 'rayscan': 'row42/RAYSCAN.json'},
             43: {'rep': 'row43/ROW43_MB_REPRESENTATION.json', 'recipe': 'row43/MB_ROWS.json', 'note': 'row43/RELABEL_NOTE.md'}}
MBC_REDERIVE_BAR_D = 0.1      # a re-derived certificate must agree with the record's figure within this many digits
MBC_WALL_S = {'default': '0.22', 'rederive': '3.54'}   # measured walls of the tier (one core;
                                                                                          # script-emitted from the pilots' captures)
MBC_REDERIVE_WALL_S = {'r69a': '0.96', 'r42a': '0.72', 'r42b': '1.86'}   # each certificate alone
PINS_MB_CORNER = {
    "vendor_row35_mb_corner/MB_CORNER_MANIFEST.sha256": "d5cba029eaeeaf801a4fe62d06bccc4813fbcd7422e404ca916a699558f8446b",
    "vendor_row35_mb_corner/row42/PILOT_R42.json": "77006d8c14c327cf806c0e89af60c53927ac99f251c84bc5e6b33ed1a6c0f937",
    "vendor_row35_mb_corner/row42/PILOT_R42_CLOSURE.json": "c45042aba32aafb16cab02c3e537db0de1f16367b003e264cebef68bf36cded1",
    "vendor_row35_mb_corner/row42/RAYSCAN.json": "37f65689caef5c0fb530a861df44d27a1531193287bc64d2314ef26e711301df",
    "vendor_row35_mb_corner/row42/mb_row42.py": "26558d0361496d0c4032df77964009ae7f9567b8a1d8ba022658537387f880b0",
    "vendor_row35_mb_corner/row42/r42_lib.py": "92f7a32ee1edab380feca6e0f61375cb289cf46fdc5d1aef4a7373f9ff0afb03",
    "vendor_row35_mb_corner/row43/MB_ROWS.json": "c5ffcef390c0ffd9b7bc5a55c5e96ec59fc5bd6fdb74774614a8ab8f9d16944c",
    "vendor_row35_mb_corner/row43/RELABEL_NOTE.md": "3c07fc6d7bc4bd2547d080d50fdc48c9fd4b73f3665c5043d506bd0e3feb447e",
    "vendor_row35_mb_corner/row43/ROW43_MB_REPRESENTATION.json": "298ea04dd6c0c23ba210b755bcfec8564da18b51ebac7eca737f17a3b16dc8a2",
    "vendor_row35_mb_corner/row69/CERTS_row69_collapse.json": "c92b92e79b532f822df847ec152963161b412b6ed492d1489f8c807bdcbad0f3",
    "vendor_row35_mb_corner/row69/GATE_row69_q1013.json": "48a8bef7553b5de2a9072edf1f5e6e75c11605ba8e46e008634690f218095bfd",
    "vendor_row35_mb_corner/row69/GATE_row69_q1117_dps20.json": "f966f3f1f88d393692f737d57b284d4582e212afe6d2778664d523250270989e",
    "vendor_row35_mb_corner/row69/GATE_row69_q1117_dps30.json": "85e08032b8914644eb27d67effc76f506abcc127d1a58bc85585a190cae79e72",
    "vendor_row35_mb_corner/row69/mb_row69.py": "11426e57e6320be2eaa5b8527f9e7218d82274b0fb5e69480dd3ec22a1c78868",
    "vendor_row35_mb_corner/row69/r69_collapse_certs.py": "bb6124436079dcd703177c32d3f671edb0b7dead03bd2d694a4c2d01b1452aca",
    "vendor_row35_mb_corner/row69/r69_gate_v2.py": "fa2540cfa363e913dddc61d5d0f7d209e0866db87ef60ec59f94b7d94330b081",
    "vendor_row35_mb_corner/row69/r69_lib.py": "3c4b64ebe5a72a6aa68265692819a8600338cc19da7b87783673b7756371eb77",
}

# ---- the imaginary parts of the reference values (--gate-im): the 36 complex rows; a comparison tier, never a value source ----
IM_REF_FILE = 'row35_reference_im.json'
IM_POINTS = (('y12', F(1, 2)), ('y35', F(3, 5)))   # the two reference points, tagged as in row35_data.json's gate_oracles
IM_COMPLEX_ROWS = (19, 20, 21, 22, 27, 28, 29, 33, 34, 35, 39, 40, 41, 42, 43, 44, 54, 55, 56, 57, 58, 59,
                   63, 64, 65, 66, 67, 68, 70, 71, 72, 73, 75, 76, 77, 78)   # the rows complex on the line: |Im| > 1e-30 |Re| at some
                              # reference order (the same 36 rows in the boundary constants and at every node of
                              # the bank); the reference file's own list must equal this table
IM_BAR_D = 37                 # pass bar on each complex row's relative Im digits over the reference orders below
                              # eps^2 = the default tier's bar; measured worst 42.46 d (y = 1/2) / 42.14 d
                              # (y = 3/5), both at row 73 eps^1
IM_ZERO_ORACLE = '1e-40'      # a reference Im below 1e-40 gscale (gscale = the row's largest |Re| reference
                              # coefficient below eps^2) is a zero-class order: no digits are quoted there and
IM_ZERO_FLOOR = '1e-30'       #   the transported |Im|/gscale must sit below 1e-30, the served absolute zero floor;
                              #   the same floor gates the transported Im of the 43 real rows (measured:
                              #   zero-class orders at most 1.7e-52, real rows at most 1.3e-147 of gscale)
IM_CONTROL = (54, 1013)       # --im-control: row 54's Im seed negated at the q = 1013 node before the transport;
                              # the tier must FAIL naming row 54 (measured -4.68 d at y = 1/2, -4.69 d at y = 3/5)
IM_LEG_WALL_S = {'y12': ('20', '23'), 'y35': ('35', '56')}   # measured per-leg walls, min / max
                              # seconds (one core per leg, a loaded host; 15 steps to y = 1/2, 24 to y = 3/5)
PINS_IM = {
    "row35_reference_im.json": "20450635a86ddca68fd66b76bc74671ed756e36859467902ded1dc2f5c436349",
}

# ---- 2026-07-06 wiring constants (value path + E4 certified fan) ----------
NODE_CERT_GUARD = 15   # node bank two-precision certificate must clear
                       # dps + this (bank measured min 124.2 d => runs at
                       # dps > ~109 REFUSE; deeper node banks are not part
                       # of this download)
CACHE_GATE_MARGIN = 16 # compare-cache threshold digits = 19*log10(q) - 16;
                       # measured worst-row agreement = 19*log10(q) - 6.1
                       # (truncation-dominated, measured calibration) =>
                       # ~10 d margin; a 1e-30 string mutation (~30 d) trips
                       # every q (threshold at q=1013 is 41.1 d)
FAN_CLAIM_CAP = 40     # measured capacity of the 24-node bank fan: quoted-
                       # window (-2..1) two-grid agreement floor 47.8/47.9 d
                       # on two independent grid2 bands; cap = floor -
                       # guard//2 - ~4 d margin (a capacity number, not a
                       # dps knob). The cap lifts when the containers are
                       # distributable and a deeper node bank is regenerated
                       # from the chain (CONTAINERS.md; --boundary-recompute
                       # --regenerate-node is one node of that regeneration).
FAN_GUARD = 8          # engine guard (two-grid tol claim+4, cond claim+8)
KC_LO, KC_HI = -2, 1   # certified subwindow = the QUOTED window (descope)
                       # (the E4 certified fan's sub-window; the reference comparison of the gates
                       #  covers every reference order below eps^2 -- eps^-3, present on 11 rows,
                       #  is compared uncapped -- and the --point / --master printer starts at
                       #  the row's own leading order)

# ---- boundary-constant refresh — all thresholds MEASURED (calibration
#      receipts recorded with the construction); every check RAISES
#      (SystemExit, rc != 0) ------------------------------------------------
BND_KC = (-2, 2)       # refresh/certify window = the measured consumed
                       # B{i}k{k} order range of the 5 radical blocks (120
                       # pairs, orders -1..2, 32 boundary masters; padded to
                       # the pole order -2)
BND_CLAIM = 37         # measured two-grid floor on (-2..2) = 44.0 gscale-d
                       # (binding order k=2; k<=1 at 47.9-48.0d) minus
                       # guard//2 + margin; a BANK-CAPACITY number, NOT a
                       # dps knob (refine = extend the node bank)
BND_COMPARE_MIN = 33   # demotion gate: refreshed constant vs old AMFlow
                       # string, RELATIVE digits, pairs |old| >= gscale*1e-8;
                       # measured healthy floor 39.23 d (worst (28,2));
                       # a 1e-30 string mutation (30 d) trips by 3 d
BND_COMPARE_MIN_G = 39 # same gate, gscale digits, ALL string-present pairs
                       # (covers the 3 small-|old| pairs); measured 43.87 d
BND_XCHECK_MIN = BND_CLAIM - 2  # producer(square fit)-vs-certifier(E4 fan)
                       # xcheck, gscale digits; measured floor 42.38 d
BND_TP_MIN = 45        # dps130-fit vs dps160-fit certificate, gscale digits;
                       # measured 127.0 d (node-content class)
BND_ZERO_MAX = 35      # string-absent (i,order): |fit| must be < gscale*
                       # 10^-35 (measured max 6.15e-58*gscale), then exact
                       # '0' is vendored (old bnd_val true-zero semantics)


# ---------------------------------------------------------------- exact A at d0

def _ev(coeffs, x):
    r = F(0)
    for c in reversed(coeffs):
        r = r * x + c
    return r

def parse_entries(raw):
    """JSON strings -> Fractions once (parent process)."""
    ent = []
    for key, e in raw.items():
        i, j = (int(t) for t in key.split(','))
        N = [([F(c) for c in nd['num']], [F(c) for c in nd['den']]) for nd in e['N']]
        Q = [([F(c) for c in qd['num']], [F(c) for c in qd['den']]) for qd in e['Q']]
        ent.append((i, j, N, Q))
    return ent

def A_at_d0(ent, d0):
    """-> list of (i, j, Ncoeffs(y), Qcoeffs(y)) exact Fractions, ascending in y."""
    out = []
    for i, j, N, Q in ent:
        Nc = [_ev(n, d0) / _ev(d, d0) for n, d in N]
        Qc = [_ev(n, d0) / _ev(d, d0) for n, d in Q]
        while len(Nc) > 1 and Nc[-1] == 0: Nc.pop()
        while len(Qc) > 1 and Qc[-1] == 0: Qc.pop()
        out.append((i, j, Nc, Qc))
    return out

# ---------------------------------------------------------------- transport (arb)
# Fixed-eps Taylor-jet transport: shift-matrix poly recentring, Newton series
# inversion, complex-pole clearance + measured geometric tail bound step
# control. SAFETY = 0.25 (tightened from the original 0.35).

SAFETY = 0.25

def arbF(x):
    return flint.arb(flint.fmpq(x.numerator, x.denominator))

def transport(n, ent, y0, y1, I0, M, prec, poles):
    flint.ctx.prec = prec
    maxdeg = max(max(len(N), len(Q)) for _, _, N, Q in ent)
    rows = []
    for _, _, N, Q in ent:
        rows.append([arbF(c) for c in N] + [flint.arb(0)] * (maxdeg - len(N)))
        rows.append([arbF(c) for c in Q] + [flint.arb(0)] * (maxdeg - len(Q)))
    C = flint.arb_mat(rows)                       # (2E) x maxdeg
    y = flint.arb(flint.fmpq(y0.numerator, y0.denominator))
    yt = flint.arb(flint.fmpq(y1.numerator, y1.denominator))
    I = flint.arb_mat([[v] for v in I0])          # n x 1
    direction = 1 if y1 > y0 else -1
    steps = 0
    while True:
        rem = yt - y
        if abs(float(rem.mid())) < 1e-30:
            break
        yf = float(y.mid())
        clear = min((((yf - pr) ** 2 + pi ** 2) ** 0.5 for (pr, pi) in poles), default=1.0)
        h_mag = min(SAFETY * clear, abs(float(rem.mid())))
        h = flint.arb(direction * h_mag)
        if abs(float(rem.mid())) <= h_mag * 1.0000001:
            h = rem
        # shift matrix S[m][k] = C(m,k) y^(m-k): recentre all polys at current y
        S = [[flint.arb(0)] * (M + 1) for _ in range(maxdeg)]
        ypow = [flint.arb(1)]
        for _ in range(maxdeg):
            ypow.append(ypow[-1] * y)
        for m in range(maxdeg):
            b = 1
            for k in range(0, min(m, M) + 1):
                S[m][k] = flint.arb(b) * ypow[m - k]
                b = b * (m - k) // (k + 1)
        SH = C * flint.arb_mat(S)                 # (2E) x (M+1): poly jets at centre
        def trunc(pp, nn):
            return flint.arb_poly([pp[t] for t in range(nn)])
        Amats = [[[flint.arb(0)] * n for _ in range(n)] for _ in range(M + 1)]
        two = flint.arb_poly([2])
        for e in range(len(ent)):
            i, j, _, _ = ent[e]
            Np = flint.arb_poly([SH[2 * e, k] for k in range(M + 1)])
            Qp = flint.arb_poly([SH[2 * e + 1, k] for k in range(M + 1)])
            x = flint.arb_poly([1 / SH[2 * e + 1, 0]])
            m2 = 1
            while m2 < M + 1:                     # Newton inversion of Q series
                m2 = min(2 * m2, M + 1)
                x = trunc(x * (two - trunc(Qp, m2) * x), m2)
            a = trunc(Np * x, M + 1)
            for m in range(M + 1):
                Amats[m][i][j] = a[m]
        Am = [flint.arb_mat(Amats[m]) for m in range(M + 1)]
        jets = [I]                                # jet recursion I^(m+1)/(m+1)!
        for m in range(M):
            s = flint.arb_mat(n, 1)
            for k in range(min(m, M) + 1):
                s = s + Am[k] * jets[m - k]
            jets.append(s * flint.arb(flint.fmpq(1, m + 1)))
        # tail-controlled advance: halve h until measured geometric bound < tol
        Inorm = max(max(abs(float(jets[0][r, 0].mid())) for r in range(n)), 1e-300)
        tol = Inorm * 2.0 ** (-(prec - 60))
        jM = max(abs(float(jets[M][r, 0].mid())) for r in range(n))
        jM1 = max(abs(float(jets[M - 1][r, 0].mid())) for r in range(n))
        while True:
            hm = abs(float(h.mid()))
            t1 = jM * hm ** M
            t0 = jM1 * hm ** (M - 1)
            ratio = min(0.75, (t1 / t0) if t0 > 0 else 0.5)
            bound = (t1 + t0) / (1 - ratio)
            if bound < tol or hm < 1e-8:
                break
            h = h * flint.arb(flint.fmpq(1, 2))
        Inew = jets[M]
        for m in range(M - 1, -1, -1):
            Inew = Inew * h + jets[m]
        I = Inew
        y = y + h
        steps += 1
        if steps > 4000:
            raise RuntimeError('too many transport steps')
    return I, steps

# ---------------------------------------------------------------- per-q leg (worker)

def _split_master_tokens(s):
    """Bracket-aware split of the --master argument (2026-07-07 close fix).
    ALL 79 wpairT4[...] master names contain commas, so the previous bare
    split(',') made by-name selection DEAD CODE (every name refused rc=1,
    verifier sec-6 flag (a)).  Commas inside [...] no longer delimit; ';' is
    also accepted as a delimiter; unbalanced brackets refuse (SystemExit)."""
    toks, cur, depth = [], [], 0
    for ch in s:
        if ch in ',;' and depth == 0:
            toks.append(''.join(cur).strip())
            cur = []
            continue
        if ch == '[':
            depth += 1
        elif ch == ']':
            depth -= 1
            if depth < 0:
                raise SystemExit(f'--master: unbalanced brackets in {s!r}')
        cur.append(ch)
    if depth != 0:
        raise SystemExit(f'--master: unbalanced brackets in {s!r}')
    toks.append(''.join(cur).strip())
    return [t for t in toks if t]

def _dep_closure(seeds):
    """Downward DE dependency closure of the seed masters under the exact
    connection's sparsity (rows reachable from the seeds via nonzero A(i,j)).
    MEASURED (on this data): the connection is sector-
    lower-triangular — closure sizes over the 79 masters are min 1 / median
    10 / max 79; 75/79 masters close strictly below 79 (only 75-78 pull the
    full system).  The restriction of the DE to a closure is exactly closed,
    so the subset march performs the SAME per-row arithmetic as the full
    march (zero-entry contributions are exact arb no-ops); only the step-
    size control maxes run over the subset — byte-identity of the printed
    coefficients is a MEASURED property, not an assumption, and holds
    ON NON-NOISE-FLOOR coefficients only: true-zero orders (|cf|<1e-30, gate
    zero-skip class) print fit-noise tails that agree to ~1.5e-130 abs, not
    byte-for-byte (verifier 2026-07-07, m63 eps^-2)."""
    adj = {}
    for i, j, _, _ in DATA['ent']:
        adj.setdefault(i, set()).add(j)
    seen, stack = set(seeds), list(seeds)
    while stack:
        u = stack.pop()
        for v in adj.get(u, ()):
            if v not in seen:
                seen.add(v)
                stack.append(v)
    return sorted(seen)

def leg(args):
    q, y_to, prec, order, src = args
    sel = DATA.get('sel')                 # master-subset mode: closure rows
    n = len(sel) if sel else 79
    ent_src = DATA['ent_sel'] if sel else DATA['ent']
    ent79 = A_at_d0(ent_src, F(4) - F(2, q))
    if src == 'bank':
        # VALUE PATH (2026-07-06): boundary at eps=1/q from the certified
        # recompute node bank (row35_nodes dps160 sweep, Re part — real
        # connection => Re/Im decouple under the transport; two-precision
        # certificate + cache-compare gates already passed at load).
        I0s = ([DATA['bank'][q][i] for i in sel] if sel else DATA['bank'][q])
    else:
        # cache path (--cached fast-start / grid2 check legs): boundary
        # resummed from the vendored deep-Laurent strings (dps 220 >= 190).
        with mp.workdps(220):
            eps = mp.mpf(1) / q
            I0s = []
            for coeffs in ([DATA['bnd'][i] for i in sel] if sel
                           else DATA['bnd']):
                v = mp.mpf(0)
                for order_n, re in coeffs:
                    v += mp.mpf(re) * eps ** order_n
                I0s.append(mp.nstr(v, 200))
    flint.ctx.prec = prec
    I0 = [flint.arb(s) for s in I0s]
    I, steps = transport(n, ent79, F(1, 3), F(y_to), I0, order, prec, DATA['poles'])
    vals, rads = [], []
    for r in range(n):
        m, rad = I[r, 0].mid(), I[r, 0].rad()
        vals.append(m.str(220, radius=False))
        rads.append(float(rad.str(5, radius=False)))
    return q, vals, rads, steps

# ---------------------------------------------------------------- Laurent extraction

LO, HI = -4, 15          # fixed design: 20 fit nodes + 4 interleaved verify (24 q's)

def extract(nodes, dps_x):
    """nodes: [(q, vals, rads)] -> (coeffs[nr][LO..HI], self_digits[nr], max_rad).
    nr = len(vals) (79 full-mode; the closure size under --master — the
    per-row lu_solve is row-independent, so subsetting rows is exact)."""
    nr = len(nodes[0][1])
    with mp.workdps(dps_x):
        nodes = sorted(nodes, key=lambda t: mp.mpf(1) / t[0])
        P = HI - LO + 1
        k = len(nodes) - P
        ver_idx = set(round((i + 1) * len(nodes) / (k + 1)) for i in range(k)) if k > 0 else set()
        fit = [nd for i, nd in enumerate(nodes) if i not in ver_idx]
        ver = [nd for i, nd in enumerate(nodes) if i in ver_idx]
        assert len(fit) == P, f'square solve needs {P} fit nodes, have {len(fit)}'
        V = mp.matrix(P, P)
        for r, (q, _, _) in enumerate(fit):
            eps = mp.mpf(1) / q
            for c in range(P):
                V[r, c] = eps ** (LO + c)
        coeffs, selfd = [], []
        for i in range(nr):
            b = mp.matrix([mp.mpf(fit[r][1][i]) for r in range(P)])
            c = mp.lu_solve(V, b)
            err = mp.mpf(0)
            for (q, vals, _) in ver:
                eps = mp.mpf(1) / q
                pred = sum(c[t] * eps ** (LO + t) for t in range(P))
                v = mp.mpf(vals[i])
                err = max(err, abs(pred - v) / max(abs(v), mp.mpf('1e-300')))
            selfd.append(float(-mp.log10(max(err, mp.mpf('1e-999')))))
            coeffs.append([mp.nstr(c[t], min(dps_x - 10, 80)) for t in range(P)])
        max_rad = max(max(r for r in rads) if rads else 0.0 for _, _, rads in nodes)
        return coeffs, selfd, max_rad

# ------------------------------------------------- radical closed-form fold
# Layered-VoP closed forms (vopclose engine; exact zero-remainder certified:
# 35/35, 35/35, 52/52 container identities in-run) for the radical blocks:
# sec417 (masters 27-29), sec449 (45-47), sec482 (60-62) at eps^-2..2 from
# the shipped row35_radical_feed.json, and sec421 (33-35), sec453 (48-50)
# at eps^-2..1 from the not-hosted heavy containers (CONTAINERS.md; absent
# containers leave those six masters on the transport, present ones are
# size + sha256 checked against containers.json at load). Folded
# Laurent coefficients are evaluated DIRECTLY from the certified containers,
# replacing the y=1/3 -> y arb transport for those masters. The B{i}k{k}
# boundary constants are refreshed at load from the sha-manifested node
# bank (_bndval_refresh); the legacy strings are a raising compare-check
# only. The sec481 block (an elliptic maximal-cut curve; its eps^0 block
# reducible to first order, the census file's sector_481 entry; its full
# block admits no rational-letter eps-form on the line) stays on
# transport in this evaluator (its certified closed-form construction is
# written out in the expression file).

HEAVY_SECS = ('421', '453')   # partial-fold blocks: eps^-2..eps^1 folded (L=+1,
                              # layers -1..2); ~1.9M-term containers ->
                              # dedicated grouped path (when present).
HEAVY_NC = (88, 112)          # measured two-precision NC pair for the heavy
                              # blocks (light blocks keep 120/160).
HEAVY_TARGETS = {'421': (33, 34, 35), '453': (48, 49, 50)}
                              # target masters of the heavy blocks (header
                              # provenance, fold5 2026-07-04) — used ONLY to
                              # SKIP a heavy block in --master subset mode
                              # without loading its ~0.5GB feed; when a heavy
                              # block IS run, _heavy_leg asserts the loaded
                              # feed's target_rows == this constant
                              # (fail-closed against feed drift).

def _detour_roots_exact(b, sec):
    """Exact detour-root evaluation (2026-08-07 design-law lift; 2026-08-07b
    cure: eval() retired for an AST walk with an EXACT Fraction skeleton).
    The contour detour points are ALGEBRAIC — real zeros of the blocks'
    det-basis apparent-pole polys (vopclose det_roots_of_strategies) — and
    the design law forbids finite-precision numbers as inputs, so bare
    float/decimal root literals REFUSE instead of being consumed.
    Accepted vendored forms, evaluated at RUNTIME precision (the calling
    leg's mp.workdps): exact integers/rationals (int, or 'p/q' string) and
    radical expressions over sqrt of rationals (+ - * / ( ) sqrt over
    integer literals).  ALL rational arithmetic runs in Fraction — the old
    charset-guarded eval() computed int/int subterms as 53-bit doubles
    ('sqrt(1/3)' was 16-digit-wrong at any dps) — so ONLY sqrt (and the
    final Fraction->mpf conversion) rounds, at runtime precision.  '**' is
    refused ('2**(1/2)' is a double in disguise); sqrt of a NEGATIVE is
    refused (a detour point must be real — the old silent mp.re projection
    of complex radicals to 0.0 is retired); charset-legal identifiers
    assembled from sqrt's letters ('t*r') hit the SAME designed refusal,
    never a raw NameError.  Contour geometry is deformation-invariant and
    every consumer keeps the Im-guard asserts (radical_overrides
    :915-class), so detour-POINT precision never touches shipped values —
    this closes the input class, not a live value bug.  MEASURED
    2026-08-07: all five vendored blocks (417/449/482/421/453) carry
    detour_roots == [], so the refusal is exercised the moment a future
    feed lands roots, and nothing changes today.  RuntimeError (not
    SystemExit): also runs inside Pool workers (_heavy_leg), where a
    BaseException can hang the pool instead of failing."""
    import ast

    def _refuse(x, why=''):
        raise RuntimeError(
            f'[detour] block b{sec}: detour_root {x!r} is not an EXACT '
            f'rational/radical expression{why} — finite-precision root '
            f'literals are REFUSED (design law 2026-08-07: zero finite-'
            f'precision inputs; lift the root to its exact radical — it is '
            f'a root of the block\'s vendored det-basis polys — and '
            f're-vendor).')

    def _ex(node, x):
        # returns Fraction while the subtree is radical-free (EXACT), else
        # an mp.mpf computed at the caller's runtime precision
        if isinstance(node, ast.Expression):
            return _ex(node.body, x)
        if (isinstance(node, ast.Constant) and isinstance(node.value, int)
                and not isinstance(node.value, bool)):
            return F(node.value)
        if (isinstance(node, ast.UnaryOp)
                and isinstance(node.op, (ast.UAdd, ast.USub))):
            v = _ex(node.operand, x)
            return v if isinstance(node.op, ast.UAdd) else -v
        if (isinstance(node, ast.BinOp) and isinstance(
                node.op, (ast.Add, ast.Sub, ast.Mult, ast.Div))):
            va, vb = _ex(node.left, x), _ex(node.right, x)
            if not (isinstance(va, F) and isinstance(vb, F)):
                if isinstance(va, F):     # a radical entered: continue in mp
                    va = mp.mpf(va.numerator) / va.denominator
                if isinstance(vb, F):
                    vb = mp.mpf(vb.numerator) / vb.denominator
            try:
                if isinstance(node.op, ast.Add):
                    return va + vb
                if isinstance(node.op, ast.Sub):
                    return va - vb
                if isinstance(node.op, ast.Mult):
                    return va * vb
                return va / vb
            except ZeroDivisionError:
                _refuse(x, ' (division by zero)')
        if (isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
                and node.func.id == 'sqrt' and len(node.args) == 1
                and not node.keywords):
            v = _ex(node.args[0], x)
            if isinstance(v, F):
                if v < 0:
                    _refuse(x, ' (sqrt of a negative: a detour POINT must '
                               'be real — silent real-projection retired)')
                return mp.sqrt(mp.mpf(v.numerator) / v.denominator)
            if v < 0:
                _refuse(x, ' (sqrt of a negative: a detour POINT must '
                           'be real — silent real-projection retired)')
            return mp.sqrt(v)
        # ast.Pow ('**'), ast.Name ('t*r' from sqrt's letters), float
        # constants, everything else: the ONE designed refusal — never a
        # raw NameError/TypeError escaping eval
        _refuse(x, f' (unsupported {type(node).__name__} node)')

    roots = []
    for x in b['detour_roots']:
        if isinstance(x, int):
            roots.append(mp.mpf(x))
            continue
        # decimal points refuse EVERYWHERE: '0.123456' is a finite-precision
        # literal even though Fraction would parse it exactly — the exact
        # input class is integer ratios and radicals over them, no '.'
        if isinstance(x, str) and '.' not in x:
            s = x.replace(' ', '')
            try:
                f = F(s)
                roots.append(mp.mpf(f.numerator) / f.denominator)
                continue
            except (ValueError, ZeroDivisionError):
                pass
            if 'sqrt(' in s and not set(s) - set('0123456789+-*/()sqrt'):
                try:
                    tree = ast.parse(s, mode='eval')
                except (SyntaxError, ValueError):
                    _refuse(x, ' (unparseable)')
                v = _ex(tree, x)
                if isinstance(v, F):      # defensive: sqrt() unreachable in
                    v = mp.mpf(v.numerator) / v.denominator   # the tree
                roots.append(mp.mpf(v))
                continue
        _refuse(x)
    return sorted(roots)


def _radical_eval(y_to, dps_c, nc, only=None):
    """{(master_i, eps_order): mp.mpc} for the 9 fully-folded masters at target
    y, via the vendored vopclose spectral engine. reset_registries per block so
    letter/kernel indices match the block's serialized order. HEAVY_SECS are
    handled by _heavy_leg (grouped/memoized, same primitives)."""
    feed = DATA['radical']
    bv = DATA['bndval']   # certified-bank fan constants (2026-07-06b refresh;
                          # provenance: row35_nodes/ sha-manifested bank, NOT
                          # the AMFlow strings — those are compare-gate only)

    def bnd_val(i, order):
        try:
            return mp.mpc(mp.mpf(bv[(i, order)]))
        except KeyError:
            # RuntimeError (not SystemExit): also raised inside Pool workers,
            # where a BaseException can hang the pool instead of failing
            raise RuntimeError(
                f'[bndval] radical fold requests B{i} at eps^{order}, outside '
                f'the refreshed certified window {BND_KC} — the silent '
                f'AMFlow-string/zero fallback is retired; extend the refresh '
                f'window + recalibrate (fail-closed)')

    t = (F(y_to) - F(1, 3)) * F(15, 4)          # y = 1/3 + (4/15) t
    with mp.workdps(dps_c):
        zt = mp.mpc(mp.mpf(t.numerator) / t.denominator)
        out = {}
        for sec in sorted(feed):
            if sec in HEAVY_SECS:
                continue
            b = feed[sec]
            if only is not None and not (set(b['target_rows']) & only):
                continue      # --master subset: block folds none of the
                              # selected masters (folds are output-level
                              # per-(i,order) overrides — transport never
                              # consumes them, so skipping is exact)
            Loff = {int(k): v for k, v in b['L_offsets'].items()}
            V.reset_registries()
            for coeffs in b['letters']:
                V.LETTERS.append(V.fp([F(c) for c in coeffs]))
            for r in b['rkerns']:
                V.RKERNS.append(V.Rat(r['n'], r['d']))
            for ak in b['akerns']:
                V.AKERNS.append((V.Rat(ak['rat']['n'], ak['rat']['d']), tuple(ak['rad'])))
            conts = {}
            for key, terms in b['containers'].items():
                i, k = (int(x) for x in key.split(','))
                if i not in b['target_rows']:
                    continue
                A = {}
                for tm in terms:
                    ct = tm['ctag']
                    if ct != '1' and ct not in V.CONSTS:
                        bi, bk = ct[1:].split('k')
                        V.CONSTS[ct] = bnd_val(int(bi), int(bk) - Loff.get(int(bi), 0))
                    A[(ct, tuple(tm['rad']),
                       tuple((w[0], w[1]) for w in tm['word']))] = V.Rat(tm['rat']['n'], tm['rat']['d'])
                conts[(i, k)] = A
            eng = V.Engine(_detour_roots_exact(b, sec), NC=nc)
            for (i, k), A in conts.items():
                out[(i, k - Loff.get(i, 0))] = eng.eval_cf(A, zt)
        return out

def _heavy_leg(args):
    """One (sec, precision-pass) closed-form evaluation of a b421/b453 block.
    Same primitives and the same sum as Engine.eval_cf (word_vals/rad_vals/
    interp/Rat.ev_mpc), but terms are grouped by (rad, word) and the word/rad
    interpolated values memoized across the block's 12 containers -- the only
    way the ~1.9M-term certified containers are affordable at gate time.
    Returns (sec, nc, {(i, eps_order): (re_str, im_str)}). The ~0.5GB block
    file is loaded HERE (lazily, per leg) so the 48-worker transport Pool
    never forks over it (refcount/GC copy-on-write hazard on a shared box)."""
    sec, y_num, y_den, dps_c, nc = args
    b = json.load(open(DATA['radical_heavy'][sec]))['block']
    assert set(b['target_rows']) == set(HEAVY_TARGETS[sec]), \
        (f'heavy fold b{sec}: feed target_rows {sorted(b["target_rows"])} != '
         f'HEAVY_TARGETS {sorted(HEAVY_TARGETS[sec])} — the --master skip '
         f'constant has drifted from the feed; update HEAVY_TARGETS')
    Loff = {int(k): v for k, v in b['L_offsets'].items()}
    bv = DATA['bndval']   # certified-bank fan constants (2026-07-06b refresh;
                          # fork-shared; AMFlow strings are compare-gate only)

    def bnd_val(i, order):
        try:
            return mp.mpc(mp.mpf(bv[(i, order)]))
        except KeyError:
            # RuntimeError (not SystemExit): raised inside a Pool worker,
            # where a BaseException can hang the pool instead of failing
            raise RuntimeError(
                f'[bndval] heavy fold b{sec} requests B{i} at eps^{order}, '
                f'outside the refreshed certified window {BND_KC} — the '
                f'silent AMFlow-string/zero fallback is retired (fail-closed)')

    t = (F(y_num, y_den) - F(1, 3)) * F(15, 4)  # y = 1/3 + (4/15) t
    with mp.workdps(dps_c):
        zt = mp.mpc(mp.mpf(t.numerator) / t.denominator)

        def rat_ev(nn, dd):
            # same Horner as V.Rat.ev_mpc, minus the Rat gcd/lc normalization
            # (which cancels exactly in num/den) -- the gcd is ~30x the cost
            # on the ~1.9M-term containers.
            num = mp.mpc(0)
            for cs in reversed(nn):
                f = F(cs)
                num = num * zt + mp.mpf(f.numerator) / f.denominator
            den = mp.mpc(0)
            for cs in reversed(dd):
                f = F(cs)
                den = den * zt + mp.mpf(f.numerator) / f.denominator
            return num / den

        V.reset_registries()
        for coeffs in b['letters']:
            V.LETTERS.append(V.fp([F(c) for c in coeffs]))
        for r in b['rkerns']:
            V.RKERNS.append(V.Rat(r['n'], r['d']))
        for ak in b['akerns']:
            V.AKERNS.append((V.Rat(ak['rat']['n'], ak['rat']['d']), tuple(ak['rad'])))
        eng = V.Engine(_detour_roots_exact(b, sec), NC=nc)
        s, u = eng.locate(zt)
        memo, out = {}, {}
        for key, terms in b['containers'].items():
            i, k = (int(x) for x in key.split(','))
            if i not in b['target_rows']:
                continue
            G = {}
            for tm in terms:
                ct = tm['ctag']
                if ct != '1' and ct not in V.CONSTS:
                    bi, bk = ct[1:].split('k')
                    V.CONSTS[ct] = bnd_val(int(bi), int(bk) - Loff.get(int(bi), 0))
                rw = (tuple(tm['rad']), tuple((w[0], w[1]) for w in tm['word']))
                c = V.CONSTS[ct] * rat_ev(tm['rat']['n'], tm['rat']['d'])
                G[rw] = G.get(rw, mp.mpc(0)) + c
            tot = mp.mpc(0)
            for (rad, word), c in G.items():
                if (rad, word) not in memo:
                    gv = eng.interp(eng.word_vals(word)[s], u) if word else mp.mpc(1)
                    rv = eng.interp(eng.rad_vals(rad)[s], u) if rad else mp.mpc(1)
                    memo[(rad, word)] = gv * rv
                tot += c * memo[(rad, word)]
            out[(i, k - Loff.get(i, 0))] = (mp.nstr(mp.re(tot), min(dps_c, 200)),
                                            mp.nstr(mp.im(tot), 20))
    return sec, nc, out

def radical_overrides(y_to, dps, jobs=1, only=None):
    """Two-precision closed-form fold: coefficient strings + per-master self-
    consistency. Light blocks (417/449/482): NC=120 dps_c vs NC=160 dps_c+25,
    unchanged. Heavy blocks (421/453): HEAVY_NC pair at the same dps pair via
    the grouped _heavy_leg path, parallel over (block x pass). Returns
    (coeff_over {(i,order): str}, self_over {i: digits}).
    only (--master subset mode): set of SELECTED masters — blocks whose
    target rows miss it are skipped (folds are per-(i,order) OUTPUT
    overrides; the transport never consumes them, so the skip is exact for
    every kept master)."""
    dps_c = max(dps + 20, 95)
    v1 = _radical_eval(y_to, dps_c, 120, only)
    v2 = _radical_eval(y_to, dps_c + 25, 160, only)
    heavy = sorted(DATA.get('radical_heavy', {}))
    if only is not None:
        heavy = [s for s in heavy if set(HEAVY_TARGETS[s]) & only]
    if heavy:
        yf = F(y_to)
        tasks = [(sec, yf.numerator, yf.denominator, d, n)
                 for sec in heavy
                 for d, n in ((dps_c, HEAVY_NC[0]), (dps_c + 25, HEAVY_NC[1]))]
        if jobs > 1:
            with Pool(min(jobs, len(tasks))) as pool:
                hres = pool.map(_heavy_leg, tasks)
        else:
            hres = [_heavy_leg(tk) for tk in tasks]
        with mp.workdps(dps_c + 25):
            for sec, nc, hout in hres:
                tgt = v1 if nc == HEAVY_NC[0] else v2
                for io, (re_s, im_s) in hout.items():
                    tgt[io] = mp.mpc(mp.mpf(re_s), mp.mpf(im_s))
    coeff_over, per = {}, {}
    with mp.workdps(dps_c):
        for (i, o), v in v1.items():
            w = v2[(i, o)]
            # documented domain: y real in (0,1) => coefficients are real; the
            # contour detour returns a vanishing imaginary part (guarded).
            assert abs(mp.im(v)) < max(abs(mp.re(v)), mp.mpf(1)) * mp.mpf(10) ** -40, \
                f'radical fold: master {i} order {o} nonreal ({mp.im(v)})'
            vr, wr = mp.re(v), mp.re(w)
            if max(abs(vr), abs(wr)) < mp.mpf('1e-30'):
                # true-zero Laurent coefficient (e.g. masters 33/35/48/50 have
                # no eps^-2 pole): the container cancels to ~0, so a RELATIVE
                # two-precision bar is meaningless noise. Vendored value keeps
                # the computed residual; the gate's own |cf|<1e-30 zero-skip
                # handles the oracle side. Excluded from the self bar.
                coeff_over[(i, o)] = mp.nstr(vr, min(dps_c - 10, 90))
                continue
            dd = abs(vr - wr)
            dig = 200.0 if dd == 0 else float(-mp.log10(max(dd / max(abs(vr), mp.mpf('1e-300')),
                                                            mp.mpf('1e-999'))))
            per[i] = min(per.get(i, 1e9), dig)
            coeff_over[(i, o)] = mp.nstr(vr, min(dps_c - 10, 90))
    return coeff_over, per

# ------------------------------------------------- second line L2: exact verify tier

def _exact_in_d(s, d0):
    """Exact Fraction value at d = d0 of a withheld-reduction entry written as
    a rational expression in d (the record strings: integer literals, d, + -
    * /, ^ or ** powers, unary minus, parentheses), by an AST walk -- never
    eval.  Any other node (a float literal, a name other than d, a call, a
    non-integer or negative power) is REFUSED (RuntimeError): the tier
    consumes exact rational input only."""
    import ast
    tree = ast.parse(s.replace('^', '**'), mode='eval')

    def _refuse(node):
        raise RuntimeError(
            f'[L2] reduction entry {s[:60]!r}: unsupported '
            f'{type(node).__name__} node -- not an exact rational expression '
            f'in d; refusing')

    def w(n):
        if isinstance(n, ast.Expression):
            return w(n.body)
        if (isinstance(n, ast.Constant) and isinstance(n.value, int)
                and not isinstance(n.value, bool)):
            return F(n.value)
        if isinstance(n, ast.Name) and n.id == 'd':
            return d0
        if isinstance(n, ast.UnaryOp) and isinstance(n.op, (ast.UAdd, ast.USub)):
            v = w(n.operand)
            return v if isinstance(n.op, ast.UAdd) else -v
        if isinstance(n, ast.BinOp) and isinstance(
                n.op, (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.Pow)):
            a, b = w(n.left), w(n.right)
            if isinstance(n.op, ast.Add):
                return a + b
            if isinstance(n.op, ast.Sub):
                return a - b
            if isinstance(n.op, ast.Mult):
                return a * b
            if isinstance(n.op, ast.Div):
                return a / b
            if b.denominator != 1 or b < 0:
                _refuse(n)
            return a ** int(b)
        _refuse(n)

    return w(tree)


def _key_order(k):
    return tuple(int(t) for t in k.split(','))


def verify_exact_L2(mutate=False):
    """--line L2 --verify-exact: the shipped L2 connection (row35_L2/
    connection_L2.json) evaluated at d = L2_FRESH_D and at each withheld y in
    exact Fraction arithmetic, compared entry by entry with the withheld Kira
    reduction at that y (its record strings evaluated exactly at the same d).
    Every row35_L2/ file is sha256-checked against PINS_L2 first.  Returns the
    exit code: 0 = every entry of both reductions exact (L2_ENTRIES/L2_ENTRIES
    at both), 1 = a mismatched, unclosed or absent entry (named), 3 = a pin
    differs, 4 = a pinned file is missing.  --mutate changes one digit of one
    entry in memory and must return 1 naming that entry."""
    import hashlib
    t0 = time.time()
    print('# eval_row35 -- nonplanar T4 qqbar->WW evaluator | mode: second line '
          'L2 = (17/2, 7/4), exact verification of the shipped connection '
          f'against the two withheld Kira reductions at d = {L2_FRESH_D} '
          '(Fraction arithmetic; no transport, no node bank)'
          + (' | MUTATE CONTROL' if mutate else ''), flush=True)
    for rel, want in PINS_L2.items():
        p = os.path.join(HERE, rel)
        if not os.path.exists(p):
            print(f'[L2] MISSING: {rel} is not beside this script -- every '
                  f'row35_L2/ file is required for --line L2 --verify-exact; '
                  f'restore the download', file=sys.stderr)
            return 4
        got = hashlib.sha256(open(p, 'rb').read()).hexdigest()
        if got != want:
            print(f'[L2] PIN MISMATCH: {rel} sha256 {got[:16]}... != pinned '
                  f'{want[:16]}... -- refusing to verify against altered bytes',
                  file=sys.stderr)
            return 3
    conn = json.load(open(os.path.join(HERE, L2_DIR, 'connection_L2.json')))
    raw = conn['A_entries']
    ln = conn['line']
    cl = conn['closure']
    print(f'# L2 objects: {len(PINS_L2)}/{len(PINS_L2)} sha256 pins OK; '
          f'connection_L2.json '
          f'{PINS_L2["row35_L2/connection_L2.json"][:16]}: {len(raw)} '
          f'entries on (x, z) = ({ln["x"]}, {ln["z"]}), {conn["n_points_fit"]} '
          f'points in the fit, {len(conn["d_fit"])} fit + '
          f'{len(conn["d_verify"])} check d-nodes; {cl["plain_fit"]} entries '
          f'by the plain fit + {cl["known_denominator_closure"]} by the '
          f'known-denominator rescue fit')
    if mutate:
        k0 = sorted(raw, key=_key_order)[0]
        old = raw[k0]['N'][0]['num'][0]
        num, slash, den = old.partition('/')
        new = num[:-1] + str((int(num[-1]) + 1) % 10) + slash + den
        raw[k0]['N'][0]['num'][0] = new
        print(f'# MUTATE CONTROL (L2): entry ({k0}) N[0] numerator coefficient '
              f'{old!r} -> {new!r} (one digit changed in memory; the shipped '
              f'file is untouched)')
    ent = parse_entries(raw)
    keys_conn = set(raw)
    A0 = A_at_d0(ent, L2_FRESH_D)
    fails, exact_by_point = [], []
    for ys, fn in L2_WITHHELD:
        w = json.load(open(os.path.join(HERE, L2_DIR, fn)))
        if (w.get('y') != ys or w.get('masters_hash') != conn['masters_hash']
                or w.get('masters') != conn['masters']):
            print(f'[L2] {fn}: header (y, master hash, master list) does not '
                  f'match the connection -- refusing', file=sys.stderr)
            return 3
        yv = F(ys)
        red = w['A']
        keys_red = set(red)
        unclosed = sorted(keys_red - keys_conn, key=_key_order)
        absent = sorted(keys_conn - keys_red, key=_key_order)
        ok, bad = 0, []
        for i, j, Nc, Qc in A0:
            key = f'{i},{j}'
            if key not in red:
                continue
            got = _ev(Nc, yv) / _ev(Qc, yv)
            want = _exact_in_d(red[key], L2_FRESH_D)
            if got == want:
                ok += 1
            else:
                bad.append(key)
        exact_by_point.append((ys, ok, len(keys_red)))
        print(f'# L2 y={ys} d={L2_FRESH_D}: {ok}/{len(keys_red)} entries of the '
              f'withheld reduction exact ({ok + len(bad)} compared; mismatched '
              f'{len(bad)}; unclosed -- in the reduction, no connection entry '
              f'-- {len(unclosed)}; connection entries with no reduction '
              f'entry {len(absent)})' + (' [PASS]' if ok == len(keys_red)
                                        == L2_ENTRIES and not absent
                                        else ' [FAIL]'))

        def _names(ks):
            s = ', '.join(f'({k})' for k in ks[:20])
            return s + (f' (+{len(ks) - 20} more)' if len(ks) > 20 else '')
        if bad:
            fails.append(f'y={ys}: MISMATCH at {_names(bad)}')
        if unclosed:
            fails.append(f'y={ys}: UNCLOSED (no connection entry) '
                         f'{_names(unclosed)}')
        if absent:
            fails.append(f'y={ys}: connection entries absent from the '
                         f'reduction {_names(absent)}')
        if len(keys_red) != L2_ENTRIES:
            fails.append(f'y={ys}: the reduction carries {len(keys_red)} '
                         f'entries, not {L2_ENTRIES}')
    wall = time.time() - t0
    if fails:
        tot = ' and '.join(f'{ok}/{n} at y={ys}' for ys, ok, n in exact_by_point)
        print(f'# --line L2 --verify-exact: FAIL -- {tot}; '
              + '; '.join(fails) + f' (wall {wall:.1f}s)')
        return 1
    tot = ' and '.join(f'{ok}/{n}' for ys, ok, n in exact_by_point)
    ysn = ' and '.join(ys for ys, _, _ in exact_by_point)
    print(f'# --line L2 --verify-exact: {tot} exact at both withheld points '
          f'(y = {ysn}) at d = {L2_FRESH_D} -- the shipped L2 connection '
          f'reproduces the withheld Kira reductions entry by entry in exact '
          f'arithmetic [PASS] (wall {wall:.1f}s)')
    return 0


def verify_exact_L1(mutate=False):
    """--line L1 --verify-exact (the default line): the first line's shipped
    connection (row35_data.json, A_entries) evaluated at d = L1_FRESH_D and at
    each withheld y in exact Fraction arithmetic, compared entry by entry with
    the withheld Kira reduction at that y (its record strings evaluated exactly
    at the same d) -- the twin of verify_exact_L2 with the first line's objects.
    Pins first: every row35_L1/ file against PINS_L1; row35_L2/lines.json (the
    line facts and the connection's sha256) and row35_L2/connection_L2.json
    (the master hash the two lines share) against PINS_L2; then row35_data.json
    against the sha256 lines.json records for it.  Returns the exit code: 0 =
    every entry of both reductions exact (L1_ENTRIES/L1_ENTRIES at both), 1 = a
    mismatched, unclosed or absent entry (named), 3 = a pin or a header
    differs, 4 = a pinned file is missing.  --mutate changes one digit of one
    entry in memory and must return 1 naming that entry."""
    import hashlib
    t0 = time.time()
    print('# eval_row35 -- nonplanar T4 qqbar->WW evaluator | mode: first line '
          'L1 = (17/2, 5/3), exact verification of the shipped connection '
          f'against the two withheld Kira reductions at d = {L1_FRESH_D} '
          '(Fraction arithmetic; no transport, no node bank)'
          + (' | MUTATE CONTROL' if mutate else ''), flush=True)
    need = dict(PINS_L1)
    for rel in ('row35_L2/lines.json', 'row35_L2/connection_L2.json'):
        need[rel] = PINS_L2[rel]
    for rel, want in need.items():
        p = os.path.join(HERE, rel)
        if not os.path.exists(p):
            print(f'[L1] MISSING: {rel} is not beside this script -- every '
                  f'row35_L1/ file, row35_L2/lines.json and row35_L2/'
                  f'connection_L2.json are required for --line L1 '
                  f'--verify-exact; restore the download', file=sys.stderr)
            return 4
        got = hashlib.sha256(open(p, 'rb').read()).hexdigest()
        if got != want:
            print(f'[L1] PIN MISMATCH: {rel} sha256 {got[:16]}... != pinned '
                  f'{want[:16]}... -- refusing to verify against altered bytes',
                  file=sys.stderr)
            return 3
    line = json.load(open(os.path.join(HERE, L2_DIR, 'lines.json')))['lines']['L1']
    wv = line['withheld_verification']
    if (F(wv['d']) != L1_FRESH_D or wv['y'] != [ys for ys, _ in L1_WITHHELD]
            or wv['files'] != [f'{L1_DIR}/{fn}' for _, fn in L1_WITHHELD]
            or wv.get('shipped') is not True):
        print('[L1] row35_L2/lines.json: the first line\'s withheld-verification '
              'block (d, y, files) does not match this script\'s L1 constants -- '
              'refusing', file=sys.stderr)
        return 3
    conn_p = os.path.join(HERE, 'row35_data.json')
    if not os.path.exists(conn_p):
        print('[L1] MISSING: row35_data.json is not beside this script -- the '
              'first line\'s connection; restore the download', file=sys.stderr)
        return 4
    got = hashlib.sha256(open(conn_p, 'rb').read()).hexdigest()
    if got != line['connection_sha256']:
        print(f'[L1] PIN MISMATCH: row35_data.json sha256 {got[:16]}... != the '
              f'sha256 row35_L2/lines.json records for the first line\'s '
              f'connection {line["connection_sha256"][:16]}... -- refusing to '
              f'verify against altered bytes', file=sys.stderr)
        return 3
    mh = json.load(open(os.path.join(HERE, L2_DIR, 'connection_L2.json')))['masters_hash']
    if wv.get('masters_hash') != mh:
        print('[L1] row35_L2/lines.json: the first line\'s master hash differs '
              'from the second line\'s connection -- refusing', file=sys.stderr)
        return 3
    conn = json.load(open(conn_p))
    raw = conn['A_entries']
    fit = line['fit']
    print(f'# L1 objects: {len(need)}/{len(need)} sha256 pins OK; row35_data.json '
          f'{got[:16]}: {len(raw)} entries on (x, z) = ({line["x"]}, {line["z"]}), '
          f'{fit["n_points"]} points in the fit; {fit["plain_fit"]} entries by the '
          f'plain fit + {fit["known_denominator_closure"]} by the known-denominator '
          f'rescue fit (row35_L2/lines.json); master hash {mh[:16]} shared with '
          f'the second line')
    if mutate:
        k0 = sorted(raw, key=_key_order)[0]
        old = raw[k0]['N'][0]['num'][0]
        num, slash, den = old.partition('/')
        new = num[:-1] + str((int(num[-1]) + 1) % 10) + slash + den
        raw[k0]['N'][0]['num'][0] = new
        print(f'# MUTATE CONTROL (L1): entry ({k0}) N[0] numerator coefficient '
              f'{old!r} -> {new!r} (one digit changed in memory; the shipped '
              f'file is untouched)')
    ent = parse_entries(raw)
    keys_conn = set(raw)
    A0 = A_at_d0(ent, L1_FRESH_D)
    fails, exact_by_point = [], []
    for ys, fn in L1_WITHHELD:
        w = json.load(open(os.path.join(HERE, L1_DIR, fn)))
        if (w.get('y') != ys or w.get('masters_hash') != mh
                or w.get('masters') != conn['masters']):
            print(f'[L1] {fn}: header (y, master hash, master list) does not '
                  f'match the connection -- refusing', file=sys.stderr)
            return 3
        yv = F(ys)
        red = w['A']
        keys_red = set(red)
        unclosed = sorted(keys_red - keys_conn, key=_key_order)
        absent = sorted(keys_conn - keys_red, key=_key_order)
        ok, bad = 0, []
        for i, j, Nc, Qc in A0:
            key = f'{i},{j}'
            if key not in red:
                continue
            got = _ev(Nc, yv) / _ev(Qc, yv)
            want = _exact_in_d(red[key], L1_FRESH_D)
            if got == want:
                ok += 1
            else:
                bad.append(key)
        exact_by_point.append((ys, ok, len(keys_red)))
        print(f'# L1 y={ys} d={L1_FRESH_D}: {ok}/{len(keys_red)} entries of the '
              f'withheld reduction exact ({ok + len(bad)} compared; mismatched '
              f'{len(bad)}; unclosed -- in the reduction, no connection entry '
              f'-- {len(unclosed)}; connection entries with no reduction '
              f'entry {len(absent)})' + (' [PASS]' if ok == len(keys_red)
                                        == L1_ENTRIES and not absent
                                        else ' [FAIL]'))

        def _names(ks):
            s = ', '.join(f'({k})' for k in ks[:20])
            return s + (f' (+{len(ks) - 20} more)' if len(ks) > 20 else '')
        if bad:
            fails.append(f'y={ys}: MISMATCH at {_names(bad)}')
        if unclosed:
            fails.append(f'y={ys}: UNCLOSED (no connection entry) '
                         f'{_names(unclosed)}')
        if absent:
            fails.append(f'y={ys}: connection entries absent from the '
                         f'reduction {_names(absent)}')
        if len(keys_red) != L1_ENTRIES:
            fails.append(f'y={ys}: the reduction carries {len(keys_red)} '
                         f'entries, not {L1_ENTRIES}')
    wall = time.time() - t0
    if fails:
        tot = ' and '.join(f'{ok}/{n} at y={ys}' for ys, ok, n in exact_by_point)
        print(f'# --line L1 --verify-exact: FAIL -- {tot}; '
              + '; '.join(fails) + f' (wall {wall:.1f}s)')
        return 1
    tot = ' and '.join(f'{ok}/{n}' for ys, ok, n in exact_by_point)
    ysn = ' and '.join(ys for ys, _, _ in exact_by_point)
    print(f'# --line L1 --verify-exact: {tot} exact at both withheld points '
          f'(y = {ysn}) at d = {L1_FRESH_D} -- the shipped L1 connection '
          f'reproduces the withheld Kira reductions entry by entry in exact '
          f'arithmetic [PASS] (wall {wall:.1f}s)')
    return 0



# ---------------------------------------------- the canonical-basis census (--canonical-blocks)
# The exact check of the record's own verifier, ported: dual numbers on the
# engine's strings give T and dT/dy exactly; every product is a Fraction.

class _CDual:
    """a + b*t with t^2 = 0: exact value and y-derivative together."""
    __slots__ = ('a', 'b')

    def __init__(self, a, b=F(0)):
        self.a = F(a)
        self.b = F(b)

    def __add__(s, o):
        o = _cd(o)
        return _CDual(s.a + o.a, s.b + o.b)
    __radd__ = __add__

    def __sub__(s, o):
        o = _cd(o)
        return _CDual(s.a - o.a, s.b - o.b)

    def __rsub__(s, o):
        o = _cd(o)
        return _CDual(o.a - s.a, o.b - s.b)

    def __neg__(s):
        return _CDual(-s.a, -s.b)

    def __mul__(s, o):
        o = _cd(o)
        return _CDual(s.a * o.a, s.a * o.b + s.b * o.a)
    __rmul__ = __mul__

    def __truediv__(s, o):
        o = _cd(o)
        return _CDual(s.a / o.a, (s.b * o.a - s.a * o.b) / (o.a * o.a))

    def __rtruediv__(s, o):
        return _cd(o) / s

    def __pow__(s, k):
        r = _CDual(1)
        for _ in range(int(k)):
            r = r * s
        return r


def _cd(o):
    return o if isinstance(o, _CDual) else _CDual(o)


def _ceval(s, env):
    """the engine's string (integer literals, p//q rationals, the names of
    env, + - * / ^) evaluated exactly by an AST walk -- never eval; any other
    node (a float, another name, a call, a non-integer power) is REFUSED."""
    import ast
    tree = ast.parse(s.replace('^', '**'), mode='eval')

    def w(n):
        if isinstance(n, ast.Expression):
            return w(n.body)
        if (isinstance(n, ast.Constant) and isinstance(n.value, int)
                and not isinstance(n.value, bool)):
            return _CDual(n.value)
        if isinstance(n, ast.Name) and n.id in env:
            return env[n.id]
        if isinstance(n, ast.UnaryOp) and isinstance(n.op, (ast.USub, ast.UAdd)):
            v = w(n.operand)
            return -v if isinstance(n.op, ast.USub) else v
        if isinstance(n, ast.BinOp) and isinstance(
                n.op, (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Pow)):
            a, b = w(n.left), w(n.right)
            if isinstance(n.op, ast.Add):
                return a + b
            if isinstance(n.op, ast.Sub):
                return a - b
            if isinstance(n.op, ast.Mult):
                return a * b
            if isinstance(n.op, (ast.Div, ast.FloorDiv)):
                return a / b
            if b.b != 0 or b.a.denominator != 1 or b.a < 0:
                raise ValueError(f'non-integer power in {s[:60]!r}')
            return a ** int(b.a)
        raise ValueError(f'unsupported {type(n).__name__} node in {s[:60]!r}')
    return w(tree)


def _cmat(M, env):
    """a row-major string matrix -> _CDual matrix ('0' entries without a parse)."""
    return [[_ceval(M[i][j], env) if M[i][j] != '0' else _CDual(0)
             for j in range(len(M))] for i in range(len(M))]


def _cmul(A, B):
    n = len(A)
    return [[sum((A[i][k] * B[k][j] for k in range(n)), F(0)) for j in range(n)]
            for i in range(n)]


def _cinv(A):
    """exact inverse by Gauss-Jordan; None when singular."""
    n = len(A)
    M = [list(r) + [F(int(i == j)) for j in range(n)] for i, r in enumerate(A)]
    for c in range(n):
        p = next((r for r in range(c, n) if M[r][c] != 0), None)
        if p is None:
            return None
        M[c], M[p] = M[p], M[c]
        piv = M[c][c]
        M[c] = [x / piv for x in M[c]]
        for r in range(n):
            if r != c and M[r][c] != 0:
                f = M[r][c]
                M[r] = [x - f * y for x, y in zip(M[r], M[c])]
    return [r[n:] for r in M]


def canonical_blocks(line, mutate=False, verbose=False):
    """--line L1|L2 --canonical-blocks: the line's shipped canonical-basis
    census (row35_<line>/blocks_epsform.json) re-checked exactly against the
    line's shipped connection.  Pins first (the blocks file and the gauge file
    against PINS_CANON, row35_L2/lines.json against PINS_L2, the connection
    against its pin: row35_data.json against the sha256 lines.json records for
    it on L1, row35_L2/connection_L2.json against PINS_L2 on L2), the line's
    canonical_blocks block of lines.json against this script's constants and
    the objects' headers; then for every factorised block, at each check point
    (eps, y) of CANON_POINTS with A the connection block at d = 4 - 2 eps:
    T A T^-1 + (dT/dy) T^-1 == eps * Atilde entrywise, Atilde unchanged at
    eps + CANON_EPS_SHIFT, Atilde(y) == sum_p R_p/(y - p) + (U y + V)/q(y) from
    the shipped residues, R_inf == -(sum_p R_p + U/lead(q)), the block's master
    list == the connection's rows; the gauge file's residue pairs: the line's
    residue == its side of every pair and G R1 G^-1 == R2; the stopped blocks
    in their named classes.  Returns the exit code: 0 = every block passes and
    the census line equals the shipped one, 1 = a block fails (named), 3 = a
    pin or a header differs, 4 = a pinned file is missing.  --mutate changes
    one digit of one T entry in memory and must return 1 naming the block."""
    import hashlib
    t0 = time.time()
    tag = f'[canonical {line}]'
    xz = {'L1': '(17/2, 5/3)', 'L2': '(17/2, 7/4)'}[line]
    print(f'# eval_row35 -- nonplanar T4 qqbar->WW evaluator | mode: '
          f'{"first" if line == "L1" else "second"} line {line} = {xz}, the '
          f'canonical-basis census of the 35 non-elliptic diagonal blocks '
          f're-checked exactly against the shipped connection (Fraction '
          f'arithmetic; no transport, no node bank)'
          + (' | MUTATE CONTROL' if mutate else ''), flush=True)
    need = {CANON_FILE[line]: PINS_CANON[CANON_FILE[line]],
            CANON_GAUGE: PINS_CANON[CANON_GAUGE],
            'row35_L2/lines.json': PINS_L2['row35_L2/lines.json']}
    if line == 'L2':
        need['row35_L2/connection_L2.json'] = PINS_L2['row35_L2/connection_L2.json']
    for rel, want in need.items():
        p = os.path.join(HERE, rel)
        if not os.path.exists(p):
            print(f'{tag} MISSING: {rel} is not beside this script -- the '
                  f'line\'s blocks_epsform.json, {CANON_GAUGE}, row35_L2/'
                  f'lines.json and the line\'s connection are required for '
                  f'--line {line} --canonical-blocks; restore the download',
                  file=sys.stderr)
            return 4
        got = hashlib.sha256(open(p, 'rb').read()).hexdigest()
        if got != want:
            print(f'{tag} PIN MISMATCH: {rel} sha256 {got[:16]}... != pinned '
                  f'{want[:16]}... -- refusing to check altered bytes',
                  file=sys.stderr)
            return 3
    lj = json.load(open(os.path.join(HERE, L2_DIR, 'lines.json')))['lines'][line]
    cb = lj.get('canonical_blocks') or {}
    pts = [[str(e), str(y)] for e, y in CANON_POINTS]
    gb = cb.get('gauge') or {}
    if (cb.get('file') != CANON_FILE[line] or cb.get('sha256') != PINS_CANON[CANON_FILE[line]]
            or cb.get('check_points') != pts or cb.get('eps_free_shift') != str(CANON_EPS_SHIFT)
            or gb.get('file') != CANON_GAUGE or gb.get('sha256') != PINS_CANON[CANON_GAUGE]
            or cb.get('tier') != f'--line {line} --canonical-blocks'
            or cb.get('elliptic_not_run') != CANON_ELLIPTIC
            or {k: sorted(v) for k, v in (cb.get('stopped_by_class') or {}).items()}
            != {k: sorted(v) for k, v in CANON_STOP_CLASSES.items()}
            or sorted(gb.get('nontrivial_G_blocks') or []) != sorted(CANON_NONTRIVIAL_G)):
        print(f'{tag} row35_L2/lines.json: the {line} canonical_blocks block '
              f'(file, sha256, check points, stop classes, gauge file, tier) '
              f'does not match this script\'s constants -- refusing',
              file=sys.stderr)
        return 3
    if line == 'L1':
        conn_p = os.path.join(HERE, 'row35_data.json')
        if not os.path.exists(conn_p):
            print(f'{tag} MISSING: row35_data.json is not beside this script '
                  f'-- the first line\'s connection; restore the download',
                  file=sys.stderr)
            return 4
        conn_sha = hashlib.sha256(open(conn_p, 'rb').read()).hexdigest()
        if conn_sha != lj['connection_sha256']:
            print(f'{tag} PIN MISMATCH: row35_data.json sha256 {conn_sha[:16]}... '
                  f'!= the sha256 row35_L2/lines.json records for the first '
                  f'line\'s connection {lj["connection_sha256"][:16]}... -- '
                  f'refusing to check altered bytes', file=sys.stderr)
            return 3
    else:
        conn_p = os.path.join(HERE, L2_DIR, 'connection_L2.json')
        conn_sha = PINS_L2['row35_L2/connection_L2.json']
    conn = json.load(open(conn_p))
    raw = conn['A_entries']
    masters = conn['masters']
    obj = json.load(open(os.path.join(HERE, CANON_FILE[line])))
    gauge = json.load(open(os.path.join(HERE, CANON_GAUGE)))
    cen = obj['census']
    gc = gauge['counts']
    if (obj['line']['name'] != line or obj['line']['x'] != lj['x'] or obj['line']['z'] != lj['z']
            or len(obj['blocks']) != cen['n_blocks'] or cen['n_blocks'] != cb.get('n_blocks')
            or cen['n_ok'] != cb.get('n_ok') or cen['n_stopped'] != cb.get('n_stopped')
            or {k: sorted(v) for k, v in cen['stopped_by_class'].items()}
            != {k: sorted(v) for k, v in CANON_STOP_CLASSES.items()}
            or obj['check_points'] != pts or obj['eps_free_shift'] != str(CANON_EPS_SHIFT)
            or cen['elliptic_not_run']['sector'] != CANON_ELLIPTIC
            or gauge['sources']['blocks_epsform'].get(CANON_FILE[line]) != PINS_CANON[CANON_FILE[line]]
            or sorted(gc['nontrivial_G_blocks']) != sorted(CANON_NONTRIVIAL_G)
            or gc['identity_G_blocks'] + len(gc['nontrivial_G_blocks']) != cen['n_ok']):
        print(f'{tag} {CANON_FILE[line]} / {CANON_GAUGE}: a header (line, '
              f'counts, stop classes, check points, the gauge file\'s pin of '
              f'the blocks file) does not match lines.json and this script\'s '
              f'constants -- refusing', file=sys.stderr)
        return 3
    print(f'# {line} objects: {len(need)}/{len(need)} sha256 pins OK; '
          f'{CANON_FILE[line]} {PINS_CANON[CANON_FILE[line]][:16]}: '
          f'{cen["n_blocks"]} blocks on (x, z) = ({lj["x"]}, {lj["z"]}), '
          f'{cen["n_ok"]} factorised + {cen["n_stopped"]} stopped, sector '
          f'{CANON_ELLIPTIC} with an elliptic maximal-cut curve (its eps^0 block reducible to first order; not run); {CANON_GAUGE} '
          f'{PINS_CANON[CANON_GAUGE][:16]}: {gc["n_ok_both"]} blocks factorised '
          f'on both lines, G = identity on {gc["identity_G_blocks"]}, nontrivial '
          f'on {", ".join(str(s) for s in gc["nontrivial_G_blocks"])}; '
          f'connection {os.path.relpath(conn_p, HERE)} {conn_sha[:16]}: '
          f'{len(raw)} entries at d = 4 - 2 eps; check points (eps, y) = '
          + ' and '.join(f'({e}, {y})' for e, y in pts))
    if mutate:
        done = False
        for blk in obj['blocks']:
            if done or not blk['ok'] or blk['n'] < 2:
                continue
            for j, col in enumerate(blk['T']):
                for i, s in enumerate(col):
                    k = next((q for q, ch in enumerate(s) if ch.isdigit()), None)
                    if k is None or done:
                        continue
                    new = s[:k] + str((int(s[k]) + 1) % 10) + s[k + 1:]
                    blk['T'][j][i] = new
                    print(f'# MUTATE CONTROL ({line}): block b{blk["sector"]} T '
                          f'entry ({i},{j}) character {k} {s[k]!r} -> '
                          f'{new[k]!r} (one digit changed in memory; the '
                          f'shipped file is untouched)')
                    done = True
    ent = parse_entries(raw)
    Apts = []
    for eps, y in CANON_POINTS:
        Apts.append({(i, j): (Nc, Qc) for i, j, Nc, Qc in A_at_d0(ent, 4 - 2 * eps)})
    fails, classes = [], {k: [] for k in CANON_STOP_CLASSES}
    n_pass = n_stop = 0
    for blk in obj['blocks']:
        sec, n, rows = blk['sector'], blk['n'], blk['rows']
        name = f'b{sec}'
        label = f'# {name} n={n} rows {rows[0]}-{rows[-1]}'
        if blk['masters'] != [masters[r] for r in rows]:
            fails.append(f'{name}: the block\'s master list differs from the '
                         f'connection\'s rows {rows[0]}-{rows[-1]}')
            print(f'{label}: MASTERS MISMATCH [FAIL]')
            continue
        if not blk['ok']:
            st, cls = blk['stop'], blk['stop_class']
            by_string = ('Moser-irreducible' if 'Moser' in st else
                         'eps^0 obstruction' if 'eps^0' in st else None)
            if cls != by_string or sec not in CANON_STOP_CLASSES.get(cls, ()):
                fails.append(f'{name}: stop class {cls!r} does not match its '
                             f'stop string or the named classes')
                print(f'{label}: STOPPED -- {cls} [FAIL: class]')
                continue
            classes[cls].append(sec)
            n_stop += 1
            print(f'{label}: STOPPED -- {cls} (no rotation)'
                  + (f' | the engine: "{st}"' if verbose else ''))
            continue
        try:
            T = [[str(blk['T'][j][i]) for j in range(n)] for i in range(n)]
            At = [[str(blk['Atilde'][j][i]) for j in range(n)] for i in range(n)]
            let = blk['letters']
            poles = [F(p) for p in let['poles']]
            R = {F(ps): [[F(x) for x in r] for r in let['residues'][ps]]
                 for ps in let['poles']}
            Rinf = [[F(x) for x in r] for r in let['Rinf']]
            quads = [(q, [[F(x) for x in r] for r in UV['U']],
                      [[F(x) for x in r] for r in UV['V']])
                     for q, UV in let['quad_kernels'].items()]
            bad, pt_txt = [], []
            for k, (eps, y) in enumerate(CANON_POINTS):
                A = [[F(0)] * n for _ in range(n)]
                for a in range(n):
                    for b in range(n):
                        e = Apts[k].get((rows[a], rows[b]))
                        if e is not None:
                            A[a][b] = _ev(e[0], y) / _ev(e[1], y)
                envT = {'eps': _CDual(eps), 'x': _CDual(y, 1)}
                envT2 = {'eps': _CDual(eps + CANON_EPS_SHIFT), 'x': _CDual(y, 1)}
                Tm = _cmat(T, envT)
                Tv = [[x.a for x in r] for r in Tm]
                dT = [[x.b for x in r] for r in Tm]
                Atv = [[x.a for x in r] for r in _cmat(At, envT)]
                Atv2 = [[x.a for x in r] for r in _cmat(At, envT2)]
                Ti = _cinv(Tv)
                if Ti is None:
                    bad.append(f'T singular at (eps, y) = ({eps}, {y})')
                    pt_txt.append(f'({eps}, {y}) FAIL')
                    continue
                lhs = _cmul(_cmul(Tv, A), Ti)
                dTTi = _cmul(dT, Ti)
                ok_id = all(lhs[a][b] + dTTi[a][b] == eps * Atv[a][b]
                            for a in range(n) for b in range(n))
                ok_free = Atv == Atv2
                S = [[sum((R[p][a][b] / (y - p) for p in poles), F(0))
                      for b in range(n)] for a in range(n)]
                for q, U, V in quads:
                    qv = _ceval(q, {'x': _CDual(y)}).a
                    for a in range(n):
                        for b in range(n):
                            S[a][b] += (U[a][b] * y + V[a][b]) / qv
                ok_pf = S == Atv
                pt_txt.append(f'({eps}, {y}) {"PASS" if ok_id else "FAIL"}')
                if not ok_id:
                    bad.append(f'identity at (eps, y) = ({eps}, {y})')
                if not ok_free:
                    bad.append(f'Atilde moves at eps + {CANON_EPS_SHIFT} at y = {y}')
                if not ok_pf:
                    bad.append(f'dlog partial fractions at y = {y}')
            Rexp = [[-sum((R[p][a][b] for p in poles), F(0)) for b in range(n)]
                    for a in range(n)]
            for q, U, V in quads:
                qf = lambda x: _ceval(q, {'x': _CDual(x)}).a
                lead = (qf(F(2)) - 2 * qf(F(1)) + qf(F(0))) / 2   # the x^2 coefficient
                for a in range(n):
                    for b in range(n):
                        Rexp[a][b] -= U[a][b] / lead
            ok_inf = Rinf == Rexp
            if not ok_inf:
                bad.append('the residue at infinity')
            g = gauge['blocks'][str(sec)]
            G = [[F(x) for x in r] for r in g['G']]
            Gi = _cinv(G)
            side = 'R1' if line == 'L1' else 'R2'
            pkey = 'L1_pole' if line == 'L1' else 'L2_pole'
            pairs = g['residue_pairs']
            n_conj = n_eq = 0
            gbad = []
            if Gi is None:
                gbad.append('G singular')
            for lab, pr in pairs.items():
                R1 = [[F(x) for x in r] for r in pr['R1']]
                R2 = [[F(x) for x in r] for r in pr['R2']]
                mine = Rinf if pr[pkey] == 'inf' else R.get(F(pr[pkey]))
                if mine != (R1 if line == 'L1' else R2):
                    gbad.append(f'{lab}: the line\'s residue != the gauge '
                                f'file\'s {side}')
                if Gi is not None and _cmul(_cmul(G, R1), Gi) == R2:
                    n_conj += 1
                    n_eq += R1 == R2
                else:
                    gbad.append(f'{lab}: G R1 G^-1 != R2')
            if set(poles) != set(F(pr[pkey]) for pr in pairs.values()
                                 if pr[pkey] != 'inf'):
                gbad.append('the pole set differs from the gauge file\'s')
            nontriv = sec in CANON_NONTRIVIAL_G
            if nontriv != ('transformation' in g):
                gbad.append('nontrivial-G membership differs from the gauge file')
            let_txt = ', '.join(f'{ps} [{let["alphabet_letters"][ps]}]'
                                for ps in let['poles']) or '(none)'
            quad_txt = ', '.join(f'{q} [{let["quadratic_alphabet_letter"]}]'
                                 for q, _, _ in quads) or 'none'
            gauge_txt = ((f'G(L1->L2) = {g["G"]} (det {g["transformation"]["det_G"]}, '
                          f'nullspace dim {g["nullspace_dim"]}); ' if nontriv else
                          'G = identity; ')
                         + f'{n_conj}/{len(pairs)} letters G R1 G^-1 = R2 '
                         f'({n_eq} equal, {n_conj - n_eq} conjugated)')
            ok_blk = not bad and not gbad
            print(f'{label}: OK | letters {let_txt}; quadratic {quad_txt} | '
                  f'identity {", ".join(pt_txt)}; eps-free '
                  f'{"PASS" if not any("moves" in x for x in bad) else "FAIL"}; '
                  f'dlog partial fractions '
                  f'{"PASS" if not any("partial" in x for x in bad) else "FAIL"}; '
                  f'Rinf {"PASS" if ok_inf else "FAIL"} | gauge {gauge_txt} '
                  f'[{"PASS" if ok_blk else "FAIL"}]')
            if verbose and nontriv:
                for lab, pr in pairs.items():
                    print(f'#     {lab}: R1 = {pr["R1"]}; R2 = {pr["R2"]}; '
                          f'{"equal" if pr["equal"] else "conjugated"}')
            if ok_blk:
                n_pass += 1
            else:
                fails.append(f'{name}: ' + '; '.join(bad + gbad))
        except (ValueError, ZeroDivisionError, KeyError, TypeError) as e:
            fails.append(f'{name}: {type(e).__name__}: {str(e)[:80]}')
            print(f'{label}: {type(e).__name__}: {str(e)[:80]} [FAIL]')
    wall = time.time() - t0
    census = (f'{n_pass} OK / {n_stop} stopped ({len(classes["Moser-irreducible"])} '
              f'Moser-irreducible + {len(classes["eps^0 obstruction"])} eps^0) / '
              f'1 elliptic')
    if fails or census != cen['line_text']:
        print(f'# --line {line} --canonical-blocks: FAIL -- census {census} '
              f'(shipped: {cen["line_text"]}); ' + '; '.join(fails)
              + f' (wall {wall:.1f}s)')
        return 1
    print(f'# --line {line} --canonical-blocks: {census} -- every factorised '
          f'block passes the exact identity T A T^-1 + T\' T^-1 = eps Atilde at '
          f'both check points, Atilde eps-free, the dlog form from the shipped '
          f'residues exact, the constant gauge to the other line verified on '
          f'every letter; the six stopped blocks in their named classes '
          f'[PASS] (wall {wall:.1f}s)')
    return 0


# ------------------------------------------------- value-path gates (2026-07-06)
# Certified-recompute node bank = the VALUE PATH; vendored Laurent strings =
# compare-cache only.  All gates below are RAISING (SystemExit, nonzero rc).

def _bank_load_and_gate(dps_run, cap=True):
    """Verify + load row35_nodes/ (48 NODE files, sha manifest), run the
    two-precision node certificate and the compare-cache mismatch gate.
    Returns {'bank': {q: [79 re-strings (dps160 sweep)]},
             'cert_min_digits', 'cache_min_margin_digits'}.
    All three load-time checks refuse on failure (nonzero exit)."""
    import hashlib, math
    root = os.path.join(HERE, 'row35_nodes')
    manp = os.path.join(root, 'MANIFEST.sha256.json')
    if not os.path.exists(manp):
        raise SystemExit('[value-path] row35_nodes/MANIFEST.sha256.json '
                         'MISSING — certified recompute bank absent; the '
                         'vendored strings are a compare-cache, NOT a value '
                         'path. Restore the bank (see row35_nodes/'
                         'PROVENANCE.md).')
    man = json.load(open(manp))
    for rel, want in sorted(man.items()):
        p = os.path.join(root, rel)
        if not os.path.exists(p):
            raise SystemExit(f'[value-path] node bank file MISSING: {rel}')
        got = hashlib.sha256(open(p, 'rb').read()).hexdigest()
        if got != want:
            raise SystemExit(f'[value-path] node bank INTEGRITY FAILURE: '
                             f'{rel} sha256 {got[:16]}... != manifest '
                             f'{want[:16]}... — refusing to run')
    b130, b160 = {}, {}
    for sub, tgt, dexp in (('dps130', b130, 130), ('dps160', b160, 160)):
        for q in DATA['qset']:
            d = json.load(open(os.path.join(root, sub,
                                            f'NODE{q}_TARGETS.json')))
            if d.get('eps') != f'1/{q}' or int(d.get('dps', 0)) != dexp:
                raise SystemExit(f'[value-path] node bank {sub}/NODE{q}: '
                                 f'header mismatch (eps={d.get("eps")}, '
                                 f'dps={d.get("dps")})')
            rows = sorted(d['rows'], key=lambda r: r['row'])
            if len(rows) != 79 or [r['row'] for r in rows] != list(range(79)):
                raise SystemExit(f'[value-path] node bank {sub}/NODE{q}: '
                                 f'expected rows 0..78')
            tgt[q] = [(r['re'], r['im']) for r in rows]
    cert_min, cert_at = 1e9, None
    cache_min_margin, cache_at = 1e9, None
    q_first = min(DATA['qset'])
    with mp.workdps(200):
        for q in DATA['qset']:
            eps = mp.mpf(1) / q
            thr = 19.0 * math.log10(q) - CACHE_GATE_MARGIN
            for i in range(79):
                a = mp.mpc(mp.mpf(b130[q][i][0]), mp.mpf(b130[q][i][1]))
                if MUTATE and i == 0 and q == q_first:
                    a = a * (1 + mp.mpf('1e-30'))   # --mutate control
                b = mp.mpc(mp.mpf(b160[q][i][0]), mp.mpf(b160[q][i][1]))
                rel = abs(a - b) / max(abs(b), mp.mpf('1e-300'))
                dig = float(-mp.log10(max(rel, mp.mpf('1e-999'))))
                if dig < cert_min:
                    cert_min, cert_at = dig, (i, q)
                # compare-cache: vendored Laurent strings resummed at eps
                s = mp.mpf(0)
                for o, cs in DATA['bnd'][i]:
                    s += mp.mpf(cs) * eps ** o
                relc = abs(s - mp.re(b)) / max(abs(b), mp.mpf('1e-300'))
                digc = float(-mp.log10(max(relc, mp.mpf('1e-999'))))
                if digc < thr:
                    raise SystemExit(
                        f'[compare-cache] vendored boundary_y13_laurent '
                        f'MISMATCH vs certified recompute bank: master {i} '
                        f'q={q}: agreement {digc:.1f} d < threshold '
                        f'{thr:.1f} d (= 19*log10(q) - {CACHE_GATE_MARGIN}; '
                        f'measured healthy floor 19*log10(q) - 6.1). The '
                        f'recompute path is the definition — a cache/string '
                        f'mutation or stale vendor is fatal. NOT running.')
                if digc - thr < cache_min_margin:
                    cache_min_margin, cache_at = digc - thr, (i, q)
    need = dps_run + NODE_CERT_GUARD
    if cap and cert_min < need:
        # source that capped: the BANK's own measured pair certificate
        raise SystemExit(
            f'[value-path] node-bank two-precision certificate INSUFFICIENT '
            f'for --dps {dps_run}: min dps130-vs-dps160 agreement '
            f'{cert_min:.1f} d (master {cert_at[0]}, q={cert_at[1]}) < '
            f'need dps+{NODE_CERT_GUARD} = {need} d. This download ships '
            f'the 124.2 d bank — lower --dps (deeper node banks are not '
            f'part of this download).')
    return {'bank': {q: [re for re, _ in b160[q]] for q in DATA['qset']},
            'bank130': {q: [re for re, _ in b130[q]] for q in DATA['qset']},
            'cert_min_digits': cert_min, 'cert_at': cert_at,
            'cache_min_margin_digits': cache_min_margin,
            'cache_at': cache_at}


def _bndval_refresh():
    """2026-07-06b (pass-4 follow-up): derive the radical closed forms'
    B{i}k{k} boundary constants from the certified recompute bank at load,
    replacing the AMFlow-provenance vendored strings (which demote to a
    raising compare-gate here). Producer/certifier split per the validated
    wiring pattern: the legacy full-precision square Vandermonde fit
    (extract(), dps_x=420, 20 fit + 4 verify bank nodes) produces the
    values; the E4 certified fan (claim = BND_CLAIM measured bank capacity,
    grid2 = the demoted strings' mild-shift band) certifies the
    construction, with a raising producer-vs-certifier xcheck. Requires
    DATA['bank'], DATA['bank130'], DATA['bnd'], DATA['q2'], DATA['r0'].
    Sets DATA['bndval'] = {(i, order): decimal string} over BND_KC for all
    79 masters; returns the gate summary for the load-time print."""
    q1 = sorted(DATA['qset'])
    q2 = DATA['q2']
    # producer: full-precision base-point fits from BOTH bank sweeps
    # (sha-pinned at load by _bank_load_and_gate; zero transport — the bank
    # IS the base-point boundary)
    c160, self160, _ = extract([(q, DATA['bank'][q], [0.0]) for q in q1], 420)
    c130, _, _ = extract([(q, DATA['bank130'][q], [0.0]) for q in q1], 420)
    # certifier grids: grid1 = bank values, grid2 = the demoted strings
    # resummed on the mild-shift band (their compare-cache role).
    vals = {}
    with mp.workdps(220):
        for q in q2:
            eps = mp.mpf(1) / q
            vals[q] = [mp.nstr(sum(mp.mpf(cs) * eps ** o for o, cs in coeffs),
                               200) for coeffs in DATA['bnd']]
    for q in q1:
        vals[q] = DATA['bank'][q]

    def f(e):
        q = int(round(1 / float(e)))
        assert abs(1 / float(e) - q) < 1e-6 * q and q in vals, \
            f'bndval fan: unexpected node eps={e}'
        return [mp.mpf(s) for s in vals[q]]

    try:
        res = EFAN.vandermonde_laurent_certified(
            f, LO, HI, BND_CLAIM, R0=DATA['r0'],
            eps_nodes1=['1/%d' % q for q in q1],
            eps_nodes2=['1/%d' % q for q in q2],
            nodes_seed=24, guard=FAN_GUARD, k_certify=BND_KC)
    except EFAN.EpsFanCertifyError as exc:
        raise SystemExit(
            f'[bndval] certified fan refresh FAILED ({exc}) — the radical '
            f'closed forms cannot be seeded from the bank; NOT falling back '
            f'to the AMFlow strings.')
    diag = res['diag']
    bv = {}
    worst_cmp, cmp_at = 1e9, None
    worst_g, worst_x, worst_tp, zero_max = 1e9, 1e9, 1e9, 0.0
    with mp.workdps(200):
        gsc = max(mp.mpf(diag['gscale']), mp.mpf(1))
        for i in range(79):
            for o in range(BND_KC[0], BND_KC[1] + 1):
                v = mp.mpf(c160[i][o - LO])
                v130 = mp.mpf(c130[i][o - LO])
                eng = mp.mpf(mp.re(res['coeffs'][o][i]))

                def dig(d):
                    return float(-mp.log10(max(d, mp.mpf('1e-999'))))

                worst_x = min(worst_x, dig(abs(v - eng) / gsc))
                worst_tp = min(worst_tp, dig(abs(v - v130) / gsc))
                old_s = next((s for oo, s in DATA['bnd'][i] if oo == o), None)
                if old_s is None:
                    # old bnd_val returned exact 0 here: verify the bank fit
                    # is consistent with zero, then KEEP the exact-zero
                    # semantics (a fitted 1e-50-class residual must not
                    # pollute true-zero container cancellations)
                    if abs(v) > gsc * mp.mpf(10) ** (-BND_ZERO_MAX):
                        raise SystemExit(
                            f'[bndval] string-absent constant B{i}k{o} fits '
                            f'NON-ZERO from the bank: |c| = {mp.nstr(abs(v), 8)} '
                            f'> gscale*1e-{BND_ZERO_MAX} — true-zero semantics '
                            f'violated; refusing (measured healthy max '
                            f'6.15e-58*gscale).')
                    bv[(i, o)] = '0'
                    continue
                old = mp.mpf(old_s)
                dg = dig(abs(v - old) / gsc)
                worst_g = min(worst_g, dg)
                dr = dig(abs(v - old) / max(abs(old), mp.mpf('1e-300')))
                if abs(old) >= gsc * mp.mpf('1e-8'):
                    if dr < worst_cmp:
                        worst_cmp, cmp_at = dr, (i, o)
                    if dr < BND_COMPARE_MIN:
                        raise SystemExit(
                            f'[bndval] refreshed constant B{i}k{o} vs demoted '
                            f'AMFlow string MISMATCH: {dr:.1f} d < '
                            f'{BND_COMPARE_MIN} d (measured healthy floor '
                            f'39.23 d) — a string/bank mutation or stale '
                            f'vendor is fatal; the bank is the definition. '
                            f'NOT running.')
                if dg < BND_COMPARE_MIN_G:
                    raise SystemExit(
                        f'[bndval] refreshed constant B{i}k{o} vs demoted '
                        f'AMFlow string MISMATCH (gscale): {dg:.1f} d < '
                        f'{BND_COMPARE_MIN_G} d (measured healthy floor '
                        f'43.87 d). NOT running.')
                bv[(i, o)] = c160[i][o - LO]
    if worst_x < BND_XCHECK_MIN:
        raise SystemExit(
            f'[bndval] producer-vs-certifier xcheck FAILED: {worst_x:.1f} d '
            f'< claim-2 = {BND_XCHECK_MIN} d (measured healthy 42.4 d) — '
            f'the square fit and the certified fan have diverged; NOT '
            f'trusting either.')
    if worst_tp < BND_TP_MIN:
        raise SystemExit(
            f'[bndval] dps130-vs-dps160 fit certificate FAILED: '
            f'{worst_tp:.1f} d < {BND_TP_MIN} d (measured healthy 127.0 d) '
            f'— bank sweeps inconsistent at the fit level; NOT running.')
    DATA['bndval'] = bv
    return {'claim': BND_CLAIM, 'kc': BND_KC,
            'certify_min': diag['certify_min_agree_digits'],
            'verify_min': min(self160), 'cond': diag['cond'],
            'wp': diag['wp'], 'compare_min': worst_cmp, 'compare_at': cmp_at,
            'compare_min_g': worst_g, 'xcheck_min': worst_x,
            'tp_min': worst_tp, 'n_zero': sum(1 for s in bv.values()
                                              if s == '0')}


def _certified_R0():
    """Certified lower bound on the eps-analyticity radius of the exact
    connection's y-INDEPENDENT coefficient denominators: primitive-dedupe
    all N/Q coefficient den polys (in d), shift t = d-4 with EXACT t^m
    deflation (eps=0 = expansion point), then per poly the Cauchy lower
    bound |q0|/(|q0|+max|qk|); polys below 3/100 get exact rational-root
    deflation + polyroots (err-deflated) refinement.  eps = t/2.  The
    y-DEPENDENT Q(d,y) flow zeros are NOT bounded here — they are gated a
    posteriori by the fan's interleaved-verify + two-grid + node-
    certificate checks (all raising).  Returns (R0_string, float) — measured on this
    data: 143 primitive polys, true nearest den singularity eps = 1/4
    (d = 7/2), certified bound >= 0.015."""
    from math import gcd
    dens = set()
    for _i, _j, N, Q in DATA['ent']:
        for side in (N, Q):
            for _nc, dc in side:
                dens.add(tuple(dc))
    prim = set()
    for p in dens:
        cs = list(p)
        while cs and cs[-1] == 0:
            cs.pop()
        if len(cs) <= 1:
            continue
        L = 1
        for c in cs:
            L = L * c.denominator // gcd(L, c.denominator)
        ints = [int(c * L) for c in cs]
        g = 0
        for v in ints:
            g = gcd(g, abs(v))
        ints = [v // g for v in ints]
        if ints[-1] < 0:
            ints = [-v for v in ints]
        prim.add(tuple(ints))

    def shifted_deflated(p):
        n = len(p)
        q = [F(0)] * n
        for k, a in enumerate(p):
            c = 1
            for j in range(k + 1):
                q[j] += F(a) * c * F(4) ** (k - j)
                c = c * (k - j) // (j + 1)
        while q and q[-1] == 0:
            q.pop()
        lo = 0
        while lo < len(q) and q[lo] == 0:
            lo += 1
        return q[lo:]

    def rat_deflate(q):
        roots = []
        cur = list(q)
        changed = True
        while changed and len(cur) > 1:
            changed = False
            L = 1
            for c in cur:
                L = L * c.denominator // gcd(L, c.denominator)
            ic = [int(c * L) for c in cur]

            def divs(n):
                n = abs(n) or 1
                ds, i = [], 1
                while i * i <= n:
                    if n % i == 0:
                        ds += [i, n // i]
                    i += 1
                return sorted(set(ds))
            for pn in divs(ic[0]):
                for qd in divs(ic[-1]):
                    for s in (1, -1):
                        r = F(s * pn, qd)
                        v = F(0)
                        for c in reversed(ic):
                            v = v * r + c
                        if v == 0 and r != 0:
                            b = [F(0)] * (len(ic) - 1)
                            b[-1] = F(ic[-1])
                            for k in range(len(ic) - 3, -1, -1):
                                b[k] = F(ic[k + 1]) + r * b[k + 1]
                            roots.append(abs(r))
                            cur = b
                            changed = True
                            break
                    if changed:
                        break
                if changed:
                    break
        return roots, cur

    best = None
    with mp.workdps(80):
        for p in sorted(prim):
            q = shifted_deflated(p)
            if len(q) <= 1:
                continue
            q0 = abs(q[0])
            mx = max(abs(c) for c in q[1:])
            cb = F(q0, q0 + mx)
            if cb >= F(3, 100):
                cand = mp.mpf(cb.numerator) / cb.denominator
            else:
                rr, defl = rat_deflate(q)
                cand = None
                if rr:
                    cand = mp.mpf(min(rr).numerator) / min(rr).denominator
                if len(defl) > 1:
                    try:
                        roots, err = mp.polyroots(
                            [mp.mpf(c.numerator) / mp.mpf(c.denominator)
                             for c in reversed(defl)],
                            error=True, maxsteps=400, extraprec=300)
                        mn = min(abs(rt) for rt in roots) - err
                    except Exception:
                        d0 = abs(defl[0])
                        dm = max(abs(c) for c in defl[1:])
                        mn = mp.mpf(F(d0, d0 + dm).numerator) / \
                            F(d0, d0 + dm).denominator
                    cand = mn if cand is None else min(cand, mn)
                if cand is None:
                    cand = mp.mpf(cb.numerator) / cb.denominator
            if best is None or cand < best:
                best = cand
        r0 = best / 2                     # eps = (4 - d)/2
        return mp.nstr(r0, 12), float(r0)


def _is_prime(n):
    if n < 2:
        return False
    d, s = n - 1, 0
    while d % 2 == 0:
        d //= 2
        s += 1
    for a in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
        if a >= n:
            continue
        x = pow(a, d, n)
        if x in (1, n - 1):
            continue
        for _ in range(s - 1):
            x = x * x % n
            if x == n - 1:
                break
        else:
            return False
    return True


def _grid2_primes(qset):
    """36 shifted primes, geometric on the mild-shift band
    [1013/0.93, 10037/0.93] (the E4 grid_shift=0.93 design point mapped to
    the q side), disjoint from qset.  Deterministic."""
    used = set(qset)
    out = []
    lo, hi = 1013 / 0.93, 10037 / 0.93
    for i in range(36):
        t = int(lo * (hi / lo) ** (i / 35.0))
        p = t + 1 if t % 2 == 0 else t + 2
        while not _is_prime(p) or p in used:
            p += 2
        used.add(p)
        out.append(p)
    return out


def fan_certify(vals_by_q, dps, legacy_coeffs):
    """E4 certified-fan layer (E4 design rule 4, engine =
    epsfan_vendored.vandermonde_laurent_certified): explicit two-grid
    (bank-fed 24-q vs cache-fed 36-q mild-shift) + condition monitor + wp
    escalation + interleaved verify, all RAISING; two-grid check enforced on
    the QUOTED window (KC_LO..KC_HI) per the k_certify extension (higher
    fitted orders are tail-absorbers — measured per-k content is reported
    in the diag).  Cross-checks the engine's grid1 fit against the legacy
    full-precision fit (same node design) and RAISES on disagreement.
    Returns the engine diag + claim bookkeeping."""
    claim = min(dps, FAN_CLAIM_CAP)
    q1 = sorted(DATA['qset'])
    q2 = DATA['q2']
    q1set = set(q1)

    def f(e):
        q = int(round(1 / float(e)))
        assert abs(1 / float(e) - q) < 1e-6 * q, 'fan: non-1/q node'
        assert q in q1set or q in set(q2), f'fan: unexpected node q={q}'
        return [mp.mpf(s) for s in vals_by_q[q]]

    res = EFAN.vandermonde_laurent_certified(
        f, LO, HI, claim, R0=DATA['r0'],
        eps_nodes1=['1/%d' % q for q in q1],
        eps_nodes2=['1/%d' % q for q in q2],
        nodes_seed=24, guard=FAN_GUARD, k_certify=(KC_LO, KC_HI))
    diag = res['diag']
    with mp.workdps(claim + 60):
        gsc = max(mp.mpf(diag['gscale']), mp.mpf(1))
        worst = 1e9
        for k in range(KC_LO, KC_HI + 1):
            for i in range(len(legacy_coeffs)):
                d = abs(mp.mpf(legacy_coeffs[i][k - LO])
                        - mp.re(res['coeffs'][k][i]))
                worst = min(worst, float(-mp.log10(max(d / gsc,
                                                       mp.mpf('1e-999')))))
    if worst < claim - 2:
        raise SystemExit(
            f'[fan] engine-vs-legacy fit cross-check FAILED: quoted-window '
            f'agreement {worst:.1f} d < claim-2 = {claim - 2} d — the '
            f'certified gate layer and the shipped numbers have diverged; '
            f'NOT trusting either.')
    diag['legacy_xcheck_digits'] = worst
    diag['claim'] = claim
    diag['claim_capped'] = bool(dps > FAN_CLAIM_CAP)
    return diag


# ---------------------------------------------------------------- pipeline

def run_point(y_to, dps, jobs, order):
    prec = max(500, int(3.33 * (dps + 120)))
    dps_x = max(420, 3 * dps)
    t0 = time.time()
    cached = DATA.get('cached', False)
    src1 = 'strings' if cached else 'bank'
    tasks = [(q, y_to, prec, order, src1) for q in DATA['qset']]
    if not cached:
        # E4 shifted check grid (cache-fed by design: the vendored strings
        # are the compare-cache; their content on this band is certified by
        # the load-time compare check + the 19*log10(q)-6.1 truncation law).
        # These grid2 values feed ONLY fan_certify's raising checks — they
        # can refuse the run, never seed a shipped coefficient.
        tasks += [(q, y_to, prec, order, 'strings') for q in DATA['q2']]
    if jobs > 1:
        with Pool(min(jobs, len(tasks))) as pool:
            res = pool.map(leg, tasks)
    else:
        res = [leg(t) for t in tasks]
    t_legs = time.time() - t0
    byq = {q: (vals, rads) for q, vals, rads, _ in res}
    nodes = [(q, byq[q][0], byq[q][1]) for q in DATA['qset']]
    steps = sum(s for _, _, _, s in res)
    t1 = time.time()
    coeffs, selfd, max_rad = extract(nodes, dps_x)
    t_extract = time.time() - t1
    fan = None
    t1 = time.time()
    if not cached:
        fan = fan_certify({q: v for q, (v, _) in byq.items()}, dps, coeffs)
    t_fan = time.time() - t1
    folded = []
    sel = DATA.get('sel')
    pos = DATA.get('sel_pos') or {i: i for i in range(79)}
    only = set(DATA['targets']) if sel else None
    t1 = time.time()
    if DATA.get('radical') or DATA.get('radical_heavy'):
        coeff_over, self_over = radical_overrides(y_to, dps, jobs, only)
        by_master = {}
        for (i, o), s in coeff_over.items():
            if i not in pos:
                continue    # subset mode: a kept block folds ALL its target
                            # rows; rows outside the transported closure are
                            # not shipped — skip (full mode: pos covers 0..78)
            coeffs[pos[i]][o - LO] = s
            by_master.setdefault(i, set()).add(o)
        for i, d in self_over.items():
            if i not in pos:
                continue
            if by_master.get(i, set()) >= set(range(-2, 2)):
                selfd[pos[i]] = d     # fully folded over the QUOTED window
                                      # (-2..1, post-descope): closed-form bar
            else:
                selfd[pos[i]] = min(selfd[pos[i]], d)  # partial fold -- keep
                                              # the tighter of the two bars
        folded = sorted(i for i in self_over if i in pos)
    t_fold = time.time() - t1
    return {'coeffs': coeffs, 'self_digits': selfd, 'max_ball_rad': max_rad,
            'steps_total': steps, 'wall_s': time.time() - t0,
            'folded': folded, 'fan': fan,
            'phase_walls': {'march_legs_s': round(t_legs, 1),
                            'n_legs': len(tasks),
                            'n_rows': len(sel) if sel else 79,
                            'extract_s': round(t_extract, 1),
                            'fan_s': round(t_fan, 1),
                            'radical_fold_s': round(t_fold, 1)}}

def gate_point(tag, y_to, dps, jobs, order):
    out = run_point(y_to, dps, jobs, order)
    orc = DATA['oracles'][tag]
    rows = DATA.get('targets') or list(range(79))   # --master: gate the
    pos = DATA.get('sel_pos') or {i: i for i in range(79)}  # selected only
    per_master = []
    with mp.workdps(max(120, dps + 20)):
        for i in rows:
            mind = 1e9
            for order_n, re in orc['coeffs'][i]:
                if order_n >= 2:
                    continue          # eps^2+ DESCOPED 2026-07-04 (see header)
                ov = mp.mpf(re)
                cf = mp.mpf(out['coeffs'][pos[i]][order_n - LO])
                if ov == 0 and abs(cf) < mp.mpf('1e-30'):
                    continue
                dv = abs(cf - ov) / max(abs(ov), mp.mpf('1e-300'))
                mind = min(mind, float(-mp.log10(max(dv, mp.mpf('1e-999')))))
            per_master.append(min(mind, out['self_digits'][pos[i]]))
    out['gate_min_digits'] = min(per_master)
    out['gate_worst_master'] = DATA['masters'][rows[per_master.index(min(per_master))]]
    out['self_min_digits'] = min(out['self_digits'][pos[i]] for i in rows)
    out['n_gated'] = len(rows)
    out['per_master'] = list(zip(rows, per_master))
    return out

def _print_fan(fan, label):
    """One deterministic line per point for the E4 certified-fan layer."""
    if not fan:
        return
    ka, kb = fan['k_certify']
    print(f'# E4 FAN [{label}]: claim {fan["claim"]} d'
          + (' (CAPPED at %d — 24-node bank capacity, NOT a dps knob)'
             % FAN_CLAIM_CAP
             if fan['claim_capped'] else '')
          + f'; two-grid quoted-window (eps^{ka}..eps^{kb}) min '
            f'{fan["certify_min_agree_digits"]:.1f} d; verify self '
            f'{fan["self_digits"]:.1f} d; cond {fan["cond"]} (wp {fan["wp"]});'
            f' legacy-fit xcheck {fan["legacy_xcheck_digits"]:.1f} d; '
            f'n{fan["n_grid1"]}+{fan["n_grid2"]} explicit 1/q grids '
            f'[CERTIFIED]')


# ------------------------------------------- the imaginary parts (--gate-im)
# (2026-09-11) The line connection A(d, y) is real-rational, so the imaginary part of the 79-vector obeys the same
# differential equation as the real part the value tiers transport.  --gate-im seeds the SAME transport() with the
# certified node bank's imaginary parts (leg_im, the twin of leg), re-extracts the Laurent coefficients with the SAME
# extract(), and compares the 36 complex rows with the imaginary parts of the independent reference values
# (row35_reference_im.json; their real parts are row35_data.json's gate_oracles strings).  Nothing here enters a
# value tier: leg(), run_point(), gate_point() and every load gate are as they were.

def _im_pins(tag, quiet=False):
    """row35_reference_im.json against PINS_IM (rc 4 missing / rc 3 a sha256 differing, by name, before any use) --
    checked on every value run like the corner-row pins (the download is one bundle); 0 when the pin holds."""
    import hashlib
    for rel, want in PINS_IM.items():
        p = os.path.join(HERE, rel)
        if not os.path.exists(p):
            print(f'{tag} MISSING: {rel} is not beside this script -- it is part of the download (the '
                  f'imaginary parts of the reference values, read by --gate-im); restore it', file=sys.stderr)
            return 4
        got = hashlib.sha256(open(p, 'rb').read()).hexdigest()
        if got != want:
            print(f'{tag} PIN MISMATCH: {rel} sha256 {got[:16]}... != pinned {want[:16]}... -- refusing '
                  f'to read altered bytes', file=sys.stderr)
            return 3
    if not quiet:
        print(f'# {IM_REF_FILE}: sha256 pin OK ({PINS_IM[IM_REF_FILE][:16]}; the imaginary parts of the '
              f'independent reference values at y=1/2 and y=3/5, {len(IM_COMPLEX_ROWS)} complex rows named)')
    return 0


def _im_reference():
    """-> {'y12': [...], 'y35': [...]}: per row the [order, im-string] pairs of row35_reference_im.json (read after
    _im_pins).  The file's complex-row list must equal IM_COMPLEX_ROWS, its master list must equal
    row35_data.json's, and each point must carry 79 rows at the point's y (rc 3 by name otherwise)."""
    d = json.load(open(os.path.join(HERE, IM_REF_FILE)))
    raw = json.load(open(os.path.join(HERE, 'row35_data.json')))

    def refuse(msg):
        print(f'[gate-im] {IM_REF_FILE}: {msg} -- refusing', file=sys.stderr)
        raise SystemExit(3)
    if tuple(d['complex_rows']) != IM_COMPLEX_ROWS:
        refuse('complex_rows differ from the script\'s IM_COMPLEX_ROWS')
    if list(d['masters']) != list(raw['masters']):
        refuse('masters differ from row35_data.json\'s')
    out = {}
    for tag, y in IM_POINTS:
        pt = d['points'].get(tag)
        if pt is None or F(pt['y']) != y or len(pt['coeffs']) != 79:
            refuse(f'point {tag}: expected y = {y} and 79 rows')
        srv = raw['gate_oracles'][tag]['coeffs']
        for i in range(79):
            if [o for o, _ in pt['coeffs'][i]] != [o for o, _ in srv[i]]:
                refuse(f'point {tag} row {i}: the eps-orders differ from gate_oracles')
        out[tag] = pt['coeffs']
    return out


def _bank_im_seeds():
    """{q: [79 im-strings]}: the imaginary parts of the certified node bank's dps160 sweep, read after
    _bank_load_and_gate has verified the bank's sha manifest, headers and certificates in this process (that gate
    parses both parts of every node; the value tiers keep the real parts)."""
    root = os.path.join(HERE, 'row35_nodes', 'dps160')
    out = {}
    for q in DATA['qset']:
        d = json.load(open(os.path.join(root, f'NODE{q}_TARGETS.json')))
        rows = sorted(d['rows'], key=lambda r: r['row'])
        if [r['row'] for r in rows] != list(range(79)):
            raise SystemExit(f'[gate-im] node bank dps160/NODE{q}: expected rows 0..78')
        out[q] = [r['im'] for r in rows]
    return out


def leg_im(args):
    """The Im twin of leg(): the same exact connection at d = 4 - 2/q, the same transport() from the base point
    y = 1/3 with the same precision, order and pole list, seeded with the bank's imaginary parts DATA['bank_im'][q]
    (all 79 rows).  Under the control the seed of row IM_CONTROL[0] is negated at q = IM_CONTROL[1].
    Returns (q, vals, rads, steps, wall_s)."""
    q, y_to, prec, order, control = args
    ent79 = A_at_d0(DATA['ent'], F(4) - F(2, q))
    seeds = list(DATA['bank_im'][q])
    if control and q == IM_CONTROL[1]:
        s = seeds[IM_CONTROL[0]]
        seeds[IM_CONTROL[0]] = s[1:] if s.startswith('-') else '-' + s
    flint.ctx.prec = prec
    I0 = [flint.arb(s) for s in seeds]
    t0 = time.time()
    I, steps = transport(79, ent79, F(1, 3), F(y_to), I0, order, prec, DATA['poles'])
    vals, rads = [], []
    for r in range(79):
        m, rad = I[r, 0].mid(), I[r, 0].rad()
        vals.append(m.str(220, radius=False))
        rads.append(float(rad.str(5, radius=False)))
    return q, vals, rads, steps, time.time() - t0


def gate_point_im(tag, y_to, dps, jobs, order, ref, control=False):
    """--gate-im at one reference point: the 24 Im legs, then extract() (the served 20 fit + 4 verify design at
    dps_x), then per complex row the relative digits of every reference order below eps^2 against the reference
    imaginary parts (a zero-class order by the absolute floor instead) and per real row the transported
    |Im|/gscale against the same floor.  Returns the per-row table and the point's summary."""
    prec = max(500, int(3.33 * (dps + 120)))
    dps_x = max(420, 3 * dps)
    t0 = time.time()
    tasks = [(q, y_to, prec, order, control) for q in DATA['qset']]
    if jobs > 1:
        with Pool(min(jobs, len(tasks))) as pool:
            res = pool.map(leg_im, tasks)
    else:
        res = [leg_im(t) for t in tasks]
    t_legs = time.time() - t0
    byq = {q: (vals, rads, steps, w) for q, vals, rads, steps, w in res}
    nodes = [(q, byq[q][0], byq[q][1]) for q in DATA['qset']]
    t1 = time.time()
    coeffs, selfd, max_rad = extract(nodes, dps_x)
    t_extract = time.time() - t1
    orc_re, orc_im = DATA['oracles'][tag]['coeffs'], ref[tag]
    zero_o, floor = mp.mpf(IM_ZERO_ORACLE), mp.mpf(IM_ZERO_FLOOR)
    per_row, per_order = [], {}
    zero_n, zero_max, zero_fail = 0, 0.0, []
    real_max, real_at, real_fail = 0.0, None, []
    cset = set(IM_COMPLEX_ROWS)
    with mp.workdps(max(120, dps + 20)):
        for i in range(79):
            gscale = max([abs(mp.mpf(s)) for o, s in orc_re[i] if o < 2] + [mp.mpf('1e-300')])
            if i in cset:
                mind, worst_o, lead = 1e9, None, min(o for o, _ in orc_im[i])
                for o, s in orc_im[i]:
                    if o >= 2:
                        continue            # eps^2 and above: no digits quoted (the real gate's rule)
                    cf, ov = mp.mpf(coeffs[i][o - LO]), mp.mpf(s)
                    if abs(ov) < zero_o * gscale:
                        z = float(abs(cf) / gscale)
                        zero_n += 1
                        zero_max = max(zero_max, z)
                        if not z < float(floor):
                            zero_fail.append((i, o, z))
                        continue
                    dg = float(-mp.log10(max(abs(cf - ov) / abs(ov), mp.mpf('1e-999'))))
                    per_order[o] = min(per_order.get(o, 1e9), dg)
                    if dg < mind:
                        mind, worst_o = dg, o
                per_row.append((i, mind, worst_o, lead, selfd[i]))
            else:
                z = max([float(abs(mp.mpf(coeffs[i][o - LO])) / gscale) for o, _ in orc_im[i] if o < 2] + [0.0])
                if z >= real_max:
                    real_max, real_at = z, i
                if not z < float(floor):
                    real_fail.append((i, z))
    walls = sorted(byq[q][3] for q in DATA['qset'])
    steps = sorted(byq[q][2] for q in DATA['qset'])
    worst = min(per_row, key=lambda t: t[1])
    return {'tag': tag, 'y': y_to, 'prec': prec, 'dps_x': dps_x, 'order': order, 'jobs': jobs,
            'per_row': per_row, 'per_order': per_order, 'min': worst[1], 'worst_row': worst[0],
            'worst_order': worst[2], 'self_min_complex': min(t[4] for t in per_row),
            'zero_n': zero_n, 'zero_max': zero_max, 'zero_fail': zero_fail,
            'real_n': 79 - len(cset), 'real_max': real_max, 'real_at': real_at, 'real_fail': real_fail,
            'below_bar': [(i, d) for i, d, _o, _l, _s in per_row if d < IM_BAR_D],
            'legs_wall': (walls[0], walls[len(walls) // 2], walls[-1]), 'legs_steps': (steps[0], steps[-1]),
            'march_s': t_legs, 'extract_s': t_extract, 'max_rad': max_rad, 'wall_s': time.time() - t0}


def gate_im(a, ref):
    """The --gate-im tier: every point of --im-point through gate_point_im, one line per complex row, one CHECK-IM
    line per point, PASS / FAIL by name; rc 0 / 1."""
    pts = [(t, y) for t, y in IM_POINTS if a.im_point in ('both', t)]
    DATA['bank_im'] = _bank_im_seeds()
    print(f'# --gate-im: Im seeds = the certified node bank\'s imaginary parts (row35_nodes/dps160, '
          f'{len(DATA["qset"])} primes x 79 rows; the bank gates above passed on this load); reference = '
          f'{IM_REF_FILE} {PINS_IM[IM_REF_FILE][:16]} (the imaginary parts of the same independent reference '
          f'values whose real parts gate the value tiers; never used in any fit); bar {IM_BAR_D} d on each of the '
          f'{len(IM_COMPLEX_ROWS)} complex rows, |Im|/gscale < {IM_ZERO_FLOOR} on zero-class orders and on the '
          f'{79 - len(IM_COMPLEX_ROWS)} real rows', flush=True)
    if a.im_control:
        print(f'# --gate-im IM CONTROL: row {IM_CONTROL[0]} ({DATA["masters"][IM_CONTROL[0]]}) Im seed NEGATED at '
              f'the q = {IM_CONTROL[1]} node before the transport -- the tier must FAIL naming row {IM_CONTROL[0]}',
              flush=True)
    t0 = time.time()
    fails, mins = [], []
    for tag, y in pts:
        r = gate_point_im(tag, y, a.dps, a.jobs, a.order, ref, control=a.im_control)
        lw, ls = r['legs_wall'], r['legs_steps']
        print(f'# --gate-im [{tag} y={y}]: {len(DATA["qset"])} Im legs y=1/3 -> y={y} ({r["prec"]} bits, order '
              f'{r["order"]}, {ls[0]}-{ls[1]} steps per leg; per-leg wall {lw[0]:.1f} / {lw[1]:.1f} / {lw[2]:.1f} s '
              f'min / median / max; jobs {r["jobs"]}): march {r["march_s"]:.1f}s, extract {r["extract_s"]:.1f}s '
              f'(20 fit + 4 verify nodes, dps_x {r["dps_x"]}; max arb ball rad {r["max_rad"]:.1e})')
        for i, d, o, lead, s in r['per_row']:
            print(f'# master {DATA["masters"][i]} (row {i}): {d:.1f} digits (Im) vs the complex reference '
                  f'(y={y}; reference orders {lead}..1, worst at eps^{o}) [self {s:.1f}d]')
        ok = not (r['below_bar'] or r['zero_fail'] or r['real_fail'])
        po = ' / '.join(f'eps^{o} {v:.2f}' for o, v in sorted(r['per_order'].items()))
        print(f'# CHECK-IM {tag} y={y}: min {r["min"]:.2f}d over the {len(r["per_row"])} complex rows x the '
              f'reference orders below eps^2 (worst row {r["worst_row"]} {DATA["masters"][r["worst_row"]]} at '
              f'eps^{r["worst_order"]}; per order {po}); {r["zero_n"]} zero-class orders, max |Im|/gscale '
              f'{r["zero_max"]:.2e}; the {r["real_n"]} real rows: max transported |Im|/gscale {r["real_max"]:.2e} '
              f'(row {r["real_at"]}); self-consistency min over the complex rows {r["self_min_complex"]:.1f}d; '
              f'wall {r["wall_s"]:.1f}s [{"PASS" if ok else "FAIL"} >= {IM_BAR_D}]', flush=True)
        mins.append((tag, y, r['min']))
        if not ok:
            fails.append((tag, y, r))
    wall = time.time() - t0
    if not fails:
        print('# --gate-im: PASS -- the imaginary parts of the ' + str(len(IM_COMPLEX_ROWS)) + ' complex rows agree '
              'with the complex reference values to at least ' + ' and '.join(f'{m:.2f} d (y={y})' for _t, y, m in mins)
              + f' over the reference orders below eps^2; every zero-class order and every one of the '
              f'{79 - len(IM_COMPLEX_ROWS)} real rows below |Im|/gscale {IM_ZERO_FLOOR}; total wall {wall:.1f}s')
        return 0
    parts = []
    for tag, y, r in fails:
        seg = []
        if r['below_bar']:
            seg.append(f'{len(r["below_bar"])} complex rows below {IM_BAR_D} d: ' + ', '.join(
                f'row {i} {DATA["masters"][i]} {d:.1f}d' for i, d in r['below_bar']))
        if r['zero_fail']:
            seg.append('zero-class orders above the floor: ' + ', '.join(
                f'row {i} eps^{o} {z:.1e}' for i, o, z in r['zero_fail']))
        if r['real_fail']:
            seg.append('real rows above the floor: ' + ', '.join(f'row {i} {z:.1e}' for i, z in r['real_fail']))
        parts.append(f'{tag} y={y}: ' + '; '.join(seg))
    print('# --gate-im: FAIL' + (' (IM CONTROL)' if a.im_control else '') + ' -- ' + ' | '.join(parts)
          + f'; total wall {wall:.1f}s')
    return 1

# ------------------------------------------- expression-file check (--check-expression)

def check_expression(mutate=False):
    """Recompute, live and exactly, the structural claims written out in
    qqww-t4-expression.md: (1) the sector-487 fundamental system solves its
    block of the exact connection with ZERO remainder (exact Fraction
    rational-function arithmetic, no numerics); (2) the 15-letter alphabet:
    every claimed letter occurs in the y-denominator locus of the exact
    connection at d=4, with r+- the roots of 18y^2+93y+50; (3) r+- =
    (-31 +- sqrt(561))/12 exactly; (4) the elliptic-curve j chain: the
    sector-481 cubic at the base fiber gives the exact rational j, which
    factors through X0(2) as j = (t+256)^3/t^2 with the unique rational
    root t = 6787441/213725. Any mismatch exits nonzero. --mutate perturbs
    one sector-487 basis coefficient by a relative 1e-30 first — the check
    must then FAIL (the shipped control)."""
    t0 = time.time()
    print('# --check-expression: recomputing the expression file\'s '
          'structural claims (exact arithmetic)', flush=True)
    fails = []

    # ---- tiny exact poly / rational-function kit (coeff lists, asc) ------
    def padd(a, b):
        n = max(len(a), len(b))
        return [(a[i] if i < len(a) else F(0)) + (b[i] if i < len(b) else F(0))
                for i in range(n)]
    def pmul(a, b):
        r = [F(0)] * (len(a) + len(b) - 1)
        for i, x in enumerate(a):
            if x == 0:
                continue
            for j2, y2 in enumerate(b):
                r[i + j2] += x * y2
        return r
    def pder(a):
        return [a[i] * i for i in range(1, len(a))] or [F(0)]
    def ptrim(a):
        while len(a) > 1 and a[-1] == 0:
            a = a[:-1]
        return a
    def rf(n, d):
        return (ptrim(list(n)), ptrim(list(d)))
    def rf_add(A, B):
        (n1, d1), (n2, d2) = A, B
        return rf(padd(pmul(n1, d2), pmul(n2, d1)), pmul(d1, d2))
    def rf_mul(A, B):
        (n1, d1), (n2, d2) = A, B
        return rf(pmul(n1, n2), pmul(d1, d2))
    def rf_der(A):
        n, d = A
        return rf(padd(pmul(pder(n), d), [-c for c in pmul(n, pder(d))]),
                  pmul(d, d))
    def rf_iszero(A):
        return all(x == 0 for x in ptrim(A[0]))
    ZERO = rf([F(0)], [F(1)])

    raw = json.load(open(os.path.join(HERE, 'row35_data.json')))

    # ---- (1) sector-487 zero-remainder substitution ----------------------
    bas = json.load(open(os.path.join(HERE, 'qqww-t4-sector487.json')))
    rows487 = bas['rows']
    idx = {g: l for l, g in enumerate(rows487)}
    a0, b0 = F(1, 3), F(4, 15)          # y = 1/3 + (4/15) t
    def ysub(p):                        # poly in y -> poly in t (exact)
        res = [F(0)]
        for c in reversed(p):
            res = padd(pmul(res, [a0, b0]), [c])
        return res
    def evd(nd, d0):
        num = sum(F(c) * d0 ** k for k, c in enumerate(nd['num']))
        den = sum(F(c) * d0 ** k for k, c in enumerate(nd['den']))
        return num / den
    Asub = [[ZERO] * 4 for _ in range(4)]
    for key, e in raw['A_entries'].items():
        i, j2 = (int(t) for t in key.split(','))
        if i in idx and j2 in idx:
            Nc = [evd(nd, F(4)) for nd in e['N']]
            Qc = [evd(qd, F(4)) for qd in e['Q']]
            Asub[idx[i]][idx[j2]] = rf(ysub(Nc), ysub(Qc))
    mut_note = ''
    cols = []
    for ci, col in enumerate(bas['columns']):
        comps = []
        for comp in col:
            v = ZERO
            for term in comp:
                if term['rad'] or term['word']:
                    fails.append('487 basis carries non-rational terms '
                                 '(expression file claims pure rational)')
                n = [F(c) for c in term['rat']['n']] or [F(0)]
                d = [F(c) for c in term['rat']['d']]
                if mutate and not mut_note and any(c != 0 for c in n):
                    k = next(k for k, c in enumerate(n) if c != 0)
                    n[k] = n[k] * (F(10 ** 30 + 1, 10 ** 30))
                    mut_note = (f'column {ci + 1}, coefficient {k}: '
                                f'relative 1e-30 perturbation applied')
                v = rf_add(v, rf(n, d))
            comps.append(v)
        cols.append(comps)
    if mutate:
        print(f'#   MUTATE CONTROL: {mut_note}')
    bad = 0
    for ci, col in enumerate(cols):
        for a in range(4):
            resid = rf_der(col[a])
            for b in range(4):
                # dY/dt = (dy/dt) A_y(y(t)) Y = (4/15) A Y
                term = rf_mul(Asub[a][b], col[b])
                resid = rf_add(resid, rf_mul(term, ([-b0], [F(1)])))
            if not rf_iszero(resid):
                bad += 1
    if bad:
        fails.append(f'sector-487 remainder NONZERO in {bad}/16 components')
        print(f'#   sector 487: remainder NONZERO in {bad}/16 components [FAIL]')
    else:
        print('#   sector 487: d/dt Y_c - (4/15) A(t) Y_c == 0 exactly, all '
              '4 columns x 4 components [PASS]')

    # ---- (2)+(3) alphabet from the denominators + r+- --------------------
    CLAIMED_RATIONAL = [F(0), F(-1), F(5, 3), F(-5, 3), F(-31, 12), F(-31, 6),
                        F(-41, 6), F(-25, 6), F(-7, 2), F(-73, 48),
                        F(-175, 48), F(91, 24), F(-215, 24)]
    RPM_QUAD = (50, 93, 18)             # 18 y^2 + 93 y + 50, asc coeffs
    from math import lcm
    roots, quads = set(), set()
    seen_dens = {}
    for key, e in raw['A_entries'].items():
        Qc = tuple(evd(qd, F(4)) for qd in e['Q'])
        while len(Qc) > 1 and Qc[-1] == 0:
            Qc = Qc[:-1]
        if len(Qc) <= 1 or Qc in seen_dens:
            continue
        seen_dens[Qc] = True
        L = 1
        for c in Qc:
            L = lcm(L, c.denominator)
        p = flint.fmpz_poly([int(c * L) for c in Qc])
        _, fac = p.factor()
        for f, _m in fac:
            cf = [int(f[i]) for i in range(f.degree() + 1)]
            if f.degree() == 1:
                roots.add(F(-cf[0], cf[1]))
            elif f.degree() >= 2:
                g = lcm(cf[0], 1)
                quads.add(tuple(cf))
    missing = [str(r) for r in CLAIMED_RATIONAL if r not in roots]
    # the r+- quadratic, up to an overall integer factor
    def prim(t):
        from math import gcd
        g = 0
        for c in t:
            g = gcd(g, abs(c))
        t = tuple(c // g for c in t)
        return t if t[-1] > 0 else tuple(-c for c in t)
    have_quad = any(prim(qd) == RPM_QUAD for qd in quads)
    if missing:
        fails.append(f'alphabet letters NOT in the denominator locus: {missing}')
        print(f'#   alphabet: MISSING letters {missing} [FAIL]')
    elif not have_quad:
        fails.append('quadratic 18y^2+93y+50 not among denominator factors')
        print('#   alphabet: r+- quadratic NOT found [FAIL]')
    else:
        extra = sorted(set(roots) - set(CLAIMED_RATIONAL))
        print(f'#   alphabet: all 13 rational letters + the quadratic '
              f'18y^2+93y+50 (roots r+-) found in the denominator locus of '
              f'the exact connection at d=4 ({len(seen_dens)} distinct '
              f'denominators) [PASS]')
        print(f'#   (the locus also carries {len(extra)} additional apparent '
              f'singularities that appear in no GPL word — listed in the '
              f'expression file)')
    # r+- = (-31 +- sqrt(561))/12 exactly: work in Q(sqrt(561)),
    # r = (-31 + s*e)/12 with e^2 = 561; 18r^2 + 93r + 50 must vanish in
    # both the rational and the sqrt component.
    for sgn in (1, -1):
        # r^2 = (961 + 561 - 62*sgn*e)/144 = (1522 - 62 sgn e)/144
        rat = F(18) * F(1522, 144) + F(93) * F(-31, 12) + 50
        irr = F(18) * F(-62 * sgn, 144) + F(93) * F(sgn, 12)
        if rat != 0 or irr != 0:
            fails.append(f'r{"+" if sgn > 0 else "-"} does not satisfy '
                         f'18y^2+93y+50=0')
    if not fails or all('r+' not in f and 'r-' not in f for f in fails):
        print('#   r+- = (-31 +- sqrt(561))/12: 18 r^2 + 93 r + 50 == 0 '
              'exactly (rational and sqrt components both vanish) [PASS]')

    # ---- (4) elliptic j chain (exact Fractions end to end) ---------------
    x, z, yv, z5 = F(17, 2), F(5, 3), F(1, 3), F(7, 3)
    # cubic in z4: g1 * G2 with the page's explicit polynomials
    # g1 = -1/4 (y^2 - 2 y z5 + 2 y + 4 z z4 + z5^2 - 2 z5 + 1)
    g1 = [F(-1, 4) * (yv * yv - 2 * yv * z5 + 2 * yv + z5 * z5 - 2 * z5 + 1),
          F(-1, 4) * 4 * z]                                      # deg 1 in z4
    # G2 = 1/16 ( ... )  — coefficients of z4^0, z4^1, z4^2
    G2c0 = F(1, 16) * (x * x * yv * yv + 2 * x * x * yv + x * x
                       + 2 * x * yv * yv * z5 - 2 * x * yv * z * z5
                       + 2 * x * yv * z5 - 2 * x * z * z5
                       + yv * yv * z5 * z5 - 2 * yv * z * z5 * z5
                       + z * z * z5 * z5)
    G2c1 = F(1, 16) * (2 * x * x * yv - 2 * x * x - 4 * x * yv * z
                       + 2 * x * yv * z5 - 4 * x * yv + 4 * x * z * z
                       + 2 * x * z * z5 + 4 * x * z)
    G2c2 = F(1, 16) * (x * x - 4 * x * z)
    cub = pmul(g1, [G2c0, G2c1, G2c2])
    if len(ptrim(cub)) != 4:
        fails.append('sector-481 curve: g1*G2 is not cubic in z4')
    aa0, aa1, aa2, aa3 = cub[0], cub[1], cub[2], cub[3]
    bq = aa2 / aa3; cq = aa1 / aa3; dq = aa0 / aa3
    b2 = 4 * bq; b4 = 2 * cq; b6 = 4 * dq
    c4 = b2 * b2 - 24 * b4
    c6 = -b2 ** 3 + 36 * b2 * b4 - 216 * b6
    disc = (c4 ** 3 - c6 ** 2) / 1728
    jexact = c4 ** 3 / disc
    J_CLAIM = F(232620187166690272611921, 9846172967579601725)
    T_CLAIM = F(6787441, 213725)
    if jexact != J_CLAIM:
        fails.append(f'j mismatch: computed {jexact} != claimed {J_CLAIM}')
        print('#   j chain: exact j MISMATCH [FAIL]')
    elif (T_CLAIM + 256) ** 3 != jexact * T_CLAIM ** 2:
        fails.append('t = 6787441/213725 does not satisfy (t+256)^3 = j t^2')
        print('#   j chain: X0(2) relation FAILS at the claimed t [FAIL]')
    else:
        with mp.workdps(20):
            jf = mp.mpf(jexact.numerator) / jexact.denominator
            print(f'#   sector-481 curve at the base fiber (y=1/3, z5=7/3): '
                  f'exact j = {jexact.numerator}/{jexact.denominator} '
                  f'= {mp.nstr(jf, 10)}; (t+256)^3 = j t^2 holds exactly at '
                  f't = 6787441/213725 [PASS]')

    wall = time.time() - t0
    if fails:
        print(f'# --check-expression: FAIL ({len(fails)} failure(s), '
              f'wall {wall:.1f}s)')
        for f in fails:
            print(f'#   FAIL: {f}')
        return 5
    print(f'# --check-expression: ALL CHECKS PASS (wall {wall:.1f}s)')
    return 0


# ------------------------------------------------- the containers of containers.json
# (2026-09-05; hosting 2026-09-11) CONTAINERS.md beside this script names every
# container of this bundle -- the boundary-regeneration chain, hosted beside the
# script, and the files not hosted with it (the two closed-form containers of
# sectors 421/453, the regenerated node
# pair) by file name, sha256 and byte size; containers.json is its
# machine-readable twin and the only source the checks below read.  A
# container found beside the script is verified (size first, sha256 only
# when the size matches) before it is used; a mismatch refuses by name with
# exit code 3, a required container that is absent refuses with exit code 4
# and prints the container's line.  Runs of the chain write every product
# under row35_chain_work/ beside the script; the container directory itself
# is never modified by this script (the chain may add a best-effort root
# cache .sings_cache/ inside it; no listed member changes).

CONTAINERS_JSON = 'containers.json'
CHAIN_TAR = 'row35_chain.tar.gz'
CHAIN_DIR = 'row35_chain'
CHAIN_RUNS = 'row35_chain_work'
CHAIN_ORACLE = 'out_d0_1013.json'      # the fixed-d0 oracle inside the chain dir
CHAIN_ETA0, CHAIN_LANDR = '130', '0.01'  # the recorded production launch line
                                       # (--eta0-factor / --land-r of the 48
                                       # node solves behind row35_nodes/)
RC_MISMATCH, RC_MISSING, RC_GATE = 3, 4, 5


def _refuse(rc, msg):
    print(msg, file=sys.stderr, flush=True)
    raise SystemExit(rc)


def _sha256_file(p):
    import hashlib
    h = hashlib.sha256()
    with open(p, 'rb') as f:
        for blk in iter(lambda: f.read(1 << 24), b''):
            h.update(blk)
    return h.hexdigest()


def _containers_manifest(required=True):
    p = os.path.join(HERE, CONTAINERS_JSON)
    if not os.path.exists(p):
        if required:
            _refuse(RC_MISSING, f'[containers] {CONTAINERS_JSON} is MISSING beside this '
                    f'script; it is part of the download (the machine-readable twin of '
                    f'CONTAINERS.md) and no container is used without it.')
        return None
    return json.load(open(p))


def _container_line(name, e, man):
    return (f'{name}: sha256 {e["sha256"]}, {e["bytes"]:,} bytes — {e["role"]}; '
            f'{man["availability"]} (CONTAINERS.md)')


def _container_verify(name, man):
    """A container found beside the script vs containers.json: size first,
    sha256 only when the size matches. -> 'absent' | 'ok'; refuses rc 3 on a
    mismatch, rc 4 when the manifest has no entry for a file that is there."""
    p = os.path.join(HERE, name)
    if not os.path.exists(p):
        return 'absent'
    e = man['containers'].get(name)
    if e is None:
        _refuse(RC_MISSING, f'[containers] {name} is beside this script but '
                f'{CONTAINERS_JSON} has no entry for it — not used.')
    got = os.path.getsize(p)
    if got != e['bytes']:
        _refuse(RC_MISMATCH, f'[containers] {name}: size {got:,} bytes != manifest '
                f'{e["bytes"]:,} bytes — REFUSED; a mismatched container is never '
                f'used. Obtain the file whose sha256 is {e["sha256"]}.')
    s = _sha256_file(p)
    if s != e['sha256']:
        _refuse(RC_MISMATCH, f'[containers] {name}: sha256 {s} != manifest '
                f'{e["sha256"]} — REFUSED; a mismatched container is never used.')
    return 'ok'


def _chain_members_check(cdir):
    """Every member of row35_chain/ vs the chain's own MANIFEST.sha256.json
    (size first, sha256 when present). -> (n_listed, missing, mismatching)."""
    mp_ = os.path.join(cdir, 'MANIFEST.sha256.json')
    if not os.path.exists(mp_):
        return 0, ['MANIFEST.sha256.json'], []
    cm = json.load(open(mp_))
    missing, bad = [], []
    for rel, ent in sorted(cm.items()):
        p = os.path.join(cdir, rel)
        if not os.path.exists(p):
            missing.append(rel)
        elif os.path.getsize(p) != ent['bytes'] or _sha256_file(p) != ent['sha256']:
            bad.append(rel)
    return len(cm), missing, bad


def _containers_status(man):
    """[(name, entry, status-string, level)] for every entry of containers.json
    as found beside the script; level = 'ok' | 'absent' | 'bad'."""
    rows = []
    for name, e in man['containers'].items():
        p = os.path.join(HERE, name)
        unp = e.get('unpacks_to')
        udir = os.path.join(HERE, unp) if unp else None
        if udir and os.path.isdir(udir):
            n, missing, bad = _chain_members_check(udir)
            if not missing and not bad:
                st, lv = f'unpacked as {unp}, {n}/{n} members verified', 'ok'
            elif missing:
                st, lv = (f'unpacked as {unp} but {len(missing)} of {n} members '
                          f'missing (first: {missing[0]})'), 'bad'
            else:
                st, lv = (f'unpacked as {unp} but {len(bad)} of {n} members do not '
                          f'match its manifest (first: {bad[0]})'), 'bad'
        elif os.path.exists(p):
            got = os.path.getsize(p)
            if got != e['bytes']:
                st, lv = f'present, size {got:,} bytes != {e["bytes"]:,} (MISMATCH)', 'bad'
            elif _sha256_file(p) != e['sha256']:
                st, lv = 'present, sha256 MISMATCH', 'bad'
            else:
                st, lv = ('present, sha256 OK' + (' (not yet unpacked)' if unp else ''),
                          'ok')
        else:
            st, lv = 'absent', 'absent'
        rows.append((name, e, st, lv))
    return rows


def _print_containers(rows, man, header):
    print(header)
    for name, e, st, _ in rows:
        print(f'#   {name}: {st} — sha256 {e["sha256"]}, {e["bytes"]:,} bytes; '
              f'{e["role"]}')
    print(f'#   ({man["availability"]}; CONTAINERS.md beside this script)')


def containers_cmd():
    """--containers: the status of every container listed in containers.json as found beside
    the script. rc 0, or rc 3 when a present container does not match."""
    man = _containers_manifest()
    rows = _containers_status(man)
    _print_containers(rows, man, f'# CONTAINERS (containers.json emitted {man["emitted"]}):')
    return RC_MISMATCH if any(lv == 'bad' for _, _, _, lv in rows) else 0


def _chain_require(man):
    """row35_chain/ beside the script with every member verified against the
    chain's own sha manifest. Refuses rc 4 (chain absent / tarball not
    unpacked / member missing) or rc 3 (member or tarball mismatch)."""
    e = man['containers'][CHAIN_TAR]
    cdir = os.path.join(HERE, CHAIN_DIR)
    if not os.path.isdir(cdir):
        if os.path.exists(os.path.join(HERE, CHAIN_TAR)):
            _container_verify(CHAIN_TAR, man)          # rc 3 on a mismatch
            _refuse(RC_MISSING, f'[boundary-recompute] {CHAIN_TAR} is beside this script '
                    f'(sha256 OK) but not unpacked: run  tar xzf {CHAIN_TAR}  in this '
                    f'directory so {CHAIN_DIR}/ sits beside the script, then rerun.')
        rows = _containers_status(man)
        lines = [f'[boundary-recompute] REFUSED (exit {RC_MISSING}): this mode needs the '
                 f'boundary-regeneration chain row35_chain.tar.gz (a download of this bundle, to be placed beside this script).',
                 f'  MISSING (required): {_container_line(CHAIN_TAR, e, man)}',
                 f'  unpack it beside this script: tar xzf {CHAIN_TAR}',
                 f'  status of every container of containers.json beside this script:']
        for name, en, st, _ in rows:
            lines.append(f'    {name}: {st} — sha256 {en["sha256"]}, {en["bytes"]:,} '
                         f'bytes; {en["role"]}')
        _refuse(RC_MISSING, '\n'.join(lines))
    n, missing, bad = _chain_members_check(cdir)
    if missing:
        _refuse(RC_MISSING, f'[boundary-recompute] {CHAIN_DIR}/: {len(missing)} of {n} '
                f'member(s) missing (first: {missing[0]}) — unpack {CHAIN_TAR} again '
                f'({_container_line(CHAIN_TAR, e, man)}).')
    if bad:
        _refuse(RC_MISMATCH, f'[boundary-recompute] {CHAIN_DIR}/{bad[0]} does not match '
                f'{CHAIN_DIR}/MANIFEST.sha256.json ({len(bad)} of {n} mismatching) — '
                f'REFUSED; re-obtain {CHAIN_TAR} (sha256 {e["sha256"]}, '
                f'{e["bytes"]:,} bytes).')
    print(f'# CHAIN: {CHAIN_DIR}/ beside this script, {n}/{n} members verified against '
          f'its sha manifest ({CHAIN_TAR} sha256 {e["sha256"][:16]}...)', flush=True)
    return cdir


def _rel(x):
    """Print form of a chain argument or product path: a path under the
    script's own directory is shown relative to it (every input and product
    of a chain run lives there); anything else is printed as is.  Only the
    printed line changes -- the argument handed to the driver is the same."""
    s = str(x)
    if os.path.isabs(s) and (s == HERE or s.startswith(HERE + os.sep)):
        return os.path.relpath(s, HERE)
    return s


def _run_chain(cdir, driver_rel, argv):
    """Run one chain driver from row35_chain/ with the container's own modules
    authoritative: the container directory is put first on the module path and
    detransport / chain_transport / flint_march are imported from it before the
    driver starts, so the code that runs is the code the sha manifest pins."""
    import subprocess
    code = ('import sys, runpy; C = sys.argv[1]; sys.path.insert(0, C); '
            'import detransport, chain_transport, flint_march; '
            'sys.argv = [sys.argv[2]] + sys.argv[3:]; '
            'runpy.run_path(sys.argv[0], run_name="__main__")')
    env = dict(os.environ)
    env.update({'ROW35_CHAIN_TRANSPORT': cdir, 'T4_TOOLS': cdir, 'T4_HEXA': cdir,
                'T4_DATA': cdir, 'PYTHONDONTWRITEBYTECODE': '1'})
    cmd = ([sys.executable, '-c', code, cdir, os.path.join(cdir, driver_rel)]
           + [str(x) for x in argv])
    print(f'# CHAIN RUN: {driver_rel} ' + ' '.join(_rel(x) for x in argv), flush=True)
    sys.stdout.flush()
    return subprocess.run(cmd, cwd=cdir, env=env).returncode


def _node_agreement(node_path, bank_path):
    """min over the 79 rows of the complex relative agreement (digits) between
    a regenerated node file and a shipped bank node — the bank's own
    two-precision comparator (mp.workdps(200))."""
    f = json.load(open(node_path))
    b = json.load(open(bank_path))
    fr = {r['row']: r for r in f['rows']}
    br = {r['row']: r for r in b['rows']}
    if sorted(fr) != list(range(79)) or any(fr[i].get('re') is None for i in fr):
        return None, None
    worst, at = 1e9, None
    with mp.workdps(200):
        for i in range(79):
            x = mp.mpc(mp.mpf(fr[i]['re']), mp.mpf(fr[i]['im']))
            y = mp.mpc(mp.mpf(br[i]['re']), mp.mpf(br[i]['im']))
            rel = abs(x - y) / max(abs(y), mp.mpf('1e-300'))
            dig = float(-mp.log10(max(rel, mp.mpf('1e-999'))))
            if dig < worst:
                worst, at = dig, i
    return worst, at


def boundary_recompute(a):
    """--boundary-recompute [DPS]: the from-definition chain, driven from
    row35_chain/ (verified first).  Three forms:
      default            GATE-D0 replay: the gate driver re-solves the chain at
                         eps=1/1013 on the DE closure of --bc-rows oracle rows
                         (default 20) and gates the result against the fixed-d0
                         oracle out_d0_1013.json inside the chain dir; where the
                         chain dir records a report for the same (rows, dps)
                         form, the new worst-row digits must reach it to 0.5 d.
      --gate-bc-only     the reduced boundary-table gate (seeds vs the exact
                         boundary tables at the first grid eps) + the recorded
                         GATE-D0 reports re-read from the verified chain dir.
      --regenerate-node Q  one from-definition node solve with the production
                         driver at eps=1/Q and the given dps (the recorded
                         launch line), written to row35_chain_work/fresh/dpsDPS/
                         NODEQ_TARGETS.json (a finished node is the checkpoint:
                         rerun skips it and says so) and compared row by row to the shipped
                         bank node(s); bar = dps-10 digits (the recorded gate at
                         dps130 was 120 d; the record read back identical).
                         The 48-solve regeneration of the bank is this call over
                         the 24 bank primes at dps 130 and 160.
    Returns 0 on pass; refusals exit 3/4, gate failures exit 5."""
    man = _containers_manifest()
    cdir = _chain_require(man)
    bdps = int(a.boundary_recompute)
    runs = os.path.join(HERE, CHAIN_RUNS)
    os.makedirs(runs, exist_ok=True)
    t0 = time.time()
    if a.regenerate_node is not None:
        q = int(a.regenerate_node)
        bank130 = os.path.join(HERE, 'row35_nodes', 'dps130', f'NODE{q}_TARGETS.json')
        bank160 = os.path.join(HERE, 'row35_nodes', 'dps160', f'NODE{q}_TARGETS.json')
        if not (os.path.exists(bank130) and os.path.exists(bank160)):
            _refuse(1, f'[boundary-recompute] --regenerate-node {q}: no shipped bank node '
                    f'for q={q} (row35_nodes/dps130 and dps160 hold the 24 bank primes; '
                    f'unpack row35_nodes.tar.gz beside the script).')
        node = os.path.join(runs, 'fresh', f'dps{bdps}', f'NODE{q}_TARGETS.json')
        os.makedirs(os.path.dirname(node), exist_ok=True)
        out = os.path.join(runs, f'node_dps{bdps}_q{q}')
        done = os.path.exists(node) and _node_agreement(node, bank130)[0] is not None
        if done:
            print(f'# NODE q={q} dps={bdps}: {_rel(node)} already complete (79/79 rows) — '
                  f'checkpoint honoured, solve skipped; comparing only', flush=True)
        else:
            rc = _run_chain(cdir, os.path.join('production', 't4_chain.py'),
                            ['--eps', f'1/{q}', '--dps', bdps, '--eta0-factor', CHAIN_ETA0,
                             '--land-r', CHAIN_LANDR, '--march-backend', 'flint',
                             '--out', out, '--rmap-out', node])
            if rc != 0:
                _refuse(RC_GATE, f'[boundary-recompute] node solve q={q} dps={bdps} FAILED '
                        f'rc={rc} (driver log above; march checkpoints under {_rel(out)}/ck/ '
                        f'are reused on rerun)')
        bar = bdps - 10
        worst = 1e9
        for lab, bp in (('dps130', bank130), ('dps160', bank160)):
            d, at = _node_agreement(node, bp)
            if d is None:
                _refuse(RC_GATE, f'[boundary-recompute] {_rel(node)}: incomplete node file')
            print(f'# NODE q={q} dps={bdps} vs shipped bank {lab}: min per-row agreement '
                  f'{d:.1f} d (row {at}) over 79 rows (complex, relative)')
            worst = min(worst, d)
        ok = worst >= bar
        how = ('from the checkpoint (solve skipped)' if done
               else 'regenerated from definition')
        print(f'# NODE q={q} dps={bdps}: {how}, worst agreement with '
              f'the shipped bank {worst:.1f} d vs bar dps-10 = {bar} d '
              f'[{"PASS" if ok else "FAIL"}]; wall {time.time() - t0:.1f}s '
              f'(checkpoint: {_rel(node)})')
        return 0 if ok else RC_GATE
    if a.gate_bc_only:
        out = os.path.join(runs, f'gate_bc_dps{bdps}')
        print(f'[boundary-recompute {bdps}] --gate-bc-only: reduced boundary-table gate '
              f'(GATE-BC, seeds vs the exact boundary tables at the first grid eps) + '
              f'the recorded GATE-D0 reports (NOT the end-to-end fixed-d0 gate)')
        rc = _run_chain(cdir, 't4_chain.py', ['--dps', bdps, '--gate-bc',
                                              '--bc-eps-indices', '0', '--out', out])
        if rc != 0:
            _refuse(RC_GATE, f'[boundary-recompute] GATE-BC FAILED rc={rc}')
        reps = json.load(open(os.path.join(out, 'gate_bc_report.json')))
        rec = json.load(open(os.path.join(cdir, 'chain_out', 'gate_bc_report.json')))
        recd = {(r['system'], r['eps_idx']): r for r in rec}
        for r in reps:
            key = (r['system'], r['eps_idx'])
            rr = recd.get(key, {})
            print(f"[boundary-recompute] GATE-BC system {r['system']} eps-index "
                  f"{r['eps_idx']}: entries {r.get('worst_entry_digits', -1):.1f} d, mu "
                  f"{r.get('worst_mu_digits', -1):.1f} d, sub-values "
                  f"{r.get('worst_subvalue_digits', -1):.1f} d (recorded "
                  f"{rr.get('worst_entry_digits', float('nan')):.1f} / "
                  f"{rr.get('worst_mu_digits', float('nan')):.1f} / "
                  f"{rr.get('worst_subvalue_digits', float('nan')):.1f} d)"
                  + ('' if 'FAIL' not in r else f" FAIL: {r['FAIL']}"))
        if any('FAIL' in r for r in reps):
            _refuse(RC_GATE, '[boundary-recompute] GATE-BC reported a failure (above)')
        for gp in ('gate_d0_rows5_dps60.json', 'gate_d0_rows20_dps130.json'):
            g = json.load(open(os.path.join(cdir, 'chain_out', gp)))
            print(f"[boundary-recompute] recorded {gp}: worst {g['digits_worst']:.1f} d "
                  f"over {g['nrows_gated']} rows (member of the verified chain dir)")
    else:
        nrows = int(a.bc_rows)
        out = os.path.join(runs, f'gate_d0_dps{bdps}_rows{nrows}')
        print(f'[boundary-recompute {bdps}] GATE-D0 replay of the chain on the closure of '
              f'{nrows} oracle rows, gated against the fixed-d0 oracle ...')
        rc = _run_chain(cdir, 't4_chain.py', ['--dps', bdps, '--gate-d0',
                                              os.path.join(cdir, CHAIN_ORACLE),
                                              '--d0-rows', nrows, '--out', out])
        if rc != 0:
            _refuse(RC_GATE, f'[boundary-recompute] chain replay FAILED rc={rc}')
        rep = f'gate_d0_rows{nrows}_dps{bdps}.json'
        g = json.load(open(os.path.join(out, rep)))
        recp = os.path.join(cdir, 'chain_out', rep)
        line = (f"[boundary-recompute] GATE-D0 vs fixed-d0 oracle: worst "
                f"{g['digits_worst']:.1f} / median {g['digits_median']:.1f} / best "
                f"{g['digits_best']:.1f} d over {g['nrows_gated']} rows at dps {bdps}")
        if os.path.exists(recp):
            r = json.load(open(recp))
            ok = g['digits_worst'] >= r['digits_worst'] - 0.5
            print(line + f" (recorded {r['digits_worst']:.1f} / {r['digits_median']:.1f} / "
                  f"{r['digits_best']:.1f} d for this form; bar recorded-0.5 d) "
                  f"[{'PASS' if ok else 'FAIL'}]")
            if not ok:
                _refuse(RC_GATE, '[boundary-recompute] GATE-D0 below the recorded worst')
        else:
            print(line + ' (no recorded report for this form; printed, not gated)')
    tp = json.load(open(os.path.join(cdir, 'ceiling_demo', 'TWO_PRECISION_LANDED.json')))
    ds = [float(d) for _, d in tp['pairs']]
    print(f'[boundary-recompute] the chain is the definition of the boundary; its recorded '
          f'two-precision certificate (dps150 vs dps210 at eps=1/1013, {len(ds)} system-0 '
          f'masters, ceiling_demo/) spans {min(ds):.1f}-{max(ds):.1f} d; the vendored '
          f'boundary_y13_laurent strings stay a compare-on-load cache (~50-57 d effective); '
          f'the value path below stays the certified bank (wall {time.time() - t0:.1f}s)\n')
    return 0


# ---- the Mellin-Barnes corner rows of the boundary: --mb-corner-provenance -------------------------------------------
def _mbc_sha(p):
    import hashlib
    return hashlib.sha256(open(p, 'rb').read()).hexdigest()


def _mbc_pins(tag, quiet=False):
    """every file of vendor_row35_mb_corner/ against PINS_MB_CORNER (rc 4 a file missing / rc 3 a sha256 differing, by
    name, before any print) and the vendored manifest's own sha lines against the same pins; 0 when every pin holds."""
    for rel, want in PINS_MB_CORNER.items():
        p = os.path.join(HERE, rel)
        if not os.path.exists(p):
            print(f'{tag} MISSING: {rel} is not beside this script -- every file of '
                  f'{MBC_DIR}/ is part of the download; restore it', file=sys.stderr)
            return 4
        got = _mbc_sha(p)
        if got != want:
            print(f'{tag} PIN MISMATCH: {rel} sha256 {got[:16]}... != pinned '
                  f'{want[:16]}... -- refusing to read altered bytes', file=sys.stderr)
            return 3
    man = [l for l in open(os.path.join(HERE, MBC_MANIFEST), encoding='utf-8').read().split('\n')
           if l and not l.startswith('#')]
    mm = {l.split()[1]: l.split()[0] for l in man}
    for rel, want in PINS_MB_CORNER.items():
        r2 = rel[len(MBC_DIR) + 1:]
        if r2 == 'MB_CORNER_MANIFEST.sha256':
            continue
        if mm.get(r2) != want:
            print(f'{tag} PIN MISMATCH: {MBC_MANIFEST} lists {r2} as {str(mm.get(r2))[:16]}... '
                  f'!= pinned {want[:16]}...', file=sys.stderr)
            return 3
    if not quiet:
        print(f'# {MBC_DIR}: {len(PINS_MB_CORNER)}/{len(PINS_MB_CORNER)} sha256 pins OK; {MBC_MANIFEST} '
              f'{PINS_MB_CORNER[MBC_MANIFEST][:16]} ({len(mm)} files by sha256, every line == its pin)')
    return 0


def _mbc_manifest_records():
    """the '# record:' and '# not shipped:' header lines of the vendored manifest: vendored file -> its record sha256 and
    status (VERBATIM or RE-CUT), and the record objects named but not shipped"""
    recs, not_shipped = {}, {}
    for l in open(os.path.join(HERE, MBC_MANIFEST), encoding='utf-8').read().split('\n'):
        if l.startswith('# record: ') and ' record_sha256 ' in l:
            w = l[len('# record: '):].split()
            if w[0].startswith('<'):
                continue      # the legend line
            recs[w[0]] = {'record_sha256': w[2], 'bytes': int(w[4]), 'status': w[5],
                          'vendored_sha256': w[9] if w[5] == 'RE-CUT' else w[2],
                          'recut_strings': int(w[7]) if w[5] == 'RE-CUT' else 0}
        elif l.startswith('# not shipped: '):
            w = l[len('# not shipped: '):].split()
            not_shipped[w[0]] = {'sha256': w[2], 'bytes': int(w[4]), 'note': l.split('(', 1)[1].rstrip(')') if '(' in l else ''}
    return recs, not_shipped


def _mbc_label(rel, recs):
    """'<file> <sha16>' (+ ' (record <sha16>)' when the vendored copy is a re-cut of the record object)"""
    v = PINS_MB_CORNER[MBC_DIR + '/' + rel][:16]
    r = recs.get(rel)
    if r and r['status'] == 'RE-CUT':
        return f'{rel.split("/")[-1]} {v} (record {r["record_sha256"][:16]}, {r["recut_strings"]} strings re-cut)'
    return f'{rel.split("/")[-1]} {v}'


def _mbc_render_lin(c0, ce, coeffs, names, eps='eps'):
    """'c0 + ce*eps + sum coeff*var' in the record's prose form ('1 + eps + s1 + s2 + s3', '-eps - s1', '-1 + delta - s1 + 2b1')"""
    terms = []
    if c0:
        terms.append((c0, ''))
    if ce:
        terms.append((ce, eps))
    for k, v in zip(coeffs, names):
        if k:
            terms.append((k, v))
    if not terms:
        return '0'
    out = ''
    for i, (k, v) in enumerate(terms):
        mag = abs(k)
        body = (str(mag) if not v else (v if mag == 1 else f'{mag}{v}'))
        if i == 0:
            out = ('-' if k < 0 else '') + body
        else:
            out += (' - ' if k < 0 else ' + ') + body
    return out


def _mbc_rep_module(path):
    """the record's representation module read AS TEXT (its engine imports are not shipped; nothing is executed): the
    docstring, the Gamma lists of build() rendered from its C(...)/A(...) literals, the contours, the closure sides, the
    bases"""
    import ast
    tree = ast.parse(open(path, encoding='utf-8').read())
    doc = ast.get_docstring(tree, clean=False) or ''
    out = {'doc': doc, 'gn': [], 'gd': [], 'pw': [], 'contours': [], 'names': [], 'sides': {}, 'bases': {}, 'pref': None, 'nfold': None}

    def ints(call):
        return [(-a.operand.value if isinstance(a, ast.UnaryOp) else a.value) for a in call.args]

    def gamma(tup):
        c, a = tup.elts
        ci = ints(c)
        return (ci[0], ci[1] if len(ci) > 1 else 0, ints(a))

    def frac(node):
        if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Div):
            return f'{frac(node.left)}/{frac(node.right)}'
        if isinstance(node, ast.Call):
            return str(node.args[0].value)
        return str(node.value)
    for node in tree.body:
        if isinstance(node, ast.Assign) and isinstance(node.value, ast.Tuple) and isinstance(node.targets[0], ast.Tuple):
            for tg, val in zip(node.targets[0].elts, node.value.elts):
                if tg.id in ('S', 'W', 'U'):
                    out['bases'][tg.id] = frac(val)
        if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name) and node.targets[0].id == 'SIDES':
            out['sides'] = {k.value: v.value for k, v in zip(node.value.keys, node.value.values)}
        if isinstance(node, ast.FunctionDef) and node.name == 'build':
            for st in node.body:
                if isinstance(st, ast.Assign) and isinstance(st.targets[0], ast.Name) and st.targets[0].id in ('gn', 'gd'):
                    out[st.targets[0].id] = [gamma(e) for e in st.value.elts]
                if isinstance(st, ast.Assign) and isinstance(st.targets[0], ast.Name) and st.targets[0].id == 'pw':
                    for e in st.value.elts:
                        base, c, a = e.elts
                        ci = ints(c)
                        out['pw'].append((base.value, ci[0], ci[1] if len(ci) > 1 else 0, ints(a)))
                if isinstance(st, ast.Return):
                    args = st.value.args
                    out['nfold'] = args[0].value
                    out['pref'] = -args[1].operand.value if isinstance(args[1], ast.UnaryOp) else args[1].value
                    out['contours'] = [c.args[0].value for c in args[5].elts]
                    out['names'] = [n.value for n in args[6].elts]
    names = out['names']
    out['gn_str'] = [_mbc_render_lin(c0, ce, a, names) for c0, ce, a in out['gn']]
    out['gd_str'] = [_mbc_render_lin(c0, ce, a, names) for c0, ce, a in out['gd']]
    out['pw_str'] = [f'{b}^{{{_mbc_render_lin(c0, ce, a, names)}}}' for b, c0, ce, a in out['pw']]
    return out


def _mbc_result_block(doc):
    """the RESULT block of the record docstring (from 'RESULT' to the contour line), verbatim, and its Gamma counts and
    contour tuple parsed from the prose"""
    import re as _re
    i = doc.find('RESULT')
    j = _re.search(r'\n\s*(Contours|CONTOURS)', doc[i:])
    block = doc[i:i + j.start()] if j else doc[i:]
    num, den = block, ''
    if '/ [' in block:
        num, den = block.split('/ [', 1)
    n_num = num.count('G('); n_den = den.count('G(')
    m = _re.search(r'\(c_s1[^)]*\)\s*=\s*\(([^)]*)\)', doc[i:])
    cont = [x.strip() for x in m.group(1).split(',')] if m else []
    return block, n_num, n_den, cont


def _mbc_point(s):
    """an mpc from the object's '(re + imj)' decimal strings exactly as the record built it (mpc(mpf(re), mpf(im)))"""
    import re as _re
    m = _re.match(r'\(?\s*([-+]?\d+(?:\.\d+)?)\s*([-+])\s*(\d+(?:\.\d+)?)j\s*\)?$', s)
    return mp.mpc(mp.mpf(m.group(1)), mp.mpf(m.group(2) + m.group(3)))


def _mbc_digits(a, b):
    return float(-mp.log10(abs(a - b) / abs(b))) if a != b else 999.0


def _mbc_scoped_import(subdir, name):
    d = os.path.join(HERE, MBC_DIR, subdir)
    sys.path.insert(0, d)
    try:
        return __import__(name)
    finally:
        sys.path.remove(d)


def _mbc_quad_breakpoints(lib_path, func_name):
    """the breakpoint list of the quad(...) call inside the named method of a vendored library, by AST"""
    import ast
    tree = ast.parse(open(lib_path, encoding='utf-8').read())
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == func_name:
            T = None
            for a_, dflt in zip(reversed(node.args.args), reversed(node.args.defaults)):
                if a_.arg == 'T':
                    T = dflt.value
            for sub in ast.walk(node):
                if isinstance(sub, ast.Call) and getattr(sub.func, 'id', '') == 'quad':
                    pts = []
                    for e in sub.args[1].elts:
                        if isinstance(e, ast.Constant):
                            pts.append(e.value)
                        elif isinstance(e, ast.UnaryOp):
                            pts.append(-(e.operand.value if isinstance(e.operand, ast.Constant) else T))
                        else:
                            pts.append(T)
                    return pts, T
    raise KeyError(func_name)


def _mbc_recipe_r69a(producer_path):
    """the record producer's certificate (a) recipe by AST: the contour c3 and the breakpoints sorted(set(BASE + ip + OFFS))"""
    import ast
    tree = ast.parse(open(producer_path, encoding='utf-8').read())
    c3 = base = offs = None
    for node in ast.walk(tree):
        if isinstance(node, ast.Assign) and len(node.targets) == 1:
            tn = ast.unparse(node.targets[0])
            if tn == 'c3' and isinstance(node.value, ast.Call):
                c3 = node.value.args[0].value
            if tn == 'pts' and base is None and isinstance(node.value, ast.Call):
                inner = node.value.args[0].args[0]
                base = [ast.literal_eval(e) for e in inner.left.elts]
                offs = []
                for e in inner.right.elts:
                    if isinstance(e, ast.Name):
                        offs.append(0.0)
                    else:
                        v = e.right.value
                        offs.append(v if isinstance(e.op, ast.Add) else -v)
    return c3, base, offs


def _mbc_rederive(rows, dps_rd, compare):
    """the three seconds-class certificate re-derivations at the objects' working precision; returns the FAIL names"""
    import time as _time
    fails = []
    V = os.path.join(HERE, MBC_DIR)
    if 69 in rows:
        certs = json.load(open(os.path.join(V, MBC_FILES[69]['certs'])))
        lib = _mbc_scoped_import('row69', 'r69_lib')
        with mp.mp.workdps(dps_rd):
            num, den = certs['eps'].split('/')
            R = lib.Row69(mp.mpf(int(num)) / int(den))
            s1, s2 = _mbc_point(certs['test_point']['s1']), _mbc_point(certs['test_point']['s2'])
            c3s, base, offs = _mbc_recipe_r69a(os.path.join(V, MBC_FILES[69]['certs_producer']))
            a_, b_, c_ = R.H3_abc(s1, s2)
            c3 = mp.mpf(c3s)
            ip = float(-(a_).imag)
            pts = sorted(set(base + [ip + o for o in offs]))
            W = lib.W
            f = lambda t: (lambda s: mp.gamma(a_ + s) * mp.gamma(b_ + s) * mp.gamma(-s) * mp.rgamma(c_ + s) * W ** s)(mp.mpc(c3, t))
            t0 = _time.time()
            qa = mp.quad(f, pts) / (2 * mp.pi)
            ha = R.H3(s1, s2)
            d = round(_mbc_digits(qa, ha), 1)
            rec = certs['a_s3_to_2F1']['agree_digits']
            same = str(qa) == certs['a_s3_to_2F1']['quad'] and str(ha) == certs['a_s3_to_2F1']['closed']
            v = ('PASS' if abs(d - rec) <= MBC_REDERIVE_BAR_D else 'FAIL') if compare else 'not compared'
            print(f'#   re-derived here (dps {dps_rd}; the producer\'s recipe read from '
                  f'{MBC_FILES[69]["certs_producer"].split("/")[-1]}: contour Re s3 = {c3s}, breakpoints '
                  f'{base} + ip{offs} with ip = -Im(a)): (a) s3 -> 2F1 at the record test point {d} d '
                  f'(record {rec} d; |diff| {abs(d - rec):.1f} <= {MBC_REDERIVE_BAR_D}: {v}; the quad and closed-form '
                  f'strings == the object\'s: {same}) (wall {_time.time() - t0:.1f}s)')
            if v == 'FAIL':
                fails.append('row 69 (a) s3 -> 2F1')
    if 42 in rows:
        pil = json.load(open(os.path.join(V, MBC_FILES[42]['pilot'])))
        lib = _mbc_scoped_import('row42', 'r42_lib')
        with mp.mp.workdps(dps_rd):
            num, den = pil['eps'].split('/')
            R = lib.Row42(mp.mpf(int(num)) / int(den))
            s1, s2, b1 = (_mbc_point(pil['test_point'][k]) for k in ('s1', 's2', 'b1'))
            t0 = _time.time()
            qa = R.H3_quad(s1, s2)
            a_, b_, c_ = R.H3_abc(s1, s2)
            ha = mp.gamma(a_) * mp.gamma(b_) * R.R3(s1, s2)
            d = round(_mbc_digits(qa, ha), 1)
            rec = pil['a_s3_to_2F1']['agree_digits']
            same = str(qa) == pil['a_s3_to_2F1']['quad'] and str(ha) == pil['a_s3_to_2F1']['closed']
            v = ('PASS' if abs(d - rec) <= MBC_REDERIVE_BAR_D else 'FAIL') if compare else 'not compared'
            print(f'#   re-derived here (dps {dps_rd}; r42_lib H3_quad vs G(a)G(b)R3): (a) s3 -> 2F1 at the record '
                  f'test point {d} d (record {rec} d; |diff| {abs(d - rec):.1f} <= {MBC_REDERIVE_BAR_D}: {v}; the strings '
                  f'== the object\'s: {same}) (wall {_time.time() - t0:.1f}s)')
            if v == 'FAIL':
                fails.append('row 42 (a) s3 -> 2F1')
            t0 = _time.time()
            qb = R.M_quad(s1, s2, b1)
            mb_ = R.M(s1, s2, b1)
            d = round(_mbc_digits(qb, mb_), 1)
            rec = pil['b_b2_to_MeijerG']['agree_digits']
            pts, T = _mbc_quad_breakpoints(os.path.join(V, MBC_FILES[42]['lib']), 'M_quad')
            A, Bp = R.AB(s1, s2, b1)
            lx2 = mp.log(lib.U()) - mp.log(lib.W()) + mp.mpc(0, 1) * mp.pi
            cb2 = lib.CB2()
            f2 = lambda t: (lambda s: mp.gamma(A + s) * mp.gamma(1 + s) * mp.gamma(-s) * mp.gamma(Bp - s) * mp.exp(s * lx2))(mp.mpc(cb2, t))
            qb2 = mp.quad(f2, pts) / (2 * mp.pi)
            dc = round(_mbc_digits(qb2, mb_), 1)
            recc = pil['b_b2_to_MeijerG']['control_wrong_phase_agree_digits']
            same = str(qb) == pil['b_b2_to_MeijerG']['quad_with_phase'] and str(mb_) == pil['b_b2_to_MeijerG']['meijerg_inverted_principal']
            v = ('PASS' if abs(d - rec) <= MBC_REDERIVE_BAR_D else 'FAIL') if compare else 'not compared'
            vc = ('PASS' if abs(dc - recc) <= MBC_REDERIVE_BAR_D else 'FAIL') if compare else 'not compared'
            print(f'#   re-derived here (dps {dps_rd}; r42_lib M_quad vs M, the +i pi phase on the same breakpoints '
                  f'{pts} as the control): (b) b2 -> Meijer G with the u-channel phase {d} d (record {rec} d; |diff| '
                  f'{abs(d - rec):.1f} <= {MBC_REDERIVE_BAR_D}: {v}; the strings == the object\'s: {same}); the wrong-phase '
                  f'control {dc} d (record {recc} d; |diff| {abs(dc - recc):.1f}: {vc}) (wall {_time.time() - t0:.1f}s)')
            if v == 'FAIL':
                fails.append('row 42 (b) b2 -> Meijer G')
            if vc == 'FAIL':
                fails.append('row 42 (b) the wrong-phase control')
    return fails


def mb_corner_provenance(rows, rederive=False, dps_rd=None, dps_explicit=False):
    """--mb-corner-provenance: the Mellin-Barnes corner rows 69 / 42 / 43 of the boundary printed BY OBJECT from the files
    under vendor_row35_mb_corner/ (pins first, before any print); every figure read from a vendored file by key and
    named with its source file and sha256; the tier enters no digit into --check or any served gate.  Returns 0 PASS /
    1 a re-derivation FAIL or a record inconsistency (named) / 3 a pin differs / 4 a pinned file missing."""
    tag = '[mb-corner]'
    rc = _mbc_pins(tag)
    if rc:
        return rc
    V = os.path.join(HERE, MBC_DIR)
    recs, not_shipped = _mbc_manifest_records()
    inconsistent = []
    print(f'# eval_row35 -- nonplanar T4 qqbar->WW evaluator | mode: the Mellin-Barnes corner rows '
          f'{" / ".join(str(r) for r in rows)} of the boundary, provenance by object (the written representations and '
          f'their certificates read from {MBC_DIR}/; no transport, no node bank; no digit enters --check)'
          + (' | RE-DERIVE' if rederive else ''), flush=True)
    n_verb = sum(1 for r in recs.values() if r['status'] == 'VERBATIM')
    print(f'# objects: {len(recs)} record files under {MBC_DIR}/ ({n_verb} verbatim by sha256, {len(recs) - n_verb} re-cut of only '
          f'their register-hitting strings, the record sha256 of each in the manifest header); '
          + '; '.join(f'{k} {v["sha256"][:16]} ({v["bytes"]:,} B) not shipped' for k, v in not_shipped.items()))
    if 69 in rows:
        F = MBC_FILES[69]
        rep = _mbc_rep_module(os.path.join(V, F['rep']))
        blk, n_num, n_den, cont = _mbc_result_block(rep['doc'])
        gr = json.load(open(os.path.join(V, F['gate_record'])))
        g20 = json.load(open(os.path.join(V, F['gate_q1117_dps20'])))
        g30 = json.load(open(os.path.join(V, F['gate_q1117_dps30'])))
        certs = json.load(open(os.path.join(V, F['certs'])))
        print(f'## row 69 (sector {gr["sector"]}, wpairT4{gr["indices"]}): the written five-fold representation of record -- '
              f'{_mbc_label(F["rep"], recs)}')
        print(f'#   variables ({", ".join(rep["names"])}); {rep["nfold"]} folds, prefactor {rep["pref"]}, measure (1/2 pi i)^{rep["nfold"]}; '
              f'contours ({", ".join(rep["contours"])}); bases ' + ', '.join(f'{k} = {v}' for k, v in rep['bases'].items())
              + '; closure sides of record ' + ', '.join(f'{k} {v}' for k, v in rep['sides'].items()))
        print(f'#   numerator Gammas ({len(rep["gn_str"])}): ' + ' '.join(f'G({s})' for s in rep['gn_str']))
        print(f'#   denominator Gammas ({len(rep["gd_str"])}): ' + ' '.join(f'G({s})' for s in rep['gd_str']))
        print(f'#   powers: ' + ' '.join(rep['pw_str']))
        print(f'#   the RESULT block of the record docstring, verbatim:')
        for l in blk.rstrip('\n').split('\n'):
            print(f'#     {l}')
        ok_cnt = (n_num == len(rep['gn'])) and (n_den == len(rep['gd'])) and (cont == rep['contours'])
        print(f'#   the prose against build(): {n_num} numerator / {n_den} denominator Gammas and the contour tuple '
              f'{tuple(cont)} {"==" if ok_cnt else "!="} the Gamma lists and contours of build() [{"PASS" if ok_cnt else "FAIL"}]')
        if not ok_cnt:
            inconsistent.append('row 69: the docstring RESULT block vs build()')
        print(f'#   certificates by object:')
        pr = gr['PRODUCER']
        print(f'#     {_mbc_label(F["gate_record"], recs)} (the record\'s gate; producer {pr["script"]} {pr["sha256"][:16]} + '
              f'{pr["lib"]} {pr["lib_sha256"][:16]}, dps {pr["mp_dps"]}): eps = {gr["eps"]}, value {gr["value_re"]}, '
              f'matched digits against the node bank {gr["GATE_heldout"]["dps130"]["matched_digits"]} (dps130 bank '
              f'{gr["GATE_heldout"]["dps130"]["bank_sha256"][:16]}) / {gr["GATE_heldout"]["dps160"]["matched_digits"]} (dps160 bank '
              f'{gr["GATE_heldout"]["dps160"]["bank_sha256"][:16]}); N = {gr["N_shanks"]} series terms, {gr["n_lines"]} s1 lines x '
              f'{gr["n_s2"]} s2 nodes')
        for key, g in (('gate_q1117_dps20', g20), ('gate_q1117_dps30', g30)):
            pr = g['PRODUCER']
            c130 = g['GATE_heldout']['dps130']; c160 = g['GATE_heldout']['dps160']
            print(f'#     {_mbc_label(F[key], recs)} (producer {pr["script"]} {pr["sha256"][:16]} + {pr["lib"]} '
                  f'{pr["lib_sha256"][:16]}, dps {pr["mp_dps"]}): eps = {g["eps"]}, value {g["value_re"]}, matched digits '
                  f'{c130["matched_digits"]} (dps130 bank {c130["bank_sha256"][:16]}) / {c160["matched_digits"]} (dps160 bank '
                  f'{c160["bank_sha256"][:16]}); N = {g["N_shanks"]}, T1 = {g["T1"]}, T2 = {g["T2"]}, panel width {g["PW"]}; '
                  f'the planted-digit control (the bank string\'s char {c130["planted_digit_control"]["position"]} changed): '
                  f'{c130["planted_digit_control"]["matched_digits"]} d -> {c130["planted_digit_control"]["verdict"]}')
        with mp.mp.workdps(60):
            v20, v30 = mp.mpf(g20['value_re']), mp.mpf(g30['value_re'])
            pair = float(-mp.log10(abs(v20 - v30) / abs(v30)))
        print(f'#     the pair at eps = {g20["eps"]}: the dps {g20["PRODUCER"]["mp_dps"]} and dps {g30["PRODUCER"]["mp_dps"]} values '
              f'agree to {pair:.2f} digits (computed here from the two objects\' value strings; the same grid and series length, so '
              f'the pair is the roundoff floor, not the truncation floor)')
        # the sha links between the objects
        links = [('the certificates\' record_rep.sha256 == the record sha256 of ' + F['rep'].split('/')[-1],
                  certs['record_rep']['sha256'] == recs[F['rep']]['record_sha256']),
                 ('the q1117 gates\' PRODUCER.sha256 == the record sha256 of ' + F['gate_producer'].split('/')[-1],
                  g20['PRODUCER']['sha256'] == g30['PRODUCER']['sha256'] == recs[F['gate_producer']]['record_sha256']),
                 ('every gate\'s and the certificates\' lib_sha256 == the sha256 of ' + F['lib'].split('/')[-1],
                  gr['PRODUCER']['lib_sha256'] == g20['PRODUCER']['lib_sha256'] == g30['PRODUCER']['lib_sha256']
                  == certs['PRODUCER']['lib_sha256'] == PINS_MB_CORNER[MBC_DIR + '/' + F['lib']]),
                 ('the certificates\' PRODUCER.sha256 == the record sha256 of ' + F['certs_producer'].split('/')[-1],
                  certs['PRODUCER']['sha256'] == recs[F['certs_producer']]['record_sha256']),
                 ('the two q1117 gates name the same bank files by sha256',
                  g20['GATE_heldout']['dps130']['bank_sha256'] == g30['GATE_heldout']['dps130']['bank_sha256']
                  and g20['GATE_heldout']['dps160']['bank_sha256'] == g30['GATE_heldout']['dps160']['bank_sha256'])]
        for bf in ('dps130', 'dps160'):
            bp = os.path.join(HERE, g20['GATE_heldout'][bf]['bank_file'])
            if os.path.exists(bp):
                links.append((f'the bank file {g20["GATE_heldout"][bf]["bank_file"]} beside this script == the gates\' bank_sha256',
                              _mbc_sha(bp) == g20['GATE_heldout'][bf]['bank_sha256']))
            else:
                links.append((f'the bank file {g20["GATE_heldout"][bf]["bank_file"]} is not unpacked beside this script: not cross-checked', True))
        for txt, ok in links:
            print(f'#     link: {txt}: {"OK" if ok else "MISMATCH"}')
            if not ok:
                inconsistent.append('row 69: ' + txt)
        tp = certs['test_point']
        ca, cb, cc, cd, ce = (certs[k] for k in ('a_s3_to_2F1', 'b_s4_to_MeijerG', 'c_split_vs_meijerg', 'd_s2_closure_census', 'e_w_closure'))
        print(f'#     {_mbc_label(F["certs"], recs)} (dps {certs["mp_dps"]}, eps {certs["eps"]}, test point s1 = {tp["s1"]}, '
              f's2 = {tp["s2"]}, w = {tp["w"]}): (a) s3 -> 2F1: {ca["agree_digits"]} d against direct contour quadrature; '
              f'(b) s4 -> Meijer G: {cb["agree_digits"]} d (the producer\'s sentinel for agreement at every printed digit) against '
              f'direct quadrature; (c) the Meijer split vs meijerg {cc["agree_digits"]} d; (d) the s2 residue closures: '
              f'{cd["verdict"]} (growth per step ' + ', '.join(f'{k} {v["growth_per_step_30to40"]}' for k, v in cd['families'].items())
              + f'); (e) the w LEFT closure {ce["L_agree_digits"]} d against direct quadrature ({ce["L_terms"]} terms), the RIGHT '
              f'closure {ce["R_verdict"]}; (f) {certs["f_cost_ms_per_F_eval"]} ms per integrand evaluation')
        src = open(os.path.join(V, F['gate_producer']), encoding='utf-8').read().split('\n')
        ref = [(i + 1, l.strip()) for i, l in enumerate(src) if 'sys.exit(5)' in l and 'foreign point' in l]
        print(f'#     the foreign point: {_mbc_label(F["gate_producer"], recs)} refuses a point the bank does not hold before any '
              f'compute (rc 5): line {ref[0][0] if ref else "?"}: {ref[0][1] if ref else "NOT FOUND"}')
        if not ref:
            inconsistent.append('row 69: the foreign-point refusal branch of ' + F['gate_producer'])
        print(f'#   established by object: the written representation evaluated independently at two points to the ten-to-eleven-digit '
              f'class against the node bank; not shipped here: the deeper first-point runs')
        if rederive:
            for f_ in _mbc_rederive((69,), dps_rd, compare=(dps_rd == certs['mp_dps'])):
                inconsistent.append(f_)
    if 42 in rows:
        F = MBC_FILES[42]
        rep = _mbc_rep_module(os.path.join(V, F['rep']))
        blk, n_num, n_den, cont = _mbc_result_block(rep['doc'])
        pil = json.load(open(os.path.join(V, F['pilot'])))
        clo = json.load(open(os.path.join(V, F['closure'])))
        ray = json.load(open(os.path.join(V, F['rayscan'])))
        print(f'## row 42 (sector 227, the written five-fold representation of record) -- {_mbc_label(F["rep"], recs)}')
        print(f'#   variables ({", ".join(rep["names"])}); {rep["nfold"]} folds, prefactor {rep["pref"]}, measure (1/2 pi i)^{rep["nfold"]}; '
              f'contours ({", ".join(rep["contours"])}); bases ' + ', '.join(f'{k} = {v}' for k, v in rep['bases'].items())
              + ' (U\' = u e^{-i pi}, the single phase-carrying base); closure sides of record '
              + ', '.join(f'{k} {v}' for k, v in rep['sides'].items()))
        print(f'#   numerator Gammas ({len(rep["gn_str"])}): ' + ' '.join(f'G({s})' for s in rep['gn_str']))
        print(f'#   denominator Gammas ({len(rep["gd_str"])}): ' + ' '.join(f'G({s})' for s in rep['gd_str']))
        print(f'#   powers: ' + ' '.join(rep['pw_str']))
        print(f'#   the RESULT block of the record docstring, verbatim:')
        for l in blk.rstrip('\n').split('\n'):
            print(f'#     {l}')
        ok_cnt = (n_num == len(rep['gn'])) and (n_den == len(rep['gd'])) and (cont == rep['contours'])
        print(f'#   the prose against build(): {n_num} numerator / {n_den} denominator Gammas and the contour tuple '
              f'{tuple(cont)} {"==" if ok_cnt else "!="} the Gamma lists and contours of build() [{"PASS" if ok_cnt else "FAIL"}]')
        if not ok_cnt:
            inconsistent.append('row 42: the docstring RESULT block vs build()')
        tp = pil['test_point']
        a, b, c, d = (pil[k] for k in ('a_s3_to_2F1', 'b_b2_to_MeijerG', 'c_continuation_control', 'd_b1_closure'))
        print(f'#   certificates by object:')
        print(f'#     {_mbc_label(F["pilot"], recs)} (producer {pil["PRODUCER"]["script"]} {pil["PRODUCER"]["sha256"][:16]} with '
              f'{pil["PRODUCER"]["lib"]} at {pil["PRODUCER"]["lib_sha256"][:16]}, an earlier cut of the vendored library '
              f'{PINS_MB_CORNER[MBC_DIR + "/" + F["lib"]][:16]}; dps {pil["dps"]}, eps {pil["eps"]}, test point s1 = {tp["s1"]}, '
              f's2 = {tp["s2"]}, b1 = {tp["b1"]}): (a) s3 -> 2F1: {a["agree_digits"]} d against direct contour quadrature; '
              f'(b) b2 -> Meijer G with the u-channel phase: {b["agree_digits"]} d against the direct quadrature carrying the phase, '
              f'the wrong-phase control {b["control_wrong_phase_agree_digits"]} d; (c) the continuation control: legal point '
              f'{c["legal_point_digits"]} d, straight + rest {c["illegal_straight_plus_rest_digits"]} d, straight - rest '
              f'{c["illegal_straight_minus_rest_digits"]} d ({c["rule"]}); (d) every b1 residue closure grows -- per step '
              + ', '.join(f'{k} {v["growth_per_step_30to40"]}' for k, v in d['families_growth'].items())
              + f' -- so b1 is quadrature (the R closure sum against the quadrature {d["R_sum_vs_quad_digits"]} d); (e) the straight '
              f'upper s2 tail relative to the origin ' + ', '.join(f'{k}: {v}' for k, v in pil['e_tail_scan']['s2'].items() if k.startswith('+'))
              + f' (a power law); (f) {pil["f_cost_ms_per_F_eval"]} ms per integrand evaluation')
        print(f'#     {_mbc_label(F["rayscan"], recs)}: the upper s2 ray from Im s2 = {ray["H"]} decays ' + '; '.join(
            f'{ang}: ' + ', '.join(f'tau {k}: {v}' for k, v in r.items()) for ang, r in ray['rays'].items()) + ' (relative to the origin)')
        cf = clo['1_closed_form_vs_meijerg']; fam = clo['1b_fam3_pinch_vs_limit']; cq = clo['2_closure_vs_quad']
        print(f'#     {_mbc_label(F["closure"], recs)} (dps {clo["dps"]}, eps {clo["eps"]}, contours c1 = {clo["c1"]}, cb1 = {clo["cb1"]}): '
              f'the Meijer closed form matches meijerg on the side {clo["side"]} of the 2F1 cut (pt0 {cf["pt0"]["closed_minus_digits"]} d, '
              f'pt1 {cf["pt1"]["closed_minus_digits"]} d); the pinch formula against the eta-limit '
              + ', '.join(f'{k}: {v["agree_digits"]} d' for k, v in fam.items())
              + '; the s2 LEFT residue closure against the piecewise quadrature '
              + ', '.join(f'{k}: {v["agree_digits"]} d after {v["terms"]} terms' for k, v in cq.items())
              + f' -- {clo.get("verdict", "the closure converges only as a power law: the s2 fold is quadrature")}')
        print(f'#   NOT EVALUATED: no bank digit')
        if rederive:
            for f_ in _mbc_rederive((42,), dps_rd, compare=(dps_rd == pil['dps'])):
                inconsistent.append(f_)
    if 43 in rows:
        F = MBC_FILES[43]
        r43 = json.load(open(os.path.join(V, F['rep'])))
        mbr = json.load(open(os.path.join(V, F['recipe'])))
        note = open(os.path.join(V, F['note']), encoding='utf-8').read().rstrip('\n').split('\n')
        print(f'## row 43 (sector {r43["sector"]}, wpairT4{r43["indices"]}): the written representation -- {_mbc_label(F["rep"], recs)}')
        print(f'#   variables ({", ".join(r43["vars"])}); basis of every Gamma argument ({", ".join(r43["basis"])}); prefactor and measure: {r43["pref"]}')
        print(f'#   numerator Gammas ({len(r43["numerator_gammas"])}): ' + ' '.join(f'G({s})' for s in r43['numerator_gammas']))
        print(f'#   denominator Gammas ({len(r43["denominator_gammas"])}): ' + ' '.join(f'G({s})' for s in r43['denominator_gammas']))
        print(f'#   powers: ' + ' '.join(f'{k}^{{{v}}}' for k, v in r43['powers'].items()) + '; bases '
              + '; '.join(f'{k} = {v}' for k, v in r43['bases'].items()))
        ef = r43['exact_factor']
        print(f'#   the exact factor {ef["form"]} = {ef["at_delta_0"]} at delta = 0 (by Gamma(z+1) = z Gamma(z) at z = -1-s1; {ef["origin"]})')
        # the argument vectors against the argument strings (the object's own consistency)
        names = r43['basis'][3:]
        ok_vec = True
        for strs, vecs in ((r43['numerator_gammas'], r43['numerator_gammas_vec']), (r43['denominator_gammas'], r43['denominator_gammas_vec'])):
            for s, v in zip(strs, vecs):
                iv = [int(x) for x in v]
                rendered = _mbc_render_lin(iv[0], iv[1], iv[3:], names)
                if iv[2]:
                    rendered = _mbc_render_lin(iv[0], 0, [iv[1], iv[2]] + iv[3:], ['eps', 'delta'] + names)
                if rendered != s:
                    ok_vec = False
        print(f'#   the argument vectors over the basis re-rendered against the argument strings: '
              f'{len(r43["numerator_gammas"]) + len(r43["denominator_gammas"])} Gammas [{"PASS" if ok_vec else "FAIL"}]')
        if not ok_vec:
            inconsistent.append('row 43: the Gamma argument vectors vs their strings')
        pn = r43['pinches']
        print(f'#   pinches: argument sums {pn["pinch1_Gamma(nu3+b1)Gamma(a3)_argsum"]} and '
              f'{pn["pinch2_Gamma(1+s1+s2)Gamma(lam+b1+b2)Gamma(-b1)Gamma(-b2)_argsum"]}: {pn["verdict"]}')
        dp = r43['defining_point']
        print(f'#   the delta-regulated defining point: eps0 = {dp["eps0"]}, delta0 = {dp["delta0"]}, contours {dp["contours (c_s1,c_s2,c_s3,c_b1,c_b2)"]}, '
              f'minimum margin {dp["min_margin"]} (all positive: {dp["all_positive"]}); at delta = 0 on the row-42 contours the failing arguments are '
              + ', '.join(f'{k} (margin {v})' for k, v in r43['delta0_row42_contours_failing_args'].items()))
        ws = r43['delta_walk_spec']
        ncross = sum(1 for fam in ws['families'] for p in fam['poles'] if p['crosses_c_b1'])
        print(f'#   the delta walk ({ws["contour"]}): {len(ws["families"])} b1 families enumerated, {ncross} poles cross the b1 contour between '
              f'delta = {dp["delta0"]} and 0; {ws["note"]}')
        wt = next(iter(not_shipped.items()), None)
        if wt:
            print(f'#   the enumerated pole-crossing tree {wt[0]} (sha256 {wt[1]["sha256"][:16]}, {wt[1]["bytes"]:,} B) is a record object not shipped here: {wt[1]["note"]}')
        ctl = r43['control_row42_reproduced']
        print(f'#   control: the general-power outer box reproduces the record\'s row-42 Gammas -- '
              + ', '.join(f'{k} {v}' for k, v in ctl.items()) + f' [{"PASS" if all(ctl.values()) else "FAIL"}]')
        if not all(ctl.values()):
            inconsistent.append('row 43: the row-42 reproduction control')
        cfm = r43['collapsed_form']
        print(f'#   the collapsed form: s3: {cfm["s3"]}; b2: {cfm["b2"]}')
        rr = r43['recipe_of_record']
        ok_recipe = (rr['MB_ROWS.json'] == recs[F['recipe']]['record_sha256'] and r43['row42_of_record']['sha256'] == recs[MBC_FILES[42]['rep']]['record_sha256'])
        spec = mbr['43']
        recipe_line = next((s[s.find('Row 43'):] for s in spec['continuation_spec'] if 'Row 43' in s), '')
        ok_recipe = ok_recipe and rr['text'] in recipe_line
        print(f'#   the recipe of record: {_mbc_label(F["recipe"], recs)} entry 43 (status of record: {spec["status"]}; sector {spec["sector"]}; '
              f'tuple {spec["tuple"]}): "{recipe_line}" -- the object\'s recipe_of_record.MB_ROWS.json and row42_of_record.sha256 == '
              f'the record sha256 of the vendored MB_ROWS.json and mb_row42.py, and its recipe text is in the entry: {ok_recipe}')
        if not ok_recipe:
            inconsistent.append('row 43: the recipe-of-record sha links')
        print(f'#   the record note {_mbc_label(F["note"], recs)}:')
        for l in note:
            print(f'#     {l}')
        print(f'#   WRITTEN, NOT EVALUATED: no straight-contour defining point at any eps; the pinch argument sums -eps and eps + delta')
    print(f'# this tier enters no digit into --check; the served gates are the eta-transport + node bank')
    if inconsistent:
        print(f'# --mb-corner-provenance: FAIL -- ' + '; '.join(inconsistent), flush=True)
        return 1
    print(f'# --mb-corner-provenance: PASS -- {len(recs)} objects by sha256; the printed figures are the objects\' own'
          + ('; every re-derivation within the bar' if rederive else ''), flush=True)
    return 0


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument('--dps', type=int, default=40)
    ap.add_argument('--point', default=None, help='rational y in (0,1), e.g. 17/40')
    ap.add_argument('--gate', action='store_true',
                    help='run both reference points over all 79 rows '
                         '(same as --gate-full)')
    ap.add_argument('--gate-full', action='store_true',
                    help='the full suite: all 79 rows compared against the '
                         'independent reference values at BOTH points '
                         'y=1/2 and y=3/5 (long — many core-minutes)')
    ap.add_argument('--check', action='store_true', help='rerun at dps+60 and diff')
    ap.add_argument('--mutate', action='store_true',
                    help='control run: perturb one boundary-bank node value '
                         'by a relative 1e-30 before the load-time checks; '
                         'the run must then refuse (nonzero exit) — proves '
                         'the certificates are live, not decorative')
    ap.add_argument('--nodes-source', default='bank', metavar='bank|fresh:DIR',
                    help="boundary-node value source. Only 'bank' (the "
                         "shipped certified node bank row35_nodes/) is "
                         "available in this download; 'fresh:DIR' needs a "
                         "two-precision node pair (the regenerated pair is "
                         "listed in CONTAINERS.md as row35_fresh_pair.tar.gz) "
                         "AND its consumer code path, which is not included, "
                         "and refuses.")
    ap.add_argument('--cached', action='store_true',
                    help='FAST-START: value path from the vendored Laurent '
                         'strings (ceiling ~57 d). The strings are STILL '
                         'compare-checked against the certified node bank '
                         'at load (mismatch refuses); the certified-fan '
                         'layer is skipped. Default (no flag) = certified '
                         'recompute value path.')
    ap.add_argument('--e4-extract', action='store_true',
                    help='extractor mode — NOT available in this download '
                         '(needs the transport-on-demand node-cache '
                         'tooling); refuses with a named message.')
    ap.add_argument('--jobs', type=int, default=min(48, os.cpu_count() or 1))
    ap.add_argument('--order', type=int, default=60, help='Taylor jet order')
    ap.add_argument('--master', default=None, metavar='I|NAME[,J|NAME,...]',
                    help='subset mode: master indices 0-78 and/or exact '
                         'wpairT4[...] names (bracket-aware parsing — names '
                         'contain commas; ";" also delimits; unknown '
                         'names/indices and unbalanced brackets refuse). '
                         'Transports ONLY the DE dependency closure of the '
                         'selection (closure sizes: min 1 / median 10 / '
                         'max 79) and evaluates/compares the selected '
                         'masters. Load-time bank checks stay full 79-row.')
    ap.add_argument('--boundary-recompute', nargs='?', const=130, type=int,
                    metavar='DPS', default=None,
                    help='the from-definition boundary chain, driven from '
                         'row35_chain/ beside this script (unpacked from '
                         'row35_chain.tar.gz, hosted with this bundle, CONTAINERS.md; every '
                         'member sha-verified first; absent -> exit 4 naming '
                         'it). Default form: GATE-D0 replay at eps=1/1013 on '
                         'the closure of --bc-rows oracle rows, gated against '
                         'the fixed-d0 oracle (recorded: 20 rows dps130 = '
                         '93.1 d worst, ~6 min single-core; 5 rows dps60 = '
                         '70.0 d, ~1 min); the run then continues into the '
                         'value path. Products go to row35_chain_work/.')
    ap.add_argument('--gate-bc-only', action='store_true',
                    help='with --boundary-recompute: the reduced boundary-'
                         'table gate (seeds vs the exact boundary tables) plus '
                         'the recorded GATE-D0 reports, not the end-to-end '
                         'fixed-d0 gate. Same container requirement.')
    ap.add_argument('--bc-rows', type=int, default=20, metavar='N',
                    help='with --boundary-recompute: number of fixed-d0 oracle '
                         'rows whose DE closure the chain replays (default 20 '
                         '= the recorded form; 5 = the recorded dps60 shakeout; '
                         '79 = a full node, ~4 h single-core at dps130).')
    ap.add_argument('--regenerate-node', type=int, default=None, metavar='Q',
                    help='with --boundary-recompute DPS: one from-definition '
                         'node solve at eps=1/Q with the production driver '
                         '(the recorded launch line), written to '
                         'row35_chain_work/fresh/dpsDPS/NODEQ_TARGETS.json '
                         '(a finished node is a checkpoint: rerun skips it) '
                         'and compared row by row to the shipped bank node '
                         '(bar dps-10 digits). The 48-solve regeneration of '
                         'the bank is this call over the 24 bank primes at '
                         'dps 130 and 160 (recorded: 54 min and ~64 min per '
                         'node single-core, 0.5 GB resident). Exits after '
                         'the comparison.')
    ap.add_argument('--containers', action='store_true',
                    help='print the status (absent / present + sha256 check / '
                         'unpacked + member check) of every '
                         'container listed in containers.json, then exit.')
    ap.add_argument('--line', default='L1', choices=('L1', 'L2'),
                    help='the kinematic line: L1 = (x, z) = (17/2, 5/3), the '
                         'default, the line of every value tier and of '
                         '--verify-exact against row35_L1/; L2 = '
                         '(17/2, 7/4), the second line, on which '
                         '--verify-exact and --canonical-blocks run (the '
                         'value tiers refuse by name, rc 2: the node bank, '
                         'base point, compare-cache strings and reference '
                         'values are L1\'s)')
    ap.add_argument('--verify-exact', action='store_true',
                    help='evaluate the shipped connection of the chosen line '
                         '(--line L1, the default: row35_data.json at d = '
                         '890/223 and the two withheld y = 29/211, 17/139 '
                         'against row35_L1/; --line L2: row35_L2/'
                         'connection_L2.json at d = 7/3 and y = 296/101, '
                         '306/103 against row35_L2/) in exact Fraction '
                         'arithmetic and compare entry by entry with the '
                         'withheld Kira reductions; 1240/1240 exact at both '
                         '= rc 0, any mismatched or unclosed entry named = '
                         'rc 1 (pins rc 3, missing file rc 4); measured wall '
                         + L1_VERIFY_WALL_S + ' s (L1) / ' + L2_VERIFY_WALL_S
                         + ' s (L2); --mutate makes it FAIL by name.')
    ap.add_argument('--canonical-blocks', action='store_true',
                    help='re-check the chosen line\'s canonical-basis census '
                         '(row35_<line>/blocks_epsform.json: the 29 diagonal '
                         'blocks with an eps-factorised dlog form and the 6 '
                         'stopped ones) exactly against the shipped '
                         'connection: T A T^-1 + T\' T^-1 = eps Atilde at '
                         '(eps, y) = (1/223, 29/211) and (5/6, 17/139), '
                         'Atilde eps-free, the dlog form from the shipped '
                         'residues, the constant gauge to the other line; '
                         'the census line 29 OK / 6 stopped (2 Moser-'
                         'irreducible + 4 eps^0) / 1 elliptic = rc 0, a '
                         'failing block named = rc 1 (usage rc 2, pins rc 3, '
                         'missing file rc 4); measured wall '
                         + CANON_WALL_S['L1'] + ' s (L1) / ' + CANON_WALL_S['L2']
                         + ' s (L2); --mutate makes it FAIL by name.')
    ap.add_argument('--verbose', action='store_true',
                    help='with --canonical-blocks: print the engine\'s stop '
                         'strings verbatim and the residue pairs of the five '
                         'nontrivial-G blocks')
    ap.add_argument('--mb-corner-provenance', action='store_true',
                    help='print the Mellin-Barnes corner rows 69 / 42 / 43 of the '
                         'boundary by object: the written representations and '
                         'their certificates read from the pinned files under '
                         'vendor_row35_mb_corner/ (pins first, rc 3 / rc 4 by '
                         'name); provenance only -- no digit enters --check or '
                         'any value tier, and the tier combines with no other '
                         'flag (rc 2); measured wall ' + MBC_WALL_S['default']
                         + ' s (every row), ' + MBC_WALL_S['rederive'] + ' s with '
                         '--rederive')
    ap.add_argument('--row', default='all', choices=('69', '42', '43', 'all'),
                    help='with --mb-corner-provenance: one corner row or all')
    ap.add_argument('--rederive', action='store_true',
                    help='with --mb-corner-provenance: re-derive the three '
                         'seconds-class certificates (row 69 s3 -> 2F1 by the '
                         'vendored producer\'s own recipe; row 42 s3 -> 2F1 and '
                         'b2 -> Meijer G with the wrong-phase control) at the '
                         'objects\' working precision and compare each with the '
                         'record figure within ' + str(MBC_REDERIVE_BAR_D) + ' d, '
                         'PASS/FAIL by name (rc 1 on FAIL); --dps D moves the '
                         'precision (compared only at the record\'s)')
    ap.add_argument('--check-expression', action='store_true',
                    help='recompute the structural claims of qqww-t4-'
                         'expression.md live (sector-487 zero remainder, '
                         'the 15-letter alphabet, r+-, the exact j and its '
                         'X0(2) parameter t); exact arithmetic, under a '
                         'minute; combine with --mutate to prove the check '
                         'fails on a perturbed basis.')
    ap.add_argument('--gate-im', action='store_true',
                    help='the imaginary parts: transport the node bank\'s '
                         'imaginary parts with the same solve (24 legs per '
                         'point, all 79 rows) and compare the 36 complex rows\' '
                         'Laurent coefficients (every reference order below '
                         'eps^2) with the imaginary parts of the independent '
                         'reference values in ' + IM_REF_FILE + ' at both '
                         'reference points; bar ' + str(IM_BAR_D) + ' d per complex '
                         'row, |Im|/gscale < ' + IM_ZERO_FLOOR + ' on zero-class '
                         'orders and on the 43 real rows; rc 0 PASS / 1 FAIL '
                         '(rows named) / 2 refused / 3 pin / 4 missing; first '
                         'line only; measured ' + IM_LEG_WALL_S['y12'][0] + '-'
                         + IM_LEG_WALL_S['y12'][1] + ' s per leg to y=1/2 and '
                         + IM_LEG_WALL_S['y35'][0] + '-' + IM_LEG_WALL_S['y35'][1]
                         + ' s to y=3/5 (one core per leg), --jobs legs at a time')
    ap.add_argument('--im-point', default='both', choices=('y12', 'y35', 'both'),
                    help='with --gate-im: one reference point (y12 = 1/2, y35 = '
                         '3/5) or both (the default)')
    ap.add_argument('--im-control', action='store_true',
                    help='with --gate-im: negate row ' + str(IM_CONTROL[0]) + '\'s imaginary '
                         'seed at the q = ' + str(IM_CONTROL[1]) + ' node before the '
                         'transport; the tier must then FAIL naming that row '
                         '(the shipped control of the tier)')
    a = ap.parse_args()
    try:
        sys.stdout.reconfigure(line_buffering=True)
    except Exception:
        pass
    # ---- the Mellin-Barnes corner rows: --mb-corner-provenance combines with no other flag -----
    if (a.row != 'all' or a.rederive) and not a.mb_corner_provenance:
        print('--row and --rederive belong to --mb-corner-provenance; pass it.', file=sys.stderr)
        return 2
    if a.mb_corner_provenance:
        served = [n for n, on in (('--check', a.check), ('--verify-exact', a.verify_exact),
                                  ('--canonical-blocks', a.canonical_blocks),
                                  ('--check-expression', a.check_expression),
                                  ('--boundary-recompute', a.boundary_recompute is not None),
                                  ('--gate', a.gate), ('--gate-full', a.gate_full),
                                  ('--point', a.point is not None), ('--master', a.master is not None),
                                  ('--mutate', a.mutate), ('--cached', a.cached),
                                  ('--containers', a.containers), ('--verbose', a.verbose),
                                  ('--e4-extract', a.e4_extract),
                                  ('--nodes-source', a.nodes_source != 'bank'),
                                  ('--gate-bc-only', a.gate_bc_only),
                                  ('--regenerate-node', a.regenerate_node is not None),
                                  ('--line L2', a.line != 'L1'), ('--gate-im', a.gate_im),
                                  ('--im-point', a.im_point != 'both'), ('--im-control', a.im_control)) if on]
        if served:
            print('--mb-corner-provenance is a provenance tier of its own and combines with '
                  'no served flag: ' + ', '.join(served) + ' (the value tiers, the exact tiers and '
                  'their controls run one at a time); no digit of the corner rows enters --check.',
                  file=sys.stderr)
            return 2
        dps_explicit = any(x == '--dps' or x.startswith('--dps=') for x in sys.argv[1:])
        rows = tuple(MBC_ROWS) if a.row == 'all' else (int(a.row),)
        dps_rd = a.dps if dps_explicit else None
        if a.rederive and dps_rd is None:
            dps_rd = json.load(open(os.path.join(HERE, MBC_DIR, MBC_FILES[69]['certs'])))['mp_dps']
        return mb_corner_provenance(rows, rederive=a.rederive, dps_rd=dps_rd, dps_explicit=dps_explicit)
    # ---- the containers of containers.json / modes outside this download -----
    if a.containers:
        return containers_cmd()
    if a.gate_bc_only and a.boundary_recompute is None:
        raise SystemExit('--gate-bc-only only modifies --boundary-recompute; '
                         'pass both.')
    if a.regenerate_node is not None and a.boundary_recompute is None:
        raise SystemExit('--regenerate-node Q needs --boundary-recompute DPS '
                         '(the dps of the node solve; the bank pair is 130 '
                         'and 160); pass both.')
    if a.nodes_source != 'bank':
        raise SystemExit("--nodes-source: only 'bank' (the shipped certified "
                         "node bank) is available in this download; "
                         "'fresh:DIR' needs a two-precision node pair (the "
                         "regenerated pair is listed in CONTAINERS.md as "
                         "row35_fresh_pair.tar.gz) and its consumer code "
                         "path, which is not included.")
    if a.e4_extract:
        raise SystemExit('--e4-extract needs the transport-on-demand '
                         'node-cache tooling, which is not part of this '
                         'download.')
    # ---- the imaginary parts: --gate-im is a tier of its own (the first line; the bank's Im seeds) ----
    if (a.im_control or a.im_point != 'both') and not a.gate_im:
        print('--im-point and --im-control belong to --gate-im; pass it.', file=sys.stderr)
        return 2
    if a.gate_im:
        clash = [n for n, on in (('--check', a.check), ('--verify-exact', a.verify_exact),
                                 ('--canonical-blocks', a.canonical_blocks),
                                 ('--check-expression', a.check_expression),
                                 ('--boundary-recompute', a.boundary_recompute is not None),
                                 ('--gate', a.gate), ('--gate-full', a.gate_full),
                                 ('--point', a.point is not None), ('--master', a.master is not None),
                                 ('--mutate', a.mutate), ('--cached', a.cached),
                                 ('--verbose', a.verbose)) if on]
        if clash:
            print('--gate-im is a tier of its own (the imaginary parts of the 36 complex rows at the '
                  'reference points; all 79 rows transported from the bank\'s imaginary parts) and '
                  'combines with --dps, --jobs, --order, --im-point and --im-control only, not with: '
                  + ', '.join(clash) + ' (its control is --im-control; --mutate is the bank control of '
                  'the value tiers).', file=sys.stderr)
            return 2
    # ---- the canonical-basis census: --canonical-blocks on either line -----
    if a.verbose and not a.canonical_blocks:
        print('--verbose belongs to --canonical-blocks (the engine\'s stop '
              'strings verbatim and the residue pairs of the nontrivial-G '
              'blocks); pass both.', file=sys.stderr)
        return 2
    if a.canonical_blocks:
        if a.verify_exact or a.check_expression:
            print('--canonical-blocks, --verify-exact and --check-expression '
                  'are separate tiers; run them one at a time.',
                  file=sys.stderr)
            return 2
        return canonical_blocks(a.line, mutate=a.mutate, verbose=a.verbose)
    # ---- the second line: only the exact tiers run on L2 -------------------
    if a.line == 'L2' and not a.verify_exact:
        print('--line L2: the value tiers (default, --point, --gate/--gate-'
              'full, --gate-im, --master, --check, --cached) and --check-expression run '
              'on the first line L1 = (17/2, 5/3) only -- the certified node '
              'bank row35_nodes/, the base point y = 1/3, the compare-cache '
              'strings and the reference values are that line\'s, and the '
              'record holds no boundary data on L2 = (17/2, 7/4). The tiers '
              'shipped for L2 are --line L2 --verify-exact (the exact check of '
              'the L2 connection against its two withheld Kira reductions) '
              'and --line L2 --canonical-blocks (the exact check of the '
              'line\'s canonical-basis census, its 29 factorised diagonal '
              'blocks).',
              file=sys.stderr)
        return 2
    if a.verify_exact:
        if a.check_expression:
            print('--verify-exact and --check-expression are separate tiers; '
                  'run them one at a time.', file=sys.stderr)
            return 2
        # the exact tier of the chosen line: L2 against row35_L2/, L1 (the
        # default line) against row35_L1/
        if a.line == 'L2':
            return verify_exact_L2(mutate=a.mutate)
        return verify_exact_L1(mutate=a.mutate)
    if a.check_expression:
        return check_expression(mutate=a.mutate)
    # ---- the Mellin-Barnes corner-row objects are pinned on every value run too (one download) ----
    rc_mbc = _mbc_pins('[value path]', quiet=True)
    if rc_mbc:
        return rc_mbc
    # ---- the imaginary-part reference file is pinned on every value run too (one download) ----
    rc_im = _im_pins('[value path]', quiet=True)
    if rc_im:
        return rc_im
    ref_im = _im_reference() if a.gate_im else None
    if a.boundary_recompute is not None:
        # the chain first (refuses by name without row35_chain/); the
        # --regenerate-node form exits after its bank comparison, the gate
        # forms continue into the value path below (L1 only: the L2 gate
        # above has already refused a --line L2 value run)
        rc_bc = boundary_recompute(a)
        if a.regenerate_node is not None:
            return rc_bc
    # ---- default = quick run: y=1/2, small master subset ------------------
    quick = not (a.gate or a.gate_full or a.point or a.master or a.gate_im)
    if quick:
        a.master = '0,3,60'
    mode = ('quick default (y=1/2, masters 0,3,60)' if quick else
            f'imaginary parts (--gate-im, {a.im_point}: the 36 complex rows, all 79 rows transported)'
            if a.gate_im else
            f'point y={a.point}' if a.point else
            'full suite (both points, all 79 rows)' if (a.gate or a.gate_full)
            else f'subset ({a.master})')
    print(f'# eval_row35 — nonplanar T4 qqbar->WW evaluator | mode: {mode} | '
          f'dps {a.dps} | jobs {a.jobs}' + (' | MUTATE CONTROL' if a.mutate else ''),
          flush=True)
    global MUTATE
    MUTATE = bool(a.mutate)
    fresh_dir = None
    mp.mp.dps = a.dps                                     # set AFTER argparse (the import-dps pitfall)
    global DATA
    raw = json.load(open(os.path.join(HERE, 'row35_data.json')))

    DATA = {'ent': parse_entries(raw['A_entries']),
            'bnd': raw['boundary_y13_laurent']['coeffs'],
            'oracles': {'y12': raw['gate_oracles']['y12'], 'y35': raw['gate_oracles']['y35']},
            'qset': raw['qset'], 'masters': raw['masters'],
            'poles': [tuple(p) for p in raw['poles_step_control']['list']]}
    rf = os.path.join(HERE, 'row35_radical_feed.json')
    if os.path.exists(rf):
        DATA['radical'] = json.load(open(rf))['blocks']
    cman = _containers_manifest(required=False)
    for sec in HEAVY_SECS:      # b421/b453: lazy per-leg load (see _heavy_leg)
        hf = os.path.join(HERE, f'row35_radical_feed_b{sec}.json')
        if os.path.exists(hf):
            if cman is None:
                _refuse(RC_MISSING, f'[containers] {os.path.basename(hf)} is beside '
                        f'this script but {CONTAINERS_JSON} is missing, so it cannot '
                        f'be verified — not used; restore {CONTAINERS_JSON} (part of '
                        f'the download).')
            _container_verify(os.path.basename(hf), cman)   # size, then sha256; rc 3
            ce = cman['containers'][os.path.basename(hf)]
            print(f'# CONTAINER {os.path.basename(hf)}: beside this script, size '
                  f'{ce["bytes"]:,} bytes and sha256 {ce["sha256"][:16]}... verified — '
                  f'masters {"-".join(str(m) for m in (HEAVY_TARGETS[sec][0], HEAVY_TARGETS[sec][-1]))} '
                  f'fold from its certified closed forms', flush=True)
            DATA.setdefault('radical_heavy', {})[sec] = hf

    if a.master:
        # ---- MASTER-SUBSET MODE (2026-07-06c, measured; see CHANGELOG) ----
        # 2026-07-07 close fix: bracket-aware token split — by-name selection
        # was dead code under split(',') because every master name contains
        # commas (verifier sec-6 flag (a)).
        targets = []
        for tok in _split_master_tokens(a.master):
            if tok.lstrip('+').isdigit():
                i = int(tok)
                if not 0 <= i < 79:
                    raise SystemExit(f'--master: index {i} outside 0..78')
            else:
                if tok not in DATA['masters']:
                    raise SystemExit(f'--master: unknown master name {tok!r}')
                i = DATA['masters'].index(tok)
            targets.append(i)
        targets = sorted(set(targets))
        closure = _dep_closure(targets)
        selset = set(closure)
        DATA['targets'] = targets
        DATA['sel'] = closure
        DATA['sel_pos'] = {m: p for p, m in enumerate(closure)}
        DATA['ent_sel'] = [(DATA['sel_pos'][i], DATA['sel_pos'][j], N, Q)
                           for i, j, N, Q in DATA['ent']
                           if i in selset and j in selset]
        rad_t = {27, 28, 29, 33, 34, 35, 45, 46, 47, 48, 49, 50, 60, 61, 62}
        print(f'# MASTER-SUBSET MODE: {len(targets)} selected '
              f'{targets}; DE dependency closure {len(closure)}/79 rows, '
              f'{len(DATA["ent_sel"])}/{len(DATA["ent"])} connection '
              f'entries; radical folds: '
              f'{sorted(set(targets) & rad_t) or "none needed"}; load-time '
              f'bank/bndval gates stay FULL 79-row (raising). '
              + ('NOTE: selection pulls the FULL 79-row coupled block — no '
                 'march reduction at this pick (measured structure: only '
                 'masters 75-78 do this).' if len(closure) == 79 else
                 f'March/extract/fan restricted to the {len(closure)}-row '
                 f'closed block (exact restriction — see PHASE WALLS for '
                 f'the measured speedup).'))

    # ---- VALUE PATH: certified recompute node bank ------------------------
    # All three checks RAISE (nonzero exit) — bank integrity, two-precision
    # node certificate, compare-cache mismatch — in BOTH modes ('--cached'
    # keeps the cache compare-checked).
    tg0 = time.time()
    # --check reruns at dps+60: check the node source for the DEEPEST pass
    dps_gate = a.dps + (60 if a.check else 0)
    bi = _bank_load_and_gate(dps_gate)
    DATA['bank'] = bi['bank']
    DATA['bank130'] = bi['bank130']
    DATA['nodes_source'] = 'bank'
    DATA['nodes_source_id'] = 'bank'
    DATA['cached'] = bool(a.cached)
    DATA['q2'] = _grid2_primes(DATA['qset'])
    r0s, r0f = _certified_R0()
    DATA['r0'] = r0s
    bd = _bndval_refresh()   # radical-fold B{i}k{k} constants from the bank
                             # (raising gates inside; runs in BOTH modes —
                             # --cached also folds the radical blocks)
    print(f'# VALUE PATH: certified recompute node bank (row35_nodes/, 48 '
          f'fresh boundary solves at two precisions): manifest 48/48 OK; '
          f'two-precision node certificate min '
          f'{bi["cert_min_digits"]:.1f} d (master {bi["cert_at"][0]}, '
          f'q={bi["cert_at"][1]}) >= need dps+{NODE_CERT_GUARD} = '
          f'{dps_gate + NODE_CERT_GUARD} d [PASS]')
    print(f'# COMPARE-CACHE: vendored boundary_y13_laurent strings vs bank '
          f'(Re): min margin +{bi["cache_min_margin_digits"]:.1f} d over '
          f'threshold 19*log10(q)-{CACHE_GATE_MARGIN} (worst at master '
          f'{bi["cache_at"][0]}, q={bi["cache_at"][1]}) [PASS] — strings '
          f'are a Re-only compare-cache; the recompute path is the '
          f'definition (checks wall {time.time() - tg0:.1f}s)')
    print(f'# E4 FAN CONFIG: R0 >= {r0f:.4g} (certified den-poly eps-'
          f'analyticity lower bound; true nearest den singularity eps=1/4; '
          f'y-dependent flow zeros gated a posteriori by verify/two-grid/'
          f'node-cert raises); grid2 = 36 mild-shift primes '
          f'{DATA["q2"][0]}..{DATA["q2"][-1]}')
    print(f'# BND_VAL REFRESH: radical-fold B constants from the bank '
          f'(claim {bd["claim"]} d = measured 24-node window capacity, '
          f'certify eps^{bd["kc"][0]}..eps^{bd["kc"][1]} two-grid '
          f'{bd["certify_min"]:.1f} d, verify {bd["verify_min"]:.1f} d, '
          f'cond {bd["cond"]} wp {bd["wp"]}); vs demoted AMFlow strings: '
          f'min {bd["compare_min"]:.1f} d rel (B{bd["compare_at"][0]}'
          f'k{bd["compare_at"][1]}) / {bd["compare_min_g"]:.1f} d gscale '
          f'[PASS >= {BND_COMPARE_MIN}/{BND_COMPARE_MIN_G}]; xcheck '
          f'{bd["xcheck_min"]:.1f} d; fit130v160 {bd["tp_min"]:.1f} d; '
          f'{bd["n_zero"]} true-zero orders re-verified [PASS]')
    if a.cached:
        print('# --cached: FAST-START value path from the vendored strings '
              '(ceiling ~57 d, legacy square fan; E4 certified-fan layer '
              'SKIPPED). The certified-recompute definition was NOT '
              'exercised for the values of this run.')
    if a.gate_im:
        return gate_im(a, ref_im)
    t00 = time.time()

    def _print_phases(r, label):
        pw = r.get('phase_walls')
        if not pw:
            return
        print(f'# PHASE WALLS [{label}]: march {pw["march_legs_s"]}s '
              f'({pw["n_legs"]} legs x {pw["n_rows"]}-row system), '
              f'extract {pw["extract_s"]}s, e4-fan {pw["fan_s"]}s, '
              f'radical-fold {pw["radical_fold_s"]}s, '
              f'total {r["wall_s"]:.1f}s (measured this run, this box load)')

    def one_pass(dps):
        if a.point and not quick:
            y = F(a.point)
            assert 0 < y < 1, 'documented domain: y in (0,1)'
            r = run_point(y, dps, a.jobs, a.order)
            print(f'# row35 point y={a.point} (x,z)=(17/2,5/3) dps={dps} '
                  f'wall={r["wall_s"]:.1f}s steps={r["steps_total"]} '
                  f'self-consistency min {min(r["self_digits"]):.1f}d '
                  f'max arb ball rad {r["max_ball_rad"]:.1e}')
            _print_phases(r, f'y={a.point}')
            _print_fan(r.get('fan'), f'y={a.point}')
            return {'y': a.point, 'r': r}
        res = {}
        subset = bool(DATA.get('sel'))
        heavies = bool(DATA.get('radical_heavy'))
        points = ((('y12', F(1, 2)),) if quick else
                  (('y12', F(1, 2)), ('y35', F(3, 5))))
        for tag, y in points:
            r = gate_point(tag, y, dps, a.jobs, a.order)
            res[tag] = r
            for mi, dgt in r['per_master']:
                print(f'# master {DATA["masters"][mi]}: {dgt:.1f} digits vs '
                      f'independent reference (y={y}, orders -2..1)')
            print(f'# CHECK {tag} y={y}: min {r["gate_min_digits"]:.2f}d over '
                  f'{r["n_gated"]} masters x orders -2..1 vs the independent '
                  f'reference values (never used in any fit; self-consistency '
                  f'min {r["self_min_digits"]:.1f}d, worst master '
                  f'{r["gate_worst_master"]}, '
                  f'{len(r.get("folded", []))} masters closed-form-folded'
                  + ('' if heavies else
                     ' — sectors 421/453 containers not beside this script '
                     '(CONTAINERS.md), their masters ride the transport')
                  + f', wall {r["wall_s"]:.1f}s)')
            _print_phases(r, tag)
            _print_fan(r.get('fan'), tag)
        if not quick:
            print(f'# recorded full-run reference: y12 39.16d / y35 39.12d '
                  f'(transport-only baseline, 2026-07-01)'
                  + (' [subset run: NOT comparable to the all-79 minimum]'
                     if subset else ''))
        return res

    out1 = one_pass(a.dps)
    if quick:
        floor = min(d for _, d in out1['y12']['per_master'])
        if floor < 37.0:
            print(f'# FAIL: worst master agreement {floor:.1f} d < 37 d bar')
            raise SystemExit(4)
    if a.check:
        print(f'# --check: rerunning at dps={a.dps + 60}')
        out2 = one_pass(a.dps + 60)
        with mp.workdps(a.dps + 80):
            worst = 1e9
            pairs = ([(out1['r'], out2['r'])] if a.point else
                     [(out1[t], out2[t]) for t in out1])
            # 2026-09-05: the pairs are the tags THIS pass gated -- the quick
            # default gates y = 1/2 only (out1 holds 'y12' alone), the full
            # suite and --master gate both reference points; the literal
            # ('y12', 'y35') that stood here raised KeyError 'y35' after the
            # quick default's dps+60 rerun.  Every other tier: pairs unchanged.
            for r1, r2 in pairs:
                for i in range(len(r1['coeffs'])):
                    for n in range(-2, 2):        # quoted window only (descope)
                        t = n - LO
                        v1, v2 = mp.mpf(r1['coeffs'][i][t]), mp.mpf(r2['coeffs'][i][t])
                        if abs(v2) < mp.mpf('1e-25'):
                            continue
                        dv = abs(v1 - v2) / abs(v2)
                        worst = min(worst, float(-mp.log10(max(dv, mp.mpf('1e-999')))))
            if worst >= 999.0:
                # 2026-09-11: the two passes print the same 80-digit strings at any dps (one node bank,
                # one node design, deterministic truncation), so a digit count here is vacuous; say so
                print(f'# --check: identical at the capped {min(a.dps, FAN_CLAIM_CAP)}-digit claim -- the '
                      f'dps {a.dps} and dps {a.dps + 60} passes print the same coefficient strings over the '
                      f'quoted window (the printed digits of this path do not depend on dps); the '
                      f'two-precision certificate of this path is the node bank\'s '
                      f'{bi["cert_min_digits"]:.1f} d (its dps130 and dps160 sweeps, compared at load)')
            else:
                print(f'# --check agreement: {worst:.1f} digits (floor: printed-coefficient '
                      f'precision / arithmetic; truncation errors are deterministic and cancel)')
    if a.point and not quick:
        r = out1['r']
        rows = DATA.get('targets') or list(range(79))
        pos = DATA.get('sel_pos') or {i: i for i in range(79)}
        print('# master  order  coefficient (self-consistency digits per master; from each row\'s own '
              'leading order -- eps^-3 on 11 of the 79 rows -- through eps^1)')
        for i in rows:
            lead = min(o for o, _ in DATA['bnd'][i])   # the row's leading order at the base point; the
            for n in range(min(lead, -2), 2):           # quoted window -2..1 is always printed
                print(f'{DATA["masters"][i]}  eps^{n}  {r["coeffs"][pos[i]][n - LO]}  '
                      f'[self {r["self_digits"][pos[i]]:.1f}d]')
    print(f'# total wall {time.time() - t00:.1f}s')

if __name__ == '__main__':
    sys.exit(main())
