#!/usr/bin/env python3
"""LBL3X (crossed light-by-light box, sector 938) -- final-form evaluator.

FUNCTION CLASS (the deliverable). The family's function space splits, exactly,
into (i) a pure-polylog part over the 8-letter alphabet
{s, t, s+t, s+t+4, s+t+16, s-4, t-4, 2s+t} and (ii) the K3 subsector (sec-15
equal-mass three-loop banana m13 at virtuality u = -s-t) entering m18 = the
top-sector master I(1,1,1,1,1,1) through ONE exact rational kernel.  This
script ships, as honest arbitrary-precision objects:

 A. m13(u, eps^-3..0)   as a Picard-Fuchs/MUM period series: exact rational
    9-master u-DE (vendored), CLOSED-FORM u=0 boundary tower in {1,pi^2,zeta3}
    + 3 named resonance constants + 1 named subsector constant, Frobenius
    series at the MUM point u=0, local-Taylor analytic continuation anywhere.
    Precision is set ONLY by dps (more series terms / smaller steps); there is
    no numeric node cache anywhere in the chain.
    The K3 direction inside m13 eps^0 is EXACTLY the Domb (OEIS A002895)
    period: the script verifies, in exact rational arithmetic at runtime, the
    dimension-shift identity
      144*u*h(u) = (u^4+6u^3-72u^2-256u) w + (2u^4+30u^3-672u^2+640u) theta(w)
                   + (u^4+20u^3-672u^2+1280u+4096) theta^2(w),
    w = varpi0(u/64) = sum Domb_n (u/64)^n,  theta = u d/du,
    h = the m13-eps0 component of the unique MUM free direction that feeds
    m13.  So  m13^(0)(u) = (closed {1,pi^2,zeta3} series) + C0 * h(u)  with
    ONE named K3 constant C0.  (Domb generator vendored from
    files/banana/banana-evaluate.py.)
 B. K3-tail of m18 (the task-named object): the 2-variable one-fold iterated
    integral over the exact rational kernel
      A_s[m18->m13]|_{d=4} = 9743/(660 s) - 8/(15 u) + 21/(u-4)
                             + 35/(2 (u-4)^2) - 87/(22 (u-16)),
      Tail(s,t) = INT_{Gamma(2 -> u)} K(u',t) m13^(0)(u') du',
      K(u',t)   = -A_s[m18->m13](s'=-u'-t, t),
    along the Feynman contour Gamma = real u'-axis with +i box detours around
    u'={4,16} and the genuinely 2-variable letter u' = -t (this pole IS the
    s' = 0 letter; basepoint u'=2, same convention as the archived K3-tail
    tooling).  Two independent live engines (Taylor-accumulator co-transport
    and composite Gauss-Legendre) cross-gate it at runtime.
 C. Exact base-point values and identities, all computed/verified live: the m18^(0)(0,0)
    closed form; the d=4 kernel partial fractions == the archived full rational
    expression (exact Fraction check); m18 eps^-1 = 2 zeta3 against ALL FIVE
    withheld AMFlow points of the m^2-DE gate (33.95-38.51 d provenance); the
    Euler identity (s d_s + t d_t) m18^(0) = -2 Delta checked on the archived
    Rm ray oracle.
 D. The closed 13-master polylog lower block: live eps-graded DE transport on
    the shipped exact-rational on-curve kernel, gated against an independent
    AMFlow oracle at the withheld point (-8,-4).  (Final-form caveat stated in
    part 7: this block's SEED towers are certified stored numerics at ~65 d;
    the archived pure-zeta closed forms of the S/T-banana + tadpole constants
    exist -- artifact paths below -- but the 140k-word GPL evaluator is not
    vendored here.)
 E. KERNEL PATH (2-var kernel regen, folded 2026-07-05): the kernel-backed
    41x41 A^s/A^t connection of the preferred41 basis, per-entry
    evidence-class tagged, d on the 34-node lattice {101..132, 1009/3,
    -211/5} (source record: <archive>/solve_row21/kernel2var/RESULT.md at
    REGISTRY v4 / addendum A6, 2026-07-05; ported same day from the
    tools/rowscripts/eval_row21.py kernel fold).  Coverage at v4, no
    rounding up (2045 nonzero entries; tallies recomputed at load from
    the vendored map and asserted):
      - EXACT 1989 (1678@6-prime + 261@10-prime + 46@extra-prime +
        4 direct): exact Fraction value at ARBITRARY rational (s,t) per
        lattice node.
        Rows fully 2-var closed: A^s 35/41, A^t 24/41.
      - certified-2prime 16: VERIFICATION-GRADE residues mod the 2 fit
        primes ONLY; never float-lifted, no exact rationals exist.
      - exact-extraprime 46 (succession of 2026-09-07): the entries whose
        two-prime columns were closed exactly on the 676-point record
        grid (71 columns = 68 direct + 3 fold16-exact; Chinese
        remaindering over 5 to 9 primes, 2 fresh primes on every fit
        point, 52 withheld points exact, both fit primes' residues at
        every node); evaluated by the same exact path.  The 26 two-prime
        columns of 13 targets whose record pair (c41[18], c41[39]) is
        not separable from 39-master data stay two-prime.
      - UNCLOSED 40 (26 post-fix-data-limited + 14 genuine): not
        evaluable, class reported honestly.
      - per-line-only: NONE -- class ELIMINATED (record A1); _k_light()
        asserts LOUDLY at load if any vendored record still carries the
        tag.
    Evidence classes are ENFORCED IN CODE: evaluating an entry outside
    its class raises KernelClassError.
    GATE-2 FRAME CONSTRAINT (record A3, GATE2_LEAK_PROFILE.json): the raw
    (A^s, A^t) pair is NOT a flat 2D connection off-curve -- naive (s,t)
    integrability is a measured-FAIL that is STRUCTURAL (documented
    bug#21-v5 off-shell frame leak of the raw source_v3 pair; identical
    497-entry failing set at all test points, pure entrywise curl).  The
    frame-clean object is the combination V = A^s - (t^2/s^2) A^t
    transported along the 1/s+1/t=const foliation -- exactly what the
    49 d transport gate of this page uses.  kernel_V_exact() computes
    it; do NOT consume the raw pair as a flat connection off-curve.
    TWO OBJECTS (the binding 21:5x two-objects decision): LBL3X on this page is
    (1) the GRAPH -- parts A-D, the row-21 census item: the DEFAULT
    run, --point, and the gate suite, which NEVER touch witness/kernel
    data -- and (2) the THEOREM (LBL3X-thm) -- the kernel function-form
    refutation, whose proof certificate is this part E behind the
    explicit --theorem-check subcommand (certificate model: statement
    in prose, witness = exact rational data, checker = this code).
    PAGE-BUNDLE DATA SPLIT (stated plainly): the connection map +
    denominator data + manifest are vendored in THIS directory
    (lbl3x-kernel-map.json, lbl3x-kernel-denoms.json,
    lbl3x-kernel-manifest.json; numeric payloads identical to the
    eval_row21 bundle with provenance strings neutralized for release,
    sha256 == the manifest pins for the heavy banks) -- structure,
    evidence classes,
    coverage tallies, the exact denominator machinery and the info
    report are fully live from this directory alone.  The theorem
    WITNESS is the ONE-NODE exact slice (~12.5 MB, sha-pinned; design:
    <archive>/lbl3x_kernel_compact/DESIGN.md):
    lbl3x-kernel-witness/ = slice_n1_exact.pkl.gz (4255 exact rational
    (s,t) numerator cols at d-node 101) + slice_n1_fits.pkl.gz (26
    two-prime residue cols) + witness_manifest.json (sha256 pins +
    nodes_kept), sliced by the kernel-compaction step; sha256 is
    verified against the manifest on every load, and
    kernel_entry_val_exact / kernel_entry_val_modp / kernel_V_exact
    evaluate at the vendored node(s) only (KernelDataError names any
    non-vendored node).  If the witness is ABSENT the checker fails
    LOUD (KernelWitnessError, nonzero exit) -- no kernel digit is ever
    claimed without sha-verified data (an honest gap beats a disguised
    cache, same rule as the Delta gap below).  The FULL 34-node
    lattice (kernel_exact.pkl.gz 324 MB + kernel_fits.pkl.gz 25 MB)
    stays a campaign-archive pointer only (canonical copies:
    tools/rowscripts/row21_kernel_data/); dropping both banks into
    lbl3x-kernel-banks/ (sha256-VERIFIED against the vendored manifest
    before first use) remains an optional full-lattice override.
    HONEST LIMITS (record A6.4): d-dependence on the 34-node lattice only
    (closed-form-in-d not reconstructed); the 40 UNCLOSED entries need
    denser crossed columns; this fold does NOT close the Delta gap
    below.

WHAT IS *NOT* SHIPPED (the Delta gap, stated precisely): the remaining
polylog content of m18 eps^0 -- equivalently Delta = m34+m35+3 zeta3 in
(s d_s + t d_t) m18^(0) = -2 Delta -- is a 25-row variation-of-parameters
integral of the top-block system sourced by m13 through A_s[17][38] = 2/s.
Its exact eps-graded kernels lived in symbolic_de.json, which was purged from
disk in the 2026-07-02 reorg (grep-verified); only the d=4 row-17 kernel above
is archived in closed form.  Hence full m18^(0)(s,t) is NOT evaluable by this
script; the archived 49.8 d value gate (taylor41) and the 5-point m^2-DE gate
remain the record for the assembled number.  An honest gap beats a disguised
cache.

Self-contained: python3 + mpmath + the data files in this directory
(lbl3x-k3seed.json, lbl3x-k3words.json, lbl3x-block13-kernel.json.gz,
lbl3x-block13-boundary.json;
kernel path part E: lbl3x-kernel-map.json, lbl3x-kernel-denoms.json,
lbl3x-kernel-manifest.json + the OPTIONAL sha-pinned heavy banks in
lbl3x-kernel-banks/, not shipped -- see part E).
Oracle values quoted below are archived artifact strings (paths + sha256[:16]
in comments); every agreement digit printed is recomputed here at runtime as
-log10 |f-oracle|/|oracle|.  Run `python3 lbl3x-evaluate.py` for the
gate suite with the deep legs trimmed (parts 1-8; part 3 at the three
u points, part 4 at the single point (-8,-4); measured cpu 97.2 s, about two minutes on a laptop),
`--full` for the complete suite (adds the u=17 and u=50 m13 legs,
Tail(-14,-3), the Gauss-Legendre engine-B cross-check and the
contour-deformation leg; measured cpu 351.5 s (about six minutes on a laptop); cpu times
measured 2026-09-03, one process on a busy 96-core host -- wall time tracks
the cpu figure on an unloaded machine),
`--point s t [dps]` for f(s,t,dps) at any other point of the domain,
`--m18-eps0 [--point -7|-8] [--gates ...]` for the FULL m18 eps^0 value
served LIVE at the certified on-curve points via the vendored
row21_chain/ package (sha-pinned inputs; substrate: mpmath +
python-flint + gmpy2, used by this arm only; the standing s=-7
prediction record is lbl3x-prediction.json in this directory; at
`--point -7` that prediction is TESTED (2026-09-06) against the goal-60
AMFlow record of the point, row21_chain/data/GATE_M7_GOAL60.json,
sha256-pinned here (mismatch rc 3, absent rc 4, by name; the goal-40
twin inside): the run prints 'tested: N held-out digits' and the pair
line, both recomputed from the record strings against its own value --
72 and 49 measured, the record's 72.644 / 49.787 beside),
`--k3-words` for the K3-sector exact words quoted at runtime from the
sha-verified vendored wordlist lbl3x-k3words.json (sha256 57e9ac16...,
the scrubbed copy of the campaign's 2026-07-08 final-closure record
WORDLIST_FINAL5.json) plus the x_17 LEG-B artifact vendored-with-pin-
on-read as lbl3x-legb-x17.json (sha256 aba4a9b7... verified on EVERY
read, NAMED X17IntegrityError otherwise;
STATUS: rat-sector words complete, twist sector measured zero; one
symbolic word tower still unfinished as words -- the value-serving
evaluator is closed),
`--derive-constants [dps]` to rerun the leg4 chain as an independent
cross-check oracle (the leg4 chain vendored under row21_leg4/; the 4 MUM/M3_eps0 constants are served
from EXACT closed forms since 2026-07-08, the shipped strings are a
demoted gate-cache -- see the closed-form block below),
`--theorem-check` for the LBL3X-thm refutation-certificate checker
(part E; `--theorem-check --help` prints the theorem statement +
certificate model + witness contract), or `--kernel-info` for the
kernel-path coverage report (kept as a compat alias of
`--theorem-check --info`; per-class entry counts recomputed live from
the vendored map, no evaluation).
`--sector63-map` for the 41 -> 39 CONVENTION MAP of the two spurious
sector-63 masters of the preferred41 basis (M41[39] = -M39[18];
M41[40] = M39[20] - M39[19] + 2 M39[18] - (t/2) M39[17] + M39[16]; exact,
d- and m^2-independent, one entry linear in t), re-checked in exact
Fraction arithmetic from the 14 sha256-pinned fixtures under
row21_offcurve/fixtures/ (per point the reduction's own export
kira_target_s63_<tag>.m and its parsed form S63_REDUCTION_<tag>.json, at
the seven off-curve points of row21_offcurve/; the point t from the
served points/points.json); the map bears on NO served number of this
evaluator (see the SECTOR-63 block below) -- it lets the 41-master
tables fold onto the 39-master convention, nothing more; seconds;
`--sector63-map --help` prints the map, the fixtures, the exit codes
and the measured wall; `--sector63-map --mutate` is the planted
control (one coefficient changed in memory -> FAIL by name, rc 1).
DOMAIN: Euclidean s<0, t<0 with u = -s-t in (2, 50]; the u-DE is transported
on the real axis with +i Feynman detours around its singular points {4,16}
and the 2-variable letter u'=-t, so any u in that window is reachable
(m13_tower alone covers u in (0,50]).  EXCLUDED LINE: t = -2 exactly
(kernel pole u'=-t ON the one-fold basepoint u'=2; logarithmic endpoint
divergence -- NAMED refusal, exit 2; any other t in the domain works,
near-pole cost grows ~log(1/|t+2|)).  Precision: any dps; cost grows
~linearly in dps (series terms KMAX ~ 1.66*dps, local-Taylor order ~ 2.3*dps).

CHANGELOG:
  2026-09-07  KERNEL-BANK SUCCESSION (part E).  71 of the 97 two-prime
              columns of the witness slice, closed exactly on the
              676-point record grid in the record's preferred-41
              convention (the closed bank object sha256 33b6847b68306a60...,
              its grid receipt 575e94ec77ee6690...; 68 direct + 3 fold16-exact),
              enter slice_n1_exact.pkl.gz as exact rational numerator
              columns and leave slice_n1_fits.pkl.gz: 4184 + 71 = 4255
              exact / 26 two-prime / 62 absent (the map's 4343
              referenced cols unchanged).  Re-checked at this re-issue
              from the object alone: every promoted column's dense
              coefficients reduce mod both fit primes to the served
              two-prime residues at node 101 on every slot (90322
              slots, 0 mismatches; the full-lattice banks: every node,
              3070948 slots, 0 mismatches).  The map tags every term
              on those columns exact-extraprime; entry classes follow
              the worst-term rule (direct-exact < exact-6prime <
              exact-10prime < exact-extraprime < certified-2prime):
              1943 -> 1989 exact entries (46 moved), 62 -> 16
              certified-2prime, 40 UNCLOSED unchanged.  The 26 two-prime
              columns of 13 targets whose record pair (c41[18],
              c41[39]) is not separable from 39-master data stay
              two-prime (a convention change would be needed, not a
              succession).  K_EXACT_CLASSES gains the tag; --theorem-check
              (t1)/(t3) read 1989/16 and 4255/26, (t4) 4343/62/40
              unchanged, a new (t8) checks the succession tally against
              the manifests (structure only); every value path
              (kernel_entry_val_exact / _modp, _k_col_exact / _modp,
              _k_heavy) is byte-identical; parts A-D never read the
              kernel.  The witness manifest and lbl3x-kernel-manifest.json
              carry a 'succession' block naming the objects by sha256.
  2026-09-06b M7-TESTED (the -7 point tested; cure-queue entry 37).  The
              standing s=-7 prediction of lbl3x-prediction.json (122 d,
              recorded 2026-07-08 with no oracle at the point) gains its
              reference: ONE independent AMFlow run at (-7,-56/13), goal
              60 (the route of the -8 goal-60 record, the point moved),
              with its goal-40 twin, vendored as the NEW gate record
              row21_chain/data/GATE_M7_GOAL60.json (the GATE_GOAL60.json
              form: the four midpoints at full printed length with their
              radii, the output/configuration sha256 of both runs, the
              receipt of record; m18_eps0_d 72.644, the goal-40 twin
              49.787, the pair floor 49.787).  `--m18-eps0 --point -7`
              now pins the record (rc 3 mismatch / rc 4 missing, by
              name, before any compute), serves the value live as
              before and RAISES on it: 'tested: 72 held-out digits'
              (this run vs the goal-60 string, floored; measured
              72.644 d) and 'pair: 49' (vs the goal-40 twin, 49.787 d;
              the goal-40/goal-60 floor 49.787 d recomputed from the
              strings), the record figures beside; a below-bar line
              FAILS by name, rc 1; the 'NO oracle exists at (-7) --
              NEVER a gate' print of THAT path is replaced.  The record
              is pinned by this script, not by the package
              MANIFEST.json (the package root pin, the -8 gate
              GATE_GOAL60.json and the goal-40 records byte-identical);
              the -8 path, --gates and every other arm are
              byte-identical after masking stamps and walls (the -8
              path's own (b) block, its 'NO oracle exists at (-7)' line
              included, is as served -- its re-wording is a follow-up);
              lbl3x-prediction.json unchanged (the prediction record
              stays the prediction).  Wall at -7: 105 s (measured 2026-09-06, one process, nice
              10, a shared 96-core host at loadavg 103.45, 103 MB
              maximum resident set; the served -7 serve 106 s on the
              same day and host -- the gate adds nothing measurable; the
              serve dominates)
  2026-09-06  SECTOR63-MAP (the 41 -> 39 convention map of the two
              spurious sector-63 masters as 14 pinned fixtures; the
              reduction of record at the seven off-curve points of
              row21_offcurve/, sectors [63] r 9 s 2, FireFly in (d, m2),
              82568 equations, 'unreduced integrals: 0.' at every point).
              NEW arm --sector63-map (+ --help, --mutate): the two
              relations checked exactly (Fraction) at d = 101 and 102,
              m2 = 1, at every point, the -t/2 entry against the point t
              of points/points.json, the .m export parsed and compared
              with its JSON form, the seven exports shown to differ only
              in the M39[17] line; the 14 fixtures + points.json +
              preferred39 sha256-pinned (mismatch rc 3, missing rc 4, by
              name).  Every other arm untouched (byte-identical output
              after masking stamps and walls); no served number moves:
              the fold is the identity on rows 0..16 (the rows of the
              off-curve chain) and parts A-D never use the 41-master
              basis.  Rows 17..40 off the curve stay NOT established.
  2026-07-08c FLIP RULINGS (the 10:2x, pre-cleared flip sequence;
              evidence <archive>/axis3_wave/row21-k3-wiring/
              flip/).  (1) x_17 VENDORED-WITH-PIN-ON-READ: pin-only
              rejected at 124 KB (standalone bar) -- LEGB_X17_FINAL.json
              vendored byte-identical as lbl3x-legb-x17.json and
              sha256-verified (aba4a9b7...) on EVERY --k3-words read,
              the NAMED X17IntegrityError otherwise; the x_17 quote now
              recomputes its counts/uniqueness/zero-remainder facts
              from the vendored data (data, not display).  (2)
              PER-CONSTANT CLAMP on the k3seed gate-cache compare:
              bar_i = min(dps, floor_i) - 5 with floor_i the constant's
              own measured cache floor (223.6/226.7/224.3/225.3 d for
              MUM1/MUM2/MUM3/M3_eps0, vendored in
              measured_cache_floor_digits) -- replaces the flat
              min(dps,231)-5 bar whose literal reading raised on honest
              dps >= 229 requests; deep requests now SERVE with the bar
              capped at each floor (no false-raise; measured: dps 240
              serves 4/4).  STATUS LAW unchanged: pole tower + complete
              K3 sector exact; two named residual classes with
              certificates.  Theorem arm untouched.
  2026-07-08  SMALL-U --POINT FIX, BLOG MIRROR (the 09:5x CONFIRM of the
              rowscripts route + mirror follow-up; mirrored from
              tools/rowscripts/eval_row21.py 2026-07-08, sha256
              dbc124f8...; evidence <archive>/axis3_wave/
              lbl3x-smallu-fix/, blog_* legs = this file's own pre-fix
              repros archived from the TRUE live copy).  ROOT CAUSE
              (measured): at t = -2 EXACTLY the kernel pole u' = -t
              coincides with the k3tail one-fold basepoint u' = 2 (the
              s'=0 letter passes through the basepoint) -- the one-fold
              has a LOGARITHMIC ENDPOINT DIVERGENCE there (K ~
              9743/(660(u'-2)) with m13^(0)(2) finite), so the point is
              not evaluable in this representation: series engine hit
              ZeroDivisionError in _K_pf at u0=2; quad engine would
              stall (rad=0 => h=0).  SECOND DEFECT: the SHARED radset
              put the kernel pole -t ON the leg-1 path [1,2] whenever
              -t in (1,2] -- the adaptive stepper cannot cross a radset
              point (h -> 0 stall), i.e. ALL t in (-2,-1] failed, not
              just t=-2.  Leg 1 carries no kernel series (DE
              singularities are {0,4,16} only).  CURES: (1) NAMED
              ValueError refusal at t == -2 in f()/k3tail()/
              k3tail_quad() (genuine divergence); --point CLI arm
              converts ValueError to a printed REFUSED line + exit 2
              (fleet refusal convention).  (2) leg-1 radset = {0,4,16}
              + (-t only if -t > 2): cures the (1,2] stall class while
              preserving the byte-exact step sequence of every
              previously-working point (-t > 2 unchanged; -t <= 2
              previously always failed).  Leg 2 keeps the full radset
              (kernel local-series radius genuinely needs -t).
              Measured on THIS file: (-1,-2) pre-fix ZeroDivisionError
              rc=1 / post-fix named refusal rc=2; (-1.6,-1.9) pre-fix
              stall (timeboxed kill) / post-fix rc=0; (-1,-2.0001)
              post-fix rc=0.  Default run, gate suite, --theorem-check:
              code paths untouched.  DOMAIN unchanged except the single
              excluded line t = -2.
  2026-07-08b ROW21-K3-WIRING (mirrored from tools/rowscripts/
              eval_row21.py same date; the 02:2x decision,
              the form record gated CONFIRM; evidence
              <archive>/axis3_wave/row21-k3-wiring/).
              (A) --k3-words: runtime-derived quotes of the K3-sector
              exact words + r_17 strings from the vendored
              WORDLIST_FINAL.json copy lbl3x-k3words.json (sha256
              75358ee1... verified on EVERY read, the NAMED
              K3WordsIntegrityError otherwise); x_17 quoted by artifact
              pin (LEGB_X17_FINAL.json sha256 aba4a9b7...), strings not
              vendored.  (B) k3seed upgrade: the 4 constants are served
              from EXACT closed forms in {1,pi^2,zeta3,gammaE} (record
              sec 3), runtime-evaluated at any dps; the stored strings
              are DEMOTED to a gate-cache (kept, compare-only): every
              serve gates closed form vs cache to >= min(dps,231)-5 d,
              else the NAMED K3SeedClosedFormGateError.  The automatic
              derive-on-demand trigger on --point dps > 215 is gone
              (closed forms scale); --derive-constants stays as an
              independent cross-check oracle.  STATUS LAW for all text
              here: pole tower + complete K3 sector exact; two named
              residual classes with certificates.  Theorem arm (part E)
              and its text UNTOUCHED.
  2026-07-05c THEOREM-SPLIT (the binding 21:5x two-objects decision;
              evidence <archive>/axis3_wave/lbl3x-split/).
              Part E is now the LBL3X-thm refutation-certificate
              CHECKER behind the explicit --theorem-check subcommand
              (--theorem-check --help states the theorem: NO
              finite-depth closed function form for the kernel
              connection, eps^0-coupled 24-SCC obstruction; and the
              certificate model: statement / witness / checker).
              Witness = the ONE-NODE exact slice (~12.5 MB, sha-pinned)
              at lbl3x-kernel-witness/ per <archive>/
              lbl3x_kernel_compact/DESIGN.md, loaded with a
              sha-manifest check; ABSENT witness = LOUD
              KernelWitnessError, nonzero exit, never a silent
              degrade.  --kernel-info kept as a compat alias of
              --theorem-check --info.  GRAPH paths (DEFAULT run,
              --point, gate suite, parts A-D) untouched:
              byte-identical outputs pre/post (leg-1 evidence).
  2026-07-05b AXIS-3 WAVE (infinite-precision charter, quick-win 7;
              mirrored from tools/rowscripts/eval_row21.py 2026-07-05c;
              evidence <archive>/axis3_wave/row21/).  Two
              truncations promoted from silent knobs to refine-until-
              certified loops: (a) MUM seed series: KMAX is now a STARTING
              guess; the series at u*=1 is accepted only when the
              certified trailing-8-window geometric tail bound (series
              ratio r <= 1/4, u-DE singularity at u=4 vs expansion point
              u=0) beats 10^-(work+10); grows x1.5 by EXACT continuation
              of the same recurrence to cap 8x, RAISES at cap; the bound
              is printed as a certified BOUND line (gate table + --point).
              (b) _step local-Taylor: exhausting the NTAY = 2.3*work+12
              allocation UNCONVERGED previously PROCEEDED SILENTLY
              (measured: 21/55 k3tail-leg steps exit with last-term
              estimate at ~tol); now grows x1.5 by exact continuation and
              RAISES at cap 8x.  Values move only below 10^-(work+4), far
              under every printed discriminant.  Interim MUM/M3/block-13
              literals UNTOUCHED (source tree owns them).
  2026-07-05  KERNEL2VAR FOLD (port of the tools/rowscripts/eval_row21.py
              2026-07-05 + 2026-07-05b kernel folds at REGISTRY v4 / record
              ADDENDUM A6; source record <archive>/solve_row21/kernel2var/
              RESULT.md): added part E, the kernel-backed 41x41 A^s/A^t
              connection API -- kernel_nodes / kernel_entry_class /
              kernel_entry_val_exact / kernel_entry_val_modp /
              kernel_V_exact / kernel_info -- with per-entry
              evidence-class enforcement (KernelClassError), the v4
              per-line-only-EMPTY load guard, and the gate-2 frame
              constraint honored in code (V = A^s - (t^2/s^2) A^t on the
              1/s+1/t=const foliation; record A3).  New CLI flag
              --kernel-info; existing CLI (gate suite / --point s t
              [dps]) unchanged.  Data vendored into this directory:
              lbl3x-kernel-map.json + lbl3x-kernel-denoms.json +
              lbl3x-kernel-manifest.json (numeric payloads identical to
              row21_kernel_data/ with provenance strings neutralized for
              release; heavy-bank sha256 == manifest pins).  Heavy col
              banks NOT shipped (349 MB; KernelDataError until the
              sha-verified drop-in lbl3x-kernel-banks/ is populated --
              part E).  Upstream fold gates: <archive>/rowscripts_interim/
              fold_row21_v4/FOLDLOG_V4.md (leg-1 withheld pt_8801 =
              (-67/6,-101/9), all claimed entries x 34 nodes, exact
              Fractions / mod both primes; leg-2 on-curve vs
              oncurve_M_ALTB_patched incl. the 18/18 row-15 combination
              checks; leg-3 evidence-class guards).  This port
              re-validated against eval_row21 on identical vendored data
              (equality harness, <archive>/blog_evaluators/
              lbl3x_kernel2var_fold_2026-07-05/).
  2026-07-03  original final-form evaluator (parts A-D, gate suite; this
              file is the source the tools/rowscripts/eval_row21.py route
              vendored from on 2026-07-03).
"""
import json, gzip, os, sys, time
from fractions import Fraction
from decimal import Decimal, getcontext
import mpmath as mp

# 2026-09-03: line-buffer stdout at import.  With stdout piped (a file, a
# pipe, a grader) Python block-buffers and the 8 KB buffer can sit
# unflushed for the whole run; line buffering makes the first line appear
# in well under a second in every mode.
if hasattr(sys.stdout, 'reconfigure'):
    sys.stdout.reconfigure(line_buffering=True)

HERE = os.path.dirname(os.path.abspath(__file__))
SEED = json.load(open(os.path.join(HERE, 'lbl3x-k3seed.json')))
T_START = time.time()
getcontext().prec = 130

# 2026-07-05 axis3 wave (mirrored from tools/rowscripts/eval_row21.py):
# certified trailing-window tail gate for the MUM seed series.  The seed is
# summed at u*=1; the u-DE D(u)=u(u-4)(u-16) has its nearest singularity to
# the expansion point u=0 at |u|=4, so the series ratio is certified
# r <= 1/4 and tail <= max(|c_k| over the trailing SEED_TAILWIN terms, all
# DIM components) * r/(1-r) = winmax/3.  (Accepted-pattern caveat: resonant
# log-polynomial factors are absorbed by the guard digits + growth.)
# Calibration (instrumented run, <archive>/axis3_wave/row21/):
# measured bound at work=40 is 1.3e-109 = 10^-(work+69), margin grows with
# work -- vs tol 10^-(work+10) that is >= 10^59 headroom; default runs
# never escalate.
SEED_TAILWIN = 8
SEED_TAIL_GUARD = 10
SEED_CAP_MULT = 8

# =====================================================================
# K3 SUBSECTOR ENGINE: exact rational 9-master u-DE (vendored, provenance
# in lbl3x-k3seed.json), MUM series at u=0, local-Taylor continuation.
# =====================================================================
BDE = SEED['ban_de']
N, NEPS = BDE['N'], BDE['NEPS']; DIM = N*NEPS
IDX_M13 = 1                       # masters[1] = I(1,1,1,1,0,...) = m13
MQ = [[(i, j, [Fraction(c) for c in BDE['M'][m][i][j]])
       for i in range(N) for j in range(N)
       if BDE['M'][m][i][j] and any(c != '0' for c in BDE['M'][m][i][j])]
      for m in range(4)]
DQ = [Fraction(c) for c in BDE['D_coeffs_asc']]      # D(u)=u(u-4)(u-16)
KVEC = SEED['kernel_int_vectors']; PIV = SEED['pivots']
KPINV = [[Fraction(x) for x in row] for row in SEED['Kp_inv_exact']]
# =====================================================================
# 2026-07-08 row21-k3-wiring (mirrored from tools/rowscripts/
# eval_row21.py; the 02:2x decision, the form record sec 3
# gated CONFIRM): the 4 constants below are EXACT CLOSED FORMS
# in {1, pi^2, zeta3, gammaE} -- e.g. M3_eps0 = 36143/288 +
# (647/72) pi^2 - 10 zeta3 -- runtime-evaluated at ANY dps from the
# exact rational coefficients in mum_constants_closed_forms
# (_bind_constants_closed_forms, called from every CLI arm once dps is
# known).  The stored strings (mum_constants_mybasis /
# M3_eps0_stripped_named) are hereby DEMOTED to a GATE-CACHE: kept,
# never deleted, never served; every serve compare-gates the closed
# forms against them to >= bar_i = min(dps, floor_i)-5 d PER CONSTANT
# (the 10:2x clamp; floor_i = measured_cache_floor_digits, 223.6/
# 226.7/224.3/225.3 d for MUM1/MUM2/MUM3/M3_eps0 -- the strings' own
# certified depth, record sec 3) and RAISES the NAMED
# K3SeedClosedFormGateError on any miss; honest deep requests at ANY
# dps serve with the bar capped at each floor (no false-raise).
# History: the
# 2026-07-06 wiring derived these AMFlow-free via the leg4 runtime
# chain (build-record sec 6 gate PASSED 2026-07-06 19:41);
# _constants_cache_gate() still tamper-checks the gate-cache vs that
# derived record at import, and --derive-constants [dps] keeps the
# vendored (row21_leg4/) leg4 chain as an independent cross-check oracle.
CONSTS = SEED['mum_constants_mybasis']    # cache (derived; record below)
M3E0S = SEED['M3_eps0_stripped_named']    # cache (derived; record below)
DREC = SEED['mum_constants_derived_record']
CONST_CACHE_SUPPORT = int(DREC['cache_support_dps'])    # honest cache depth
CONST_DERIVE_SUPPORT = int(DREC['derive_support_dps'])  # on-disk tower depth
CONSTS_DERIVED_LIVE = False               # flipped by _derive_constants
CLOSED = SEED['mum_constants_closed_forms']   # exact closed forms (record sec 3)
CONSTS_CLOSED_LIVE = False                # flipped by _bind_constants_closed_forms


class K3SeedClosedFormGateError(RuntimeError):
    """NAMED raise (the 02:2x decision; 10:2x per-constant clamp): the
    runtime-evaluated exact closed form of a k3seed constant missed the
    compare-gate vs its demoted gate-cache string (bar_i =
    min(dps, floor_i) - 5 d, floor_i = the constant's measured cache
    floor from measured_cache_floor_digits)."""


class K3WordsIntegrityError(RuntimeError):
    """NAMED raise: the vendored WORDLIST_FINAL5 copy failed the
    sha256 gate (must start with 57e9ac16) -- quoting is refused."""


class X17IntegrityError(RuntimeError):
    """NAMED raise (the 10:2x vendored-with-pin-on-read decision): the
    vendored LEGB_X17_FINAL.json copy failed the sha256 gate (must
    start with aba4a9b7) -- the x_17 quote is refused."""


# IMMUTABLE gate-cache capture (bugfix caught by this build's crank gate,
# first run): the compare-gate must ALWAYS run against the ORIGINAL
# stored strings, never against the currently-served CONSTS/M3E0S --
# after a first bind those hold the closed-form values and a second
# bind would self-compare and void the gate.
_GATECACHE_PAIRS = (('MUM1', SEED['mum_constants_mybasis'][0]),
                    ('MUM2', SEED['mum_constants_mybasis'][1]),
                    ('MUM3', SEED['mum_constants_mybasis'][2]),
                    ('M3_eps0', SEED['M3_eps0_stripped_named']))


def _eval_closed_forms(work):
    """Runtime-evaluate the 4 EXACT closed forms (form-record sec 3,
    gated CONFIRM 02:2x 2026-07-08) at `work` dps from the exact
    rational coefficients vendored in k3seed.mum_constants_closed_forms.
    Basis {1, pi^2, zeta3, g, g*pi^2, g^2, g^3}, g = EulerGamma."""
    with mp.workdps(work + 15):
        g = mp.euler
        basis = {'1': mp.mpf(1), 'pi^2': mp.pi**2, 'zeta3': mp.zeta(3),
                 'g': g, 'g*pi^2': g*mp.pi**2, 'g^2': g**2, 'g^3': g**3}
        out = {}
        for name, cf in CLOSED['coeffs'].items():
            acc = mp.mpf(0)
            for bname, c in zip(CLOSED['basis'], cf):
                q = Fraction(c)
                if q:
                    acc += mp.mpf(q.numerator)/q.denominator*basis[bname]
            out[name] = acc
    return out


def _bind_constants_closed_forms(dps):
    """2026-07-08 k3seed upgrade (the 02:2x decision): serve the 4
    constants from their EXACT closed forms, evaluated at runtime at
    dps+80 working digits; the stored strings are DEMOTED to a
    gate-cache (kept, never deleted, never served).  Compare-gate on
    every serve (the 10:2x PER-CONSTANT CLAMP): closed form vs
    gate-cache string must agree to >= bar_i = min(dps, floor_i) - 5 d,
    floor_i = the constant's own measured cache floor (223.6/226.7/
    224.3/225.3 d for MUM1/MUM2/MUM3/M3_eps0, record sec 3; vendored as
    measured_cache_floor_digits), else the NAMED
    K3SeedClosedFormGateError (fail-closed).  Honest deep requests at
    ANY dps SERVE with the bar capped at each floor -- no false-raise
    (the flat min(dps,231)-5 bar raised on honest dps >= 229)."""
    global CONSTS, M3E0S, CONSTS_CLOSED_LIVE
    work = dps + 80
    floors = CLOSED['measured_cache_floor_digits']   # per-constant (10:2x)
    vals = _eval_closed_forms(work)
    report = []
    with mp.workdps(work):
        for name, cs in _GATECACHE_PAIRS:   # ORIGINAL strings, see capture
            got, ref = vals[name], mp.mpf(cs)
            d = float(work) if got == ref else \
                float(-mp.log10(abs(got - ref)/abs(ref)))
            bar = min(float(dps), float(floors[name])) - 5   # 10:2x clamp
            report.append((name, d, bar))
            if d < bar:
                raise K3SeedClosedFormGateError(
                    'row21 k3seed closed-form compare-gate: %s (EXACT closed '
                    'form, form-record sec 3) agrees with its gate-cache '
                    'string to only %.1f d < bar_i = min(dps, floor_i) - 5 '
                    '= %.1f d (floor_i %.1f d; the 10:2x per-constant '
                    'clamp).  Honest requests at ANY dps serve with the bar '
                    'capped at the constant\'s measured cache floor, so this '
                    'raise indicts a mutated/stale gate-cache or data file, '
                    'not the request.  Restore lbl3x-k3seed.json or '
                    're-stage.'
                    % (name, d, bar, float(floors[name])))
        CONSTS = [mp.nstr(vals[n], work) for n in ('MUM1', 'MUM2', 'MUM3')]
        M3E0S = mp.nstr(vals['M3_eps0'], work)
    CONSTS_CLOSED_LIVE = True
    print('[k3seed closed-form gate] 4/4 constants served from EXACT closed '
          'forms')
    print('  (runtime-evaluated at %d working digits); agreement vs '
          'gate-cache:' % work)
    print('  %s' % ', '.join('%s %.1fd (bar %.1fd)'
                             % (n, min(d, 300.0), b) for n, d, b in report))




def _const_pairs():
    return (('MUM1', CONSTS[0]), ('MUM2', CONSTS[1]), ('MUM3', CONSTS[2]),
            ('M3_eps0', M3E0S))


def _constants_cache_gate():
    """Compare-on-load: every cached constant string must agree with the
    vendored derived-chain record (build-record sec 6) to its gate bar.
    RAISES (fail-closed) on mismatch -- a mutated/stale cache is refused."""
    with mp.workdps(300):
        for name, cs in _const_pairs():
            ref = mp.mpf(DREC['solved'][name])
            got = mp.mpf(cs)
            d = 300.0 if got == ref else float(-mp.log10(abs(got-ref)/abs(ref)))
            bar = DREC['gate_bars_digits'][name]
            if d < bar:
                raise RuntimeError(
                    'row21 constants compare-on-load gate: cached %s agrees '
                    'with the derived runtime-chain record to only %.1f d < '
                    'bar %d d (record: build-record sec 6 chain of 2026-07-06 '
                    '19:41, MUM_MATCH_dps280.json).  The cache string is '
                    'corrupt or stale -- refusing to serve it.  Rederive via '
                    '--derive-constants or restore lbl3x-k3seed.json.'
                    % (name, d, bar))


_constants_cache_gate()


def _derive_constants(dps):
    """Derive-on-demand (the vendored row21_leg4/ chain; mirrored from eval_row21.py): rerun
    the leg4 mum_match_v2 chain (zero AMFlow) against the deepest sha-pinned
    PRODUCTION BAN tower on disk, gate the fresh solve vs the cache strings
    (RAISING mismatch gate), and rebind CONSTS/M3E0S to the derived values."""
    global CONSTS, M3E0S, CONSTS_DERIVED_LIVE
    import hashlib, subprocess, tempfile
    if dps > CONST_DERIVE_SUPPORT:
        raise RuntimeError(
            'row21 derive-on-demand: requested dps %d exceeds the deepest '
            'on-disk BAN tower support (~%d d, internal certs 236-240d from '
            'the dps280 family).  Refresh path (measured, NOT run here): %s'
            % (dps, CONST_DERIVE_SUPPORT, DREC['refresh_recipe']))
    leg4 = os.environ.get(DREC['env_override'], DREC['leg4_dir'])
    if leg4 and not os.path.isabs(leg4):
        leg4 = os.path.join(HERE, leg4)   # the vendored chain: relative to this script
    if not leg4:
        raise RuntimeError(
            'row21 derive-on-demand: no chain directory is configured '
            '(mum_constants_derived_record.leg4_dir is empty in '
            'lbl3x-k3seed.json).  Set %s to a directory holding mum_match_v2.py, '
            'the eval_row21.py import shim and a BAN tower.  Refresh/provision recipe: %s'
            % (DREC['env_override'], DREC['refresh_recipe']))
    mm = os.path.join(leg4, 'mum_match_v2.py')
    if not os.path.isdir(leg4) or not os.path.exists(mm):
        raise RuntimeError(
            'row21 derive-on-demand: leg4 chain dir not found at %r (env '
            'override %s).  The cache path (default page run, --point at '
            'dps <= %d) needs nothing from that directory; the derive leg '
            'needs the vendored row21_leg4/ chain (mum_match_v2.py, the '
            'eval_row21.py import shim, a BAN tower).  Refresh/provision recipe: %s'
            % (leg4, DREC['env_override'], CONST_CACHE_SUPPORT,
               DREC['refresh_recipe']))

    def _sha(p):
        return hashlib.sha256(open(p, 'rb').read()).hexdigest()
    if _sha(mm) != DREC['mum_match_v2_sha256']:
        raise RuntimeError('row21 derive-on-demand: mum_match_v2.py sha256 '
                           'mismatch vs vendored pin -- refusing to run it')
    shim = os.path.join(leg4, 'eval_row21.py')
    if not os.path.exists(shim) or _sha(shim) != DREC['import_shim_sha256']:
        raise RuntimeError('row21 derive-on-demand: eval_row21.py import shim '
                           'missing or sha256 mismatch vs vendored pin -- '
                           'refusing to run the chain')
    ban = None
    for fn in sorted(DREC['ban_towers_sha256'],
                     key=lambda f: -int(f.split('dps')[1].split('.')[0])):
        p = os.path.join(leg4, fn)
        if os.path.exists(p):
            if _sha(p) != DREC['ban_towers_sha256'][fn]:
                raise RuntimeError('row21 derive-on-demand: %s sha256 '
                                   'mismatch vs vendored pin' % fn)
            ban = p
            break
    if ban is None:
        raise RuntimeError(
            'row21 derive-on-demand: no PRODUCTION BAN tower on disk under '
            '%r (looked for %s).  Refresh recipe: %s'
            % (leg4, sorted(DREC['ban_towers_sha256']),
               DREC['refresh_recipe']))
    work = max(dps + 35, 60)              # solve accuracy ~ work-24 measured
    t0 = time.time()
    with tempfile.NamedTemporaryFile(suffix='.json', delete=False) as tf:
        outp = tf.name
    try:
        print('[derive-on-demand] mum_match_v2 vs %s at work dps %d ...'
              % (os.path.basename(ban), work))
        r = subprocess.run([sys.executable, mm, '--ban', ban,
                            '--work', str(work), '--out', outp],
                           capture_output=True, text=True)
        if r.returncode != 0:
            raise RuntimeError('row21 derive-on-demand: mum_match_v2 failed '
                               '(rc=%d):\n%s' % (r.returncode, r.stderr[-2000:]))
        sol = json.load(open(outp))['gates']
    finally:
        os.unlink(outp)
    elapsed = time.time() - t0
    # RAISING mismatch gate: fresh derivation vs the demoted cache strings,
    # to the digits being served (capped at the honest cache depth).
    bar = min(dps, CONST_CACHE_SUPPORT)
    with mp.workdps(work + 20):
        report = []
        for name, cs in _const_pairs():
            got = mp.mpf(sol[name]['solved'])
            ref = mp.mpf(cs)
            d = float(work) if got == ref else \
                float(-mp.log10(abs(got-ref)/abs(ref)))
            report.append((name, d))
            if d < bar:
                raise RuntimeError(
                    'row21 derive-on-demand mismatch gate: fresh %s agrees '
                    'with the cache string to only %.1f d < serving bar %d d '
                    '-- refusing both values (cache mutated, tower stale, or '
                    'chain regression).' % (name, d, bar))
    CONSTS = [sol['MUM1']['solved'], sol['MUM2']['solved'],
              sol['MUM3']['solved']]
    M3E0S = sol['M3_eps0']['solved']
    CONSTS_DERIVED_LIVE = True
    print('[derive-on-demand] LIVE-DERIVED constants in %.1f s (measured); '
          'agreement vs cache: %s (serving bar %d d)'
          % (elapsed, ', '.join('%s %.1fd' % (n, d) for n, d in report), bar))

K3WORDS_FILE = 'lbl3x-k3words.json'
# 2026-09-03 refresh: the served wordlist is now the campaign's FINAL
# record WORDLIST_FINAL5.json (2026-07-08 23:22, source sha256
# 8cc9fe13640b419a...), vendored as a scrubbed copy (provenance strings
# neutralized; all mathematical content byte-identical); it supersedes
# the phase-1 draft WORDLIST_FINAL.json (75358ee1...) served before.
K3WORDS_SOURCE = ('WORDLIST_FINAL5.json', '8cc9fe13640b419a')
K3WORDS_SHA256 = \
    '57e9ac16040aab385cafb101c3e891a608ca089a5a5f41164569cca00bf0af6e'
X17_ARTIFACT = ('<archive>/lbl3x_form/phase1/closure/LEGB_X17_FINAL.json',
                'aba4a9b78114eb50')
X17_FILE = 'lbl3x-legb-x17.json'      # vendored copy (the 10:2x decision)
X17_SHA256 = \
    'aba4a9b78114eb50b4782d748063d6972f6f2a0792d0162b888e7daeb8008eaf'


def _load_x17():
    """Load the vendored byte-identical copy of LEGB_X17_FINAL.json;
    VERIFY sha256 startswith aba4a9b7 (the 10:2x vendored-with-pin-
    on-read decision) -- and in fact the full pinned hash -- on EVERY
    read; the NAMED X17IntegrityError otherwise (fail-closed, the x_17
    quote is refused)."""
    import hashlib
    p = os.path.join(HERE, X17_FILE)
    if not os.path.exists(p):
        raise X17IntegrityError(
            'row21 x17: vendored LEG-B artifact %s is ABSENT next to this '
            'script -- refusing to quote x_17.  Source of record: %s '
            '(sha256 aba4a9b7...).' % (X17_FILE, X17_ARTIFACT[0]))
    raw = open(p, 'rb').read()
    h = hashlib.sha256(raw).hexdigest()
    if not h.startswith('aba4a9b7') or h != X17_SHA256:
        raise X17IntegrityError(
            'row21 x17: vendored LEG-B artifact sha256 %s... does not match '
            'the record-pinned aba4a9b7... (LEGB_X17_FINAL.json, record_'
            'LBL3X_FORM sec 1/5) -- REFUSING to quote x_17 from it.'
            % h[:16])
    return json.loads(raw.decode('utf-8'))


def _load_k3_words():
    """Load the vendored scrubbed copy of the campaign's final wordlist
    record WORDLIST_FINAL5.json (source sha256 8cc9fe13640b419a...),
    served here as lbl3x-k3words.json; VERIFY sha256 startswith 57e9ac16
    -- and in fact the full pinned hash -- on EVERY read; the NAMED
    K3WordsIntegrityError otherwise (fail-closed, nothing quoted)."""
    import hashlib
    p = os.path.join(HERE, K3WORDS_FILE)
    if not os.path.exists(p):
        raise K3WordsIntegrityError(
            'k3-words: vendored wordlist %s is ABSENT next to this '
            'script -- refusing to quote.  Record of origin: %s, '
            '2026-07-08 final closure (source sha256 %s...).'
            % (K3WORDS_FILE, K3WORDS_SOURCE[0], K3WORDS_SOURCE[1][:8]))
    raw = open(p, 'rb').read()
    h = hashlib.sha256(raw).hexdigest()
    if not h.startswith('57e9ac16') or h != K3WORDS_SHA256:
        raise K3WordsIntegrityError(
            'k3-words: vendored wordlist %s sha256 %s... does not match '
            'the pinned 57e9ac16... (scrubbed copy of %s, source sha256 '
            '%s...) -- REFUSING to quote from it.'
            % (K3WORDS_FILE, h[:16], K3WORDS_SOURCE[0],
               K3WORDS_SOURCE[1][:8]))
    return json.loads(raw.decode('utf-8'))


def _parse_poly_q(s):
    """Exact-Fraction parse of a wordlist polynomial string in x
    (terms joined by ' + ', negative coefficients parenthesized)."""
    poly = {}
    for term in s.split(' + '):
        term = term.strip()
        if '*x^' in term:
            c, p = term.split('*x^')
            k = int(p)
        elif term.endswith('*x'):
            c, k = term[:-2], 1
        else:
            c, k = term, 0
        c = c.strip()
        if c.startswith('(') and c.endswith(')'):
            c = c[1:-1]
        poly[k] = Fraction(c)
    return poly


def print_k3_words():
    """--k3-words (record refreshed 2026-09-03): runtime quotes of the m18
    pole tower, the complete rational-sector word list, the x_17 ring word
    and the twist-sector verdict, taken ONLY from the sha-verified vendored
    copy of the campaign's FINAL record (WORDLIST_FINAL5.json, 2026-07-08
    final closure) plus the sha-verified x_17 artifact.  Every count and
    every parsed rational below is recomputed from the vendored data on
    this run -- data, not display."""
    import textwrap

    def wr(s, indent='  '):
        for ln in textwrap.wrap(s, width=72, initial_indent=indent,
                                subsequent_indent=indent + '  '):
            print(ln)

    W = _load_k3_words()
    Wm = W['m18_words']
    L0 = Wm['0']
    print('=' * 74)
    print('row 21 (LBL3X m18) -- K3-SECTOR EXACT WORDS, quoted at runtime '
          'from the')
    print('sha-verified vendored wordlist (%s)' % K3WORDS_FILE)
    print('=' * 74)
    print('record of origin: %s -- the 2026-07-08 final-closure record of '
          'the' % K3WORDS_SOURCE[0])
    print('  campaign (source sha256 %s...); served here as a scrubbed '
          'copy,' % K3WORDS_SOURCE[1][:8])
    print('  sha256 %s...%s VERIFIED on this read.'
          % (K3WORDS_SHA256[:8], K3WORDS_SHA256[-8:]))
    print('  (It supersedes the phase-1 draft wordlist, sha256 75358ee1..., '
          'that')
    print('  earlier copies of this page served; the draft predated the '
          'final')
    print('  closure and its interim classifications no longer apply.)')
    print()
    assert L0['status'].startswith('RAT-SECTOR WORDS COMPLETE'), \
        'wordlist status drifted vs the pinned FINAL5 record'
    print('STATUS (quoted from the record):')
    wr(L0['status'])
    print()

    # ---- pole tower --------------------------------------------------
    print('POLE TOWER (exact, function-level; quoted):')
    for lay in ('-3', '-2', '-1'):
        print('  m18^(%s) = %s' % (lay, Wm[lay]['value']))
    assert Wm['-1']['value'].startswith('2*zeta3'), \
        'layer -1 value drifted vs the pinned wordlist'
    print('  (this evaluator\'s part-5 gate verifies the same exact '
          '2*zeta3 value')
    print('  against five independent AMFlow points at runtime)')
    print()

    # ---- the alphabet ------------------------------------------------
    letters = W['letters']
    qint_key = [k for k in letters if k.startswith('Qint_j')][0]
    qtw_key = [k for k in letters if k.startswith('Qtw_i')][0]
    n_qint = len(qint_key.split('{')[1].split('}')[0].split(','))
    n_qtw = len(qtw_key.split('=')[1].split(')')[0].split(','))
    n_quad = 1 + n_qint + n_qtw          # N5 + Qint_j + Qtw_i
    assert n_quad == 13, 'quadrature-letter count %d != 13' % n_quad
    print('THE ALPHABET -- %d quadrature letters (plus the rational '
          'letters s and' % n_quad)
    print('%s), counted from the vendored letters block on this run:'
          % letters['w8'])
    print('  [ 1] N5:')
    wr(letters['N5'], indent='       ')
    print('  [%2d] %s:' % (n_qint, qint_key))
    wr(letters[qint_key], indent='       ')
    print('  [%2d] %s:' % (n_qtw, qtw_key))
    wr(letters[qtw_key], indent='       ')
    print()

    # ---- the 12 rational-sector words --------------------------------
    RS = L0['rat_sector_particular']
    words = RS['words']
    assert len(words) == 12, 'rat-sector word count %d != 12' % len(words)
    assert all(w['mu'] == '1' and w['r'] == '1' for w in words), \
        'a closing coefficient is not exactly 1'
    print('RATIONAL-SECTOR PARTICULAR -- %d words, closing coefficients '
          'exactly 1' % len(words))
    print('(counted and checked from the vendored data on this run):')
    for k in range(0, 12, 4):
        print('  ' + '   '.join('%-14s' % w['w'] for w in words[k:k+4]))
    print('  certificate (quoted):')
    wr(RS['certificate'], indent='    ')
    print('  minimality (quoted):')
    wr(RS['minimality'], indent='    ')
    print()

    # ---- x_17 (K3 ring word) -----------------------------------------
    print('x_17 (K3 RING WORD): EXACT -- recomputed from the vendored '
          'artifact on')
    print('this run (data, not display):')
    X = _load_x17()                   # VENDORED, sha-verified on THIS read
    nz = X['xi_exact_nonzero']
    assert int(X['n_nonzero_coords']) == len(nz) == 502, \
        'x17 nonzero-coordinate count drifted vs the pinned artifact'
    assert int(X['nullity']) == 0 and int(X['n_pivots']) == 2484 \
        and int(X['ncol_ring_coords']) == 2484, \
        'x17 uniqueness data drifted vs the pinned artifact'
    assert X['fresh_prime_all_coords_zero'] is True, \
        'x17 zero-remainder flag drifted'
    print('  vendored artifact %s, sha256 %s...%s VERIFIED on this read'
          % (X17_FILE, X17_SHA256[:8], X17_SHA256[-8:]))
    print('  (xi payload identical to the record LEGB_X17_FINAL.json; '
          'provenance strings neutralized for release).')
    print('  %d-coordinate h7 ring particular, %d nonzero; ker A = 0 '
          '(nullity 0,' % (int(X['ncol_ring_coords']), len(nz)))
    print('  %d/%d pivots) => x_17 UNIQUE given r_17; %d-prime CRT, '
          'heights <=' % (int(X['n_pivots']), int(X['ncol_ring_coords']),
                          int(X['primes_available'])))
    print('  %d/%d digits (num/den); zero-remainder A.xi + C.r_17 - b == 0 '
          'at both'
          % (int(X['heights']['max_num_digits']),
             int(X['heights']['max_den_digits'])))
    print('  confirmation primes, all %d rows (vendored flag recomputed: '
          '%s).' % (int(X['nrow']), X['fresh_prime_all_coords_zero']))
    c0 = min(nz, key=int)
    q0 = Fraction(nz[c0])
    print('  first nonzero coordinate (parsed exact on this run): c=%s, '
          '%d-digit' % (c0, len(str(abs(q0.numerator)))))
    print('  numerator / %d-digit denominator' % len(str(q0.denominator)))
    print()

    # ---- twist sector / c_q verdict ----------------------------------
    TS = L0['twist_sector']
    print('TWIST SECTOR -- THE c_q VERDICT (quoted from the record):')
    print('  status: %s' % TS['status'])
    wr(TS['statement'])
    ctrl = TS['controls']
    print('  controls (from the vendored data): planted 1e-30 twist '
          'recovered to')
    print('  %.3g absolute error; loop-defect identity residual %.3g.'
          % (float(ctrl['planted_twist_pi_1p_i_1e-30_recovered_abs_err']),
             float(ctrl['H_loop_defect_equals_minus_2H_rel'])))
    print()

    # ---- what remains unfinished -------------------------------------
    print('WHAT REMAINS UNFINISHED (quoted from the record, '
          'case-normalized):')
    wr(L0['interim_open'][0].replace('OPEN', 'open')
       .replace('EVALUATOR', 'evaluator'))
    print()
    print('VERDICT: rat-sector words complete (12-word variation-of-'
          'parameters,')
    print('three-prime certificate); pole tower exact; x_17 exact and '
          'unique;')
    print('twist sector measured zero.  One symbolic word tower remains '
          'unfinished')
    print('as words; the value-serving evaluator is closed '
          '(--m18-eps0).')

def _u0_closed(work):
    """u=0 boundary tower a0 (raw normalization) from the CLOSED forms."""
    mp.mp.dps = work
    pi2, z3, g = mp.pi**2, mp.zeta(3), mp.euler
    U0 = SEED['u0_closed']
    def val(t):
        h = U0[t]; coef = {'1': mp.mpf(1), 'pi^2': pi2, 'zeta3': z3}
        return -sum(c*coef[m] for m, c in zip(h['members'], h['vector'][1:]))/h['vector'][0]
    S = {k: [val(f'M{k}[{tag}]eps{o}') for o in (-3, -2, -1, 0)]
         for k, tag in ((0, '111000000'), (1, '111100000'), (2, '1111-20000'))}
    S[3] = [val(f'M3[1111000-20]eps{o}') for o in (-3, -2, -1)] + [mp.mpf(M3E0S)]
    S[4] = S[5] = S[6] = [a+b for a, b in zip(S[1], S[0])]
    S[7] = S[8] = [mp.mpf(4)/3*x for x in S[4]]
    def to_raw(st):  # raw_n = sum_k (-3g)^k/k! stripped_{n-k}
        return [sum((-3*g)**k/mp.factorial(k)*st[n-k] for k in range(n+1))
                for n in range(4)]
    a0 = [mp.mpf(0)]*DIM
    for i in range(N):
        rw = to_raw(S[i])
        for r in range(4): a0[r*N+i] = rw[r]
    return a0

def _numeric_blocks(work):
    mp.mp.dps = work
    Mn = [[mp.matrix(N, N) for _ in range(5)] for m in range(4)]
    for m in range(4):
        for (i, j, cl) in MQ[m]:
            for jj, c in enumerate(cl):
                Mn[m][jj][i, j] = mp.mpf(c.numerator)/c.denominator
    Ms = [[(i, j, [mp.mpf(c.numerator)/c.denominator for c in cl])
           for (i, j, cl) in MQ[m]] for m in range(4)]
    Dc = [mp.mpf(c.numerator)/c.denominator for c in DQ]
    return Mn, Ms, Dc

_SEED_CACHE = {}
def mum_seed_state(work):
    """Frobenius/MUM series at u=0 (resonant k=1: SVD particular in the exact
    pivot gauge + the 3 named constants along the exact kernel vectors),
    summed at u*=1.  Returns the 4xN tower Y(u*=1)."""
    if work in _SEED_CACHE: return _SEED_CACHE[work]
    mp.mp.dps = work
    a0 = _u0_closed(work)
    Mn, _, _ = _numeric_blocks(work)
    # frame check: B0 a0 = 0 (the closed seed sits in the DE's u->0 frame)
    B0 = mp.zeros(DIM, DIM)
    for m in range(4):
        for r in range(m, NEPS):
            for i in range(N):
                for jj in range(N):
                    v = Mn[m][0][i, jj]
                    if v: B0[r*N+i, (r-m)*N+jj] = v
    res0 = mp.norm(B0*mp.matrix(a0))/mp.norm(mp.matrix(a0))
    # 2026-07-05 axis3 wave: the closed-form length is a STARTING guess
    # only; acceptance is by the certified trailing-window tail bound
    # below (grow by EXACT continuation of the same recurrence; RAISE at
    # cap).  See the SEED_TAIL* calibration comment at module top.
    KMAX0 = int(1.66*(work+10)) + 40
    SEED_CAP = SEED_CAP_MULT*KMAX0
    kern = [[mp.mpf(x) for x in kv] for kv in KVEC]
    series = [a0]

    def _extend(k_from, k_to):
        for k in range(k_from, k_to+1):
            rhs = [mp.mpf(0)]*DIM
            for j in range(1, 5):
                if k-j < 0: break
                akj = series[k-j]
                for m in range(4):
                    Mm = Mn[m][j]
                    for r in range(m, NEPS):
                        base, src = r*N, (r-m)*N
                        for i in range(N):
                            acc = mp.mpf(0)
                            for jj in range(N):
                                v = Mm[i, jj]
                                if v: acc += v*akj[src+jj]
                            if acc: rhs[base+i] += acc
            for i in range(DIM):
                rhs[i] += 20*(k-1)*series[k-1][i]
                if k >= 2: rhs[i] -= (k-2)*series[k-2][i]
            if k == 1:
                # resonant layer: 64-B0 singular (nullity 3). SVD particular,
                # exact pivot gauge x[piv]=0, then the named constants.
                A36 = mp.mpf(64)*mp.eye(DIM) - B0
                U, Sv, V = mp.svd_r(A36)
                thr = mp.mpf(10)**(-work+15)
                Sinv = mp.diag([1/Sv[i] if Sv[i] > thr else mp.mpf(0) for i in range(DIM)])
                x = V.T*(Sinv*(U.T*mp.matrix(rhs)))
                solres = mp.norm(A36*x - mp.matrix(rhs))/mp.norm(mp.matrix(rhs))
                assert solres < mp.mpf(10)**(-work//2), 'k=1 resonance solvability'
                xp = [x[pc, 0] for pc in PIV]
                for q in range(3):
                    al = sum(mp.mpf(KPINV[q][r].numerator)/KPINV[q][r].denominator*xp[r]
                             for r in range(3))
                    coefq = al - mp.mpf(CONSTS[q])
                    for i in range(DIM): x[i, 0] -= coefq*kern[q][i]
                series.append([x[i, 0] for i in range(DIM)])
            else:
                A9 = 64*k*mp.eye(N) - Mn[0][0]
                xk = [mp.mpf(0)]*DIM
                for r in range(NEPS):
                    rr = [rhs[r*N+i] for i in range(N)]
                    for m in range(1, min(r, 3)+1):
                        Mm = Mn[m][0]
                        for i in range(N):
                            acc = mp.mpf(0)
                            for jj in range(N):
                                v = Mm[i, jj]
                                if v: acc += v*xk[(r-m)*N+jj]
                            rr[i] += acc
                    sol = mp.lu_solve(A9, mp.matrix(rr))
                    for i in range(N): xk[r*N+i] = sol[i, 0]
                series.append(xk)

    KMAX = KMAX0
    _extend(1, KMAX)
    seed_tol = mp.mpf(10)**(-(work + SEED_TAIL_GUARD))
    while True:
        # certified tail bound at u*=1 (r <= 1/4 => tail <= winmax * 1/3)
        bound = max(abs(x) for sk in series[-SEED_TAILWIN:] for x in sk)/3
        if bound < seed_tol:
            break
        if KMAX >= SEED_CAP:
            raise RuntimeError(
                'mum_seed_state: certified seed-series tail bound %.3e >= '
                'tol %.3e at u*=1 after N=%d terms (start %d, cap %d, '
                'work dps %d) -- refusing to serve an uncertified MUM seed'
                % (float(bound), float(seed_tol), KMAX, KMAX0, SEED_CAP,
                   work))
        knew = min(KMAX + max(KMAX//2, 1), SEED_CAP)
        _extend(KMAX+1, knew)      # EXACT continuation, same recurrence
        KMAX = knew
    a = [mp.mpc(0)]*DIM
    for k in range(KMAX, -1, -1):        # Horner at u*=1
        sk = series[k]
        for i in range(DIM): a[i] = a[i] + sk[i]  # u*=1: plain sum
    tail = abs(series[KMAX][3*N+IDX_M13])
    Y = [[a[r*N+i] for i in range(N)] for r in range(4)]
    _SEED_CACHE[work] = (Y, float(res0), float(tail), KMAX, float(bound))
    return _SEED_CACHE[work]

# ---- local-Taylor stepper (tower + optional tail accumulators) -------------
def _shift_poly(coeffs, u0):
    out = [mp.mpc(0)]*len(coeffs)
    for c in reversed(coeffs):
        for k in range(len(coeffs)-1, 0, -1): out[k] = out[k]*u0 + out[k-1]
        out[0] = out[0]*u0 + c
    return out

def _step(Y, J, u0, h, work, Ms, Dc, ksers):
    # 2026-07-05 axis3 wave: NTAY is a STARTING allocation only.  The
    # Taylor loop runs until its own 5-quiet-term criterion certifies the
    # truncation; exhausting the allocation UNCONVERGED (the pre-edit code
    # SILENTLY PROCEEDED here) now grows the allocation x1.5 by EXACT
    # continuation of the same recurrence, and RAISES at cap (fail-closed).
    NTAY = int(2.3*work) + 12
    NTAY0, NTAY_CAP = NTAY, 8*NTAY
    Dl = _shift_poly(Dc, u0)
    Ml = [[(i, j, _shift_poly(cl, u0)) for (i, j, cl) in Ms[m]] for m in range(4)]
    D0 = Dl[0]
    Yt = [[list(Y[n])] for n in range(4)]
    nJ = len(ksers)
    Ks = [kf(u0, NTAY) for kf in ksers]
    Jt = [[J[q]] for q in range(nJ)]
    tol = mp.mpf(10)**(-work-6)
    hp = mp.mpc(1); last_big = 0
    l = 0
    while True:
        newY = []
        for n in range(4):
            S = [mp.mpc(0)]*N
            for m in range(min(n+1, 4)):
                Yv = Yt[n-m]
                for (i, j, cl) in Ml[m]:
                    kmax = min(l, len(cl)-1)
                    s = cl[0]*Yv[l][j]
                    for k in range(1, kmax+1): s += cl[k]*Yv[l-k][j]
                    S[i] += s
            Yn = Yt[n]
            for k in range(1, min(l+1, 3)+1):
                fac = Dl[k]*(l-k+1); Yk = Yn[l-k+1]
                for i in range(N): S[i] -= fac*Yk[i]
            inv = 1/(D0*(l+1))
            newY.append([s*inv for s in S])
        for n in range(4): Yt[n].append(newY[n])
        for q in range(nJ):     # dJ/du = K(u) m13^(0)(u)
            Kq = Ks[q]
            acc = mp.mpc(0)
            for a in range(min(l, len(Kq)-1)+1):
                acc += Kq[a]*Yt[3][l-a][IDX_M13]
            Jt[q].append(acc/(l+1))
        hp = hp*h; ahp = abs(hp)
        nm = max(abs(newY[3][i]) for i in range(N))*ahp
        if nJ:
            nm = max(nm, max(abs(Jt[q][l+1]) for q in range(nJ))*ahp)
        if nm > tol: last_big = l+1
        if l+1 - last_big > 4 and l > 15: break
        l += 1
        if l >= NTAY-1:
            # allocation exhausted UNCONVERGED: grow x1.5 by exact
            # continuation (Ks are closed-form local-series coefficients
            # -- identical prefix, longer tail); raise at cap.
            if NTAY >= NTAY_CAP:
                # 2026-07-05 rc-failclosed sweep: the trigger is the
                # 5-quiet-term certificate NOT firing -- report the actual
                # quiet-run count and the last-term estimate WITHOUT
                # asserting an inequality (nm can legitimately be < tol
                # here while the quiet run is still short).
                raise RuntimeError(
                    '_step: local-Taylor series UNCONVERGED at u0=%s, '
                    'h=%s: quiet-run %d/5 consecutive sub-tol terms '
                    '(tol %.1e; last-term estimate %.3e) after '
                    'N=%d terms (start %d, cap %d, work dps %d)'
                    % (mp.nstr(u0, 12), mp.nstr(h, 12),
                       max(0, l + 1 - last_big), float(tol), float(nm),
                       NTAY, NTAY0, NTAY_CAP, work))
            NTAY = min(NTAY + max(NTAY0//2, 1), NTAY_CAP)
            Ks = [kf(u0, NTAY) for kf in ksers]
    L = len(Yt[0])
    Yo = []
    for n in range(4):
        acc = [mp.mpc(0)]*N
        for l in range(L-1, -1, -1):
            Yl = Yt[n][l]
            for i in range(N): acc[i] = acc[i]*h + Yl[i]
        Yo.append(acc)
    Jo = []
    for q in range(nJ):
        a = mp.mpc(0)
        for l in range(len(Jt[q])-1, -1, -1): a = a*h + Jt[q][l]
        Jo.append(a)
    return Yo, Jo

STEP_FRAC = 0.35
def _build_path(u0, u1, poles, r=0.5):
    """Real axis with +i box detours (Feynman branch, archived convention)."""
    ps = sorted(p for p in poles if u0 < p < u1)
    pts = [mp.mpc(u0, 0)]; prev = u0
    for i, c in enumerate(ps):
        nxt = ps[i+1] if i+1 < len(ps) else u1
        rr = min(r, (c-prev)*0.45, (nxt-c)*0.45)
        pts += [mp.mpc(c-rr, 0), mp.mpc(c-rr, rr), mp.mpc(c+rr, rr), mp.mpc(c+rr, 0)]
        prev = c+rr
    pts.append(mp.mpc(u1, 0))
    return pts

def _transport(Y, J, pts, work, Ms, Dc, ksers, radset):
    u = pts[0]; nstep = 0
    eps_u = mp.mpf(10)**(-work+5)
    for w in pts[1:]:
        while abs(u-w) > eps_u:
            rad = min(abs(u-s) for s in radset)
            d = w-u; ad = abs(d)
            h = d if ad <= STEP_FRAC*rad else d*(STEP_FRAC*rad/ad)
            Y, J = _step(Y, J, u, h, work, Ms, Dc, ksers)
            u = u+h; nstep += 1
            assert nstep < 3000, 'transport stalled'
    return Y, J, nstep

def m13_tower(u_target, dps=50, detour_r=0.5):
    """m13 tower eps^-3..0 (raw AMFlow norm) at real u in (0, 50]."""
    work = dps + 15
    Y1, res0, tl, KM, _sb = mum_seed_state(work)
    _, Ms, Dc = _numeric_blocks(work)
    uf = float(u_target)
    pth = _build_path(1, uf, [p for p in (4.0, 16.0) if 1 < p < uf], r=detour_r)
    radset = [mp.mpc(0), mp.mpc(4), mp.mpc(16)]
    Yv, _, ns = _transport([r[:] for r in Y1], [], pth, work, Ms, Dc, [], radset)
    return {n-3: Yv[n][IDX_M13] for n in range(4)}, ns

# ---- the K3-tail one-fold ---------------------------------------------------
def _K_pf(t):
    """Local-series factory for K(u,t) = -A_s[m18->m13]|_{d=4}(s=-u-t,t):
       9743/(660(u+t)) + 8/(15u) - 21/(u-4) - 35/(2(u-4)^2) + 87/(22(u-16))."""
    t = mp.mpf(t)
    simple = [(mp.mpf(9743)/660, -t), (mp.mpf(8)/15, mp.mpf(0)),
              (mp.mpf(-21), mp.mpf(4)), (mp.mpf(87)/22, mp.mpf(16))]
    c2, p2 = mp.mpf(-35)/2, mp.mpf(4)
    def ser(u0, NT):
        out = []
        for l in range(NT):
            v = mp.mpc(0)
            for (c, p) in simple: v += c*(-1)**l/(u0-p)**(l+1)
            v += c2*(-1)**l*(l+1)/(u0-p2)**(l+2)
            out.append(v)
        return out
    return ser

def _K_eval(u, t):
    return (mp.mpf(9743)/660/(u+t) + mp.mpf(8)/15/u - 21/(u-4)
            - mp.mpf(35)/2/(u-4)**2 + mp.mpf(87)/22/(u-16))

def k3tail(s, t, dps=50, detour_r=0.5):
    """Tail(s,t) = INT_{Gamma(2->u)} K(u',t) m13^(0)(u') du' (Engine A:
    co-transported Taylor accumulator).  Returns (J, m13(u), nsteps)."""
    if t == -2:                       # 2026-07-08 small-u fix (see CHANGELOG)
        raise ValueError(
            'k3tail: t = -2 puts the kernel pole u\' = -t exactly ON the '
            'one-fold basepoint u\' = 2 (s\'=0 letter through the basepoint): '
            'the one-fold has a logarithmic endpoint divergence there and is '
            'not evaluable in this representation.  Any other t in the '
            'documented domain works (near-pole cost ~log(1/|t+2|)).')
    work = dps + 15
    s, t = mp.mpf(s), mp.mpf(t); u = -(s+t)
    Y1, _, _, _, _ = mum_seed_state(work)
    _, Ms, Dc = _numeric_blocks(work)
    radset = [mp.mpc(p) for p in sorted({0.0, 4.0, 16.0, float(-t)})]
    # leg 1: u*=1 -> 2 (no accumulator; basepoint of the one-fold is u'=2).
    # 2026-07-08 small-u fix: leg 1 carries NO kernel series, so its step
    # control needs only the DE singularities {0,4,16}; the kernel pole -t
    # is kept ONLY when -t > 2 (off this leg -- preserves the byte-exact
    # step sequence of every previously-working point).  With the shared
    # radset, -t in (1,2] sat ON the leg-1 path and the adaptive stepper
    # could never cross it (h -> 0 stall; the reported u=3/3.5 failures).
    rad1 = [mp.mpc(p) for p in
            sorted({0.0, 4.0, 16.0} | ({float(-t)} if float(-t) > 2
                                       else set()))]
    Y2, _, n1 = _transport([r[:] for r in Y1], [], [mp.mpc(1), mp.mpc(2)],
                           work, Ms, Dc, [], rad1)
    poles = [p for p in (4.0, 16.0, float(-t)) if 2 < p < float(u)]
    pth = _build_path(2, float(u), sorted(set(poles)), r=detour_r)
    Yv, J, n2 = _transport(Y2, [mp.mpc(0)], pth, work, Ms, Dc, [_K_pf(t)], radset)
    return J[0], Yv[3][IDX_M13], n1+n2

def k3tail_quad(s, t, dps=40, degree=6):
    """Engine B: same contour, composite Gauss-Legendre; m13 by sequential
    marching of the SAME tower (independent integration discretization)."""
    from mpmath.calculus.quadrature import GaussLegendre
    if t == -2:                       # 2026-07-08 small-u fix (see CHANGELOG)
        raise ValueError(
            'k3tail_quad: t = -2 puts the kernel pole u\' = -t exactly ON '
            'the one-fold basepoint u\' = 2 (endpoint divergence; the '
            'transport would stall at rad=0) -- refused, same locus as '
            'k3tail.')
    work = dps + 15
    s, t = mp.mpf(s), mp.mpf(t); u = -(s+t)
    Y1, _, _, _, _ = mum_seed_state(work)
    _, Ms, Dc = _numeric_blocks(work)
    radset = [mp.mpc(p) for p in sorted({0.0, 4.0, 16.0, float(-t)})]
    # 2026-07-08 small-u fix: same leg-1 radset split as k3tail (no kernel
    # series on this leg; -t in (1,2] on the path = h->0 stall).
    rad1 = [mp.mpc(p) for p in
            sorted({0.0, 4.0, 16.0} | ({float(-t)} if float(-t) > 2
                                       else set()))]
    Yb, _, _ = _transport([r[:] for r in Y1], [], [mp.mpc(1), mp.mpc(2)],
                          work, Ms, Dc, [], rad1)
    poles = [p for p in (4.0, 16.0, float(-t)) if 2 < p < float(u)]
    pth = _build_path(2, float(u), sorted(set(poles)))
    gl = GaussLegendre(mp.mp)
    nodes = sorted(gl.calc_nodes(degree, mp.mp.prec), key=lambda nw: mp.re(nw[0]))
    total = mp.mpc(0); Ycur = Yb; ucur = mp.mpc(2)
    for a, b in zip(pth[:-1], pth[1:]):
        mid, half = (a+b)/2, (b-a)/2
        seg = mp.mpc(0)
        for (x, wgt) in nodes:
            un = mid + half*x
            Ycur, _, _ = _transport(Ycur, [], [ucur, un], work, Ms, Dc, [], radset)
            ucur = un
            seg += wgt*_K_eval(un, t)*Ycur[3][IDX_M13]
        total += half*seg
    return total

def f(s, t, dps=50):
    """Public API: the shipped final-form pieces at Euclidean (s,t), u=-s-t
    in (2,50].  Returns dict with the m13 tower, the K3-tail one-fold, the
    exact kernel value, and m18's closed-form pole 2*zeta3."""
    mp.mp.dps = dps + 15
    sF, tF = Fraction(str(s)), Fraction(str(t)); uF = -sF - tF
    assert sF < 0 and tF < 0 and 2 < -sF-tF <= 50, \
        'domain: Euclidean s<0, t<0 with u=-s-t in (2,50]'
    if tF == -2:                      # 2026-07-08 small-u fix (see CHANGELOG)
        raise ValueError(
            't = -2: the kernel pole u\' = -t coincides with the k3tail '
            'one-fold basepoint u\' = 2 (the s\'=0 letter passes through '
            'the basepoint), so the one-fold piece has a logarithmic '
            'endpoint divergence and the point is not evaluable in this '
            'representation.  Any other t with s<0, t<0, u=-s-t in (2,50] '
            'works (near-pole cost grows ~log(1/|t+2|)); refused BEFORE '
            'any transport (fail-closed, exit 2 via the --point arm).')
    tw, _ = m13_tower(-(mp.mpf(s)+mp.mpf(t)), dps=dps)
    J, m13u, _ = k3tail(s, t, dps=dps)
    kv = (Fraction(9743, 660)/sF - Fraction(8, 15)/uF + 21/(uF-4)
          + Fraction(35, 2)/(uF-4)**2 - Fraction(87, 22)/(uF-16))
    return {'m13_tower': tw, 'k3tail_onefold': J, 'm13_at_u': m13u,
            'kernel_As_m18_m13_d4': kv, 'm18_em1': 2*mp.zeta(3),
            'contour': 'u\'=2 -> u, +i box detours at {4,16,-t}'}

# =====================================================================
# ORACLE STRINGS (archived artifacts; paths + sha256[:16]; never used in
# any fit that produced the constants above, except ic2 as flagged).
# =====================================================================
# <archive>/lbl3x_bootstrap/BAN_EVAL_VALIDATE.json sha=747fe0203e59e35c
#   ("ref" = direct AMFlow evaluations of the banana family, goal ~65)
BAN_HELDOUT = [
 ('3.0',  '10.124987754194821418584688365176826498892478'),
 ('5.5',  '7.8466759020331097309745439187250186035308624'),
 ('11.0', '-3.37429647160185966996593628202591585327832003'),
]
# <archive>/lbl3x_bootstrap/K3TAIL_COLUMNS.json sha=dccf256ded1e33db (55 d,
# ban_eval transport from AMFlow base points out_ic{2,6,10,18,26,50} -- an
# INDEPENDENT route: different seed (AMFlow base points), different engine)
M13_CROSS = [
 (-14.0, -3.0,  '-24.014251997323332214764639613876764478728284392547162',
                '0.001381837887141278422478120377835836597450342427488058166'),
 (-25.0, -25.0, '-227.6237295285195228018692139942455189708151897517060049',
                '96.60911896121353107099851876399109878855810332838570352'),
]
# <archive>/lbl3x_fulla/ring15_pslq/out_ic2_hi.json sha=d9d66f4ac1b6b09e
# (AMFlow goal-220 at u=2; the 3 MUM constants were SOLVED against this
# vector -- printed as an internal-consistency reproduction, NOT a gate)
IC2_M13E0 = '10.509239356694183397882731867492244189510773092773683870325'
# <archive>/lbl3x_bootstrap/R5_ray_amflow/out/*_ferm.json -- the five withheld
# withheld points of the m^2-DE 33.95-38.51 d gate (m18 = I(1,1,1,1,1,1)):
R5_M18_EM1 = {
 (-25, -25): '2.40411380631918857079947632302289998152997258468099776357710265351066',
 (-11, -2):  '2.40411380631918857079947632302289998152997258468099776357710206522040',
 (-14, -3):  '2.40411380631918857079947632302289998152997258468099776357710200186192',
 (-23, -10): '2.40411380631918857079947632302289998152997258468099776357710206032610',
 (-25, -11): '2.40411380631918857079947632302289998152997258468099776357710213990302',
}
# Rm ray (t/s = 1/2, lambda = 2..12, (s,t) = lambda*(-1,-1/2)) m18/m34/m35
# eps^0 for the Euler check (same archived R5 directory):
RM_RAY = {
 2:  ('-10.286236339712260153419108269264767932959628343030852608',
      '-1.7923028872281730311349318342118514895449647796872096678',
      '-1.7826192586407684865728247571127711768599057587030886936'),
 4:  ('-10.342642782924237722984211289456331356708052360063441476',
      '-1.7865627584321175967029056160962498794997699105292110883',
      '-1.7691606668585968224303160662804593495486294704308993046'),
 6:  ('-10.387269041176259742858930685511463673697104485566573877',
      '-1.7858943070510005659275253919866378931510282275556731820',
      '-1.7620584425948183214501854091361681509788070742797855206'),
 8:  ('-10.420138000588583079473002145208474566497095018353497268',
      '-1.7910031979264975353746347892027189576292915675812558020',
      '-1.7616154076618176644795811084603149081949189073490914460'),
 10: ('-10.440246955373301616235019775217114116201049757641306758',
      '-1.8040810702261023217533368679502825973754581167309235886',
      '-1.7697535532836032562481900247067568071775393078368109300'),
 12: ('-10.443644631712537901292593093123279342016416109426356619',
      '-1.8338256661567386715977213853806955753547115153386712045',
      '-1.7949532630205719897181127122371035409443491193404084874'),
}

def _digits(a, b):
    a, b = mp.mpc(a), mp.mpc(b)
    if a == b: return mp.inf
    return float(-mp.log10(abs(a-b)/max(abs(b), mp.mpf('1e-30'))))

def _gate_check(label, checks):
    # 2026-07-05 rc-failclosed sweep (charter v2 clause 4): a below-bar
    # withheld agreement must set a NONZERO EXIT CODE, not just print.
    # checks = [(desc, measured_d, bar_d), ...]; prints ONE summary line
    # on pass, raises RuntimeError naming every below-bar entry on fail.
    bad = [(ds, d, b) for (ds, d, b) in checks if not (d >= b)]
    if bad:
        raise RuntimeError(
            '%s GATE FAIL (below bar => nonzero exit): ' % label
            + '; '.join('%s %.1f d < bar %.1f d' % x for x in bad))
    worst = min(d - b for (_, d, b) in checks)
    print('    [gate] %s: %d/%d agreements >= bar (worst margin +%.1f d; '
          'below-bar RAISES, rc!=0)' % (label, len(checks), len(checks), worst))

# =====================================================================
def run_gates(full=False):
    print('='*74)
    print('LBL3X final-form evaluator -- gate suite (all agreements computed live)')
    print('='*74)

    # (1) exact base point + kernel identity ---------------------------------
    mp.mp.dps = 60
    L2 = mp.log(2)
    Vb = (6*mp.zeta(3) - 22*mp.zeta(4) - 8*mp.zeta(2)*L2**2
          + mp.mpf(4)/3*L2**4 + 32*mp.polylog(4, mp.mpf(1)/2))
    print('\n(1) EXACT BASE-POINT VALUES')
    print('    m18^(0)(0,0) = Vbar_4N - 6*gammaE*zeta3 =',
          mp.nstr(Vb - 6*mp.euler*mp.zeta(3), 40))
    # kernel transcription integrity: the verified 5-term partial fractions
    # (archived: phase2.py A_kernel_verification -- 6 rational points on the
    # t=-5 slice vs the reduction; also the k3tail tooling record) == their
    # single-fraction form over 660*s*(s+t)*(s+t+4)^2*(s+t+16).
    # [The rational display in archived K3_TAIL_ALPHABET.md does NOT match --
    #  that md predates the bug21v5 operator audit; the PF residues are the
    #  verified record.]
    NUMC = {(4, 0): -1155, (3, 1): 6278, (3, 0): -2490, (2, 2): 25764,
            (2, 1): 228852, (2, 0): 793200, (1, 3): 28074, (1, 2): 465174,
            (1, 1): 2196192, (1, 0): 2584320, (0, 4): 9743, (0, 3): 233832,
            (0, 2): 1402992, (0, 1): 2494208}
    ok = True
    for (sq, tq) in ((Fraction(-7), Fraction(-3)), (Fraction(-9, 2), Fraction(-13, 5)),
                     (Fraction(-31, 7), Fraction(-1, 3))):
        uq = -sq - tq
        pf = (Fraction(9743, 660)/sq - Fraction(8, 15)/uq + 21/(uq-4)
              + Fraction(35, 2)/(uq-4)**2 - Fraction(87, 22)/(uq-16))
        num = sum(c*sq**a*tq**b for (a, b), c in NUMC.items())
        ok &= (pf == num/(660*sq*(sq+tq)*(sq+tq+4)**2*(sq+tq+16)))
    print('    kernel A_s[m18->m13]|_{d=4}: 5-term PF == single-fraction form')
    print('    at 3 rational (s,t): %s (exact Fraction arithmetic)'
          % ('PASS' if ok else 'FAIL'))
    assert ok

    # (2) Domb dimension-shift identity (exact rational, live) ----------
    print('\n(2) K3 GEOMETRY = DOMB (A002895), EXACT + LIVE')
    t0 = time.time()
    KT = 36
    # exact homogeneous towers seeded by each MUM kernel vector
    M00 = [[Fraction(0)]*N for _ in range(N)]
    for (i, jj, cl) in MQ[0]: M00[i][jj] = cl[0]
    def solve_exact(k, rhs):
        x = [Fraction(0)]*DIM
        for r in range(NEPS):
            rr = [rhs[r*N+i] for i in range(N)]
            for m in range(1, min(r, 3)+1):
                for (i, jj, cl) in MQ[m]:
                    if cl[0] != 0: rr[i] += cl[0]*x[(r-m)*N+jj]
            Aug = [[(Fraction(64*k) if a == b else Fraction(0)) - M00[a][b]
                    for b in range(N)] + [rr[a]] for a in range(N)]
            for c in range(N):
                p = next(a for a in range(c, N) if Aug[a][c] != 0)
                Aug[c], Aug[p] = Aug[p], Aug[c]
                iv = 1/Aug[c][c]; Aug[c] = [v*iv for v in Aug[c]]
                for a in range(N):
                    if a != c and Aug[a][c] != 0:
                        fc = Aug[a][c]
                        Aug[a] = [v-fc*w for v, w in zip(Aug[a], Aug[c])]
            for a in range(N): x[r*N+a] = Aug[a][N]
        return x
    hs = []
    for q in range(3):
        ser = [[Fraction(0)]*DIM, [Fraction(x) for x in KVEC[q]]]
        for k in range(2, KT):
            rhs = [Fraction(0)]*DIM
            for j in range(1, 5):
                if k-j >= 0:
                    v = ser[k-j]
                    for m in range(4):
                        for (i, jj, cl) in MQ[m]:
                            if j < len(cl) and cl[j] != 0:
                                for r in range(m, NEPS):
                                    rhs[r*N+i] += cl[j]*v[(r-m)*N+jj]
            rhs = [a+20*(k-1)*b for a, b in zip(rhs, ser[k-1])]
            rhs = [a-(k-2)*b for a, b in zip(rhs, ser[k-2])]
            ser.append(solve_exact(k, rhs))
        hs.append([ser[k][3*N+IDX_M13] for k in range(KT)])
    assert all(all(c == 0 for c in hs[q]) for q in (1, 2)), \
        'kernel directions 1,2 must not feed m13'
    print('    only kernel direction 0 feeds m13 eps^0 (dirs 1,2 identically 0')
    print('    through u^%d, exact) => ONE named K3 constant C0 enters m13' % (KT-1))
    # Domb generator (vendored from files/banana/banana-evaluate.py)
    Dm = [Fraction(1), Fraction(4)]
    for n in range(1, KT):
        Dm.append((2*(2*n+1)*(5*n*n+5*n+2)*Dm[n] - 64*n**3*Dm[n-1])
                  / Fraction((n+1)**3))
    assert Dm[:5] == [1, 4, 28, 256, 2716]
    w = [Dm[k]/Fraction(64)**k for k in range(KT)]
    tw = [j*w[j] for j in range(KT)]        # theta w
    t2w = [j*j*w[j] for j in range(KT)]     # theta^2 w
    DS = SEED['domb_shift_identity']
    A4, B4, C4 = ([Fraction(c) for c in DS[k]] for k in ('A', 'B', 'C'))
    h = hs[0]
    def conv(P, gg, k):
        return sum(P[i]*gg[k-i] for i in range(len(P)) if 0 <= k-i < KT)
    nfail = 0
    for k in range(KT):
        # coeff of u^k: LHS 144*u*h -> 144*h[k-1]; RHS A w + B (th w) + C (th^2 w)
        lhs = 144*h[k-1] if k >= 1 else Fraction(0)
        if lhs != conv(A4, w, k) + conv(B4, tw, k) + conv(C4, t2w, k):
            nfail += 1
    print('    dimension-shift identity 144 u h = P_A w + P_B (theta w) + P_C')
    print('    (theta^2 w), w = varpi0(u/64):  %d/%d orders EXACT (%.1fs)'
          % (KT-nfail, KT, time.time()-t0))
    assert nfail == 0
    print('    => m13^(0)(u) = closed {1,pi^2,zeta3} series + C0 * h(u),')
    print('       C0 = %s... (named; PSLQ-null vs conductor-15 CM ring)'
          % CONSTS[0][:30])

    # (3) m13 evaluator + gates ------------------------------------------
    print('\n(3) m13(u) PF-SERIES EVALUATOR (dps 50, working 65)')
    t0 = time.time()
    Y1, res0, tl, KM, sbnd = mum_seed_state(65)
    print('    MUM seed: closed u=0 tower, B0.a0 frame residual = %.1e,' % res0)
    print('    %d series terms, tail %.1e at u*=1 (%.1fs)' % (KM, tl, time.time()-t0))
    print('    certified seed-tail BOUND %.2e < tol 1.0e-%d (trailing-%d window'
          % (sbnd, 65+SEED_TAIL_GUARD, SEED_TAILWIN))
    print('    max * r/(1-r), r<=1/4 from the u=4 singularity; RAISES on miss)')
    # towers at the gate points (computed once each)
    t0 = time.time()
    towers = {us: m13_tower(mp.mpf(us), dps=50)[0] for (us, _) in BAN_HELDOUT}
    # pole closed forms (e^{3 gamma eps}-stripped normalization), exact in u:
    g = mp.euler; pi2 = mp.pi**2
    pole_min = mp.inf
    for us in ('3.0', '11.0'):
        uv = mp.mpf(us); tw = towers[us]
        for n, closed in ((-3, mp.mpf(2)),
                          (-2, mp.mpf(23)/3 - uv/3),
                          (-1, (315 - 27*uv + uv**2/2 + 9*pi2)/18)):
            st = sum((3*g)**k/mp.factorial(k)*tw[n-k] for k in range(n+4))
            pole_min = min(pole_min, _digits(st, closed))
    print('    pole orders vs EXACT closed u-polynomials (eps^-3,-2,-1 at')
    print('    u=3,11; e.g. eps^-1 = (315-27u+u^2/2+9pi^2)/18): >= %.1f d' % pole_min)
    gates = []
    g3 = []          # rc-failclosed sweep: (desc, measured d, bar) triples
    for (us, ref) in BAN_HELDOUT:
        d = _digits(towers[us][0], mp.mpf(ref))
        gates.append(d)
        g3.append(('m13^(0)(u=%s) vs withheld AMFlow' % us, d, 38.0))
        print('    m13^(0)(u=%-4s) = %-28s  %.1f d vs WITHHELD AMFlow (44-46d strings)'
              % (us, mp.nstr(towers[us][0].real, 22), d))
    if full:
        for (sv, tv, rre, rim) in M13_CROSS:
            uv = -(sv+tv)
            tw, ns = m13_tower(mp.mpf(uv), dps=50)
            ref = mp.mpc(mp.mpf(rre), mp.mpf(rim))
            d = _digits(tw[0], ref)
            gates.append(d)
            g3.append(('m13^(0)(u=%g) vs cross-route' % uv, d, 44.0))
            print('    m13^(0)(u=%-4g) = %s  %.1f d vs archived 55d cross-route'
                  % (uv, mp.nstr(tw[0], 20), d))
    else:
        print('    (the deeper u=17 and u=50 cross-checks run under '
              '--full)')
    tw2, _ = m13_tower(mp.mpf(2), dps=50)
    print('    m13^(0)(u=2) reproduction vs ic2 (constants solved there): %.1f d'
          % _digits(tw2[0], mp.mpf(IC2_M13E0)))
    print('    (%.1fs)' % (time.time()-t0))
    # bars = min(oracle-string digits, dps 50) - 6 guard (44d strings -> 38;
    # 55d cross-route strings, dps-50-capped -> 44); a 1e-30 mutation of any
    # archived string (~30 d agreement) lands far below bar.
    _gate_check('(3) m13 withheld', g3)

    # (4) the K3-tail one-fold -------------------------------------------
    print('\n(4) K3-TAIL ONE-FOLD Tail(s,t) = INT K(u\',t) m13^(0)(u\') du\'')
    print('    contour: u\'=2 -> u, +i detours at {4,16,-t}; -t is the s\'=0')
    print('    letter -- the genuinely 2-variable pole of the tail.')
    results = {}
    g4 = []          # rc-failclosed sweep: (desc, measured d, bar) triples
    for (sv, tv) in (((-8, -4), (-14, -3)) if full else ((-8, -4),)):
        t0 = time.time()
        JA, m13u, ns = k3tail(sv, tv, dps=50)
        JA2, _, _ = k3tail(sv, tv, dps=35)
        d2p = _digits(JA2, JA)
        results[(sv, tv)] = JA
        g4.append(('Tail(%d,%d) two-precision' % (sv, tv), d2p, 29.0))
        print('    Tail(%d,%d) = %s' % (sv, tv, mp.nstr(JA, 30)))
        print('      two-precision (dps 35 vs 50): %.1f d stable  (%d steps, %.1fs)'
              % (d2p, ns, time.time()-t0))
    if full:
        t0 = time.time()
        JB = k3tail_quad(-8, -4, dps=40, degree=6)
        dAB = _digits(JB, results[(-8, -4)])
        g4.append(('Tail(-8,-4) cross-method', dAB, 32.0))
        print('    Engine B (composite Gauss-Legendre, same contour, '
              'dps 40):')
        print('      Tail(-8,-4) cross-method agreement: %.1f d  (%.1fs)'
              % (dAB, time.time()-t0))
        t0 = time.time()
        JC, _, _ = k3tail(-8, -4, dps=45, detour_r=0.8)
        dr = _digits(JC, results[(-8, -4)])
        g4.append(('contour deformation 0.5->0.8', dr, 37.0))
        print('    contour deformation (detour radius 0.5 -> 0.8): '
              '%.1f d invariant' % dr, ' (%.1fs)' % (time.time()-t0))
    else:
        print('    (Tail(-14,-3), the engine-B cross-method and the '
              'contour-deformation')
        print('    legs run under --full)')
    # bars = the cheaper engine's own dps (35/40/45) minus a 6-8 d guard
    # (agreement is capped by the lower-dps leg, never by the dps-50 run).
    _gate_check('(4) K3-tail cross-checks', g4)

    # (5) m18 pole vs the five withheld oracle points ---------------------
    mp.mp.dps = 80
    print('\n(5) m18 eps^-1 = 2*zeta3 (closed form) vs ALL FIVE withheld')
    print('    AMFlow points of the m^2-DE 33.95-38.51d gate (withheld):')
    z2 = 2*mp.zeta(3)
    for (pt, ref) in R5_M18_EM1.items():
        print('      (s,t)=(%d,%d): %.1f d' % (pt[0], pt[1], _digits(z2, mp.mpf(ref))))

    # (6) Euler identity ---------------------------------------------------
    print('\n(6) EULER IDENTITY (s d_s + t d_t) m18^(0) = -2 Delta,')
    print('    Delta = m34 + m35 + 3 zeta3   [exact IBP identity]')
    lams = [2, 4, 6, 8, 10, 12]
    m18v = [mp.mpf(RM_RAY[l][0]) for l in lams]
    der = mp.mpf(0)
    for i, li in enumerate(lams):
        ssum = mp.mpf(0)
        for k, lk in enumerate(lams):
            if k == i: continue
            p = mp.mpf(1)
            for j, lj in enumerate(lams):
                if j in (i, k): continue
                p *= mp.mpf(8-lj)/(li-lj)
            ssum += p/(li-lk)
        der += ssum*m18v[i]
    lhs = 8*der
    delta = mp.mpf(RM_RAY[8][1]) + mp.mpf(RM_RAY[8][2]) + 3*mp.zeta(3)
    print('    on the archived Rm ray (t/s=1/2, 6 oracle points, deriv at (-8,-4)):')
    print('    lam d(m18)/dlam = %s   -2*Delta = %s   agree %.1f d'
          % (mp.nstr(lhs, 10), mp.nstr(-2*delta, 10), _digits(lhs, -2*delta)))
    print('    (agreement limited by the 6-point Lagrange derivative, not the')
    print('     identity; it fixes the -2 and the +3 zeta3 in Delta)')
    print('    Delta at (0,0) = 0 and m18^(0)(0,0) = the part-(1) closed form.')
    print('    NOTE: the page\'s reference value m18^(0)(-8,-4) = %s...'
          % RM_RAY[8][0][:12])
    print('    is a STORED comparison value -- the RM_RAY[8] oracle string, '
          'consumed')
    print('    by this part as an input.  No run of this gate suite '
          '(default or')
    print('    --full) recomputes it; the --m18-eps0 arm re-derives the '
          'full value')
    print('    live at the certified on-curve points.')

    print('\n    >>> THE DELTA GAP (what is NOT shipped): Delta itself -- the')
    print('    polylog remainder of m18 eps^0 -- is a 25-row VoP of the top')
    print('    block sourced by m13 via A_s[17][38] = 2/s.  Its eps-graded')
    print('    kernels (symbolic_de.json) were purged in the 2026-07-02 reorg;')
    print('    only the d=4 row-17->13 kernel above is archived in closed form.')
    print('    Full m18^(0)(s,t) therefore is NOT evaluable here; the archived')
    print('    gates (49.8d taylor41; 33.95-38.51d m^2-DE, 5 pts) stand.')

def run_block13():
    # ==================================================================
    # (7) closed 13-master polylog lower block: LIVE eps-graded transport
    # on the shipped exact-rational on-curve kernel (round-1 machinery,
    # kept verbatim in method; provenance in comments below).
    # Kernel: rows<=12 of <archive>/lbl3x_fulla/final_assembly/altgate/
    #   oncurve_M_ALTB_patched.json (exact rational P/Q in s on the curve
    #   1/s+1/t=-3/8; block-triangular, self-contained).
    # Seed: lbl3x-block13-boundary.json = m^2-DE v3 towers at P=(-6,-24/5)
    #   (towers_Rm6_K8_dps65; NOT an AMFlow value).  FINAL-FORM CAVEAT:
    #   these seed towers are certified stored numerics (~65 d) -- the one
    #   piece of this script whose precision does NOT scale with dps.
    #   Banked CLOSED forms exist for the S/T-banana + tadpole boundary
    #   constants (pure zeta, 6^(n+4) denominators: <archive>/lbl3x_fulla/
    #   {gate_report_S,gate_report_T}.json, consts/) and the 13 masters are
    #   ALL classified GPL with archived word lists (MASTERS_0_12_CLASSIFY,
    #   closure_final/CLOSURE_5_11_TRI.json, 140,470 words, letters
    #   Q(sqrt5)); the word-list evaluator is not vendored here.
    # Oracle: independent AMFlow at withheld Q=(-8,-4)
    #   (<archive>/lbl3x_fulla/final_assembly/altgate/boundary41_END.json).
    # ==================================================================
    print('\n(7) LOWER POLYLOG BLOCK: live 13-master transport P=(-6,-24/5)')
    print('    --[1/s+1/t=-3/8]--> Q=(-8,-4), vs independent AMFlow at Q')
    def _fx(sv, B):
        f = Fraction(sv) if '/' in sv or ('.' not in sv and 'e' not in sv.lower()) \
            else Fraction(Decimal(sv))
        return (f.numerator << B) // f.denominator
    def _hshift(coeffs, s0, Nn, B):
        out = [0]
        for c in reversed(coeffs):
            L = len(out); Ln = min(L+1, Nn+1)
            new = [0]*Ln
            for m in range(L):
                v = out[m]
                if v:
                    new[m] += (v*s0) >> B
                    if m+1 < Ln: new[m+1] += v
            if c is not None: new[0] += c
            out = new
        return out + [0]*max(0, Nn+1-len(out))
    def _entry_series(P, Q, s0, Nn, K, B):
        p = [_hshift(r, s0, Nn, B) for r in P] + [[0]*(Nn+1) for _ in range(K-len(P))]
        q = [_hshift(r, s0, Nn, B) for r in Q] + [[0]*(Nn+1) for _ in range(K-len(Q))]
        qnz = [(k, m, q[k][m]) for k in range(K) for m in range(Nn+1)
               if q[k][m] and (k, m) != (0, 0)]
        q00 = q[0][0]
        assert q00 != 0, 's0 on kernel pole'
        inv00 = (1 << (2*B))//q00
        b = [[0]*(Nn+1) for _ in range(K)]
        b[0][0] = inv00
        for m in range(Nn+1):
            for k in range(K):
                if (k, m) == (0, 0): continue
                acc = 0
                for (ka, ma, qv) in qnz:
                    if ka <= k and ma <= m: acc += qv*b[k-ka][m-ma]
                if acc: b[k][m] = -((inv00*acc) >> (2*B))
        c = [[0]*(Nn+1) for _ in range(K)]
        for kp in range(K):
            prow = p[kp]
            for mp_ in range(Nn+1):
                pv = prow[mp_]
                if not pv: continue
                for k in range(K-kp):
                    brow = b[k]; crow = c[kp+k]
                    for m in range(Nn+1-mp_):
                        bv = brow[m]
                        if bv: crow[mp_+m] += pv*bv
        out = []
        for kc in range(K):
            row = [v >> B for v in c[kc]]
            if any(row): out.append((kc, row))
        return out
    KER = json.loads(gzip.open(os.path.join(HERE, 'lbl3x-block13-kernel.json.gz'),
                               'rt').read())
    BND = json.load(open(os.path.join(HERE, 'lbl3x-block13-boundary.json')))
    def transport13(Nn, B):
        K, KMIN, NM = 7, -3, 13
        ENT = []
        for key, e in sorted(KER['block'].items()):
            i, j = map(int, key.split(',')[:2])
            P = [[None if c == '0' else _fx(c, B) for c in r] for r in e['P']]
            Q = [[None if c == '0' else _fx(c, B) for c in r] for r in e['Q']]
            ENT.append((i, j, P, Q))
        poles = [complex(p) for p in KER['poles_eps0']]
        Y = [[_fx(BND['towers'][str(i)].get(str(k+KMIN), '0'), B) for k in range(K)]
             for i in range(NM)]
        s_cur, s_end = Fraction(-6), Fraction(-8)
        DIR = -1
        nstep = 0
        while s_cur != s_end:
            dist = min(abs(p-complex(s_cur)) for p in poles)
            rem = abs(float(s_end-s_cur))
            h_try = 0.20*dist
            s1 = s_end if rem <= h_try else s_cur + DIR*Fraction(int(h_try*1024), 1024)
            s0fx = _fx(str(s_cur), B); hfx = _fx(str(s1-s_cur), B)
            C = []
            for (i, j, P, Q) in ENT:
                rows = _entry_series(P, Q, s0fx, Nn, K, B)
                if rows: C.append((i, j, rows))
            ys = [[[Y[i][k]] for k in range(K)] for i in range(NM)]
            for n in range(Nn):
                new = [[0]*K for _ in range(NM)]
                for (i, j, crows) in C:
                    yj = ys[j]; newi = new[i]
                    for (kc, row) in crows:
                        for ky in range(K-kc):
                            col = yj[ky]
                            acc = 0
                            for m_ in range(min(len(row), n+1)):
                                cv = row[m_]
                                if cv: acc += cv*col[n-m_]
                            if acc: newi[kc+ky] += acc
                for i in range(NM):
                    for k in range(K):
                        ys[i][k].append((new[i][k] >> B)//(n+1))
            hp = [1 << B]
            for _ in range(Nn): hp.append((hp[-1]*hfx) >> B)
            for i in range(NM):
                for k in range(K):
                    Y[i][k] = sum((ys[i][k][m_]*hp[m_]) >> B for m_ in range(Nn+1))
            nstep += 1
            s_cur = s1
            assert nstep < 60
        return {i: {k-3: mp.ldexp(mp.mpf(Y[i][k]), -B) for k in range(7)}
                for i in range(13)}, nstep
    # independent withheld oracle at Q=(-8,-4): AMFlow (arXiv:2201.11669),
    # archived boundary41_END.json (provenance inside names raw out.json+kira);
    # 60-digit truncations; never used in the transport above.
    ORACLE_Q = {
     0: {-1: "6.85422754348530588627604222334897181289351675253952795366188",
          0: "11.0008364639032740430391615384690656254366458711891799711606"},
     1: {-1: "16.7635757697783967766755019352737424087061617521330166698293",
          0: "27.1323133037686541596299716560437455316367296268856830331521"},
     2: {-1: "-2.20194902656518924759866566830938382187803547821659856757283",
          0: "-2.94922964469820767343476724545602878890236612991643103685183"},
     3: {-1: "4.77176077329327794368270655282601492441636795947421911153018",
          0: "5.17007887512128777716758616277718287843597266090976792293524"},
     4: {-1: "11.6284288576878543260892439181386644610667819599498614136579",
          0: "24.0813231825787733537971037880022062924763692744633061313644"},
     5: {-1: "36.0854949786264780381137475339399063129137002379874057369145",
          0: "54.0758546580477933466955682319098019229428428629174042149294"},
     6: {-1: "-2.73144905684357325062832909624820260012386530785726235815355",
          0: "-6.16457627862459080533963649458349780920975720695918194651835"},
     7: {-1: "3.67532553995503827415573307018044334164450209108604181794008",
          0: "8.09855071345321582088277627097572536190463517553470650605076"},
     8: {-1: "3.75254120485657113476224516026284577268666142702596541674585",
          0: "8.96920496146185182452256833861646126416509358488241345074919"},
     9: {-1: "0.729007385923110772473736333418081074747996173848750110255607",
          0: "1.40362566284030838512433273405380455323327476678420308652070"},
     10: {-1: "10.9617621910211876594225772514719977944001152932831947469912",
          0: "26.7644783042683155324887288552658724367211098459563946508738"},
     11: {-1: "21.4062229516242563362676050842581788317434906152807630547985",
          0: "27.7933952221086402775888225896031570522181285679097896517321"},
     12: {-1: "-6.73186771727238968663389097061131993208148452954674758953961",
          0: "-17.3620987086274093055948107267866743257134452237167166598003"},
    }
    mp.mp.dps = 130
    t0 = time.time()
    RES, ns = transport13(64, 448)
    gd = []
    for i in range(13):
        for o in (-1, 0):
            gd.append(min(_digits(RES[i][o], mp.mpf(ORACLE_Q[i][o])), 60.0))
    print('    %d steps, %.1fs; 26 gates (eps^-1,0 x 13): min/med %.1f / %.1f d'
          % (ns, time.time()-t0, min(gd), sorted(gd)[len(gd)//2]))
    t0 = time.time()
    RES2, _ = transport13(48, 352)
    dd2 = min(_digits(RES2[i][0], RES[i][0]) for i in range(13))
    print('    two-precision (N=48,2^352 vs N=64,2^448): >= %.1f d (%.1fs)'
          % (dd2, time.time()-t0))
    print('    NOTE: floors at the stored seed accuracy (8.7 d/order alias:')
    print('    ~68/59/50/41 d at eps^-3..0) -- see the final-form caveat above.')
    # rc-failclosed sweep: fixed-precision block (dps 130, N=64, 2^448);
    # bars = the documented ~41 d eps^0 seed floor minus 3 d guard, and the
    # measured 38.5 d two-precision agreement minus 3.5 d guard.
    _gate_check('(7) block13 vs independent AMFlow',
                [('min over 26 eps^-1,0 gates', min(gd), 38.0),
                 ('two-precision N=48 vs N=64', dd2, 35.0)])

def run_doubling():
    # ==================================================================
    # (8) DPS-DOUBLING DEMO: precision is set ONLY by dps (no node cache
    # anywhere in the PF-series chain).  One gate point -- m13^(0) at
    # u=3, vs the WITHHELD archived AMFlow string -- rerun on the doubling
    # ladder dps = 22 -> 44 -> 88; every agreement recomputed live.
    # ==================================================================
    print('\n(8) DPS-DOUBLING DEMO (gate point u=3, live -log10 agreements)')
    mp.mp.dps = 130
    ref = mp.mpf(BAN_HELDOUT[0][1])          # parse at HIGH dps (footgun)
    cap = sum(ch.isdigit() for ch in BAN_HELDOUT[0][1])
    vals = {}
    for dps in (22, 44, 88):
        t0 = time.time()
        tw, _ = m13_tower(mp.mpf(3), dps=dps)
        vals[dps] = tw[0]
        mp.mp.dps = 130
        print('    dps=%3d: agree %.1f d vs withheld archived string  (%.1fs)'
              % (dps, _digits(tw[0], ref), time.time()-t0))
    print('    doubling 22 -> 44 GROWS the live agreement; at dps 44 and 88 it')
    print('    SATURATES at the stored-oracle-string cap: the archived artifact')
    print('    string has %d significant digits.  The evaluator itself is' % cap)
    print('    uncapped: the dps=44 and dps=88 runs agree to %.1f d (live,'
          % _digits(vals[44], vals[88]))
    print('    beyond the string cap; limited only by the dps+15 working prec).')

# =====================================================================
# PART E: KERNEL-BACKED 41x41 A^s/A^t CONNECTION (LBL3X 2-var kernel-
# regen record, <archive>/solve_row21/kernel2var/RESULT.md at REGISTRY v4 /
# addendum A6; ported 2026-07-05 from the tools/rowscripts/
# eval_row21.py kernel fold).  See the part-E block in the module
# docstring for scope/caps/data split.
# Data: lbl3x-kernel-map.json + lbl3x-kernel-denoms.json (light, always
# loaded on demand) + lbl3x-kernel-manifest.json (sha256 pins).  Heavy
# col banks are NOT shipped with the page; they lazy-load ONLY from the
# local drop-in dir lbl3x-kernel-banks/ and are sha256-verified against
# the vendored manifest before first use (KernelDataError otherwise).
# Semantics of record: <archive>/lbl3x_kernel_regen/ship/asm_atscale.py
# (eval_exact_col / entry_val_exact / entry_val_modp); reimplemented
# standalone (Fraction + pow-mod only; no imports from the archive at runtime).
# Representation (record section 1): entry A^var[i][j](d,s,t) = sum(direct
# prefactors) + sum pre(s,t) * c_{T,Mj}(d,s,t); c = N/D per d-node;
# N = sum coeffs[u] s^(u div (dt+1)) t^(u mod (dt+1)); D = families^rung
# x d-dep exact factors (Qsp/F7lin/P5a/P5b, mirrors via s<->t swap)
# x T2^eT2, T2 = t^2 + d*t + 2*(d-3).
# EVIDENCE-CLASS ENFORCEMENT (record section 4 + A6, in code): evaluating
# an entry outside its class raises KernelClassError -- exact classes
# only via _exact; certified-2prime only mod the 2 fit primes; UNCLOSED
# never.  The per-line-only class is EMPTY at v4 (record A1) and its code
# path does not exist here: _k_light() raises at load if any record
# still carries the tag.
# GATE-2 FRAME CONSTRAINT (record A3, GATE2_LEAK_PROFILE.json): the raw
# (A^s, A^t) pair is NOT a flat 2D connection off-curve (structural
# bug#21-v5 frame leak); the frame-clean object is V = A^s-(t^2/s^2)A^t
# on the 1/s+1/t=const foliation -- kernel_V_exact() below.
# pt_8801 is the withheld fold-gate point (never fit).
# =====================================================================
K_MAP_FILE = os.path.join(HERE, 'lbl3x-kernel-map.json')
K_DEN_FILE = os.path.join(HERE, 'lbl3x-kernel-denoms.json')
K_MAN_FILE = os.path.join(HERE, 'lbl3x-kernel-manifest.json')
K_BANKS_DIR = os.path.join(HERE, 'lbl3x-kernel-banks')   # optional drop-in
# LBL3X-thm witness (21:5x decision): the ONE-NODE exact slice, sliced by
# the kernel-compaction step per
# <archive>/lbl3x_kernel_compact/DESIGN.md.  Contract:
#   lbl3x-kernel-witness/witness_manifest.json =
#     {"nodes_kept": [0], "outputs_sha256":
#      {"slice_n1_exact.pkl.gz": <sha256>, "slice_n1_fits.pkl.gz": <sha256>}}
#   + the two slice files next to it (slice format = slice_probe.py:
#   exact 'coeffs' keyed by ORIGINAL node index; fits 'xs' re-indexed
#   in nodes_kept order).
K_WITNESS_DIR = os.path.join(HERE, 'lbl3x-kernel-witness')
K_WIT_MAN_FILE = os.path.join(K_WITNESS_DIR, 'witness_manifest.json')
K_PRIMES = (2305843009213693951, 2305843009213693967)
K_EXACT_CLASSES = ('direct-exact', 'exact-6prime', 'exact-10prime',
                   'exact-extraprime')
_KC = {}


class KernelClassError(RuntimeError):
    """Entry evaluated outside its recorded evidence class (usage-constraint bug)."""


class KernelDataError(RuntimeError):
    """Heavy kernel col data absent/corrupt or d-node not vendored
    (part E: witness slice / optional full-lattice drop-in)."""


class KernelWitnessError(KernelDataError):
    """LBL3X-thm witness (the one-node exact slice) absent or failing
    its sha-manifest check: the theorem certificate cannot be verified.
    FAIL-LOUD by design (--theorem-check exits nonzero with a named
    message); the evaluator never silently degrades."""


def _k_light():
    """Load map + denominator data (fast, ~1.3 MB); heavy banks stay lazy."""
    if 'M41' in _KC:
        return _KC
    mp_ = json.load(open(K_MAP_FILE))
    dn = json.load(open(K_DEN_FILE))
    assert tuple(int(p) for p in dn['PRIMES']) == K_PRIMES
    M41 = [tuple(x['indices']) for x in mp_['masters']]
    assert len(M41) == 41
    ent = {v: {tuple(map(int, k.split(','))): e
               for k, e in mp_['diffeq_map'][v].items()} for v in ('s', 't')}
    # LOUD v4 guarantee (record A1/A6): the per-line-only class is EMPTY.
    # If ANY vendored record still carries the tag, the bundle is not
    # registry-v4 -- refuse to serve it.
    n_pl = sum((e['class'] == 'per-line-only')
               + sum(1 for tm in e['terms']
                     if tm['target'] != 'DIRECT'
                     and tm.get('class') == 'per-line-only')
               for v in ('s', 't') for e in ent[v].values())
    assert n_pl == 0, (
        f'REGISTRY-v4 VIOLATION: {n_pl} per-line-only tag(s) in vendored '
        f'lbl3x-kernel-map.json -- the class is EMPTY at v4 (record A6); '
        f'this bundle is stale.  Re-vendor from row21_kernel_data/.')
    _KC.update(
        M41=M41, ent=ent,
        NODES=[Fraction(a, b) for a, b in dn['NODES']],
        DDEP={int(k): (v[0], int(v[1])) for k, v in dn['DDEP'].items()},
        DSUP={k: tuple(v) for k, v in dn['DSUP'].items()},
        fams=[{tuple(map(int, k.split(','))): int(c)
               for k, c in mono.items()} for mono in dn['families_mono']],
        fx={k: [Fraction(x) for x in v]
            for k, v in dn['factors_exact'].items()},
        coverage=mp_['coverage_entry_classes'])
    return _KC


def _k_sha256(path):
    import hashlib
    h = hashlib.sha256()
    with open(path, 'rb') as fh:
        for chunk in iter(lambda: fh.read(1 << 22), b''):
            h.update(chunk)
    return h.hexdigest()


def _k_mode():
    """Heavy-data source: 'full' iff BOTH full-lattice banks sit in the
    optional drop-in dir lbl3x-kernel-banks/ (campaign-archive
    override), else 'witness' (the shipped one-node slice)."""
    if 'mode' not in _KC:
        full = all(os.path.exists(os.path.join(K_BANKS_DIR,
                                               f'kernel_{w}.pkl.gz'))
                   for w in ('exact', 'fits'))
        _KC['mode'] = 'full' if full else 'witness'
    return _KC['mode']


def _k_witness_manifest():
    """Load + sanity-check the witness manifest.  FAIL-LOUD if absent:
    the LBL3X-thm certificate has no witness to check."""
    if 'wit_man' not in _KC:
        if not os.path.exists(K_WIT_MAN_FILE):
            raise KernelWitnessError(
                f'LBL3X-thm WITNESS ABSENT: {K_WIT_MAN_FILE} not found.  '
                f'The theorem-certificate witness is the ONE-NODE exact '
                f'slice (~12.5 MB, sha-pinned: slice_n1_exact.pkl.gz + '
                f'slice_n1_fits.pkl.gz + witness_manifest.json; design '
                f'<archive>/lbl3x_kernel_compact/DESIGN.md; '
                f'sliced by the kernel-compaction step from the '
                f'canonical 34-node banks in '
                f'tools/rowscripts/row21_kernel_data/).  Refusing to '
                f'degrade silently (21:5x decision).')
        man = json.load(open(K_WIT_MAN_FILE))
        if 'nodes_kept' not in man or 'outputs_sha256' not in man:
            raise KernelWitnessError(
                'witness_manifest.json malformed: required keys '
                "'nodes_kept' + 'outputs_sha256' "
                f'(got {sorted(man)}).')
        _KC['wit_man'] = man
    return _KC['wit_man']


def _k_heavy(which):
    """Lazy-load one heavy numerator col bank: 'exact' | 'fits'.
    Source per _k_mode(): the shipped one-node WITNESS slice
    (lbl3x-kernel-witness/, sha256-verified against its
    witness_manifest.json; KernelWitnessError = FAIL-LOUD if absent) or
    the optional full-lattice drop-in override (lbl3x-kernel-banks/,
    sha256-verified against the vendored lbl3x-kernel-manifest.json)."""
    assert which in ('exact', 'fits'), \
        f'unknown kernel bank {which!r} (per-line bank removed at v4)'
    key = 'bank_' + which
    if key not in _KC:
        import pickle
        if _k_mode() == 'full':
            fn = f'kernel_{which}.pkl.gz'
            path = os.path.join(K_BANKS_DIR, fn)
            pin = json.load(open(K_MAN_FILE))['outputs_sha256'][fn]
            err = KernelDataError
            _KC['nodes_avail'] = None          # full 34-node lattice
            _KC['wit_pos'] = None
        else:
            man = _k_witness_manifest()
            cand = [f for f in man['outputs_sha256'] if f'_{which}' in f]
            if len(cand) != 1:
                raise KernelWitnessError(
                    f'witness_manifest.json: need exactly one '
                    f'*_{which}* file in outputs_sha256, got {cand}.')
            fn = cand[0]
            path = os.path.join(K_WITNESS_DIR, fn)
            pin = man['outputs_sha256'][fn]
            err = KernelWitnessError
            nk = [int(n) for n in man['nodes_kept']]
            _KC['nodes_avail'] = nk
            _KC['wit_pos'] = {n: i for i, n in enumerate(nk)}
        if not os.path.exists(path):
            raise err(
                f'kernel col data {fn} absent at {path} (required '
                f'sha256 {pin}).  Structure/class/coverage queries and '
                f'--kernel-info / --theorem-check --info need no heavy '
                f'data; entry evaluation and the theorem checker do.')
        got = _k_sha256(path)
        if got != pin:
            raise err(
                f'{fn}: sha256 {got} != manifest pin {pin} -- refusing '
                f'to serve data that does not match its sha manifest.')
        _KC[key] = pickle.load(gzip.open(path))
    return _KC[key]


def _k_node_check(nn):
    """Raise (named) if d-node nn is not vendored in the loaded source."""
    na = _KC.get('nodes_avail')
    if na is not None and nn not in na:
        raise KernelDataError(
            f'd-node index {nn} not vendored in the witness slice '
            f'(shipped node indices {na}).  The full 34-node lattice is '
            f'a campaign-archive object '
            f'(tools/rowscripts/row21_kernel_data/); the optional '
            f'drop-in override lbl3x-kernel-banks/ activates it.')


def kernel_nodes():
    """The 34-node d lattice (list of Fractions), record order."""
    return list(_k_light()['NODES'])


def kernel_entry(var, i, j):
    """Map record {'class','terms'} for A^var[i][j] (0-based); None = zero."""
    return _k_light()['ent'][var].get((i, j))


def kernel_entry_class(var, i, j):
    e = kernel_entry(var, i, j)
    return 'zero' if e is None else e['class']


def _k_pre(pre, sF, tF):
    """Prefactor string 'c/s' | 'c/t' (c integer) -> exact Fraction."""
    c, v = pre.rsplit('/', 1)
    if v not in ('s', 't'):
        raise ValueError(f'unexpected prefactor {pre}')
    return Fraction(int(c)) / (sF if v == 's' else tF)


def _k_fam(fi, nn, sF, tF):
    """Denominator family fi value at node nn, exact Fraction."""
    b = _k_light()
    if fi in b['DDEP']:
        nm, sw = b['DDEP'][fi]
        FS, FT = b['DSUP'][nm]
        co = b['fx'][f'{nm}@{nn}']
        a, bb = (tF, sF) if sw else (sF, tF)
        return sum(co[c * (FT + 1) + e] * a ** c * bb ** e
                   for c in range(FS + 1) for e in range(FT + 1))
    return sum(Fraction(cc) * sF ** p * tF ** q
               for (p, q), cc in b['fams'][fi].items())


def _k_D(rung, eT2, nn, sF, tF):
    b = _k_light()
    v = Fraction(1)
    for fi, e in enumerate(rung):
        if e:
            v *= _k_fam(fi, nn, sF, tF) ** e
    if eT2:
        d = b['NODES'][nn]
        v *= (tF * tF + d * tF + 2 * (d - 3)) ** eT2
    return v


def _k_col_exact(key, nn, sF, tF):
    """Exact col value c_{T,m}(d_nn, s, t) = N/D (asm_atscale.eval_exact_col)."""
    r = _k_heavy('exact')[key]
    _k_node_check(nn)
    ds, dt = r['support']
    spw = [Fraction(1)] * (ds + 1)
    for a in range(1, ds + 1):
        spw[a] = spw[a - 1] * sF
    tpw = [Fraction(1)] * (dt + 1)
    for a in range(1, dt + 1):
        tpw[a] = tpw[a - 1] * tF
    N = Fraction(0)
    for u, (num, den) in enumerate(r['coeffs'][nn]):
        if num:
            N += Fraction(num, den) * spw[u // (dt + 1)] * tpw[u % (dt + 1)]
    return N / _k_D(r['rung'], r['eT2'], nn, sF, tF)


def kernel_entry_val_exact(var, i, j, nn, s, t):
    """A^var[i][j](d_nn, s, t) as an exact Fraction.  ONLY for entries of
    class direct-exact / exact-6prime / exact-10prime / exact-extraprime (the
    K_EXACT_CLASSES tuple; raises KernelClassError otherwise -- record usage
    constraint)."""
    e = kernel_entry(var, i, j)
    if e is None:
        return Fraction(0)
    if e['class'] not in K_EXACT_CLASSES:
        raise KernelClassError(
            f'A^{var}[{i}][{j}] class {e["class"]}: exact evaluation not '
            f'in its evidence class')
    sF, tF = Fraction(s), Fraction(t)
    b = _k_light()
    acc = Fraction(0)
    for tm in e['terms']:
        if tm['target'] == 'DIRECT':
            acc += _k_pre(tm['pre'], sF, tF)
        else:
            key = (tuple(tm['target']), b['M41'][j])
            acc += _k_pre(tm['pre'], sF, tF) * _k_col_exact(key, nn, sF, tF)
    return acc


def _k_modv(q, p):
    return q.numerator % p * pow(q.denominator % p, p - 2, p) % p


def _k_fam_modp(fi, nn, sv, tv, p):
    b = _k_light()
    if fi in b['DDEP']:
        nm, sw = b['DDEP'][fi]
        FS, FT = b['DSUP'][nm]
        co = b['fx'][f'{nm}@{nn}']
        a, bb = (tv, sv) if sw else (sv, tv)
        acc = 0
        for c in range(FS + 1):
            for e in range(FT + 1):
                acc = (acc + _k_modv(co[c * (FT + 1) + e], p)
                       * pow(a, c, p) * pow(bb, e, p)) % p
        return acc
    acc = 0
    for (pw, qw), cc in b['fams'][fi].items():
        acc = (acc + cc % p * pow(sv, pw, p) * pow(tv, qw, p)) % p
    return acc


def _k_D_modp(rung, eT2, nn, sv, tv, p):
    b = _k_light()
    D = 1
    for fi, e in enumerate(rung):
        if e:
            D = D * pow(_k_fam_modp(fi, nn, sv, tv, p), e, p) % p
    if eT2:
        d = b['NODES'][nn]
        t2 = (tv * tv + _k_modv(d, p) * tv + _k_modv(2 * (d - 3), p)) % p
        D = D * pow(t2, eT2, p) % p
    return D


def _k_col_modp(key, nn, sv, tv, p):
    """Col residue mod p: exact record (any class) or certified-2prime
    record (residues live only at the 2 fit primes)."""
    ex = _k_heavy('exact')
    _k_node_check(nn)
    if key in ex:
        r = ex[key]
        ds, dt = r['support']
        Nc = [n % p * pow(d % p, p - 2, p) % p if n else 0
              for n, d in r['coeffs'][nn]]
    else:
        r = _k_heavy('fits')[key]
        ds, dt = r['support']
        wp = _KC.get('wit_pos')
        # witness fits slices re-index nodes in nodes_kept order
        Nc = r['xs'][K_PRIMES.index(p)][nn if wp is None else wp[nn]]
    NV = 0
    for u, cv in enumerate(Nc):
        if cv:
            NV = (NV + cv * pow(sv, u // (dt + 1), p)
                  * pow(tv, u % (dt + 1), p)) % p
    Dv = _k_D_modp(r['rung'], r['eT2'], nn, sv, tv, p)
    return NV * pow(Dv, p - 2, p) % p


def kernel_entry_val_modp(var, i, j, nn, s, t, p):
    """Entry residue mod p; p MUST be one of the 2 fit primes.  Valid for
    exact-class AND certified-2prime entries.  certified-2prime is
    VERIFICATION-GRADE ONLY (record section 4): residues mod the fit primes,
    never float-lifted, no exact rationals exist."""
    if p not in K_PRIMES:
        raise KernelClassError(
            f'p={p} is not a fit prime; certified-2prime residues exist '
            f'only mod {K_PRIMES}')
    e = kernel_entry(var, i, j)
    if e is None:
        return 0
    if e['class'] not in K_EXACT_CLASSES + ('certified-2prime',):
        raise KernelClassError(
            f'A^{var}[{i}][{j}] class {e["class"]}: mod-p evaluation not '
            f'in its evidence class')
    sF, tF = Fraction(s), Fraction(t)
    sv, tv = _k_modv(sF, p), _k_modv(tF, p)
    b = _k_light()
    acc = 0
    for tm in e['terms']:
        if tm['target'] == 'DIRECT':
            acc = (acc + _k_modv(_k_pre(tm['pre'], sF, tF), p)) % p
        else:
            key = (tuple(tm['target']), b['M41'][j])
            acc = (acc + _k_modv(_k_pre(tm['pre'], sF, tF), p)
                   * _k_col_modp(key, nn, sv, tv, p)) % p
    return acc


def kernel_V_exact(i, j, nn, s, t):
    """The gate-2 FRAME-CLEAN combination V[i][j](d_nn, s, t) =
    A^s[i][j] - (t^2/s^2) A^t[i][j], as an exact Fraction.  Per record A3 /
    GATE2_LEAK_PROFILE.json this combination transported along the
    1/s+1/t=const foliation is the SAFE object -- the raw (A^s, A^t) pair
    is NOT a flat 2D connection off-curve (structural bug#21-v5 frame
    leak).  Both entries must be exact-class (KernelClassError otherwise;
    zero entries contribute 0)."""
    sF, tF = Fraction(s), Fraction(t)
    return (kernel_entry_val_exact('s', i, j, nn, sF, tF)
            - (tF * tF) / (sF * sF)
            * kernel_entry_val_exact('t', i, j, nn, sF, tF))


def kernel_info():
    """Per-class entry counts + col-bank counts + caps (for --kernel-info)."""
    b = _k_light()
    man = json.load(open(K_MAN_FILE))
    cnt = {}
    for var in ('s', 't'):
        for e in b['ent'][var].values():
            cnt[e['class']] = cnt.get(e['class'], 0) + 1
    assert cnt == b['coverage'], 'map coverage tally drifted'
    assert cnt.get('per-line-only', 0) == 0, \
        'per-line-only must be EMPTY at v4 (record A6)'
    banks = {w: ('present (sha-verified on first load)'
                 if os.path.exists(os.path.join(K_BANKS_DIR,
                                                f'kernel_{w}.pkl.gz'))
                 else 'not present (optional full-lattice override; '
                      'the shipped path is the witness slice)')
             for w in ('exact', 'fits')}
    if os.path.exists(K_WIT_MAN_FILE):
        try:
            wm = json.load(open(K_WIT_MAN_FILE))
            witness = ('present: nodes_kept %s, files %s (sha-verified '
                       'on load)' % (wm.get('nodes_kept'),
                                     sorted(wm.get('outputs_sha256', {}))))
        except Exception as e:                     # malformed = loud
            witness = f'MANIFEST UNREADABLE ({e}) -- theorem-check will FAIL LOUD'
    else:
        witness = ('NOT LANDED (kernel-compaction step owns slicing; '
                   '--theorem-check FAILS LOUD, rc!=0, until the '
                   'one-node slice + witness_manifest.json land in '
                   'lbl3x-kernel-witness/)')
    return {
        'two_objects': 'LBL3X = (1) GRAPH (parts A-D: default run, '
                       '--point, gate suite; never touches kernel/'
                       'witness data) + (2) THEOREM LBL3X-thm (part E '
                       'behind --theorem-check; this report is its '
                       'light info view -- 21:5x decision)',
        'witness_slice': witness,
        'registry': 'v4 (addendum A6, 2026-07-05): 4049 CLOSED-exact '
                    '/ 97 CLOSED-modp2 / 62 UNCLOSED cols; succession '
                    '2026-09-07: 71 two-prime cols closed exactly in the '
                    'record convention enter the exact bank (tag '
                    'exact-extraprime), 26 stay two-prime',
        'entry_classes': cnt,
        'entries_nonzero_total': sum(cnt.values()),
        'exact_entries': sum(cnt.get(c, 0) for c in K_EXACT_CLASSES),
        'certified_2prime_entries': cnt.get('certified-2prime', 0),
        'extraprime_entries': cnt.get('exact-extraprime', 0),
        'perline_entries': 0,
        'unclosed_entries': sum(v for k, v in cnt.items()
                                if k.startswith('UNCLOSED')),
        'rows_fully_2var_closed': 'A^s 35/41, A^t 24/41 (record A6.3)',
        'col_banks': man['counts'],
        'local_heavy_banks': banks,
        'd_lattice': '34 nodes: 101..132, 1009/3, -211/5 (lattice-only; '
                     'closed-form-in-d not reconstructed)',
        'fit_primes': list(K_PRIMES),
        'gate2_frame_constraint':
            'raw (A^s, A^t) is NOT a flat 2D connection off-curve '
            '(structural bug#21-v5 frame leak, record A3 / '
            'GATE2_LEAK_PROFILE.json); the safe object is '
            'V = A^s - (t^2/s^2) A^t on the 1/s+1/t=const foliation '
            '(kernel_V_exact)',
        'fold_gate': 'pt_8801 = (-67/6, -101/9), held out from every fit; '
                     'v4 fold gate: <archive>/rowscripts_interim/'
                     'fold_row21_v4/FOLDLOG_V4.md (v1: fold_row21_kernel)',
        'honest_limit': 'UNCLOSED 40 entries need denser crossed columns; '
                        'd on the 34-node lattice only; Delta not '
                        'assembled here (record A6.4)',
    }


def print_kernel_info():
    info = kernel_info()
    print('=' * 74)
    print('part E: kernel-backed 41x41 A^s/A^t connection -- coverage')
    print('        (no rounding up; tallies recomputed live from the map)')
    print('=' * 74)
    for k, v in info.items():
        if k == 'entry_classes':
            print('  per-class entry counts:')
            for c in sorted(v):
                print(f'    {c:44s} {v[c]}')
        elif k == 'col_banks':
            print('  vendored col banks (manifest counts):')
            for c, n in v.items():
                if c != 'entry_classes':
                    print(f'    {c:44s} {n}')
        elif k == 'local_heavy_banks':
            print('  local heavy banks (lbl3x-kernel-banks/):')
            for c, n in v.items():
                print(f'    {c:44s} {n}')
        else:
            print(f'  {k}: {v}')

THEOREM_HELP = """\
==========================================================================
LBL3X-thm -- the kernel function-form refutation: certificate checker
==========================================================================
TWO OBJECTS (the binding 21:5x two-objects decision).  LBL3X on this page is
  (1) the GRAPH   -- row 21, the master integrals, parts A-D: the
      DEFAULT run, --point and the gate suite.  Those paths never touch
      witness/kernel data.
  (2) the THEOREM -- LBL3X-thm, this subcommand: the refutation below,
      shipped in the certificate model.

THEOREM (function-form refutation).  The 41x41 kernel connection
(A^s, A^t) of the preferred41 basis admits NO finite-depth closed
function form: its eps^0-coupled block is a single 24-master strongly
connected component (the 24-SCC obstruction), so no finite-depth
triangular rewriting closes the system in function form (archived STAGE0
verdict, project-lbl3x-function-form-target).  Scope note: the
refutation concerns finite-depth FUNCTION FORMS -- per-point evaluation
is unaffected (and is exactly what this checker exercises).

CERTIFICATE MODEL: statement / witness / checker.
  statement  the prose above (paper: its own theorem environment).
  witness    the ONE-NODE exact slice of the kernel connection,
             ~12.5 MB sha-pinned, per <archive>/
             lbl3x_kernel_compact/DESIGN.md:
               lbl3x-kernel-witness/slice_n1_exact.pkl.gz
                 (4255 exact rational (s,t) numerator cols, d-node 101)
               lbl3x-kernel-witness/slice_n1_fits.pkl.gz
                 (26 two-prime residue cols)
               lbl3x-kernel-witness/witness_manifest.json
                 (sha256 pins + nodes_kept)
             The slice is a DEFINITION (the exact symbolic (s,t)
             connection at a declared d-node), not a cache; slicing is
             owned by the kernel-compaction step.  sha256 is verified
             against the manifest on every load.  ABSENT witness =>
             KernelWitnessError, exit code 2 -- never a silent degrade.
  checker    this subcommand: recomputes coverage tallies from the
             vendored map; verifies the 24-SCC coupling structure live;
             sha-verifies + loads the witness; checks bank closure (the
             map's 4343 referenced cols = 4255 exact + 26 two-prime +
             exactly 62 ABSENT = the UNCLOSED cols); reproduces the
             known closed entry A^s[17][38] = 2/s exactly; cross-checks
             exact values against mod-p residues at both fit primes;
             and exercises the evidence-class guards (KernelClassError
             negative controls).

HONEST GAPS (part of the theorem's story, not an omission):
  * the 40 UNCLOSED entries (62 cols) are ABSENT from every bank,
    including the full campaign banks -- that absence is itself a
    finding (they need denser crossed columns; record A6.4).
  * the 26 two-prime columns (16 certified-2prime entries) are
    VERIFICATION-GRADE only: residues mod the 2 fit primes, never
    float-lifted; no exact rationals exist for them.  The other 71
    two-prime columns were closed exactly on the record grid (2026-09-07)
    and are exact-extraprime entries of the exact slice; the (t8)
    succession tally checks their count against the manifests.
  * in the witness, d lives at the vendored node(s) only; the FULL
    34-node lattice is a campaign-archive pointer
    (tools/rowscripts/row21_kernel_data/, sha-pinned), optionally
    activated locally via the lbl3x-kernel-banks/ drop-in override.
    Closed-form-in-d was never reconstructed.
  * the Delta gap (module docstring) is unchanged by part E.

USAGE
  --theorem-check           run the certificate checker (needs witness;
                            rc=0 pass, rc=2 witness absent/corrupt,
                            rc=1 any check failure)
  --theorem-check --info    light coverage report (no witness needed)
  --theorem-check --help    this text
  --kernel-info             compat alias of --theorem-check --info
"""


def _k_scc_sizes(adj):
    """SCC sizes (desc) of a small digraph {node: set(succ)} (Tarjan)."""
    idx, low, onstk, stk, comps, ctr = {}, {}, set(), [], [], [0]

    def dfs(u):
        idx[u] = low[u] = ctr[0]; ctr[0] += 1
        stk.append(u); onstk.add(u)
        for w in adj[u]:
            if w not in idx:
                dfs(w); low[u] = min(low[u], low[w])
            elif w in onstk:
                low[u] = min(low[u], idx[w])
        if low[u] == idx[u]:
            comp = []
            while True:
                w = stk.pop(); onstk.discard(w); comp.append(w)
                if w == u:
                    break
            comps.append(comp)

    for u in adj:
        if u not in idx:
            dfs(u)
    return sorted((len(c) for c in comps), reverse=True)


def run_theorem_check():
    """LBL3X-thm certificate checker (see THEOREM_HELP).  Prints the
    check table; raises (nonzero exit) on ANY failure -- including a
    LOUD KernelWitnessError when the witness has not landed."""
    print('=' * 74)
    print('LBL3X-thm: kernel function-form refutation -- certificate check')
    print('=' * 74)
    print('THEOREM: the 41x41 kernel connection admits NO finite-depth closed')
    print('function form (eps^0-coupled 24-SCC obstruction).  Certificate =')
    print('statement + one-node exact witness (sha-pinned) + this checker.')
    b = _k_light()
    # (t1) coverage tallies recomputed live from the vendored map
    cnt = {}
    for var in ('s', 't'):
        for e in b['ent'][var].values():
            cnt[e['class']] = cnt.get(e['class'], 0) + 1
    assert cnt == b['coverage'], 'map coverage tally drifted'
    n_ex = sum(cnt.get(c, 0) for c in K_EXACT_CLASSES)
    n_2p = cnt.get('certified-2prime', 0)
    n_un = sum(v for k, v in cnt.items() if k.startswith('UNCLOSED'))
    assert (n_ex, n_2p, n_un) == (1989, 16, 40), \
        'coverage drifted (v4 + the 2026-09-07 succession)'
    print('(t1) coverage recomputed from map: 1989 exact / 16 certified-'
          '2prime /')
    print('     40 UNCLOSED of %d nonzero entries  PASS' % sum(cnt.values()))
    # (t2) the obstruction structure, live: largest SCC of the union
    # digraph (i -> j iff A^s or A^t entry nonzero) = 24 masters.
    adj = {i: set() for i in range(41)}
    for var in ('s', 't'):
        for (i, j) in b['ent'][var]:
            adj[i].add(j)
    sizes = _k_scc_sizes(adj)
    assert sizes[0] == 24, \
        f'largest SCC {sizes[0]} != 24 -- obstruction structure drifted'
    print('(t2) SCC sizes of the nonzero-entry digraph: %s' % sizes[:8])
    print('     largest SCC = 24 masters (the finite-depth obstruction)  PASS')
    # (t3) witness load: sha-manifest verified; FAIL-LOUD if absent
    mode = _k_mode()
    ex = _k_heavy('exact'); ft = _k_heavy('fits')
    na = _KC.get('nodes_avail')
    assert len(ex) == 4255 and len(ft) == 26, \
        f'col-bank counts {len(ex)}/{len(ft)} != 4255/26'
    if na is None:
        print('(t3) heavy source: FULL 34-node drop-in override '
              '(lbl3x-kernel-banks/),')
    else:
        print('(t3) heavy source: WITNESS slice, node indices %s (d = %s),'
              % (na, [str(b['NODES'][n]) for n in na]))
    print('     sha256 == manifest pins; 4255 exact + 26 two-prime cols  PASS')
    # (t4) bank closure == the honest gap, verified
    refs = set()
    uncl_entries, hit_missing = set(), set()
    for var in ('s', 't'):
        for (i, j), e in b['ent'][var].items():
            if e['class'].startswith('UNCLOSED'):
                uncl_entries.add((var, i, j))
            for tm in e['terms']:
                if tm['target'] != 'DIRECT':
                    refs.add((tuple(tm['target']), b['M41'][j]))
    missing = refs - set(ex) - set(ft)
    for var in ('s', 't'):
        for (i, j), e in b['ent'][var].items():
            for tm in e['terms']:
                if tm['target'] != 'DIRECT' and \
                        (tuple(tm['target']), b['M41'][j]) in missing:
                    hit_missing.add((var, i, j))
    assert len(refs) == 4343 and len(missing) == 62, \
        f'closure drifted: {len(refs)} refs, {len(missing)} missing'
    assert hit_missing == uncl_entries and len(uncl_entries) == 40, \
        'missing cols do not coincide with the UNCLOSED entries'
    print('(t4) bank closure: 4343 referenced cols = 4255 exact + 26 two-'
          'prime')
    print('     + 62 ABSENT == exactly the UNCLOSED-entry cols (40 entries);')
    print('     the absence is part of the theorem, not an omission  PASS')
    # (t5) known closed entry + frame-clean combination at pt_8801
    nn = 0 if na is None else na[0]
    sF, tF = Fraction(-67, 6), Fraction(-101, 9)
    v = kernel_entry_val_exact('s', 17, 38, nn, sF, tF)
    assert v == Fraction(2) / sF, f'A^s[17][38] = {v} != 2/s'
    vV = kernel_V_exact(17, 38, nn, sF, tF)
    assert vV == v - (tF * tF) / (sF * sF) \
        * kernel_entry_val_exact('t', 17, 38, nn, sF, tF)
    print('(t5) closed entry A^s[17][38] == 2/s EXACT at pt_8801, node %d;'
          % nn)
    print('     kernel_V_exact combines (frame-clean V, gate-2)  PASS')
    # (t6) exact <-> mod-p cross-check at both fit primes (3 col-backed
    # exact entries, deterministic pick)
    done = 0
    for var in ('s', 't'):
        for (i, j) in sorted(b['ent'][var]):
            e = b['ent'][var][(i, j)]
            if e['class'] in K_EXACT_CLASSES and \
                    any(tm['target'] != 'DIRECT' for tm in e['terms']):
                val = kernel_entry_val_exact(var, i, j, nn, sF, tF)
                for p in K_PRIMES:
                    assert _k_modv(val, p) == \
                        kernel_entry_val_modp(var, i, j, nn, sF, tF, p), \
                        f'exact vs mod-{p} mismatch at A^{var}[{i}][{j}]'
                done += 1
            if done >= 3:
                break
        if done >= 3:
            break
    assert done == 3
    print('(t6) exact vs mod-p residues, both fit primes, 3 entries: 6/6  PASS')
    # (t7) evidence-class guards (negative controls)
    e2p = next((var, i, j) for var in ('s', 't')
               for (i, j), e in sorted(b['ent'][var].items())
               if e['class'] == 'certified-2prime')
    eun = next((var, i, j) for var in ('s', 't')
               for (i, j), e in sorted(b['ent'][var].items())
               if e['class'].startswith('UNCLOSED'))
    for (var, i, j), what in ((e2p, 'certified-2prime exact eval'),
                              (eun, 'UNCLOSED exact eval')):
        try:
            kernel_entry_val_exact(var, i, j, nn, sF, tF)
            raise AssertionError(f'{what} did NOT raise KernelClassError')
        except KernelClassError:
            pass
    try:
        kernel_entry_val_modp(*e2p, nn, sF, tF, 101)
        raise AssertionError('non-fit prime did NOT raise KernelClassError')
    except KernelClassError:
        pass
    print('(t7) evidence-class guards: 2prime/UNCLOSED exact eval + non-fit')
    print('     prime all raise KernelClassError  PASS')
    # (t8) the succession tally: the exact-extraprime entries of the map,
    # the columns they reference (all in the exact bank, none in the
    # two-prime bank), the two-prime bank's size, against the loaded
    # manifest's succession block and the map's own block -- structure
    # only, no value re-derived here
    sc = (_k_witness_manifest() if na is not None
          else json.load(open(K_MAN_FILE)))['succession']
    ms = json.load(open(K_MAP_FILE))['succession']
    n_xp = cnt.get('exact-extraprime', 0)
    keys_xp, keys_2p = set(), set()
    for var in ('s', 't'):
        for (i, j), e in b['ent'][var].items():
            for tm in e['terms']:
                if tm['target'] == 'DIRECT':
                    continue
                if tm.get('class') == 'exact-extraprime':
                    keys_xp.add((tuple(tm['target']), b['M41'][j]))
                elif tm.get('class') == 'certified-2prime':
                    keys_2p.add((tuple(tm['target']), b['M41'][j]))
    assert keys_xp <= set(ex) and not (keys_xp & set(ft)), \
        'an extra-prime column is not in the exact bank'
    assert keys_2p == set(ft), \
        'the two-prime bank != the certified-2prime columns of the map'
    assert len(keys_xp) == sc['promoted']['columns'] == \
        ms['columns_promoted'], 'promoted-column count drifted'
    assert len(ft) == sc['retained_two_prime']['columns'] == \
        ms['columns_retained_two_prime'], 'retained two-prime count drifted'
    assert n_xp == ms['entries_moved_certified_2prime_to_exact_extraprime'], \
        'exact-extraprime entry tally drifted'
    print('(t8) succession tally: %d exact-extraprime entries / %d columns in'
          % (n_xp, len(keys_xp)))
    print('     the exact bank carry the extra-prime tag == the manifest')
    print('     succession counts (%d promoted, %d retained two-prime = the'
          % (sc['promoted']['columns'], len(ft)))
    print('     two-prime bank)  PASS')
    print()
    print('THEOREM-CHECK PASS: certificate verified '
          '(statement + witness + checker).')


def _theorem_cli(args):
    if any(a in ('--help', '-h', 'help') for a in args):
        print(THEOREM_HELP)
        return
    if '--info' in args:
        print_kernel_info()
        return
    try:
        run_theorem_check()
    except KernelWitnessError as e:
        print('THEOREM-CHECK FAIL-LOUD (LBL3X-thm witness): %s' % e,
              file=sys.stderr)
        sys.exit(2)


# =====================================================================
# THE -7 POINT TESTED (2026-09-06, cure-queue entry 37).  The standing
# s=-7 prediction of lbl3x-prediction.json (122 quotable digits, recorded
# 2026-07-08 with no oracle at the point) was tested by ONE independent
# AMFlow run at (-7,-56/13) at goal 60 (the route of the -8 goal-60
# record GATE_GOAL60.json with the point moved; the goal-40 twin of the
# same run beside it).  The record row21_chain/data/GATE_M7_GOAL60.json
# carries the four midpoints at their full printed length with their
# radii (py34, py35, py17 at eps^-1 and eps^0; goal 60 and goal 40), the
# output/configuration sha256 of both runs, the receipt of record and
# the comparator figures: goal-60 vs the served prediction string
# 72.644 d (first differing printed digit 74), the goal-40 twin 49.787 d,
# the goal-40/goal-60 pair floor 49.787 d.  At `--m18-eps0 --point -7`
# the record is sha256-pinned HERE (M7_GATE_PIN; a mismatch REFUSES by
# name, rc 3; absent, rc 4 -- before anything is computed), the value is
# served live exactly as before, and the chain's (b) STANDING PREDICTION
# print is replaced for that path by the tested form: two RAISING lines
# in the -8 never-fit form (this run's raw value vs the goal-60 string,
# bar = the record's 72.644 minus its rounding half-width; vs the
# goal-40 twin, bar from 49.787), the pair recomputed from the two
# strings, then 'tested: N held-out digits' (N = the goal-60 agreement
# floored, the agreement ending on the oracle side -- the Table-2
# convention of the -8 record) and 'pair: M' (the goal-40 twin floored).
# Both N and M are this run's own comparison; the record's figures are
# printed beside.  A below-bar line FAILS by name, rc 1.  The record is
# NOT an entry of the package MANIFEST.json (its root pin, the -8 gate
# GATE_GOAL60.json and the goal-40 records are byte-identical); the -8
# path, --gates, --seed-gate-only and --refusal-suite are untouched.
# =====================================================================
M7_GATE_FILE = 'GATE_M7_GOAL60.json'
M7_GATE_REL = 'row21_chain/data/' + M7_GATE_FILE
# --- PIN (script-emitted from the shipped bytes; sha256 of the record) ---
M7_GATE_PIN = '83cef53c435aeb8fe0de2c638cf7690052eb9350d5304bdc688aec466c348a0a'
M7_RC_FAIL, M7_RC_REFUSED, M7_RC_MISSING = 1, 3, 4
M7_POINT = (Fraction(-7), Fraction(-56, 13))      # t = -8s/(3s+8) at s = -7


def _m7_requested(args):
    """True when the --m18-eps0 argument list asks for the single serve at
    s = -7; the --gates / --seed-gate-only / --refusal-suite / --help arms
    are the chain's own, untouched."""
    if any(a in ('--gates', '--seed-gate-only', '--refusal-suite', '-h',
                 '--help') for a in args):
        return False
    pt = None
    for i, a in enumerate(args):
        if a == '--point' and i + 1 < len(args):
            pt = args[i + 1]
        elif a.startswith('--point='):
            pt = a.split('=', 1)[1]
    if pt is None:
        return False
    try:
        return Fraction(pt) == M7_POINT[0]
    except (ValueError, ZeroDivisionError):
        return False


def _m7_load_record():
    """The pinned record: absent -> rc 4; sha256 mismatch -> rc 3; a record
    naming another point -> rc 3 (all by name; nothing computed first)."""
    p = os.path.join(HERE, 'row21_chain', 'data', M7_GATE_FILE)
    if not os.path.exists(p):
        print('M18-EPS0 -7 MISSING: pinned file %s is absent (required '
              'sha256 %s)' % (M7_GATE_REL, M7_GATE_PIN))
        sys.exit(M7_RC_MISSING)
    got = _k_sha256(p)
    if got != M7_GATE_PIN:
        print('M18-EPS0 -7 REFUSED: %s sha256 %s != pinned %s'
              % (M7_GATE_REL, got, M7_GATE_PIN))
        sys.exit(M7_RC_REFUSED)
    with open(p) as fh:
        rec = json.load(fh)
    q = rec['Q']
    if (Fraction(str(q['s'])), Fraction(str(q['t']))) != M7_POINT:
        print('M18-EPS0 -7 REFUSED: %s names the point (s, t) = (%s, %s), '
              'not (%s, %s)' % (M7_GATE_REL, q['s'], q['t'], M7_POINT[0],
                                M7_POINT[1]))
        sys.exit(M7_RC_REFUSED)
    print('[pins] 1 shipped file verified by sha256 (%s: the goal-60 AMFlow '
          'record of the -7 point + its goal-40 twin)' % M7_GATE_REL)
    return rec


def _m7_tested_print(chain, res_by_prec, rec):
    """The (b) block of the -7 path: the phase3 receipt quoted (as served)
    + the tested gate (the -8 never-fit form) + the two summary lines."""
    print('\n    (b) THE -7 POINT TESTED (on-curve t=-56/13): the standing '
          '122 d')
    print('        prediction (lbl3x-prediction.json; the phase3 receipts '
          'quoted')
    print('        below) against the goal-60 AMFlow record of this point,')
    print('        %s (sha256-pinned; the goal-40 twin inside) -- a'
          % M7_GATE_FILE)
    print('        RAISING gate.')
    r0 = chain.verified_json(os.path.join(chain.DATA, 'S7_VAL_main_p1.json'))
    print('        phase3 receipt (%s):' % chain.PRED_RECEIPT_NOTE)
    print('          stripped: %s...' % r0['m18_at_m7'][0][:66])
    print('          raw     : %s...' % r0['m18_at_m7_raw'][0][:66])
    ent = rec['values']['py17@eps^0']
    prov = rec['provenance']
    rec60 = float(rec['m18_eps0_d'])
    rec40 = float(rec['goal40_twin_d'])
    recpair = float(rec['pair_floor_d'])
    bar60 = chain._record_bar(rec60)
    bar40 = chain._record_bar(rec40)
    for prec, res in res_by_prec.items():
        if 'm7' not in res:
            continue
        chain.set_prec(res['bits'])
        ds = chain._digits(res['m7']['stripped'],
                           chain.P.str_mpc(r0['m18_at_m7']).real)
        dr = chain._digits(res['m7']['raw'],
                           chain.P.str_mpc(r0['m18_at_m7_raw']).real)
        print('        this run [%s]: stripped %s' % (prec,
              chain.mpfr(res['m7']['stripped'].real).__format__('.60g')))
        print('          consistency vs receipt: stripped %.1f d / raw '
              '%.1f d (receipt cross-check, NOT a gate)' % (ds, dr))
        raw = res['m7']['raw']
        o60 = chain.mpfr(ent['amflow'])
        o40 = chain.mpfr(ent['amflow_goal40'])
        d60 = chain._digits(raw, o60)
        d40 = chain._digits(raw, o40)
        pair = chain._digits(o40, o60)
        print('    never-fit m7 PRIMARY: raw vs %s AMFlow string (goal %d, '
              'ball radius %s): %.3f d (record %.3f, bar %.4f)'
              % (M7_GATE_FILE, rec['goal_digits'], ent['amflow_ball_rad'],
                 d60, rec60, bar60))
        print('        record provenance: receipt sha256 %s... (%s); AMFlow '
              'config %s... / output %s..., rc %s'
              % (prov['source_receipt_sha256'][:16],
                 prov['source_receipt_stamp_utc'],
                 prov['amflow_config_sha256'][:16],
                 prov['amflow_output_sha256'][:16], prov['amflow_rc']))
        print('    never-fit m7 TWIN: raw vs the goal-40 twin string (ball '
              'radius %s; config %s... / output %s..., rc %s): %.3f d '
              '(record %.3f, bar %.4f); goal-40 vs goal-60 strings '
              'recomputed %.3f d (record pair floor %.3f)'
              % (ent['amflow_goal40_ball_rad'],
                 prov['goal40_twin_config_sha256'][:16],
                 prov['goal40_twin_output_sha256'][:16],
                 prov['goal40_twin_rc'], d40, rec40, bar40, pair, recpair))
        try:
            chain.gate_check(
                '(b) NEVER-FIT POINT m7 (the prediction tested)',
                [('%s (goal %d AMFlow record)' % (M7_GATE_FILE,
                                                   rec['goal_digits']),
                  d60, bar60),
                 ('%s (the goal-40 twin)' % M7_GATE_FILE, d40, bar40)])
        except RuntimeError as e:
            print('M18-EPS0 -7 GATE FAIL by name: %s' % e)
            sys.exit(M7_RC_FAIL)
        print('    tested: %d held-out digits (this run vs the goal-60 '
              'string, %.3f d floored; the record figure %.3f)'
              % (int(d60), d60, rec60))
        print('    pair: %d (this run vs the goal-40 twin, %.3f d floored; '
              'the goal-40/goal-60 two-precision floor %.3f d; the record '
              'figure %.3f)' % (int(d40), d40, pair, recpair))


def _m7_install(chain):
    """Pin + load the record FIRST (rc 3 / rc 4 by name), then replace the
    chain's prediction_print for this process with the tested form."""
    rec = _m7_load_record()

    def _tested(res_by_prec):
        _m7_tested_print(chain, res_by_prec, rec)
    chain.prediction_print = _tested


def _m18_eps0_cli(args):
    # 2026-09-03 port of the eval_row21.py value arm: lazy-load the
    # vendored phase3 chain (row21_chain/); ABSENT/corrupt package =
    # LOUD, exit 2, never a silent degrade.  All chain data is
    # sha-pinned via the package MANIFEST; named refusals exit 2.
    chain_dir = os.path.join(HERE, 'row21_chain')
    if not os.path.isdir(chain_dir):
        print('M18-EPS0 FAIL-LOUD: vendored chain package absent: %s'
              % chain_dir, file=sys.stderr)
        sys.exit(2)
    sys.path.insert(0, chain_dir)
    try:
        import chain as _chain
    except Exception as e:
        print('M18-EPS0 FAIL-LOUD: row21_chain unavailable (this arm '
              'needs python-flint and gmpy2): %s: %s'
              % (type(e).__name__, e), file=sys.stderr)
        sys.exit(2)
    if _m7_requested(args):
        # 2026-09-06 (cure-queue entry 37): the -7 point TESTED -- the
        # record pinned and loaded FIRST (rc 3 / rc 4 by name, before any
        # compute), then the chain's (b) prediction print replaced for
        # this process by the tested form (the raising gate against the
        # goal-60 string and its goal-40 twin); the -8 path and --gates
        # are untouched.
        _m7_install(_chain)
    sys.exit(_chain.cli(args))


# =====================================================================
# SECTOR-63 CONVENTION MAP (2026-09-06).  The preferred41 basis of part E
# carries two masters in sector 63 beyond the strict 39-master window
# preferred39 = M41[0..38] (the window of every reduction under
# row21_offcurve/):
#   M41[39] = LBL3X[1,1,1,1,1,1,0,-1,0,0,0,0,0,0,0]
#   M41[40] = LBL3X[1,1,1,1,1,1,0,0,0,0,0,-1,0,0,0]
# The reduction of record (sectors [63], r 9, s 2, FireFly in (d, m2),
# 82568 equations, 'unreduced integrals: 0.' at every point) reduces them
# onto the window at the seven off-curve points of row21_offcurve/ as
#   M41[39] = -M39[18]
#   M41[40] = M39[20] - M39[19] + 2 M39[18] + (-t/2) M39[17] + M39[16]
# with M39[16] = LBL3X[1,1,1,1,1,0,0,0,0,0,0,0,0,0,0],
#      M39[17] = LBL3X[1,1,1,1,1,1,0,0,0,0,0,0,0,0,0],
#      M39[18] = LBL3X[1,1,1,1,1,1,-1,0,0,0,0,0,0,0,0],
#      M39[19] = LBL3X[1,1,1,1,1,1,0,0,-1,0,0,0,0,0,0],
#      M39[20] = LBL3X[1,1,1,1,1,1,0,0,0,-1,0,0,0,0,0];
# t = the point t (the p2.p3 = t/2 rule); exact rational relations, d- and
# m^2-independent, one entry linear in t, every other coefficient an
# integer.  The fixtures (row21_offcurve/fixtures/, pinned below): per
# point kira_target_s63_<tag>.m (the reduction's own export: the two
# targets in the order of the record, six coefficient strings) and
# S63_REDUCTION_<tag>.json (its parsed form: the two rows, the coefficient
# strings, their exact values at the d-nodes 101 and 102 with m2 = 1, the
# fold map, the fold rule and the closed form).  The reduction database of
# each point (kira.db) is NOT shipped; its sha256 is quoted per point.
# WHERE THE MAP BEARS ON THIS EVALUATOR: on no served number.  Parts A-D
# (the default run, --full, --point) use the 9-master u-DE and the
# 13-master block, never the 41-master basis; --m18-eps0 transports the
# on-curve 41-master system as it stands (closed on the curve; no fold);
# part E (--theorem-check) reads the 41x41 map, whose entries in columns
# 39/40 sit on rows 17..40 only (A^s 46, A^t 48 such entries), and the
# checker evaluates entries of rows 0 and 17 at columns 0..2 and 38 --
# never a column-39/40 entry; the off-curve chain of row21_offcurve/ runs
# on rows 0..16, where columns 39/40 carry no entry, so the fold is the
# identity there (zero digit change on every served object).  Rows 17..40
# off the curve are NOT established (row21_offcurve/ --help, label L3);
# the map is a convention statement -- nothing more is claimed here.
# =====================================================================
import re                       # the export grammar (this arm only)
S63_DIR = os.path.join(HERE, 'row21_offcurve')
S63_TAGS = ('Q_m19m18', 'Qleaf_sm17', 'Qleaf_sm20', 'Qleaf_sm37h',
            'Qleaf_sm39h', 'Qleaf_sm41h', 'Roff_m11m2')
S63_M41_39 = 'LBL3X[1,1,1,1,1,1,0,-1,0,0,0,0,0,0,0]'
S63_M41_40 = 'LBL3X[1,1,1,1,1,1,0,0,0,0,0,-1,0,0,0]'
S63_REL1 = {18: Fraction(-1)}                       # M41[39] = -M39[18]
S63_REL2_CONST = {20: Fraction(1), 19: Fraction(-1), 18: Fraction(2),
                  16: Fraction(1)}                  # + (-t/2) M39[17]
S63_T_ENTRY = 17
S63_NODES = ('d=101,m2=1', 'd=102,m2=1')
S63_RC_FAIL, S63_RC_USAGE, S63_RC_REFUSED, S63_RC_MISSING = 1, 2, 3, 4
# The record's -t/2 per point and the sha256 of each point's reduction
# database (kira.db; not shipped), both read by key from the receipt of
# record (sha256 353896563b3bf40663882a9a951b2d317dbb7aa873d99e5270e5dd256b617b83) when this block was
# emitted; the tier recomputes -t/2 from the served points.json and
# compares.
S63_MINUS_T_OVER_2 = {
    'Q_m19m18': '9',
    'Qleaf_sm17': '2907/287',
    'Qleaf_sm20': '1710/199',
    'Qleaf_sm37h': '6327/685',
    'Qleaf_sm39h': '2223/253',
    'Qleaf_sm41h': '7011/833',
    'Roff_m11m2': '1',
}
S63_KIRA_DB_SHA256 = {
    'Q_m19m18': '0ce58ca0d9b66b54211480f0bf38e6c07e3ff0a9caa13ed7e9313f7a6f84e568',
    'Qleaf_sm17': '31002cda8fc2e2ef46850cf0078d833902caa8ee2b8593b4d4d31e9639ce4bd2',
    'Qleaf_sm20': '9d7b75dad40e312aed8d91c3233fd20b71f00d69e21290ce838e5801274dbc77',
    'Qleaf_sm37h': '836ee10913e44a2b617c2df63903808295308fe65a6dadc95359d3f1e510a854',
    'Qleaf_sm39h': '7e118a3950919780c620db9defab08e4086e01562a5269772012cf655a84df35',
    'Qleaf_sm41h': '8ee94e916e915bb7d8a93fb74079d1cd3fc419feed0d9f815050450245b6e50c',
    'Roff_m11m2': 'd15cb25551fe55b8a94b3b68d6bbcdc21f4fcd55046aab4c681532c5a622ec0d',
}
# the strings every fixture carries (asserted equal across the seven)
S63_CLOSED_FORM = 'M41[39] = -M39[18]; M41[40] = M39[20] - M39[19] + 2 M39[18] + (-t/2) M39[17] + M39[16] (t = the point t; d- and m2-independent)'
S63_FOLD_RULE = 'A_fold[i][j] = A[i][j] + A[i][39] R[M41[39]][j] + A[i][40] R[M41[40]][j] for i, j < 39; rows 39, 40 dropped; rows 0..16 unchanged (C6)'
# --- PINS (script-emitted from the shipped bytes; sha256 of the 14
# fixtures + the two served files the tier reads) ---
S63_PINS = {
    'fixtures/S63_REDUCTION_Q_m19m18.json': '6434cd78f222131b84888a0e166a98b10640283568ce16731d33688287fd95d0',
    'fixtures/S63_REDUCTION_Qleaf_sm17.json': 'f1b3c932fdf4167b65271e1307f6b335c1ff71b69db843c376fd7936c2bafb79',
    'fixtures/S63_REDUCTION_Qleaf_sm20.json': '7a0f0f9367dc0815006428052358f810ddef11813a5275f2eecb727db1385db3',
    'fixtures/S63_REDUCTION_Qleaf_sm37h.json': 'befb397986c497e0403c13c27b8555dc4ae718458ca97d7a09627baee87c13bd',
    'fixtures/S63_REDUCTION_Qleaf_sm39h.json': '75420ee8578e06a057ee1ccbcc04dee55a686ecd554bfd29374100292713df86',
    'fixtures/S63_REDUCTION_Qleaf_sm41h.json': 'a8227dd63d93ae6de963b4ed9ddc0f152cfd22f787549e1fd5c5c672eb529f51',
    'fixtures/S63_REDUCTION_Roff_m11m2.json': 'ea8a3aedaa3713bd5d1266ccacbb8bed059e3265ea61c1b68452c0be80e5657c',
    'fixtures/kira_target_s63_Q_m19m18.m': '0754d4dfbd89b3332e3e170c67f3f05d71d223226c40558f918676dfd818fcee',
    'fixtures/kira_target_s63_Qleaf_sm17.m': '5e96086d963bab133c40e482f0fc70d2d3fec587f32728457ed8691b258a1c00',
    'fixtures/kira_target_s63_Qleaf_sm20.m': '59948aaef5010b6dfaed7855c9e732e2eb8b4e6c0d2fde32fdd18af2e17a5b48',
    'fixtures/kira_target_s63_Qleaf_sm37h.m': 'a2fcbd50315e70f02f4f07153cf1b641ef27cf61d0b7c1054845def26ea5ecc7',
    'fixtures/kira_target_s63_Qleaf_sm39h.m': 'd25d7bd84d542fecc9aded64f919ebb03c9819cc77a0b2071ef0326d276adf0c',
    'fixtures/kira_target_s63_Qleaf_sm41h.m': '8ee72d2eb26a32196affd95531e67ed15b201ab0dbe2bd67b648ee6f2de98d2c',
    'fixtures/kira_target_s63_Roff_m11m2.m': '1c7535ca0e8896fe8086c4396994df78e27ebf152ef8afb5fb851732e11ae6c0',
    'points/Q_m19m18/preferred39': 'b142c7c37d637f98b5dabc03e3c0f4b22fff19cc1d747703200416c127f963e7',
    'points/points.json': 'e9df96dd55ddf7c06434b07a60c36f2612a236a07100adefaa3ac63c2950013d',
}

S63_HELP = """\
==========================================================================
--sector63-map -- the 41 -> 39 convention map of the two spurious
sector-63 masters, re-checked exactly from the pinned fixtures
==========================================================================
THE MAP (exact rational relations, d- and m^2-independent, one entry
linear in t; every other coefficient an integer):
  M41[39] = LBL3X[1,1,1,1,1,1,0,-1,0,0,0,0,0,0,0]  = -M39[18]
  M41[40] = LBL3X[1,1,1,1,1,1,0,0,0,0,0,-1,0,0,0] = M39[20] - M39[19]
            + 2 M39[18] - (t/2) M39[17] + M39[16]
  M39[16] = LBL3X[1,1,1,1,1,0,0,0,0,0,0,0,0,0,0]
  M39[17] = LBL3X[1,1,1,1,1,1,0,0,0,0,0,0,0,0,0]
  M39[18] = LBL3X[1,1,1,1,1,1,-1,0,0,0,0,0,0,0,0]
  M39[19] = LBL3X[1,1,1,1,1,1,0,0,-1,0,0,0,0,0,0]
  M39[20] = LBL3X[1,1,1,1,1,1,0,0,0,-1,0,0,0,0,0]
  t = the point t (the p2.p3 = t/2 rule); M39[i] = line i+1 of preferred39.
WHAT THE TIER DOES.  Pins first: the 14 fixtures under
row21_offcurve/fixtures/ + points/points.json + points/Q_m19m18/preferred39
are sha256-verified (a mismatch REFUSES by name, rc 3; a missing file rc 4).
Then, per point: the JSON fixture's two rows are checked against the map
in exact Fraction arithmetic -- the masters by name against preferred39,
the coefficient strings under the reduction's grammar, their values at
d = 101 and d = 102 (m2 = 1) equal to the map's, the M39[17] coefficient
equal to -t/2 with t read from points.json and compared with the record's
-t/2 string, integer everywhere else (and the t-entry's own integrality
stated); the .m export is re-hashed (== the JSON's source_file_sha256 ==
the pin), parsed, and compared term by term with the JSON rows; the fold
map, the fold rule and the closed-form string are checked; across the
seven points the exports are shown to differ only in the M39[17] line.
The kira.db sha256 of each reduction is printed (the database is not
shipped).  Verdict: PASS (rc 0) only when every check at every point
holds; any miss FAILS by name (rc 1) naming the point and the relation.
FIXTURES  row21_offcurve/fixtures/S63_REDUCTION_<tag>.json (7) and
          row21_offcurve/fixtures/kira_target_s63_<tag>.m (7), tags
          Q_m19m18, Qleaf_sm17, Qleaf_sm20, Qleaf_sm37h, Qleaf_sm39h,
          Qleaf_sm41h, Roff_m11m2 (the points of row21_offcurve/); the
          sha256 of every file is in S63_PINS.
SCOPE     The map bears on no served number of this evaluator (parts A-D
          never use the 41-master basis; --m18-eps0 is the on-curve
          41-master system unfolded; the off-curve chain runs on rows
          0..16 where columns 39/40 are empty).  Rows 17..40 off the
          curve are NOT established.
USAGE
  --sector63-map            the check (rc 0 PASS / 1 FAIL by name /
                            3 pin mismatch / 4 missing file)
  --sector63-map --mutate   the planted control: one coefficient changed
                            in memory (M39[18] in M41[40] at Q_m19m18:
                            2 -> 3) -> FAIL by name, rc 1
  --sector63-map --help     this text
WALLS (measured, one process, nice 10, a shared 96-core host; GNU time)
  --sector63-map            0.14 s wall, 31 MB maximum resident set (measured 2026-09-06, loadavg 97.47; exact rational arithmetic on 14 small files -- seconds on any machine)
"""


def _s63_coef(s):
    """A coefficient string of the reduction's export, '((9)/(1))',
    '(((-1))/(1))' or '((2907/287)/(1))', -> exact Fraction; the grammar
    is enforced (anything else is a FAIL by name)."""
    m = re.fullmatch(r'\(\((\(-?\d+\)|-?\d+(?:/\d+)?)\)/\((\d+)\)\)', s)
    if not m:
        raise ValueError('coefficient string outside the export grammar: %r'
                         % s)
    num = m.group(1).strip('()')
    return Fraction(num) / Fraction(m.group(2))


def _s63_parse_m(text):
    """The .m export: '{ LHS -> \\n + M*(c) \\n ... , LHS2 -> ... }' ->
    [(lhs, [(master, coef_string), ...]), ...] in file order."""
    body = text.strip()
    if not (body.startswith('{') and body.endswith('}')):
        raise ValueError('export not a { ... } block')
    out = []
    # the targets are separated by a line holding a lone comma (the
    # master names carry commas of their own)
    for blk in re.split(r'\n\s*,\s*\n', body[1:-1]):
        blk = blk.strip()
        if not blk:
            continue
        if '->' not in blk:
            raise ValueError('export block without ->: %r' % blk[:40])
        lhs, rhs = blk.split('->', 1)
        terms = []
        for ln in rhs.strip().split('\n'):
            ln = ln.strip()
            if not ln:
                continue
            if not ln.startswith('+ '):
                raise ValueError('export term not of the form + M*(c): %r'
                                 % ln)
            master, coef = ln[2:].split('*', 1)
            terms.append((master.strip(), coef.strip()))
        out.append((lhs.strip(), terms))
    return out


def _s63_check_pins():
    """Every pinned file present and byte-identical to its pin; a MISSING
    file exits 4, a mismatch REFUSES by name and exits 3 (nothing else
    is read before this)."""
    n = 0
    for rel in sorted(S63_PINS):
        p = os.path.join(S63_DIR, rel)
        if not os.path.exists(p):
            print('SECTOR63-MAP MISSING: pinned file row21_offcurve/%s is '
                  'absent (required sha256 %s)' % (rel, S63_PINS[rel]))
            sys.exit(S63_RC_MISSING)
        got = _k_sha256(p)
        if got != S63_PINS[rel]:
            print('SECTOR63-MAP REFUSED: row21_offcurve/%s sha256 %s != '
                  'pinned %s' % (rel, got, S63_PINS[rel]))
            sys.exit(S63_RC_REFUSED)
        n += 1
    print('[pins] %d shipped files verified by sha256 (14 fixtures + '
          'points/points.json + points/Q_m19m18/preferred39)' % n)


def run_sector63_map(mutate=False):
    """The check; returns 0 on PASS, 1 on the first FAIL by name (every
    point is still printed)."""
    print('=' * 74)
    print('LBL3X sector-63 convention map: M41[39], M41[40] -> the '
          'preferred39 window')
    print('  M41[39] = -M39[18];  M41[40] = M39[20] - M39[19] + 2 M39[18] '
          '+ (-t/2) M39[17] + M39[16]')
    print('  exact Fraction arithmetic at d = 101 and 102 (m2 = 1) from '
          'the 14 pinned fixtures')
    print('=' * 74)
    _s63_check_pins()
    pref = [ln.strip() for ln in
            open(os.path.join(S63_DIR, 'points', 'Q_m19m18', 'preferred39'))
            if ln.strip()]
    assert len(pref) == 39, 'preferred39 must list 39 masters'
    pts = json.load(open(os.path.join(S63_DIR, 'points', 'points.json')))
    fails = []
    rel_pass = {1: 0, 2: 0}
    exports = {}

    def relname(rel):
        return 'relation %d' % rel if rel else 'the fixture'

    def fail(tag, rel, what):
        fails.append((tag, rel, what))
        print('  FAIL %s %s: %s' % (tag, relname(rel), what))

    for tag in S63_TAGS:
        J = json.load(open(os.path.join(S63_DIR, 'fixtures',
                                        'S63_REDUCTION_%s.json' % tag)))
        mpath = os.path.join(S63_DIR, 'fixtures',
                             'kira_target_s63_%s.m' % tag)
        mtext = open(mpath).read()
        exports[tag] = mtext
        rows = J['rows']
        if mutate and tag == 'Q_m19m18':
            rows[S63_M41_40]['18']['coef_string'] = '((3)/(1))'
            for nd in S63_NODES:
                rows[S63_M41_40]['18']['at_nodes'][nd] = '3'
            print('  [--mutate] Q_m19m18: the coefficient of M39[18] in '
                  'M41[40] changed in memory 2 -> 3')
        s, t = Fraction(pts['points'][tag]['s']), Fraction(pts['points'][tag]['t'])
        mt2 = -t / 2
        ok_pt = True
        # the file-level facts
        msha = _k_sha256(mpath)
        if not (J['tag'] == tag and J['source_file_sha256'] == msha
                == S63_PINS['fixtures/kira_target_s63_%s.m' % tag]):
            fail(tag, 0, 'tag / export sha256 / pin disagree'); ok_pt = False
        if list(rows) != [S63_M41_39, S63_M41_40]:
            fail(tag, 0, 'the two targets are not M41[39], M41[40] in '
                 'order: %s' % list(rows)); ok_pt = False
        if J.get('constant') is not True:
            fail(tag, 0, 'the fixture does not state constant '
                 '(d-, m2-free) coefficients'); ok_pt = False
        if J['closed_form'] != S63_CLOSED_FORM or J['fold_rule'] != S63_FOLD_RULE:
            fail(tag, 0, 'closed_form / fold_rule strings differ from '
                 'the record\'s'); ok_pt = False
        # the two relations
        rel2 = dict(S63_REL2_CONST)
        rel2[S63_T_ENTRY] = mt2
        for rel, lhs, expect in ((1, S63_M41_39, dict(S63_REL1)),
                                 (2, S63_M41_40, rel2)):
            row = rows[lhs]
            got_keys = sorted(int(k) for k in row)
            if got_keys != sorted(expect):
                fail(tag, rel, 'M39 columns %s != %s'
                     % (got_keys, sorted(expect))); ok_pt = False
                continue
            rel_ok = True
            for k in sorted(expect):
                e = row[str(k)]
                if e['master'] != pref[k]:
                    fail(tag, rel, 'column %d names %s, preferred39 line '
                         '%d is %s' % (k, e['master'], k + 1, pref[k]))
                    rel_ok = False
                try:
                    cv = _s63_coef(e['coef_string'])
                except ValueError as err:
                    fail(tag, rel, str(err)); rel_ok = False; continue
                if cv != expect[k]:
                    fail(tag, rel, 'the coefficient of M39[%d] reads %s, '
                         'the map says %s' % (k, cv, expect[k]))
                    rel_ok = False
                for nd in S63_NODES:
                    if Fraction(e['at_nodes'][nd]) != expect[k]:
                        fail(tag, rel, 'value at %s of M39[%d] reads %s, '
                             'the map says %s'
                             % (nd, k, e['at_nodes'][nd], expect[k]))
                        rel_ok = False
                if k != S63_T_ENTRY and cv.denominator != 1:
                    fail(tag, rel, 'M39[%d] coefficient %s is not an '
                         'integer' % (k, cv)); rel_ok = False
            fm = J['fold_map'][lhs]
            if (sorted(fm['M39_index']) != sorted(expect)
                    or {int(k): Fraction(v) for k, v in fm['coef_at_101_1'].items()}
                    != expect):
                fail(tag, rel, 'the fold_map block disagrees with the rows')
                rel_ok = False
            if rel_ok:
                rel_pass[rel] += 1
            ok_pt &= rel_ok
        # the export parsed and compared with the JSON rows
        try:
            parsed = _s63_parse_m(mtext)
            if [p[0] for p in parsed] != [S63_M41_39, S63_M41_40]:
                raise ValueError('export targets %s' % [p[0] for p in parsed])
            for (lhs, terms) in parsed:
                want = [(e['master'], e['coef_string'])
                        for e in rows[lhs].values()]
                if terms != want:
                    raise ValueError('export terms of %s differ from the '
                                     'JSON rows' % lhs)
            nterms = sum(len(p[1]) for p in parsed)
        except ValueError as err:
            fail(tag, 0, 'export: %s' % err); ok_pt = False; nterms = -1
        rec = S63_MINUS_T_OVER_2[tag]
        if str(mt2) != rec:
            fail(tag, 2, '-t/2 = %s from points.json, the record lists %s'
                 % (mt2, rec)); ok_pt = False
        print('  %-11s (s, t) = (%s, %s): -t/2 = %s (record %s: %s); '
              'relation 1 M41[39] = -M39[18]: %s; relation 2 M41[40]: %s '
              '(integer entries 16, 18, 19, 20; the t-entry %s %s); '
              'export %d terms == JSON rows: %s (sha256 %s...); '
              'kira.db sha256 %s... (not shipped); point %s'
              % (tag, s, t, mt2, rec, '==' if str(mt2) == rec else '!=',
                 'PASS' if not [f for f in fails if f[0] == tag and f[1] == 1] else 'FAIL',
                 'PASS' if not [f for f in fails if f[0] == tag and f[1] == 2] else 'FAIL',
                 mt2, 'an integer' if mt2.denominator == 1 else 'not an integer',
                 nterms, 'yes' if nterms > 0 else 'NO', msha[:16],
                 S63_KIRA_DB_SHA256[tag][:16], 'PASS' if ok_pt else 'FAIL'))
    # across the seven: the exports differ only in the M39[17] line
    stripped = {tag: '\n'.join(ln for ln in txt.split('\n')
                               if not ln.strip().startswith('+ ' + pref[S63_T_ENTRY] + '*'))
                for tag, txt in exports.items()}
    same = len(set(stripped.values())) == 1
    print('  the seven exports differ only in the M39[17] (-t/2) line: %s'
          % ('yes' if same else 'NO'))
    if not same:
        fail('all', 0, 'the exports differ beyond the M39[17] line')
    print('  relation 1 (M41[39] = -M39[18]) exact at %d/7 points at d = 101 '
          'and 102' % rel_pass[1])
    print('  relation 2 (M41[40] = M39[20] - M39[19] + 2 M39[18] + (-t/2) '
          'M39[17] + M39[16]) exact at %d/7 points at d = 101 and 102'
          % rel_pass[2])
    print('  -t/2 recomputed from points.json == the record\'s list at %d/7 '
          'points' % sum(1 for tag in S63_TAGS
                         if str(-Fraction(pts['points'][tag]['t']) / 2)
                         == S63_MINUS_T_OVER_2[tag]))
    if fails:
        first = fails[0]
        print('SECTOR63-MAP FAIL by name: %s %s: %s (%d finding%s)%s'
              % (first[0], relname(first[1]), first[2], len(fails),
                 '' if len(fails) == 1 else 's',
                 ' [the --mutate control: one coefficient changed in memory]'
                 if mutate else ''))
        return S63_RC_FAIL
    print('SECTOR63-MAP PASS: 7 points x 2 relations = 14 relation checks '
          'exact at d = 101 and 102; integer everywhere except the one '
          't-dependent entry; the exports match their parsed forms')
    return 0


def _sector63_cli(args):
    if any(a in ('--help', '-h', 'help') for a in args):
        print(S63_HELP)
        return
    mutate = '--mutate' in args
    rest = [a for a in args if a != '--mutate']
    if rest:
        print('usage: lbl3x-evaluate.py --sector63-map [--mutate | --help]'
              '  (unknown: %s)' % rest)
        sys.exit(S63_RC_USAGE)
    sys.exit(run_sector63_map(mutate=mutate))




def _print_mode_line(mode):
    timings = {'default': 'cpu 97.2 s -- about two minutes on a laptop', 'full': 'cpu 351.5 s -- about six minutes on a laptop'}
    print('mode: %s -- measured %s;' % (mode.upper(), timings[mode]))
    if mode == 'default':
        print('  `--full` adds the u=17/u=50 m13 legs, Tail(-14,-3), '
              'engine B and the')
        print('  contour-deformation leg, measured %s.' % timings['full'])
    else:
        print('  the default run trims those deep legs, measured %s.'
              % timings['default'])


if __name__ == '__main__':
    if len(sys.argv) > 1 and sys.argv[1] == '--theorem-check':
        _theorem_cli(sys.argv[2:])
    elif len(sys.argv) > 1 and sys.argv[1] == '--m18-eps0':
        # FULL m18 eps^0 served live (vendored row21_chain package);
        # intercepted like --theorem-check so chain.cli owns its args.
        _m18_eps0_cli(sys.argv[2:])
    elif len(sys.argv) > 1 and sys.argv[1] == '--sector63-map':
        # 2026-09-06 sector-63 map: the 41 -> 39 convention of the two
        # spurious preferred41 masters, checked exactly on the 14 pinned
        # fixtures; intercepted like --theorem-check so the arm owns its
        # arguments.  GRAPH and THEOREM paths untouched.
        _sector63_cli(sys.argv[2:])
    elif len(sys.argv) > 1 and sys.argv[1] == '--full':
        _bind_constants_closed_forms(88)   # deepest suite use
        _print_mode_line('full')
        run_gates(full=True)
        run_block13()
        run_doubling()
        print('\ntotal wall time %.1f s (measured)' % (time.time()-T_START))
    elif len(sys.argv) > 1 and sys.argv[1] == '--kernel-info':
        print_kernel_info()
        print()
        print('[compat] --kernel-info is the light info view of the '
              'LBL3X-thm certificate')
        print('checker, kept as an alias of `--theorem-check --info` '
              '(21:5x two-objects')
        print('decision); run `--theorem-check --help` for the theorem '
              'statement + witness')
        print('contract.')
    elif len(sys.argv) > 1 and sys.argv[1] == '--k3-words':
        # 2026-07-08 row21-k3-wiring: K3-sector exact words, quoted at
        # runtime from the sha-verified vendored wordlist.  GRAPH path
        # only -- the theorem arm is untouched.
        print_k3_words()
    elif len(sys.argv) > 1 and sys.argv[1] == '--derive-constants':
        # 2026-07-06 row21-wiring (kept 2026-07-08 as the independent
        # cross-check oracle): closed-form serve + gate FIRST, then the
        # vendored leg4 derive re-gates vs the served strings and
        # rebinds; then the complete (--full) gate suite, block 13 and
        # the doubling demo.  GRAPH path only.
        dps = int(sys.argv[2]) if len(sys.argv) > 2 else 50
        _bind_constants_closed_forms(max(dps, 88))
        _derive_constants(dps)
        run_gates(full=True)
        run_block13()
        run_doubling()
        print('\ntotal wall time %.1f s (measured)' % (time.time()-T_START))
    elif len(sys.argv) > 1 and sys.argv[1] == '--point':
        if len(sys.argv) < 4:
            sys.exit('usage: lbl3x-evaluate.py --point s t [dps]   '
                     '(Euclidean s<0, t<0, u=-s-t in (2,50]; default dps 50)')
        s, t = sys.argv[2], sys.argv[3]
        dps = int(sys.argv[4]) if len(sys.argv) > 4 else 50
        _bind_constants_closed_forms(dps)  # exact closed forms + gate
        try:                          # 2026-07-08 small-u fix: named refusal
            out = f(s, t, dps=dps)
            print('f(%s, %s, dps=%d):' % (s, t, dps))
            for k, v in out.items():
                if k == 'm13_tower':
                    for n in sorted(v):
                        print('  m13 eps^%d = %s' % (n, mp.nstr(v[n], dps)))
                else:
                    print('  %s = %s'
                          % (k, mp.nstr(v, dps) if isinstance(v, (mp.mpf, mp.mpc))
                             else v))
            print('  certified seed-tail BOUND %.2e (tol 1.0e-%d; raises on '
                  'miss)'
                  % (_SEED_CACHE[dps + 15][4], dps + 15 + SEED_TAIL_GUARD))
        except ValueError as e:       # domain refusals: rc=2, fleet convention
            print('REFUSED: %s' % e)
            raise SystemExit(2)
    else:
        _bind_constants_closed_forms(88)   # deepest default-suite use
        _print_mode_line('default')
        run_gates()
        run_block13()
        run_doubling()
        print('\ntotal wall time %.1f s (measured)' % (time.time()-T_START))
