#!/usr/bin/env python3
r"""fk1-evaluate.py -- NNLO EEC F^K1(zeta): symbolic word-form evaluator
(DEFAULT, fast) + certified live ODE-transport / quadrature oracle
(--deep, the independent second leg) + live moment integrals T0, T2.

DEFAULT PATH (2026-07-06): THE SYMBOLIC WORD FORM
=================================================
This work's OP3 closure (2026-07-06) derived F^K1 itself in
explicit symbolic form -- the last external anchor of the T0/T2 frame:

    F^K1(ze) = (ze-1) * sum_{(w,mu)} r_{w,mu}(ze) * W_{w, zb(1-zb)*mu},

159 elliptic words with DERIVED Q(ze) coefficients (zero fitted; the
second-kind admixture of the zb, zb^2 measures closes on the exact recorded
relations I0 = A/3, I1 = I0/2, sigma = -(4/3)(1-ze) [theorem]).  Machine
form: fk1_words.json (vendored here from
EEC/eec/gamma16_2026-07-04/op3_fk1/, sha256-pinned below; the run REFUSES
to start if the file is absent or does not match the pin).  Their gates:
59 d @ ze=1/3 (bar 50), 51 d @ 1/2 (bar 45), 55 d @ 2/7 (bar 30; a point
never used in the construction),
two working precisions x two truncation heights (OP3_RESULT.md).

Numerically the word sum is evaluated EXACTLY as in the OP3 certification
of record (op3_fk1/fk1_eval.py; engine = the S0 sector's s0_eval.py): by the
certified Picard-Fuchs split the word combination collapses POINTWISE to
the sqrtQ-free 12-block form

    K(zb)  = sum_j coeff_j(zb) * B_j(zb),
    B_j    = int_0^zb mono_j(z(t,zb), zb) / D_K dt,
    F^K1   = (ze-1) * int_0^1 zb(1-zb) K(zb) dzb  =  (ze-1)(S1 - S2),

so one two-fold pass costs minutes, not the hours of the --deep BVP path.
FAIL-CLOSED CERTIFICATION of every word-path value, at runtime:
  (a) sha256 pin of fk1_words.json (absent/mutated data = refusal).
      THIS IS THE PRIMARY TAMPER GATE: any byte change to the data file
      is a refusal, unconditionally;
  (b) per-run SPOT GATE: the block-form K(zb) is recomputed at 4 spot
      points (incl. one in the eps<0.05 panel regime) and gated against
      certified LIVE quadrature of the K1 integrand itself (the
      independent oracle layer of this script) at >= max(dps+2, 32) d.
      This is a numeric cross-check of the decoded coefficients, but its
      bar is RELATIVE to the run depth, so its sensitivity to a
      1e-30-scale coefficient corruption is coefficient- and
      depth-dependent, NOT universal (measured 2026-07-07, verifier
      mutants: a 1e-30 blocks[0] mutation is caught at the default
      dps 32 -- 33.8 d < bar 34, rc 1 -- but passes the bar at dps 12,
      where the printed value was still correct to ~21 certified d).
      Tamper detection rests on (a); (b) guards the decode/transcription
      layer at the depth the run actually certifies;
  (c) two-height escalation: the outer/inner tanh-sinh ledger is run at
      increasing node densities until two successive heights agree to
      >= dps+2 digits (the printed certificate; cap = refusal);
  (d) the exact bookkeeping identity FK1 = (ze-1)[(2ze^2-ze)S0 - SM] is
      recomputed from independently accumulated moments and must close.

HONEST DOMAIN OF THE WORD FORM (evidence, not hope)
===================================================
The OP3 gates ran at ze = 1/3, 1/2, 2/7; 1/2 lies OUTSIDE the --deep
transport corridor [1/7, 5/13], so the word form is broader than the BVP
representation.  The 8-point hull battery (run 2026-07-07,
recorded per point; the per-angle gates are quoted below)
gated the word path (D_word = 30, two heights h = 1/17 vs 1/23;
two-height certificates 34.7-36.8 d, bar 32) at
ze = 1/10, 1/7, 3/11, 1/3, 5/13, 1/2, 3/5, 3/4 -- every point PASSED
the 30 d bar, measured gates 36.0-41.6 d.  References per point:
THIS script's live fk1_direct quadrature oracle at dps 32 at
1/10, 1/7, 5/13, 3/5, 3/4; the recorded OP3 certification-of-record
values at 1/3 (cap 59 d) and 1/2 (cap 51 d); and a further dps-32
fk1_direct value at 3/11 (certified bound 1e-40,
ratefit_oracle_D32.log).  The DEFAULT path therefore accepts
ze in [1/10, 3/4] (the gated hull) and REFUSES outside it unless
--live-gate is given, in which case the requested point is gated live
against the quadrature oracle at >= min(dps, 30) d (fail-closed) --
the same gate the five live-oracle hull points passed.

WHAT THE --deep PATH COMPUTES (the independent second leg -- kept fully
functional; it shares NOTHING numerical with the word data)
================
F^K1(zeta) = int_0^1 dzb int_0^zb dt  [a1/D_K] * P1(z(t,zb;zeta), zb),
  a1 = -zb(zb-1)(zeta-1),  D_K = (1-t)(1-zb)zb + zeta(t-zb)(1-t-zb),
the genuinely-elliptic K1 piece of the NNLO EEC remainder in N=4 sYM
(integrand from Henn-Sokatchev-Yan-Zhiboedov, arXiv:1903.05314, eq. 19,
after the exact partial-fraction split of this work), and
the two open moment constants
  T_k(zeta) = int_0^1 u^k K(u) / Q(u;zeta) du   (k = 0, 2),
  K(u)  = [ int_0^u f_K1(t; u, zeta) dt ] / ( -u(u-1)(zeta-1) ),
  Q     = u^4 - 2u^3 + (4z^2-2z+1)u^2 - (4z^2-2z)u + z^2  (z = zeta),
to which the certified Picard-Fuchs normal form collapses the entire
elliptic content of the source.

THE BOOTSTRAPPED ROUTE (everything live, from the integrand definition)
=======================================================================
  (1) OPERATOR.  L = z(z-1)(8z+1) d^2 + (8z^2+1) d - (2z+1)/z, the
      equal-mass-sunrise Picard-Fuchs operator pulled back to the angle
      variable (exact rational coefficients -- this work's certified
      Griffiths-Dwork identity; runtime-selftested here, see (S)).
  (2) SOURCE.  S(z) = L[F^K1](z) = int int L[a1/D_K * P1] -- the operator
      commutes into the integral; the closed-form integrand L[G] is
      transcribed here (pref1/P1 zeta-derivative layer) and every S(ze_j)
      at the M Chebyshev-Gauss collocation nodes on [1/7, 5/13] is
      recomputed ANALYTICALLY AT RUNTIME by certified two-fold quadrature.
      No stored source nodes, no precomputed data.
  (3) ANCHORS.  Two boundary rows F(1/7), F(1/3), each recomputed live by
      the certified two-fold quadrature of the F^K1 integrand itself.
      Deliberate design change vs the original script: the second row is a
      VALUE row (BVP form), not the stored complex-step derivative
      F'(1/7) whose silent cs21->cs18 file fallback capped the archived
      chain at ~36 d (RECOMPUTE_SPEC_EEC.md finding, 2026-07-05).  There
      is NO stored-file fallback anywhere in this script.
  (4) SOLVE.  Square spectral collocation: ODE rows at the M nodes +
      2 anchor rows, Chebyshev basis of degree M+1, exact-rational
      operator coefficients, mp.lu_solve at dps+30.
  (5) GATE (the certificate).  Every transported value is gated AT ITS OWN
      POINT against a live INDEPENDENT oracle -- direct certified two-fold
      quadrature of the F^K1 integrand, which never touches the operator,
      the source, or the solve.  The printed error bound is
        |transported - oracle| + oracle_bound + propagated_source_bound,
      and the run RAISES if it misses the --dps bar (fail-closed).
  (6) MOMENTS.  T0, T2 by live nested certified quadrature (kernel cache),
      refine-until-bound.  These two constants are NOT identified in
      closed form (archived 100-digit PSLQ searches saturate honestly);
      this script prints certified numerical values, nothing more.

FAIL-CLOSED CONTRACT (runtime bounds -- no frozen depths on the value path)
===========================================================================
Every quadrature runs inside a refine-until-bound loop: nested tanh-sinh
levels are escalated until the double-refinement agreement |I_d - I_{d-1}|
beats 10^-(dps+guard); non-convergence at the depth cap RAISES with the
measured agreement, tol, depth and cap named -- a value the loop did not
certify is never printed.  (Same semantics as tools/detransport/quad.py
[E3], vendored inline because this script must stay dependency-free
beyond mpmath; deliberately more conservative than mpmath's own
extrapolated estimate.)  The collocation grid size M is seeded from the
measured truncation slope (0.62 digits/degree, recorded control scan;
0.5 used conservatively) and then VALIDATED at runtime by a
manufactured-solution control (same operator, same grid, same anchor
structure, same singularity class log^2(z) at z=0): the control must
reproduce its exact solution to dps+2 digits before any expensive
quadrature is spent, and the grid auto-escalates if it does not.  All
knobs are speed seeds, never answers.

RUNTIME SELFTESTS (S) -- run on every invocation, RAISE on failure
==================================================================
  * closed-form pref1 zeta-derivatives vs mp.diff (transcription guard);
  * assembled L[G] Taylor data (dG, d2G) vs mp.diff of G;
  * the two INDEPENDENT transcriptions of the K1 integrand (oracle layer
    vs derivative layer) agree pointwise.  Detection floor: relative
    1e-40 (XLAYER_EXP), tightened 2026-07-05 from 1e-30 after measuring
    the true cross-layer agreement at the selftest precision (159 bits):
    bit-exact at all probe points, so a 1e-30 mutation of an O(1)
    constant now overshoots the gate by ~10 digits (it previously sat
    exactly AT the strict-> threshold).  The measured worst cross-layer
    agreement is printed on every run;
  * manufactured-solution solver control (see above).

ARCHIVED CONTEXT (quoted as archived -- not recomputed here)
============================================================
This work's end-to-end certification of F^K1 as the unique solution of
its ODE reached 34.57-34.99 d at three never-used angles (2026-07-04 recert,
dps50/M60 sources; eecnote.tex), and a dps75/90 M=128 source run targeting
>= 60 d was in flight on 2026-07-05.  Those numbers rest on that archive's
own inputs; the digits THIS script prints are certified live at the depth
of the current run.

HONEST LIMITATIONS
==================
  * The live gate runs at the depth --dps buys.  Measured 2026-07-05
    (reference run, 8 parallel workers,
    single-thread rates): default --dps 20 = 15.2 min wall
    (104 CPU-min; per source node 88 s, moments 216 s, oracle 88 s),
    landing a 29.2-29.9 d measured gate agreement and a certified
    27.9-28.0 d >= the 20 d bar.  It does NOT re-establish the archived
    35 d claim live.
  * Cost scaling: the source-node evaluations dominate and each tanh-sinh refinement
    level roughly DOUBLES the cost of every fold (levels square the
    error, so cost is quantized in big steps).  Measured: dps 26 (one
    level deeper in both folds, M=45) = 63.7 min wall, 468 CPU-min,
    4.5x the dps-20 CPU (load rose to ~1.6x CPU-oversubscription during that pass; certified
    30.0-30.2 d, now truncation-limited, and the --check crank verdict
    was CONSISTENT with 29.2-30.4 d cross-run value agreement).  The grid
    adds ~2 nodes per requested digit past the M=44 ceiling (measured
    27.65 d).
    Reaching the archived >= 60 d live is a ~100+ CPU-hour run (that is
    what the archived production run did) -- this script will do it fail-closed,
    but plan the wall time.
  * Transport corridor: zeta in [1/7, 5/13] (the certified interval; the
    collocation representation is not valid outside it).  Moments are
    computed at any zeta in (0,1) for which Q has no real root on (0,1)
    (a root raises fail-closed).

INTERFACE
=========
  default        WORD-FORM evaluation of F^K1 at --point (default 1/3)
                 at --dps (default 12) certified digits, fail-closed
                 gates (a)-(d) above.  Measured walls, load-sensitive:
                 dps 12 = 46.7 s near-idle, 84-178 s ~1.7x CPU-oversubscribed
                 (verifier reruns, 2026-07-07), 202.4 s wall / 158.1 s
                 user CPU ~4.8x CPU-oversubscribed (default-change run, log
                 stamps 2026-09-03T04:35:01Z..04:38:29Z UTC).
                 --dps 32 (the pre-2026-09-03 default) = 454.5 s
                 near-idle (default_D32.log).
  --point P/Q    evaluation angle.  Word path: ze in the gated hull
                 [1/10, 3/4] (or any ze in (0,1) with --live-gate).
                 Deep path: ze in the transport corridor [1/7, 5/13].
  --dps D        certified-digit request (word default 12, deep default
                 20; --dps 32 reproduces the deeper pre-2026-09-03 word
                 default).  Every printed value carries a runtime
                 certificate at >= D digits, fail-closed.
  --live-gate    word path only: ALSO run the independent certified
                 quadrature oracle (fk1_direct, this script's --deep
                 oracle layer) at the same point and gate the word value
                 against it at >= min(D, 30) d (nonzero exit on a miss).
                 This is the two-leg cross-check and the domain-extension
                 mechanism; budget minutes-class extra wall.
  --deep         the certified live ODE-transport evaluator (the
                 independent second leg; everything below unchanged).
                 Without --point: gate demo at the gate angles 3/11
                 and 5/13 + T0, T2 at zeta = 1/3.
  --moments P/Q  T0, T2 at zeta = P/Q only (live quadrature; no word
                 data, no transport; works in either mode).
  --workers N    parallel workers (default min(8, cpu); the word ledger
                 shards over them too).
  --check [STEP] crank test.  Word path: rerun at dps D+STEP (default
                 +40) with its own fail-closed certificate; the two
                 values must agree to >= D digits (nonzero exit).  Deep
                 path: as before (default +6, gates AND the T0/T2 moment
                 pair, fail-closed).

Changelog:
  2026-07-05  created (assessed-then-built from the source
              artifacts {oracle_K,lsun_K,dintegrand2,
              close7_transport}.py; all eval-path
              inputs recomputed live, fail-closed loops, BVP
              anchor rows replace the stored-dF fallback).
  2026-07-05b wave-2 verifier follow-up (fk1-checkcrank): T0/T2 moments
              bundled into the --check crank (both runs recompute them
              live; pair gated at >= D digits, fail-closed nonzero exit);
              selftest (c) detection floor measured (bit-exact at 159
              bits) and tightened 1e-30 -> 1e-40 (XLAYER_EXP) so
              1e-30 mutations FAIL LOUDLY instead of sitting at the
              threshold; floor printed honestly every run.  No numeric
              value paths touched.
  2026-07-06  OP3 word form switched in: this work's OP3
              symbolic closure (fk1_words.json, 159 derived words, zero
              fitted; OP3_RESULT.md gates 59/51/55 d) becomes the DEFAULT
              evaluation path -- engine vendored from the OP3
              certification of record (op3_fk1/fk1_eval.py + symb_ell/
              s0_eval.py), sha256-pinned data, per-run live spot gate vs
              this script's own quadrature oracle layer, two-height
              fail-closed certificate, evidence-based domain hull with
              --live-gate escape.  The previous default (ODE-transport
              BVP + live oracle) DEMOTES intact to --deep: it is the
              independent second leg and the oracle used to gate the
              word path.  Word --check crank default +40.
  2026-07-07  fk1-wordform close-out (text-only; no numeric path
              touched).  The 8-point hull battery was RUN and recorded
              (per-angle gate files; the 2026-07-06 text
              had claimed it ahead of the evidence -- corrected): every
              point PASSED, gates 36.0-41.6 d vs bar 30, word two-height
              certificates 34.7-36.8 d vs bar 32.  Docstring walls
              corrected to the measured load-sensitive class (dps 12:
              46.7 s idle / 84-178 s at load ~160; dps 32: 454.5 s).
              Spot-gate claim made honest: its bar is depth-relative,
              so 1e-30 sensitivity is coefficient- and depth-dependent
              (verifier mutant measurements quoted); the sha256 pin is
              the primary tamper gate.
  2026-09-03  page-speed default (no numeric path touched): word-path
              default dps 32 -> 12, so the no-flag run lands in minutes
              even on a busy machine (measured walls in the INTERFACE
              block; --dps 32 reproduces the old default exactly -- the
              printed dps-12 digits are a prefix of the dps-32 value).
              stdout switched to line buffering at startup so the first
              line appears within seconds through a pipe.  All gates,
              bars, and the --deep leg unchanged.
"""
import argparse
import hashlib
import json
import math
import multiprocessing
import os
import re
import sys
import time
from fractions import Fraction

import mpmath as mp
from mpmath.calculus.quadrature import TanhSinh

# ---------------------------------------------------------------------------
# problem constants (exact rationals -- they DEFINE the problem, no decimals)
# ---------------------------------------------------------------------------
ZLO, ZHI = Fraction(1, 7), Fraction(5, 13)      # transport corridor
CQ = (ZLO + ZHI) / 2                            # 24/91
HQ = (ZHI - ZLO) / 2                            # 11/91
ANCHORS = [Fraction(1, 7), Fraction(1, 3)]      # BVP anchor rows (live)
GATE_PTS = [Fraction(3, 11), Fraction(5, 13)]   # gate angles (never used in the construction)
MOMENT_PT = Fraction(1, 3)                      # default moment point

# guard digits (calibrated 2026-07-05, fk1-build row report; all are seeds
# of fail-closed loops -- they set tolerances, never answers)
G_NODE, G_ANCH, G_ORC, G_MOM, G_KER = 6, 8, 6, 6, 10
INNER_DROP = 2          # inner-quad tol = outer tol * 10^-INNER_DROP
WP_EXTRA = 12           # working-precision headroom above dps+guard
DEPTH_EXTRA = 5         # tanh-sinh escalation cap = seed depth + this
SLOPE = 0.5             # digits/degree used for grid sizing (measured 0.62)
CEIL44 = 27.5           # measured M=44 truncation ceiling (27.65 d)
KER_AMP = 3             # log-of-budget for kernel-error amplification (see
                        # moments(): tanh-sinh weights beat the 1/u factor;
                        # budgeted at 10^KER_AMP, policed by the outer
                        # double-refinement agreement, which cannot beat tol
                        # on a kernel-noise plateau)
XLAYER_EXP = 40         # selftest (c) detection floor: the oracle-layer /
                        # derivative-layer cross-check RAISES above relative
                        # 10^-XLAYER_EXP.  Tightened 2026-07-05 from 30 after
                        # measuring the actual cross-layer agreement at the
                        # selftest precision (159 bits ~ 47.9 d): bit-exact
                        # (0.0) at all probe points (fk1-checkcrank/
                        # probe_floor.log), so 1e-40 sits >= 5 d above any
                        # realistic platform round-off while a 1e-30 mutation
                        # of an O(1) constant overshoots the gate by ~10 d
                        # (the old floor put such mutations exactly AT the
                        # strict-> threshold: detection depended on last-bit
                        # rounding direction)


def digits(a, b):
    """-log10 |a-b|/|b|: measured agreement in decimal digits."""
    if a == b:
        return float('inf')
    return float(-mp.log10(abs((a - b) / b)))


def _mpq(fr):
    return mp.mpf(fr.numerator) / fr.denominator


# ---------------------------------------------------------------------------
# certified quadrature: refine-until-bound, fail-closed
# (tools/detransport/quad.py [E3] semantics, vendored for self-containment)
# ---------------------------------------------------------------------------
_TS = None


def _rule():
    global _TS
    if _TS is None:
        _TS = TanhSinh(mp.mp)      # the CONTEXT, not the module
    return _TS


class CertFail(RuntimeError):
    """Fail-closed refusal: a loop could not certify its bound."""


def cert_quad(f, a, b, tol_exp, wp, tag=""):
    """Integrate f over [a,b]; return (value, agreement, depth) with the
    double-refinement agreement |I_d - I_{d-1}| <= 10^-tol_exp.

    Nested tanh-sinh levels; escalation is exact continuation (each new
    depth adds interleaved nodes and reuses the previous sum).  Acceptance
    is ONLY by the measured agreement; hitting the depth cap or a
    non-finite level sum RAISES with named diagnostics."""
    prec = int(wp * 3.3333) + 10
    with mp.workprec(prec):
        a, b = mp.convert(a), mp.convert(b)
        if a == b:
            return mp.mpf(0), mp.mpf(0), 0
        tol = mp.mpf(10) ** (-tol_exp)
        rule = _rule()
        cap = max(rule.guess_degree(prec), 3) + DEPTH_EXTRA
        results, agr = [], None
        for depth in range(1, cap + 1):
            nodes = rule.get_nodes(a, b, depth, prec)
            I = rule.sum_next(f, nodes, depth, prec, results)
            results.append(I)
            if not (mp.isfinite(mp.re(I)) and mp.isfinite(mp.im(I))):
                raise CertFail(
                    "[%s] certified quadrature FAILED (fail-closed): "
                    "non-finite level sum at depth %d on [%s, %s] -- "
                    "integrand diverges / pole on path" %
                    (tag, depth, mp.nstr(a, 8), mp.nstr(b, 8)))
            if depth >= 2:
                agr = abs(results[-1] - results[-2])
                if agr <= tol:
                    return results[-1], agr, depth
        raise CertFail(
            "[%s] certified quadrature FAILED (fail-closed): "
            "double-refinement agreement %s >= tol %s at depth %d "
            "(cap %d, wp %d) on [%s, %s]" %
            (tag, mp.nstr(agr, 3), mp.nstr(tol, 3), cap, cap, wp,
             mp.nstr(a, 8), mp.nstr(b, 8)))


# ---------------------------------------------------------------------------
# closed-form integrand layer
# (inlined from the source modules {oracle.py, oracle_K.py,
#  dintegrand2.py, lsun_K.py}; the ORACLE layer and the DERIVATIVE layer are
#  two independent transcriptions and are cross-checked at runtime)
# ---------------------------------------------------------------------------
def _S12(x):
    """Nielsen S_{1,2}(x) = -Li3(1-x) + log(1-x)Li2(1-x)
       + (1/2)log(x)log^2(1-x) + zeta(3)."""
    return (-mp.polylog(3, 1 - x) + mp.log(1 - x) * mp.polylog(2, 1 - x)
            + mp.mpf(1) / 2 * mp.log(x) * mp.log(1 - x) ** 2 + mp.zeta(3))


def D_K(t, zb, zeta):
    return (1 - t) * (1 - zb) * zb + zeta * (t - zb) * (1 - t - zb)


def make_inner_K1(zb, zeta):
    """ORACLE layer: fast inner integrand f(t) of the K1 piece,
    (a1/D_K) * P1(z(t), zb) with the zb-constant HPLs precomputed
    (transcribed from oracle_K.make_inner_K1)."""
    H1_1zb = -mp.log(zb)
    H1zb = -mp.log(1 - zb)
    H2_1zb = mp.polylog(2, 1 - zb)
    H3_1zb = mp.polylog(3, 1 - zb)
    H11_1zb = mp.log(zb) ** 2 / 2
    S12_1zb = _S12(1 - zb)
    H21_1zb = S12_1zb
    H12_1zb = -mp.log(zb) * mp.polylog(2, 1 - zb) - 2 * S12_1zb
    H111_1zb = -mp.log(zb) ** 3 / 6
    a1 = -zb * (zb - 1) * (zeta - 1)

    def f(t):
        # tanh-sinh endpoint nodes can round ONTO an endpoint at working
        # precision; there the integrand is (vanishing prefactor) x
        # log-powers with limit 0 in measure, and the node weight is
        # < 10^-wp, far below every certified agreement gate.
        if t <= 0 or t >= zb:
            return mp.mpf(0)
        # den in the cancellation-free form zeta*(t-zb) + zb*(1-t)
        # (== t*(zeta-zb) + (1-zeta)*zb, which loses ALL digits at
        # tanh-sinh nodes with t ~ zb ~ 1)
        den = zeta * (t - zb) + zb * (1 - t)
        z = zeta * t * (t - zb) / den
        pref1 = a1 / D_K(t, zb, zeta)
        H0mz = mp.log(-z)
        L1z = mp.log(1 - z)
        H1z = -L1z
        H2z = mp.polylog(2, z)
        H3z = mp.polylog(3, z)
        H11z = L1z ** 2 / 2
        H21z = _S12(z)
        H111z = -L1z ** 3 / 6
        p1 = -(
            H0mz ** 2 * (H1z - H1_1zb)
            + 4 * H0mz * (-H2z + H2_1zb)
            + 2 * H1zb * (-(H1z * H1_1zb) + H0mz * (-H1z + H1_1zb)
                          + H2z - H2_1zb + H11z + H11_1zb)
            + 2 * (3 * H3z - 3 * H3_1zb + H1_1zb * H11z
                   - H1z * (H2_1zb + H11_1zb)
                   + H12_1zb + H21z + H21_1zb - H111z + H111_1zb)
        ) / 8
        return pref1 * p1
    return f


# ---- DERIVATIVE layer (for the source S = L[F^K1]) -------------------------
def _z_and_dzeta(t, zb, zeta):
    """z(t,zb;zeta) and its first two zeta-derivatives (den linear in zeta).
    den is written in the cancellation-free form (see make_inner_K1)."""
    den = zeta * (t - zb) + zb * (1 - t)
    num = zeta * t * (t - zb)
    z = num / den
    dnum = t * (t - zb)
    dden = t - zb
    dz = (dnum * den - num * dden) / den ** 2
    d2z = -2 * dden * dz / den
    return z, dz, d2z


def _zb_consts(zb):
    """The zb-constant HPL block of P1 (hoisted so per-t evaluations do not
    recompute it; ~1.7x on the source batch)."""
    S12_1zb = _S12(1 - zb)
    Li2_1zb = mp.polylog(2, 1 - zb)
    return (-mp.log(zb),                                # H1_1zb
            -mp.log(1 - zb),                            # H1zb
            Li2_1zb,                                    # H2_1zb
            mp.polylog(3, 1 - zb),                      # H3_1zb
            mp.log(zb) ** 2 / 2,                        # H11_1zb
            -mp.log(zb) * Li2_1zb - 2 * S12_1zb,        # H12_1zb
            S12_1zb,                                    # H21_1zb
            -mp.log(zb) ** 3 / 6)                       # H111_1zb


def _P1_d2(z, zb, zbc=None):
    """(P1, dP1/dz, d2P1/dz2) -- weight-3 HPL block of the K1 piece."""
    L1 = mp.log(1 - z)
    Li2 = mp.polylog(2, z)
    Li3 = mp.polylog(3, z)
    H0mz = mp.log(-z)
    H1z = -L1
    H2z = Li2
    H3z = Li3
    H11z = L1 ** 2 / 2
    H21z = _S12(z)
    H111z = -L1 ** 3 / 6
    (H1_1zb, H1zb, H2_1zb, H3_1zb, H11_1zb, H12_1zb, H21_1zb,
     H111_1zb) = zbc if zbc is not None else _zb_consts(zb)

    P1 = -(
        H0mz ** 2 * (H1z - H1_1zb) + 4 * H0mz * (-H2z + H2_1zb)
        + 2 * H1zb * (-(H1z * H1_1zb) + H0mz * (-H1z + H1_1zb)
                      + H2z - H2_1zb + H11z + H11_1zb)
        + 2 * (3 * H3z - 3 * H3_1zb + H1_1zb * H11z
               - H1z * (H2_1zb + H11_1zb)
               + H12_1zb + H21z + H21_1zb - H111z + H111_1zb)
    ) / 8
    dH0mz = 1 / z
    dH1z = 1 / (1 - z)
    dH2z = -L1 / z
    dH3z = Li2 / z
    dH11z = -L1 / (1 - z)
    dH21z = L1 ** 2 / (2 * z)
    dH111z = L1 ** 2 / (2 * (1 - z))
    dP1 = -(
        2 * H0mz * dH0mz * (H1z - H1_1zb) + H0mz ** 2 * dH1z
        + 4 * dH0mz * (-H2z + H2_1zb) + 4 * H0mz * (-dH2z)
        + 2 * H1zb * (-(dH1z * H1_1zb) + dH0mz * (-H1z + H1_1zb)
                      + H0mz * (-dH1z) + dH2z + dH11z)
        + 2 * (3 * dH3z + H1_1zb * dH11z - dH1z * (H2_1zb + H11_1zb)
               + dH21z - dH111z)
    ) / 8
    d2H0mz = -1 / z ** 2
    d2H1z = 1 / (1 - z) ** 2
    d2H2z = 1 / (z * (1 - z)) + L1 / z ** 2
    d2H3z = (-L1 - Li2) / z ** 2
    d2H11z = (1 - L1) / (1 - z) ** 2
    d2H21z = -L1 / (z * (1 - z)) - L1 ** 2 / (2 * z ** 2)
    d2H111z = -L1 / (1 - z) ** 2 + L1 ** 2 / (2 * (1 - z) ** 2)
    d2P1 = -(
        2 * (dH0mz ** 2 + H0mz * d2H0mz) * (H1z - H1_1zb)
        + 2 * H0mz * dH0mz * dH1z
        + 2 * H0mz * dH0mz * dH1z + H0mz ** 2 * d2H1z
        + 4 * d2H0mz * (-H2z + H2_1zb) + 4 * dH0mz * (-dH2z)
        + 4 * dH0mz * (-dH2z) + 4 * H0mz * (-d2H2z)
        + 2 * H1zb * (-(d2H1z * H1_1zb) + d2H0mz * (-H1z + H1_1zb)
                      + dH0mz * (-dH1z) + dH0mz * (-dH1z)
                      + H0mz * (-d2H1z) + d2H2z + d2H11z)
        + 2 * (3 * d2H3z + H1_1zb * d2H11z - d2H1z * (H2_1zb + H11_1zb)
               + d2H21z - d2H111z)
    ) / 8
    return P1, dP1, d2P1


def _pref1_and_dzeta(t, zb, zeta):
    """pref1 = a1/D_K and its first two zeta-derivatives (both zeta-linear)."""
    C = -zb * (zb - 1)
    a1 = C * (zeta - 1)
    da1 = C
    D0 = (1 - t) * (1 - zb) * zb
    E = (t - zb) * (1 - t - zb)
    DK = D0 + zeta * E
    dDK = E
    pref1 = a1 / DK
    dpref1 = (da1 * DK - a1 * dDK) / DK ** 2
    d2pref1 = -2 * da1 * dDK / DK ** 2 + a1 * 2 * dDK ** 2 / DK ** 3
    return pref1, dpref1, d2pref1


def Lcoef(ze):
    """The pulled-back sunrise Picard-Fuchs operator L (exact)."""
    A2 = ze * (ze - 1) * (8 * ze + 1)
    A1 = 8 * ze ** 2 + 1
    A0 = -(2 * ze + 1) / ze
    return A2, A1, A0


def LsunG_K1(t, zb, zeta, zbc=None):
    """L applied under the integral: L[pref1*P1] at fixed (t, zb).
    S(zeta) = int_0^1 dzb int_0^zb dt of this (the ODE source)."""
    z, dz, d2z = _z_and_dzeta(t, zb, zeta)
    pref1, dpref1, d2pref1 = _pref1_and_dzeta(t, zb, zeta)
    P1, dP1_dz, d2P1_dz = _P1_d2(z, zb, zbc)
    dP1 = dP1_dz * dz
    d2P1 = d2P1_dz * dz ** 2 + dP1_dz * d2z
    G = pref1 * P1
    dG = dpref1 * P1 + pref1 * dP1
    d2G = d2pref1 * P1 + 2 * dpref1 * dP1 + pref1 * d2P1
    A2, A1, A0 = Lcoef(zeta)
    return A2 * d2G + A1 * dG + A0 * G


def Qquartic(u, zeta):
    return (u ** 4 - 2 * u ** 3 + (4 * zeta ** 2 - 2 * zeta + 1) * u ** 2
            - (4 * zeta ** 2 - 2 * zeta) * u + zeta ** 2)


# ---------------------------------------------------------------------------
# certified integral objects (all live, all refine-until-bound)
# ---------------------------------------------------------------------------
def fk1_direct(fr, D, guard, tag):
    """Certified two-fold F^K1(zeta): the independent oracle route.
    Returns (value_re, err_bound, outer_depth)."""
    wp = D + guard + WP_EXTRA
    inner_exp = D + guard + INNER_DROP
    with mp.workprec(int(wp * 3.3333) + 10):
        zeta = _mpq(fr)
        floor = mp.mpf(10) ** (-(wp - 6))

        def outer(zb):
            # endpoint-rounded tanh-sinh node: the discarded contribution
            # is <= zb * log^2-factors < 10^-(D+guard+8), below every gate
            if zb <= floor or 1 - zb <= floor:
                return mp.mpf(0)
            f = make_inner_K1(zb, zeta)
            v, _, _ = cert_quad(f, mp.mpf(0), zb, inner_exp, wp,
                                tag=tag + ".inner")
            return v

        val, agr, depth = cert_quad(outer, 0, 1, D + guard, wp, tag=tag)
        bound = (agr + mp.mpf(10) ** (-inner_exp) + abs(mp.im(val))
                 + mp.mpf(10) ** (-(wp - 6)) * max(mp.mpf(1), abs(val)))
        return mp.re(val), bound, depth


def src_node(j, M, D, tag):
    """Certified two-fold S(ze_j) = L[F^K1](ze_j) at collocation node j
    of the M-node Chebyshev-Gauss grid.  Returns (S_re, bound, depth)."""
    wp = D + G_NODE + WP_EXTRA
    inner_exp = D + G_NODE + INNER_DROP
    with mp.workprec(int(wp * 3.3333) + 10):
        ze = _mpq(CQ) + _mpq(HQ) * mp.cos(mp.pi * (2 * j + 1) / (2 * M))
        floor = mp.mpf(10) ** (-(wp - 6))

        def outer(zb):
            if zb <= floor or 1 - zb <= floor:   # see fk1_direct.outer
                return mp.mpf(0)
            zbc = _zb_consts(zb)
            v, _, _ = cert_quad(lambda t: mp.mpf(0) if (t <= 0 or t >= zb)
                                else LsunG_K1(t, zb, ze, zbc), mp.mpf(0), zb,
                                inner_exp, wp, tag=tag + ".inner")
            return v

        val, agr, depth = cert_quad(outer, 0, 1, D + G_NODE, wp, tag=tag)
        bound = (agr + mp.mpf(10) ** (-inner_exp) + abs(mp.im(val))
                 + mp.mpf(10) ** (-(wp - 6)) * max(mp.mpf(1), abs(val)))
        return mp.re(val), bound, depth


def moments(fr, D, tag):
    """Certified T0, T2 at zeta = fr: outer refine-until-bound over the
    kernel K(u) (itself a certified inner quadrature, cached per u).
    Returns (T0, bound0, T2, bound2).

    Error accounting: outer double-refinement agreement + the kernel
    tolerance amplified by the budget factor 10^KER_AMP (the a1-division
    1/(u(1-u)) grows polynomially while tanh-sinh endpoint weights decay
    double-exponentially, so the true amplification is logarithmic; a
    kernel-noise plateau above tol would FAIL the outer agreement gate,
    fail-closed)."""
    wp = D + G_MOM + WP_EXTRA
    ker_exp = D + G_KER
    with mp.workprec(int(wp * 3.3333) + 10):
        zeta = _mpq(fr)
        floor = mp.mpf(10) ** (-(wp - 6))
        cache = {}

        def K(u):
            if u not in cache:
                f = make_inner_K1(u, zeta)
                v, _, _ = cert_quad(f, mp.mpf(0), u, ker_exp, wp,
                                    tag=tag + ".kernel")
                cache[u] = v / (-u * (u - 1) * (zeta - 1))
            return cache[u]

        out = []
        for k in (0, 2):
            val, agr, depth = cert_quad(lambda u: mp.mpf(0)
                                        if (u <= floor or 1 - u <= floor)
                                        else u ** k * K(u)
                                        / Qquartic(u, zeta),
                                        0, 1, D + G_MOM, wp,
                                        tag="%s.T%d" % (tag, k))
            bound = (agr + mp.mpf(10) ** (-(ker_exp - KER_AMP))
                     + abs(mp.im(val))
                     + mp.mpf(10) ** (-(wp - 6)) * max(mp.mpf(1), abs(val)))
            out += [mp.re(val), bound]
        return tuple(out)


# ---------------------------------------------------------------------------
# OP3 SYMBOLIC WORD FORM -- the DEFAULT (fast) evaluation path
#
# Data: fk1_words.json, vendored 2026-07-06 from this work's OP3
# closure (op3_fk1/fk1_words.json, recorded gates
# 59/51/55 d, OP3_RESULT.md).  159 words, derived Q(ze) coefficients, ZERO
# fitted; the 12-block sqrtQ-free form below is pointwise-equal to the word
# sum by the certified PF split, and IS the numeric route of the OP3 gates
# of record.  Engine transcribed from op3_fk1/fk1_eval.py + symb_ell/
# s0_eval.py (same formulas, same panel structure; block coefficients are
# parsed exactly from the pinned JSON with a small Fraction-polynomial
# evaluator instead of sympy, so this script stays mpmath-only).
# ---------------------------------------------------------------------------
WORDS_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                          "fk1_words.json")
WORDS_SHA256 = ("77dfc3a3b80e1774c79fa3144cf93726"
                "c43311e5b6ad3062d22d773eb893cc77")
# evidence-gated hull of the word form (8-point battery, run
# 2026-07-07: word value vs per-point reference >= 30 d at ze = 1/10,
# 1/7, 3/11, 1/3, 5/13, 1/2, 3/5, 3/4, measured gates 36.0-41.6 d;
# recorded per-angle gates -- see module docstring).  Outside:
# fail-closed refusal unless --live-gate re-establishes the gate live.
WORD_ZLO, WORD_ZHI = Fraction(1, 10), Fraction(3, 4)
WORD_SPOT_ZB = ("0.19", "0.53", "0.81", "0.97")   # 0.97 = panel regime
WORD_MUT_EXP = 32       # spot-gate bar >= max(D+2, 32).  Bar-RELATIVE:
                        # a 1e-30 rel corruption of a block coefficient
                        # is caught when it lands below the bar (measured
                        # blocks[0]: caught at dps 32, passes at dps 12)
                        # -- the sha256 pin is the primary tamper gate
WORD_GUARD = 10         # working dps = D + WORD_GUARD on the ledger

# the 12 block monomials over (L0, L1, Li2, Li3, S12) at z = z(t,zb) --
# fixed order asserted against the pinned JSON at load time
W_BLOCK_MONOS = [(2, 1, 0, 0, 0), (2, 0, 0, 0, 0), (1, 1, 0, 0, 0),
                 (1, 0, 1, 0, 0), (1, 0, 0, 0, 0), (0, 3, 0, 0, 0),
                 (0, 2, 0, 0, 0), (0, 1, 0, 0, 0), (0, 0, 1, 0, 0),
                 (0, 0, 0, 1, 0), (0, 0, 0, 0, 1), (0, 0, 0, 0, 0)]


class _WPoly(object):
    """Exact polynomial over Fraction in the 5 zb-constants
    (lz, l1, La2, La3, Si12) -- just enough arithmetic to evaluate the
    sympy-printed block-coefficient strings of the pinned JSON."""
    __slots__ = ("d",)

    def __init__(self, d):
        self.d = {k: v for k, v in d.items() if v != 0}

    @staticmethod
    def _as(o):
        if isinstance(o, _WPoly):
            return o
        return _WPoly({(0, 0, 0, 0, 0): Fraction(o)})

    def __add__(self, o):
        o = self._as(o)
        d = dict(self.d)
        for k, v in o.d.items():
            d[k] = d.get(k, Fraction(0)) + v
        return _WPoly(d)
    __radd__ = __add__

    def __neg__(self):
        return _WPoly({k: -v for k, v in self.d.items()})

    def __sub__(self, o):
        return self + (-self._as(o))

    def __rsub__(self, o):
        return self._as(o) + (-self)

    def __mul__(self, o):
        o = self._as(o)
        d = {}
        for k1, v1 in self.d.items():
            for k2, v2 in o.d.items():
                k = tuple(a + b for a, b in zip(k1, k2))
                d[k] = d.get(k, Fraction(0)) + v1 * v2
        return _WPoly(d)
    __rmul__ = __mul__

    def __truediv__(self, o):
        if isinstance(o, _WPoly):
            if list(o.d.keys()) != [(0, 0, 0, 0, 0)]:
                raise CertFail("word data parse: division by non-constant")
            o = o.d[(0, 0, 0, 0, 0)]
        return self * Fraction(1, 1) * Fraction(o) ** -1

    def __pow__(self, n):
        n = int(Fraction(n))
        out = _WPoly({(0, 0, 0, 0, 0): Fraction(1)})
        for _ in range(n):
            out = out * self
        return out


def _parse_block_coeff(s):
    """'-La2/2 - l1*lz/4' -> [(Fraction, exponent-tuple), ...], exactly."""
    env = {"__builtins__": {}, "F": Fraction}
    for i, name in enumerate(("lz", "l1", "La2", "La3", "Si12")):
        e = [0, 0, 0, 0, 0]
        e[i] = 1
        env[name] = _WPoly({tuple(e): Fraction(1)})
    expr = re.sub(r"(?<![\w.])(\d+)(?![\w.])", r"F(\1)", s)
    val = eval(expr, env)                     # sha-pinned data only
    val = _WPoly._as(val)
    return [(v, k) for k, v in sorted(val.d.items())]


_WORDS_CACHE = {}


def load_word_data():
    """sha-pinned load of fk1_words.json -> (blocks, meta).  FAIL-LOUD:
    absent file or any byte-level mutation of the pinned data refuses."""
    if "blocks" in _WORDS_CACHE:
        return _WORDS_CACHE["blocks"], _WORDS_CACHE["meta"]
    if not os.path.exists(WORDS_FILE):
        raise CertFail(
            "word data REFUSED (fail-closed): %s is ABSENT. The symbolic "
            "word form cannot run without the pinned OP3 data file "
            "(sha256 %s...). Use --deep for the transport/quadrature leg."
            % (WORDS_FILE, WORDS_SHA256[:16]))
    raw = open(WORDS_FILE, "rb").read()
    sha = hashlib.sha256(raw).hexdigest()
    if sha != WORDS_SHA256:
        raise CertFail(
            "word data REFUSED (fail-closed): sha256 of %s is %s, pinned "
            "OP3 value is %s. The file was modified -- re-vendor it from "
            "EEC/eec/gamma16_2026-07-04/op3_fk1/fk1_words.json or use "
            "--deep." % (WORDS_FILE, sha, WORDS_SHA256))
    d = json.loads(raw.decode())
    if len(d["words"]) != 159 or not d["meta"].get("no_fitted_coefficients"):
        raise CertFail("word data REFUSED: structure check failed "
                       "(need 159 words, no_fitted_coefficients=true)")
    monos = [tuple(b["mono"]) for b in d["blocks"]]
    if monos != W_BLOCK_MONOS:
        raise CertFail("word data REFUSED: block monomial order mismatch")
    blocks = [_parse_block_coeff(b["coeff"]) for b in d["blocks"]]
    _WORDS_CACHE["blocks"] = blocks
    _WORDS_CACHE["meta"] = d["meta"]
    return blocks, d["meta"]


# ---- tanh-sinh / Gauss-Legendre node machinery (s0_eval.py transcription)
def w_ts_nodes(h, tmax, wcut):
    """tanh-sinh nodes on (0,1): list of (x, 1-x, weight), both computed
    stably (1-x exactly, not by subtraction)."""
    out = []
    k = 0
    while True:
        tk = mp.mpf(k) * h
        if tk > tmax:
            break
        sh = mp.pi / 2 * mp.sinh(tk)
        ch = mp.cosh(sh)
        w = h * (mp.pi / 4) * mp.cosh(tk) / ch ** 2
        ex = mp.exp(-2 * sh)
        xm = 1 / (1 + ex)
        xm_c = ex / (1 + ex)
        if k == 0:
            out.append((mp.mpf("0.5"), mp.mpf("0.5"), w))
        else:
            if w > wcut:
                out.append((xm, xm_c, w))
                out.append((xm_c, xm, w))
        if w < wcut and k > 8:
            break
        k += 1
    return out


_W_GL_CACHE = {}


def w_gl_nodes(n):
    """Gauss-Legendre nodes/weights on [-1,1] (Newton on P_n), cached per
    (n, ambient dps)."""
    key = (n, mp.mp.dps)
    if key in _W_GL_CACHE:
        return _W_GL_CACHE[key]
    old = mp.mp.dps
    mp.mp.dps = old + 12
    nodes = []
    for i in range(1, n // 2 + 1):
        x = mp.cos(mp.pi * (i - mp.mpf(1) / 4) / (n + mp.mpf(1) / 2))
        dp = mp.mpf(1)
        for _ in range(60):
            p0, p1 = mp.mpf(1), x
            for k in range(2, n + 1):
                p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
            dp = n * (x * p1 - p0) / (x ** 2 - 1)
            dx = p1 / dp
            x -= dx
            if abs(dx) < mp.mpf(10) ** (-(old + 8)):
                break
        w = 2 / ((1 - x ** 2) * dp ** 2)
        nodes.append((x, w))
        nodes.append((-x, w))
    if n % 2:
        x = mp.mpf(0)
        p0, p1 = mp.mpf(1), x
        for k in range(2, n + 1):
            p0, p1 = p1, ((2 * k - 1) * x * p1 - (k - 1) * p0) / k
        dp = n * (x * p1 - p0) / (x ** 2 - 1)
        nodes.append((x, 2 / dp ** 2))
    mp.mp.dps = old
    nodes = [(mp.mpf(x), mp.mpf(w)) for x, w in nodes]
    _W_GL_CACHE[key] = nodes
    return nodes


_W_TS_CACHE = {}


def w_ts_cached(h_denom, wcut_exp):
    key = (h_denom, wcut_exp, mp.mp.dps)
    if key not in _W_TS_CACHE:
        _W_TS_CACHE[key] = w_ts_nodes(mp.mpf(1) / h_denom, mp.mpf("7.5"),
                                      mp.mpf(10) ** (-wcut_exp))
    return _W_TS_CACHE[key]


_W_HARM = [mp.mpf(0)]


def _w_harm(n):
    while len(_W_HARM) <= n:
        _W_HARM.append(_W_HARM[-1] + mp.mpf(1) / len(_W_HARM))
    return _W_HARM[n]


def w_S12_neg(zv):
    """Nielsen S12(z) for z < 0, fully real (inversion formula; the
    z+i0 <-> (1-z)-i0 branch bookkeeping is derived in the S0 sector)."""
    X = 1 - zv
    Lx = mp.log(X)
    ix = 1 / X
    ReLi2X = mp.pi ** 2 / 3 - Lx ** 2 / 2 - mp.polylog(2, ix)
    ReLi3X = mp.polylog(3, ix) - Lx ** 3 / 6 + mp.pi ** 2 * Lx / 3
    return (mp.zeta(3) - ReLi3X + Lx * ReLi2X + mp.log(-zv) * Lx ** 2 / 2)


def w_polyset(mz, nterms):
    """(L0, L1, Li2(z), Li3(z), S12(z)) at z = -mz < 0; direct series when
    |z| <= 0.35 (harmonic-sum S12 series), closed forms otherwise."""
    zv = -mz
    L0 = mp.log(mz)
    L1 = mp.log1p(mz)
    if mz < mp.mpf("0.35"):
        s2 = mp.mpf(0)
        s3 = mp.mpf(0)
        s12 = mp.mpf(0)
        zk = mp.mpf(1)
        for k in range(1, nterms + 1):
            zk *= zv
            t2 = zk / k ** 2
            s2 += t2
            s3 += t2 / k
            if k >= 2:
                s12 += _w_harm(k - 1) * t2
        return (L0, L1, s2, s3, s12)
    return (L0, L1, mp.polylog(2, zv), mp.polylog(3, zv), w_S12_neg(zv))


def w_stable_consts(zbv, eps):
    """(lz, l1, La2, La3, Si12)(zb) evaluated stably at both endpoints
    (eps = 1-zb passed exactly)."""
    if zbv < mp.mpf("0.5"):
        lz = mp.log(zbv)
        l1 = mp.log1p(-zbv)
    else:
        lz = mp.log1p(-eps)
        l1 = mp.log(eps)
    if eps <= mp.mpf("0.5"):
        La2 = mp.polylog(2, eps)
        La3 = mp.polylog(3, eps)
    else:
        La2 = mp.pi ** 2 / 6 - lz * l1 - mp.polylog(2, zbv)
        La3 = (mp.zeta(3) + lz ** 3 / 6 + mp.pi ** 2 * lz / 6
               - lz ** 2 * l1 / 2 - mp.polylog(3, zbv)
               - mp.polylog(3, 1 - 1 / zbv))
    Si = (-mp.polylog(3, zbv) + lz * mp.polylog(2, zbv)
          + l1 * lz ** 2 / 2 + mp.zeta(3))
    return lz, l1, La2, La3, Si


def w_coeff_vector(zbv, eps, blocks):
    """coeff_j(zb) from the exact (pinned) block coefficients."""
    consts = w_stable_consts(zbv, eps)
    out = []
    for terms in blocks:
        c = mp.mpf(0)
        for q, e in terms:
            m = mp.mpf(q.numerator) / q.denominator
            for v, k in zip(consts, e):
                for _ in range(k):
                    m *= v
            c += m
        out.append(c)
    return out


def w_panel_params(dps):
    """Inner-panel effort vs requested depth: the S0-sector settings (GL48,
    rho>=3 floor ~1e-46) up to ~40 d, the OP3 upgraded settings (GL64,
    ts_first 1/32; used by the 50 d-bar gates of record) above."""
    if dps > 40:
        return 64, 64, 32
    return 48, 32, 24


def w_inner_vector(zbv, eps, zev, nodes_in, gl_fine, gl_tiny, ts_first_den):
    """B_j(zb) for the 12 blocks (endpoint-stable derived forms; fk1_eval
    transcription).  eps > 0.05: single tanh-sinh pass.  eps <= 0.05:
    TS first panel + geometric GL panels around the eps-scale inner
    endpoints t- ~ -O(eps), t+ = zb + O(eps^2)."""
    B = [mp.mpf(0)] * 12
    nterms = int(mp.mp.dps * 2.3) + 8

    def acc(mz, fac):
        vals = w_polyset(mz, nterms)
        for j, e in enumerate(W_BLOCK_MONOS):
            m = fac
            for v, p in zip(vals, e):
                for _ in range(p):
                    m *= v
            B[j] += m

    if eps > mp.mpf("0.05"):
        for s, sc, w in nodes_in:
            dd = sc * (1 - zev) + s * eps
            DKr = eps * (sc + s * eps) + zev * sc * (s - eps * (1 + s))
            mz = zev * s * sc * zbv / dd
            acc(mz, w / DKr)
        return B

    Mv = -zbv * eps + zev * (2 * zev - 1)
    sqQ = mp.sqrt(Mv ** 2 + 4 * zev ** 3 * (1 - zev))
    bKv = zev - zbv * eps
    cKv = zbv * eps * (1 - zev)
    tmv = -2 * cKv / (bKv + sqQ)
    Rv = zbv - tmv
    a = zbv * eps ** 2 / (zev * Rv)
    half = zbv / 2
    fine = eps > mp.mpf("1e-8")
    gl = w_gl_nodes(gl_fine if fine else gl_tiny)
    ts_first = w_ts_cached(ts_first_den, mp.mp.dps + 10)

    def fA(tv):
        den = tv * (zev - zbv) + (1 - zev) * zbv
        mz = zev * tv * (zbv - tv) / den
        DK = zev * (zbv + a - tv) * (tv - tmv)
        return mz, 1 / DK

    def fB(v):
        den = v * (1 - zev - eps) + zbv * eps
        mz = zev * (zbv - v) * v / den
        return mz, 1 / (zev * (a + v) * (Rv - v))

    for f, scale in ((fA, -8 * tmv), (fB, 8 * a)):
        p1 = min(scale, half)
        for s, sc, w in ts_first:
            x = p1 * s
            mz, dk = f(x)
            acc(mz, w * p1 * dk)
        p = p1
        while p < half:
            q = min(4 * p, half)
            c1 = (q - p) / 2
            c0 = (q + p) / 2
            for x, w in gl:
                mz, dk = f(c0 + c1 * x)
                acc(mz, w * c1 * dk)
            p = q
    return B


W_MOMENTS = ("S0", "S1", "S2", "SM")


def _word_task(arg):
    """Worker: one shard of the two-fold word ledger at height h.  Returns
    partial moment sums as strings (deterministic; pickle-safe)."""
    wp = arg["wp"]
    mp.mp.dps = wp
    blocks, _ = load_word_data()
    zev = mp.mpf(arg["p"]) / arg["q"]
    m_shift = 2 * zev ** 2 - zev
    glf, glt, tsd = w_panel_params(wp)
    wcut = mp.mpf(10) ** (-(wp + 12))
    no = w_ts_nodes(mp.mpf(1) / arg["h"], mp.mpf("7.5"), wcut)
    mine = no[arg["shard"]::arg["nshard"]]
    t0 = time.time()
    S = {k: mp.mpf(0) for k in W_MOMENTS}
    for zbv, eps, w in mine:
        B = w_inner_vector(zbv, eps, zev, no, glf, glt, tsd)
        C = w_coeff_vector(zbv, eps, blocks)
        kb = mp.fsum(C[j] * B[j] for j in range(12))
        S["S0"] += w * kb
        S["S1"] += w * zbv * kb
        S["S2"] += w * zbv * zbv * kb
        S["SM"] += w * (zbv * zbv - zbv + m_shift) * kb
    return {"n_mine": len(mine), "n_total": len(no),
            "sec": time.time() - t0,
            "moments": {k: mp.nstr(S[k], wp + 8) for k in W_MOMENTS}}


def word_ledger(fr, D, h, workers, verbose=True):
    """One full two-fold ledger at height h -> dict of the four moments
    (mpf at wp = D + WORD_GUARD) + node/timing info."""
    wp = D + WORD_GUARD
    tasks = [{"p": fr.numerator, "q": fr.denominator, "wp": wp, "h": h,
              "shard": i, "nshard": workers} for i in range(workers)]
    t0 = time.time()
    if workers <= 1:
        res = [_word_task(a) for a in tasks]
    else:
        with multiprocessing.Pool(workers) as pool:
            res = pool.map(_word_task, tasks, chunksize=1)
    with mp.workprec(int(wp * 3.3333) + 10):
        S = {k: mp.mpf(0) for k in W_MOMENTS}
        for r in res:
            for k in W_MOMENTS:
                S[k] += mp.mpf(r["moments"][k])
    n = sum(r["n_mine"] for r in res)
    if n != res[0]["n_total"]:
        raise CertFail("word ledger shard accounting broken: %d != %d"
                       % (n, res[0]["n_total"]))
    if verbose:
        print("[word]      ledger h=1/%d (%d outer nodes, wp %d, %d "
              "workers): wall %.1f s (cpu %.1f s)"
              % (h, n, wp, workers, time.time() - t0,
                 sum(r["sec"] for r in res)))
    return S, n


def word_spot_gate(fr, D, verbose=True):
    """Per-run LIVE gate of the pinned symbolic data: the block-form
    kernel K(zb) vs certified quadrature of the K1 integrand (this
    script's oracle layer -- shares nothing with the word data) at the
    4 spot points.  Bar max(D+2, WORD_MUT_EXP) digits: catches 1e-30
    coefficient corruption numerically.  Returns worst measured digits."""
    Dspot = max(D + 2, WORD_MUT_EXP)
    wp = Dspot + 14
    old_dps = mp.mp.dps
    worst = float("inf")
    try:
        mp.mp.dps = wp
        blocks, _ = load_word_data()
        glf, glt, tsd = w_panel_params(wp)
        zev = mp.mpf(fr.numerator) / fr.denominator
        ni = w_ts_nodes(mp.mpf(1) / 28, mp.mpf("7.5"),
                        mp.mpf(10) ** (-(wp + 10)))
        for zb_s in WORD_SPOT_ZB:
            zbv = mp.mpf(zb_s)
            eps = 1 - zbv
            B = w_inner_vector(zbv, eps, zev, ni, glf, glt, tsd)
            C = w_coeff_vector(zbv, eps, blocks)
            K = mp.fsum(C[j] * B[j] for j in range(12))
            f = make_inner_K1(zbv, zev)
            v, _, _ = cert_quad(f, mp.mpf(0), zbv, Dspot + 4, wp,
                                tag="word.spot(zb=%s)" % zb_s)
            a1 = -zbv * (zbv - 1) * (zev - 1)
            Kref = mp.re(v) / a1
            d = digits(K, Kref)
            worst = min(worst, d)
            if d < Dspot:
                raise CertFail(
                    "word SPOT GATE FAILED (fail-closed) at zb=%s, "
                    "zeta=%s: block-form K agrees with the live certified "
                    "integrand quadrature to only %.1f d (bar %d d). The "
                    "symbolic data or its transcription is corrupt."
                    % (zb_s, fr, d, Dspot))
    finally:
        mp.mp.dps = old_dps
    if verbose:
        print("[word]      spot gate: block-form K(zb) vs LIVE certified "
              "quadrature at %d spots: worst %.1f d (bar %d) -- PASS"
              % (len(WORD_SPOT_ZB), worst, Dspot))
    return worst


def word_eval(fr, D, workers, verbose=True):
    """Word-form F^K1(fr) at >= D certified digits, fail-closed:
    two-height escalation until successive ledgers agree to >= D+2 d,
    plus the exact M-identity closure.  Returns (value, cert_digits, S)."""
    wp = D + WORD_GUARD
    h0 = max(10, int(math.ceil((D + 4) / 2.0)))
    schedule = [h0, int(math.ceil(1.3 * h0)), int(math.ceil(1.69 * h0))]
    prev = None
    with mp.workprec(int(wp * 3.3333) + 10):
        zev = mp.mpf(fr.numerator) / fr.denominator
        for li, h in enumerate(schedule):
            S, n = word_ledger(fr, D, h, workers, verbose=verbose)
            fk1 = (zev - 1) * (S["S1"] - S["S2"])
            fk1_M = (zev - 1) * ((2 * zev ** 2 - zev) * S["S0"] - S["SM"])
            resid = abs(fk1 - fk1_M) / abs(fk1)
            if resid > mp.mpf(10) ** (-(D + 2)):
                raise CertFail(
                    "word M-identity FAILED (fail-closed) at h=1/%d: "
                    "rel resid %s > 1e-%d -- ledger assembly corrupt"
                    % (h, mp.nstr(resid, 3), D + 2))
            if prev is not None:
                agr = digits(fk1, prev)
                if verbose:
                    print("[word]      two-height agreement h=1/%d vs "
                          "1/%d: %.1f d (bar %d); M-identity resid %s"
                          % (schedule[li - 1], h, agr, D + 2,
                             mp.nstr(resid, 2)))
                if agr >= D + 2:
                    return fk1, agr, S
            prev = fk1
    raise CertFail(
        "word ledger FAILED (fail-closed): heights %s exhausted without "
        "two successive levels agreeing to %d d at zeta=%s. No value is "
        "printed." % (schedule, D + 2, fr))


# ---------------------------------------------------------------------------
# spectral collocation transport (grid + solve + sensitivity)
# ---------------------------------------------------------------------------
def cheb_TdTd2(N, x):
    """T_k, T'_k, T''_k for k = 0..N-1 by recurrence."""
    T = [mp.mpf(1), x]
    dT = [mp.mpf(0), mp.mpf(1)]
    d2T = [mp.mpf(0), mp.mpf(0)]
    for k in range(1, N - 1):
        T.append(2 * x * T[k] - T[k - 1])
        dT.append(2 * T[k] + 2 * x * dT[k] - dT[k - 1])
        d2T.append(4 * dT[k] + 2 * x * d2T[k] - d2T[k - 1])
    return T[:N], dT[:N], d2T[:N]


def build_system(M):
    """Collocation matrix A ((M+2) x (M+2)): ODE rows at the M
    Chebyshev-Gauss nodes + value rows at the two anchors.  Also returns
    the node list.  Runs at ambient working precision."""
    N = M + 2
    C, H = _mpq(CQ), _mpq(HQ)
    A = mp.matrix(N, N)
    zs = []
    for j in range(M):
        x = mp.cos(mp.pi * (2 * j + 1) / (2 * M))
        ze = C + H * x
        zs.append(ze)
        A2, A1, A0 = Lcoef(ze)
        T, dT, d2T = cheb_TdTd2(N, x)
        for k in range(N):
            A[j, k] = A2 * d2T[k] / H ** 2 + A1 * dT[k] / H + A0 * T[k]
    for i, fr in enumerate(ANCHORS):
        x = (_mpq(fr) - C) / H
        T, _, _ = cheb_TdTd2(N, x)
        for k in range(N):
            A[M + i, k] = T[k]
    return A, zs


def eval_cheb(coef, fr):
    x = (_mpq(fr) - _mpq(CQ)) / _mpq(HQ)
    T, _, _ = cheb_TdTd2(len(coef), x)
    return mp.fsum(coef[k] * T[k] for k in range(len(coef)))


def sensitivity(A, fr):
    """|phi^T A^-1| row: propagation weights of the rhs errors into the
    transported value at zeta = fr (exact l1 accounting)."""
    N = A.rows
    x = (_mpq(fr) - _mpq(CQ)) / _mpq(HQ)
    T, _, _ = cheb_TdTd2(N, x)
    phi = mp.matrix(N, 1)
    for k in range(N):
        phi[k] = T[k]
    y = mp.lu_solve(A.T, phi)
    return [abs(y[i]) for i in range(N)]


# ---------------------------------------------------------------------------
# runtime selftests (transcription + solver control) -- RAISE on failure
# ---------------------------------------------------------------------------
def selftest_transcription():
    """Cross-validate the inlined closed forms:
      (a) pref1 zeta-derivatives vs mp.diff;
      (b) assembled (dG, d2G) vs mp.diff of G;
      (c) ORACLE-layer integrand == DERIVATIVE-layer pref1*P1 pointwise
          (two independent transcriptions)."""
    with mp.workprec(int(45 * 3.3333) + 10):
        zeta = mp.mpf(1) / 3
        pts = [(mp.mpf("0.11"), mp.mpf("0.6")),
               (mp.mpf("0.05"), mp.mpf("0.3"))]
        for (t, zb) in pts:
            p, dp, d2p = _pref1_and_dzeta(t, zb, zeta)
            fref = lambda zz: _pref1_and_dzeta(t, zb, zz)[0]
            if abs(dp - mp.diff(fref, zeta, 1)) > mp.mpf(10) ** -25 or \
               abs(d2p - mp.diff(fref, zeta, 2)) > mp.mpf(10) ** -22:
                raise CertFail("selftest FAILED: pref1 zeta-derivative "
                               "transcription broken at (t,zb)=(%s,%s)"
                               % (t, zb))

        def Gf(t, zb, zz):
            z, _, _ = _z_and_dzeta(t, zb, zz)
            p, _, _ = _pref1_and_dzeta(t, zb, zz)
            P1, _, _ = _P1_d2(z, zb)
            return p * P1

        for (t, zb) in pts:
            z, dz, d2z = _z_and_dzeta(t, zb, zeta)
            pref1, dpref1, d2pref1 = _pref1_and_dzeta(t, zb, zeta)
            P1, dP1_dz, d2P1_dz = _P1_d2(z, zb)
            dG = dpref1 * P1 + pref1 * (dP1_dz * dz)
            d2G = (d2pref1 * P1 + 2 * dpref1 * (dP1_dz * dz)
                   + pref1 * (d2P1_dz * dz ** 2 + dP1_dz * d2z))
            if abs(dG - mp.diff(lambda zz: Gf(t, zb, zz), zeta, 1)) \
                    > mp.mpf(10) ** -24 or \
               abs(d2G - mp.diff(lambda zz: Gf(t, zb, zz), zeta, 2)) \
                    > mp.mpf(10) ** -20:
                raise CertFail("selftest FAILED: L[G] derivative assembly "
                               "broken at (t,zb)=(%s,%s)" % (t, zb))
        worst_rel = mp.mpf(0)
        for (t, zb) in pts + [(mp.mpf("0.31"), mp.mpf("0.44"))]:
            z, _, _ = _z_and_dzeta(t, zb, zeta)
            p, _, _ = _pref1_and_dzeta(t, zb, zeta)
            P1, _, _ = _P1_d2(z, zb)
            two = p * P1
            one = make_inner_K1(zb, zeta)(t)
            rel = abs(one - two) / max(1, abs(one))
            worst_rel = max(worst_rel, rel)
            if rel > mp.mpf(10) ** -XLAYER_EXP:
                raise CertFail("selftest FAILED: the two independent "
                               "K1-integrand transcriptions disagree at "
                               "(t,zb)=(%s,%s): rel %s > detection floor "
                               "1e-%d: %s vs %s"
                               % (t, zb, mp.nstr(rel, 4), XLAYER_EXP,
                                  mp.nstr(one, 20), mp.nstr(two, 20)))
        return worst_rel


def control_ceiling(M, D, pts, verbose=False):
    """Manufactured-solution POSITIVE CONTROL and live truncation meter.
    G0 = log(ze)^2 + 1/(1-ze) (same log^2 singularity at ze=0 that limits
    F^K1's Chebyshev convergence on this interval); S0 = L[G0] closed form.
    Solves the SAME system (same grid, operator rows, anchor structure) and
    returns the worst reproduction digits over pts + gate angles."""
    wp_solve = D + 30
    with mp.workprec(int(wp_solve * 3.3333) + 10):
        def G0(ze):
            return mp.log(ze) ** 2 + 1 / (1 - ze)

        def S0(ze):
            g = G0(ze)
            dg = 2 * mp.log(ze) / ze + 1 / (1 - ze) ** 2
            d2g = (2 - 2 * mp.log(ze)) / ze ** 2 + 2 / (1 - ze) ** 3
            A2, A1, A0 = Lcoef(ze)
            return A2 * d2g + A1 * dg + A0 * g

        A, zs = build_system(M)
        b = mp.matrix(M + 2, 1)
        for j, ze in enumerate(zs):
            b[j] = S0(ze)
        for i, fr in enumerate(ANCHORS):
            b[M + i] = G0(_mpq(fr))
        coef = mp.lu_solve(A, b)
        worst = float('inf')
        for fr in list(pts) + GATE_PTS:
            d = digits(eval_cheb(coef, fr), G0(_mpq(fr)))
            worst = min(worst, d)
        if verbose:
            print("[control]   manufactured-solution solve at M=%d: worst "
                  "reproduction %.1f d (need >= %d)" % (M, worst, D + 2))
        return worst


def size_grid(D, pts, verbose=False):
    """Seed M from the measured slope, then VALIDATE by the live control;
    escalate until the control clears D+2 digits (fail-closed at cap)."""
    M = 44 + max(0, math.ceil((D + 2 - CEIL44) / SLOPE))
    for _ in range(5):
        dc = control_ceiling(M, D, pts, verbose=verbose)
        if dc >= D + 2:
            return M, dc
        M += max(4, math.ceil((D + 2 - dc) / SLOPE))
    raise CertFail("grid sizing FAILED (fail-closed): control still below "
                   "%d digits at M=%d" % (D + 2, M))


# ---------------------------------------------------------------------------
# parallel task pool
# ---------------------------------------------------------------------------
def _task(arg):
    """Worker entry: one certified integral; returns strings (pickle-safe)."""
    kind = arg['kind']
    D = arg['D']
    t0 = time.time()
    _rule().transformed_cache.clear()      # bound per-worker memory
    outdig = D + 24
    if kind == 'node':
        v, b, dep = src_node(arg['j'], arg['M'], D,
                             tag="S(node %d/%d)" % (arg['j'], arg['M']))
    elif kind in ('anchor', 'oracle'):
        fr = Fraction(arg['p'], arg['q'])
        guard = G_ANCH if kind == 'anchor' else G_ORC
        v, b, dep = fk1_direct(fr, D, guard, tag="F^K1(%s)" % fr)
    elif kind == 'moments':
        fr = Fraction(arg['p'], arg['q'])
        T0v, b0, T2v, b2 = moments(fr, D, tag="T(%s)" % fr)
        with mp.workprec(int((D + 40) * 3.3333)):
            return {'kind': kind, 'p': arg['p'], 'q': arg['q'],
                    'T0': mp.nstr(T0v, outdig), 'b0': mp.nstr(b0, 5),
                    'T2': mp.nstr(T2v, outdig), 'b2': mp.nstr(b2, 5),
                    'sec': time.time() - t0}
    else:
        raise ValueError(kind)
    with mp.workprec(int((D + 40) * 3.3333)):
        return {'kind': kind, 'j': arg.get('j'), 'p': arg.get('p'),
                'q': arg.get('q'), 'val': mp.nstr(v, outdig),
                'bound': mp.nstr(b, 5), 'depth': dep,
                'sec': time.time() - t0}


def farm(tasks, workers, verbose=True):
    t0 = time.time()
    if workers <= 1:
        res = [_task(a) for a in tasks]
    else:
        with multiprocessing.Pool(workers) as pool:
            res = pool.map(_task, tasks, chunksize=1)
    if verbose:
        cpu = sum(r['sec'] for r in res)
        print("[farm]      %d certified integrals, %d workers: wall %.1f s "
              "(cpu %.1f s)" % (len(tasks), workers, time.time() - t0, cpu))
    return res


# ---------------------------------------------------------------------------
# drivers
# ---------------------------------------------------------------------------
def transport_run(D, eval_pts, workers, with_moments=None, verbose=True):
    """Full certified run: grid sizing -> live batch -> solve -> per-point
    live-oracle gate (fail-closed).  Returns worst certified digits."""
    M, dctrl = size_grid(D, eval_pts, verbose=verbose)
    attempt = 0
    node_res = None
    while True:
        attempt += 1
        tasks = [{'kind': 'node', 'j': j, 'M': M, 'D': D} for j in range(M)]
        if node_res is None:
            tasks += [{'kind': 'anchor', 'p': f.numerator, 'q': f.denominator,
                       'D': D} for f in ANCHORS]
            tasks += [{'kind': 'oracle', 'p': f.numerator, 'q': f.denominator,
                       'D': D} for f in eval_pts]
            if with_moments:
                tasks.append({'kind': 'moments', 'p': with_moments.numerator,
                              'q': with_moments.denominator, 'D': D})
        res = farm(tasks, workers, verbose=verbose)
        if node_res is None:
            other = [r for r in res if r['kind'] != 'node']
        node_res = {r['j']: r for r in res if r['kind'] == 'node'}

        wp_solve = D + 30
        with mp.workprec(int(wp_solve * 3.3333) + 10):
            A, zs = build_system(M)
            b = mp.matrix(M + 2, 1)
            eps = []
            for j in range(M):
                b[j] = mp.mpf(node_res[j]['val'])
                eps.append(mp.mpf(node_res[j]['bound']))
            anch = {(r['p'], r['q']): r for r in other
                    if r['kind'] == 'anchor'}
            for i, fr in enumerate(ANCHORS):
                r = anch[(fr.numerator, fr.denominator)]
                b[M + i] = mp.mpf(r['val'])
                eps.append(mp.mpf(r['bound']))
            coef = mp.lu_solve(A, b)
            orc = {(r['p'], r['q']): r for r in other
                   if r['kind'] == 'oracle'}

            worst = float('inf')
            fails = []
            values = {}
            print("\n== F^K1 gate at dps %d  (grid M=%d, control ceiling "
                  "%.1f d, live sources) ==" % (D, M, dctrl))
            for fr in eval_pts:
                tv = eval_cheb(coef, fr)
                r = orc[(fr.numerator, fr.denominator)]
                ov, ob = mp.mpf(r['val']), mp.mpf(r['bound'])
                w = sensitivity(A, fr)
                prop = mp.fsum(w[i] * eps[i] for i in range(len(eps)))
                delta = abs(tv - ov)
                cert = delta + ob + prop
                cd = float(-mp.log10(cert / abs(ov)))
                agree = digits(tv, ov)
                values[fr] = mp.nstr(tv, D + 30)
                worst = min(worst, cd)
                held = " (never used in the construction)" if fr not in ANCHORS else \
                       " (ANCHOR -- gate not independent)"
                tag = "PASS" if cd >= D else "FAIL"
                print("\n  zeta = %s%s" % (fr, held))
                print("    transported  %s" % mp.nstr(tv, D + 4))
                print("    live oracle  %s  [certified |err| <= %s]"
                      % (mp.nstr(ov, D + 4), mp.nstr(ob, 3)))
                print("    agreement %.1f d | certified err <= %s "
                      "(routes %s + oracle %s + sources %s) -> "
                      "certified %.1f d vs %d d bar: %s"
                      % (agree, mp.nstr(cert, 3), mp.nstr(delta, 3),
                         mp.nstr(ob, 3), mp.nstr(prop, 3), cd, D, tag))
                if cd < D:
                    fails.append((fr, cd, delta, ob, prop))

        if not fails:
            break
        if attempt >= 2:
            fr, cd, delta, ob, prop = fails[0]
            raise CertFail(
                "gate FAILED (fail-closed) at zeta=%s after grid escalation:"
                " certified %.1f d < %d d bar (routes %s, oracle %s, sources"
                " %s, M=%d). Raise --dps guards / inspect the dominating "
                "term." % (fr, cd, D, mp.nstr(delta, 3), mp.nstr(ob, 3),
                           mp.nstr(prop, 3), M))
        deficit = max(D - c[1] for c in fails)
        M += max(4, math.ceil((deficit + 2) / SLOPE))
        print("\n[escalate]  gate below the %d d bar; regrowing grid to M=%d"
              " and recomputing sources (fail-closed after this attempt)"
              % (D, M))
        node_res = None

    mres = None
    if with_moments:
        mres = [r for r in other if r['kind'] == 'moments'][0]
        print("\n== moments at zeta = %s (live, refine-until-bound; the two "
              "constants NOT identified in closed form) ==" % with_moments)
        print("    T0 = %s  [certified |err| <= %s]"
              % (mres['T0'][:D + 6], mres['b0']))
        print("    T2 = %s  [certified |err| <= %s]"
              % (mres['T2'][:D + 6], mres['b2']))
        print("    (archived 100-digit PSLQ searches over the modular-letter"
              " alphabet saturate honestly -- no closed form is claimed)")
    return worst, values, mres


def word_main(args, D, check_step, T00):
    """DEFAULT path: symbolic word-form evaluation (fail-closed)."""
    fr = Fraction(args.point) if args.point else Fraction(1, 3)
    if not 0 < fr < 1:
        raise SystemExit("--point P/Q must lie in (0,1)")
    blocks, meta = load_word_data()
    print("[word]      pinned OP3 data OK: %d derived words, %d blocks, "
          "no fitted coefficients (sha256 %s...)"
          % (len(json.load(open(WORDS_FILE))["words"]), len(blocks),
             WORDS_SHA256[:16]))
    if not (WORD_ZLO <= fr <= WORD_ZHI) and not args.live_gate:
        raise SystemExit(
            "zeta=%s is OUTSIDE the evidence-gated word-form hull "
            "[%s, %s] (8-point battery, run 2026-07-07, recorded: "
            ">= 30 d at 1/10, 1/7, 3/11, 1/3, "
            "5/13, 1/2, 3/5, 3/4, measured gates 36.0-41.6 d, vs the "
            "live dps-32 quadrature oracle at 5 points and the recorded "
            "OP3 / independent dps-32 oracle references at 1/3, 1/2, 3/11). "
            "Re-run with --live-gate to certify this point against the "
            "live oracle (minutes-class), or use --deep inside "
            "[1/7, 5/13]. Fail-closed: no ungated value is printed."
            % (fr, WORD_ZLO, WORD_ZHI))
    spot_worst = word_spot_gate(fr, D)

    runs = [(D, None)]
    if check_step:
        runs.append((D + check_step, None))
    vals = []
    for d_run, _ in runs:
        val, cert, S = word_eval(fr, d_run, args.workers)
        vals.append(val)
        with mp.workprec(int((d_run + WORD_GUARD) * 3.3333) + 10):
            # print policy (print-only-certified): only certified digits --
            # the two-height agreement is the value-level certificate
            n_print = max(6, min(int(cert), d_run + 6))
            print("\n== F^K1 word form at zeta = %s, dps %d ==" % (fr, d_run))
            print("    F^K1 = %s   (%d certified digits printed)"
                  % (mp.nstr(val, n_print), n_print))
            print("    certificate: two-height agreement %.1f d (bar %d) "
                  "| spot gate worst %.1f d | data sha-pinned"
                  % (cert, d_run + 2, spot_worst))
    if check_step:
        with mp.workprec(int((D + check_step + 30) * 3.3333)):
            ad = digits(vals[0], vals[1])
            ok = ad >= D
            print("\n[check] word crank dps %d vs %d: values agree to "
                  "%.1f d (need >= %d): %s"
                  % (D, D + check_step, ad, D,
                     "CONSISTENT" if ok else "FAILED"))
            if not ok:
                raise SystemExit(1)

    if args.live_gate:
        D_orc = min(D, 40)
        bar = min(D, 30)
        print("\n[live-gate] running the INDEPENDENT certified quadrature "
              "oracle at dps %d (shares nothing with the word data)..."
              % D_orc)
        t0 = time.time()
        ov, ob, _ = fk1_direct(fr, D_orc, G_ORC, tag="F^K1(%s)" % fr)
        with mp.workprec(int((D_orc + 30) * 3.3333)):
            ad = digits(vals[0], ov)
            print("    live oracle  %s  [certified |err| <= %s]  (%.1f s)"
                  % (mp.nstr(ov, D_orc + 4), mp.nstr(ob, 3),
                     time.time() - t0))
            print("    word vs oracle agreement: %.1f d (bar %d): %s"
                  % (ad, bar, "PASS" if ad >= bar else "FAIL"))
            if ad < bar:
                raise SystemExit(1)

    print("\n[provenance] word form: eecNNLO OP3 closure 2026-07-06 "
          "(OP3_RESULT.md gates 59 d @1/3, 51 d @1/2, 55 d @2/7, a point never used in the construction; "
          "engine = the OP3 certification of record). The --deep "
          "ODE-transport/quadrature evaluator is the independent second "
          "leg and remains fully functional.")
    print("Total wall time: %.1f s" % (time.time() - T00))


def main():
    ap = argparse.ArgumentParser(
        description="NNLO EEC F^K1: symbolic word-form evaluator (default) "
                    "+ certified live ODE-transport / quadrature oracle "
                    "(--deep) + live T0/T2 moments (see module docstring).")
    ap.add_argument('--dps', type=int, default=None,
                    help='certified-digit request (default: 12 word path, '
                         '20 deep path; --dps 32 reproduces the deeper '
                         'pre-2026-09-03 default); every printed value '
                         'carries a fail-closed runtime certificate at '
                         '>= dps digits')
    ap.add_argument('--point', metavar='P/Q',
                    help='evaluate F^K1 at zeta=P/Q (word path default '
                         '1/3, hull [1/10, 3/4]; deep path corridor '
                         '[1/7, 5/13])')
    ap.add_argument('--deep', action='store_true',
                    help='use the certified live ODE-transport evaluator '
                         '(the independent second leg; hours-class at '
                         'dps>=30)')
    ap.add_argument('--live-gate', action='store_true',
                    help='word path: also gate the value against the live '
                         'certified quadrature oracle at >= min(dps, 30) d '
                         '(fail-closed); required for points outside the '
                         'gated hull')
    ap.add_argument('--moments', metavar='P/Q',
                    help='compute only T0, T2 at zeta=P/Q (live '
                         'quadrature, no word data, no transport)')
    ap.add_argument('--workers', type=int,
                    default=min(8, multiprocessing.cpu_count()),
                    help='parallel workers (default min(8, cpu))')
    ap.add_argument('--check', nargs='?', const=-1, type=int, metavar='STEP',
                    help='crank test: rerun at dps+STEP (default +40 word '
                         'path / +6 deep path) and require >= dps-digit '
                         'value agreement, fail-closed')
    args = ap.parse_args()
    try:   # liveness (2026-09-03): line-buffered stdout so the first line
        sys.stdout.reconfigure(line_buffering=True)   # lands within seconds
    except Exception:                                 # even through a pipe
        pass
    D = args.dps if args.dps is not None else (20 if args.deep else 12)
    if D < 6:
        raise SystemExit("--dps must be >= 6")
    check_step = None
    if args.check is not None:
        check_step = args.check if args.check != -1 else \
            (6 if args.deep else 40)
    T00 = time.time()

    t0 = time.time()
    xfloor = selftest_transcription()
    print("[selftest]  closed-form transcription cross-checks PASS "
          "(pref1/L[G] derivs vs mp.diff; oracle vs derivative layer "
          "agree to %s rel, detection floor 1e-%d)   (%.1f s)"
          % ("0 (bit-exact)" if xfloor == 0 else mp.nstr(xfloor, 3),
             XLAYER_EXP, time.time() - t0))

    if args.moments:
        fr = Fraction(args.moments)
        if not 0 < fr < 1:
            raise SystemExit("--moments P/Q must lie in (0,1)")
        r = _task({'kind': 'moments', 'p': fr.numerator, 'q': fr.denominator,
                   'D': D})
        print("\n== moments at zeta = %s (live, refine-until-bound) ==" % fr)
        print("    T0 = %s  [certified |err| <= %s]" % (r['T0'][:D + 6],
                                                        r['b0']))
        print("    T2 = %s  [certified |err| <= %s]" % (r['T2'][:D + 6],
                                                        r['b2']))
        print("\nTotal wall time: %.1f s" % (time.time() - T00))
        return

    if not args.deep:
        word_main(args, D, check_step, T00)
        return

    if args.point:
        fr = Fraction(args.point)
        if not ZLO <= fr <= ZHI:
            raise SystemExit(
                "zeta=%s outside the transport corridor [1/7, 5/13] "
                "(this work's collocation interval; the word-form "
                "DEFAULT path covers [1/10, 3/4])" % fr)
        worst, _, _ = transport_run(D, [fr], args.workers)
    else:
        runs = [D] + ([D + check_step] if check_step else [])
        results = []
        for d in runs:
            # moments ride EVERY run: under --check the D+STEP pass recomputes
            # T0/T2 at genuinely tighter internal tolerances, so the crank
            # gates the moment pair too (bundled 2026-07-05; previously the
            # crank covered only the transported gate values).
            worst, vals, moms = transport_run(
                d, GATE_PTS, args.workers, with_moments=MOMENT_PT)
            results.append((worst, vals, moms))
            print("\n  worst certified digits at dps %d: %.1f  (>= %d bar: "
                  "%s)" % (d, worst, d, "PASS" if worst >= d else "FAIL"))
        if check_step:
            # crank semantics: the D+STEP run passed its own HIGHER bar with
            # genuinely tighter internal tolerances, and the two transported
            # values AND the two moment constants agree to >= D digits point
            # by point.  Fail-closed: a missing moment pair is a refusal,
            # not a skip.
            ok = True
            with mp.workprec(int((D + check_step + 30) * 3.3333)):
                for fr in GATE_PTS:
                    ad = digits(mp.mpf(results[0][1][fr]),
                                mp.mpf(results[1][1][fr]))
                    ok = ok and ad >= D
                    print("[check] zeta=%s: dps %d vs dps %d transported "
                          "values agree to %.1f d (need >= %d)"
                          % (fr, D, D + check_step, ad, D))
                if results[0][2] is None or results[1][2] is None:
                    raise CertFail("--check FAILED (fail-closed): moment "
                                   "pair missing from a crank run -- cannot "
                                   "gate T0/T2")
                for name in ('T0', 'T2'):
                    ad = digits(mp.mpf(results[0][2][name]),
                                mp.mpf(results[1][2][name]))
                    ok = ok and ad >= D
                    print("[check] %s(zeta=%s): dps %d vs dps %d moment "
                          "values agree to %.1f d (need >= %d)"
                          % (name, MOMENT_PT, D, D + check_step, ad, D))
            print("[check] dps crank %d -> %d (gates + T0/T2 moments): %s"
                  % (D, D + check_step,
                     "CONSISTENT" if ok else "FAILED"))
            if not ok:
                raise SystemExit(1)

    print("\n[archived]  end-to-end certification of this work (quoted as "
          "archived, not recomputed here): 34.57-34.99 d at 3/11, 5/13, "
          "4/11 (2026-07-04 recert, dps50/M60 sources); a dps75/90 M=128 "
          "source run targeting >= 60 d was in flight 2026-07-05.")
    print("Total wall time: %.1f s" % (time.time() - T00))


if __name__ == '__main__':
    main()
