#!/usr/bin/env python3
"""Unequal-mass kite (masses 1, 0, 1, 0, sqrt(2)) top master J(1,1,1,1,1) eps^0
-- LIVE DE-transport from the single s=-2 boundary, gated against a held-out
AMFlow oracle.  The boundary seed itself is AMFlow-FREE: it is the DERIVED
vector emitted by the companion kite-boundary.py (classical constants only --
gamma_E, zeta(2), ln 2, Catalan); AMFlow appears in this pipeline as held-out
gates only (the seed cross-check at startup and the held-out oracle below).

What this script COMPUTES at runtime (for any Euclidean s < 0):

  J^0_top(s)  by high-order Taylor transport of the full eps-graded 14-master
  Kira system  d/ds M(eps,s) = A(eps,s) M(eps,s),  seeded ONLY by the boundary
  Laurent vector at s = -2.  This is the honest terminal representation: a
  kernel-modularity proof (see kite-expression.md) shows there is NO finite
  constant-coefficient eMPL closed form for this master (the integration
  kernel psi1^3/W is non-modular on the non-congruence (1,1,2) sunrise curve),
  so the analytic formula IS the transport
      J^0_top(s) = J^0_top(-2) + int_{-2}^{s} psi1^3/W * S ds'
  realised here as numerical integration of the exact rational connection.

  It also computes, from scratch (mpmath ellipk / polyroots / numeric diff):
    - the BMSW (1,1,2) sunrise-curve periods at s=-2:  k^2 = (2+sqrt2)/4,
      psi1(-2), and the Wronskian W(-2) = i*pi/8 (Legendre relation);
    - the real period om1 of the fiber's minimal model y^2 = x^3 - 756x + 7344
      (conductor 128), verifying psi1(-2) = 3*om1 at working precision.

Literal inputs (all labelled, none is a result printed as computed):
  - kite-connection-A14.json : the exact rational 14x14 IBP connection A(d,s)
    (analytic formula -- the Kira reduction of this family, vendored here);
  - kite-boundary-derived.json : the 130-digit boundary Laurent vector at s=-2
    (transport seed) -- DERIVED, not measured: emitted by the companion script
    kite-boundary.py in this directory (closed-form two-loop vacuum ring at
    s=0 -- every constant classical: gamma_E, zeta(2), ln 2, Catalan, with
    xi(1,1,2) = -8*Catalan -- plus bounded-branch Frobenius regularity at the
    regular singular point s=0 and exact-DE transport to s=-2).  NO AMFlow
    number enters the seed.  Regenerable at any precision:
        python3 kite-boundary.py --dps 130 --emit kite-boundary-derived.json
    (In classical named rings these constants still have no product closed
    form -- PSLQ honestly negative, kite-expression.md -- the derivation is a
    convergent construction, not a fit.);
  - kite-boundary-sm2.json   : the 130-digit AMFlow boundary vector at s=-2
    (from the original computation), HELD OUT as a gate only:
    at startup the derived seed is compared against it component by component
    and the worst-of-42 agreement is printed live; it never enters the
    transport;
  - ORACLE below            : independent held-out AMFlow oracle values (never
    used in the transport), from the 130-digit AMFlow reference set of the
    original computation;
  - N_KITE below            : the named boundary constant N_kite =
    -8*M13[eps^0](-2) (close-out record of the original computation),
    now a theorem of the kite-boundary.py construction.

Agreement digits are RECOMPUTED here as -log10(|computed-oracle|/|oracle|).
Every transport step carries a CERTIFIED trailing-term tail bound (see the
2026-07-05 changelog below): --dps D delivers >= D digits or raises.  The
bare invocation is a QUICK demo at dps 30 (seed cross-check, the s=-5/2
held-out point, the runtime geometry checks, and a dps-doubling demo 30->60);
--full runs the deep suite: the dps-100 three-point gate demo (saturates the
working precision, ~124-125 held-out digits, oracle strings cap at 128) plus
the dps-200 doubling demo at s=-5/2, which hits the 128-digit stored-string cap.

Standalone: Python 3 + mpmath + the JSON data files and the exact parser module
  kite_exact_parse.py in this dir (no sympy at runtime since 2026-09-05).

Usage (evaluation interface):
  python3 kite-evaluate.py                      # QUICK demo at dps 30 (see above)
  python3 kite-evaluate.py --full               # dps-100 gate demo + dps-200 doubling
  python3 kite-evaluate.py --point=-7/3         # any Euclidean point s < 0
  python3 kite-evaluate.py --point=-7/3 --dps 150 --boundary-recompute
  (use --point=-7/3, with '=': a bare leading-dash value confuses argparse)
  python3 kite-evaluate.py --masses 1,1,3                      # the (1,1,3) line: quick demo (s=-10/3, dps 30)
  python3 kite-evaluate.py --masses 1,1,3 --point=-10/3 --dps 130   # the (1,1,3) reference point, 22-entry table
  python3 kite-evaluate.py --masses 1,1,3 --point=-5/3 --dps 130    # the (1,1,3) seed point (no transport)
  python3 kite-evaluate.py --minkowski --point 16 --dps 60      # the Minkowski arm: s + i0 at s = 16 by the complex detour,
                                                                #   gated against the vendored AMFlow record (42-component table)
  python3 kite-evaluate.py --minkowski --point 3/2 --dps 30     # any s > 0 off the five poles (no record there: the values,
                                                                #   the branch structure and the transport pair print)
  python3 kite-evaluate.py --point 16 --detour=-4 --dps 30      # the lower detour (s - i0) as the conjugate control; --detour H
                                                                #   alone selects the arm (the alias; H > 0 upper, H < 0 lower)
  python3 kite-evaluate.py --minkowski --point 16 --mutate --dps 30   # the control: one record digit altered in memory -> FAIL
  As a library: kite_top_eps0(s, dps=None, order=None); KITE_MASSES=1,1,3 in the
  environment selects the (1,1,3) line for library use.
DOMAIN: real Euclidean s < 0 on the real axis; s > 0 off the five poles by
  the Minkowski arm.  The connection has poles at s = 0, 1, 2,
  6 +/- 4*sqrt(2); the transport path from the s=-2 boundary stays on the
  negative real axis, so --point at s >= 0 (thresholds / analytic
  continuation) is rejected -- unless --minkowski is given (2026-09-06): then
  the same 42-component state is transported by the same certified step along
  the complex rectangle -2 -> -2 + iH -> s + iH -> s (H = --detour, default 4),
  which yields the Feynman s + i0 boundary value at s; the lower path
  (--detour=-H) yields its complex conjugate and is printed as the conjugate
  control.  Precision is arbitrary: --dps D computes at working D+25 and the
  certified per-step gate grows the Taylor order as needed (ORDER/--order is a
  STARTING seed only).  The stored boundary seed holds 130 digits: for
  D > 118 the script fail-closes and demands --boundary-recompute, which
  re-derives the seed live at the required precision.

CHANGELOG 2026-07-05 -- certified-tail hardening:
  * CERTIFIED per-step tail gate on the transport: trailing-8-term window
    max |a_n h^n| * r/(1-r), r <= SAFETY certified by the step rule
    (h <= SAFETY x distance to the nearest connection pole); the Taylor order
    is a STARTING seed that grows x1.5 by EXACT continuation of the same
    recurrences until the bound beats 10^-(working_dps+12); RuntimeError at
    the 8x cap.  Certified BOUND lines are printed with the values.
  * All computation at working precision target+25; printed digits = target.
  * Agreement gates RAISE now: startup derived-seed vs AMFlow cross-check,
    held-out oracle gate, dps-doubling demo, and (for --point, which has no
    oracle) an in-run two-precision rerun at dps+60 that must agree to >= D.
  * Fail-closed seed cap: requesting D with D+12 > stored seed digits raises
    unless --boundary-recompute re-derives the seed at the needed precision.

CHANGELOG 2026-07-05b -- --point seed gate:
  * The --point path now runs the SAME raising derived-seed vs held-out-AMFlow
    boundary cache-compare as the gate demo, BEFORE any transport.  Previously
    that gate ran only in the demo suite, so a corrupted/mutated
    kite-boundary-derived.json produced a silently wrong --point value (the
    in-run two-precision rerun shares the seed and cannot see seed damage).
    A 1e-30 seed mutation now fails LOUDLY (RuntimeError, nonzero exit) before
    a value is printed.  If the cross-check file is absent, --point fails
    closed unless the seed was just re-derived live (and byte-checked against
    the stored cache) by --boundary-recompute.

CHANGELOG 2026-07-06 -- --no-crank:
  * The mandatory in-run dps+60 two-precision rerun of --point (the "crank")
    is now OPTIONAL: default ON (behavior byte-identical), --no-crank skips
    it and prints an explicit UNCROSS-CHECKED label instead of the
    two-precision PASS line.  Everything else on the --point path is
    unchanged and still raising: the boundary-seed gate,
    the fail-closed seed-precision cap, and the per-step CERTIFIED tail
    bounds (the value path).  --no-crank without --point is refused
    (argparse error): the demo/gate suite always cranks.

CHANGELOG 2026-09-05 -- --masses 1,1,3 (the (1,1,x) line at x = 3):
  * The kite family is the (1,1,x) line: propagator masses (1, 0, 1, 0, sqrt x),
    x = the third squared mass of the sunrise sub-block (D1,D3,D5).  x = 2 is
    everything above (the default; every path byte-identical, --masses 1,1,2
    explicit == the default).  --masses 1,1,3 selects the x = 3 line: the exact
    rational connection kite-connection-A14-x3.json (same 14 masters, same
    nonzero pattern; poles at s = 0, 7 - 4 sqrt3, 1, 3, 7 + 4 sqrt3 -- the
    negative axis is pole-free), the DERIVED seed kite-boundary-derived-x3.json
    at the seed point s = -5/3 (190 digits; closed-form vacuum seed at s = 0
    with xi(1,1,3) = -(8/sqrt3) Cl2(pi/3) + bounded-branch Frobenius summed at
    the exit s = -1/40 + exact-DE transport, by the shipped x-general engine
    kite-boundary-general.py -- the (1,1,x)-line copy of kite-boundary.py whose
    (1,1,2) literals, embedded connection, pole list and 1/10 exit do not
    generalise: at x = 3 the DE pole 7 - 4 sqrt3 = 0.0718 sits inside the 1/10
    exit radius), and the INDEPENDENT REFERENCE kite-reference-x3.json (AMFlow
    at s = -5/3 and s = -10/3: twenty-two (master, eps order) entries per point,
    sixteen compared by digits, six exact rationals; gate only, never an input).
    The four x = 3 files are sha256-pinned (PINS below): any byte change is
    REFUSED by name (exit 3) before a value is printed.
  * The --point tier at x = 3 runs the SAME form as at x = 2: the raising seed
    gate (the derived seed vs the reference at the seed point, worst of the 22
    entries vs cap-8), the certified transport from s = -5/3, then -- when the
    point is a reference point -- the 22-entry table with the agreement
    recomputed per entry and a RAISING bar: the sixteen digit-compared entries
    >= min(128, dps) digits (128 = the floor of the independent gate of record
    at dps 130) and the six rational entries exact at the printed precision;
    then the mandatory dps+60 two-precision crank.  At the seed point itself
    (--point=-5/3) there is no transport: the printed value is the seed's top
    component, the table is the seed gate entry by entry, the crank is trivial.
    The reference strings hold 130 digits, so the measurable agreement caps at
    about 129-131 digits whatever the dps.
  * --masses 1,1,3 without --point = the x = 3 QUICK demo: --point=-10/3 at
    dps 30 (the reference table at both points via the seed gate + the
    transported point); --full is refused at x = 3 (the deep suite is the
    (1,1,2) record); --boundary-recompute [DPS] at x = 3 re-derives the s = -5/3
    seed live by the shipped engine (the receipt's vector at the exit -1/40),
    byte-checks the stored strings and seeds the transport from the live
    vector, exactly as the x = 2 path does with kite-boundary.py.
  * Measured walls (this host, a shared 96-core server at loadavg ~130; wall
    clock, /usr/bin/time): --masses 1,1,3 quick demo 53 s; --masses 1,1,3
    --point=-10/3 --dps 130 192 s; --point=-5/3 --dps 130
    43 s; --point=-10/3 --dps 130 --boundary-recompute 312 s.
    The x = 2 tiers are unchanged (default 18 s, --point=-7/3 47 s,
    --point=-7/3 --dps 150 --boundary-recompute 164 s, --full 219 s).

CHANGELOG 2026-09-05b -- exact parser, no sympy at runtime:
  * The connection strings are parsed by the sibling module kite_exact_parse.py
    (integers, the names d and s, + - * / **, parentheses -- the whole grammar
    of the shipped files; fractions.Fraction arithmetic), and the eps-graded
    coefficient lists the transport consumes are READ from the pinned graded
    file of the line (kite-connection-A14-graded.json / -x3-graded.json: the
    lists the earlier sympy parse produced, frozen once) and CHECKED against
    the parsed strings entry by entry at every start (equal as rational
    functions, equal key sets; a mismatch is REFUSED by name, exit 3).  The
    numerics receive the same integers as before, so every tier prints the
    same bytes (stamps and walls aside); sympy is no longer imported.  The
    parser module and the two graded files are sha256-pinned (PINS below), as
    is the cured engine kite-boundary-general.py.

CHANGELOG 2026-09-06 -- --minkowski: the (1,1,2) line continued to s > 0 (the
  Feynman s + i0 boundary value by a complex detour), gated at s = 16:
  * NEW --minkowski --point S [--detour H] (S > 0 off the five poles; H = 4 by
    default; --detour H alone selects the arm).  The 42-component graded state
    is transported from the derived s = -2 seed along the rectangle
    -2 -> -2 + iH -> S + iH -> S by the SAME certified Taylor step `_step`:
    the connection's only finite singular points are the five real poles, so
    the served step rule |h| <= SAFETY x (distance to the nearest pole) --
    here the complex distance -- certifies the same trailing-window tail bound
    for a complex step about a complex point.  The value at S is the boundary
    value from the upper half plane = s + i0 (D + i0 propagators, the AMFlow
    convention); the lower path (--detour=-H, s - i0) is its complex
    conjugate (real seed, real-rational connection: Schwarz reflection) and
    is printed as the CONJUGATE CONTROL: with H < 0 both paths are run and
    the agreement of the upper value with the conjugate of the lower is
    printed per component (RAISING at >= dps).  Every component prints its
    real and imaginary part at the target precision with the summed certified
    tail bound of the whole path.
  * NEW kite-reference-minkowski.json (sha256-pinned; a byte change is REFUSED
    by name, exit 3; the file missing, exit 4): the INDEPENDENT AMFlow record at
    s = 16 (goal 60, eps order 8, the engine's own +i0) -- the midpoint and the
    radius of every Arb ball of the 14 masters' eps^-2..eps^0 coefficients,
    real and imaginary parts, copied verbatim from the output object (the top
    master's eps^-2 / eps^-1 are absent there: identically zero) -- with the
    goal-40 twin block beside it.  GATE ONLY, never an input.  At --point 16
    the arm prints the 42-component table against it: the complex agreement
    -log10(|this - record| / |record|) and the real- and imaginary-part
    agreements (each relative to |record|), 'identical' where the two agree to
    the shorter printed length (this run prints dps + 5 digits; the record
    holds 110), 'zero' where both vanish, the floors with their members, the
    16 components with a resolved imaginary part and their floor, the sign
    check on those, and the vendored goal-60 vs goal-40 pair floor recomputed
    from the two blocks.  RAISING bar: every compared component, complex and
    (where resolved) imaginary, >= min(dps, 64) - 2 digits (64 = the
    certified count of record at this point; 2 = the guard on the last printed
    digit); a wrong sign on a resolved imaginary part or a component missing
    from the record FAILS by name (exit 1).
  * The TRANSPORT PAIR: the arm always reruns the same path at dps - 20 (the
    record's 60/40 form; at half the precision below --dps 40) and prints the
    per-component agreement of the two printed value sets (floor, member,
    identical count; a component vanishing in both sets counts as identical),
    RAISING at >= the lower precision; then ONE summary line from the run's
    own figures:
    'N digits at dps D (the transport pair certifies M)' -- N = the gate floor
    against the record rounded down, M = the pair floor rounded down; at a
    point without a record the line names the pair only.
  * --mutate (with --minkowski --point 16): the record's top eps^0 real part
    is altered in memory at its 10th significant digit (the file and its pin
    untouched) and the gate must FAIL by name.  Refused (exit 2): --minkowski
    without --point; --point <= 0, on a pole, or --dps below 20 under
    --minkowski (below 20 the bar would let the control pass by construction);
    --minkowski with --masses 1,1,3, with --full or with --no-crank (the arm
    always runs its pair); --mutate without --minkowski or off the record
    point.  --point S >= 0 WITHOUT --minkowski is rejected exactly as before
    (the Euclidean fence is unchanged); every served path is byte-identical.
  * Measured walls (this host, a shared 96-core server, a fenced scope at CPUQuota 200%, nice 10,
    wall clock by /usr/bin/time; loadavg 113.54 98.57 97.45 at launch): --minkowski --point 16 --dps 60
    717 s in all ([upper] 23 steps, 0 escalations, 427.9 s; [pair] 23 steps, 0 escalations, 289.2 s), max RSS
    57 MB; --minkowski --point 16 --dps 30 330 s (repeat
    365 s); --point 16 --detour=-4 --dps 30 (the conjugate control: both paths + the pair)
    555 s; --minkowski --point 3/2 --dps 30 273 s; --minkowski --point 16
    --mutate --dps 20 296 s.  The served tiers are unchanged (quick default
    12 s -> 11 s; --point=-7/3 38 s -> 48 s; --full
    220 s -> 220 s; --masses 1,1,3 48 s -> 52 s).
  * Limits (not established by this release): the served (Kira) gauge carries
    double poles at s = 1 and s = 2 (no Fuchsian gauge was built; the
    physical-sheet monodromy at those thresholds is read from the detour
    discontinuities by component, not from a residue spectrum); the certified
    count at s = 16 is bounded by the goal-60/40 AMFlow pair and by the dps-60
    transport (no goal-120 point was run); s = 16 is the ONLY Minkowski point
    gated against AMFlow (s = 3/2 and s = 1/2 were transported as internal
    controls, with no oracle there); and the absence of the Landau letters
    s-4, 2s-9, s^2-6s+1 from the connection is read from the served
    denominators (exact factorization), not re-derived by a Landau analysis.
"""
import json
import os
import sys
import time

if __name__ == "__main__":
    # line-buffered stdout + an immediate first line (kept from the days of the
    # several-second sympy parse; the exact parse below is a fraction of a second,
    # its wall in CHANGES.md)
    sys.stdout.reconfigure(line_buffering=True)
    if not any(a == "--full" or a.startswith("--point") for a in sys.argv[1:]):
        print("kite-evaluate quick demo: loading the exact 14x14 connection "
              "(exact parse, kite_exact_parse.py) ...")

import importlib.util

import mpmath as mp

HERE = os.path.dirname(os.path.abspath(__file__))
mp.mp.dps = int(os.environ.get("DPS", "100"))
ORDER = int(os.environ.get("ORDER", "100"))     # Taylor order per step (STARTING seed)
SAFETY = mp.mpf(os.environ.get("SAFETY", "0.30"))  # step = SAFETY * dist-to-pole
assert 0 < SAFETY < mp.mpf("0.5"), "SAFETY certifies the series ratio; keep < 1/2"

# Certified tail-gate parameters (2026-07-05):
#   per-step tail <= max(|a_n h^n| over trailing TAIL_WINDOW terms) * r/(1-r),
#   r <= SAFETY certified by the step rule; refine x1.5 by exact continuation
#   until the bound beats 10^-(mp.mp.dps + TAIL_GUARD); RuntimeError at 8x cap.
# Guard calibration (MEASURED this box 2026-07-05, targets 30/100 = working
# 55/125, gate paths to -5/2 and -15): worst per-step bound 2.06e-81 (w55) /
# 1.08e-157 (w125) vs tol 10^-(working+12) => margins 10^13.7 / 10^20.0 at the
# auto-scaled starting order, zero escalations on healthy runs (the certified
# step-rule ratio SAFETY=0.3 overestimates the true series ratio well away
# from the poles).  Escalation, if it ever fires, only tightens the bound.
TAIL_GUARD = 12
TAIL_WINDOW = 8
WORK_GUARD = 25      # working precision = target dps + WORK_GUARD
SEED_GUARD = 12      # stored seed must hold >= target + SEED_GUARD digits
ORACLE_GATE_FLOOR = 118   # held-out gate raises below min(target, this)

# ---------------------------------------------------------------------------
# 0. Mass-line selection (2026-09-05).  The family is the (1,1,x) line: masses
#    (1, 0, 1, 0, sqrt x), x = the third squared mass of the sunrise sub-block.
#    x = 2 is the default and every path below is unchanged for it; x = 3
#    (--masses 1,1,3) selects its own connection, derived seed, independent
#    reference, pole list and the x-general engine, all sha256-pinned.
# ---------------------------------------------------------------------------
MASS_CONFIGS = {
    (1, 1, 2): {
        "conn": "kite-connection-A14.json",
        "graded": "kite-connection-A14-graded.json",   # its eps-graded coefficient lists (checked against conn)
        "seed": "kite-boundary-derived.json",          # DERIVED seed at s = -2 (130 d)
        "ref": "kite-boundary-sm2.json",               # independent reference at s = -2
        "s_boundary": "-2",
        "poles": lambda: [mp.mpf(0), mp.mpf(1), mp.mpf(2),
                          6 - 4 * mp.sqrt(2), 6 + 4 * mp.sqrt(2)],
        "poles_text": "s = 0, 1, 2, 6 +/- 4*sqrt(2)",
    },
    (1, 1, 3): {
        "conn": "kite-connection-A14-x3.json",
        "graded": "kite-connection-A14-x3-graded.json",   # its eps-graded coefficient lists (checked against conn)
        "seed": "kite-boundary-derived-x3.json",       # DERIVED seed at s = -5/3 (190 d)
        "ref": "kite-reference-x3.json",               # independent reference at s = -5/3 (+ -10/3)
        "engine": "kite-boundary-general.py",          # the x-general seed engine
        "s_boundary": "-5/3",
        "s_exit": "-1/40",                             # Frobenius exit of the x = 3 seed
        "poles": lambda: [mp.mpf(0), 7 - 4 * mp.sqrt(3), mp.mpf(1), mp.mpf(3),
                          7 + 4 * mp.sqrt(3)],
        "poles_text": "s = 0, 7 - 4*sqrt(3), 1, 3, 7 + 4*sqrt(3)",
        "bar": 128,           # floor of the independent gate of record at dps 130
        "quick_point": "-10/3",
    },
}
# sha256 of the shipped files this script reads beyond its own line's seed and
# reference: the x = 3 files, the exact parser module and the two graded
# coefficient files (computed by the producer that cut this file, never typed);
# a mismatch is REFUSED by name before any value is printed.
PINS = {
    "kite-connection-A14-x3.json": "179662621b52d80ff415013356b6f505d1abbf02b1aa23f1b9bedfb936014900",
    "kite-boundary-derived-x3.json": "8021412a7d95072147b33407241ba79e90ebd2f632407a77fd8a72143f63232a",
    "kite-reference-x3.json": "16b3286f58d343922f4cf7e3e7782da4925d51ba1483fdbc31b82cfa7fbabd61",
    "kite-reference-minkowski.json": "5134174431c4f780c0d2dcfc408a0c6ac814df6cb29b4fee4b8c54b3cf74a67b",
    "kite-boundary-general.py": "1b4e6e08451a8659f64be55cf2a270212a3665f3b41a399e18d53e6822a269aa",
    "kite_exact_parse.py": "b2ee04d293a03e9c0aee40b155ca2c2e771486ede68db34cae3c5da4a9f97398",
    "kite-connection-A14-graded.json": "0dc5bc8f7fa8aeb014278643878e37fe885cfced281e15f7134a9bf1c9d5af71",
    "kite-connection-A14-x3-graded.json": "6fb39bb506e8ec47a9f59e6e8ba8a7662f9783904fad2c4de4e520296d92b4e3",
}


def _select_masses():
    """The mass line: --masses a,b,c on the command line (a run of this file)
    or KITE_MASSES=a,b,c in the environment (library use); default (1,1,2).
    Any triple other than the two shipped lines is refused by name (exit 2)."""
    val = os.environ.get("KITE_MASSES")
    if __name__ == "__main__":
        argv = sys.argv[1:]
        for i, a in enumerate(argv):
            if a == "--masses" and i + 1 < len(argv):
                val = argv[i + 1]
            elif a.startswith("--masses="):
                val = a.split("=", 1)[1]
    if val is None:
        return (1, 1, 2)
    try:
        t = tuple(int(x) for x in val.replace(" ", "").split(","))
    except ValueError:
        t = None
    if t not in MASS_CONFIGS:
        sys.stderr.write(f"kite-evaluate: error: unsupported --masses {val!r}: the shipped "
                         "lines are 1,1,2 (the default) and 1,1,3 (the (1,1,x) line at x = 3)\n")
        raise SystemExit(2)
    return t


MASSES = _select_masses()
CFG = MASS_CONFIGS[MASSES]
X3 = MASSES == (1, 1, 3)


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


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


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

# ---------------------------------------------------------------------------
# 1. Exact rational connection A(d,s)  (analytic formula -- Kira IBP output)
# ---------------------------------------------------------------------------
CONN = json.load(open(_pinned_path(CFG["conn"])))
MASTERS = [tuple(m) for m in CONN["masters"]]
N = len(MASTERS)            # 14
TOP = CONN["TOP_idx"]       # index of J(1,1,1,1,1)

# eps-grade: carry eps^-2 .. eps^0 for ALL 14 masters (42 components,
# unconditionally -- a component that is 0 at the boundary can evolve nonzero).
KMIN, KMAX = -2, 0
NEPS = KMAX - KMIN
# Aco[(i, j, k)] = (pc, qc): the eps^k coefficient of A_ij(4 - 2 eps, s) as the
# exact rational function P(s)/Q(s) (ascending Fraction lists).  The lists are
# READ from the pinned graded file of this line (the coefficient lists the
# earlier sympy parse produced, frozen 2026-09-05 -- the numerics consume the
# same integers as before) and CHECKED against the connection strings by the
# exact parser at every start: every entry re-derived and asserted equal as a
# rational function, the key sets equal; a mismatch is REFUSED by name before
# any value is printed.
try:
    Aco = kx.load_graded(CONN["A"], _pinned_path(CFG["graded"]), NEPS)
except kx.ParseError as _ex:
    sys.stderr.write(f"kite-evaluate REFUSED: {CFG['graded']} vs the connection {CFG['conn']}: {_ex}\n")
    raise SystemExit(3)

STATE = [(i, K) for i in range(N) for K in range(KMIN, KMAX + 1)]
IDX = {sK: n for n, sK in enumerate(STATE)}
NS = len(STATE)             # 42

# graded connection entries as exact polynomial coefficient lists (ascending):
# entry (row, col) = P(s)/Q(s); Taylor series generated per step numerically.
# Kept EXACT here; mpf copies are (re)built at the current dps by
# _rebuild_numeric() below (module-level mpf frozen at import dps would
# silently cap any later higher-precision call).
_RAT_EXACT = []
for n, (i, K) in enumerate(STATE):
    for m, (j, Kp) in enumerate(STATE):
        k = K - Kp
        if k < 0 or k > NEPS or (i, j, k) not in Aco:
            continue
        pc, qc = Aco[(i, j, k)]
        _RAT_EXACT.append((n, m, pc, qc))


# ---------------------------------------------------------------------------
# 2. Taylor-series transport of the graded system (runs at every call)
# ---------------------------------------------------------------------------
def _shift(coeffs, x0):
    """Taylor coefficients of a polynomial about x0 (synthetic division)."""
    c = list(coeffs)[::-1]
    n = len(c)
    out = []
    for j in range(n):
        for i in range(1, n - j):
            c[i] += c[i - 1] * x0
        out.append(c[n - 1 - j])
        c = c[:n - 1 - j]
    return out


def _series(pc, qc, x0, order):
    """Taylor coefficients of P/Q about x0 by exact power-series division."""
    ps, qs = _shift(pc, x0), _shift(qc, x0)
    c = [mp.mpf(0)] * (order + 1)
    q0 = qs[0]
    for n in range(order + 1):
        t = ps[n] if n < len(ps) else mp.mpf(0)
        for k in range(1, min(n, len(qs) - 1) + 1):
            t -= qs[k] * c[n - k]
        c[n] = t / q0
    return c


def _step(y0, x0, h, order0, ncap):
    """One CERTIFIED Taylor step: y(x0+h) from d y/ds = M(s) y, M rational.

    The step rule (|h| <= SAFETY x distance to the nearest connection pole)
    certifies series ratio r <= SAFETY, so the truncation tail obeys
        tail <= max(|a_n h^n| over trailing TAIL_WINDOW terms, all 42 comps)
                * SAFETY/(1-SAFETY).
    order0 is a STARTING seed; the order grows x1.5 by EXACT continuation of
    the same recurrences until the bound beats 10^-(dps+TAIL_GUARD);
    RuntimeError at the cap.  Returns (y, certified_bound, order_used)."""
    tol = mp.mpf(10) ** (-(mp.mp.dps + TAIL_GUARD))
    rfac = SAFETY / (1 - SAFETY)
    habs = abs(h)
    N = order0
    tc = [(r, cc, _series(pc, qc, x0, N)) for (r, cc, pc, qc) in RAT]
    a = [list(y0)]
    for n in range(N + 1):
        ssum = [mp.mpf(0)] * NS
        for (r, cc, t) in tc:
            acc = mp.mpf(0)
            for k in range(n + 1):
                acc += t[k] * a[n - k][cc]
            ssum[r] += acc
        a.append([v / (n + 1) for v in ssum])
    while True:
        bound = mp.mpf(0)
        for n in range(max(1, len(a) - TAIL_WINDOW), len(a)):
            hp = habs ** n
            for i in range(NS):
                t = abs(a[n][i]) * hp
                if t > bound:
                    bound = t
        bound = bound * rfac
        if bound < tol:
            break                          # step CERTIFIED at this order
        if N >= ncap:
            raise RuntimeError(
                "kite transport tail gate FAILED: certified tail bound "
                f"{mp.nstr(bound, 3)} >= tol {mp.nstr(tol, 3)} "
                f"(= 10^-(dps+{TAIL_GUARD}), dps={mp.mp.dps}) at step "
                f"x0={mp.nstr(x0, 8)}, h={mp.nstr(h, 8)} with N={N} "
                f"(cap {ncap} = 8 x starting {order0})")
        N2 = min(N * 3 // 2 + 8, ncap)
        tc = [(r, cc, _series(pc, qc, x0, N2)) for (r, cc, pc, qc) in RAT]
        for n in range(N + 1, N2 + 1):     # exact continuation, same recurrence
            ssum = [mp.mpf(0)] * NS
            for (r, cc, t) in tc:
                acc = mp.mpf(0)
                for k in range(n + 1):
                    acc += t[k] * a[n - k][cc]
                ssum[r] += acc
            a.append([v / (n + 1) for v in ssum])
        N = N2
    y = [mp.mpf(0)] * NS
    hp = mp.mpf(1)
    for n in range(len(a)):
        for i in range(NS):
            y[i] += a[n][i] * hp
        hp *= h
    return y, bound, N


# singularities of the connection: {0, 1, 2, 6 +/- 4 sqrt2}; negative axis clean
# (POLES itself is built at the current dps in _rebuild_numeric below)


def transport(y0, x0, x1):
    """Transport the 42-component state from x0 to x1 (adaptive Taylor steps).

    Returns (y, err, worst, n_escalated): err = sum of certified per-step tail
    BOUNDs (bound on the accumulated truncation, not an estimate)."""
    # starting order: user ORDER seed, pre-scaled so a healthy run meets the
    # certified gate without escalation (speed only -- the gate is the answer)
    dpo = -mp.log10(SAFETY)                # certified digits per order unit
    n0 = max(ORDER, int((mp.mp.dps + TAIL_GUARD) / dpo) + 16)
    ncap = 8 * n0
    y, t, x1 = list(y0), mp.mpf(x0), mp.mpf(x1)
    dirn = 1 if x1 > t else -1
    err = mp.mpf(0)
    worst = mp.mpf(0)
    nesc = 0
    while abs(x1 - t) > mp.mpf(10) ** (-mp.mp.dps + 10):
        r = min(abs(t - p) for p in POLES)
        h = dirn * min(SAFETY * r, abs(x1 - t))
        y, b, nused = _step(y, t, h, n0, ncap)
        err += b
        if b > worst:
            worst = b
        if nused > n0:
            nesc += 1
        t += h
    return y, err, worst, nesc


# ---------------------------------------------------------------------------
# 3. Boundary seed at s = -2 (the ONLY stored kinematic point of this work)
#    DERIVED seed (kite-boundary.py output; classical constants only).
#    The AMFlow vector kite-boundary-sm2.json is loaded further below as a
#    HELD-OUT cross-check; it never feeds the transport.
# ---------------------------------------------------------------------------
BND = json.load(open(_pinned_path(CFG["seed"])))
assert kx.rat(BND["s"]) == kx.rat(CFG["s_boundary"])
S_BOUNDARY = kx.mpf_rat(BND["s"])   # rebuilt at the working precision in _rebuild_numeric
AMF_BND_PATH = _pinned_path(CFG["ref"])
ENGINE_PATH = _pinned_path(CFG["engine"]) if "engine" in CFG else None   # the x = 3 seed engine, pin-checked at load


def seed_gate_vs_amflow():
    """Startup held-out cross-check: derived seed vs the 130-digit AMFlow
    boundary vector (kite-boundary-sm2.json).  Worst agreement over the graded
    eps^-2..eps^0 components, recomputed here from the two JSON strings.  The
    AMFlow file is consumed ONLY here -- the transport above is seeded purely
    by the derived vector.  Returns (worst_digits, cap) or None; worst is
    capped at cap = min(stored dps of the two files) -- agreement beyond the
    stored strings is not measurable."""
    if not os.path.exists(AMF_BND_PATH):
        return None
    amf = json.load(open(AMF_BND_PATH))
    cap = min(int(BND["dps"]), int(amf["dps"]))
    worst = None
    with mp.workdps(cap + 15):
        der = {(int(i), int(o)): mp.mpf(v) for i, co in BND["boundary"].items()
               for o, v in co.items() if KMIN <= int(o) <= KMAX}
        for i_str, co in amf["boundary"].items():
            for o_str, v in co.items():
                if not (KMIN <= int(o_str) <= KMAX):
                    continue
                d = digits_agree(der.get((int(i_str), int(o_str)), mp.mpf(0)), v)
                worst = d if worst is None else min(worst, d)
    return min(worst, float(cap)), cap

RAT, Y0, POLES = [], [], []
_BUILT_DPS = None


def _rebuild_numeric():
    """(Re)build every dps-dependent numeric object at the CURRENT mp.mp.dps.

    Sources of truth are exact rationals (_RAT_EXACT) and the 130-digit
    boundary strings in the JSON, re-parsed here, so raising dps genuinely
    raises working precision (no import-dps cap)."""
    global RAT, Y0, POLES, _BUILT_DPS, S_BOUNDARY
    if _BUILT_DPS == mp.mp.dps:
        return
    RAT = [(n, m,
            [mp.mpf(c.numerator) / mp.mpf(c.denominator) for c in pc],
            [mp.mpf(c.numerator) / mp.mpf(c.denominator) for c in qc])
           for (n, m, pc, qc) in _RAT_EXACT]
    gb = {int(i): {int(o): mp.mpf(v) for o, v in co.items()}
          for i, co in BND["boundary"].items()}
    Y0 = [gb.get(i, {}).get(K, mp.mpf(0)) for (i, K) in STATE]
    POLES = CFG["poles"]()         # the selected line's singular points, at this dps
    S_BOUNDARY = kx.mpf_rat(BND["s"])   # exact -2 at x = 2; -5/3 at x = 3 to this dps
    _BUILT_DPS = mp.mp.dps


_rebuild_numeric()


def kite_top_eps0(s_val, dps=None, order=None, return_cert=False,
                  allow_seed_cap=False):
    """J^0_top(s) computed live by DE-transport from the s=-2 boundary.

    s_val : kinematic point, real Euclidean s < 0.  DOMAIN: the connection
            has poles at s = 0, 1, 2, 6 +/- 4*sqrt(2); the transport path
            [-2, s] must stay on the negative real axis, so s >= 0 raises
            ValueError (analytic continuation past threshold not implemented).
    dps   : TARGET decimal digits (default: current mp.mp.dps).  Work happens
            at dps+WORK_GUARD; every step carries a certified tail bound.
    order : optional STARTING Taylor order seed (speed only, never the answer;
            the certified gate escalates it as needed).
    return_cert : also return the certified accumulated truncation BOUND.
    allow_seed_cap : skip the fail-closed stored-seed-precision check (used
            ONLY by comparator/demo reruns whose claims are explicitly capped
            by stored-string precision; never for a certified deliverable).
    """
    global ORDER
    target = int(dps) if dps is not None else mp.mp.dps
    if order is not None:
        ORDER = int(order)
    if not allow_seed_cap and int(BND["dps"]) < target + SEED_GUARD:
        raise RuntimeError(
            f"kite seed cap: target {target} digits needs a boundary seed of "
            f">= {target + SEED_GUARD} digits but the loaded seed holds only "
            f"{BND['dps']} -- rerun with --boundary-recompute "
            f"[{target + WORK_GUARD + SEED_GUARD}] (fail-closed; the vendored "
            f"strings are a fast-start cache, the recompute path is the "
            f"definition)")
    with mp.workdps(target + WORK_GUARD):
        _rebuild_numeric()
        s_val = mp.mpf(s_val)
        if s_val >= 0:
            raise ValueError("domain: Euclidean s < 0 only (connection poles at "
                             "s = 0, 1, 2, 6 +/- 4*sqrt(2))")
        yt, err, _worst, _nesc = transport(Y0, S_BOUNDARY, s_val)
        val = yt[IDX[(TOP, 0)]]
    if return_cert:
        return val, err            # exact prefactor of J^0_top is 1 (l1 = 1)
    return val


def kite_state_vector(s_val, dps=None, order=None, return_cert=False,
                      allow_seed_cap=False):
    """The full 42-component graded state at s (eps^-2..eps^0 of every master),
    by the SAME live DE-transport as kite_top_eps0 (identical seed-cap check,
    working precision, domain check and certified steps); kite_top_eps0 is
    this vector's (TOP, 0) component.  Used by the x = 3 reference table."""
    global ORDER
    target = int(dps) if dps is not None else mp.mp.dps
    if order is not None:
        ORDER = int(order)
    if not allow_seed_cap and int(BND["dps"]) < target + SEED_GUARD:
        raise RuntimeError(
            f"kite seed cap: target {target} digits needs a boundary seed of "
            f">= {target + SEED_GUARD} digits but the loaded seed holds only "
            f"{BND['dps']} -- rerun with --boundary-recompute "
            f"[{target + WORK_GUARD + SEED_GUARD}] (fail-closed; the vendored "
            f"strings are a fast-start cache, the recompute path is the "
            f"definition)")
    with mp.workdps(target + WORK_GUARD):
        _rebuild_numeric()
        s_val = mp.mpf(s_val)
        if s_val >= 0:
            raise ValueError("domain: Euclidean s < 0 only (connection poles at "
                             f"{CFG['poles_text']})")
        yt, err, _worst, _nesc = transport(Y0, S_BOUNDARY, s_val)
    if return_cert:
        return yt, err
    return yt


def _x3_reference_block(s_str):
    """The shipped independent-reference block at the point s_str (x = 3):
    the top-level block at the seed point, the 'oracle' block elsewhere;
    None when the point carries no reference."""
    ref = json.load(open(AMF_BND_PATH))
    if kx.rat(s_str) == kx.rat(ref["s"]):
        return ref
    for k, blk in ref.get("oracle", {}).items():
        if kx.rat(s_str) == kx.rat(k):
            return blk
    return None


def x3_reference_table(vec, s_str, target):
    """x = 3: print every (master, eps order) entry of the shipped independent
    reference at this point with the agreement recomputed here, and RAISE
    unless every digit-compared entry reaches min(bar, target) digits and every
    rational entry equals its rational at the printed precision.  Returns
    (worst_digits, n_digit_compared, n_rational)."""
    ref = _x3_reference_block(s_str)
    if ref is None:
        print(f"  (no shipped reference at s={s_str}; the (1,1,3) reference points "
              f"are s = {kx.rat(json.load(open(AMF_BND_PATH))['s'])} and "
              f"{', '.join(json.load(open(AMF_BND_PATH)).get('oracle', {}).keys())})")
        return None
    bar = min(CFG["bar"], target)
    rat = ref.get("rational", {})
    print(f"  independent reference at s={s_str} ({ref['dps']} d strings, gate only): "
          f"{'entry':>16} | {'computed here':>44} | {'reference':>44} | agreement")
    worst, n_dig, n_rat, bad = None, 0, 0, []
    for i_str in sorted(ref["boundary"], key=int):
        for K_str in sorted(ref["boundary"][i_str], key=int):
            i, K = int(i_str), int(K_str)
            ref_s = ref["boundary"][i_str][K_str]
            comp = vec[IDX[(i, K)]]
            label = f"M{i:<2d}{str(MASTERS[i]):<17s} eps^{K:>2d}"
            q = rat.get(i_str, {}).get(K_str)
            if q is not None:
                n_rat += 1
                with mp.workdps(target + WORK_GUARD + 40):
                    qv = kx.mpf_rat(q)
                    resid = abs(comp - qv)
                    ok = mp.nstr(comp, target) == mp.nstr(qv, target)
                verdict = (f"exact (= {q} at {target} d; |residual| {mp.nstr(resid, 3)})"
                           if ok else f"NOT exact (= {q}? |residual| {mp.nstr(resid, 3)})")
                if not ok:
                    bad.append(label)
            else:
                n_dig += 1
                d = digits_agree(comp, ref_s)
                worst = d if worst is None else min(worst, d)
                ok = d >= bar
                verdict = f"{d:6.1f} d {'>=' if ok else '< '} {bar}"
                if not ok:
                    bad.append(label)
            with mp.workdps(int(ref["dps"]) + 15):
                ref_40 = mp.nstr(mp.mpf(ref_s), 40)   # the reference parsed at its own precision
            print(f"  {label} | {mp.nstr(comp, 40):>44} | {ref_40:>44} | {verdict}")
    print(f"[gate] x=3 reference at s={s_str}: {n_dig} digit-compared entries worst "
          f"{worst:.1f} d vs bar >= {bar} (= min({CFG['bar']}, dps)); {n_rat} rational "
          f"entries exact -> {'PASS' if not bad else 'FAIL'}")
    if bad:
        raise RuntimeError(
            f"kite x=3 reference gate FAILED at s={s_str}: {len(bad)} of {n_dig + n_rat} "
            f"entries below the bar or not exact ({', '.join(bad[:4])}{' ...' if len(bad) > 4 else ''}) "
            f"-- value NOT certified")
    return worst, n_dig, n_rat


def _x3_recompute_seed(dps):
    """x = 3: re-derive the seed live by the shipped engine (kite-boundary-general.py
    --x 3, exit -1/40, transported to the seed point) and return it in the
    kite-boundary-derived.json schema (components below 10^-(dps-15) omitted,
    the served emit rule)."""
    import subprocess
    import tempfile
    _tf = tempfile.NamedTemporaryFile(suffix=".json", delete=False)
    _tf.close()
    subprocess.run([sys.executable, ENGINE_PATH,
                    "--conn", _pinned_path(CFG["conn"]), "--x", str(MASSES[2]),
                    "--dps", str(dps), "--s-exits=" + CFG["s_exit"],
                    "--points=" + str(BND["s"]), "--receipt", _tf.name], check=True)
    rec = json.load(open(_tf.name))
    os.unlink(_tf.name)
    vec = rec["exits"][CFG["s_exit"]]["points"][str(BND["s"])]["vector"]
    out = {"s": BND["s"], "dps": int(dps), "masters": BND["masters"], "boundary": {}}
    with mp.workdps(int(dps) + 20):
        thr = mp.mpf(10) ** (-(int(dps) - 15))
        for k, v in vec.items():
            i, K = (int(x) for x in k.split(","))
            if abs(mp.mpf(v)) < thr:
                continue
            out["boundary"].setdefault(str(i), {})[str(K)] = v
    return out


# ---------------------------------------------------------------------------
# 4. Held-out oracle (INDEPENDENT AMFlow oracle -- never used in the transport)
#    Source: the 130-digit AMFlow reference set of the original computation,
#    key "1,1,1,1,1", eps order "0" (the boundary s=-2 entry of that set feeds
#    the seed above, but these three held-out points do not).
# ---------------------------------------------------------------------------
ORACLE = {
    "-15": "-0.30219635513149952542573978268629167086969869042598488218438460811202420290612263644747537497699545184126836908015279216618642665",
    "-5/2": "-0.81923281916056396448348845196261127489748165066955329613978127278221480425118778340014824180823979739437832803276438465775563048",
    "-3": "-0.76106090868892144773521847459179957022044417870950166914756365717806191187716978691020642129577002388106291670516922061673024748",
}

# Named boundary constant (close-out record of the original computation):
# N_kite := 4s*J^0_top(s)|_{s=-2} = -8*M13[eps^0](-2).
# PSLQ against every furnished named ring is honestly NEGATIVE: this constant
# is delivered as a named integral, not a closed form.
N_KITE = ("7.1099373328681288451450579266132164319982323461305848134238880968741912"
          "55917005848739647269207918106090080011010041408669171518840")


def digits_agree(computed, oracle):
    # compare at elevated precision: the ambient dps is the TARGET since the
    # 2026-07-05 working-guard change, and parsing the 128-130 d reference
    # strings at target dps would silently cap the measurement there
    amb = mp.mp.dps
    with mp.workdps(amb + WORK_GUARD + 40):
        computed, oracle = mp.mpf(computed), mp.mpf(oracle)
        if computed == oracle:
            return float(amb + WORK_GUARD + 40)
        return float(-mp.log10(abs((computed - oracle) / oracle)))


# ---------------------------------------------------------------------------
# 5. Runtime geometry cross-checks (all computed here, no stored digits)
# ---------------------------------------------------------------------------
def sunrise_periods(t):
    """BMSW (1,1,2) sunrise maximal-cut curve periods psi1, psi2 at t = s."""
    m1, m2, m3 = mp.mpf(1), mp.mpf(1), mp.sqrt(2)
    M100 = m1 * m1 + m2 * m2 + m3 * m3
    mu1, mu2, mu3, mu4 = -m1 + m2 + m3, m1 - m2 + m3, m1 + m2 - m3, m1 + m2 + m3
    Delta = mu1 * mu2 * mu3 * mu4
    rad = 3 * (mp.sqrt(mu1 ** 2 - t) * mp.sqrt(mu2 ** 2 - t)
               * mp.sqrt(mu3 ** 2 - t) * mp.sqrt(mu4 ** 2 - t))
    e1 = (-t * t + 2 * M100 * t + Delta + rad) / 24
    e2 = (-t * t + 2 * M100 * t + Delta - rad) / 24
    e3 = (2 * t * t - 4 * M100 * t - 2 * Delta) / 24
    Z3 = e1 - e2
    k2 = (e3 - e2) / Z3
    psi1 = 2 / mp.sqrt(Z3) * mp.ellipk(k2)
    psi2 = 2j / mp.sqrt(Z3) * mp.ellipk(1 - k2)
    return psi1, psi2, k2


def minimal_model_om1():
    """Real period om1 of y^2 = x^3 - 756x + 7344 (conductor 128) via AGM."""
    e3m, e2m, e1m = sorted(r.real for r in mp.polyroots([1, 0, -756, 7344]))
    k2 = (e2m - e3m) / (e1m - e3m)
    return 2 * mp.ellipk(k2) / mp.sqrt(e1m - e3m)


# ---------------------------------------------------------------------------
# 6. The Minkowski arm (2026-09-06): the same certified step driven along a
#    complex rectangle above (or below) the real axis into s > 0 -- the Feynman
#    s + i0 boundary value -- gated at s = 16 against the vendored AMFlow
#    record kite-reference-minkowski.json (pinned; gate only).  The served
#    real-axis functions above are called, never copied.
# ---------------------------------------------------------------------------
MINK_REF = "kite-reference-minkowski.json"
MINK_DEFAULT_H = "4"        # the detour height of record
MINK_DPS_FLOOR = 20         # below it the raising bar would let the --mutate control pass by construction
MINK_MARGIN = 2             # the guard on the last printed digit of the gate bar
MINK_PAIR_DROP = 20         # the transport pair: the same path rerun at dps - 20 (the record's 60/40 form; half the precision below dps 40)
MINK_MUTATE_DIGIT = 10      # --mutate alters this significant digit of the record's top eps^0 real part in memory


def _minkowski_reference():
    """The vendored record, PIN FIRST: the file missing is REFUSED by name (exit 4),
    a byte change (exit 3), before any value is computed."""
    import hashlib
    path = os.path.join(HERE, MINK_REF)
    want = PINS[MINK_REF]
    if not os.path.exists(path):
        sys.stderr.write(f"kite-evaluate REFUSED: --minkowski record {MINK_REF} is MISSING (recorded sha256 {want}); "
                         "not serving --minkowski\n")
        raise SystemExit(4)
    have = hashlib.sha256(open(path, "rb").read()).hexdigest()
    if have != want:
        pos = next((k + 1 for k, (x, y) in enumerate(zip(want, have)) if x != y), 0)
        sys.stderr.write(f"kite-evaluate REFUSED: {MINK_REF} integrity pin mismatch (recorded {want}, recomputed {have}; "
                         f"first differing hex position {pos} of 64, 1-based) -- the shipped record was altered; "
                         "not serving --minkowski\n")
        raise SystemExit(3)
    ref = json.load(open(path))
    assert [tuple(m) for m in ref["masters"]] == MASTERS and int(ref["TOP_idx"]) == TOP, "record master order"
    return ref


def _complex_transport(y0, x0, nodes):
    """The served `_step` driven along the polygon x0 -> nodes[0] -> ... -> nodes[-1] with the step rule
    |h| <= SAFETY x min_p |x - p| (the COMPLEX distance to the five real poles).  Mirrors `transport`
    (starting order, cap, certified per-step bound summed); the disc of convergence of every entry's
    Taylor series about a complex x0 reaches the nearest pole, so the tail bound is certified as on the
    real axis.  Returns (y, err, worst, n_escalated, n_steps, legs) with one (steps, worst, order) record per leg."""
    dpo = -mp.log10(SAFETY)
    n0 = max(ORDER, int((mp.mp.dps + TAIL_GUARD) / dpo) + 16)
    ncap = 8 * n0
    y = [mp.mpc(v) for v in y0]
    x = mp.mpc(x0)
    err = mp.mpf(0)
    worst = mp.mpf(0)
    nesc = 0
    nstep = 0
    legs = []
    eps_end = mp.mpf(10) ** (-mp.mp.dps + 10)
    for tgt in nodes:
        tgt = mp.mpc(tgt)
        t_leg = time.time()
        n_leg = 0
        w_leg = mp.mpf(0)
        o_leg = n0
        while abs(tgt - x) > eps_end:
            r = min(abs(x - p) for p in POLES)
            dist = abs(tgt - x)
            step = min(SAFETY * r, dist)
            if step < mp.mpf(10) ** (-(mp.mp.dps - 5)):
                raise RuntimeError(f"kite --minkowski: the step collapsed at x = {mp.nstr(x, 8)}: a pole lies on the path")
            h = (tgt - x) if step >= dist else (tgt - x) / dist * step
            y, b, nused = _step(y, x, h, n0, ncap)
            err += b
            if b > worst:
                worst = b
            if b > w_leg:
                w_leg = b
            if nused > n0:
                nesc += 1
            o_leg = max(o_leg, nused)
            x = x + h
            nstep += 1
            n_leg += 1
        legs.append((n_leg, w_leg, o_leg, time.time() - t_leg))
    return y, err, worst, nesc, nstep, legs


def _mink_label(n):
    i, K = STATE[n]
    return f"M{i:<2d}{str(MASTERS[i]):<17s} eps^{K:>2d}"


def _mink_strings(vec, D):
    """The value strings of a 42-component vector at D + 5 significant digits, trailing zeros kept (the
    comparison form: 'identical' means agreement to the shorter printed length, so every string carries its
    full length -- an exact 2 prints as 2.000... and cannot pass on a short cap)."""
    return [(mp.nstr(v.real, D + 5, strip_zeros=False), mp.nstr(v.imag, D + 5, strip_zeros=False)) for v in vec]


def _mink_ndig(s):
    return len(s.replace("-", "").replace(".", "").lstrip("0").split("e")[0]) or 10 ** 6


def _mink_agree(a_re, a_im, b_re, b_im, amb):
    """(complex, real-part, imaginary-part) agreement digits of the value strings a vs b, relative to |b|;
    None where exactly equal.  Computed at elevated precision from the strings."""
    with mp.workdps(amb + WORK_GUARD + 40):
        a = mp.mpc(mp.mpf(a_re), mp.mpf(a_im))
        b = mp.mpc(mp.mpf(b_re), mp.mpf(b_im))
        mag = abs(b) if abs(b) != 0 else mp.mpf(1)
        dc = None if a == b else float(-mp.log10(abs(a - b) / mag))
        dr = None if a.real == b.real else float(-mp.log10(abs(a.real - b.real) / mag))
        di = None if a.imag == b.imag else float(-mp.log10(abs(a.imag - b.imag) / mag))
    return dc, dr, di


def _mink_floor(dmap):
    vals = [(d, k) for k, d in dmap.items() if d is not None]
    ident = [k for k, d in dmap.items() if d is None]
    if not vals:
        return None, None, len(ident), len(dmap)
    fl = min(vals)
    return fl[0], fl[1], len(ident), len(dmap)


def _mink_transport(target, s_val, H, what):
    """One detour transport of the served state at the target precision (working target + WORK_GUARD):
    the seed cap of the served --point path, the rectangle, the leg lines, the certified bound.  Returns
    the 42-component complex vector (at the working precision) and the summed certified tail bound."""
    if int(BND["dps"]) < target + SEED_GUARD:
        raise RuntimeError(
            f"kite seed cap: target {target} digits needs a boundary seed of >= {target + SEED_GUARD} digits but the "
            f"loaded seed holds only {BND['dps']} -- rerun with --boundary-recompute [{target + WORK_GUARD + SEED_GUARD}] "
            "(fail-closed; the vendored strings are a fast-start cache, the recompute path is the definition)")
    t0 = time.time()
    with mp.workdps(target + WORK_GUARD):
        _rebuild_numeric()
        s_c = mp.mpc(s_val)
        ih = mp.mpc(0, H)
        nodes = [mp.mpc(S_BOUNDARY) + ih, s_c + ih, s_c]
        print(f"[{what}] detour at target {target} (working {mp.mp.dps}): {mp.nstr(S_BOUNDARY, 6)} -> "
              f"({mp.nstr(nodes[0].real, 6)},{mp.nstr(nodes[0].imag, 6)}) -> ({mp.nstr(nodes[1].real, 6)},{mp.nstr(nodes[1].imag, 6)}) "
              f"-> ({mp.nstr(nodes[2].real, 6)},{mp.nstr(nodes[2].imag, 6)})  ({'UPPER' if H > 0 else 'LOWER'} half plane: "
              f"s {'+' if H > 0 else '-'} i0)")
        y, err, worst, nesc, nstep, legs = _complex_transport(Y0, S_BOUNDARY, nodes)
        for k, (n_leg, w_leg, o_leg, t_leg) in enumerate(legs, 1):
            print(f"  [{what}] leg {k}: {n_leg} steps, order {o_leg}, worst certified tail {mp.nstr(w_leg, 3)}, {t_leg:.1f} s")
        print(f"  [{what}] {nstep} steps, {nesc} escalations, {time.time() - t0:.1f} s")
        print(f"  [certified] transport truncation |Delta y| <= {mp.nstr(err, 3)} on every component (sum of per-step "
              f"certified tail BOUNDs, r <= SAFETY={float(SAFETY)} by the step rule; not an estimate)")
        return list(y), err


def _mink_gate_table(strings, ref, target, mutate):
    """The 42-component table of this run against the vendored record (the goal-60 block).  Returns
    (floors, fails, resolved) -- floors = {complex, re, im, im_resolved}: (digits, member, n_identical, n)."""
    goal = int(ref["goal_digits"])
    bar = min(target, int(ref["record"]["certified_count"])) - MINK_MARGIN
    zero_bar = mp.mpf(10) ** (-(min(target, goal) - 5))
    vals = ref["values"]
    if mutate:
        s = vals[str(TOP)]["0"]["re"]
        digs = [k for k, ch in enumerate(s) if ch.isdigit() and s[:k].replace("-", "").replace(".", "").lstrip("0") != "" or (ch.isdigit() and ch != "0")]
        pos = digs[MINK_MUTATE_DIGIT - 1]
        vals = json.loads(json.dumps(vals))
        vals[str(TOP)]["0"]["re"] = s[:pos] + str((int(s[pos]) + 1) % 10) + s[pos + 1:]
        print(f"[mutate] CONTROL: the record's top eps^0 real part altered in memory at significant digit "
              f"{MINK_MUTATE_DIGIT} (the file and its pin untouched): the gate below must FAIL by name")
    print(f"[gate] independent AMFlow record at s={ref['s']} (goal {goal}, eps order {ref['eps_order']}, s + i0; "
          f"{ref['midpoint_digits']}-digit midpoints, gate only): "
          f"{'component':>26s} | {'complex':>12s} | {'re':>12s} | {'im':>12s} | verdict")
    dC, dR, dI, resolved, zeros, missing, wrong_sign, fails = {}, {}, {}, [], [], [], [], []
    for n, (i, K) in enumerate(STATE):
        name = f"({i},{K})"
        p_re, p_im = strings[n]
        blk = vals.get(str(i), {}).get(str(K))
        with mp.workdps(target + WORK_GUARD + 40):
            pv = mp.mpc(mp.mpf(p_re), mp.mpf(p_im))
            if blk is None:
                if abs(pv) < zero_bar:
                    zeros.append(name)
                    print(f"  {_mink_label(n)} | {'zero':>12s} | {'':>12s} | {'':>12s} | absent in the record (below its leading order = identically 0); |this| {mp.nstr(abs(pv), 3)}")
                else:
                    missing.append(name)
                    print(f"  {_mink_label(n)} | {'MISSING':>12s} | | | absent in the record but |this| = {mp.nstr(abs(pv), 3)}")
                continue
            rv = mp.mpc(mp.mpf(blk["re"]), mp.mpf(blk["im"]))
            if abs(rv) < zero_bar and abs(pv) < zero_bar:
                zeros.append(name)
                print(f"  {_mink_label(n)} | {'zero':>12s} | {'':>12s} | {'':>12s} | both below 10^-{min(target, goal) - 5}")
                continue
            im_frac = abs(rv.imag) / abs(rv)
            r_sign = mp.sign(rv.imag)
            p_sign = mp.sign(pv.imag)
        dc, dr, di = _mink_agree(p_re, p_im, blk["re"], blk["im"], target)
        cap = float(min(min(_mink_ndig(p_re), _mink_ndig(p_im)), min(_mink_ndig(blk["re"]), _mink_ndig(blk["im"]) if blk["im"].strip() not in ("0", "0.0") else 10 ** 6)))
        dC[name] = None if (dc is None or dc >= cap) else dc
        dR[name] = None if (dr is None or dr >= cap) else dr
        dI[name] = None if (di is None or di >= cap) else di
        is_res = im_frac > mp.mpf(10) ** (-bar)
        if is_res:
            resolved.append(name)
            if r_sign != p_sign:
                wrong_sign.append(name)
        ok = (dC[name] is None or dC[name] >= bar) and (not is_res or dI[name] is None or dI[name] >= bar) and name not in wrong_sign
        cell = lambda d: f"{'identical':>12s}" if d is None else f"{d:9.2f} d  "
        print(f"  {_mink_label(n)} | {cell(dC[name])} | {cell(dR[name])} | {cell(dI[name])} | "
              f"{'PASS' if ok else 'FAIL'}{' (Im resolved)' if is_res else ''}{' (cap ' + str(int(cap)) + ')' if dC[name] is None else ''}")
        if dC[name] is not None and dC[name] < bar:
            fails.append(f"{name} complex {dC[name]:.2f} < {bar}")
        if is_res and dI[name] is not None and dI[name] < bar:
            fails.append(f"{name} imag {dI[name]:.2f} < {bar}")
        if name in wrong_sign:
            fails.append(f"{name} imaginary part has the WRONG SIGN (s - i0 where s + i0 is recorded)")
    if missing:
        fails.append(f"missing in the record: {missing}")
    fC, fR, fI = _mink_floor(dC), _mink_floor(dR), _mink_floor(dI)
    fRes = _mink_floor({k: dI[k] for k in resolved})
    fmt = lambda f: (f"{f[0]:.2f} d (member {f[1]}; identical {f[2]} of {f[3]})" if f[0] is not None else f"identical on all {f[3]}")
    print(f"[gate] floors vs the record: complex {fmt(fC)}; real part {fmt(fR)}; imaginary part {fmt(fI)}; "
          f"{len(resolved)} components with a resolved imaginary part (|Im|/|value| > 10^-{bar}), floor on those {fmt(fRes)}; "
          f"sign mismatches {len(wrong_sign)}; zero components {len(zeros)} {zeros}")
    # the vendored goal-60 vs goal-40 pair: the certificate of the strings themselves
    tw = ref["twin_goal40"]["values"]
    dT = {}
    for n, (i, K) in enumerate(STATE):
        name = f"({i},{K})"
        a = vals.get(str(i), {}).get(str(K))
        b = tw.get(str(i), {}).get(str(K))
        if a is None or b is None or name in zeros:
            continue
        dT[name] = _mink_agree(a["re"], a["im"], b["re"], b["im"], target)[0]
    fT = _mink_floor(dT)
    print(f"[record] the vendored goal-{goal} vs goal-{ref['twin_goal40']['goal_digits']} AMFlow pair, recomputed from the two blocks: "
          f"floor {fmt(fT)} (the strings' own two-precision certificate; the record's {ref['record']['amflow_pair_goal60_vs_goal40']['digits']} d)")
    print(f"[gate] bar = min(dps {target}, {ref['record']['certified_count']}) - {MINK_MARGIN} = {bar} "
          f"({ref['record']['certified_count']} = the certified count of record at s = {ref['s']}: the gate floor "
          f"{ref['record']['gate_floor_complex']['digits']} d of the dps-60 transport under the pair above; {MINK_MARGIN} = the last-digit guard) "
          f"-> {'PASS' if not fails else 'FAIL'}")
    return {"complex": fC, "re": fR, "im": fI, "im_resolved": fRes, "amflow_pair": fT}, fails, resolved, bar


def _mink_pair(strings_a, strings_b, D_a, D_b, what):
    """The two printed value sets (D_a + 5 and D_b + 5 digits) compared per component: floor, member, identical count.
    A component below 10^-(min(D_a, D_b) - 5) in BOTH sets is zero to the lower precision (the top's eps^-2 / eps^-1
    vanish identically; a relative agreement of two vanishing numbers is meaningless) and counts as identical.
    RAISING at >= min(D_a, D_b)."""
    d = {}
    n_zero = 0
    with mp.workdps(max(D_a, D_b) + WORK_GUARD + 40):
        zero_bar = mp.mpf(10) ** (-(min(D_a, D_b) - 5))
        for n, (i, K) in enumerate(STATE):
            a = mp.mpc(mp.mpf(strings_a[n][0]), mp.mpf(strings_a[n][1]))
            b = mp.mpc(mp.mpf(strings_b[n][0]), mp.mpf(strings_b[n][1]))
            if abs(a) < zero_bar and abs(b) < zero_bar:
                d[f"({i},{K})"] = None
                n_zero += 1
                continue
            d[f"({i},{K})"] = _mink_agree(strings_a[n][0], strings_a[n][1], strings_b[n][0], strings_b[n][1], max(D_a, D_b))[0]
            cap = float(min(min(_mink_ndig(strings_a[n][0]), _mink_ndig(strings_a[n][1])), min(_mink_ndig(strings_b[n][0]), _mink_ndig(strings_b[n][1]))))
            if d[f"({i},{K})"] is not None and d[f"({i},{K})"] >= cap:
                d[f"({i},{K})"] = None
    f = _mink_floor(d)
    bar = min(D_a, D_b)
    ok = f[0] is None or f[0] >= bar
    print(f"[{what}] floor {f[0]:.2f} d (member {f[1]}; identical {f[2]} of {f[3]}, of which {n_zero} zero to 10^-{min(D_a, D_b) - 5}) "
          f"vs threshold >= {bar} -> {'PASS' if ok else 'FAIL'}"
          if f[0] is not None else f"[{what}] identical on all {f[3]} components (to the shorter printed length; {n_zero} zero to 10^-{min(D_a, D_b) - 5}) -> PASS")
    return f, ok


def minkowski_tier(args, t_start):
    """The --minkowski arm: PIN first, the seed gate, the detour (and the conjugate control with H < 0), the 42
    components printed, the gate table at the record point, the transport pair, the one-line summary.  Returns 0;
    raises RuntimeError (exit 1) on any FAIL; exit 2 on a refusal by name."""
    target = mp.mp.dps
    if target < MINK_DPS_FLOOR:
        sys.stderr.write(f"kite-evaluate REFUSED: --minkowski needs --dps >= {MINK_DPS_FLOOR} (below it the raising bar "
                         f"min(dps, 64) - {MINK_MARGIN} would let the --mutate control pass by construction)\n")
        return 2
    try:
        s_val = kx.mpf_rat(args.point)
        s_rat = kx.rat(args.point)
    except (TypeError, ValueError, ZeroDivisionError):
        s_val = mp.mpf(args.point)
        s_rat = None
    if s_val <= 0:
        sys.stderr.write(f"kite-evaluate REFUSED: --minkowski is the s > 0 arm (the Feynman s + i0 boundary value); "
                         f"--point {args.point} is Euclidean: use --point without --minkowski (the served real-axis transport)\n")
        return 2
    with mp.workdps(target + WORK_GUARD):
        _rebuild_numeric()
        dmin = min(abs(mp.mpf(s_val) - p) for p in POLES)
    if (s_rat is not None and s_rat in (0, 1, 2)) or dmin < mp.mpf(10) ** (-(target)):
        sys.stderr.write(f"kite-evaluate REFUSED: --point {args.point} lies on a pole of the connection "
                         f"({CFG['poles_text']}); the detour ends on the real axis at s itself\n")
        return 2
    H = mp.mpf(kx.rat(args.detour).numerator) / mp.mpf(kx.rat(args.detour).denominator) if args.detour is not None else mp.mpf(MINK_DEFAULT_H)
    if H == 0:
        sys.stderr.write("kite-evaluate REFUSED: --detour 0 is the real axis through the poles; give H > 0 (upper) or H < 0 (lower)\n")
        return 2
    ref = _minkowski_reference()                     # PIN FIRST (exit 3 / 4 by name)
    is_record = (s_rat is not None and s_rat == kx.rat(ref["s"]))
    if args.mutate and not is_record:
        sys.stderr.write(f"kite-evaluate REFUSED: --mutate is the control of the gate at the record point s = {ref['s']}; "
                         f"--point {args.point} carries no record\n")
        return 2
    print(f"[minkowski] masses (1,1,2) = (1, 0, 1, 0, sqrt2): the Feynman s + i0 boundary value at s = {args.point} by the complex "
          f"detour of the served 42-component graded system (height H = {mp.nstr(abs(H), 6)}, "
          f"{'UPPER path = s + i0' if H > 0 else 'LOWER path = s - i0, the conjugate control'}); connection {CFG['conn']}, "
          f"derived seed {CFG['seed']} (s={BND['s']}, {BND['dps']} d), record {MINK_REF} (s = {ref['s']}, goal {ref['goal_digits']}; "
          f"gate only); pins verified; poles at {CFG['poles_text']}, nearest to s at distance {mp.nstr(dmin, 6)}")
    # RAISING boundary-seed gate (the served --point form): the loaded seed is certified BEFORE any transport
    sg = seed_gate_vs_amflow()
    if sg is None:
        if not args.boundary_recompute:
            raise RuntimeError(
                "kite --minkowski seed gate UNAVAILABLE: the cross-check file "
                f"{os.path.basename(AMF_BND_PATH)} is absent and the seed was not re-derived live -- rerun with "
                "--boundary-recompute (fail-closed: an ungated stored seed cannot certify a value)")
        print("[gate] boundary seed: cross-check file absent; seed was re-derived live by --boundary-recompute "
              "and byte-checked against the stored cache -> PASS")
    else:
        sg_ok = sg[0] >= sg[1] - 8
        print(f"[gate] boundary seed vs the independent AMFlow boundary (gate-cache only, never used in transport): worst "
              f"{sg[0]:.1f} d vs threshold >= cap-8 = {sg[1] - 8} -> {'PASS' if sg_ok else 'FAIL'}")
        if not sg_ok:
            raise RuntimeError(
                f"kite --minkowski seed gate FAILED: derived seed vs the independent AMFlow boundary worst agreement "
                f"{sg[0]:.1f} d < cap-8 = {sg[1] - 8} -- {CFG['seed']} corrupted or derivation broken; value NOT computed")
    y_main, cert = _mink_transport(target, s_val, H, "upper" if H > 0 else "lower")
    str_main = _mink_strings(y_main, target)
    if H > 0:
        physical, str_phys, cert_phys = y_main, str_main, cert
    else:
        # the conjugate control: the upper path is run too, and the upper value is compared with conj(lower)
        y_up, cert_up = _mink_transport(target, s_val, -H, "upper")
        str_up = _mink_strings(y_up, target)
        str_conj = [(re_s, mp.nstr(-mp.mpf(im_s), target + 5)) for (re_s, im_s) in str_main]
        f_sch, ok_sch = _mink_pair(str_up, str_conj, target, target, "schwarz: upper (s + i0) vs conj(lower (s - i0))")
        if not ok_sch:
            raise RuntimeError(f"kite --minkowski conjugate control FAILED at s={args.point}: upper vs conj(lower) floor "
                               f"{f_sch[0]:.2f} d < {target} (member {f_sch[1]})")
        physical, str_phys, cert_phys = y_up, str_up, cert_up
    print(f"the 42 graded components at s = {args.point} + i0 (target {target} digits, working {target + WORK_GUARD}):")
    n_branch = 0
    with mp.workdps(target + WORK_GUARD):
        thr = mp.mpf(10) ** (-(target - 5))
        for n, v in enumerate(physical):
            branch = abs(v.imag) > thr * max(abs(v), mp.mpf(1))
            n_branch += int(branch)
            print(f"  {_mink_label(n)} | Re {mp.nstr(v.real, target):>{target + 8}s} | Im {mp.nstr(v.imag, target):>{target + 8}s}"
                  f"{'' if branch else '  (no branch: |Im| below 10^-' + str(target - 5) + ')'}")
    top = physical[IDX[(TOP, 0)]]
    print(f"J^0_top(s={args.point} + i0) = {mp.nstr(top.real, target)} + i {mp.nstr(top.imag, target)}")
    print(f"  [certified] transport truncation |Delta J| <= {mp.nstr(cert_phys, 3)}; {n_branch} of {NS} components carry a "
          f"resolved imaginary part (a branch cut crossed), {NS - n_branch} are real to 10^-{target - 5}")
    floors = fails = None
    if is_record:
        floors, fails, resolved, bar = _mink_gate_table(str_phys, ref, target, args.mutate)
    else:
        print(f"  (no vendored record at s={args.point}; the record point is s = {ref['s']})")
    # the transport pair: the same path at dps - MINK_PAIR_DROP (the record's 60/40 form), half the precision below dps 40
    D_b = target - MINK_PAIR_DROP if target >= 2 * MINK_PAIR_DROP else target // 2
    print(f"[pair] the transport pair: the same path rerun at dps {D_b} ...")
    y_b, cert_b = _mink_transport(D_b, s_val, H, "pair")
    str_b = _mink_strings(y_b, D_b)
    f_pair, ok_pair = _mink_pair(str_main, str_b, target, D_b, f"pair: dps {target} vs dps {D_b}")
    if not ok_pair:
        raise RuntimeError(f"kite --minkowski transport pair FAILED at s={args.point}: dps {target} vs dps {D_b} floor "
                           f"{f_pair[0]:.2f} d < {D_b} (member {f_pair[1]})")
    # the counts of the summary line: a floor rounded down; 'identical on all' = the shorter printed length (D_b + 5, or dps + 5 vs the record)
    pair_n = int(f_pair[0]) if f_pair[0] is not None else D_b + 5
    if is_record:
        gate_n = int(floors["complex"][0]) if floors["complex"][0] is not None else min(target + 5, int(ref["midpoint_digits"]))
        print(f"{gate_n} digits at dps {target} (the transport pair certifies {pair_n})")
        if fails:
            raise RuntimeError(f"kite --minkowski gate FAILED at s={args.point} vs {MINK_REF}: {len(fails)} by name -- "
                               f"{'; '.join(fails[:6])}{' ...' if len(fails) > 6 else ''} -- value NOT certified")
    else:
        print(f"s = {args.point}: no record at this point; the transport pair certifies {pair_n} at dps {target}")
    print(f"wall time: {time.time() - t_start:.1f} s")
    return 0


# ---------------------------------------------------------------------------
# demo / gate  (default), or --point/--dps/--order single-point evaluation
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser(
        description="Unequal-mass kite top master J^0_top(s), live DE-transport "
                    "from the s=-2 boundary.  DOMAIN: Euclidean s < 0 (real "
                    "axis; connection poles at s = 0, 1, 2, 6 +/- 4*sqrt(2)).  "
                    "--masses 1,1,3 selects the (1,1,x) line at x = 3 (masses 1, 0, 1, 0, "
                    "sqrt3; seed at s = -5/3, poles at s = 0, 7 - 4*sqrt(3), 1, 3, "
                    "7 + 4*sqrt(3)).",
        epilog="TIERS (measured walls: this host, a shared 96-core server at loadavg "
               "~130, wall clock): bare = the (1,1,2) quick demo at dps 30 (18 s); "
               "--point=-7/3 (dps 100 default; 47 s); --point=-7/3 --dps 150 "
               "--boundary-recompute (164 s); --full (219 s); "
               "--masses 1,1,3 = the (1,1,3) quick demo, --point=-10/3 at dps 30 (53 s); "
               "--masses 1,1,3 --point=-10/3 --dps 130 = the transported reference point, 22-entry table "
               "(192 s); --masses 1,1,3 --point=-5/3 --dps 130 = the seed point, no transport "
               "(43 s); --masses 1,1,3 --point=-10/3 --dps 130 --boundary-recompute = the seed "
               "re-derived live by kite-boundary-general.py (312 s); --minkowski --point 16 --dps 60 = the "
               "Minkowski arm at the record point (the 42-component table vs the vendored AMFlow record + the "
               "transport pair at dps 40; the record's own measurement of this class 1069 s + 771 s at load ~220), "
               "--minkowski --point 16 --dps 30 the pilot class (330 s here).  Exit codes: 0 pass; "
               "1 a raising gate (seed gate, reference bar, two-precision, certified tail, the Minkowski gate, "
               "the transport pair, the conjugate control); 2 usage "
               "refusal (unsupported --masses, --full or --no-crank misuse; --minkowski without --point, at s <= 0, "
               "on a pole, below --dps 20, with --masses 1,1,3 / --full / --no-crank; --mutate without --minkowski "
               "or off the record point); 3 an integrity pin "
               "mismatch on a shipped file (the x = 3 data, the parser module, the graded lists, the Minkowski record); "
               "4 the Minkowski record kite-reference-minkowski.json missing.")
    ap.add_argument("--masses", metavar="A,B,C", default="1,1,2",
                    choices=["1,1,2", "1,1,3"],
                    help="the (1,1,x) mass line: 1,1,2 (default; masses 1, 0, 1, 0, sqrt2) "
                         "or 1,1,3 (masses 1, 0, 1, 0, sqrt3); any other triple is refused")
    ap.add_argument("--point", metavar="S", default=None,
                    help="evaluate at this Euclidean point s<0 (rational like "
                         "-7/3 or decimal like -4.25) instead of the gate demo")
    ap.add_argument("--dps", type=int, default=None,
                    help="working precision, decimal digits (default 100); "
                         "unless --order is given, order scales to max(order, dps)")
    ap.add_argument("--order", type=int, default=None,
                    help="Taylor order per step (default 100)")
    ap.add_argument("--boundary-recompute", nargs="?", const=130, type=int,
                    metavar="DPS", default=None,
                    help="re-derive the s=-2 boundary seed by running the shipped "
                         "kite-boundary.py at DPS (default 130) instead of reading "
                         "the cached strings; the stored JSON demotes to a "
                         "byte-agreement cache check")
    ap.add_argument("--full", action="store_true",
                    help="run the deep suite (the pre-2026-09 default): three "
                         "held-out points at dps 100 + the dps-200 doubling demo")
    ap.add_argument("--no-crank", action="store_true",
                    help="--point only: skip the in-run dps+60 two-precision "
                         "rerun (default ON); the value prints with an explicit "
                         "UNCROSS-CHECKED label; seed gate + certified per-step "
                         "tail bounds still run and still raise")
    ap.add_argument("--minkowski", action="store_true",
                    help="the Minkowski arm (2026-09-06): with --point S (S > 0 off the poles) "
                         "transport the 42-component state along the complex rectangle "
                         "-2 -> -2 + iH -> S + iH -> S (the Feynman s + i0 value); at S = 16 the "
                         "42-component table against the vendored AMFlow record; always the "
                         "transport pair (a rerun at dps - 20, half the precision below dps 40) "
                         "and the one-line summary")
    ap.add_argument("--detour", metavar="H", nargs="?", const=MINK_DEFAULT_H, default=None,
                    help="the detour height (default 4); H < 0 = the lower path (s - i0), printed "
                         "as the conjugate control against the upper; --detour alone selects "
                         "--minkowski (use --detour=-4 for a negative height)")
    ap.add_argument("--mutate", action="store_true",
                    help="--minkowski --point 16 only: alter one digit of the record's top eps^0 "
                         "real part in memory (the file and its pin untouched); the gate must "
                         "FAIL by name (exit 1)")
    args = ap.parse_args()
    # quick default (2026-09-03): bare invocation runs the dps-30 quick suite;
    # an explicit --dps, DPS env, or --full overrides.
    quick = args.point is None and not args.full
    if quick and args.dps is None and "DPS" not in os.environ:
        mp.mp.dps = 30
    if args.no_crank and args.point is None:
        ap.error("--no-crank applies to --point runs only "
                 "(the demo/gate suite always cranks)")
    if args.detour is not None and not args.minkowski:
        args.minkowski = True            # --detour H alone selects the arm (the alias)
    if args.minkowski:
        if args.point is None:
            ap.error("--minkowski needs --point S with S > 0 (the arm transports to the Feynman s + i0 value at S)")
        if args.full:
            ap.error("--full is the Euclidean deep suite; --minkowski is a --point arm")
        if X3:
            ap.error("--minkowski is the (1,1,2) line's arm (the vendored record is at (1,1,2), s = 16); "
                     "not served at --masses 1,1,3")
        if args.no_crank:
            ap.error("--no-crank applies to the Euclidean --point run; the Minkowski arm always runs its transport pair")
    elif args.mutate:
        ap.error("--mutate is the control of --minkowski --point 16 and requires --minkowski")
    if X3:
        # 2026-09-05: the x = 3 line is a --point evaluator; the demo/gate
        # suite and --full are the (1,1,2) record.  Bare --masses 1,1,3 runs
        # the x = 3 QUICK demo: the s=-10/3 reference point at dps 30.
        if args.full:
            ap.error("--full is the (1,1,2) deep suite; at --masses 1,1,3 use "
                     "--point (or no --point for the x = 3 quick demo)")
        if args.point is None:
            args.point = CFG["quick_point"]
            print(f"[x=3 quick default] --masses 1,1,3 without --point: the "
                  f"reference point s={args.point} at dps {mp.mp.dps} (the seed "
                  f"gate at s={BND['s']} + the transported 22-entry table); "
                  f"--point/--dps override")
    if args.dps is not None:
        mp.mp.dps = args.dps
        if args.order is None:
            ORDER = max(ORDER, args.dps)
    if args.order is not None:
        ORDER = args.order

    if args.boundary_recompute:
        # 2026-07-05: end-to-end live at any dps; the stored
        # 130-digit strings demote to a checked fast-start cache.
        import subprocess
        import sys as _sys
        import tempfile
        _bdps = args.boundary_recompute
        _bneed = mp.mp.dps + WORK_GUARD + SEED_GUARD
        if _bdps < _bneed:
            # fail-closed: the seed must out-hold the certified target
            print(f"[boundary-recompute] bumping requested seed dps {_bdps} -> "
                  f"{_bneed} (= target {mp.mp.dps} + working guard {WORK_GUARD} "
                  f"+ seed guard {SEED_GUARD})")
            _bdps = _bneed
        if X3:
            print(f"[boundary-recompute] deriving the s={BND['s']} seed live: "
                  f"{CFG['engine']} --conn {CFG['conn']} --x {MASSES[2]} --dps {_bdps} "
                  f"--s-exits={CFG['s_exit']} --points={BND['s']} --receipt <tmp> ...")
            BND_LIVE = _x3_recompute_seed(_bdps)
        else:
            print(f"[boundary-recompute] deriving the s=-2 seed live: "
                  f"kite-boundary.py --dps {_bdps} --emit <tmp> ...")
            _tf = tempfile.NamedTemporaryFile(suffix=".json", delete=False)
            _tf.close()
            subprocess.run([_sys.executable, os.path.join(HERE, "kite-boundary.py"),
                            "--dps", str(_bdps), "--emit", _tf.name], check=True)
            BND_LIVE = json.load(open(_tf.name))
            os.unlink(_tf.name)
        # cache check: each stored string must be a byte-prefix of
        # the live one (or vice versa at low DPS), allowing a final-digit
        # round-to-nearest difference.
        _ncomp = _nok = 0
        _bad = []
        for _i, _dd in BND["boundary"].items():
            for _k, _s_st in _dd.items():
                _s_new = BND_LIVE["boundary"].get(_i, {}).get(_k)
                _ncomp += 1
                if _s_new is None:
                    _bad.append((_i, _k, "absent"))
                    continue
                _short, _long = sorted((_s_st, _s_new), key=len)
                if _long.startswith(_short):
                    _nok += 1
                    continue
                _p = 0
                for _x, _y in zip(_s_st, _s_new):
                    if _x != _y:
                        break
                    _p += 1
                if _p >= min(len(_s_st), len(_s_new)) - 1:   # last-digit rounding
                    _nok += 1
                else:
                    _bad.append((_i, _k, f"prefix {_p}/{min(len(_s_st), len(_s_new))}"))
        print(f"[boundary-recompute] stored-string cache check: {_nok}/{_ncomp} "
              f"byte-prefix/last-digit-rounding -> "
              f"{'PASS' if _nok == _ncomp else 'FAIL'}")
        if _nok != _ncomp:
            raise SystemExit(f"[boundary-recompute] cache check FAILED: {_bad[:5]}")
        BND = BND_LIVE
        _BUILT_DPS = None            # force rebuild from the live strings
        _rebuild_numeric()

    t_start = time.time()

    if args.minkowski:
        raise SystemExit(minkowski_tier(args, t_start))

    if args.point is not None:
        try:
            s_val = kx.mpf_rat(args.point)
        except (TypeError, ValueError, ZeroDivisionError):
            s_val = mp.mpf(args.point)
        target = mp.mp.dps
        if X3:
            # the endpoint to the working precision (-10/3 is not exact in
            # binary; the x = 2 endpoints of record are built at target dps)
            try:
                with mp.workdps(target + WORK_GUARD):
                    s_val = kx.mpf_rat(args.point)
            except (TypeError, ValueError, ZeroDivisionError):
                pass
            print(f"[x=3] masses (1,1,3) = (1, 0, 1, 0, sqrt3): connection {CFG['conn']}, "
                  f"derived seed {CFG['seed']} (s={BND['s']}, {BND['dps']} d), independent "
                  f"reference {CFG['ref']} (gate only); pins verified; poles at "
                  f"{CFG['poles_text']}")
            if s_val >= 0:
                raise ValueError("domain: Euclidean s < 0 only (x = 3 connection poles at "
                                 f"{CFG['poles_text']})")
        # RAISING boundary-seed gate (2026-07-05b): certify the
        # loaded seed BEFORE any transport.  --point has no held-out oracle at
        # generic s and the two-precision rerun below shares the seed, so this
        # cache-compare (against the held-out AMFlow boundary vector -- a
        # gate-cache only, never used in the transport) is the ONLY gate that
        # can see a corrupted/mutated kite-boundary-derived.json here.
        sg = seed_gate_vs_amflow()
        if sg is None:
            if not args.boundary_recompute:
                raise RuntimeError(
                    "kite --point seed gate UNAVAILABLE: held-out cross-check "
                    f"file {os.path.basename(AMF_BND_PATH)} is absent and the "
                    "seed was not re-derived live -- rerun with "
                    "--boundary-recompute (fail-closed: an ungated stored "
                    "seed cannot certify a --point value)")
            print("[gate] boundary seed: cross-check file absent; seed was "
                  "re-derived live by --boundary-recompute and byte-checked "
                  "against the stored cache -> PASS")
        else:
            sg_ok = sg[0] >= sg[1] - 8
            print(f"[gate] boundary seed vs held-out AMFlow boundary "
                  f"(gate-cache only, never used in transport): worst "
                  f"{sg[0]:.1f} d vs threshold >= cap-8 = {sg[1] - 8} -> "
                  f"{'PASS' if sg_ok else 'FAIL'}")
            if not sg_ok:
                raise RuntimeError(
                    f"kite --point seed gate FAILED: derived seed vs held-out "
                    f"AMFlow boundary worst agreement {sg[0]:.1f} d < cap-8 = "
                    f"{sg[1] - 8} -- {CFG['seed']} corrupted or "
                    f"derivation broken; value NOT computed")
        if X3:
            vec3, cert = kite_state_vector(s_val, return_cert=True)
            val = vec3[IDX[(TOP, 0)]]
        else:
            val, cert = kite_top_eps0(s_val, return_cert=True)
        print(f"J^0_top(s={args.point}) by live DE-transport from s={BND['s']} "
              f"(target {target} digits, working {target + WORK_GUARD}):")
        print(" ", mp.nstr(val, mp.mp.dps))
        print(f"  [certified] transport truncation |Delta J| <= "
              f"{mp.nstr(cert, 3)}  (sum of per-step certified tail BOUNDs, "
              f"r <= SAFETY={float(SAFETY)} by the step rule; not an estimate)")
        if X3:
            x3_reference_table(vec3, args.point, target)
        else:
            for s_str, oracle in ORACLE.items():
                if kx.mpf_rat(s_str) == s_val:
                    print(f"  gate point: {digits_agree(val, oracle):.1f} digits "
                          f"vs held-out oracle")
        # in-run two-precision gate (RAISING): --point has no held-out oracle,
        # so certify against an independent rerun at target+60 (genuinely
        # different working precision and step orders).  Shares the stored
        # seed, so it certifies the computation; the seed itself is covered by
        # the fail-closed seed-cap check in kite_top_eps0.
        # 2026-07-06: OPTIONAL via --no-crank (default ON; the
        # skip is labelled loudly -- the value above then rests on the seed
        # gate + the certified per-step tail bounds alone).
        if args.no_crank:
            print(f"[gate] in-run two-precision rerun at dps {target + 60} "
                  "SKIPPED (--no-crank): value is UNCROSS-CHECKED this run "
                  "(no dps+60 agreement measured; the certified per-step "
                  "tail bounds and the boundary-seed gate above still hold)")
        else:
            print(f"[gate] in-run two-precision rerun at dps {target + 60} ...")
            val2 = kite_top_eps0(s_val, dps=target + 60, allow_seed_cap=True)
            d2p = digits_agree(val, val2)
            print(f"[gate] two-precision: stable to {d2p:.1f} d vs threshold "
                  f">= {target} -> {'PASS' if d2p >= target else 'FAIL'}")
            if d2p < target:
                raise RuntimeError(
                    f"kite --point two-precision gate FAILED: J^0_top({args.point}) "
                    f"stable to only {d2p:.1f} d < target {target} -- "
                    f"value NOT certified")
        print(f"wall time: {time.time() - t_start:.1f} s")
        raise SystemExit(0)

    DPS0, ORDER0 = mp.mp.dps, ORDER
    ORACLE_RUN = {"-5/2": ORACLE["-5/2"]} if quick else ORACLE
    print("Unequal-mass kite TOP J(1,1,1,1,1) eps^0 -- LIVE DE-transport vs held-out AMFlow")
    print(f"(42-component eps-graded system, Taylor order {ORDER}, dps {mp.mp.dps}, "
          f"boundary s=-2 only)\n")

    print("Boundary seed (kite-boundary-derived.json -- DERIVED by kite-boundary.py"
          "\n  from classical constants gamma_E, zeta(2), ln 2, Catalan; NO AMFlow input):")
    print("  J_top^(0)(-2) =", mp.nstr(Y0[IDX[(TOP, 0)]], 40), "...")
    sg = seed_gate_vs_amflow()
    if sg is not None:
        print(f"  derived seed vs held-out AMFlow boundary (kite-boundary-sm2.json, "
              f"gate only --\n  never used in transport): worst component agrees to "
              f"{sg[0]:.1f} digits (cap: {sg[1]} d stored)")
        # RAISING since 2026-07-05 (calibrated: healthy seed agrees AT the
        # stored-string cap, threshold cap-8 leaves >= 10^8 headroom)
        if sg[0] < sg[1] - 8:
            raise RuntimeError(
                f"kite seed gate FAILED: derived seed vs held-out AMFlow "
                f"boundary worst agreement {sg[0]:.1f} d < cap-8 = {sg[1] - 8} "
                f"-- seed JSON corrupted or derivation broken")

    print("\nHeld-out gate: value below is COMPUTED NOW by transport from s=-2.")
    print(f"{'s':>6} | {'this work (computed transport)':>42} | agree vs oracle")
    worst = mp.inf
    digs_by_s = {}
    cert_worst = mp.mpf(0)
    for s_str, oracle in ORACLE_RUN.items():
        s_val = kx.mpf_rat(s_str)
        pred, cert = kite_top_eps0(s_val, return_cert=True)
        digs = digits_agree(pred, oracle)
        digs_by_s[s_str] = digs
        worst = min(worst, digs)
        cert_worst = max(cert_worst, cert)
        print(f"{s_str:>6} | {mp.nstr(pred, 40):>42} | {digs:6.1f} digits")
    print(f"  min live agreement: {float(worst):.1f} digits "
          f"(earlier deep runs: 88.9-130.2 d at these points)")
    print(f"  [certified] transport truncation |Delta J| <= {mp.nstr(cert_worst, 3)} "
          f"(worst point; sum of per-step certified tail BOUNDs, not an estimate)")
    # held-out oracle gate, RAISING since 2026-07-05: healthy runs saturate
    # working precision (target+25, measured), so min(target, 118) never fires
    # on a healthy run (>= 10^6 headroom); a mutated seed/oracle lands here.
    oth = min(DPS0, ORACLE_GATE_FLOOR)
    print(f"[gate] held-out oracle: worst {float(worst):.1f} d vs threshold "
          f">= {oth} -> {'PASS' if worst >= oth else 'FAIL'}")
    if worst < oth:
        raise RuntimeError(
            f"kite held-out gate FAILED: worst agreement {float(worst):.1f} d "
            f"< threshold {oth} (= min(dps, {ORACLE_GATE_FLOOR})) -- "
            f"seed/oracle corrupted or precision path broken")

    # ---- geometry consistency, all recomputed from scratch ----
    psi1, psi2, k2 = sunrise_periods(mp.mpf(-2))
    om1 = minimal_model_om1()
    h = mp.mpf(10) ** (-mp.mp.dps // 3)
    p1p = (sunrise_periods(-2 + h)[0] - sunrise_periods(-2 - h)[0]) / (2 * h)
    p2p = (sunrise_periods(-2 + h)[1] - sunrise_periods(-2 - h)[1]) / (2 * h)
    W = psi1 * p2p - psi2 * p1p
    print("\nRuntime geometry checks (mpmath ellipk / polyroots, no stored digits):")
    print(f"  k^2(-2) - (2+sqrt2)/4       = {mp.nstr(abs(k2 - (2 + mp.sqrt(2)) / 4), 3)}")
    print(f"  psi1(-2) - 3*om1_minmodel   = {mp.nstr(abs(psi1.real - 3 * om1), 3)}")
    print(f"  W(-2) - i*pi/8  (Legendre)  = {mp.nstr(abs(W - 1j * mp.pi / 8), 3)}"
          f"  (central-difference W)")

    # cross-artifact identity: named constant vs boundary data file
    r1 = mp.mpf(N_KITE) + 8 * Y0[IDX[(TOP, 0)]]
    print(f"  N_kite + 8*J_top(-2)        = {mp.nstr(abs(r1), 3)}"
          f"  (close-out record vs DERIVED seed, both 130 d)")
    t_gate = time.time() - t_start

    # ---- dps-doubling demo: one gate point rerun at 2x precision ----------
    # (seed-cap exempt BY DESIGN: its claim is capped by the stored oracle
    # string and labelled so; the certified any-D path is --boundary-recompute)
    s2_str = "-5/2"
    dps2, order2 = 2 * DPS0, 2 * ORDER0
    t2 = time.time()
    pred2 = kite_top_eps0(kx.mpf_rat(s2_str), dps=dps2, order=order2,
                          allow_seed_cap=True)
    d2 = digits_agree(pred2, ORACLE[s2_str])
    cap = len(ORACLE[s2_str].split(".")[1])  # stored significant digits
    print(f"\ndps-doubling demo (s = {s2_str}): dps {DPS0} -> {dps2}, "
          f"Taylor order {ORDER0} -> {order2}")
    print(f"  live agreement: {digs_by_s[s2_str]:.1f} -> {d2:.1f} digits "
          f"({time.time() - t2:.1f} s)")
    print(f"  stored oracle string holds {cap} digits -- measurable agreement "
          f"caps there" + ("  [CAP HIT]" if d2 >= cap - 2 else ""))
    # RAISING since 2026-07-05: the doubled run must track its target up to
    # the stored-string caps.  Calibrated (measured healthy runs): DPS 30/60/
    # 100 give 85.8/125.0/128.0 d vs thresholds 60/118/118 -> >= 10^7 headroom;
    # the seed-cap slack 12 covers l1 transport amplification of the 130-digit
    # seed strings, the oracle slack 10 covers the last stored digits.
    dth = min(dps2, cap - 10, int(BND["dps"]) - 12)
    print(f"[gate] dps-doubling: {d2:.1f} d vs threshold >= {dth} -> "
          f"{'PASS' if d2 >= dth else 'FAIL'}")
    if d2 < dth:
        raise RuntimeError(
            f"kite dps-doubling gate FAILED: {d2:.1f} d < threshold {dth} "
            f"(= min(2*dps, oracle cap-10, seed cap-12)) -- digits do not "
            f"track dps")

    if quick:
        print("\n[quick default] this was the dps-30 quick suite -- rerun with "
              "--full for the three-point dps-100 gate demo + the dps-200 "
              "doubling demo")

    print(f"\nwall time: {time.time() - t_start:.1f} s "
          f"(gate demo {t_gate:.1f} s + doubling demo {time.time() - t2:.1f} s)")
