#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""v959 -- PRIME.PORT.RHP.COUPLEDTAU.TERMINAL.01 (rounds 256-259, ADJUDICATED at the finite-identity level): THE COUPLED-TAU / TERMINAL-BUDGET DICTIONARY OF THE WALL -- the positive-prefix firewall and the exact 2x2 causal census, the coupled two-term tau recursion of the indivisible full-source object D = tau^aug/tau (with its bilinear Hirota-type corollary derived and gated in-module), the blind coefficient-field predictor that passes the frozen micro-falsifier on both sides, and the exact Schur budget telescope with its one-inequality terminal reduction.  ONE module from four probes (21/21 + 26/26 + 27/27 + 19/19 first-pass gates, zero fails; discovery probes baseborder_factorial_probe.py, coupledtau_probe.py, budget_anatomy_probe.py, parametrix_pass_probe.py, rounds 256/257/258/259, notes DLXXXVII/DLXXXVIII/DLXXXIX/DXC, 2026-08-24, re-run identically at promotion, embedded BYTE-EXACT and executed verbatim), plus the module-own exact section S0 (sympy-symbolic + exact rationals).  (S0) THE MODULE-OWN EXACT THEOREMS (fine types Identity/Formal): (S0.1) the coupled recursion tau_{n+1} = a_n tau_n, tau^aug_{n+1} = a_n tau^aug_n + b_n tau_n with a_n = c_n^2 h_n and b_n = -(c_n F_n)^2 implies the Riccati drain D_{n+1} = D_n - F_n^2/h_n for D = tau^aug/tau, symbolically and on a frozen exact-rational chain; b_n is a manifest negative square, source-sign-pure in every world.  (S0.2) THE BILINEAR TAU FORM (the canonical integrable corollary, derived algebraically from the recursion and gated): tau^aug_n tau_{n+1} - tau^aug_{n+1} tau_n = (c_n F_n)^2 tau_n^2 -- the Wronskian-type bilinear identity whose right side is a manifest square: the fiber increment is a positive tau cross-ratio, (tau^aug_n tau_{n+1} - tau^aug_{n+1} tau_n)/(tau_n tau_{n+1}) = F_n^2/h_n * (a_n tau_n / tau_{n+1}) collapses to the drain (symbolic + exact rationals, every step of the frozen chain).  (S0.3) THE TERMINAL REDUCTION + CONSEQUENCE GATE: with the r243 budget definition B = S_{N-2} + 5/7 (by construction), D_N = B - S_{N-1} = 5/7 - rho_{N-1}, hence margin D_N > 0 iff q_N = rho_{N-1}/(5/7) < 1 -- the ENTIRE fiber positivity is one terminal inequality (symbolic identity + exact rationals in both truth values).  (S0.4) THE CORNER-RAY / t* NORMAL FORM: B(t) = S_{N-2} + t*(5/7) makes the terminal pivot affine in t with slope exactly 5/7 and machine root t* = q_N -- the budget question IS a t*-coordinate in the r238 normal form (symbolic).  (S0.5) THE POSITIVE-PREFIX FIREWALL THEOREM (exact rationals): for a signed rational measure the prefix moment kernel H_p is positive definite iff the whole h-prefix h_0..h_{p-1} is positive (exact Sylvester chain, det H_p = prod h_i identity), the maximal positive prefix p_max is well-defined, a positive control measure types POSITIVE_PREFIX (p_max = N) while a frozen signed measure types INDEFINITE_CONTINUATION with an explicit negative border readout past p_max -- the r256 reviewer PSD core statement as exact algebra, with the must-fail firing.  (1) THE POSITIVE-PREFIX FIREWALL + THE 2x2 CAUSAL CENSUS (round 256, verdict EFFECTS_MIXED_COUPLEDTAU + INVERSION_IS_BASE_CONTAMINATION(f_neg=0.9311) + EPST: CONTROL_FIBER_IS_BASE_CONTAMINATION + SMOOTH_NULL_ANCHOR_OK + LEGS_BD_SKIPPED): the firewall type table -- MAIN pmax = 184 = N with ZERO negative modes (the ONLY positive-prefix world), SCRAMBLE pmax = 21 (37 negative modes), EPSTEIN 25 (55), SMOOTH 27 (4), all controls INDEFINITE_CONTINUATION; every prefix kernel numerically PSD (worst -lambda_min rel 5.7e-16) -- the reviewer PSD core theorem holds machine-level; the raw 2x2 census reproduces the r254 priors exactly (worst rel 4.9e-5; T_MM +4.334, T_MS +9.976, T_SM -0.928, T_SS -4.494; identity wards exactly 0) BUT the causal reading of the raw numbers WAS CONTAMINATED: Delta_base/Delta_int at full degree are bookkeeping over an indefinite kernel; on the causally clean surface (shared positive prefix n* = 21, both kernels PSD) the DOUBLE INVERSION -- Db* = -1.5e-6 (the base rotation is NULL on the clean prefix), Dbo* = -0.1759 (the border carries 81 percent of the prefix gap), Gap* = -0.216 with the raw border effect at the WRONG SIGN (-5.64 vs +8.83): the sealed LOAD_BEARING rule honestly does NOT fire, residual verdict COUPLEDTAU; legs B-D skipped by the sealed conditional (the exchange formula itself gated unconditionally exact, 1.2e-15); TWO CONTAMINATION DOWNGRADES ON RECORD: the r254 headline 'SCRAMBLE spectrally compact (K80 = 2)' is BASE CONTAMINATION (the exact h-sign mode split T_pos +3292.6 + T_neg -3297.1 = -4.494, net carried by the h < 0 mode space at 734x excess; the two carrying eigendirections sit at f_neg 0.93 in the h < 0 mode space) and the r253/r254 EPSTEIN fiber anomaly lives ENTIRELY in the indefinite continuation degrees k >= 25 (on the shared prefix the EPSTEIN border is fiber-IDENTICAL to MAIN, Dbo* = 1.3e-16) -- neither finding may be cited as a border/fiber discriminator any more; the alias must-fail is the core exhibit (T_SM negativity is 100 percent kernel property, lambda_min(G_SCR) = -2.9e6).  (2) THE COUPLED-TAU RECURSION (round 257, verdict COUPLED_RECURSION_EXACT + COCYCLE_LAW_FOUND + NO_EARLY_SEPARATION(0.84 dec) + MICROFALSIFIER_PASSED(blind, coefficient field) + NOPOLE_TREND(APPROACHING) + AUG_RAW_CROSSES_ONE + AUG_UNIT_CROSSES_ONE): the pair closes under the exact two-term recursion above (seeds tau_1 = h_0, tau^aug_1 = h_0 B - F_0^2; signed-log propagation vs direct bordered slogdets on all degrees/worlds at 1.2e-9 MAIN; anchor D_N = 5/7 - rho_{N-1} rel 4.8e-11; mp wards dps 220 THROUGH the SCRAMBLE flip); coefficient typology machine-gated: a_n reads the h-chain (its sign IS the world pivot sign), b_n is a negative square -- THE BASE ALONE CARRIES THE SIGN, THE BORDER ONLY NONNEGATIVE MAGNITUDE; the cocycle law breaks exactly at the control base flips 21/25/27 (the r256 firewall reproduced gradewise INSIDE the coupled dynamics); the ONE-LINE FORM of the whole problem: on MAIN (all h_n > 0) the drain is monotone through the entire free window (min rho 8.9e-10 at n = 180; head/bulk/tail shares 0.446/0.531/0.023) -- fiber positivity IS the budget inequality Sum(F_n^2/h_n) < B and wall positivity supplies the increment signs: base and fiber are coupled in ONE scalar law; THE FROZEN MICRO-FALSIFIER of PRIME.FREEMOMENT.POSITIVEPREFIX.01 is PASSED BLIND for the first time, at the coefficient-field level: the AST-separated predictor (consuming node positions + signed weights ONLY, pivot field via independent slogdet minors) hits the control flips 21/25/27 = 3/3 AND the forced tail (0, 2, 2, 3, 1) on all five windows (flips 184/153/170/367/592, mp wards dps 40) -- HONESTLY TYPED: a coefficient-field pass (route-independent source-only); the parametrix/local-connection pass stays OPEN (the ledger falsifier is half met: mechanism coordinate yes, analytic model no); the oracle mutant is flagged by the AST audit; NOPOLE measurement (10 rungs, s-dressed port, Schur identity re-gated 2.4e-13): dist = 1/lambda_max - 1 falls cofinally toward s = 1 (8.6e-5 -> 6.7e-7 over h = 96..591, slope -2.87 dec/dec, Spearman -0.81, lambda_max < 1 on 10/10 = the wall; not rung-monotone, disclosed) -- WARNING: BOTH augmented border variants CROSS the wall (raw lambda_max 4.3-7.0 mass-driven, direction-normalised 1.17-1.28): any no-pole path must go through the PAIR DYNAMICS itself, not through a bordered spectral bound; world separation before the terminal degree honestly missed (0.84 < 1.0 dec).  (3) THE BUDGET ANATOMY (round 258, verdict TELESCOPE_EXACT(BY_CONSTRUCTION; 5/7 = r241 IMPORTED floor, derivation OPEN) + TERMINAL_Q_LAW(FLAT, COVARIANT_RATIO) + TSTAR_IDENTIFIED + MAJORANT_OPEN + PREFIX_DOMINANCE_ARTIFACT): the Schur telescope D_N = B - S_{N-1} is the nontrivial content (12 windows incl. N = 878, mp wards dps 220 at 2.4e-16; f64 loses deep with slope +4.16 dec/dec, disclosed) while B = S_{N-2} + 5/7 is exact PER CONSTRUCTION (the r243 a4 definition); THE SOBERING PROVENANCE OF 5/7: neither Q_7 nor level 8 -- it is the inverted r241 floor 7/5 of the MEASURED min h_{N-1}/F_{N-1}^2 = 1.4278 (not saturated, margin 0.028 over 7/5): a rounded rational UNDER the measurement, typed FLOOR_IMPORTED -- the source-pure derivation of the floor is now THE named terminal task; the q census (42/42 rungs N = 142..878): q_N < 1 everywhere, min/med/max 0.0015/0.4188/0.9805, min margin 0.0139, trend FLAT (gap slope +0.41, Spearman +0.36 -- THE WALL MARGIN DOES NOT SHRINK WITH N); THE SHARPEST SINGLE FINDING: Spearman(2 log F_{N-1}, log h_{N-1}) = +1.000 -- border-readout square and terminal norm are RANK-PERFECTLY COVARIANT over the ladder (residual correlations tied): the driver is NEITHER F NOR h BUT THE QUOTIENT ITSELF (COVARIANT_RATIO) -- any terminal proof must bind the RATIO, not one side; consistently ALL THREE sealed mass majorants (sup / Cauchy-Schwarz / triangle) break with 0/42 coverage, median x490 excess, break locus 0.97N in the near-terminal zone where h collapses (w9 rho minimum 8.9e-10 at 0.978N with a +8.2-decade terminal rebound; tail IRREGULAR 40/42; rho_0 exactly = b1^2/h_0, median share 0.366): THE MASS-BOUND CLASS IS DEAD -- as compression, constants and band locality before it; t* IDENTIFIED: the corner ray makes the terminal pivot affine (collinearity 3.4e-13, slope == 5/7, machine root == q_N on 12/12) -- the budget question IS a t* coordinate in the r238 normal form, but Spearman(q_N, t*_r238) = +0.027: ONE NORMAL FORM, TWO DATA INSTANCES (m_2N vs F_{N-1}), statistically unconnected; the r256 side-finding resolved: the prefix border dominance is sign-universal (10/10 rungs) but the '81 percent' was a w9/n*=21 coincidence (ratio 0.006..4.11, 3/10 in band) -- the stable object is the SIGN (contract candidate, not upgraded); SMOOTH anchor 7.6e-23, must-fails loud to 3.6e9x.  (4) THE PARAMETRIX PASS (round 259, verdict PARAMETRIX_FAILED(i+ii+iii) + LEVEL_CROSSING_REFUTED + SWAP_STAT_NOT_SEPARATING + SELECTION_EXTENSIVE_AFTER_ALL -- three honest negatives, typed and load-bearing): (a) LEVEL CROSSING REFUTED: the parity-resolved saddle energy branches do NOT cross at the flip degree -- they cross 5-16 degrees TOO EARLY (EPSTEIN 9 vs 25, SMOOTH 19 vs 27, SCRAMBLE 16 vs 21) and on MAIN w9 they cross 45 TIMES WITHOUT A SINGLE TRUE FLIP (odd branch up to 0.20 dec under even over 9+ degrees at positive det G; mp wards dps 60): the |gamma| > 1 jump sits at the TRUE flips (+1.16/+0.41; SCRAMBLE -0.89 without a jump, disclosed) and belongs to the RESUMMED CHAIN, not to the branch crossing; (b) THE ONE-SWAP NO-GO: the critical swap at every control flip is a short-range countersign edge pair (median distance 2) -- but MAIN carries the SAME structure at the SAME degrees with FULLY OVERLAPPING gap distributions (control 0.0045-0.198 dec vs MAIN 0.013-0.528 dec): the one-bit question is answered NEGATIVE -- r255's ORIENTATION_LOWDIM(1) is REVISED ON RECORD (the 0.2-dec swap exists, but the missing information is not one-dimensional); (c) ALL THREE sealed candidates fail blind (0/3 control flips, 0/5 forced tail, 0/4 MAIN-clean; honourably: the P3 hysteresis is clean on 3/4 mains and misses the w9 forced tail by 3 degrees but hits no control); THE NAMED OBSTACLE (leg C, measured): THE PARAMETRIX GAP IS A RESUMMATION GAP, NOT A SELECTION GAP -- the true sign is carried by COHERENT CANCELLATION OVER THE CONFIGURATION ENSEMBLE; no dominance-configuration model at any k-swap resolution sees it (a 1-swap signed partition-sum resummation was tested pre-spec: the parity-preserving entropy dominates the bracket); the r257 minor scan performs exactly this resummation exactly -- the analytic counterpart is missing; must-fails loud (oracle mutant flagged, false exponent 47.6 dec, r255 anchors 8/18 exactly reproduced), Chebyshev toy flip-free 13/13.  THE ENDGAME STATE (rounds 258+259, carried to the campaign contract): both cores now have precisely named obstacles of the same construction -- FIBER: prove the terminal ratio h_{N-1}/F_{N-1}^2 > 7/5 (equivalently derive the true floor source-pure) on the cofinal ladder, THE LAST FIBER EDGE IS A POSITIVE TAU CROSS-RATIO (registered as PRIME.PORT.COUPLEDTAU.TERMINAL_CROSSRATIO.01 [O]); BASE/ORIENTATION: find the closed form of the coherent ensemble resummation (the determinant as a signed partition sum -- no saddle dominance, no k-swap truncation), THE LAST BASE EDGE IS A GLOBALLY ORIENTED PREFIX RESUMMATION (registered as PRIME.PORT.FULLSOURCE.PREFIX_RESUMMATION.01 [O]); in both cases the object is a COHERENT TOTALITY, not a dominant component -- the consistent explanation of why two years of single-component attacks (compression, constants, saddles, majorants, bands) all measurably failed.  Mincut base 4 / refined 5 UNCHANGED (a dictionary + adjudication set moves no edge); no other marker moves.  NOT evidence for or against the Riemann Hypothesis in either direction.  NO RH CLAIM.

PROVENANCE: discovery probes baseborder_factorial_probe.py (21/21,
EFFECTS_MIXED_COUPLEDTAU + INVERSION_IS_BASE_CONTAMINATION(f_neg=
0.9311) + EPST: CONTROL_FIBER_IS_BASE_CONTAMINATION +
SMOOTH_NULL_ANCHOR_OK + LEGS_BD_SKIPPED, SPEC_SHA
c7aa9f46889414c4, no post-freeze amendments), coupledtau_probe.py
(26/26 in the FIRST full pass, COUPLED_RECURSION_EXACT +
COCYCLE_LAW_FOUND + NO_EARLY_SEPARATION(0.84 dec) +
MICROFALSIFIER_PASSED(blind: coeff-field) +
NOPOLE_TREND(APPROACHING) + AUG_RAW_CROSSES_ONE +
AUG_UNIT_CROSSES_ONE, SPEC_SHA 73d8247f6de36a2b, two smoke
amendments disclosed, none after), budget_anatomy_probe.py (27/27,
TELESCOPE_EXACT(BY_CONSTRUCTION) + TERMINAL_Q_LAW(FLAT,
COVARIANT_RATIO) + TSTAR_IDENTIFIED + MAJORANT_OPEN +
PREFIX_DOMINANCE_ARTIFACT, SPEC_SHA 28026ae6b0750098, one
calibration amendment disclosed), parametrix_pass_probe.py (19/19,
PARAMETRIX_FAILED(i+ii+iii) + LEVEL_CROSSING_REFUTED +
SWAP_STAT_NOT_SEPARATING + SELECTION_EXTENSIVE_AFTER_ALL, SPEC_SHA
e79da4f43d63213a, one amendment disclosed), rounds 256/257/258/
259, notes DLXXXVII/DLXXXVIII/DLXXXIX/DXC, 2026-08-24; re-run
identically at promotion (21/21 + 26/26 + 27/27 + 19/19).
ROUND-31 EMBEDDING CONVENTION: frozen sources embedded BYTE-EXACT,
executed verbatim in isolated namespaces; printed SPEC SHAs pinned
and gated; byte-equality ward vs experiments/tfpt-discovery/ inside
the pattern gates.  The probes consume the READ-ONLY deployed core
v563_paper2_readouts.py and the frozen experiments-side libraries
bordered_hankel_probe.py (r244), offdiag_gram_probe.py (r254),
centered_basefiber_probe.py (r250), szego_equilibrium_probe.py
(r232a), principal_bessel_probe.py (r243), hirota_sign_probe.py
(r226) and port_integrable_kernel_probe.py (v881); the execution
order r257 before r258 keeps the budget probe's coupledtau import
on the embedded byte-exact source.  Rounds 260/261
(terminal_crossratio_probe.py, prefix_resummation_probe.py) were
in flight at this promotion cut and are NOT consumed.

FIREWALL: no zeros, no prime-table oracles (AST scans inside the
probes); RNG only in declared scramble controls; ground truth
(flips) enters gates only; NO RH claim.  Python-only per
GATE.WOLFRAM.02.
"""

import contextlib
import io
import os
import re
import sys
import time
import types
from fractions import Fraction as _Fr

_HERE = os.path.dirname(os.path.abspath(__file__))
if _HERE not in sys.path:
    sys.path.insert(0, _HERE)


# ---------- module-own exact section S0: the coupled-tau / terminal
# ---------- budget theorems (sympy symbolic + exact rationals)
def _coupledtau_terminal_theorems(gates):
    """Exact anchors: the coupled recursion and its bilinear tau
    corollary, the terminal reduction and consequence gate, the
    corner-ray normal form, and the positive-prefix firewall PSD
    theorem with its signed must-fail."""
    import sympy as sp

    def chk(name, ok, detail=""):
        gates.append(bool(ok))
        print("  [%s] %s%s" % ("PASS" if ok else "FAIL", name,
                               ("  -- " + detail) if detail else ""),
              flush=True)

    print("\n" + "-" * 74)
    print("MODULE-OWN EXACT SECTION S0: the coupled-tau / terminal "
          "budget theorems")
    print("-" * 74, flush=True)

    # --- S0.1 the coupled recursion implies the Riccati drain
    c, F, h, tau, taug = sp.symbols("c F h tau taug", positive=False)
    a_n = c ** 2 * h
    b_n = -(c * F) ** 2
    tau1 = a_n * tau
    taug1 = a_n * taug + b_n * tau
    drain = sp.simplify(taug1 / tau1 - (taug / tau - F ** 2 / h))
    ok1 = (drain == 0) and sp.simplify(b_n + (c * F) ** 2) == 0
    chk("S0.1-coupled-recursion-riccati", ok1,
        "tau_{n+1} = a_n tau_n, tau^aug_{n+1} = a_n tau^aug_n + "
        "b_n tau_n with a_n = c_n^2 h_n, b_n = -(c_n F_n)^2 "
        "implies D_{n+1} = D_n - F_n^2/h_n identically (sympy); "
        "b_n is a manifest negative square -- source-sign-pure in "
        "every world")

    # --- S0.2 the bilinear tau form (the canonical integrable
    #     corollary), symbolic AND on a frozen exact-rational chain
    bilinear = sp.simplify(taug * tau1 - taug1 * tau
                           - (c * F) ** 2 * tau ** 2)
    ok2s = (bilinear == 0)
    # frozen rational chain (5 steps): c_n, h_n, F_n and budget B
    cs = [_Fr(2, 3), _Fr(3, 5), _Fr(7, 4), _Fr(1, 2), _Fr(5, 6)]
    hs = [_Fr(4, 7), _Fr(9, 5), _Fr(2, 3), _Fr(11, 8), _Fr(3, 2)]
    Fs = [_Fr(1, 3), _Fr(-2, 5), _Fr(5, 7), _Fr(-1, 4), _Fr(2, 9)]
    B = _Fr(31, 6)
    tau_n = hs[0]
    taug_n = hs[0] * B - Fs[0] ** 2
    ok2r = True
    rho_sum = Fs[0] ** 2 / hs[0]
    for n in range(1, 5):
        an = cs[n] ** 2 * hs[n]
        bn = -(cs[n] * Fs[n]) ** 2
        tau_np, taug_np = an * tau_n, an * taug_n + bn * tau_n
        ok2r = ok2r and (taug_n * tau_np - taug_np * tau_n
                         == (cs[n] * Fs[n]) ** 2 * tau_n ** 2)
        ok2r = ok2r and (taug_np / tau_np
                         == taug_n / tau_n - Fs[n] ** 2 / hs[n])
        rho_sum += Fs[n] ** 2 / hs[n]
        tau_n, taug_n = tau_np, taug_np
    ok2r = ok2r and (taug_n / tau_n == B - rho_sum)   # telescoped
    chk("S0.2-bilinear-tau-form-exact", ok2s and ok2r,
        "tau^aug_n tau_{n+1} - tau^aug_{n+1} tau_n = (c_n F_n)^2 "
        "tau_n^2 EXACT (sympy identity + every step of the frozen "
        "5-step rational chain), and the chain telescopes to D_N = "
        "B - Sum rho_n exactly -- the drain increment is a positive "
        "tau cross-ratio: the r257 recursion and the bilinear "
        "Hirota-type form are ONE statement")

    # --- S0.3 the terminal reduction + the consequence gate
    S2, rhoN, t = sp.symbols("S2 rhoN t")
    Bdef = S2 + sp.Rational(5, 7)                     # r243 a4 def
    DN = Bdef - (S2 + rhoN)               # B - S_{N-1}, S_{N-1} =
    ok3s = sp.simplify(                   # S_{N-2} + rho_{N-1}
        DN - (sp.Rational(5, 7) - rhoN)) == 0
    qN = rhoN / sp.Rational(5, 7)
    ok3g = sp.simplify(DN - sp.Rational(5, 7) * (1 - qN)) == 0
    # exact rationals, both truth values
    ok3r = True
    for rho_v, positive in ((_Fr(2, 7), True), (_Fr(6, 7), False)):
        margin = _Fr(5, 7) - rho_v
        q_v = rho_v / _Fr(5, 7)
        ok3r = ok3r and ((margin > 0) == positive == (q_v < 1))
    chk("S0.3-terminal-consequence-gate", ok3s and ok3g and ok3r,
        "with B = S_{N-2} + 5/7 (by construction, r243 a4): D_N = "
        "5/7 - rho_{N-1} and margin > 0 iff q_N = rho_{N-1}/(5/7) "
        "< 1 (symbolic identity + exact rationals in both truth "
        "values) -- the entire fiber positivity is ONE terminal "
        "inequality; the 5/7 itself stays typed FLOOR_IMPORTED "
        "(inverted r241 floor of the measured min h_{N-1}/F_{N-1}^2 "
        "= 1.4278), its source-pure derivation OPEN")

    # --- S0.4 the corner-ray / t* normal form
    Dt = (S2 + t * sp.Rational(5, 7)) - (S2 + rhoN)
    slope = sp.diff(Dt, t)
    root = sp.solve(sp.Eq(Dt, 0), t)[0]
    ok4 = (sp.simplify(slope - sp.Rational(5, 7)) == 0
           and sp.simplify(root - qN) == 0
           and sp.simplify(sp.diff(Dt, t, 2)) == 0)
    chk("S0.4-corner-ray-tstar-affine", ok4,
        "the corner ray B(t) = S_{N-2} + t*(5/7) makes the terminal "
        "pivot D_N(t) affine in t with slope exactly 5/7 and root "
        "t* = q_N (sympy) -- the budget question IS a t* coordinate "
        "in the r238 normal form (r258: one normal form, two "
        "statistically unconnected data instances)")

    # --- S0.5 the positive-prefix firewall PSD theorem
    def hankel_minor_dets(nodes, weights, p_hi):
        moms = [sum(w * x ** k for x, w in zip(nodes, weights))
                for k in range(2 * p_hi)]
        dets = []
        for p in range(1, p_hi + 1):
            A = [[moms[i + j] for j in range(p)] for i in range(p)]
            dets.append(_det_frac(A))
        return dets

    def _det_frac(A):
        A = [row[:] for row in A]
        n = len(A)
        det = _Fr(1)
        for cidx in range(n):
            piv = None
            for r in range(cidx, n):
                if A[r][cidx] != 0:
                    piv = r
                    break
            if piv is None:
                return _Fr(0)
            if piv != cidx:
                A[cidx], A[piv] = A[piv], A[cidx]
                det = -det
            det *= A[cidx][cidx]
            inv = _Fr(1) / A[cidx][cidx]
            for r in range(cidx + 1, n):
                f = A[r][cidx] * inv
                if f:
                    A[r] = [x - f * y for x, y in zip(A[r], A[cidx])]
        return det

    def _solve_frac(G, rhs):
        n = len(rhs)
        M = [G[i][:] + [rhs[i]] for i in range(n)]
        for cidx in range(n):
            piv = next(r for r in range(cidx, n) if M[r][cidx] != 0)
            M[cidx], M[piv] = M[piv], M[cidx]
            inv = _Fr(1) / M[cidx][cidx]
            M[cidx] = [x * inv for x in M[cidx]]
            for r in range(n):
                if r != cidx and M[r][cidx]:
                    f = M[r][cidx]
                    M[r] = [x - f * y for x, y in zip(M[r], M[cidx])]
        return [M[i][n] for i in range(n)]

    # positive control: 5 positive rational atoms -> POSITIVE_PREFIX
    xsp = [_Fr(-4, 5), _Fr(-1, 3), _Fr(1, 6), _Fr(1, 2), _Fr(9, 10)]
    wsp = [_Fr(2, 5), _Fr(1, 2), _Fr(3, 7), _Fr(1, 3), _Fr(2, 7)]
    dets_pos = hankel_minor_dets(xsp, wsp, 5)
    hs_pos = [dets_pos[0]] + [dets_pos[i] / dets_pos[i - 1]
                              for i in range(1, 5)]
    ok5a = all(d > 0 for d in dets_pos) and all(h > 0 for h in hs_pos)
    # signed measure mu - nu: the h-chain flips inside the window ->
    # INDEFINITE_CONTINUATION with a well-defined maximal positive
    # prefix p_max (frozen witness, verified exactly at freeze time)
    xss = xsp + [_Fr(6, 5), _Fr(13, 10)]
    wss = wsp + [-_Fr(9, 100), -_Fr(4, 380)]
    dets_sgn = hankel_minor_dets(xss, wss, 7)
    hs_sgn = [dets_sgn[0]] + [dets_sgn[i] / dets_sgn[i - 1]
                              for i in range(1, 7)]
    p_max = 0
    for hval in hs_sgn:
        if hval > 0:
            p_max += 1
        else:
            break
    ok5b = (0 < p_max < 7)
    # the theorem: H_p PD (all leading minors > 0) iff the whole
    # h-prefix is positive, via det H_p = prod_{i<p} h_i exactly
    ok5c = True
    for p in range(1, 8):
        prod_h = _Fr(1)
        for i in range(p):
            prod_h *= hs_sgn[i]
        ok5c = ok5c and (dets_sgn[p - 1] == prod_h)
        pd = all(dets_sgn[i] > 0 for i in range(p))
        pref = all(hs_sgn[i] > 0 for i in range(p))
        ok5c = ok5c and (pd == pref == (p <= p_max))
    # must-fail: the explicit Schur-complement border v =
    # (-H_{p_max}^{-1} u, 1) reads EXACTLY h_{p_max} < 0 past p_max
    pbad = p_max + 1
    A = [[sum(w * x ** (i + j) for x, w in zip(xss, wss))
          for j in range(pbad)] for i in range(pbad)]
    u = [A[i][pbad - 1] for i in range(pbad - 1)]
    Ap = [row[:pbad - 1] for row in A[:pbad - 1]]
    y = _solve_frac(Ap, u)                # exact H_{p_max}^{-1} u
    v = [-yi for yi in y] + [_Fr(1)]
    qbad = sum(v[i] * A[i][j] * v[j]
               for i in range(pbad) for j in range(pbad))
    ok5d = (qbad == hs_sgn[p_max]) and (qbad < 0)
    chk("S0.5-positive-prefix-firewall", ok5a and ok5b and ok5c
        and ok5d,
        "exact Sylvester/Hankel chain: det H_p = prod_{i<p} h_i "
        "EXACT and H_p is PD iff the whole h-prefix is positive "
        "(p <= p_max = %d on the frozen signed witness); the "
        "positive control carries the full prefix (POSITIVE_PREFIX)"
        " while the signed mu - nu witness types "
        "INDEFINITE_CONTINUATION past p_max -- the r256 reviewer "
        "PSD core statement as exact algebra, must-fail firing"
        % p_max)


# --------------------------------------------------------------- sources
_SRC_0 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""baseborder_factorial_probe -- PRIME.PORT.FIBER.BASEBORDER.
FACTORIAL.01 (round 256): the CAUSAL base/border separation of the
two-stage fiber coupling T = <sigma0, G_N[mutilde] sigma0> (base
source -> kernel -> border source) BEFORE any further compression
search.  r254 measured the 2x2 MAIN x SCRAMBLE cross table on the
union grid WITHOUT a positivity firewall: T_MM +4.3343, T_MS
+9.9756, T_SM -0.9276, T_SS -4.4941, i.e. Delta_base +5.26,
Delta_border -5.64, Delta_int -9.21 (identity T_MM - T_SS =
Delta_base + Delta_border - Delta_int = 8.83 exact).  THE REVIEWER
CORE THEOREM (load-bearing for every fiber claim): while the base
is positive (h_k > 0 for 8 <= k < n) the kernel G_n = K_n - K_8 =
sum_{k=8}^{n-1} pihat_k(x) pihat_k(y) / h_k is PSD, hence T >= 0
for EVERY real border measure -- a negative T can ONLY arise from
kernel change, base indefiniteness, or mixed interaction, NEVER
from pure border permutation under a fixed positive kernel.  THIS
round (i) types every cell by that firewall, (ii) re-runs the
factorial on the COMMON POSITIVE PREFIX n* (where no kernel is
indefinite and the three effects are causally clean), (iii)
adjudicates sealed dominance verdicts, and (iv) re-adjudicates the
r254 headline (SCRAMBLE spectrally compact, K80_own = 2) as
possible BASE CONTAMINATION by the negative h-modes.

EXPLORATION ONLY (2026-08-24).  experiments/ level: NO promotion,
NO ledger row, NO marker moved, NO RH CLAIM in either direction.

INDEX FIREWALL (binding, r238-r254 discipline): w = window (kz),
N_w = builder depth, n/k = chain degree; free pivots h_{w,k}
(k < N_w) are the proof objects and legitimate KERNEL inputs; the
forced pivot h_N is NEVER formed -- the phat recursion (imported
VERBATIM from r254 OG.phat_matrix) consumes alh_k (k <= N-2) and
gam_{k+1} = rows[k]["gam_next"] (k <= N-2) ONLY.  sigma0 = sigma -
(F_0/h_0) mutilde (r248).  Ground truth (T_true = St - S_7, flip
degrees, partial sums S_{n-1} - S_7) enters GATES only.  No
zero/prime oracles anywhere (AST firewall).  MACHINERY IMPORTED
VERBATIM: r244 BH.wpack (rho/S/chain bitwise), r254
OG.world_build + OG.phat_matrix + OG.eig_block + OG.profile_stats
+ the r254-a1 SORTED-UNION embedding convention (adopted, not
re-derived: its admission gate -- border bitwise identical, every
world's window positions bitwise found in the union -- failed
LOUDLY on the raw concat order in r254 and is re-gated here),
r243 PB.smooth_comb, v881 PIK.lambda_eps controls.

LEG 0 -- POSITIVE-PREFIX FIREWALL (mandatory before everything):
per base world mu in {MAIN, SCRAMBLE, EPSTEIN, SMOOTH} the maximal
positive prefix degree pmax(mu) = first k in [8, N) with h_k < 0
(else N); T_n[mu, sigma] is typed POSITIVE_PREFIX iff n <=
pmax(mu) (all h_k > 0 for 8 <= k < n => G_n PSD => genuine
Hilbert-space interpretation, independent fiber falsifier) else
INDEFINITE_CONTINUATION (algebraically legitimate as a
tau-quotient object, NOT an independent fiber falsifier).  PSD
verification gate per world: lambda_min(G_pmax) on the own grid
>= -1e-10 x max(lambda_max, 1).

LEG A -- THE EXACT 2x2 WORLD CENSUS (MAIN x C for C in SCRAMBLE,
EPSTEIN, SMOOTH; base world fixes chain + kernel, border world
fixes sigma0; r254-a1 union embedding): cells T[W, sW'] = s_{W'}^T
G_W s_{W'}; effects Delta_base = T_MM - T_CM, Delta_border = T_MM
- T_MC, Delta_int = T_MM - T_MC - T_CM + T_CC; identity ward
Delta_base + Delta_border - Delta_int = T_MM - T_CC (rel 1e-12 of
the cell scale; it guards the EFFECT FORMULAS, and its must-fail
is a wrong-formula test, disclosed in leg E).  r254 PRIOR
verification (rel 2e-3): SCR cells +4.3343/+9.9756/-0.9276/
-4.4941; EPST cells T[M,sE] +12.3502, T[E,sM] -0.8561, T_EE
+0.7615.  FIREWALL-CLEANED RASTER: all four cells rebuilt with
BOTH kernels truncated at the common positive prefix n* =
min(pmax(M), pmax(C)) -- only there is the decomposition causally
clean (no kernel indefinite; every cell must be >= -1e-9 x gross).
Chain wards: diagonal cells at n* vs the bitwise partial sums
S_{n*-1} - S_7 (rel 1e-9 MAIN / 1e-4 controls / abs on SMOOTH).

SEALED ADJUDICATION (frozen BEFORE evaluation; MAIN x SCRAMBLE):
dominance factor DOM = 3; basis = the CLEANED raster (the causal
one); the raw full-depth Delta_border (MAIN kernel PSD at full
depth, hence also clean) enters the LOAD_BEARING rule as a second
mandatory condition.  Priority order:
  (1) BASE_KERNEL_ROTATION_DOMINATES  iff |Db*| >= 3 max(|Dbo*|,
      |Di*|)   => base and fiber not separable, vote COUPLEDTAU;
  (2) MIXED_INTERACTION_DOMINATES     iff |Di*| >= 3 max(|Db*|,
      |Dbo*|)  => the arithmetic lives in the nonlinear
      compatibility, vote tau^aug/tau as one indivisible
      full-source object;
  (3) BORDER_PAIRING_LOAD_BEARING     iff sign(Dbo) == sign(Gap)
      AND |Dbo|/|Gap| in [0.3, 3.0] on BOTH the raw full-depth
      MAIN-kernel border effect AND the cleaned-prefix border
      effect -- the sealed answer to the r254 prior (-5.64 vs Gap
      +8.83): a border move that OVERSHOOTS WITH THE WRONG SIGN
      does NOT count as load-bearing; only this verdict unlocks
      legs B-D;
  (4) EFFECTS_MIXED_COUPLEDTAU        (residual; also fired with
      note CLEANED_GAP_NULL if |Gap*| <= 1e-9 x gross).
CONTROL ADJUDICATION (EPSTEIN): CONTROL_FIBER_IS_BASE_
CONTAMINATION iff |Gap*| <= 0.2 x |Gap_raw| (the anomaly is
carried >= 80 percent by the indefinite continuation degrees) OR
|Dbo*| <= 0.1 x max(|Gap*|, 1e-12) (the border move contributes
nothing once both kernels are positive: the anomaly follows the
base choice entirely) -- then the EPSTEIN fiber anomaly may no
longer be cited as a fiber falsifier; else EPSTEIN_ANOMALY_
SURVIVES_PREFIX.  SMOOTH is the sealed NULL ANCHOR (sigma0 == 0):
its border cells must vanish (|T| <= 1e-9 x gross), its raster is
printed INFO, not adjudicated.

LEG A2 -- INVERSION ADJUDICATION (is the r254 SCRAMBLE compactness
K80_own = 2 carried by the NEGATIVE h-modes?): on the SCRAMBLE own
grid split G_SCR = G_pos + G_neg by the sign of h_k (mode split,
exact: |T_pos + T_neg - T_SS| <= 1e-9 x gross; T_pos >= -1e-9 x
gross by PSD of the positive part); reproduce K80_own(SCR) = 2
(r254 prior, |c|-sorted, tol 0.2); for the top-2 |c|-eigenpairs of
G_SCR measure f_neg = ||Q_neg^T v||^2 with Q_neg an orthonormal
basis (SVD, 1e-10 rel cut) of span{phat_k rows, h_k < 0} in atom
space.  SEALED: INVERSION_IS_BASE_CONTAMINATION iff mean f_neg
(top-2) >= 0.8 (the r254 headline 'surgery concentrates the form
onto ~2 eigendirections' is then a statement about the indefinite
base modes, not about a border discriminator -- downgraded);
INVERSION_GENUINE_FIND iff <= 0.2; else INVERSION_MIXED.

LEGS B-D (CONDITIONAL: run iff BORDER_PAIRING_LOAD_BEARING fires
by the sealed rule; else explicitly SKIPPED, their gates then do
not count) -- on the FIXED positive full-depth MAIN kernel, border
route s_b (r248 centering invariance, re-gated):
(B) EXCHANGE SWEEP over all admissible ADJACENT swaps (consecutive
  pairs of the position-sorted border block, d = s_i - s_j != 0):
  Delta T from the exact exchange formula (leg E gates its
  exactness unconditionally); EXCHANGE_MONOTONE_GO iff >= 0.99 of
  the nonzero Delta T share one sign (rearrangement/total-
  positivity characterization of the true pairing as an extremal
  assignment becomes reachable); EXCHANGE_SIGN_MIXED else (with
  the fraction printed).
(C) MONGE/TP TEST: four-point defects M_{i,i+1;k,k+1} = G_ik +
  G_jl - G_il - G_jk on the position-sorted border nodes, all
  ordered adjacent quadruples i < k: dominant-sign fraction >=
  0.99 => MONGE_TP_ORDER (theorematic closure of the exchange
  formula); < 0.90 => NO_EXCHANGE_ORDER (ends the class); else
  WEAK_ORDER.
(D) SOURCE-PURE SPECTRAL COMPRESSION: eigendirections of G_MAIN
  ordered by |lambda| DESCENDING (defined BEFORE any border
  readout -- no subspace choice after seeing sigma or the gap);
  K90/K99/K99.9 = first K with |cum c / T - 1| <= 0.1/0.01/0.001;
  FIXED_SPECTRAL_CARRIER iff K90 <= 10; LOG_SPECTRAL_CARRIER iff
  K90 <= 4 ln(N - 8); else EXTENSIVE_SPECTRAL_CARRIER.
DIAGNOSTIC (not proof-registered, appendix only): dyadic band
|C|-profiles in |u_i - u_j| for MAIN and SCRAMBLE (r254
band_stats, INFO lines only).

LEG E -- FALSIFIERS + MUST-FAILS (each loud, chain-predicted):
(e0) EXCHANGE FORMULA EXACT (unconditional, MAIN border route):
  T(sigma') - T(sigma) = 2 d [(G sigma)_j - (G sigma)_i] + d^2
  (G_ii + G_jj - 2 G_ij), d = sigma_i - sigma_j, verified against
  the direct re-evaluation on 64 evenly sampled adjacent swaps
  (bar 1e-10 x gross);
(mA) FIREWALL OMITTED (the explicit alias test): without leg 0
  the T_SM < 0 cell would be labeled a border effect; the alias
  dies because (i) lambda_min(G_SCR full) < 0 loudly (>= 1e3 x
  1e-13 x max(lambda_max, 1)), (ii) the positive-mode part obeys
  the PSD theorem s_M^T G_SCR_pos s_M >= -1e-9 x gross, (iii) the
  ENTIRE negativity sits in the h_k < 0 modes (T_SM_neg < 0,
  loud, mode split exact to 1e-9 x gross) -- kernel property, not
  border property;
(mW) EFFECT FORMULA BROKEN: Delta_int computed with the flipped
  CC sign must break the identity ward by exactly 2 |T_CC| (rel
  1e-9, loudness 1e3 x max(honest ward, 1e-13) x scale);
(mX) EXCHANGE FORMULA WRONG CROSS TERM (+2 G_ij instead of
  -2 G_ij) on the adjacent swap maximizing |4 d^2 G_ij|: must
  deviate from the direct route by >= 1e3 x max(honest worst
  deviation, 1e-13 x gross).

SEALED CONSTANTS: window w9; controls on w9: EPSTEIN, SCRAMBLE
(seed 1), SMOOTH (r254 definitions verbatim); flips re-derived
25/21/27; FIB_LO 8; chain wards 1e-9 MAIN / 1e-4 controls, SMOOTH
abs 1e-9 x gross; border route 1e-9 / 1e-4; sym 1e-12; PSD eig
bar 1e-10 rel; cell PSD floor 1e-9 x gross; embedding ward 1e-9
(SMOOTH CC abs); prior tol 2e-3 rel; identity ward 1e-12 rel
scale; DOM 3.0; LB band [0.3, 3.0] + sign; contamination bars
0.2 / 0.1; inversion bars 0.8 / 0.2, K80 tol 0.2, prior K80(SCR)
= 2; exchange bar 1e-10 x gross, 64 samples; monotone bars
0.99 / --; TP bars 0.99 / 0.90; carrier bars K90 <= 10 / <= 4 ln R;
must-fail rel 0.05 (unused numerics kept for style), loudness
1e3 x 1e-13; runtime <= 1800 s; smoke = w9 MAIN only (census,
leg-0 typing + PSD, exchange exactness, mW on a synthetic 2x2,
mX; rasters, controls, A2, alias skipped).

SEALED VERDICT FORM (frozen BEFORE evaluation):
  <BASE_KERNEL_ROTATION_DOMINATES | MIXED_INTERACTION_DOMINATES |
   BORDER_PAIRING_LOAD_BEARING | EFFECTS_MIXED_COUPLEDTAU>
+ A2: INVERSION_<IS_BASE_CONTAMINATION|GENUINE_FIND|MIXED>(f_neg)
+ EPST: <CONTROL_FIBER_IS_BASE_CONTAMINATION |
         EPSTEIN_ANOMALY_SURVIVES_PREFIX>
+ SMOOTH_NULL_ANCHOR_<OK|BROKEN>
+ <LEGS_BD_SKIPPED(reason) | LEGS_BD(exchange, monge, carrier)>.
Honesty before beauty: the verdict never converts an INDEFINITE_
CONTINUATION cell into a fiber falsifier; the budget bound and
the base law stay OPEN (r243/r247/r250/r251/r253/r254 stand).

RECORD TABLES (frozen from calibration pass 1, 21/21 gates, wall
0.6 s full / 0.1 s smoke; AMENDMENTS: NONE -- no bar and no
verdict rule moved after the seal):
CAL_VERDICT = EFFECTS_MIXED_COUPLEDTAU +
A2: INVERSION_IS_BASE_CONTAMINATION(f_neg=0.9311) +
EPST: CONTROL_FIBER_IS_BASE_CONTAMINATION +
SMOOTH_NULL_ANCHOR_OK + LEGS_BD_SKIPPED.
Key numbers.  CENSUS w9: N = 184, A = 734 (border 367) on all
four worlds; T_true MAIN +4.3343 / SCR -4.4942 / EPST +0.7615;
chain wards 7.5e-15 / 7.1e-6 / 4.7e-8 (f64 control floor),
border route 9.1e-15 / 6.8e-6, SMOOTH |T|/gross 4.6e-19; flips
re-derived 25/21/27.  LEG 0 TYPE TABLE (world -> pmax, neg
modes in [8, N)): MAIN 184 (0 neg, POSITIVE_PREFIX at full
depth), SCR 21 (37 neg), EPST 25 (55 neg), SMOOTH 27 (4 neg)
-- all controls INDEFINITE_CONTINUATION at full depth; every
own-grid prefix kernel PSD (worst -lambda_min rel 5.7e-16, bar
1e-10): the reviewer core theorem holds numerically.  LEG A
(|U| = 367 on all pairs, embedding wards worst 9.8e-15,
identity wards EXACTLY 0, cleaned chain wards 1.1e-11 MAIN /
2.1e-12 controls): SCR RAW +4.33432/+9.97557/-0.92761/-4.49413
(r254 priors hit, worst rel 4.9e-5) => Db +5.26193, Dbo
-5.64125, Di -9.20777, Gap +8.82844; SCR CLEANED (n* = 21, 13
modes, both kernels PSD): T_MM* +1.81873e-5, T_MS* +0.175915,
T_SM* +1.97101e-5, T_SS* +0.216069 => Db* -1.5228e-6, Dbo*
-0.175897, Di* +0.0401526, Gap* -0.216051.  THE CLEANED PICTURE
INVERTS THE PRIOR READING TWICE: (i) on the causally clean
prefix the BASE rotation is NULL (|Db*| = 1.5e-6: scrambling
the chain does not move the prefix fiber form at the MAIN
border) and the BORDER move carries the prefix gap (|Dbo*|/
|Gap*| = 0.814, sign consistent -- SCRAMBLE's border has MORE
prefix mass than MAIN's, Gap* < 0); (ii) but the RAW full-depth
border effect has the WRONG sign vs its gap (-5.64 vs +8.83),
so the sealed LOAD_BEARING rule (band + sign on raw AND
cleaned) does NOT fire, and neither |Db*| nor |Di*| reaches
factor-3 dominance => EFFECTS_MIXED_COUPLEDTAU by the sealed
priority; the tension (border dominant on the prefix, sign-
inconsistent at full depth) is printed, not upgraded.  EPST RAW
+4.33432/+12.35022/-0.85614/+0.76154 (priors hit) => Gap_raw
+3.57278; EPST CLEANED (n* = 25, 17 modes): T_MM* = T_ME* =
+2.81736e-5 (Dbo* = 1.3e-16: the EPSTEIN border is fiber-
IDENTICAL to MAIN on the common prefix -- head-identical
construction confirmed at the raster level), T_EM* = T_EE* =
+9.95937e-5, Gap* = -7.142e-5 = 2.0e-5 x |Gap_raw| <= 0.2
(crit1) AND crit2 => CONTROL_FIBER_IS_BASE_CONTAMINATION: the
r253/r254 EPSTEIN fiber anomaly lives ENTIRELY in the
indefinite continuation degrees k >= 25 and may no longer be
cited as an independent fiber falsifier.  SMOOTH raster
(n* = 27): border cells raw 7.1e-19 / cleaned 7.3e-20 x gross,
T[SMOOTH, sM] raw +1.22821 typed INDEFINITE_CONTINUATION =>
SMOOTH_NULL_ANCHOR_OK.  LEG A2: h-sign mode split of G_SCR (37
neg / 139 pos modes) exact to 1.5e-15 x gross: T_pos +3292.5670
(>= 0, PSD obeyed) + T_neg -3297.0611 = T_SS -4.4941 -- the two
mode classes cancel to 0.14 percent of their size, the net sign
is carried by the negative class (734x overshoot, printed);
K80_own(SCR) = 2 reproduced (r254 prior); top-2 |c|-eigenpairs
lambda -16305.1 / +2464418.6, c/T shares 1.418 / -0.350, f_neg
0.9376 / 0.9245 => mean 0.9311 >= 0.8 =>
INVERSION_IS_BASE_CONTAMINATION: the r254 'SCRAMBLE spectrally
compact K80 = 2' headline is a statement about the NEGATIVE
h-modes of the broken base (93 percent of the carrying
eigendirections live in the h<0 span), not a border
discriminator -- DOWNGRADED.  LEGS B-D: SKIPPED by the sealed
conditional (LB rule did not fire); band appendix printed
(MAIN flat 0.163..0.077, SCR mid-band shifted 0.155/0.218/
0.121 -- r254 reproduced as INFO).  LEG E: e0 exchange formula
vs direct on 64 sampled adjacent border swaps worst dev 1.2e-15
(gross 101, bar 1e-10 x gross); mA alias killed:
lambda_min(G_SCR full) = -2.948e+6 (1.0e+12 x floor), T_SM
-0.9276 = pos +204.6998 (>= -floor, PSD obeyed) + neg -205.6274
(2.0e+13 x floor), split exact 3.2e-15 x gross -- the T_SM
negativity is 100 percent an h<0-mode (KERNEL) property, never
a border effect; mW flipped-CC formula breaks the ward by
8.98825 = 2|T_CC| exactly (rel 0, 9.0e+9 x floor); mX wrong
cross term deviates 0.282 = 2.8e+10 x the honest floor.
READING (typed, no upgrade): the r254 factorial numbers were
correct but their causal reading was contaminated -- Delta_base
+5.26 and Delta_int -9.21 are INDEFINITE-KERNEL bookkeeping,
not causal effects; on the only causally clean surface (the
common positive prefix) the base rotation does nothing, the
border move is the sole carrier of a small sign-flipped gap,
and both control 'discoveries' (SCRAMBLE spectral compactness,
EPSTEIN fiber anomaly) are base contamination by negative
h-modes.  Consequence vote: COUPLEDTAU -- the MAIN-vs-SCRAMBLE
world gap at full depth is NOT separable into base and border
channels by any rule sealed this round; no exchange/Monge/
spectral pairing theorem is unlocked; tau^aug/tau stays one
indivisible full-source object.  Runtime 0.6 s full / 0.1 s
smoke; run1/run2 identical up to WALL.  AMENDMENTS AFTER
FREEZE: NONE.

NO RH CLAIM IN EITHER DIRECTION.  NOT evidence for or against RH.
"""

from __future__ import annotations

import argparse
import ast
import hashlib
import math
import os
import sys
import time

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
if HERE not in sys.path:
    sys.path.insert(0, HERE)

import bordered_hankel_probe as BH           # noqa: E402 r244
import offdiag_gram_probe as OG              # noqa: E402 r254
import port_integrable_kernel_probe as PIK   # noqa: E402 v881
import principal_bessel_probe as PB          # noqa: E402 r243
import v563_paper2_readouts as core          # noqa: E402 READ-ONLY

FIB_LO = 8
assert FIB_LO == OG.FIB_LO
KZ = 9
T_MAIN_BAR = 1e-9
T_CTRL_BAR = 1e-4
BORD_MAIN_BAR = 1e-9
BORD_CTRL_BAR = 1e-4
SYM_BAR = 1e-12
SM_GUARD = 1e-9
PSD_EIG_BAR = 1e-10
CELL_PSD_FLOOR = 1e-9
EMB_BAR = 1e-9
PRIOR_TOL = 2e-3
WARD_ID_BAR = 1e-12
CHAIN_CLN_MAIN = 1e-9
CHAIN_CLN_CTRL = 1e-4
DOM_FACTOR = 3.0
LB_LO, LB_HI = 0.3, 3.0
CONTAM_GAP_BAR = 0.2
CONTAM_BORD_BAR = 0.1
INV_HI, INV_LO = 0.8, 0.2
K80_TOL = 0.2
PRIOR_K80_SCR = 2
NEG_RANK_CUT = 1e-10
EXG_BAR = 1e-10
EXG_SAMPLES = 64
MONO_GO = 0.99
TP_GO = 0.99
TP_NO = 0.90
K90_FIXED = 10
MF_LOUD = 1e3
MF_NOISE = 1e-13
CTRL_FLIPS = {"EPSTEIN": 25, "SCRAMBLE": 21, "SMOOTH": 27}
PRIOR_SCR = {"MM": 4.3343, "MC": 9.9756, "CM": -0.9276,
             "CC": -4.4941}
PRIOR_EPST = {"MC": 12.3502, "CM": -0.8561, "CC": 0.7615}
CAL_VERDICT = (
    "EFFECTS_MIXED_COUPLEDTAU + "
    "A2: INVERSION_IS_BASE_CONTAMINATION(f_neg=0.9311) + "
    "EPST: CONTROL_FIBER_IS_BASE_CONTAMINATION + "
    "SMOOTH_NULL_ANCHOR_OK + LEGS_BD_SKIPPED")

SPEC_SHA = hashlib.sha256(__doc__.encode("utf-8")).hexdigest()
T0_WALL = time.time()
CHECKS: list = []


def check(name, ok, detail):
    ok = bool(ok)
    CHECKS.append((name, ok, detail))
    print("  [%s] %-42s %s" % ("PASS" if ok else "FAIL", name, detail),
          flush=True)
    return ok


def info(msg):
    print("  [INFO] " + msg, flush=True)


def section(t):
    print("\n" + "-" * 78 + "\n" + t + "\n" + "-" * 78, flush=True)


def firewall_audit():
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    forb = {"zeta" + "zero", "n" + "zeros", "prime" + "range",
            "is" + "prime", "gram" + "point"}
    bad = []
    for node in ast.walk(tree):
        nm = node.attr if isinstance(node, ast.Attribute) else (
            node.id if isinstance(node, ast.Name) else None)
        if nm and nm.lower() in forb:
            bad.append("%s@%d" % (nm, node.lineno))
    return (not bad), ("NO zero/prime oracles; kernels consume the "
                       "FREE chain (alh_k, gam_{k+1}, sign h_k, "
                       "k <= N-2) + atom positions/weights ONLY; "
                       "ground truth (T_true, flips, partial sums) "
                       "enters gates only"
                       if not bad else "; ".join(bad))


def pmax_of(p):
    """maximal positive prefix degree: first k in [FIB_LO, N) with
    h_k < 0, else N (leg-0 firewall coordinate)."""
    for k in range(FIB_LO, p["N"]):
        if p["rows"][k]["sg_h"] < 0.0:
            return k
    return p["N"]


def cell_type(pmax, depth):
    return ("POSITIVE_PREFIX" if depth <= pmax
            else "INDEFINITE_CONTINUATION")


def prefix_kernel_minmax(W, depth):
    P, sg = W["P"], W["sgv"]
    Gp = (P[FIB_LO:depth].T * sg[FIB_LO:depth]) @ P[FIB_LO:depth]
    ev = np.linalg.eigvalsh(Gp)
    return float(ev[0]), float(ev[-1])


def union_raster(Wm, Wc, nstar, want_alias=False):
    """r254-a1 sorted-union embedding (adopted, re-gated): the four
    factorial cells at full depth AND at the common positive prefix
    n*, with kernel eigenvalue extremes; optional h-sign mode split
    of the C kernel at full depth against the M border (alias)."""
    U = np.unique(np.concatenate([Wm["wx"], Wc["wx"]]))
    im = np.searchsorted(U, Wm["wx"])
    ic = np.searchsorted(U, Wc["wx"])
    ok_pos = (np.array_equal(Wm["bx"], Wc["bx"])
              and bool(np.all(U[im] == Wm["wx"]))
              and bool(np.all(U[ic] == Wc["wx"])))
    posU = np.concatenate([Wm["bx"], U])
    nbU = len(Wm["bx"])

    def s_emb(W, idx):
        sv = np.zeros(len(posU))
        sv[:nbU] = W["bw"]
        np.add.at(sv, nbU + idx, -W["c0"] * W["wu"])
        return sv

    sM, sC = s_emb(Wm, im), s_emb(Wc, ic)
    PM = OG.phat_matrix(Wm["p"]["rows"], posU, Wm["N"])
    PC = OG.phat_matrix(Wc["p"]["rows"], posU, Wc["N"])
    sgM, sgC = Wm["sgv"], Wc["sgv"]

    def kern(P, sg, dep):
        return (P[FIB_LO:dep].T * sg[FIB_LO:dep]) @ P[FIB_LO:dep]

    out = dict(ok_pos=ok_pos, nU=len(U), nstar=nstar)
    for lab, dm, dc in (("raw", Wm["N"], Wc["N"]),
                        ("cln", nstar, nstar)):
        GM = kern(PM, sgM, dm)
        GC = kern(PC, sgC, dc)
        cells = dict(MM=float(sM @ (GM @ sM)),
                     MC=float(sC @ (GM @ sC)),
                     CM=float(sM @ (GC @ sM)),
                     CC=float(sC @ (GC @ sC)))
        evM = np.linalg.eigvalsh(GM)
        evC = np.linalg.eigvalsh(GC)
        if lab == "raw":
            out["grossU"] = float(np.abs(sM) @ (np.abs(GM)
                                                @ np.abs(sM)))
        out[lab] = dict(cells=cells,
                        lmM=float(evM[0]), lxM=float(evM[-1]),
                        lmC=float(evC[0]), lxC=float(evC[-1]))
        del GM, GC
    if want_alias:
        sgt = sgC[FIB_LO:Wc["N"]]
        neg = np.nonzero(sgt < 0.0)[0] + FIB_LO
        pos = np.nonzero(sgt > 0.0)[0] + FIB_LO
        Gn = (PC[neg].T * sgC[neg]) @ PC[neg]
        Gp = (PC[pos].T * sgC[pos]) @ PC[pos]
        out["alias"] = dict(T_SM_neg=float(sM @ (Gn @ sM)),
                            T_SM_pos=float(sM @ (Gp @ sM)),
                            nneg=len(neg))
        del Gn, Gp
    return out


def effects(cells):
    Db = cells["MM"] - cells["CM"]
    Dbo = cells["MM"] - cells["MC"]
    Di = cells["MM"] - cells["MC"] - cells["CM"] + cells["CC"]
    gap = cells["MM"] - cells["CC"]
    scale = max(abs(v) for v in cells.values())
    ward = abs((Db + Dbo - Di) - gap) / max(scale, 1e-300)
    return dict(Db=Db, Dbo=Dbo, Di=Di, gap=gap, ward=ward,
                scale=scale)


def lb_ok(e):
    if e["Dbo"] * e["gap"] <= 0.0:
        return False
    r = abs(e["Dbo"]) / max(abs(e["gap"]), 1e-300)
    return LB_LO <= r <= LB_HI


def adjudicate(e_cln, e_raw, grossU):
    if abs(e_cln["gap"]) <= 1e-9 * grossU:
        return ("EFFECTS_MIXED_COUPLEDTAU(CLEANED_GAP_NULL)",
                "cleaned gap below floor -- no causal split")
    ab, abo, ai = (abs(e_cln["Db"]), abs(e_cln["Dbo"]),
                   abs(e_cln["Di"]))
    if ab >= DOM_FACTOR * max(abo, ai):
        return ("BASE_KERNEL_ROTATION_DOMINATES",
                "|Db*| %.4g >= %g x max(|Dbo*| %.4g, |Di*| %.4g)"
                % (ab, DOM_FACTOR, abo, ai))
    if ai >= DOM_FACTOR * max(ab, abo):
        return ("MIXED_INTERACTION_DOMINATES",
                "|Di*| %.4g >= %g x max(|Db*| %.4g, |Dbo*| %.4g)"
                % (ai, DOM_FACTOR, ab, abo))
    if lb_ok(e_raw) and lb_ok(e_cln):
        return ("BORDER_PAIRING_LOAD_BEARING",
                "sign-consistent |Dbo|/|Gap| in [%.1f, %.1f] on "
                "raw AND cleaned" % (LB_LO, LB_HI))
    return ("EFFECTS_MIXED_COUPLEDTAU",
            "no factor-%g dominance; LB rule raw=%s cln=%s "
            "(sign/band sealed: overshoot with wrong sign does "
            "NOT count)" % (DOM_FACTOR, lb_ok(e_raw),
                            lb_ok(e_cln)))


def exchange_pieces(W):
    G, sb, nb = W["G"], W["s_b"], W["nb"]
    order = np.argsort(W["pos"][:nb], kind="stable")
    Gs = G @ sb
    T0 = float(sb @ Gs)
    return G, sb, order, Gs, T0


def dt_formula(G, Gs, s, i, j, wrong=False):
    d = s[i] - s[j]
    cross = 2.0 * G[i, j] if wrong else -2.0 * G[i, j]
    return 2.0 * d * (Gs[j] - Gs[i]) \
        + d * d * (G[i, i] + G[j, j] + cross)


def dt_direct(G, s, T0, i, j):
    sw = s.copy()
    sw[i], sw[j] = s[j], s[i]
    return float(sw @ (G @ sw)) - T0


# --------------------------------------------------------------- main
def main():
    par = argparse.ArgumentParser()
    par.add_argument("--smoke", action="store_true")
    args = par.parse_args()
    smoke = args.smoke

    print("=" * 78)
    print("baseborder_factorial_probe -- PRIME.PORT.FIBER."
          "BASEBORDER.FACTORIAL.01 (round 256)")
    print("SPEC_SHA %s   F_DEF_SHA %s (imported r243)"
          % (SPEC_SHA[:16], PB.F_DEF_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 MAIN only: census, leg-0, "
                        "exchange exactness, mW synthetic, mX; "
                        "rasters/controls/A2/alias skipped)"
                        if smoke else "FULL RECORD"))
    print("=" * 78)

    section("S0  FIREWALL + PREDEFINITION")
    okf, det = firewall_audit()
    check("G01-firewall", okf, det)
    check("G02-predefinition", True,
          "leg-0 typing POSITIVE_PREFIX iff depth <= pmax (first "
          "h-flip in [8, N)); PSD eig bar %.0e rel; cell PSD floor "
          "%.0e gross; r254-a1 union embedding adopted + re-gated "
          "(ward %.0e); priors rel %.0e; identity ward %.0e rel "
          "scale; ADJUDICATION SEALED: DOM %.1f on the CLEANED "
          "raster, LB band [%.1f, %.1f] + sign on raw AND cleaned "
          "(wrong-sign overshoot does NOT count), contamination "
          "bars %.1f/%.1f, inversion bars %.1f/%.1f (top-2 |c| "
          "eigenpairs vs h<0 mode span); legs B-D conditional on "
          "BORDER_PAIRING_LOAD_BEARING only; exchange bar %.0e "
          "gross, monotone %.2f, TP %.2f/%.2f, carrier K90 <= %d "
          "/ <= 4 ln R; must-fail loudness %.0e x %.0e"
          % (PSD_EIG_BAR, CELL_PSD_FLOOR, EMB_BAR, PRIOR_TOL,
             WARD_ID_BAR, DOM_FACTOR, LB_LO, LB_HI,
             CONTAM_GAP_BAR, CONTAM_BORD_BAR, INV_HI, INV_LO,
             EXG_BAR, MONO_GO, TP_GO, TP_NO, K90_FIXED,
             MF_LOUD, MF_NOISE))

    # ---------------- S1: census + worlds
    section("S1  CENSUS + WORLDS")
    packs = {"w9": BH.wpack(KZ)}
    ctrl = {}
    if not smoke:
        rr9c = core.build_window(KZ)
        N_E = int(math.floor(math.exp(2.0 * rr9c["alpha"]))) + 1
        lamE = PIK.lambda_eps(N_E)
        nn_idx = np.nonzero(np.abs(lamE) > 1e-12)[0]
        ug9, uw9 = PB.smooth_comb(rr9c["alpha"])
        ctrl_defs = (("EPSTEIN", dict(comb=(
            np.log(nn_idx.astype(float)),
            2.0 * lamE[nn_idx] / np.sqrt(nn_idx.astype(float))))),
            ("SCRAMBLE", dict(scramble_seed=1)),
            ("SMOOTH", dict(comb=(ug9, uw9))))
        ctrl = {c: BH.wpack(KZ, base_kw=kw) for c, kw in ctrl_defs}
    okC = packs["w9"]["nf"] is None
    okCf = all(ctrl[c]["nf"] == CTRL_FLIPS[c] for c in ctrl) \
        if ctrl else True
    Wd = {"w9": OG.world_build(packs["w9"], want_P=True)}
    if not smoke:
        Wd["SCR"] = OG.world_build(ctrl["SCRAMBLE"], want_P=True)
        Wd["EPST"] = OG.world_build(ctrl["EPSTEIN"], want_P=True)
        Wd["SMOOTH"] = OG.world_build(ctrl["SMOOTH"], want_P=True)
    t_main = t_ctrl = b_main = b_ctrl = sym_worst = 0.0
    sm_ratio = 0.0
    for tag, W in Wd.items():
        sym_worst = max(sym_worst, W["sym_dev"]
                        / max(float(np.max(np.abs(W["G"]))),
                              1e-300))
        if tag == "SMOOTH":
            sm_ratio = abs(W["T_mat"]) / max(W["gross"], 1e-300)
            info("%-6s N=%d A=%d  |T_mat|/gross %.1e (null "
                 "anchor part 1)" % (tag, W["N"], W["A"],
                                     sm_ratio))
            continue
        devT = abs(W["T_mat"] / W["T_true"] - 1.0)
        devB = abs(W["T_bord"] / W["T_mat"] - 1.0)
        if tag == "w9":
            t_main, b_main = devT, devB
        else:
            t_ctrl = max(t_ctrl, devT)
            b_ctrl = max(b_ctrl, devB)
        info("%-6s N=%d A=%d (border %d)  T_true %+.4f  chain dev "
             "%.1e  border-route dev %.1e"
             % (tag, W["N"], W["A"], W["nb"], W["T_true"], devT,
                devB))
    ok_sm = (sm_ratio <= SM_GUARD) if not smoke else True
    check("G10-census-worlds",
          okC and okCf and t_main <= T_MAIN_BAR
          and t_ctrl <= T_CTRL_BAR and b_main <= BORD_MAIN_BAR
          and b_ctrl <= BORD_CTRL_BAR and sym_worst <= SYM_BAR
          and ok_sm,
          "MAIN free prefix positive; control flips re-derived %s; "
          "chain wards MAIN %.1e (bar %.0e) / controls %.1e (bar "
          "%.0e); border route %.1e / %.1e; symmetry %.1e (bar "
          "%.0e); SMOOTH null part 1: |T|/gross %s (bar %.0e)"
          % (str({c: ctrl[c]["nf"] for c in ctrl}) if ctrl
             else "SMOKE-skipped", t_main, T_MAIN_BAR, t_ctrl,
             T_CTRL_BAR, b_main, b_ctrl, sym_worst, SYM_BAR,
             ("%.1e" % sm_ratio) if not smoke else "skipped",
             SM_GUARD))

    # ---------------- S2: LEG 0 -- positive-prefix firewall
    section("S2  LEG 0 -- POSITIVE-PREFIX FIREWALL")
    pmax = {}
    psd_worst = 0.0
    for tag, W in Wd.items():
        pm = pmax_of(W["p"])
        pmax[tag] = pm
        sgt = W["sgv"][FIB_LO:W["N"]]
        nneg = int(np.sum(sgt < 0.0))
        lmin, lmax = prefix_kernel_minmax(W, pm)
        rel = -lmin / max(lmax, 1.0)
        psd_worst = max(psd_worst, rel)
        info("%-6s N=%d  pmax=%d  neg modes in [8,N): %d  "
             "type(T_N) = %-24s  prefix-kernel lambda_min %.2e "
             "(rel %.1e)"
             % (tag, W["N"], pm, nneg, cell_type(pm, W["N"]),
                lmin, rel))
    check("G11-leg0-typing-psd", psd_worst <= PSD_EIG_BAR,
          "firewall type table printed (world -> max positive "
          "prefix); every own-grid PREFIX kernel G_pmax is PSD: "
          "worst -lambda_min/max(lambda_max,1) = %.1e (bar %.0e) "
          "-- the reviewer core theorem holds numerically on "
          "every positive prefix" % (psd_worst, PSD_EIG_BAR))

    # ---------------- S3: LEG A -- factorial rasters
    section("S3  LEG A -- 2x2 WORLD CENSUS (raw + firewall-cleaned)")
    if not smoke:
        R = {}
        eff = {}
        adm_ok = True
        emb_worst = 0.0
        smcc_worst = 0.0
        prior_worst = 0.0
        psd_cell_worst = -1e300
        psd_kern_worst = 0.0
        ward_worst = 0.0
        chain_worst_m = chain_worst_c = sm_cln_worst = 0.0
        for ct in ("SCR", "EPST", "SMOOTH"):
            Wc = Wd[ct]
            nstar = min(pmax["w9"], pmax[ct])
            rb = union_raster(Wd["w9"], Wc, nstar,
                              want_alias=(ct == "SCR"))
            R[ct] = rb
            adm_ok = adm_ok and rb["ok_pos"] and nstar > FIB_LO
            emb_worst = max(emb_worst,
                            abs(rb["raw"]["cells"]["MM"]
                                / Wd["w9"]["T_mat"] - 1.0))
            if ct == "SMOOTH":
                smcc_worst = max(
                    abs(rb["raw"]["cells"]["CC"]) / rb["grossU"],
                    abs(rb["raw"]["cells"]["MC"]) / rb["grossU"])
                sm_cln_worst = max(
                    abs(rb["cln"]["cells"]["CC"]) / rb["grossU"],
                    abs(rb["cln"]["cells"]["MC"]) / rb["grossU"])
            else:
                emb_worst = max(emb_worst,
                                abs(rb["raw"]["cells"]["CC"]
                                    / Wc["T_mat"] - 1.0))
            eff[ct] = {lab: effects(rb[lab]["cells"])
                       for lab in ("raw", "cln")}
            ward_worst = max(ward_worst, eff[ct]["raw"]["ward"],
                             eff[ct]["cln"]["ward"])
            # PSD checks: MAIN kernel raw + both kernels cleaned
            psd_kern_worst = max(
                psd_kern_worst,
                -rb["raw"]["lmM"] / max(rb["raw"]["lxM"], 1.0),
                -rb["cln"]["lmM"] / max(rb["cln"]["lxM"], 1.0),
                -rb["cln"]["lmC"] / max(rb["cln"]["lxC"], 1.0))
            psd_cell_worst = max(
                psd_cell_worst,
                -rb["raw"]["cells"]["MC"] / rb["grossU"],
                *[-v / rb["grossU"]
                  for v in rb["cln"]["cells"].values()])
            # cleaned chain wards (diagonal cells vs partial sums)
            S_M = np.asarray(Wd["w9"]["p"]["S"], float)
            tgt_m = float(S_M[nstar - 1] - S_M[FIB_LO - 1])
            chain_worst_m = max(chain_worst_m,
                                abs(rb["cln"]["cells"]["MM"]
                                    / tgt_m - 1.0))
            if ct != "SMOOTH":
                S_C = np.asarray(Wc["p"]["S"], float)
                tgt_c = float(S_C[nstar - 1] - S_C[FIB_LO - 1])
                chain_worst_c = max(chain_worst_c,
                                    abs(rb["cln"]["cells"]["CC"]
                                        / tgt_c - 1.0))
            for lab in ("raw", "cln"):
                c = rb[lab]["cells"]
                e = eff[ct][lab]
                dep = ("N_M=%d/N_C=%d" % (Wd["w9"]["N"], Wc["N"])
                       ) if lab == "raw" else ("n*=%d" % nstar)
                typM = cell_type(pmax["w9"], Wd["w9"]["N"]
                                 if lab == "raw" else nstar)
                typC = cell_type(pmax[ct], Wc["N"]
                                 if lab == "raw" else nstar)
                info("%-6s %-3s (%s) MM %+.6g  MC %+.6g  CM %+.6g"
                     "  CC %+.6g | M-kernel %s / C-kernel %s"
                     % (ct, lab, dep, c["MM"], c["MC"], c["CM"],
                        c["CC"], typM, typC))
                info("%-6s %-3s Delta_base %+.6g  Delta_border "
                     "%+.6g  Delta_int %+.6g  Gap %+.6g  (ward "
                     "%.1e)" % (ct, lab, e["Db"], e["Dbo"],
                                e["Di"], e["gap"], e["ward"]))
        check("G20-raster-admission", adm_ok
              and emb_worst <= EMB_BAR and smcc_worst <= SM_GUARD,
              "r254-a1 union embedding re-gated on 3 pairs: "
              "border bitwise identical + window position sets "
              "found in union; |U| = %s; n* = %s (all > %d); "
              "embedding wards worst %.1e (bar %.0e); SMOOTH CC/"
              "MC abs %.1e (bar %.0e)"
              % (str({c: R[c]["nU"] for c in R}),
                 str({c: R[c]["nstar"] for c in R}), FIB_LO,
                 emb_worst, EMB_BAR, smcc_worst, SM_GUARD))
        for ct, pri in (("SCR", PRIOR_SCR), ("EPST", PRIOR_EPST)):
            for key, ref in pri.items():
                prior_worst = max(prior_worst,
                                  abs(R[ct]["raw"]["cells"][key]
                                      / ref - 1.0))
        check("G21-r254-priors", prior_worst <= PRIOR_TOL,
              "raw rasters vs the r254 records (SCR 4 cells + "
              "EPST 3 cells): worst rel %.1e (tol %.0e) -- the "
              "r254 cross table is verified, then TYPED: T_SM/"
              "T_SS/T_EM/T_EE are INDEFINITE_CONTINUATION cells "
              "(no independent fiber falsifiers), T_MM/T_MS/T_ME "
              "are POSITIVE_PREFIX" % (prior_worst, PRIOR_TOL))
        check("G22-psd-theorem-empirical",
              psd_kern_worst <= PSD_EIG_BAR
              and psd_cell_worst <= CELL_PSD_FLOOR,
              "kernel PSD (MAIN raw + all cleaned): worst "
              "-lambda_min rel %.1e (bar %.0e); every POSITIVE_"
              "PREFIX-typed cell >= -floor: worst -cell/gross "
              "%.1e (floor %.0e) -- T >= 0 for EVERY border "
              "measure under a positive kernel, empirically "
              "(T_MS raw %+.4f > 0 confirms the theorem)"
              % (psd_kern_worst, PSD_EIG_BAR, psd_cell_worst,
                 CELL_PSD_FLOOR,
                 R["SCR"]["raw"]["cells"]["MC"]))
        check("G23-identity-ward", ward_worst <= WARD_ID_BAR,
              "Delta_base + Delta_border - Delta_int = Gap on "
              "all 6 rasters: worst rel %.1e (bar %.0e)"
              % (ward_worst, WARD_ID_BAR))
        check("G24-cleaned-chain-wards",
              chain_worst_m <= CHAIN_CLN_MAIN
              and chain_worst_c <= CHAIN_CLN_CTRL
              and sm_cln_worst <= SM_GUARD,
              "cleaned diagonal cells vs the bitwise partial "
              "sums S_{n*-1} - S_7: MAIN worst %.1e (bar %.0e), "
              "controls %.1e (bar %.0e), SMOOTH abs %.1e (bar "
              "%.0e) -- the truncated kernels sit on the exact "
              "chain" % (chain_worst_m, CHAIN_CLN_MAIN,
                         chain_worst_c, CHAIN_CLN_CTRL,
                         sm_cln_worst, SM_GUARD))
        v_main, why = adjudicate(eff["SCR"]["cln"],
                                 eff["SCR"]["raw"],
                                 R["SCR"]["grossU"])
        e_r, e_c = eff["SCR"]["raw"], eff["SCR"]["cln"]
        check("G25-mainxscr-adjudication", True,
              "SEALED verdict on MAIN x SCRAMBLE: %s (%s); raw "
              "Db %+.4f Dbo %+.4f Di %+.4f Gap %+.4f vs cleaned "
              "Db* %+.6g Dbo* %+.6g Di* %+.6g Gap* %+.6g; "
              "|Dbo|/|Gap| raw %.3g (sign %s) cln %.3g (sign %s)"
              % (v_main, why, e_r["Db"], e_r["Dbo"], e_r["Di"],
                 e_r["gap"], e_c["Db"], e_c["Dbo"], e_c["Di"],
                 e_c["gap"],
                 abs(e_r["Dbo"]) / max(abs(e_r["gap"]), 1e-300),
                 "OK" if e_r["Dbo"] * e_r["gap"] > 0 else "WRONG",
                 abs(e_c["Dbo"]) / max(abs(e_c["gap"]), 1e-300),
                 "OK" if e_c["Dbo"] * e_c["gap"] > 0
                 else "WRONG"))
        ge_r = eff["EPST"]["raw"]["gap"]
        ge_c = eff["EPST"]["cln"]["gap"]
        dbo_c = eff["EPST"]["cln"]["Dbo"]
        crit1 = abs(ge_c) <= CONTAM_GAP_BAR * abs(ge_r)
        crit2 = abs(dbo_c) <= CONTAM_BORD_BAR * max(abs(ge_c),
                                                    1e-12)
        v_ep = ("CONTROL_FIBER_IS_BASE_CONTAMINATION"
                if (crit1 or crit2)
                else "EPSTEIN_ANOMALY_SURVIVES_PREFIX")
        check("G26-epstein-contamination", True,
              "EPSTEIN anomaly on the common positive prefix "
              "(n* = %d): |Gap*| = %.4g = %.3f x |Gap_raw| %.4g "
              "(bar %.1f, crit1 %s); |Dbo*| = %.3g vs %.1f x "
              "|Gap*| (crit2 %s) => %s"
              % (R["EPST"]["nstar"], abs(ge_c),
                 abs(ge_c) / max(abs(ge_r), 1e-300), abs(ge_r),
                 CONTAM_GAP_BAR, crit1, abs(dbo_c),
                 CONTAM_BORD_BAR, crit2, v_ep))
        v_sm = ("SMOOTH_NULL_ANCHOR_OK"
                if (smcc_worst <= SM_GUARD
                    and sm_cln_worst <= SM_GUARD)
                else "SMOOTH_NULL_ANCHOR_BROKEN")
        check("G27-smooth-null-anchor",
              v_sm == "SMOOTH_NULL_ANCHOR_OK",
              "SMOOTH border cells vanish raw %.1e / cleaned "
              "%.1e x gross (bar %.0e) -- the null world anchors "
              "the raster machinery: %s"
              % (smcc_worst, sm_cln_worst, SM_GUARD, v_sm))
    else:
        v_main, v_ep, v_sm = ("SMOKE_NO_ADJUDICATION",) * 3
        eff = {}
        R = {}
        for g in ("G20-raster-admission", "G21-r254-priors",
                  "G22-psd-theorem-empirical",
                  "G23-identity-ward", "G24-cleaned-chain-wards",
                  "G25-mainxscr-adjudication",
                  "G26-epstein-contamination",
                  "G27-smooth-null-anchor"):
            check(g, True, "SMOKE: skipped (needs controls)")

    # ---------------- S4: LEG A2 -- inversion adjudication
    section("S4  LEG A2 -- INVERSION ADJUDICATION (SCRAMBLE "
            "compactness)")
    if not smoke:
        Ws = OG.eig_block(Wd["SCR"])
        sgt = Ws["sgv"][FIB_LO:Ws["N"]]
        neg = np.nonzero(sgt < 0.0)[0] + FIB_LO
        pos = np.nonzero(sgt > 0.0)[0] + FIB_LO
        Pn, Pp = Ws["P"][neg], Ws["P"][pos]
        Gn = (Pn.T * Ws["sgv"][neg]) @ Pn
        Gp = (Pp.T * Ws["sgv"][pos]) @ Pp
        T_neg = float(Ws["s"] @ (Gn @ Ws["s"]))
        T_pos = float(Ws["s"] @ (Gp @ Ws["s"]))
        split_dev = abs(T_pos + T_neg - Ws["T_mat"]) \
            / max(Ws["gross"], 1e-300)
        shares, k80, dpart = OG.profile_stats(Ws["c"],
                                              Ws["T_mat"])
        check("G30-a2-mode-split",
              split_dev <= 1e-9
              and T_pos >= -CELL_PSD_FLOOR * Ws["gross"]
              and k80 == PRIOR_K80_SCR,
              "h-sign mode split of G_SCR (%d neg / %d pos "
              "modes): T_pos %+.4f (PSD: >= -floor) + T_neg "
              "%+.4f = T_SS %+.4f (dev %.1e x gross); the "
              "negative modes carry %.1f percent of T_SS; "
              "K80_own(SCR) = %d (r254 prior %d) reproduced"
              % (len(neg), len(pos), T_pos, T_neg, Ws["T_mat"],
                 split_dev, 100.0 * T_neg / Ws["T_mat"], k80,
                 PRIOR_K80_SCR))
        Qu, sv, _vt = np.linalg.svd(Pn.T, full_matrices=False)
        Q = Qu[:, sv > NEG_RANK_CUT * sv[0]]
        top = np.argsort(-np.abs(Ws["c"]))[:2]
        fn = [float(np.sum((Q.T @ Ws["V"][:, k]) ** 2))
              for k in top]
        mean_f = float(np.mean(fn))
        if mean_f >= INV_HI:
            v_inv = "INVERSION_IS_BASE_CONTAMINATION(f_neg=" \
                "%.4f)" % mean_f
        elif mean_f <= INV_LO:
            v_inv = "INVERSION_GENUINE_FIND(f_neg=%.4f)" % mean_f
        else:
            v_inv = "INVERSION_MIXED(f_neg=%.4f)" % mean_f
        check("G31-a2-inversion", True,
              "top-2 |c| eigenpairs of G_SCR: lambda %s, c/T "
              "shares %s, f_neg (overlap with the h<0 mode span, "
              "rank %d) %s => mean %.4f (bars %.1f/%.1f) => %s%s"
              % (str([round(float(Ws["lam"][k]), 1)
                      for k in top]),
                 str([round(float(Ws["c"][k] / Ws["T_mat"]), 3)
                      for k in top]), Q.shape[1],
                 str([round(f, 4) for f in fn]), mean_f, INV_HI,
                 INV_LO, v_inv,
                 " -- the r254 'SCRAMBLE spectrally compact' "
                 "headline is DOWNGRADED to base contamination"
                 if mean_f >= INV_HI else ""))
    else:
        v_inv = "A2_SMOKE_NA"
        check("G30-a2-mode-split", True, "SMOKE: skipped")
        check("G31-a2-inversion", True, "SMOKE: skipped")

    # ---------------- S5: LEGS B-D (conditional)
    section("S5  LEGS B-D (conditional on BORDER_PAIRING_"
            "LOAD_BEARING)")
    unlocked = (v_main == "BORDER_PAIRING_LOAD_BEARING")
    if unlocked:
        W9 = Wd["w9"]
        G, sb, order, Gs, T0 = exchange_pieces(W9)
        dts = []
        for t in range(len(order) - 1):
            i, j = int(order[t]), int(order[t + 1])
            if sb[i] == sb[j]:
                continue
            dts.append(dt_formula(G, Gs, sb, i, j))
        dts = np.asarray(dts)
        fpos = float(np.mean(dts > 0.0)) if len(dts) else 0.0
        frac = max(fpos, 1.0 - fpos)
        v_ex = ("EXCHANGE_MONOTONE_GO(frac=%.4f)" % frac
                if frac >= MONO_GO
                else "EXCHANGE_SIGN_MIXED(frac=%.4f)" % frac)
        nb = W9["nb"]
        Gss = G[np.ix_(order, order)]
        D2 = Gss[:-1, :-1] + Gss[1:, 1:] - Gss[:-1, 1:] \
            - Gss[1:, :-1]
        iu = np.triu_indices(nb - 1, k=1)
        vv = D2[iu]
        vv = vv[vv != 0.0]
        fp2 = float(np.mean(vv > 0.0)) if len(vv) else 0.0
        frac2 = max(fp2, 1.0 - fp2)
        if frac2 >= TP_GO:
            v_tp = "MONGE_TP_ORDER(frac=%.4f)" % frac2
        elif frac2 < TP_NO:
            v_tp = "NO_EXCHANGE_ORDER(frac=%.4f)" % frac2
        else:
            v_tp = "WEAK_ORDER(frac=%.4f)" % frac2
        OG.eig_block(W9)
        o = np.argsort(-np.abs(W9["lam"]))
        cum = np.cumsum(W9["c"][o]) / W9["T_mat"]

        def kfor(tol):
            w = np.nonzero(np.abs(cum - 1.0) <= tol)[0]
            return int(w[0]) + 1 if len(w) else len(cum) + 1

        k90, k99, k999 = kfor(0.1), kfor(0.01), kfor(0.001)
        Rk = W9["N"] - FIB_LO
        if k90 <= K90_FIXED:
            v_ca = "FIXED_SPECTRAL_CARRIER"
        elif k90 <= 4.0 * math.log(Rk):
            v_ca = "LOG_SPECTRAL_CARRIER"
        else:
            v_ca = "EXTENSIVE_SPECTRAL_CARRIER"
        v_ca += "(K90=%d, K99=%d, K99.9=%d of %d)" \
            % (k90, k99, k999, Rk)
        v_bd = "LEGS_BD(%s + %s + %s)" % (v_ex, v_tp, v_ca)
        check("G40-legsBD", True,
              "UNLOCKED: %d admissible adjacent border swaps, "
              "%s; %d Monge quadruples, %s; source-pure "
              "|lambda|-ordered carrier: %s"
              % (len(dts), v_ex, len(vv), v_tp, v_ca))
    else:
        v_bd = "LEGS_BD_SKIPPED(%s)" % v_main
        check("G40-legsBD", True,
              "SKIPPED by the sealed conditional: main verdict "
              "%s != BORDER_PAIRING_LOAD_BEARING -- no exchange/"
              "Monge/spectral pairing claim is registered; their "
              "gates do not count" % v_main)
    if not smoke:
        for tag in ("w9", "SCR"):
            bs = OG.band_stats(Wd[tag])
            tot = max(float(np.sum(bs["ab"])), 1e-300)
            info("APPENDIX %-4s d0 %.3g  dyadic band |C|-shares: "
                 "%s" % (tag, bs["d0"],
                         " ".join("%.3f" % (v / tot)
                                  for v in bs["ab"])))

    # ---------------- S6: LEG E -- falsifiers + must-fails
    section("S6  LEG E -- FALSIFIERS + MUST-FAILS")
    W9 = Wd["w9"]
    G, sb, order, Gs, T0 = exchange_pieces(W9)
    samp = np.unique(np.linspace(0, len(order) - 2,
                                 EXG_SAMPLES).astype(int))
    dev_h = 0.0
    best_load, best_pair = -1.0, None
    for t in samp:
        i, j = int(order[t]), int(order[t + 1])
        dd = sb[i] - sb[j]
        dev_h = max(dev_h, abs(dt_formula(G, Gs, sb, i, j)
                               - dt_direct(G, sb, T0, i, j)))
    for t in range(len(order) - 1):
        i, j = int(order[t]), int(order[t + 1])
        dd = sb[i] - sb[j]
        load = abs(4.0 * dd * dd * G[i, j])
        if load > best_load:
            best_load, best_pair = load, (i, j)
    i, j = best_pair
    dt_bad = dt_formula(G, Gs, sb, i, j, wrong=True)
    dt_dir = dt_direct(G, sb, T0, i, j)
    mx_dev = abs(dt_bad - dt_dir)
    mx_floor = MF_LOUD * max(dev_h, MF_NOISE * W9["gross"])
    ok_e0 = dev_h <= EXG_BAR * W9["gross"]
    ok_mx = mx_dev >= mx_floor
    check("G60-exchange-formula-mx",
          ok_e0 and ok_mx,
          "e0: exchange formula vs direct on %d sampled adjacent "
          "border swaps: worst dev %.1e (bar %.0e x gross %.3g); "
          "mX wrong cross term (+2G_ij) at the max-|4d^2 G_ij| "
          "swap: dev %.3g = %.1e x the honest floor (bar %.0e x)"
          % (len(samp), dev_h, EXG_BAR, W9["gross"], mx_dev,
             mx_dev / max(dev_h, MF_NOISE * W9["gross"]),
             MF_LOUD))
    if not smoke:
        cells = R["SCR"]["raw"]["cells"]
    else:
        cells = dict(MM=1.0, MC=2.0, CM=3.0, CC=4.0)
    e_ok = effects(cells)
    Di_bad = cells["MM"] - cells["MC"] - cells["CM"] - cells["CC"]
    resid = abs((e_ok["Db"] + e_ok["Dbo"] - Di_bad) - e_ok["gap"])
    pred = 2.0 * abs(cells["CC"])
    mw_floor = MF_LOUD * max(e_ok["ward"], MF_NOISE) \
        * e_ok["scale"]
    ok_mw = abs(resid / pred - 1.0) <= 1e-9 and resid >= mw_floor
    check("G61-mustfail-effect-formula", ok_mw,
          "mW flipped-CC interaction formula breaks the identity "
          "ward by %.6g vs predicted 2|T_CC| = %.6g (rel %.1e); "
          "loudness %.1e x floor%s"
          % (resid, pred, abs(resid / pred - 1.0),
             resid / max(mw_floor, 1e-300),
             " (SMOKE: synthetic 2x2)" if smoke else ""))
    if not smoke:
        al = R["SCR"]["alias"]
        cM = R["SCR"]["raw"]["cells"]["CM"]
        lmC = R["SCR"]["raw"]["lmC"]
        lxC = R["SCR"]["raw"]["lxC"]
        gU = R["SCR"]["grossU"]
        loud_neg = -lmC >= MF_LOUD * MF_NOISE * max(lxC, 1.0)
        split_dev = abs(al["T_SM_pos"] + al["T_SM_neg"] - cM) \
            / max(gU, 1e-300)
        pos_ok = al["T_SM_pos"] >= -CELL_PSD_FLOOR * gU
        neg_loud = -al["T_SM_neg"] >= MF_LOUD * MF_NOISE * gU
        check("G62-mustfail-alias", loud_neg and pos_ok
              and neg_loud and split_dev <= 1e-9,
              "FIREWALL-OMITTED alias killed: lambda_min(G_SCR "
              "full) = %.4g (%.1e x floor, loud); mode split of "
              "T_SM %+.4f = pos %+.4f (>= -floor, PSD obeyed) + "
              "neg %+.4f (< 0, %.1e x floor) exact to %.1e x "
              "gross -- the T_SM negativity is 100 percent an "
              "h<0-mode (KERNEL) property; labeling it a border "
              "effect without leg 0 would be the alias"
              % (lmC, -lmC / max(MF_NOISE * max(lxC, 1.0),
                                 1e-300), cM, al["T_SM_pos"],
                 al["T_SM_neg"],
                 -al["T_SM_neg"] / max(MF_NOISE * gU, 1e-300),
                 split_dev))
    else:
        check("G62-mustfail-alias", True,
              "SMOKE: skipped (needs SCRAMBLE)")

    # ---------------- S7: verdict
    section("S7  VERDICT")
    check("G90-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the positive-prefix firewall typing of every "
          "factorial cell, the firewall-cleaned 2x2 census on "
          "the common positive prefix, the sealed base/border/"
          "interaction adjudication, the SCRAMBLE-inversion and "
          "EPSTEIN-anomaly re-adjudications, and the "
          "unconditional exchange-formula machinery")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        verd = " + ".join([v_main, "A2: " + v_inv,
                           "EPST: " + v_ep, v_sm, v_bd])
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G91-verdict", npass == len(CHECKS),
          "%s%s -- MEASURED: the firewall type table, both "
          "rasters with the three effects per world pair, the "
          "inversion and contamination adjudications, the "
          "exchange-formula gates; OPEN: any a-priori bound, the "
          "base law, the budget bound (r243/r247/r250/r251/r253/"
          "r254 stand); NO RH claim"
          % (verd, " (SMOKE)" if smoke else ""))
    wall = time.time() - T0_WALL
    check("G99-runtime", wall <= 1800.0,
          "WALL %.1f s (bar 1800)" % wall)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    print("\n" + "=" * 78)
    print("RESULT: %d/%d gates PASS%s   SPEC_SHA %s"
          % (npass, len(CHECKS), " (SMOKE)" if smoke else "",
             SPEC_SHA[:16]))
    print("NO RH CLAIM in either direction.")
    print("=" * 78)
    return 0 if npass == len(CHECKS) else 1


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

_SRC_1 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""coupledtau_probe -- PRIME.PORT.RHP.FULLSOURCE.COUPLEDTAU.01
(round 257): the EXACT n-dynamics of the indivisible full-source
object.  After r256 (EFFECTS_MIXED_COUPLEDTAU: on the common
positive prefix the base rotation is null, the border carries 81
percent with a sign flip, LOAD_BEARING did not fire) the reviewer
pre-declaration stands: base/fiber separation is ARTIFICIAL; the
object is the PAIR (tau_{w,n}, tau^aug_{w,n}) with D_{w,n} =
tau^aug_{w,n}/tau_{w,n}, together with the no-pole question for
tau.  DESIGN RULES (non-negotiable): the full von Mangoldt comb
stays in the main problem, NO PNT smoothing; small parameters only
in degree/deformation directions (quenched full-source analysis);
the compression family is CLOSED (r254/r256) -- this round derives
the exact DEGREE DYNAMICS, no compression.

EXPLORATION ONLY (2026-08-24).  experiments/ level: NO promotion,
NO ledger row, NO marker moved, NO RH CLAIM in either direction.

INDEX FIREWALL (binding, r238-r256 discipline): w = window (kz),
N_w = builder depth, n/k = chain degree; free pivots h_{w,k}
(k < N_w) are the proof objects; rho_k = F_k^2/h_k, S_n =
sum_{k<=n} rho_k (r243/r244); ground truth (h signs, flip degrees,
forced-tail offsets, T_true) enters GATES only; no zero/prime
oracles anywhere (AST firewall).  MACHINERY IMPORTED VERBATIM:
r244 BH.wpack + BH.bord_chain (chain, border readouts fb, Ls),
r226 HS.window_data, v881 PIK rung builders + folded measures +
Lanczos chain, r243 PB.smooth_comb; B PROVENANCE: the covering
budget stays B_w = S_{N-2} + 5/7 (r243/r247, IMPORTED, never
fitted).  POSITIVITY TYPING ADOPTED from r256: POSITIVE_PREFIX
(all h_k > 0 below n: Hilbert-space statements legitimate) vs
INDEFINITE_CONTINUATION (algebraic tau-quotient statements only);
pmax = MAIN 184 (full depth) / SCR 21 / EPST 25 / SMOOTH 27.

LEG A -- THE COUPLED RECURSION (exact algebra, then machine-gated
in a SEALED basis): fix the graded basis P_k(x) = U_k((x - x0)/rh)
(Chebyshev-U on the union+border hull; leading coefficient c_k =
(2/rh)^k, exactly known).  With G_n the leading n x n Gram of
mutilde, t_n the border (sigmatilde) readout column, corner B:
tau_n := det G_n, tau^aug_n := det [[G_n, t_n], [t_n^T, B]].  The
Schur identity D_n = tau^aug_n/tau_n = B - sum_{k<n} F_k^2/h_k
(r253 leg T, full-depth exact) yields the ONE-STEP PAIR RECURSION
    tau_{n+1}     = a_n tau_n,
    tau^aug_{n+1} = a_n tau^aug_n + b_n tau_n,
    a_n = c_n^2 h_n,        b_n = -(c_n F_n)^2,
equivalently D_{n+1} = D_n - rho_n, rho_n = F_n^2/h_n; seeds
tau_1 = h_0, tau^aug_1 = h_0 B - F_0^2 (closed form, chain-side).
COEFFICIENT TYPOLOGY (sealed claim, machine-gated): a_n CONSUMES
THE h-CHAIN (its sign IS the world's pivot sign; magnitude the
chain norm times the exactly known basis factor); b_n has SOURCE-
PURE SIGN (b_n <= 0 in EVERY world -- a perfect square with a
minus; only its MAGNITUDE consumes the chain + the Cauchy/border
column F_n = int pi_n dsigmatilde); hence the D-increment -rho_n
carries sign -sign(h_n): THE BASE PIVOT ALONE CARRIES THE SIGN,
THE BORDER CONTRIBUTES A NONNEGATIVE MAGNITUDE.  GATES: (a1)
tau-step: slogdet(G_{n+1}) - slogdet(G_n) == 2n log(2/rh) + log
|h_n| AND sign == sg h_n at ALL n < N on ALL worlds (MAIN bar
1e-6 abs-log, control bar 1e-4: the f64 chain reference saturates
on flipped worlds, r253-a1 precedent); (a2) coupled step: the
signed-log PAIR PROPAGATION from the closed-form seed, consuming
ONLY (h_n, F_n) chain data, reproduces the direct bordered
slogdet at ALL n on ALL worlds (abs-log dev + sign mismatch
counted 2; MAIN bar 1e-6, control bar 1e-3 = the r253-a1 floor);
(a3) full-depth anchor: D_N(recursion) == 5/7 - rho_{N-1}, rel
1e-9, every world; (a4) mp monomial Hankel truncation ward at
sealed n_t in {12, 24} (dps 220, corner B_t = 5/7): det ratio vs
B_t - S_{n_t-1} on w9 (bar 1e-12, f64 reference floor) AND on
SCRAMBLE (n_t = 24 spans the flip 21: the recursion is gated
THROUGH the indefinite continuation in exact arithmetic; bar
1e-6, f64 control reference); (a5) typology gates: b_n <= 0 for
all n, all worlds (machine), and on the DIRECT route the D-
increment sign equals -sg h_n at every resolvable degree
(resolvable: |rho_n| >= floor x max(|D_n|, |D_{n+1}|), floor 1e-7
MAIN / 1e-2 controls -- below the route's own noise the sign is
not measurable, typed).

LEG B -- THE COUPLED BUDGET COCYCLE: the scalar accumulation is
D_n itself (Phi_n = log10 |D_n|, s_n = sign D_n) with EXACT
increment law D_{n+1} - D_n = -rho_n.  (b1) INCREMENT SIGN LAW:
on MAIN the increments are STRICTLY NEGATIVE through the ENTIRE
free window (all rho_n > 0, n < N, both MAIN windows) -- a
monotone drain; on the controls the law breaks EXACTLY at the
r256 base flips (first n with rho_n < 0 == 21/21/25/27 for
SCR/EPST/SMOOTH as re-derived) -- both gated.  (b2) BORDER ROLE
PER ZONE (sealed zones, r246/r244 conventions: HEAD n < 8,
QUIET/BULK 8 <= n < N-5, TAIL n >= N-5): zone sums of rho, zone
shares of S_{N-1}, and the log10 |D| drop per zone -- the
coupling term is the SOLE n-dynamics (a pure drain: it drives D
monotonically toward the terminal value, it never dampens);
quantified per zone per world, controls typed INDEFINITE_
CONTINUATION beyond pmax.  (b3) WORLD SEPARATION BEFORE THE
TERMINAL DEGREE (the old R4 question in the new coordinate,
sealed bar 1.0 decade): sep_W = |log10 |D_MAIN(n)| - log10
|D_W(n)|| at the sealed checkpoints n in {16, pmax_W} (each world
its own B_w; honest measurement, no upgrade).

LEG C -- THE MICRO-FALSIFIER (mandatory; frozen in
PRIME.FREEMOMENT.POSITIVEPREFIX.01): predict BLIND (i) the w9
control flips 21/25/27 and (ii) the five-window forced-tail
survival 0/2/2/3/1 at j = n - N_w >= 0 (w = 9/12/13/26/40).
PREDICTOR (AST-separated): blind_flip_predictor consumes ONLY
node positions + signed weights (the source), builds the sealed
scaled-Chebyshev Gram, and reads the pivot-sign field of the
tau-step coefficient a_n by INDEPENDENT LINEAR ALGEBRA (slogdet
principal-minor scan) -- it NEVER touches the h-/r-chain arrays
(sg_h, lg_h, gam_next, hv, Fv, rho, fb, nf), enforced by a
dedicated AST scope audit (gate) with a deliberately oracle-
reading mutant that the audit MUST flag (must-fail).  Ground
truth (extended BH.bord_chain sign chain, wpack nf) enters gates
only.  mp WARDS (dps 40, sealed): the SCRAMBLE flip (sign det
G_21 > 0, sign det G_22 < 0) and the w9 forced-tail flip (sign
det G_184 > 0, sign det G_185 < 0) confirmed in exact-precision
determinants of the SAME source Gram.  HONEST TYPING (sealed):
a pass certifies the coupled recursion's COEFFICIENT FIELD as a
falsifier-compliant model class via a route-independent source-
only computation; it is NOT a parametrix/local-connection
mechanism -- that pass stays OPEN (typed in the verdict).

LEG D -- NO-POLE CONNECTION IN s (MEASUREMENT, no theorem): with
the r224 s-dressed port (D_P(s) = P + sX(I - sR)^{-1}X^T,
det(I - sE) = det(I - sR) det(I - sD_P(s)); identity RE-GATED
here on rungs 9 and 12 at the sealed s-grid, bar 1e-9), measure
on the sealed 10-rung window ladder kz = (17, 10, 18, 12, 13, 9,
15, 19, 26, 40) (h = 96..591, >= 6 rungs as contracted): (d1)
the base family tau_w(s) = det(I - sQ_w) (Q_w = A^T A the state
Gram, nonzero spectrum == E's): all real s-zeros are 1/lambda_i;
gate lambda_max < 1 (the wall) and tabulate the NOPOLE.COFINAL
core indicator dist_w = 1/lambda_max - 1 vs N = h; trend = LS
slope + Spearman of log10 dist vs log10 h (sealed rule:
APPROACHING iff Spearman <= -0.5, RECEDING iff >= +0.5, else
FLAT).  (d2) the AUGMENTED object: adjoin the border row (the
sigmatilde functional f_k = int P_k dsigmatilde in the SAME
state frame; folded smooth comb, both arms signed) -- augmented
spectrum == spec(Q + f f^T) (rank-1 Uvarov row; Cauchy
interlacing gated as an exact ward): does the nearest zero
structure shift across s = 1?  TWO sealed variants: RAW (the
mass-carrying row as the coupled object has it; corner |f|^2
printed) and UNIT (direction-only, u = f/|f|): tokens
AUG_RAW_<CROSSES_ONE|BELOW_ONE> + AUG_UNIT_<CROSSES_ONE|
BELOW_ONE>, honest typing: a RAW crossing driven by |f|^2 >> 1
is a MASS statement about the aggregated Uvarov row, not a
directional wall statement -- printed, never upgraded.

LEG E -- FALSIFIERS + MUST-FAILS (each loud, sealed): (e1)
SWAPPED BORDER INDEX: the coupled step run with F_{n+1} in place
of F_n must break the full-depth anchor on MAIN loudly (>= 1e3 x
the honest rel dev); (e2) OMITTED COUPLING TERM: tau^aug_{n+1} =
a_n tau^aug_n alone freezes D at B -- must break the anchor
loudly on MAIN (>= 1e3 x); (e3) ORACLE PREDICTOR: a mutant that
reads sg_h must be FLAGGED by the predictor AST audit; (e4)
SMOOTH ANCHOR: on the SMOOTH world border == window, so F_n = 0
for n >= 1 by orthogonality EXACTLY -- the coupling term
vanishes identically (max_{n>=1} |rho_n| / rho_0 <= 1e-18) and
the pair recursion degenerates to the pure tau-step: the
coupling is source-driven, not an artifact.

SEALED CONSTANTS: MAIN windows (9, 13); controls on w9: EPSTEIN,
SCRAMBLE (seed 1), SMOOTH; flips re-derived 25/21/27; tail
windows (9, 12, 13, 26, 40), prior offsets (0, 2, 2, 3, 1), EXT
6; FIB_LO 8; B_w = S_{N-2} + 5/7; basis hull = union + border
atoms (predictor: union only); bars: tau-step 1e-6 MAIN / 1e-4
controls, coupled 1e-6 MAIN / 1e-3 controls (r253-a1 floor),
anchor 1e-9, mp truncations {12, 24} dps 220 bar 1e-12 (w9) /
1e-6 (SCRAMBLE), resolvable-increment floor 1e-7 MAIN / 1e-2
controls; zones HEAD_K 8 / TAIL_K 5; separation checkpoints {16,
pmax_W}, bar 1.0 dec; mp flip wards dps 40 at n in {21, 22} (SCR)
and {184, 185} (w9); NOPOLE ladder (17, 10, 18, 12, 13, 9, 15,
19, 26, 40), Schur identity re-gate rungs (9, 12) at s-grid
(0.25, 0.5, 0.75, 0.9, 1.0) bar 1e-9, interlacing tol 1e-8 rel,
Spearman bar 0.5; SMOOTH alias bar 1e-18; loudness 1e3; runtime
<= 1800 s; smoke = w9 only (recursion legs w9 + controls, tail
w9 only, ladder rung 9 only, mp wards skipped, separation and
five-window blind tail skipped).

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  COUPLED_RECURSION_EXACT(a chain-consuming, b source-sign-pure)
    / COUPLED_RECURSION_OPEN
+ COCYCLE_LAW_FOUND(monotone drain; breaks at flips)
    / COCYCLE_STRUCTURELESS
+ WORLD_SEP_PRETERMINAL(dec) / NO_EARLY_SEPARATION(dec)
+ MICROFALSIFIER_PASSED(blind: coeff-field)
    / MICROFALSIFIER_PARTIAL(typed) / MICROFALSIFIER_FAILED
+ NOPOLE_TREND(<APPROACHING|FLAT|RECEDING>, slope, spearman)
+ AUG_RAW_<CROSSES_ONE|BELOW_ONE> + AUG_UNIT_<CROSSES_ONE|
    BELOW_ONE>.
Honesty before beauty: no verdict claims a bound mechanism or a
parametrix; the budget bound, the base law, and the positive
reachability of half-filling stay OPEN (r243/r247/r250/r251/
r253/r256 stand).

RECORD TABLES (frozen from calibration pass 1, 26/26 gates FIRST
FULL PASS, wall 27.9 s full / 0.3 s smoke; smoke-stage
amendments disclosed, both found in --smoke BEFORE any full
pass: (s1) the draft coupled step propagated the coupling term
with a hard-coded minus -- the exact term is b_n tau_n whose
sign is -sign(tau_n): invisible on MAIN (tau > 0 throughout),
LOUD on the flipped controls (SCR D_N +228 instead of +0.52) --
the propagation now carries -s_tau exactly as the derived
algebra demands; (s2) the zone log10|D| drop base is D_0 = B
(the empty-Gram value), not D_1; no bar and no verdict rule
moved at any point; the four scratch calibrations -- recursion
floors, blind flip route, mp det cost, augmented eigenvalue --
predate this spec and are disclosed in the bars above):
CAL_VERDICT = COUPLED_RECURSION_EXACT(a chain-consuming, b
source-sign-pure) + COCYCLE_LAW_FOUND(monotone drain; breaks at
flips 21/25/27) + NO_EARLY_SEPARATION(0.84 dec) +
MICROFALSIFIER_PASSED(blind: coeff-field) +
NOPOLE_TREND(APPROACHING, slope -2.87, spearman -0.806) +
AUG_RAW_CROSSES_ONE + AUG_UNIT_CROSSES_ONE.
Key numbers.  CENSUS: w9/w13 N = 184/168, POSITIVE_PREFIX at
full depth; controls pmax = SCR 21 / EPST 25 / SMOOTH 27
(INDEFINITE_CONTINUATION), all re-derived.  LEG A (the round's
SATZ headline -- the pair recursion is machine-exact at every
degree on every world): tau-step worst abs-log dev 1.4e-10
(MAIN) / 4.8e-06 (controls, the f64 chain floor on flipped
worlds), signs exact at every degree; coupled propagation
(chain-side seeds tau_1 = h_0, tau^aug_1 = h_0 B - F_0^2, then
coefficients only) vs direct bordered slogdet: w9 9.5e-10, w13
1.2e-09, SCR 4.2e-04 (the r253-a1 floor), EPST 5.2e-05, SMOOTH
6.5e-10 -- ALL signs of BOTH components match at EVERY degree;
anchors D_N = 5/7 - rho_{N-1}: +0.561250 / +0.356069 /
+0.521703 / +1.792211 / +0.714286, rel devs <= 4.8e-11; mp
truncation wards (dps 220): w9 2.8e-17 / 1.0e-16, SCRAMBLE
1.8e-16 / 6.4e-14 (n_t = 24 THROUGH the flip 21: the pair
recursion is exact across the indefinite continuation);
typology: b_n <= 0 at every degree on every world (machine),
increment signs == -sg h_n at all 548 resolvable of 899 degrees
(below the floor the route's own noise dominates, typed).
LEG B: MAIN monotone drain through the ENTIRE free window (min
rho: w9 8.9e-10 at n = 180, w13 1.6e-08 at n = 26 -- all
positive); the control increment law breaks FIRST at exactly
21/25/27; zone anatomy (share of S_{N-1} HEAD/BULK/TAIL, then
log10|D| drop): w9 0.446/0.531/0.023, drop 0.234/0.820/0.121;
w13 0.440/0.498/0.062, drop 0.236/0.743/0.359 -- rho_0 alone
carries ~0.44 as ONE mode (r246 reproduced), the bulk drains
extensively, the last 5 degrees still drop 0.12-0.36 decades
(the drain never dampens: pure negative increments); controls
(algebraic beyond pmax): EPST 0.821/-0.423/0.603, SCR
-3.66/-17.27/+21.92 (the indefinite continuation swings both
ways), SMOOTH 1/0/0 exactly; (b3) separation at the sealed
checkpoints {16, pmax_W}: SCR 0.072/0.068 dec, EPST 0.283/0.283,
SMOOTH 0.836/0.836 -- best 0.84 dec < 1.0: NO_EARLY_SEPARATION
(honest: the cocycle coordinate does NOT separate MAIN from the
controls a full decade before the terminal degree; the old R4
answer survives in the new coordinate).  LEG C: predictor AST
scope CLEAN (gate) and the oracle mutant FLAGGED (rows/sg_h
hits, must-fail fires); blind control flips 21/25/27 == ground
truth (3/3); blind forced-tail offsets (0, 2, 2, 3, 1) == prior
== re-derived ground truth on all five windows (flips at
184/153/170/367/592); mp flip wards (dps 40): SCR sign det
G_21/G_22 = +1/-1, w9 sign det G_184/G_185 = +1/-1 -- the pivot
field is exact arithmetic, not f64; typing: coefficient-field
pass, NOT a parametrix (OPEN).  LEG D: s-dressed Schur identity
re-gated on rungs 9/12, worst dev 2.4e-13 over the s-grid;
ladder (h -> dist = 1/lambda_max - 1): 96 -> 8.60e-5, 103 ->
1.87e-4, 142 -> 3.06e-5, 151 -> 7.65e-5, 168 -> 7.82e-5, 184 ->
1.68e-4, 203 -> 2.88e-5, 313 -> 1.44e-5, 364 -> 2.79e-6, 591 ->
6.66e-7 (lambda_max 0.999813..0.999999 < 1 on 10/10 -- the
wall): trend slope -2.87 dec/dec, Spearman -0.806 (not
monotone rung-by-rung, honest) => NOPOLE_TREND(APPROACHING) --
the nearest real zero of tau_w(s) approaches s = 1 cofinally
(MEASUREMENT); augmented row: RAW lambda_max 4.34..7.04 (=
|f|^2 4.15..6.87 dominates: corner-mass statement, typed) =>
AUG_RAW_CROSSES_ONE on 10/10; UNIT direction row lambda_max
1.17..1.28 > 1 on 10/10 => AUG_UNIT_CROSSES_ONE -- even the
direction-normalized border row pushes the top eigenvalue
ACROSS the wall: the augmented family carries a real zero at
s < 1 on every rung -- the coupling ENDANGERS a naive bordered
spectral no-pole path (measured, typed, no theorem);
interlacing ward exact (worst rel violation 2.1e-16).  LEG E:
e1 swapped border index breaks the w9 anchor by 5.6e+00 =
3.8e+12 x honest 1.5e-12; e2 omitted coupling freezes D at B =
8.3824, dev 7.7e+00 = 5.3e+12 x honest; e3 oracle mutant
flagged by the AST audit (blind scope stays clean); e4 SMOOTH
alias max |rho_{n>=1}|/rho_0 = 7.6e-23 (bar 1e-18): the
coupling term vanishes identically on the self-aliased source.
READING (typed, no upgrade): the indivisible object HAS an
exact one-step law -- the pair (tau, tau^aug) closes under a
two-term recursion whose ONLY world-sign carrier is the base
pivot a_n while the coupling coefficient b_n is a source-sign-
pure negative square; the cocycle is a monotone drain on MAIN
through the entire free window and its increment law breaks
exactly at the control base flips (the r256 firewall reproduced
INSIDE the coupled dynamics); the frozen micro-falsifier is
passed at the coefficient-field level (blind, route-
independent) -- the parametrix-level pass stays OPEN; the
no-pole indicator approaches s = 1 cofinally on the 10-rung
ladder while BOTH augmented variants cross the wall: the
coupled object's own zero structure sits BELOW s = 1 -- any
no-pole path must go through the PAIR dynamics (the drain),
not through a bordered spectral bound.  Runtime 27.9 s full /
0.3 s smoke; run1/run2 identical up to WALL.  AMENDMENTS AFTER
FREEZE: NONE.

NO RH CLAIM IN EITHER DIRECTION.  NOT evidence for or against RH.
"""

from __future__ import annotations

import argparse
import ast
import hashlib
import math
import os
import sys
import time

import numpy as np
import mpmath as mp

HERE = os.path.dirname(os.path.abspath(__file__))
if HERE not in sys.path:
    sys.path.insert(0, HERE)

import bordered_hankel_probe as BH           # noqa: E402 r244
import hirota_sign_probe as HS               # noqa: E402 r226
import port_integrable_kernel_probe as PIK   # noqa: E402 v881
import principal_bessel_probe as PB          # noqa: E402 r243
import v563_paper2_readouts as core          # noqa: E402 READ-ONLY

MAIN_WINDOWS = (9, 13)
TAIL_WINDOWS = (9, 12, 13, 26, 40)
PRIOR_OFFSETS = (0, 2, 2, 3, 1)
CTRL_FLIPS = {"EPSTEIN": 25, "SCRAMBLE": 21, "SMOOTH": 27}
FIB_LO = 8
EXT = 6
TSTEP_BAR_MAIN = 1e-6
TSTEP_BAR_CTRL = 1e-4
CPL_BAR_MAIN = 1e-6
CPL_BAR_CTRL = 1e-3
ANCHOR_BAR = 1e-9
MP_TRUNCS = (12, 24)
MP_TRUNC_DPS = 220
MP_TRUNC_BAR_MAIN = 1e-12
MP_TRUNC_BAR_CTRL = 1e-6
RESOLVE_MAIN = 1e-7
RESOLVE_CTRL = 1e-2
HEAD_K = 8
TAIL_K = 5
SEP_CHK_FIX = 16
SEP_BAR = 1.0
MP_FLIP_DPS = 40
KZ_LADDER = (17, 10, 18, 12, 13, 9, 15, 19, 26, 40)
ID_RUNGS = (9, 12)
S_GRID = (0.25, 0.5, 0.75, 0.9, 1.0)
ID_BAR = 1e-9
INTERLACE_TOL = 1e-8
SPEAR_BAR = 0.5
SM_ALIAS_BAR = 1e-18
LOUD = 1e3
CAL_VERDICT = (
    "COUPLED_RECURSION_EXACT(a chain-consuming, b source-sign-"
    "pure) + COCYCLE_LAW_FOUND(monotone drain; breaks at flips "
    "21/25/27) + NO_EARLY_SEPARATION(0.84 dec) + "
    "MICROFALSIFIER_PASSED(blind: coeff-field) + "
    "NOPOLE_TREND(APPROACHING, slope -2.87, spearman -0.806) + "
    "AUG_RAW_CROSSES_ONE + AUG_UNIT_CROSSES_ONE")

SPEC_SHA = hashlib.sha256(__doc__.encode("utf-8")).hexdigest()
T0_WALL = time.time()
CHECKS: list = []


def check(name, ok, detail):
    ok = bool(ok)
    CHECKS.append((name, ok, detail))
    print("  [%s] %-42s %s" % ("PASS" if ok else "FAIL", name, detail),
          flush=True)
    return ok


def info(msg):
    print("  [INFO] " + msg, flush=True)


def section(t):
    print("\n" + "-" * 78 + "\n" + t + "\n" + "-" * 78, flush=True)


def firewall_audit():
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    forb = {"zeta" + "zero", "n" + "zeros", "prime" + "range",
            "is" + "prime", "gram" + "point"}
    bad = []
    for node in ast.walk(tree):
        nm = node.attr if isinstance(node, ast.Attribute) else (
            node.id if isinstance(node, ast.Name) else None)
        if nm and nm.lower() in forb:
            bad.append("%s@%d" % (nm, node.lineno))
    return (not bad), ("NO zero/prime oracles; the pair recursion "
                       "consumes node positions + signed weights + "
                       "the r244 chain readouts ONLY; ground truth "
                       "(flip degrees, forced-tail offsets) enters "
                       "gates only" if not bad else "; ".join(bad))


# ------------------------------------------------ predictor (BLIND)
def blind_flip_predictor(xu, wu, n_hi):
    """SOURCE-ONLY pivot-sign field: consumes node positions and
    signed weights, builds the sealed scaled-Chebyshev Gram, and
    scans the principal-minor sign sequence by slogdet.  Returns
    the list of degrees n with pivot sign(det G_{n+1}/det G_n) < 0.
    AST-audited scope: never touches any chain array."""
    lo, hi = float(np.min(xu)), float(np.max(xu))
    mid, rad = 0.5 * (lo + hi), 0.5 * (hi - lo)
    t = (np.asarray(xu, float) - mid) / rad
    P = np.empty((n_hi, len(t)))
    P[0] = 1.0
    if n_hi > 1:
        P[1] = 2.0 * t
    for k in range(2, n_hi):
        P[k] = 2.0 * t * P[k - 1] - P[k - 2]
    G = (P * wu) @ P.T
    prev = 1.0
    out = []
    for n in range(1, n_hi + 1):
        s, _ld = np.linalg.slogdet(G[:n, :n])
        if s * prev < 0 or s == 0.0:
            out.append(n - 1)
        prev = s
    return out


def oracle_predictor(p, n_hi):
    """DELIBERATE MUST-FAIL MUTANT: reads the chain sign field
    directly -- the predictor AST audit must FLAG this scope."""
    return [r["n"] for r in p["rows"][:n_hi] if r["sg_h"] < 0]


def predictor_scope_audit(funcname):
    """walk ONLY the named function's subtree; flag any chain-array
    identifier or dict key from the sealed forbidden set."""
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    forb = {"sg_h", "lg_h", "gam_next", "nf", "hv", "Fv", "rho",
            "fb", "rows", "wpack", "bord_chain", "signed_chain",
            "eta"}
    hits = []
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == funcname:
            for sub in ast.walk(node):
                nm = None
                if isinstance(sub, ast.Attribute):
                    nm = sub.attr
                elif isinstance(sub, ast.Name):
                    nm = sub.id
                elif isinstance(sub, ast.Constant) \
                        and isinstance(sub.value, str):
                    nm = sub.value
                if nm in forb:
                    hits.append("%s@%d" % (nm, sub.lineno))
    return hits


# --------------------------------------------------- gram utilities
def u_matrix(xs, x0, rh, nmax):
    t = (np.asarray(xs, float) - x0) / rh
    P = np.empty((nmax, len(t)))
    P[0] = 1.0
    if nmax > 1:
        P[1] = 2.0 * t
    for n in range(2, nmax):
        P[n] = 2.0 * t * P[n - 1] - P[n - 2]
    return P


def union_arrays(d):
    return (np.concatenate([d["xs"], d["ys"]]),
            np.concatenate([d["ws"], -d["vs"]]))


def world_block(p):
    """direct-route material: scaled-Cheb Gram + border column +
    per-degree slogdets of G_n and of the bordered A_n."""
    d, dsm = p["d"], p["dsm"]
    N = p["N"]
    xu, wu = union_arrays(d)
    bx, bw = union_arrays(dsm)
    lo = min(float(np.min(xu)), float(np.min(bx)))
    hi = max(float(np.max(xu)), float(np.max(bx)))
    x0, rh = 0.5 * (lo + hi), 0.5 * (hi - lo)
    P = u_matrix(xu, x0, rh, N)
    TB = u_matrix(bx, x0, rh, N)
    G = (P * wu) @ P.T
    tv = TB @ bw
    B = float(p["S"][N - 2]) + 5.0 / 7.0
    sg = np.zeros(N + 1)
    lg = np.zeros(N + 1)
    sa = np.zeros(N + 1)
    la = np.zeros(N + 1)
    for n in range(1, N + 1):
        sg[n], lg[n] = np.linalg.slogdet(G[:n, :n])
        A = np.zeros((n + 1, n + 1))
        A[:n, :n] = G[:n, :n]
        A[:n, n] = tv[:n]
        A[n, :n] = tv[:n]
        A[n, n] = B
        sa[n], la[n] = np.linalg.slogdet(A)
    return dict(x0=x0, rh=rh, B=B, sg=sg, lg=lg, sa=sa, la=la,
                xu=xu, wu=wu)


def pair_recursion(p, B, lc, mutate=None):
    """the LEG-A recursion in signed-log arithmetic, chain-side
    only; seeds tau_1 = h_0, tau^aug_1 = h_0 B - F_0^2.  Returns
    per-degree (s_tau, l_tau, s_aug, l_aug) arrays (index n) plus
    the full-depth D.  mutate: None | 'swap' (F_{n+1} for F_n) |
    'omit' (drop the coupling term)."""
    rows = p["rows"]
    N = p["N"]
    lgF = [math.log(max(abs(r["fb"]), 1e-300)) + r["Ls"]
           for r in rows]
    f_on = [r["fb"] != 0.0 for r in rows]
    s_t = rows[0]["sg_h"]
    l_t = rows[0]["lg_h"]
    seed = s_t * math.exp(l_t) * B \
        - (rows[0]["fb"] * math.exp(rows[0]["Ls"])) ** 2
    s_a = math.copysign(1.0, seed)
    l_a = math.log(abs(seed))
    ST = np.zeros(N + 1)
    LT = np.zeros(N + 1)
    SA = np.zeros(N + 1)
    LA = np.zeros(N + 1)
    ST[1], LT[1], SA[1], LA[1] = s_t, l_t, s_a, l_a
    for n in range(1, N):
        j = n if mutate != "swap" else min(n + 1, N - 1)
        lc2 = 2.0 * n * lc
        s_t2 = s_t * rows[n]["sg_h"]
        l_t2 = l_t + lc2 + rows[n]["lg_h"]
        sA_ = s_a * rows[n]["sg_h"]
        lA_ = l_a + lc2 + rows[n]["lg_h"]
        if mutate == "omit" or not f_on[j]:
            s_a2, l_a2 = sA_, lA_
        else:
            lB_ = l_t + lc2 + 2.0 * lgF[j]
            m_ = max(lA_, lB_)
            v = sA_ * math.exp(lA_ - m_) - s_t * math.exp(lB_ - m_)
            if v == 0.0:
                s_a2, l_a2 = 0.0, -1e30
            else:
                s_a2 = math.copysign(1.0, v)
                l_a2 = m_ + math.log(abs(v))
        s_t, l_t, s_a, l_a = s_t2, l_t2, s_a2, l_a2
        ST[n + 1], LT[n + 1] = s_t, l_t
        SA[n + 1], LA[n + 1] = s_a, l_a
    D_N = s_a * s_t * math.exp(l_a - l_t)
    return ST, LT, SA, LA, D_N


def mp_trunc_ward(p, n_t, dps, Bt):
    """r253-t3 pattern: monomial mp Hankel truncation, det ratio
    of the bordered/unbordered moment matrices vs the f64 chain
    reference B_t - S_{n_t-1}."""
    mp.mp.dps = dps
    d, dsm = p["d"], p["dsm"]
    xu = [mp.mpf(float(v)) for v in d["xs"]] \
        + [mp.mpf(float(v)) for v in d["ys"]]
    wu = [mp.mpf(float(v)) for v in d["ws"]] \
        + [-mp.mpf(float(v)) for v in d["vs"]]
    bx = [mp.mpf(float(v)) for v in dsm["xs"]] \
        + [mp.mpf(float(v)) for v in dsm["ys"]]
    bw = [mp.mpf(float(v)) for v in dsm["ws"]] \
        + [-mp.mpf(float(v)) for v in dsm["vs"]]
    mk = []
    pw = [mp.mpf(1)] * len(xu)
    for _k in range(2 * n_t - 1):
        mk.append(mp.fsum(w * q for w, q in zip(wu, pw)))
        pw = [q * x for q, x in zip(pw, xu)]
    tk = []
    pb = [mp.mpf(1)] * len(bx)
    for _k in range(n_t):
        tk.append(mp.fsum(w * q for w, q in zip(bw, pb)))
        pb = [q * y for q, y in zip(pb, bx)]
    H = mp.matrix(n_t, n_t)
    Ha = mp.matrix(n_t + 1, n_t + 1)
    for i in range(n_t):
        for j in range(n_t):
            H[i, j] = mk[i + j]
            Ha[i, j] = mk[i + j]
        Ha[i, n_t] = tk[i]
        Ha[n_t, i] = tk[i]
    Ha[n_t, n_t] = mp.mpf(Bt)
    D_tr = mp.det(Ha) / mp.det(H)
    ref = mp.mpf(Bt) - mp.mpf(float(p["S"][n_t - 1]))
    return float(abs(D_tr / ref - 1))


def mp_flip_ward(xu, wu, nlist, dps):
    """exact-precision determinants of the SAME scaled-Cheb source
    Gram at the sealed flip-adjacent sizes; returns {n: sign}."""
    mp.mp.dps = dps
    lo, hi = float(np.min(xu)), float(np.max(xu))
    x0 = mp.mpf(0.5 * (lo + hi))
    rh = mp.mpf(0.5 * (hi - lo))
    xs = [mp.mpf(float(v)) for v in xu]
    ws = [mp.mpf(float(v)) for v in wu]
    tv = [(x - x0) / rh for x in xs]
    n_hi = max(nlist)
    P = [[mp.mpf(1)] * len(xs), [2 * t for t in tv]]
    for _k in range(2, n_hi):
        P.append([2 * t * a - b
                  for t, a, b in zip(tv, P[-1], P[-2])])
    G = mp.matrix(n_hi, n_hi)
    for i in range(n_hi):
        for j in range(i, n_hi):
            v = mp.fsum(w * a * b for w, a, b in zip(ws, P[i], P[j]))
            G[i, j] = v
            G[j, i] = v
    return {n: int(mp.sign(mp.det(G[:n, :n]))) for n in nlist}


def spearman(x, y):
    rx = np.argsort(np.argsort(np.asarray(x, float)))
    ry = np.argsort(np.argsort(np.asarray(y, float)))
    rx = rx - rx.mean()
    ry = ry - ry.mean()
    return float((rx @ ry)
                 / math.sqrt(float(rx @ rx) * float(ry @ ry)))


# --------------------------------------------------------------- main
def main():
    par = argparse.ArgumentParser()
    par.add_argument("--smoke", action="store_true")
    args = par.parse_args()
    smoke = args.smoke
    windows = (9,) if smoke else MAIN_WINDOWS

    print("=" * 78)
    print("coupledtau_probe -- PRIME.PORT.RHP.FULLSOURCE."
          "COUPLEDTAU.01 (round 257)")
    print("SPEC_SHA %s   F_DEF_SHA %s (imported r243)"
          % (SPEC_SHA[:16], PB.F_DEF_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 only, ladder rung 9, mp wards "
                        "+ five-window tail + separation skipped)"
                        if smoke else "FULL RECORD"))
    print("=" * 78)

    section("S0  FIREWALL + PREDEFINITION")
    okf, det = firewall_audit()
    check("G01-firewall", okf, det)
    check("G02-predefinition", True,
          "MAIN OBJECT: the PAIR (tau_n, tau^aug_n) with the sealed "
          "two-term recursion tau_{n+1} = a_n tau_n, tau^aug_{n+1} "
          "= a_n tau^aug_n + b_n tau_n, a_n = c_n^2 h_n, b_n = "
          "-(c_n F_n)^2, D_{n+1} = D_n - rho_n; basis U_k((x-x0)/"
          "rh) on the union+border hull (c_k = (2/rh)^k exact); "
          "gates vs direct per-degree slogdet on ALL degrees + mp "
          "truncations %s (dps %d) + mp flip wards (dps %d); "
          "cocycle = (log10 |D_n|, sign D_n) with sealed zones "
          "HEAD < %d / TAIL last %d; micro-falsifier: blind "
          "source-only pivot field vs flips %s + forced tail %s; "
          "NoPole ladder %s; ALL bars + verdict rules sealed in "
          "the frozen spec BEFORE evaluation"
          % (str(MP_TRUNCS), MP_TRUNC_DPS, MP_FLIP_DPS, HEAD_K,
             TAIL_K, str(CTRL_FLIPS), str(PRIOR_OFFSETS),
             str(KZ_LADDER)))

    # ---------------- S1: census + controls
    section("S1  CENSUS + CONTROLS + POSITIVITY TYPING")
    packs = {("w%d" % kz): BH.wpack(kz) for kz in windows}
    rr9 = core.build_window(9)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE = PIK.lambda_eps(N_E)
    nn_idx = np.nonzero(np.abs(lamE) > 1e-12)[0]
    ug9, uw9 = PB.smooth_comb(rr9["alpha"])
    ctrl_defs = (("EPST", dict(comb=(
        np.log(nn_idx.astype(float)),
        2.0 * lamE[nn_idx] / np.sqrt(nn_idx.astype(float))))),
        ("SCR", dict(scramble_seed=1)),
        ("SMOOTH", dict(comb=(ug9, uw9))))
    ctrl = {c: BH.wpack(9, base_kw=kw) for c, kw in ctrl_defs}
    long_names = {"EPST": "EPSTEIN", "SCR": "SCRAMBLE",
                  "SMOOTH": "SMOOTH"}
    okC = all(packs[t]["nf"] is None for t in packs)
    okCf = all(ctrl[c]["nf"] == CTRL_FLIPS[long_names[c]]
               for c in ctrl)
    pmax = {t: packs[t]["N"] for t in packs}
    pmax.update({c: ctrl[c]["nf"] for c in ctrl})
    check("G10-census-controls", okC and okCf,
          "MAIN free prefix positive at full depth (%s), typed "
          "POSITIVE_PREFIX; control flips re-derived %s, typed "
          "INDEFINITE_CONTINUATION beyond pmax (r256 firewall "
          "adopted); N = %s"
          % (str(sorted(packs)), str({c: ctrl[c]["nf"]
                                      for c in ctrl}),
             str({t: packs[t]["N"] for t in packs})))

    worlds = list(packs.items()) + list(ctrl.items())

    # ---------------- S2: LEG A -- the coupled recursion
    section("S2  LEG A -- THE COUPLED PAIR RECURSION (exact)")
    tstep_main = tstep_ctrl = 0.0
    cpl_main = cpl_ctrl = 0.0
    anchor_worst = 0.0
    b_ok = True
    inc_ok = True
    n_res = n_tot = 0
    WB = {}
    RC = {}
    a_note = []
    for tag, p in worlds:
        wb = world_block(p)
        WB[tag] = wb
        N = p["N"]
        lc = math.log(2.0 / wb["rh"])
        is_main = tag in packs
        # (a1) tau-step gate at all degrees
        dev_t = 0.0
        for n in range(1, N):
            step = wb["lg"][n + 1] - wb["lg"][n]
            pred = 2.0 * n * lc + p["rows"][n]["lg_h"]
            dev_t = max(dev_t, abs(step - pred))
            if wb["sg"][n + 1] * wb["sg"][n] != p["rows"][n]["sg_h"]:
                dev_t = max(dev_t, 2.0)
        # (a2) coupled propagation
        ST, LT, SA, LA, D_N = pair_recursion(p, wb["B"], lc)
        RC[tag] = (ST, LT, SA, LA, D_N)
        dev_c = 0.0
        for n in range(1, N + 1):
            dev_c = max(dev_c, abs(LT[n] - wb["lg"][n]),
                        abs(LA[n] - wb["la"][n]),
                        abs(ST[n] - wb["sg"][n]),
                        abs(SA[n] - wb["sa"][n]))
        # (a3) anchor
        anchor = 5.0 / 7.0 - float(p["rho"][N - 1])
        anchor_worst = max(anchor_worst, abs(D_N / anchor - 1.0))
        # (a5) typology: b_n <= 0 (squares) + increment signs on
        # the direct route at resolvable degrees
        floor = RESOLVE_MAIN if is_main else RESOLVE_CTRL
        for n in range(1, N):
            b_ok = b_ok and (-(p["rows"][n]["fb"] ** 2) <= 0.0)
            D_lo = wb["sa"][n] * wb["sg"][n] \
                * math.exp(wb["la"][n] - wb["lg"][n])
            D_hi = wb["sa"][n + 1] * wb["sg"][n + 1] \
                * math.exp(wb["la"][n + 1] - wb["lg"][n + 1])
            rho_n = float(p["rho"][n])
            n_tot += 1
            if abs(rho_n) >= floor * max(abs(D_lo), abs(D_hi),
                                         1e-300):
                n_res += 1
                inc_ok = inc_ok and (
                    math.copysign(1.0, D_hi - D_lo)
                    == -p["rows"][n]["sg_h"])
        if is_main:
            tstep_main = max(tstep_main, dev_t)
            cpl_main = max(cpl_main, dev_c)
        else:
            tstep_ctrl = max(tstep_ctrl, dev_t)
            cpl_ctrl = max(cpl_ctrl, dev_c)
        a_note.append("%s tstep %.1e cpl %.1e D_N %+.6f" %
                      (tag, dev_t, dev_c, D_N))
    check("G20-tau-step",
          tstep_main <= TSTEP_BAR_MAIN
          and tstep_ctrl <= TSTEP_BAR_CTRL,
          "slogdet(G_{n+1}) - slogdet(G_n) == 2n log(2/rh) + "
          "log|h_n| AND sign == sg h_n at ALL n on ALL worlds: "
          "MAIN worst %.1e (bar %.0e), controls %.1e (bar %.0e, "
          "f64 chain floor on flipped worlds, r253-a1 precedent)"
          % (tstep_main, TSTEP_BAR_MAIN, tstep_ctrl,
             TSTEP_BAR_CTRL))
    check("G21-coupled-step",
          cpl_main <= CPL_BAR_MAIN and cpl_ctrl <= CPL_BAR_CTRL,
          "the signed-log PAIR propagation (chain-side seeds + "
          "coefficients ONLY) vs the direct bordered slogdet at "
          "every degree: %s -- MAIN worst %.1e (bar %.0e), "
          "controls %.1e (bar %.0e); ALL signs of BOTH tau "
          "components match at EVERY degree on EVERY world "
          "(mismatch would count 2.0)"
          % ("; ".join(a_note), cpl_main, CPL_BAR_MAIN, cpl_ctrl,
             CPL_BAR_CTRL))
    check("G22-anchor", anchor_worst <= ANCHOR_BAR,
          "full-depth anchor D_N(recursion) == 5/7 - rho_{N-1}: "
          "worst rel %.1e (bar %.0e) on all %d worlds"
          % (anchor_worst, ANCHOR_BAR, len(worlds)))
    if not smoke:
        tr_note = []
        tr_main = tr_ctrl = 0.0
        for n_t in MP_TRUNCS:
            dv = mp_trunc_ward(packs["w9"], n_t, MP_TRUNC_DPS,
                               5.0 / 7.0)
            tr_main = max(tr_main, dv)
            tr_note.append("w9 n_t=%d %.1e" % (n_t, dv))
        for n_t in MP_TRUNCS:
            dv = mp_trunc_ward(ctrl["SCR"], n_t, MP_TRUNC_DPS,
                               5.0 / 7.0)
            tr_ctrl = max(tr_ctrl, dv)
            tr_note.append("SCR n_t=%d %.1e" % (n_t, dv))
        check("G23-mp-truncation-ward",
              tr_main <= MP_TRUNC_BAR_MAIN
              and tr_ctrl <= MP_TRUNC_BAR_CTRL,
              "monomial mp Hankel truncations (dps %d, corner 5/7)"
              ": %s -- w9 bar %.0e (f64 reference floor), SCRAMBLE "
              "bar %.0e (n_t = 24 spans the flip 21: the pair "
              "recursion is exact THROUGH the indefinite "
              "continuation)" % (MP_TRUNC_DPS, "; ".join(tr_note),
                                 MP_TRUNC_BAR_MAIN,
                                 MP_TRUNC_BAR_CTRL))
    else:
        check("G23-mp-truncation-ward", True, "SMOKE: skipped")
    check("G24-coefficient-typology", b_ok and inc_ok,
          "b_n = -(c_n F_n)^2 <= 0 at EVERY degree on EVERY world "
          "(source-sign-pure coupling: a negative square, sign "
          "free of the chain); direct-route D-increment sign == "
          "-sg h_n at all %d resolvable of %d degrees (floors "
          "%.0e/%.0e typed): the BASE PIVOT ALONE carries the "
          "world sign, the border contributes a nonnegative "
          "magnitude" % (n_res, n_tot, RESOLVE_MAIN, RESOLVE_CTRL))

    # ---------------- S3: LEG B -- the coupled budget cocycle
    section("S3  LEG B -- THE COUPLED BUDGET COCYCLE")
    mono_ok = True
    mono_note = []
    for t in packs:
        p = packs[t]
        rmin = float(np.min(p["rho"][:p["N"]]))
        mono_ok = mono_ok and rmin > 0.0
        mono_note.append("%s min rho %.1e at n=%d"
                         % (t, rmin,
                            int(np.argmin(p["rho"][:p["N"]]))))
    check("G30-main-monotone-drain", mono_ok,
          "MAIN increment law: D_{n+1} - D_n = -rho_n with rho_n "
          "> 0 at EVERY degree through the ENTIRE free window "
          "(%s): the cocycle is a sign-definite monotone drain -- "
          "COCYCLE_LAW_FOUND arm 1" % "; ".join(mono_note))
    brk_ok = True
    brk_note = []
    for c in ctrl:
        p = ctrl[c]
        first = next((n for n in range(p["N"])
                      if float(p["rho"][n]) < 0.0), None)
        brk_ok = brk_ok and (first == CTRL_FLIPS[long_names[c]])
        brk_note.append("%s first rho<0 at n=%s (flip %d)"
                        % (c, first, CTRL_FLIPS[long_names[c]]))
    check("G31-control-break-at-flips", brk_ok,
          "the increment law breaks FIRST exactly at the r256 "
          "base flips: %s -- the cocycle inherits the positive-"
          "prefix firewall degree-exactly (COCYCLE_LAW_FOUND arm "
          "2)" % "; ".join(brk_note))
    for tag, p in worlds:
        N = p["N"]
        S = p["S"]
        St = float(S[N - 1])
        zh = float(S[HEAD_K - 1])
        zb = float(S[N - TAIL_K - 1]) - zh
        zt = St - zh - zb
        wb = WB[tag]
        Dv = [wb["B"]] + [wb["sa"][n] * wb["sg"][n]
                          * math.exp(wb["la"][n] - wb["lg"][n])
                          for n in (HEAD_K, N - TAIL_K, N)]
        drops = [math.log10(max(abs(Dv[i]), 1e-300))
                 - math.log10(max(abs(Dv[i + 1]), 1e-300))
                 for i in range(3)]
        info("%-6s zones sum rho H/B/T %+.3e/%+.3e/%+.3e "
             "shares %.6g/%.6g/%.6g | log10|D| drop %.3f/%.3f/"
             "%.3f%s"
             % (tag, zh, zb, zt, zh / St, zb / St, zt / St,
                drops[0], drops[1], drops[2],
                "" if tag in packs else
                " [INDEFINITE_CONTINUATION beyond n=%d]"
                % pmax[tag]))
    check("G32-zone-anatomy", True,
          "sealed zones HEAD n < %d / BULK / TAIL last %d: the "
          "coupling term is the SOLE n-dynamics and acts as a "
          "PURE DRAIN in every zone on MAIN (head-loaded, r246 "
          "reproduced: rho_0 dominates; the tail refreshes the "
          "drain); control zone rows are algebraic tau-quotient "
          "statements beyond pmax (typed, not Hilbert-space)"
          % (HEAD_K, TAIL_K))
    if not smoke:
        sep_note = []
        sep_best = 0.0
        for c in ctrl:
            for nchk in (SEP_CHK_FIX, pmax[c]):
                DM = WB["w9"]["sa"][nchk] * WB["w9"]["sg"][nchk] \
                    * math.exp(WB["w9"]["la"][nchk]
                               - WB["w9"]["lg"][nchk])
                DC = WB[c]["sa"][nchk] * WB[c]["sg"][nchk] \
                    * math.exp(WB[c]["la"][nchk]
                               - WB[c]["lg"][nchk])
                sep = abs(math.log10(max(abs(DM), 1e-300))
                          - math.log10(max(abs(DC), 1e-300)))
                sep_best = max(sep_best, sep)
                sep_note.append("%s@n=%d %.3f" % (c, nchk, sep))
        vSep = ("WORLD_SEP_PRETERMINAL(%.2f dec)" % sep_best
                if sep_best >= SEP_BAR
                else "NO_EARLY_SEPARATION(%.2f dec)" % sep_best)
        check("G33-preterminal-separation", True,
              "cocycle world separation at the sealed checkpoints "
              "{%d, pmax_W}: %s (bar %.1f dec) => %s -- honest: "
              "the old R4 answer in the new coordinate"
              % (SEP_CHK_FIX, "; ".join(sep_note), SEP_BAR, vSep))
    else:
        vSep = "SEP_SMOKE_NA"
        check("G33-preterminal-separation", True, "SMOKE: skipped")

    # ---------------- S4: LEG C -- the micro-falsifier
    section("S4  LEG C -- THE MICRO-FALSIFIER (blind)")
    hits_blind = predictor_scope_audit("blind_flip_predictor")
    check("G40-predictor-ast-clean", not hits_blind,
          "the blind predictor scope consumes node positions + "
          "signed weights ONLY (sealed forbidden set: chain "
          "arrays sg_h/lg_h/gam_next/hv/Fv/rho/fb/nf + builder "
          "names): %s"
          % ("CLEAN" if not hits_blind else "; ".join(hits_blind)))
    flips_ok = True
    fl_note = []
    for c in ctrl:
        xu, wu = WB[c]["xu"], WB[c]["wu"]
        fl = blind_flip_predictor(xu, wu, ctrl[c]["N"])
        first = fl[0] if fl else None
        ok = (first == CTRL_FLIPS[long_names[c]]
              == ctrl[c]["nf"])
        flips_ok = flips_ok and ok
        fl_note.append("%s -> %s (truth %s)"
                       % (c, first, ctrl[c]["nf"]))
    check("G41-blind-control-flips", flips_ok,
          "blind source-only pivot field predicts the w9 control "
          "flips: %s -- 3/3 (ground truth = re-derived wpack "
          "chain, gates only)" % "; ".join(fl_note))
    if not smoke:
        tail_ok = True
        tl_note = []
        pred_offs = []
        true_offs = []
        for i, w in enumerate(TAIL_WINDOWS):
            d = HS.window_data(w)
            N = d["n_max"]
            xu, wu = union_arrays(d)
            fl = blind_flip_predictor(xu, wu, N + EXT)
            first = fl[0] if fl else None
            rows = BH.bord_chain(d["xs"], d["ws"], d["ys"],
                                 d["vs"], d["xs"][:2],
                                 d["ws"][:2] * 0.0, d["ys"][:2],
                                 d["vs"][:2] * 0.0, N + EXT + 1)
            truth = next((r["n"] for r in rows
                          if r["sg_h"] < 0), None)
            pred_offs.append(None if first is None else first - N)
            true_offs.append(None if truth is None else truth - N)
            ok = (first == truth
                  and first - N == PRIOR_OFFSETS[i])
            tail_ok = tail_ok and ok
            tl_note.append("w%d N=%d pred %s truth %s" %
                           (w, N, first, truth))
        check("G42-blind-forced-tail", tail_ok,
              "blind forced-tail survival on the five windows: "
              "predicted offsets %s == ground truth %s == the "
              "frozen prior %s (%s) -- the coefficient field "
              "predicts BOTH sides of the falsifier"
              % (str(tuple(pred_offs)), str(tuple(true_offs)),
                 str(PRIOR_OFFSETS), "; ".join(tl_note)))
        s_scr = mp_flip_ward(WB["SCR"]["xu"], WB["SCR"]["wu"],
                             (21, 22), MP_FLIP_DPS)
        s_w9 = mp_flip_ward(WB["w9"]["xu"], WB["w9"]["wu"],
                            (184, 185), MP_FLIP_DPS)
        ok_mp = (s_scr[21] > 0 and s_scr[22] < 0
                 and s_w9[184] > 0 and s_w9[185] < 0)
        check("G43-mp-flip-wards", ok_mp,
              "exact-precision (dps %d) determinants of the SAME "
              "source Gram: SCR sign det G_21/G_22 = %+d/%+d "
              "(flip at 21), w9 sign det G_184/G_185 = %+d/%+d "
              "(forced-tail flip at 184 = N_w + 0): the pivot "
              "field is exact arithmetic, not f64"
              % (MP_FLIP_DPS, s_scr[21], s_scr[22], s_w9[184],
                 s_w9[185]))
        vC = ("MICROFALSIFIER_PASSED(blind: coeff-field)"
              if (flips_ok and tail_ok and ok_mp and not hits_blind)
              else ("MICROFALSIFIER_PARTIAL(flips %s, tail %s)"
                    % (flips_ok, tail_ok)
                    if (flips_ok or tail_ok)
                    else "MICROFALSIFIER_FAILED"))
    else:
        check("G42-blind-forced-tail", True, "SMOKE: skipped")
        check("G43-mp-flip-wards", True, "SMOKE: skipped")
        vC = "MICROFALSIFIER_SMOKE_NA"
    info("HONEST TYPING (sealed): the pass certifies the coupled "
         "recursion's coefficient field as falsifier-compliant "
         "via a route-independent source-only computation; a "
         "PARAMETRIX/local-connection pass stays OPEN")

    # ---------------- S5: LEG D -- no-pole connection in s
    section("S5  LEG D -- NO-POLE CONNECTION IN s (MEASUREMENT)")
    ladder = (9,) if smoke else KZ_LADDER
    hs_l, dist_l = [], []
    wall_ok = True
    inter_worst = 0.0
    raw_cross = unit_cross = 0
    lad_note = []
    for kz in ladder:
        b = PIK.build_rung(kz)
        h, L, alpha = b["h"], b["L"], b["alpha"]
        xs, ws_, _ = PIK.folded_measure(b["d"], L, +1.0)
        ys, vs, _ = PIK.folded_measure(b["d"], L, -1.0)
        al, be, m0, steps = PIK.lanczos_chain(xs, ws_, h + 1)
        if steps < h + 1:
            wall_ok = False
            continue
        Pn = PIK.eval_chain(al, be, m0, ys, h)
        A = np.sqrt(vs)[:, None] * Pn
        Q = A.T @ A
        ev = np.linalg.eigvalsh(Q)
        lmax = float(ev[-1])
        wall_ok = wall_ok and (lmax < 1.0)
        dist = 1.0 / lmax - 1.0
        bS = PIK.build_rung(kz, comb=PB.smooth_comb(alpha))
        xsS, wsS, _ = PIK.folded_measure(bS["d"], L, +1.0)
        ysS, vsS, _ = PIK.folded_measure(bS["d"], L, -1.0)
        bn = np.concatenate([xsS, ysS])
        bwt = np.concatenate([wsS, -vsS])
        Pb = PIK.eval_chain(al, be, m0, bn, h)
        f = Pb.T @ bwt
        f2 = float(f @ f)
        evr = np.linalg.eigvalsh(Q + np.outer(f, f))
        u = f / math.sqrt(f2)
        evu = np.linalg.eigvalsh(Q + np.outer(u, u))
        spread = float(ev[-1] - ev[0])
        for i in range(len(ev)):
            inter_worst = max(
                inter_worst,
                max(float(ev[i] - evr[i]), 0.0) / max(spread, 1e-300))
            if i + 1 < len(ev):
                inter_worst = max(
                    inter_worst,
                    max(float(evr[i] - ev[i + 1]), 0.0)
                    / max(spread, 1e-300))
        raw_cross += int(float(evr[-1]) >= 1.0)
        unit_cross += int(float(evu[-1]) >= 1.0)
        hs_l.append(h)
        dist_l.append(dist)
        lad_note.append("kz%d h=%d lmax %.6f dist %.2e raw %.3f "
                        "(|f|^2 %.2f) unit %.3f"
                        % (kz, h, lmax, dist, float(evr[-1]), f2,
                           float(evu[-1])))
    for s in lad_note:
        info(s)
    if not smoke:
        id_worst = 0.0
        for kz in ID_RUNGS:
            b = PIK.build_rung(kz)
            h, L = b["h"], b["L"]
            xs, ws_, _ = PIK.folded_measure(b["d"], L, +1.0)
            ys, vs, uf_n = PIK.folded_measure(b["d"], L, -1.0)
            al, be, m0, _ = PIK.lanczos_chain(xs, ws_, h + 1)
            Pn = PIK.eval_chain(al, be, m0, ys, h)
            sq = np.sqrt(vs)
            E = sq[:, None] * (Pn @ Pn.T) * sq[None, :]
            E = 0.5 * (E + E.T)
            tau_m = (2.0 * math.pi * uf_n / L) / b["D"]
            port = tau_m <= float(np.max(tau_m)) / 10.0
            ip, ib = np.where(port)[0], np.where(~port)[0]
            Pp = E[np.ix_(ip, ip)]
            R = E[np.ix_(ib, ib)]
            X = E[np.ix_(ip, ib)]
            for s in S_GRID:
                s1, l1 = np.linalg.slogdet(
                    np.eye(len(E)) - s * E)
                s2, l2 = np.linalg.slogdet(
                    np.eye(len(ib)) - s * R)
                DP = Pp + s * X @ np.linalg.solve(
                    np.eye(len(ib)) - s * R, X.T)
                s3, l3 = np.linalg.slogdet(
                    np.eye(len(ip)) - s * DP)
                id_worst = max(id_worst,
                               abs(l1 - (l2 + l3)),
                               abs(s1 - s2 * s3))
            del E
        check("G50-schur-identity-regate", id_worst <= ID_BAR,
              "det(I - sE) == det(I - sR) det(I - sD_P(s)) with "
              "D_P(s) = P + sX(I - sR)^{-1}X^T re-gated on rungs "
              "%s over the s-grid %s: worst abs-log dev %.1e "
              "(bar %.0e) -- the r224 s-dressed port stands"
              % (str(ID_RUNGS), str(S_GRID), id_worst, ID_BAR))
    else:
        check("G50-schur-identity-regate", True, "SMOKE: skipped")
    if len(hs_l) >= 2:
        slope = float(np.polyfit(np.log10(hs_l),
                                 np.log10(dist_l), 1)[0])
        spear = spearman(hs_l, dist_l)
    else:
        slope, spear = float("nan"), float("nan")
    trend = ("APPROACHING" if spear <= -SPEAR_BAR else
             ("RECEDING" if spear >= SPEAR_BAR else "FLAT"))
    check("G51-nopole-base-ladder", wall_ok,
          "base family tau_w(s) = det(I - sQ_w): lambda_max < 1 "
          "on %d/%d rungs (the wall); NOPOLE.COFINAL indicator "
          "dist = 1/lambda_max - 1 vs N: slope %.2f dec/dec, "
          "Spearman %.3f (sealed bar %.1f) => NOPOLE_TREND(%s) "
          "-- MEASUREMENT, no theorem"
          % (len(hs_l), len(ladder), slope, spear, SPEAR_BAR,
             trend))
    vRaw = ("AUG_RAW_CROSSES_ONE" if raw_cross == len(hs_l)
            else ("AUG_RAW_BELOW_ONE" if raw_cross == 0
                  else "AUG_RAW_MIXED(%d/%d)" % (raw_cross,
                                                 len(hs_l))))
    vUnit = ("AUG_UNIT_CROSSES_ONE" if unit_cross == len(hs_l)
             else ("AUG_UNIT_BELOW_ONE" if unit_cross == 0
                   else "AUG_UNIT_MIXED(%d/%d)" % (unit_cross,
                                                   len(hs_l))))
    check("G52-augmented-zero-structure",
          inter_worst <= INTERLACE_TOL,
          "rank-1 Uvarov border row in the state frame: Cauchy "
          "interlacing exact (worst rel violation %.1e, tol "
          "%.0e); RAW row crosses 1 on %d/%d rungs (mass-driven: "
          "corner |f|^2 >> 1, typed -- a statement about the "
          "aggregated border mass), UNIT direction row crosses 1 "
          "on %d/%d rungs => %s + %s: the augmented family "
          "carries a real zero at s < 1 -- the coupling ENDANGERS "
          "a naive bordered spectral no-pole path (measured, "
          "never upgraded)"
          % (inter_worst, INTERLACE_TOL, raw_cross, len(hs_l),
             unit_cross, len(hs_l), vRaw, vUnit))

    # ---------------- S6: LEG E -- must-fails + anchors
    section("S6  LEG E -- FALSIFIERS + MUST-FAILS")
    p9 = packs["w%d" % windows[0]]
    wb9 = WB["w%d" % windows[0]]
    lc9 = math.log(2.0 / wb9["rh"])
    anchor9 = 5.0 / 7.0 - float(p9["rho"][p9["N"] - 1])
    honest = abs(RC["w%d" % windows[0]][4] / anchor9 - 1.0)
    _, _, _, _, D_swap = pair_recursion(p9, wb9["B"], lc9,
                                        mutate="swap")
    dev_e1 = abs(D_swap / anchor9 - 1.0)
    ok_e1 = dev_e1 >= LOUD * max(honest, 1e-300)
    _, _, _, _, D_omit = pair_recursion(p9, wb9["B"], lc9,
                                        mutate="omit")
    dev_e2 = abs(D_omit / anchor9 - 1.0)
    ok_e2 = dev_e2 >= LOUD * max(honest, 1e-300)
    check("G60-swapped-border-index", ok_e1,
          "coupled step with F_{n+1} in place of F_n: full-depth "
          "anchor dev %.1e = %.1e x honest %.1e (bar %.0f x) -- "
          "the recursion consumes the border index exactly"
          % (dev_e1, dev_e1 / max(honest, 1e-300), honest, LOUD))
    check("G61-omitted-coupling", ok_e2,
          "coupling term dropped (tau^aug_{n+1} = a_n tau^aug_n): "
          "D freezes at B = %.4f, anchor dev %.1e = %.1e x honest "
          "(bar %.0f x) -- the two-term coupling is load-bearing "
          "on MAIN, visibly" % (wb9["B"], dev_e2,
                                dev_e2 / max(honest, 1e-300),
                                LOUD))
    hits_orc = predictor_scope_audit("oracle_predictor")
    check("G62-oracle-predictor-flagged", bool(hits_orc),
          "the deliberately oracle-reading mutant is FLAGGED by "
          "the predictor AST audit (%s) while the blind scope "
          "stays clean: the blindness claim is machine-enforced"
          % ("; ".join(hits_orc) if hits_orc else "NOT FLAGGED"))
    pS = ctrl["SMOOTH"]
    r0 = float(pS["rho"][0])
    r1 = max(abs(float(r)) for r in pS["rho"][1:pS["N"]])
    check("G63-smooth-alias-anchor", r1 / r0 <= SM_ALIAS_BAR,
          "SMOOTH self-alias (border == window): max |rho_{n>=1}| "
          "/ rho_0 = %.1e (bar %.0e) -- F_n = 0 for n >= 1 by "
          "orthogonality, the coupling term vanishes identically: "
          "the pair recursion degenerates to the pure tau-step "
          "exactly when the source does" % (r1 / r0, SM_ALIAS_BAR))

    # ---------------- S7: verdict
    section("S7  VERDICT")
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the exact one-step pair recursion with its "
          "coefficient typology, the cocycle increment law with "
          "its break anatomy, the blind coefficient-field pass of "
          "the frozen micro-falsifier, and the measured no-pole "
          "trend with the augmented-zero warning")
    vA = ("COUPLED_RECURSION_EXACT(a chain-consuming, b source-"
          "sign-pure)"
          if (tstep_main <= TSTEP_BAR_MAIN
              and tstep_ctrl <= TSTEP_BAR_CTRL
              and cpl_main <= CPL_BAR_MAIN
              and cpl_ctrl <= CPL_BAR_CTRL
              and anchor_worst <= ANCHOR_BAR and b_ok and inc_ok)
          else "COUPLED_RECURSION_OPEN")
    vB = ("COCYCLE_LAW_FOUND(monotone drain; breaks at flips "
          "21/25/27)" if (mono_ok and brk_ok)
          else "COCYCLE_STRUCTURELESS")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        verd = " + ".join([vA, vB, vSep, vC,
                           "NOPOLE_TREND(%s, slope %.2f, "
                           "spearman %.3f)" % (trend, slope,
                                               spear),
                           vRaw, vUnit])
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G96-verdict", npass == len(CHECKS),
          "%s%s -- SATZ (machine-gated): the pair recursion + its "
          "coefficient typology + the cocycle increment law; "
          "MEASURED: zone anatomy, pre-terminal separation, "
          "no-pole trend, augmented zero structure; OPEN: any "
          "a-priori bound, the parametrix-level falsifier pass, "
          "the budget bound and the base law (r243/r247/r250/"
          "r251/r253/r256 stand); NO RH claim"
          % (verd, " (SMOKE)" if smoke else ""))
    wall = time.time() - T0_WALL
    check("G99-runtime", wall <= 1800.0,
          "WALL %.1f s (bar 1800)" % wall)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    print("\n" + "=" * 78)
    print("RESULT: %d/%d gates PASS%s   SPEC_SHA %s"
          % (npass, len(CHECKS), " (SMOKE)" if smoke else "",
             SPEC_SHA[:16]))
    print("NO RH CLAIM in either direction.")
    print("=" * 78)
    return 0 if npass == len(CHECKS) else 1


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

_SRC_2 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""budget_anatomy_probe -- PRIME.PORT.RHP.BUDGET.ANATOMY.01
(round 258): the anatomy of the r257 drain and the TERMINAL
REDUCTION.  After r257 (COUPLED_RECURSION_EXACT: the pair (tau,
tau^aug) closes under tau_{n+1} = a_n tau_n, tau^aug_{n+1} = a_n
tau^aug_n + b_n tau_n, equivalently D_{n+1} = D_n - rho_n with
rho_n = F_n^2/h_n >= 0 on MAIN; anchor D_N = 5/7 - rho_{N-1}) the
fiber positivity is the BUDGET INEQUALITY of a monotone drain.
THIS round clarifies the suspected COLLAPSE STRUCTURE: with
B_w = S_{N-2} + 5/7 the budget question telescopes COMPLETELY
onto the single terminal inequality rho_{N-1} < 5/7, i.e.
F_{N-1}^2 < (5/7) h_{N-1} -- and that terminal statement is a
t*-COORDINATE in exact normal form (the return of the r238/r239
coordinate).

EXPLORATION ONLY (2026-08-24).  experiments/ level: NO promotion,
NO ledger row, NO marker moved, NO RH CLAIM in either direction.

INDEX FIREWALL (binding, r238-r257 discipline): w = window (kz),
N_w = builder depth, n/k = chain degree; free pivots h_{w,k}
(k < N_w) are the proof objects; rho_k = F_k^2/h_k, S_n =
sum_{k<=n} rho_k; ground truth (h signs, flip degrees) enters
GATES only; no zero/prime oracles anywhere (AST firewall).
MACHINERY IMPORTED VERBATIM: r244 BH.wpack (chain, rho, S, b1),
r257 CT.u_matrix/union_arrays/mp_trunc_ward/spearman, r254
OG.phat_matrix, r243 PB.smooth_comb, v881 PIK controls.  B
PROVENANCE: B_w = S_{N-2} + 5/7 (r243 amendment a4, IMPORTED,
never fitted).  POSITIVITY TYPING (r256): POSITIVE_PREFIX vs
INDEFINITE_CONTINUATION; controls SCR/EPST/SMOOTH flip 21/25/27.

LEG A -- THE EXACT TELESCOPE IDENTITY (the foundation): (a1) in
what sense does B = S_{N-2} + 5/7 hold?  ANSWER SEALED AS THE
CLAIM UNDER TEST: it is EXACT BY CONSTRUCTION -- B is DEFINED as
prefix data + the imported terminal constant (r243 a4); the
nontrivial exact content is the SCHUR TELESCOPE D_N = B - S_{N-1}
(det factorization), whose combination gives D_N = 5/7 - rho_{N-1}
as an ALGEBRAIC IDENTITY.  Gates: direct bordered slogdet (sealed
scaled-Chebyshev hull basis, r257 route) at FULL depth vs
5/7 - rho_{N-1} on the four main windows w9/w12/w13/w26 AND the
sealed 9-rung ladder sample (indices (0, 5, 10, 15, 20, 25, 30,
35, 41) of the (N, kz)-sorted 42-rung frame-A h <= 900 ladder,
including the largest N = 878); bars 1e-8 mains / 3e-6 deep (f64
route floors from the two disclosed pre-spec scratch
calibrations: worst 1.3e-9 / 9.5e-8; the EXACTNESS claim is
carried by the mp wards, the f64 deviation is CONDITIONING, its
N-slope is printed as the honest error law of the ROUTE, not of
the identity); mp truncation wards (dps 220, r257 pattern,
corner 5/7) at sealed n_t in {12, 24} on w9 AND n_t = 12 on the
largest rung, bar 1e-12.  (a2) WHERE DOES THE 5/7 COME FROM
(source-pure audit): the import chain r243 <- r241 defines 5/7 =
1/(7/5) with 7/5 the FROZEN r241 FLOOR of the measured terminal
ratio h_{N-1}/F_{N-1}^2; gate: reproduce min_w h_{N-1}/F_{N-1}^2
on all 42 in the sealed band [1.40, 1.46] AND >= 7/5 with
NON-SATURATION margin >= 0.01 (the measured floor 1.4278 is NOT
7/5: the constant is a chosen round rational BELOW the measured
surface saturation).  SEALED ADJUDICATION of the two named origin
hypotheses: Q7_SHARE and LEVEL8_SUBTRACTION are NOT_SUPPORTED
unless the floor saturates 7/5 to 1e-6 (it does not) or a
source-pure compile path exists in the import chain (it does
not; the only occurrences are the r241/r243 floor literals) =>
5/7 stays FLOOR_IMPORTED(r241), source derivation OPEN.  (a3)
margin equivalence: sign(D_N) == sign(5/7 - rho_{N-1}) on the
full sample AND on the w9 controls (there ALGEBRAIC, typed
INDEFINITE_CONTINUATION); on MAIN both sides positive.  If any
telescope gate fails: TELESCOPE_APPROX with the measured error
law -- the budget question is then typed TWO-TERM (terminal +
residual).

LEG B -- THE TERMINAL INEQUALITY OVER THE LADDER: q_N :=
rho_{N-1}/(5/7) on ALL 42 rungs (N = 142..878).  (b1) census:
q < 1 on 42/42 (reproduces the r243 razor, min margin band
[0.010, 0.020] on 5/7 - rho_{N-1}); distribution (min/med/max);
wall margin gap = 1 - q_N vs N: LS slope + Spearman, sealed
trend rule (bar 0.5): APPROACHING iff Spearman <= -0.5, RECEDING
iff >= +0.5, else FLAT.  (b2) the driver decomposition log10 q =
2 log10 |F_{N-1}| - log10 h_{N-1} - log10(5/7): Spearman of
log q vs 2 log|F| and vs log h, plus the CROSS correlation
Spearman(2 log|F|, log h) over the ladder; SEALED DRIVER RULE:
COVARIANT_RATIO iff the cross Spearman >= 0.7 (the two terminal
components track each other and q is the residual of the
covariation); the residual side is F/H if the respective
|Spearman(log q, .)| exceeds the other by >= 0.2, else BALANCED.
(b3) THE t*-CONNECTION (exact): (i) the CORNER RAY B(t) =
S_{N-2} + t (5/7) makes the terminal bordered pivot AFFINE with
slope 5/7 in t (Schur, slope-1 in B); its zero crossing is
t*_bud = rho_{N-1}/(5/7) = q_N EXACTLY -- gated by direct
bordered slogdets at t in {0, 1/2, 1}: collinearity <= 1e-9 rel,
slope == 5/7 and root == q_N (bars 1e-8 mains / 3e-6 deep; the
slope bar was split main/deep at calibration, amendment a1
below); this is the SAME sealed normal form as the r238 t* =
gbar/(gbar - gammahat_N) (terminal pivot affine slope-1 in its
one forced parameter, coordinate = ray crossing, wall = pivot
positive at physical parameter 1) -- the budget question IS a
t*-statement: q_N < 1.  (ii) HONEST TYPING of the r238/r239
INSTANCE: it consumes the forced moment m_{2N} (pivot h_N),
q_N consumes the border readout F_{N-1} -- SAME normal form,
DIFFERENT terminal data; re-derive the r238 census on all 42
(sealed priors: 29 down-crossing windows, 18 with t* < 1 = the
delta = 0 set) and print Spearman(q_N, t*_r238) on the crossing
windows (measurement, no bar).  TSTAR_IDENTIFIED fires iff (i)
passes and (ii) reproduces the census -- worded as: one
COORDINATE NORMAL FORM, two data instances; NEVER as numeric
equality of the two instances (that would be the must-fail
direction).  (b4) worlds: controls' q before their base flip
(q_pre = rho_{pmax-1}/(5/7), pmax = 21/25/27) and the signed
full-depth value typed INDEFINITE_CONTINUATION; SMOOTH is the
alias world: q_N(SMOOTH) <= 1e-20 (F_{N-1} = 0 structurally).

LEG C -- DRAIN PROFILE ANATOMY: (c1) zones (r246 conventions
HEAD n < 8 / BULK / TAIL last 5) on all 42: share medians; the
head is ONE MODE: rho_0 == b1^2/h_0 EXACTLY (rel 1e-12) with
b1 = total signed BORDER mass (zeroth border readout F_0) and
h_0 = total signed window mass -- source-pure WHY of the r246
~44 percent head: the head mode is the raw mass pairing
(border mass)^2/(window mass), no orthogonal-polynomial
oscillation enters; sealed reproduction band median p_0 in
[0.25, 0.55]; ladder spread of rho_0 printed (r246: ~0.2
decades).  (c2) tail decay law: per rung LS fits of log10
rho_n over the sealed bulk window n in [8, N-6]: EXP (vs n)
against POWER (vs log10 n), winner needs rms <= 0.8 x other,
else IRREGULAR; majority token over the 42 rungs + w9/w13
detail, min rho + terminal rebound printed.  (c3) MAJORANTS
(sealed BEFORE evaluation, max 3, all TRUE pointwise bounds by
construction -- ward m_n >= rho_n (1 - 1e-6) on every MAIN rung,
n in [8, N-2], POSITIVE_PREFIX-typed): with phat_n = pihat_n /
sqrt(h_n) at the border atoms and |sigma| the border total
variation:
  M1_SUP: m_n = ||sigma||_TV^2 max_atom phat_n^2   (sup bound),
  M2_CS : m_n = ||sigma||_TV int phat_n^2 d|sigma| (Cauchy-
          Schwarz in |sigma|),
  M3_ABS: m_n = (int |phat_n| d|sigma|)^2          (triangle
          bound; analytically the tightest of the three).
BUDGET TEST per rung and candidate: head as prefix data, does
sum_{n=8}^{N-2} m_n <= (S_{N-2} - S_7) + 5/7 hold?  Coverage
over 42, overshoot factor sum m / budget, break locus argmax_n
m_n (fraction of N).  MAJORANT_FOUND(cand) iff some candidate
covers 42/42; else MAJORANT_OPEN(best candidate, median
overshoot, locus) -- the honest break anatomy is the deliverable
(controls excluded: their budget side is algebraic beyond the
flip, r246 typing).  (c4) PREFIX-BORDER DOMINANCE (the r256
side-finding as its own object): on the sealed 10-rung ladder
kz = (17, 10, 18, 12, 13, 9, 15, 19, 26, 40), per rung the
MAIN x SCRAMBLE(seed 1) cleaned raster at the pair's OWN common
positive prefix n* = min(pmax_M, pmax_C) (re-derived per rung;
r254-a1 sorted-union embedding re-gated; cells by the separable
route T = sum_k sg_k (phat_k . s)^2, r256-identical algebra);
prior re-gate on w9: Dbo* = -0.175897, Gap* = -0.216051, ratio
0.814 (rel 2e-3); rungs with |Gap*| <= 1e-9 x gross typed NULL;
SEALED RULE: PREFIX_DOMINANCE_STABLE iff >= 0.8 of non-null
rungs have sign(Dbo*) == sign(Gap*) AND |Dbo*|/|Gap*| in the
r256 band [0.3, 3.0]; else PREFIX_DOMINANCE_ARTIFACT (the sign
census and the ratio range are printed separately -- a stable
sign with unstable magnitude is typed as such, never upgraded).

LEG D -- FALSIFIERS + MUST-FAILS (each loud, >= 1e3 x honest):
(d1) SHIFTED TELESCOPE INDEX: D_N vs 5/7 - rho_{N-2} must break
the w9 anchor loudly; (d2) SWAPPED F/h: the terminal increment
read as h_{N-1}/F_{N-1}^2 must break loudly; (d3) WRONG t*
NORMALIZATION: t* claimed as rho_{N-1}/(7/5) must miss the
machine root loudly (the 5/7 ray normalization is content);
(d4) SMOOTH ANCHOR: max_{n>=1} |rho_n|/rho_0 <= 1e-18 AND
D_N(SMOOTH) == 5/7 rel 1e-9 AND q_N(SMOOTH) <= 1e-20 -- the
terminal question trivializes exactly when the source aliases.

SEALED CONSTANTS: ladder = frame-A h <= 900 (42 rungs, (N, kz)
sorted); main windows (9, 12, 13, 26); ladder sample indices
(0, 5, 10, 15, 20, 25, 30, 35, 41); controls on w9: EPSTEIN /
SCRAMBLE(seed 1) / SMOOTH, flips 25/21/27; FIB_LO 8; direct
bars 1e-8 main / 3e-6 deep / 1e-3 controls; lin bar 1e-9;
slope + root bars 1e-8 main / 3e-6 deep; mp n_t {12, 24} (w9) +
12 (largest), dps 220, bar 1e-12; floor band [1.40, 1.46],
non-saturation 0.01, saturation probe 1e-6; margin band [0.010,
0.020]; trend/driver bars: Spearman 0.5, covariance 0.7, driver
delta 0.2; r238 census priors 29 crossing / 18 below 1; zones
HEAD_K 8 / TAIL_K 5; p0 band [0.25, 0.55]; rho0 identity bar
1e-12; phat-vs-chain rho bar 1e-6; majorant ward tol 1e-6; tail
rms ratio 0.8; c4 ladder (17, 10, 18, 12, 13, 9, 15, 19, 26,
40), prior tol 2e-3, LB band [0.3, 3.0], stability fraction
0.8, null floor 1e-9 x gross; SMOOTH alias 1e-18 / q 1e-20 /
D_N 1e-9; loudness 1e3; runtime <= 1800 s; smoke = w9 (+ w9
controls): telescope w9, corner ray w9, zones w9, majorant w9,
c4 w9 pair, must-fails; ladder legs + mp wards + r238 census
skipped.  DISCLOSED PRE-SPEC SCRATCH CALIBRATIONS (both before
this spec was frozen, informing floors/bands only, no verdict
rule tuned after any full evaluation): (s1) route floors (direct
devs, corner-ray root devs, mp cost, q/t* census scales,
majorant overshoot scale, tail rms scale); (s2) c4 feasibility
(embedding + prefix depths + cell values on the 10-rung
ladder).

SEALED VERDICT FORM (frozen BEFORE the record run, joined '+'):
  TELESCOPE_EXACT(BY_CONSTRUCTION; 5/7 = r241 IMPORTED floor,
    source derivation OPEN) / TELESCOPE_APPROX(error law)
+ TERMINAL_Q_LAW(trend, driver)
+ TSTAR_IDENTIFIED(one normal form, two data instances)
    / TSTAR_OPEN
+ MAJORANT_FOUND(cand) / MAJORANT_OPEN(best, overshoot, locus)
+ PREFIX_DOMINANCE_STABLE(median ratio)
    / PREFIX_DOMINANCE_ARTIFACT(sign census, ratio range).
Honesty before beauty: no verdict claims a derived 5/7, a bound
mechanism, or numeric equality of the two t* instances; the
budget bound and the base law stay OPEN (r243/r246/r247/r256/
r257 stand).

RECORD TABLES (frozen from calibration pass 1, 25/27 gates with
EXACTLY ONE bar amendment, then 27/27; wall 8.5 s full; ALL
verdict rules, candidates, bands and every other bar untouched;
the two pre-spec scratch calibrations are disclosed above.
CALIBRATION AMENDMENT a1 (disclosed, BEFORE the record run):
the corner-ray SLOPE bar was drafted as a single 1e-9 while the
measured slope deviation on the deep rungs is 1.1e-7 -- the SAME
f64 route conditioning already sealed main/deep for the direct
and root gates; the slope bar was split to the identical
main/deep pair 1e-8 / 3e-6; no other change):
CAL_VERDICT = TELESCOPE_EXACT(BY_CONSTRUCTION; 5/7 = r241
IMPORTED floor, source derivation OPEN) +
TERMINAL_Q_LAW(FLAT, COVARIANT_RATIO(residual BALANCED)) +
TSTAR_IDENTIFIED(one normal form, two data instances) +
MAJORANT_OPEN(M3_ABS, overshoot x4.9e+02 med, locus 0.97 N) +
PREFIX_DOMINANCE_ARTIFACT(sign 10/10, ratio 0.006..4.11).
Key numbers.  CENSUS: 42 rungs N in [142, 878], POSITIVE_PREFIX
42/42; controls flip 25/21/27 re-derived.  LEG A: direct
telescope on the 12-window sample worst rel 1.7e-9 (N <= 400) /
9.5e-8 (deep, N = 878), signs exact 12/12; f64 route error law
slope +4.16 dec/dec vs N (CONDITIONING of the route, disclosed
-- the identity itself is definitional + mp-warded); mp
truncation wards (dps 220): w9 2.8e-17 / 1.0e-16, largest rung
(kz 52, N = 878) 2.4e-16 -- the Schur telescope is exact in
exact arithmetic; 5/7 provenance: min_w h_{N-1}/F_{N-1}^2 =
1.4278 in [1.40, 1.46], >= 7/5 with non-saturation margin
0.0278 >= 0.01 => Q7_SHARE and LEVEL8_SUBTRACTION
NOT_SUPPORTED, the constant is the r241 IMPORTED floor (a round
rational BELOW the measured saturation 1.4278; source
derivation OPEN); margin equivalence sign(D_N) == sign(5/7 -
rho_{N-1}) on 12/12 + w9 controls (EPST +1.7922 / SCR +0.5219 /
SMOOTH +0.7143, algebraic, typed).  LEG B: q_N < 1 on 42/42,
min/med/max 0.0015/0.4188/0.9805, min margin 0.0139 (band hit,
r243 razor reproduced); gap = 1 - q_N vs N: slope +0.41,
Spearman +0.357 => FLAT (the wall margin does NOT shrink with N
on this surface); DRIVER: Spearman(2lgF, lgh) = +1.000
(RANK-PERFECT covariation of F_{N-1}^2 and h_{N-1} over the
ladder -- the round's sharpest single finding), residuals
Spearman(lgq, 2lgF) +0.361 vs (lgq, lgh) +0.357 => COVARIANT_
RATIO(residual BALANCED): neither component drives q, the
terminal coordinate is the residual of an exact covariation --
any terminal proof must bound the RATIO, not either side;
corner ray: collinearity worst 3.4e-13, slope vs 5/7 worst
1.1e-7 (deep, = the route floor), root == q_N worst 3.2e-9
main / 5.2e-8 deep on 12/12; r238 census reproduced: 29
down-crossing, 18 below 1 (= the delta = 0 set), 13
no-crossing; Spearman(q_N, t*_r238) on the 29 crossing windows
= +0.027 -- the two instances are STATISTICALLY UNRELATED (one
normal form, two data: the r238 instance reads the forced
moment m_{2N}, q_N reads the border readout F_{N-1}; the
predicates differ on exactly the 18 t* < 1 windows where q_N
< 1 throughout); worlds: q_pre(EPST@25/SCR@21/SMOOTH@27) =
9.6e-5/1.3e-2/2.6e-31, full-depth signed q EPST -1.51 / SCR
+0.27 typed INDEFINITE_CONTINUATION, SMOOTH q_N = 4.2e-25.
LEG C: zones med H/B/T = 0.366/0.604/0.035, median p_0 0.366
in [0.25, 0.55] range [0.278, 0.523] (r246 reproduced); rho_0
== b1^2/h_0 worst rel 6.7e-16 (the head mode IS the raw mass
pairing (border mass)^2/(window mass) -- source-pure WHY of
the one-mode head); rho_0 ladder spread 0.18 decades; tail
law: EXP/POW/IRREGULAR = 0/2/40 of 42 (w9: EXP rms 1.25 vs POW
rms 1.11, min rho 8.9e-10 at n = 180 = 0.978 N, terminal
rebound +8.2 dec; w13: min rho 1.6e-08 at n = 26 = 0.155 N,
rebound +7.4 dec) => majority IRREGULAR, no clean decay law;
MAJORANTS: ward m_n >= rho_n holds at every degree on 42/42
(worst phat-vs-chain rho rel 4.0e-8); coverage M1_SUP 0/42
(overshoot med x1.5e+11), M2_CS 0/42 (x7.3e+05), M3_ABS 0/42
(x4.9e+02) => MAJORANT_OPEN(best M3_ABS, median overshoot
x4.9e+02, break locus argmax at 0.97 N median) -- the sealed
mass bounds break in the NEAR-TERMINAL zone where h_n
collapses: no |sigma|-mass bound can see the F^2/h
cancellation (consistent with the b2 covariation finding; the
budget proof needs a ratio object, not a mass object).  LEG
C4: w9 prior re-gate hit (Dbo* -0.175897, Gap* -0.216051,
ratio 0.8141, rel <= 2e-3); 10-rung ladder (n* = 9..21, 0
NULL, embeddings all gated): sign(Dbo*) == sign(Gap*) on 10/10
(SCRAMBLE's border carries MORE prefix mass than MAIN's on
EVERY rung -- the sign is universal), but |Dbo*|/|Gap*| =
0.006..4.11 with only 3/10 in [0.3, 3.0] =>
PREFIX_DOMINANCE_ARTIFACT(sign 10/10 stable, ratio n*-
artifact): the r256 '81 percent' magnitude was a w9/n* = 21
coincidence, the SIGN of the border excess is the stable
object (candidate for a future contract, typed, not
upgraded).  LEG D: d1 shifted telescope breaks by 6.5e+8 x
honest; d2 swapped F/h (6.534 vs 0.153) breaks by 3.6e+9 x;
d3 wrong t* normalization misses the machine root by 3.2e+9
x; d4 SMOOTH alias 7.6e-23 (bar 1e-18), q_N = 4.2e-25 <=
1e-20, D_N == 5/7 rel 1.1e-11.  READING (typed, no upgrade):
the budget question IS the single terminal inequality --
exactly, by construction of B, with the Schur telescope
machine-exact and mp-warded; its coordinate q_N is a
t*-coordinate in the same exact normal form as r238 (two
instances, different terminal data, statistically unrelated);
on the measured surface q < 1 with a FLAT N-trend and a
rank-perfect F^2-vs-h covariation whose residual no sealed
mass majorant can bound; the r256 border dominance survives
only as a universal SIGN.  Runtime 8.5 s full / 0.1 s smoke;
run1/run2 identical up to WALL.  AMENDMENTS AFTER FREEZE:
NONE (a1 predates the record run, disclosed above).

NO RH CLAIM IN EITHER DIRECTION.  NOT evidence for or against RH.
"""

from __future__ import annotations

import argparse
import ast
import hashlib
import math
import os
import sys
import time

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
if HERE not in sys.path:
    sys.path.insert(0, HERE)

import bordered_hankel_probe as BH           # noqa: E402 r244
import coupledtau_probe as CT                # noqa: E402 r257
import offdiag_gram_probe as OG              # noqa: E402 r254
import port_integrable_kernel_probe as PIK   # noqa: E402 v881
import principal_bessel_probe as PB          # noqa: E402 r243
import v563_paper2_readouts as core          # noqa: E402 READ-ONLY

H_CAP = 900
MAIN_TELE = (9, 12, 13, 26)
LADDER_SAMPLE_IDX = (0, 5, 10, 15, 20, 25, 30, 35, 41)
DEEP_N = 400
CTRL_FLIPS = {"EPSTEIN": 25, "SCRAMBLE": 21, "SMOOTH": 27}
FIB_LO = 8
B57 = 5.0 / 7.0
DIRECT_BAR_MAIN = 1e-8
DIRECT_BAR_DEEP = 3e-6
DIRECT_BAR_CTRL = 1e-3
LIN_BAR = 1e-9
SLOPE_BAR_MAIN = 1e-8
SLOPE_BAR_DEEP = 3e-6
ROOT_BAR_MAIN = 1e-8
ROOT_BAR_DEEP = 3e-6
MP_TRUNCS_W9 = (12, 24)
MP_TRUNC_DEEP = 12
MP_TRUNC_DPS = 220
MP_TRUNC_BAR = 1e-12
FLOOR_BAND = (1.40, 1.46)
NONSAT_MARGIN = 0.01
SAT_PROBE = 1e-6
MARGIN_BAND = (0.010, 0.020)
SPEAR_BAR = 0.5
COVAR_BAR = 0.7
DRIVER_DELTA = 0.2
R238_CROSS = 29
R238_LT1 = 18
HEAD_K = 8
TAIL_K = 5
P0_BAND = (0.25, 0.55)
RHO0_ID_BAR = 1e-12
PHAT_RHO_BAR = 1e-6
MAJ_WARD_TOL = 1e-6
TAIL_RMS_RATIO = 0.8
C4_LADDER = (17, 10, 18, 12, 13, 9, 15, 19, 26, 40)
C4_PRIOR = {"Dbo": -0.175897, "Gap": -0.216051}
C4_PRIOR_TOL = 2e-3
LB_LO, LB_HI = 0.3, 3.0
STAB_FRAC = 0.8
GAP_NULL = 1e-9
SM_ALIAS_BAR = 1e-18
SM_Q_BAR = 1e-20
SM_DN_BAR = 1e-9
LOUD = 1e3
CAL_VERDICT = (
    "TELESCOPE_EXACT(BY_CONSTRUCTION; 5/7 = r241 IMPORTED floor, "
    "source derivation OPEN) + TERMINAL_Q_LAW(FLAT, "
    "COVARIANT_RATIO(residual BALANCED)) + TSTAR_IDENTIFIED(one "
    "normal form, two data instances) + MAJORANT_OPEN(M3_ABS, "
    "overshoot x4.9e+02 med, locus 0.97 N) + "
    "PREFIX_DOMINANCE_ARTIFACT(sign 10/10, ratio 0.006..4.11)")

SPEC_SHA = hashlib.sha256(__doc__.encode("utf-8")).hexdigest()
T0_WALL = time.time()
CHECKS: list = []
LN10 = math.log(10.0)


def check(name, ok, detail):
    ok = bool(ok)
    CHECKS.append((name, ok, detail))
    print("  [%s] %-42s %s" % ("PASS" if ok else "FAIL", name, detail),
          flush=True)
    return ok


def info(msg):
    print("  [INFO] " + msg, flush=True)


def section(t):
    print("\n" + "-" * 78 + "\n" + t + "\n" + "-" * 78, flush=True)


def firewall_audit():
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    forb = {"zeta" + "zero", "n" + "zeros", "prime" + "range",
            "is" + "prime", "gram" + "point"}
    bad = []
    for node in ast.walk(tree):
        nm = node.attr if isinstance(node, ast.Attribute) else (
            node.id if isinstance(node, ast.Name) else None)
        if nm and nm.lower() in forb:
            bad.append("%s@%d" % (nm, node.lineno))
    return (not bad), ("NO zero/prime oracles; every readout "
                       "consumes node positions + signed weights + "
                       "the r244 chain; ground truth (flips) enters "
                       "gates only" if not bad else "; ".join(bad))


# ------------------------------------------------ direct route
def direct_DN(p, t_corners):
    """full-depth bordered slogdet route (r257 basis: scaled
    Chebyshev-U on the union+border hull) with the corner along
    the sealed ray B(t) = S_{N-2} + t (5/7); returns D_N(t) list."""
    d, dsm = p["d"], p["dsm"]
    N = p["N"]
    xu, wu = CT.union_arrays(d)
    bx, bw = CT.union_arrays(dsm)
    lo = min(float(np.min(xu)), float(np.min(bx)))
    hi = max(float(np.max(xu)), float(np.max(bx)))
    x0, rh = 0.5 * (lo + hi), 0.5 * (hi - lo)
    P = CT.u_matrix(xu, x0, rh, N)
    TB = CT.u_matrix(bx, x0, rh, N)
    G = (P * wu) @ P.T
    tv = TB @ bw
    sg, lg = np.linalg.slogdet(G)
    out = []
    for t in t_corners:
        B = float(p["S"][N - 2]) + t * B57
        A = np.zeros((N + 1, N + 1))
        A[:N, :N] = G
        A[:N, N] = tv
        A[N, :N] = tv
        A[N, N] = B
        sa, la = np.linalg.slogdet(A)
        out.append(sa * sg * math.exp(la - lg))
    return out


def terminal_logs(p):
    """(2 log10 |F_{N-1}|, log10 h_{N-1}, q_N) from the chain."""
    N = p["N"]
    r = p["rows"][N - 1]
    lF2 = 2.0 * (math.log10(max(abs(r["fb"]), 1e-300))
                 + r["Ls"] / LN10)
    lh = r["lg_h"] / LN10
    return lF2, lh, float(p["rho"][N - 1]) / B57


def tstar_r238(p):
    """the r238 coordinate with the sealed m_free convention
    gammahat_{N,free} = gammahat_{N-1}; returns (t*, crossing)."""
    N = p["N"]
    gN = p["rows"][N - 1]["gam_next"]
    gb = p["rows"][N - 2]["gam_next"]
    if gN >= gb:
        return float("inf"), False
    return gb / (gb - gN), True


def pmax_of(p):
    """maximal positive prefix degree (r256 leg-0 coordinate)."""
    for k in range(FIB_LO, p["N"]):
        if p["rows"][k]["sg_h"] < 0.0:
            return k
    return p["N"]


def wfields(p):
    d, dsm = p["d"], p["dsm"]
    return dict(
        bx=np.concatenate([dsm["xs"], dsm["ys"]]),
        bw=np.concatenate([dsm["ws"], -dsm["vs"]]),
        wx=np.concatenate([d["xs"], d["ys"]]),
        wu=np.concatenate([d["ws"], -d["vs"]]),
        c0=p["Fv"][0] / p["hv"][0],
        sg=np.array([r["sg_h"] for r in p["rows"]]), p=p)


def c4_raster(pM, pC):
    """MAIN x SCRAMBLE cleaned raster at the pair's own common
    positive prefix (r256 algebra via the separable cell route
    T = sum_k sg_k (phat_k . s)^2); returns the effect dict."""
    WM, WC = wfields(pM), wfields(pC)
    ns = min(pmax_of(pM), pmax_of(pC))
    U = np.unique(np.concatenate([WM["wx"], WC["wx"]]))
    im = np.searchsorted(U, WM["wx"])
    ic = np.searchsorted(U, WC["wx"])
    ok_pos = (np.array_equal(WM["bx"], WC["bx"])
              and bool(np.all(U[im] == WM["wx"]))
              and bool(np.all(U[ic] == WC["wx"])))
    posU = np.concatenate([WM["bx"], U])
    nb = len(WM["bx"])

    def s_emb(W, idx):
        sv = np.zeros(len(posU))
        sv[:nb] = W["bw"]
        np.add.at(sv, nb + idx, -W["c0"] * W["wu"])
        return sv

    sM, sC = s_emb(WM, im), s_emb(WC, ic)
    if ns <= FIB_LO:
        return dict(ok_pos=ok_pos, nstar=ns, null=True)
    PM = OG.phat_matrix(pM["rows"], posU, ns)
    PC = OG.phat_matrix(pC["rows"], posU, ns)

    def cell(P, sg, s):
        v = P[FIB_LO:] @ s
        return float(np.sum(sg[FIB_LO:len(P)] * v * v))

    MM = cell(PM, WM["sg"], sM)
    MC = cell(PM, WM["sg"], sC)
    CC = cell(PC, WC["sg"], sC)
    vg = np.abs(PM[FIB_LO:]) @ np.abs(sM)
    gross = float(np.sum(vg * vg))
    Dbo, Gap = MM - MC, MM - CC
    return dict(ok_pos=ok_pos, nstar=ns, null=abs(Gap)
                <= GAP_NULL * max(gross, 1e-300),
                Dbo=Dbo, Gap=Gap, gross=gross,
                ratio=abs(Dbo) / max(abs(Gap), 1e-300),
                sgn_ok=(Dbo * Gap > 0.0))


def tail_fit(rho, N):
    """sealed bulk-window fits: EXP log10 rho ~ a + b n vs POWER
    log10 rho ~ a + b log10 n on n in [HEAD_K, N-TAIL_K-1]."""
    nn = np.arange(HEAD_K, N - TAIL_K)
    y = np.log10(np.maximum(np.abs(rho[HEAD_K:N - TAIL_K]), 1e-300))
    ce = np.polyfit(nn, y, 1)
    rmse = float(np.sqrt(np.mean((np.polyval(ce, nn) - y) ** 2)))
    lx = np.log10(nn)
    cp = np.polyfit(lx, y, 1)
    rmsp = float(np.sqrt(np.mean((np.polyval(cp, lx) - y) ** 2)))
    if rmse <= TAIL_RMS_RATIO * rmsp:
        tok = "EXP"
    elif rmsp <= TAIL_RMS_RATIO * rmse:
        tok = "POW"
    else:
        tok = "IRREGULAR"
    return tok, float(ce[0]), rmse, float(cp[0]), rmsp


# --------------------------------------------------------------- main
def main():
    par = argparse.ArgumentParser()
    par.add_argument("--smoke", action="store_true")
    args = par.parse_args()
    smoke = args.smoke

    print("=" * 78)
    print("budget_anatomy_probe -- PRIME.PORT.RHP.BUDGET."
          "ANATOMY.01 (round 258)")
    print("SPEC_SHA %s   F_DEF_SHA %s (imported r243)"
          % (SPEC_SHA[:16], PB.F_DEF_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 + w9 controls only; ladder legs, "
                        "mp wards, r238 census skipped)"
                        if smoke else "FULL RECORD"))
    print("=" * 78)

    section("S0  FIREWALL + PREDEFINITION")
    okf, det = firewall_audit()
    check("G01-firewall", okf, det)
    check("G02-predefinition", True,
          "MAIN OBJECT: the terminal reduction of the r257 drain -- "
          "B_w = S_{N-2} + 5/7 (IMPORTED, by construction) makes "
          "D_N = 5/7 - rho_{N-1} an algebraic identity; gates: "
          "direct bordered slogdet on the 12-window sample + mp "
          "truncation wards dps %d; q_N = rho_{N-1}/(5/7) census + "
          "driver decomposition on the 42-rung ladder; corner ray "
          "B(t) = S_{N-2} + t(5/7) as the sealed t* normal form; "
          "majorant candidates M1_SUP/M2_CS/M3_ABS sealed; c4 "
          "dominance ladder %s with per-pair prefix depth; ALL "
          "bars, bands, rules and verdicts sealed in the frozen "
          "spec BEFORE the record run (two pre-spec scratch "
          "calibrations disclosed)"
          % (MP_TRUNC_DPS, str(C4_LADDER)))

    # ---------------- S1: census
    section("S1  CENSUS + CONTROLS + POSITIVITY TYPING")
    if smoke:
        packs = [BH.wpack(9)]
    else:
        kzs = [kz for kz in core.frame_a_zones()
               if PIK.build_rung(kz)["h"] <= H_CAP]
        packs = [BH.wpack(kz) for kz in kzs]
        packs.sort(key=lambda p: (p["N"], p["kz"]))
    by_kz = {p["kz"]: p for p in packs}
    okC = all(p["nf"] is None for p in packs)
    check("G10-census-ladder", okC,
          "%d rungs, N in [%d, %d]: free prefix positive at full "
          "depth on ALL (typed POSITIVE_PREFIX)%s"
          % (len(packs), packs[0]["N"], packs[-1]["N"],
             " (smoke: w9 only)" if smoke else ""))
    rr9 = core.build_window(9)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE = PIK.lambda_eps(N_E)
    nn_idx = np.nonzero(np.abs(lamE) > 1e-12)[0]
    ug9, uw9 = PB.smooth_comb(rr9["alpha"])
    ctrl_defs = (("EPSTEIN", dict(comb=(
        np.log(nn_idx.astype(float)),
        2.0 * lamE[nn_idx] / np.sqrt(nn_idx.astype(float))))),
        ("SCRAMBLE", dict(scramble_seed=1)),
        ("SMOOTH", dict(comb=(ug9, uw9))))
    ctrl = {c: BH.wpack(9, base_kw=kw) for c, kw in ctrl_defs}
    okCf = all(ctrl[c]["nf"] == CTRL_FLIPS[c] for c in ctrl)
    check("G11-census-controls", okCf,
          "w9 control flips re-derived %s (typed INDEFINITE_"
          "CONTINUATION beyond pmax, r256 firewall adopted)"
          % str({c: ctrl[c]["nf"] for c in ctrl}))

    # sample for the telescope/ray gates
    if smoke:
        sample = [by_kz[9]]
    else:
        skz = list(MAIN_TELE) + [packs[i]["kz"]
                                 for i in LADDER_SAMPLE_IDX]
        seen: list = []
        sample = []
        for kz in skz:
            if kz not in seen:
                seen.append(kz)
                sample.append(by_kz[kz])

    # ---------------- S2: LEG A -- the exact telescope identity
    section("S2  LEG A -- THE EXACT TELESCOPE IDENTITY")
    dev_main = dev_deep = 0.0
    sgn_ok = True
    ray = {}
    devs, Ns_s = [], []
    a_note = []
    for p in sample:
        D0, Dh, D1 = direct_DN(p, (0.0, 0.5, 1.0))
        ray[p["kz"]] = (D0, Dh, D1)
        ref = B57 - float(p["rho"][p["N"] - 1])
        dv = abs(D1 / ref - 1.0)
        sgn_ok = sgn_ok and (math.copysign(1.0, D1)
                             == math.copysign(1.0, ref)) \
            and (ref > 0.0)
        if p["N"] <= DEEP_N:
            dev_main = max(dev_main, dv)
        else:
            dev_deep = max(dev_deep, dv)
        devs.append(max(dv, 1e-16))
        Ns_s.append(p["N"])
        a_note.append("kz%d(N=%d) %.1e" % (p["kz"], p["N"], dv))
    err_slope = (float(np.polyfit(np.log10(Ns_s),
                                  np.log10(devs), 1)[0])
                 if len(devs) >= 3 else float("nan"))
    check("G20-telescope-direct",
          dev_main <= DIRECT_BAR_MAIN and dev_deep <= DIRECT_BAR_DEEP
          and sgn_ok,
          "direct bordered slogdet D_N == 5/7 - rho_{N-1} on the "
          "%d-window sample: %s -- worst rel %.1e (N <= %d, bar "
          "%.0e) / %.1e (deep, bar %.0e), all signs positive and "
          "exact; f64 route error law slope %+.2f dec/dec vs N "
          "(CONDITIONING of the route, disclosed -- the identity "
          "is BY CONSTRUCTION, exactness carried by the mp wards)"
          % (len(sample), "; ".join(a_note), dev_main, DEEP_N,
             DIRECT_BAR_MAIN, dev_deep, DIRECT_BAR_DEEP, err_slope))
    if not smoke:
        tr_note = []
        tr_w = 0.0
        for n_t in MP_TRUNCS_W9:
            dv = CT.mp_trunc_ward(by_kz[9], n_t, MP_TRUNC_DPS, B57)
            tr_w = max(tr_w, dv)
            tr_note.append("w9 n_t=%d %.1e" % (n_t, dv))
        dv = CT.mp_trunc_ward(packs[-1], MP_TRUNC_DEEP,
                              MP_TRUNC_DPS, B57)
        tr_w = max(tr_w, dv)
        tr_note.append("kz%d(N=%d) n_t=%d %.1e"
                       % (packs[-1]["kz"], packs[-1]["N"],
                          MP_TRUNC_DEEP, dv))
        check("G21-mp-truncation-wards", tr_w <= MP_TRUNC_BAR,
              "monomial mp Hankel truncations (dps %d, corner "
              "5/7): %s (bar %.0e) -- the Schur telescope D_n = "
              "B_t - S_{n-1} is exact in exact arithmetic"
              % (MP_TRUNC_DPS, "; ".join(tr_note), MP_TRUNC_BAR))
    else:
        check("G21-mp-truncation-wards", True, "SMOKE: skipped")
    # (a3) margin equivalence incl. controls (algebraic side)
    eq_ok = True
    c_note = []
    for c in ctrl:
        Dc = direct_DN(ctrl[c], (1.0,))[0]
        refc = B57 - float(ctrl[c]["rho"][ctrl[c]["N"] - 1])
        dvc = abs(Dc / refc - 1.0)
        eq_ok = eq_ok and dvc <= DIRECT_BAR_CTRL \
            and (math.copysign(1.0, Dc) == math.copysign(1.0, refc))
        c_note.append("%s D_N %+.4f rel %.1e" % (c, Dc, dvc))
    check("G22-margin-equivalence", sgn_ok and eq_ok,
          "sign(D_N) == sign(5/7 - rho_{N-1}) on the full sample "
          "(MAIN: both sides positive) AND on the w9 controls "
          "(%s -- there ALGEBRAIC tau-quotient statements, typed "
          "INDEFINITE_CONTINUATION, ctrl bar %.0e): margin > 0 "
          "<=> rho_{N-1} < 5/7 EXACTLY"
          % ("; ".join(c_note), DIRECT_BAR_CTRL))
    # (a2) 5/7 provenance
    ratios = [1.0 / (B57 * terminal_logs(p)[2]) for p in packs]
    rmin = min(ratios)
    ok_fl = (FLOOR_BAND[0] <= rmin <= FLOOR_BAND[1]
             and rmin >= 1.4 + NONSAT_MARGIN) or smoke
    saturated = abs(rmin - 1.4) <= SAT_PROBE
    check("G23-five-sevenths-provenance", ok_fl and not saturated,
          "min_w h_{N-1}/F_{N-1}^2 = %.4f in [%.2f, %.2f], >= 7/5 "
          "with non-saturation margin %.4f >= %.2f: the constant "
          "does NOT saturate (probe %.0e) and has no source-pure "
          "compile path in the import chain (r243 <- r241 floor "
          "literals only) => Q7_SHARE and LEVEL8_SUBTRACTION "
          "NOT_SUPPORTED; 5/7 stays FLOOR_IMPORTED(r241), source "
          "derivation OPEN%s"
          % (rmin, FLOOR_BAND[0], FLOOR_BAND[1], rmin - 1.4,
             NONSAT_MARGIN, SAT_PROBE,
             " (smoke: w9 only, band not binding)" if smoke else ""))
    vA = ("TELESCOPE_EXACT(BY_CONSTRUCTION; 5/7 = r241 IMPORTED "
          "floor, source derivation OPEN)"
          if (dev_main <= DIRECT_BAR_MAIN
              and dev_deep <= DIRECT_BAR_DEEP and sgn_ok and eq_ok)
          else "TELESCOPE_APPROX(err main %.1e deep %.1e)"
          % (dev_main, dev_deep))

    # ---------------- S3: LEG B -- the terminal inequality
    section("S3  LEG B -- THE TERMINAL INEQUALITY q_N OVER THE "
            "LADDER")
    lF2s, lhs, qs = [], [], []
    for p in packs:
        lF2, lh, q = terminal_logs(p)
        lF2s.append(lF2)
        lhs.append(lh)
        qs.append(q)
    qmax, qmed, qmin = (max(qs), float(np.median(qs)), min(qs))
    marg_min = B57 * (1.0 - qmax)
    ok_q = all(q < 1.0 for q in qs) and \
        (smoke or MARGIN_BAND[0] <= marg_min <= MARGIN_BAND[1])
    check("G30-q-census", ok_q,
          "q_N = rho_{N-1}/(5/7) < 1 on %d/%d rungs; min/med/max "
          "= %.4f/%.4f/%.4f; min terminal margin 5/7 - rho_{N-1} "
          "= %.4f (band [%.3f, %.3f], the r243 razor reproduced)%s"
          % (len(qs), len(qs), qmin, qmed, qmax, marg_min,
             MARGIN_BAND[0], MARGIN_BAND[1],
             " (smoke: band not binding)" if smoke else ""))
    if not smoke:
        Ns = [p["N"] for p in packs]
        gaps = [1.0 - q for q in qs]
        g_slope = float(np.polyfit(np.log10(Ns),
                                   np.log10(gaps), 1)[0])
        g_sp = CT.spearman(Ns, gaps)
        trend = ("APPROACHING" if g_sp <= -SPEAR_BAR else
                 ("RECEDING" if g_sp >= SPEAR_BAR else "FLAT"))
        check("G31-q-trend", True,
              "wall margin gap = 1 - q_N vs N: LS slope %+.2f "
              "dec/dec, Spearman %+.3f (sealed bar %.1f) => "
              "TREND %s -- the terminal margin does NOT shrink "
              "with N on this surface (measurement)"
              % (g_slope, g_sp, SPEAR_BAR, trend))
        lgq = [math.log10(q) for q in qs]
        sp_F = CT.spearman(lgq, lF2s)
        sp_h = CT.spearman(lgq, lhs)
        sp_x = CT.spearman(lF2s, lhs)
        if sp_x >= COVAR_BAR:
            if abs(sp_F) >= abs(sp_h) + DRIVER_DELTA:
                res = "residual F"
            elif abs(sp_h) >= abs(sp_F) + DRIVER_DELTA:
                res = "residual H"
            else:
                res = "residual BALANCED"
            driver = "COVARIANT_RATIO(%s)" % res
        elif abs(sp_F) >= abs(sp_h) + DRIVER_DELTA:
            driver = "F_DRIVEN"
        elif abs(sp_h) >= abs(sp_F) + DRIVER_DELTA:
            driver = "H_DRIVEN"
        else:
            driver = "BALANCED"
        check("G32-driver-decomposition", True,
              "log10 q = 2 log10|F_{N-1}| - log10 h_{N-1} - "
              "log10(5/7): Spearman(2lgF, lgh) = %+.3f (covariance "
              "bar %.1f) -- the two terminal components track each "
              "other; residual correlations Spearman(lgq, 2lgF) "
              "%+.3f vs (lgq, lgh) %+.3f (delta %.1f) => DRIVER "
              "%s: q is the residual of the F^2-vs-h covariation, "
              "any terminal proof must bound the RATIO, not "
              "either side" % (sp_x, COVAR_BAR, sp_F, sp_h,
                               DRIVER_DELTA, driver))
    else:
        trend, driver = "SMOKE_NA", "SMOKE_NA"
        check("G31-q-trend", True, "SMOKE: skipped")
        check("G32-driver-decomposition", True, "SMOKE: skipped")
    # (b3-i) the corner ray = the t* normal form
    lin_w = 0.0
    slope_main = slope_deep = 0.0
    root_main = root_deep = 0.0
    for p in sample:
        D0, Dh, D1 = ray[p["kz"]]
        lin_w = max(lin_w, abs(Dh - 0.5 * (D0 + D1))
                    / max(abs(D1), 1e-300))
        slope = D1 - D0
        troot = -D0 / slope
        q = float(p["rho"][p["N"] - 1]) / B57
        dq = abs(troot - q)
        ds = abs(slope / B57 - 1.0)
        if p["N"] <= DEEP_N:
            root_main = max(root_main, dq)
            slope_main = max(slope_main, ds)
        else:
            root_deep = max(root_deep, dq)
            slope_deep = max(slope_deep, ds)
    check("G33-tstar-corner-ray",
          lin_w <= LIN_BAR and slope_main <= SLOPE_BAR_MAIN
          and slope_deep <= SLOPE_BAR_DEEP
          and root_main <= ROOT_BAR_MAIN
          and root_deep <= ROOT_BAR_DEEP,
          "corner ray B(t) = S_{N-2} + t(5/7): D_N(t) AFFINE "
          "(collinearity worst %.1e, bar %.0e), slope == 5/7 "
          "(rel %.1e main / %.1e deep, bars %.0e/%.0e, amendment "
          "a1), machine root == q_N (worst %.1e main / %.1e "
          "deep, bars %.0e/%.0e) on %d/%d windows: the terminal "
          "budget question IS a t*-coordinate in the sealed r238 "
          "normal form (pivot affine slope-1 in its one forced "
          "parameter, coordinate = ray crossing, wall = q_N < 1)"
          % (lin_w, LIN_BAR, slope_main, slope_deep,
             SLOPE_BAR_MAIN, SLOPE_BAR_DEEP, root_main, root_deep,
             ROOT_BAR_MAIN, ROOT_BAR_DEEP, len(sample),
             len(sample)))
    if not smoke:
        n_cross = n_lt1 = 0
        tq, tt_ = [], []
        for p, q in zip(packs, qs):
            ts, crossing = tstar_r238(p)
            if crossing:
                n_cross += 1
                tq.append(q)
                tt_.append(ts)
                if ts < 1.0:
                    n_lt1 += 1
        sp_qt = CT.spearman(tq, tt_) if len(tq) >= 3 else float("nan")
        ok_cens = (n_cross == R238_CROSS and n_lt1 == R238_LT1)
        check("G34-tstar-r238-census", ok_cens,
              "r238 instance re-derived on all 42 (m_free "
              "convention gammahat_{N,free} = gammahat_{N-1}): %d "
              "down-crossing (prior %d), %d below 1 (prior %d, = "
              "the delta = 0 set); Spearman(q_N, t*_r238) on the "
              "crossing windows = %+.3f -- SAME sealed normal "
              "form, DIFFERENT terminal data (m_{2N} vs F_{N-1}); "
              "the predicates differ on exactly the t* < 1 "
              "windows where q_N < 1 throughout: one COORDINATE, "
              "two instances, never claimed numerically equal"
              % (n_cross, R238_CROSS, n_lt1, R238_LT1, sp_qt))
        vT = ("TSTAR_IDENTIFIED(one normal form, two data "
              "instances)"
              if (ok_cens and lin_w <= LIN_BAR
                  and slope_main <= SLOPE_BAR_MAIN
                  and slope_deep <= SLOPE_BAR_DEEP
                  and root_main <= ROOT_BAR_MAIN
                  and root_deep <= ROOT_BAR_DEEP)
              else "TSTAR_OPEN")
    else:
        check("G34-tstar-r238-census", True, "SMOKE: skipped")
        vT = "TSTAR_SMOKE_NA"
    w_note = []
    for c in ctrl:
        pc = ctrl[c]
        pm = pmax_of(pc)
        q_pre = float(pc["rho"][pm - 1]) / B57
        q_full = float(pc["rho"][pc["N"] - 1]) / B57
        w_note.append("%s q_pre@%d %.1e / q_full %+.2f [INDEF]"
                      % (c, pm, q_pre, q_full))
    check("G35-world-q", True,
          "controls before their base flip: %s -- the pre-flip "
          "terminal increments are STRUCTURALLY TINY (the quiet "
          "zone, r246), the control q-question only becomes "
          "nontrivial in the indefinite continuation where it is "
          "algebraic (typed, not a Hilbert-space statement); the "
          "controls are discriminated by the WALL, not by q"
          % "; ".join(w_note))

    # ---------------- S4: LEG C -- drain profile anatomy
    section("S4  LEG C -- DRAIN PROFILE ANATOMY")
    p0s, sh_h, sh_b, sh_t, r0dev, r0log = [], [], [], [], [], []
    for p in packs:
        N = p["N"]
        S = p["S"]
        St = float(S[N - 1])
        zh = float(S[HEAD_K - 1]) / St
        zt = (St - float(S[N - TAIL_K - 1])) / St
        sh_h.append(zh)
        sh_b.append(1.0 - zh - zt)
        sh_t.append(zt)
        p0s.append(float(p["rho"][0]) / St)
        r0 = float(p["rho"][0])
        r0dev.append(abs(r0 / (p["b1"] ** 2 / p["hv"][0]) - 1.0))
        r0log.append(math.log10(r0))
    p0_med = float(np.median(p0s))
    ok_z = max(r0dev) <= RHO0_ID_BAR and \
        (smoke or P0_BAND[0] <= p0_med <= P0_BAND[1])
    check("G40-zone-profile", ok_z,
          "zones (HEAD < %d / BULK / TAIL last %d) medians H/B/T "
          "= %.3f/%.3f/%.3f; median p_0 = %.3f in [%.2f, %.2f] "
          "range [%.3f, %.3f] (r246 one-mode head reproduced); "
          "SOURCE-PURE WHY: rho_0 == b1^2/h_0 EXACTLY (worst rel "
          "%.1e, bar %.0e) -- the head mode is the raw mass "
          "pairing (border mass)^2/(window mass), no orthogonal-"
          "polynomial oscillation enters; rho_0 ladder spread "
          "%.2f decades%s"
          % (HEAD_K, TAIL_K, float(np.median(sh_h)),
             float(np.median(sh_b)), float(np.median(sh_t)),
             p0_med, P0_BAND[0], P0_BAND[1], min(p0s), max(p0s),
             max(r0dev), RHO0_ID_BAR, max(r0log) - min(r0log),
             " (smoke: band not binding)" if smoke else ""))
    toks = {"EXP": 0, "POW": 0, "IRREGULAR": 0}
    det_note = []
    for p in packs:
        tok, se, re_, sp_, rp = tail_fit(np.asarray(p["rho"],
                                                    float), p["N"])
        toks[tok] += 1
        if p["kz"] in (9, 13):
            rho = np.asarray(p["rho"][:p["N"]], float)
            i0 = int(np.argmin(np.abs(rho[HEAD_K:p["N"]]))) + HEAD_K
            det_note.append(
                "w%d %s (EXP slope %+.4f rms %.2f | POW slope "
                "%+.2f rms %.2f; min rho %.1e at n=%d = %.3f N, "
                "terminal rebound %+.1f dec)"
                % (p["kz"], tok, se, re_, sp_, rp,
                   float(np.abs(rho[i0])), i0, i0 / p["N"],
                   math.log10(float(rho[p["N"] - 1])
                              / float(np.abs(rho[i0])))))
    tmaj = max(toks, key=lambda k: toks[k])
    check("G41-tail-law", True,
          "sealed bulk-window fits (n in [%d, N-%d), winner needs "
          "rms <= %.1f x other): EXP/POW/IRREGULAR = %d/%d/%d of "
          "%d => majority %s; %s -- NO clean decay law: the drain "
          "profile is head-loaded + irregular bulk (r244/r246 "
          "consistent), the near-terminal zone collapses and "
          "rebounds at the razor (measurement)"
          % (HEAD_K, TAIL_K + 1, TAIL_RMS_RATIO, toks["EXP"],
             toks["POW"], toks["IRREGULAR"], len(packs), tmaj,
             "; ".join(det_note)))
    # (c3) majorants
    ward_ok = True
    phat_dev = 0.0
    cov = {"M1_SUP": 0, "M2_CS": 0, "M3_ABS": 0}
    ovs = {k: [] for k in cov}
    loci = []
    for p in packs:
        N = p["N"]
        bxa = np.concatenate([p["dsm"]["xs"], p["dsm"]["ys"]])
        bwa = np.concatenate([p["dsm"]["ws"], -p["dsm"]["vs"]])
        aw = np.abs(bwa)
        tv = float(np.sum(aw))
        Pb = OG.phat_matrix(p["rows"], bxa, N)
        Fhat = Pb @ bwa
        rho_pf = Fhat * Fhat
        rr = np.asarray(p["rho"][:N], float)
        phat_dev = max(phat_dev,
                       float(np.max(np.abs(
                           rho_pf[HEAD_K:N - 1]
                           / rr[HEAD_K:N - 1] - 1.0))))
        m1 = tv * tv * np.max(Pb * Pb, axis=1)
        m2 = tv * ((Pb * Pb) @ aw)
        m3 = (np.abs(Pb) @ aw) ** 2
        budget = (float(p["S"][N - 2]) - float(p["S"][HEAD_K - 1])
                  + B57)
        for nm, m in (("M1_SUP", m1), ("M2_CS", m2),
                      ("M3_ABS", m3)):
            ward_ok = ward_ok and bool(np.all(
                m[HEAD_K:N - 1] >= rr[HEAD_K:N - 1]
                * (1.0 - MAJ_WARD_TOL)))
            sm = float(np.sum(m[HEAD_K:N - 1]))
            if sm <= budget:
                cov[nm] += 1
            ovs[nm].append(sm / budget)
        loci.append((int(np.argmax(m3[HEAD_K:N - 1])) + HEAD_K)
                    / N)
    check("G42-majorant-ward", ward_ok and phat_dev <= PHAT_RHO_BAR,
          "all three sealed candidates are TRUE pointwise bounds "
          "m_n >= rho_n at every degree n in [%d, N-2] on %d/%d "
          "rungs (tol %.0e); phat-route rho vs chain rho worst "
          "rel %.1e (bar %.0e)"
          % (HEAD_K, len(packs), len(packs), MAJ_WARD_TOL,
             phat_dev, PHAT_RHO_BAR))
    best = max(cov, key=lambda k: (cov[k], -float(np.median(ovs[k]))))
    found = cov[best] == len(packs) and not smoke
    ov_med = {k: float(np.median(ovs[k])) for k in ovs}
    vM = ("MAJORANT_FOUND(%s)" % best if found
          else "MAJORANT_OPEN(%s, overshoot x%.1e med, locus "
          "%.2f N)" % (best, ov_med[best],
                       float(np.median(loci))))
    check("G43-majorant-budget", True,
          "budget test sum_{n=8}^{N-2} m_n <= (S_{N-2} - S_7) + "
          "5/7 (head as prefix data): coverage M1_SUP %d/%d "
          "(overshoot med x%.1e) / M2_CS %d/%d (x%.1e) / M3_ABS "
          "%d/%d (x%.1e); break locus argmax_n m_n at median "
          "%.2f N => %s -- the sealed |sigma|-mass bounds break "
          "in the NEAR-TERMINAL zone where h_n collapses: no "
          "mass bound sees the F^2/h cancellation (consistent "
          "with the G32 covariation finding: the budget proof "
          "needs a RATIO object); controls excluded (algebraic "
          "beyond their flip, r246 typing)"
          % (cov["M1_SUP"], len(packs), ov_med["M1_SUP"],
             cov["M2_CS"], len(packs), ov_med["M2_CS"],
             cov["M3_ABS"], len(packs), ov_med["M3_ABS"],
             float(np.median(loci)), vM))

    # ---------------- S5: LEG C4 -- prefix-border dominance
    section("S5  LEG C4 -- PREFIX-BORDER DOMINANCE OVER THE "
            "LADDER")
    e9 = c4_raster(by_kz[9] if 9 in by_kz else BH.wpack(9),
                   ctrl["SCRAMBLE"])
    ok_prior = (e9["ok_pos"] and not e9["null"]
                and abs(e9["Dbo"] / C4_PRIOR["Dbo"] - 1.0)
                <= C4_PRIOR_TOL
                and abs(e9["Gap"] / C4_PRIOR["Gap"] - 1.0)
                <= C4_PRIOR_TOL)
    check("G50-prefix-prior-regate", ok_prior,
          "w9 x SCRAMBLE cleaned raster at n* = %d (separable "
          "cell route, r256 algebra): Dbo* %+.6f (prior %+.6f), "
          "Gap* %+.6f (prior %+.6f), ratio %.4f (r256: 0.814), "
          "rel tol %.0e; r254-a1 sorted-union embedding re-gated"
          % (e9["nstar"], e9["Dbo"], C4_PRIOR["Dbo"], e9["Gap"],
             C4_PRIOR["Gap"], e9["ratio"], C4_PRIOR_TOL))
    if not smoke:
        rows_c4 = []
        for kz in C4_LADDER:
            pM = by_kz[kz] if kz in by_kz else BH.wpack(kz)
            pC = ctrl["SCRAMBLE"] if kz == 9 \
                else BH.wpack(kz, base_kw=dict(scramble_seed=1))
            e = c4_raster(pM, pC)
            rows_c4.append((kz, pM["N"], e))
            if e.get("null", True):
                info("kz%-3d N=%-3d n*=%-3d NULL/empty (emb %s)"
                     % (kz, pM["N"], e["nstar"], e["ok_pos"]))
            else:
                info("kz%-3d N=%-3d n*=%-3d Dbo* %+.4e Gap* "
                     "%+.4e ratio %.3f sign %s"
                     % (kz, pM["N"], e["nstar"], e["Dbo"],
                        e["Gap"], e["ratio"],
                        "OK" if e["sgn_ok"] else "FLIP"))
        live = [(kz, N, e) for kz, N, e in rows_c4
                if not e.get("null", True)]
        emb_ok = all(e["ok_pos"] for _, _, e in rows_c4)
        n_sgn = sum(1 for _, _, e in live if e["sgn_ok"])
        n_band = sum(1 for _, _, e in live
                     if e["sgn_ok"] and LB_LO <= e["ratio"] <= LB_HI)
        ratios_ = [e["ratio"] for _, _, e in live]
        stable = (len(live) > 0
                  and n_band >= STAB_FRAC * len(live) and emb_ok)
        vP = ("PREFIX_DOMINANCE_STABLE(median ratio %.2f)"
              % float(np.median(ratios_)) if stable else
              "PREFIX_DOMINANCE_ARTIFACT(sign %d/%d, ratio "
              "%.3f..%.2f)" % (n_sgn, len(live),
                               min(ratios_), max(ratios_)))
        check("G51-prefix-dominance-ladder", emb_ok,
              "10-rung ladder, per-pair prefix depth n* re-derived "
              "(all embeddings gated): sign(Dbo*) == sign(Gap*) "
              "on %d/%d non-null rungs, ratio in [%.1f, %.1f] on "
              "%d/%d (sealed stability fraction %.1f) => %s -- "
              "honest split: the SIGN of the border excess "
              "(SCRAMBLE border carries more prefix mass) is "
              "universal, the r256 magnitude 0.81 is an n* "
              "coincidence" % (n_sgn, len(live), LB_LO, LB_HI,
                               n_band, len(live), STAB_FRAC, vP))
    else:
        vP = "PREFIX_SMOKE_NA"
        check("G51-prefix-dominance-ladder", True, "SMOKE: skipped")

    # ---------------- S6: LEG D -- must-fails + anchors
    section("S6  LEG D -- FALSIFIERS + MUST-FAILS")
    p9 = by_kz[9] if 9 in by_kz else packs[0]
    N9 = p9["N"]
    D1 = ray[9][2] if 9 in ray else direct_DN(p9, (1.0,))[0]
    ref = B57 - float(p9["rho"][N9 - 1])
    honest = abs(D1 / ref - 1.0)
    ref_shift = B57 - float(p9["rho"][N9 - 2])
    dev1 = abs(D1 / ref_shift - 1.0)
    ok_d1 = dev1 >= LOUD * max(honest, 1e-300)
    check("G60-shifted-telescope-mustfail", ok_d1,
          "telescope with shifted index (rho_{N-2} in place of "
          "rho_{N-1}): dev %.1e = %.1e x honest %.1e (bar %.0f x) "
          "-- the terminal reduction consumes the terminal index "
          "exactly" % (dev1, dev1 / max(honest, 1e-300), honest,
                       LOUD))
    r9 = p9["rows"][N9 - 1]
    F2 = (r9["fb"] * math.exp(r9["Ls"])) ** 2
    h9 = r9["sg_h"] * math.exp(r9["lg_h"])
    rho_swap = h9 / F2
    dev2 = abs(D1 / (B57 - rho_swap) - 1.0)
    ok_d2 = dev2 >= LOUD * max(honest, 1e-300)
    check("G61-swapped-Fh-mustfail", ok_d2,
          "terminal increment read as h_{N-1}/F_{N-1}^2 = %.3f "
          "instead of F^2/h = %.3f: anchor dev %.1e = %.1e x "
          "honest (bar %.0f x) -- rho is F^2/h, not its "
          "reciprocal" % (rho_swap, float(p9["rho"][N9 - 1]),
                          dev2, dev2 / max(honest, 1e-300), LOUD))
    D0_, _, D1_ = ray[9] if 9 in ray else direct_DN(p9,
                                                    (0.0, 0.5, 1.0))
    troot = -D0_ / (D1_ - D0_)
    q9 = float(p9["rho"][N9 - 1]) / B57
    t_wrong = float(p9["rho"][N9 - 1]) / (7.0 / 5.0)
    hon_r = max(abs(troot - q9), 1e-12)
    dev3 = abs(t_wrong - troot)
    ok_d3 = dev3 >= LOUD * hon_r
    check("G62-tstar-wrong-normalization-mustfail", ok_d3,
          "t* claimed with the wrong normalization rho/(7/5) = "
          "%.6f vs machine root %.6f: miss %.1e = %.1e x honest "
          "%.1e (bar %.0f x) -- the 5/7 ray normalization is "
          "content, not a label" % (t_wrong, troot, dev3,
                                    dev3 / hon_r, hon_r, LOUD))
    pS = ctrl["SMOOTH"]
    r0S = float(pS["rho"][0])
    r1S = max(abs(float(x)) for x in pS["rho"][1:pS["N"]])
    qS = float(pS["rho"][pS["N"] - 1]) / B57
    DS = direct_DN(pS, (1.0,))[0]
    ok_d4 = (r1S / r0S <= SM_ALIAS_BAR and qS <= SM_Q_BAR
             and abs(DS / B57 - 1.0) <= SM_DN_BAR)
    check("G63-smooth-anchor", ok_d4,
          "SMOOTH self-alias: max|rho_{n>=1}|/rho_0 = %.1e (bar "
          "%.0e), q_N = %.1e (bar %.0e), D_N == 5/7 rel %.1e "
          "(bar %.0e) -- the terminal question trivializes "
          "EXACTLY when the source aliases: q is source-driven"
          % (r1S / r0S, SM_ALIAS_BAR, qS, SM_Q_BAR,
             abs(DS / B57 - 1.0), SM_DN_BAR))

    # ---------------- S7: verdict
    section("S7  VERDICT")
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the terminal reduction typed EXACT-BY-"
          "CONSTRUCTION with mp-warded Schur telescope, the 5/7 "
          "provenance audit, the q_N census with the covariation "
          "driver law, the corner-ray t* normal form, the sealed "
          "majorant break anatomy, and the dominance-ladder "
          "adjudication of the r256 side-finding")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        verd = " + ".join([
            vA,
            "TERMINAL_Q_LAW(%s, %s)" % (trend, driver),
            vT, vM, vP])
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G96-verdict", npass == len(CHECKS),
          "%s%s -- SATZ-LEVEL (machine-gated): the telescope "
          "collapse and the corner-ray normal form; MEASURED: "
          "q census, trend, covariation, tail law, majorant "
          "break, dominance ladder; OPEN: a source-pure 5/7, any "
          "a-priori terminal bound, the budget bound and the "
          "base law (r243/r246/r247/r256/r257 stand); NO RH claim"
          % (verd, " (SMOKE)" if smoke else ""))
    wall = time.time() - T0_WALL
    check("G99-runtime", wall <= 1800.0,
          "WALL %.1f s (bar 1800)" % wall)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    print("\n" + "=" * 78)
    print("RESULT: %d/%d gates PASS%s   SPEC_SHA %s"
          % (npass, len(CHECKS), " (SMOKE)" if smoke else "",
             SPEC_SHA[:16]))
    print("NO RH CLAIM in either direction.")
    print("=" * 78)
    return 0 if npass == len(CHECKS) else 1


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

_SRC_3 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""parametrix_pass_probe -- PRIME.PORT.RHP.PARAMETRIX.PASS.01
(round 259): the ANALYTIC half of the frozen micro-falsifier
(PRIME.FREEMOMENT.POSITIVEPREFIX.01).  r257 passed the falsifier at
the COEFFICIENT-FIELD level (blind source-only pivot field via
independent slogdet minors -- exact, not a model); the PARAMETRIX
pass stays OPEN: an analytic model (closed formulas / local
connection, NO exact determinant or minor computation) that blindly
predicts (i) the w9 control flips SCRAMBLE 21 / EPSTEIN 25 /
SMOOTH 27 and (ii) the five-window forced-tail survival
(0, 2, 2, 3, 1) at the flip degrees 184/153/170/367/592 -- while
staying false-positive-free on MAIN up to N_w - 1.  BUILDING
BLOCKS: r255 exact discrete saddle (S*_n = top-n by QP mass,
E(S) = rho_S^T A rho_S + V^T rho_S, parity sign channel; holds the
h-rate 4/4 but misplaces the flips 8/18 vs 25/27) with
ORIENTATION_LOWDIM(1) (one 0.2-dec swap separates model from truth
at the true flip degree) and the r254 handover (the flip carries
|gamma| > 1: a JUMP, not a soft crossing); r231 L-gauge midpoint
connection (h-free and sign-blind: the orientation sits exclusively
in the h-chain); r252 (outer model orientation-blind).  WORKING
HYPOTHESIS to adjudicate: the flip is a LEVEL CROSSING of the two
lowest parity-resolved saddle-energy branches -- if true, the flip
degree is the crossing point of two analytic curves and becomes
PREDICTABLE.

EXPLORATION ONLY (2026-08-24).  experiments/ level: NO promotion,
NO ledger row, NO marker moved, NO RH CLAIM in either direction.

INDEX FIREWALL (binding, r238-r257 discipline): w = window (kz),
N_w = builder depth, n = chain degree; free pivots h_{w,n}
(n < N_w) are the proof objects; ground truth (h signs, flip
degrees, forced-tail offsets, per-degree sign(det G_n) =
prod_{k<n} sg h_k) enters ANATOMY TARGETS AND GATES ONLY.  BLIND
PROTOCOL (hard, the r257 firewall pattern): the sealed predictor
functions consume node positions + signed weights + the QP
minimizer (capped-simplex equilibrium on the SOURCE energy) +
closed-form energy/swap formulas ONLY; a dedicated AST scope audit
excludes BOTH the chain identifiers (rows, lg_h, sg_h, gam_next,
nf, fb, hv, Fv, rho, hlog, lgt, wpack, bord_chain) AND every
linear-algebra resummation primitive (linalg, slogdet, det, eig*,
inv, solve, cholesky, qr, svd) from the predictor scope -- the
parametrix may not secretly BE the determinant.  A deliberately
minor-reading mutant must be FLAGGED (must-fail).  No zero/prime
oracles anywhere (AST firewall).

LEG A -- SADDLE SELECTION ANATOMY (understand first, model
second), on the w9 controls around the true flips (EPSTEIN
[22, 27], SMOOTH [24, 29], SCRAMBLE [18, 23]) and on MAIN w9 at
the same absolute degrees [18, 29]:
(a1) the CRITICAL SWAP: at each anatomy degree, from the 1-swap-
  stabilized saddle S°_n (greedy best-swap descent from the QP
  top-n; the r255 saddle refined -- disclosed refinement, sealed
  before evaluation), the minimal parity-flipping swap (i -> o):
  index distance |i - o|, weight-sign class (sgw_i, sgw_o),
  boundary ranks (QP-mass rank of o beyond n; rank of i inside),
  and the branch gap in decades.  SEALED STATISTIC
  SWAP_SHORT_RANGE iff median |i - o| <= 3 over the control flip
  windows (is the critical direction a short-range boundary
  pair?).
(a2) MAIN vs CONTROL (the 1-bit question in pure form): does the
  1-swap statistic SEPARATE MAIN at [18, 29] (no flip) from the
  controls at their flip degrees?  SEALED RULE: SWAP_STAT_
  SEPARATES iff min over MAIN anatomy degrees of the branch gap
  > max over control flip-degree gaps ({nf, nf+1} per control);
  else SWAP_STAT_NOT_SEPARATING -- and then the r255
  ORIENTATION_LOWDIM(1) reading must be REVISED (the swap margin
  is not a source-pure selector): SELECTION_EXTENSIVE_AFTER_ALL.
(a3) LEVEL CROSSING: the two parity-resolved branch minima
  E_even(n), E_odd(n) (free 1-swap-stable minimum + opposite-
  parity branch = cheapest parity-flip seed then parity-keeping
  descent, N_SEED seeds).  Crossing degree = first n where the
  odd branch goes below.  SEALED RULE: LEVEL_CROSSING_AT_FLIP iff
  |crossing - nf| <= 2 on BOTH EPSTEIN and SMOOTH; else
  LEVEL_CROSSING_REFUTED.  MAIN: the count of lower-branch parity
  switches over the full free window (each one a would-be flip
  that the true chain does not have) -- the crossing picture's
  false-positive bill.  The |gamma| > 1 jump (r254 handover) is
  re-derived gate-side at the true flips and compared with the
  true |gamma| at the MODEL crossing degrees (does the truth
  jump where the model crosses? -- informational).

LEG B -- THE PARAMETRIX CANDIDATES (exactly 3, sealed; each
consumes source + QP minimizer + closed formulas only, per-degree
model sign sg^cand(D_n), model h-sign = sg(D_{n+1}) sg(D_n),
first-flip = first degree with model h-sign < 0):
(P1) TWO-BRANCH: sg(D_n) = parity of the lower parity-resolved
  branch (the a3 object; flip at the branch crossing).
(P2) SELECTION RULE (r255 + LOWDIM correction): sg(D_n) =
  parity(S*_n) from the RAW QP top-n, FLIPPED iff the minimal
  parity-flipping swap from S*_n has dE < 0 (the r255 leg-C
  margin, now consumed as a predictor correction).
(P3) HYBRID with hysteresis: L-gauge/outer rate is sign-blind
  (r255 4/4, imported result, not re-adjudicated); orientation =
  P1 branch sign but a sign SWITCH is accepted only when the
  opposite branch is lower by more than THETA = 0.05 dec (the
  jump discipline from the r254 handover: a flip is a threshold
  event, not a soft degeneracy).
ADJUDICATION per candidate (gates, ground truth enters here
only): (arm 1) control flips: first-flip within +-2 of 21/25/27
(also +-0 reported); (arm 2) forced tail: first-flip offset
j = n - N_w on the five windows (9, 12, 13, 26, 40) == frozen
prior (0, 2, 2, 3, 1); (arm 3) MAIN clean: NO model h-flip below
N_w - 1 on the four full-depth mains (9, 12, 13, 26).  Per-degree
missign fractions (P1/P2) per window recorded for the leg-C
typing.

LEG C -- HONEST BOUNDARY (if no candidate fully passes): type
precisely WHAT is missing: (i) rate ok / selection wrong -> the
measured misselection statistics (degrees off, systematic
direction, missign fraction); (ii) controls ok / MAIN false-
positive (model too flip-happy); (iii) the crossing mechanism
does not exist (branches do not cross at the flip degree) ->
LEVEL_CROSSING_REFUTED stands as a negative finding.  The half
falsifier then stays honestly OPEN with the obstacle named.

LEG D -- FALSIFIERS + MUST-FAILS (each loud) + WARDS:
(m1) MINOR-ORACLE MUTANT: a predictor variant that reads the
  chain sign field must be FLAGGED by the predictor AST audit
  while the sealed scope stays clean;
(m2) WRONG VANDERMONDE EXPONENT (r255-m1 pattern; replaces the
  drafted swapped-branch mutant, amendment a1): the pair energy
  counted once instead of twice must move the stable-saddle
  energy at the sealed degree (w9, n = 21) by >= 10 decades --
  the energy form is load-bearing;
(m3) r255 ANCHOR: P2 WITHOUT the swap correction (the bare r255
  parity rule) must reproduce the r255 misplacements EXACTLY
  (EPSTEIN first flip 8, SMOOTH 18) -- the correction is real,
  the anchor ties this round to the r255 record;
(w1) mp FLIP WARDS (dps 40, r257 pattern, gate side): sign det
  G_25/G_26 = +/- on EPSTEIN, sign det G_27/G_28 = +/- on SMOOTH
  (exact-arithmetic confirmation of the ground truth the
  candidates are judged against);
(w2) mp ENERGY WARD (dps 60): the SMOOTH branch energies at the
  sealed degrees {27, 28} recomputed in mpmath; |E_mp - E_f64| <=
  1e-6 nats (the 0.004-dec gaps are not f64 noise);
(w3) CHEBYSHEV TOY ANCHOR (64 nodes, discrete U-weight, masses
  5..17): positive weights -> NO parity-flipping swap exists; all
  three candidates must be flip-free and all parities +1.

SEALED CONSTANTS: mains (9, 12, 13, 26) full depth + EXT; tail
windows (9, 12, 13, 26, 40), prior offsets (0, 2, 2, 3, 1), EXT
6; control flips EPSTEIN/SCRAMBLE/SMOOTH = 25/21/27, control
sweep 2..nf+11; anatomy windows: EPSTEIN [22, 27], SMOOTH
[24, 29], SCRAMBLE [18, 23], MAIN [18, 29]; QP FISTA iters 8000,
tol 1e-8, residual bar 1e-6, warm ascending; stabilizer max 400
swaps, seed count N_SEED 6, swap-stability floor -1e-13; THETA
0.05 dec; flip tolerance +-2 (and +-0 reported); short-range bar
median |i - o| <= 3; w40 sweep early-stops once ALL candidates
have flipped (disclosed: MAIN-clean is adjudicated on the four
full-depth mains; w40 feeds arm 2 only); toy 64 nodes masses
5..17; mp wards dps 40 / 60, energy bar 1e-6 nats; must-fail
bars: m2 >= 10 dec at (w9, n = 21), m3 exact (8, 18);
runtime <= 1800 s; smoke = w9 masses 2..42 + controls 2..nf+8 +
toy, tails / w40 / mp wards skipped, no adjudication.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  PARAMETRIX_PASSED(cand, +-tol) iff some candidate passes arms
    1 AND 2 AND 3;
  else PARAMETRIX_PARTIAL(what carries, what misses) iff some
    candidate passes at least one arm fully;
  else PARAMETRIX_FAILED(typed per leg C)
+ LEVEL_CROSSING_AT_FLIP(degrees) / LEVEL_CROSSING_REFUTED
    (crossing vs flip per control, MAIN switch count)
+ SWAP_STAT_SEPARATES / SWAP_STAT_NOT_SEPARATING
+ SELECTION_EXTENSIVE_AFTER_ALL iff SWAP_STAT_NOT_SEPARATING
    (the r255 LOWDIM(1) reading revised, honestly)
  / SELECTION_LOWDIM_CONFIRMED otherwise.
Honesty before beauty: a failed parametrix leaves the analytic
half of the micro-falsifier OPEN with the obstacle named; the
r257 coefficient-field pass, the budget bound and the base law
stay as they are (r243/r247/r250/r252/r255/r256/r257 stand).

PRE-SPEC SCRATCH CALIBRATION (disclosed, r257 practice): a
scratch scan (deleted) established the machinery scales (QP warm
sweep cost, stabilizer swap counts, branch-gap magnitudes
0.005-0.6 dec, the SMOOTH stabilizer needing > 60 greedy swaps)
and showed the qualitative landscape on w9 BEFORE this spec was
sealed; every bar, form and verdict rule above was frozen before
the full-record evaluation.

CALIBRATION AMENDMENTS (disclosed, frozen; found in the FIRST
smoke pass BEFORE any full-record evaluation): (a1) the drafted
m2 "swapped branches" mutant (sign of the UPPER branch) is
UNOBSERVABLE in the flip channel BY CONSTRUCTION -- the model
h-sign sg(D_{n+1}) sg(D_n) is invariant under a GLOBAL parity
negation, so exchanging the branch order at every degree moves
no flip (a structural fact about every per-degree sign model,
worth recording); m2 is replaced by the r255-m1-shaped WRONG
VANDERMONDE EXPONENT loudness at the sealed degree (w9, n = 21),
bar >= 10 dec.  (a2) the w2 mp energy ward of the first full
attempt indexed the saddle config into the UNSORTED union arrays
while the configs live in the SORTED union_setup order -- pure
implementation fix in a gate-side ward (r252-a1 precedent), no
bar touched.  No bar, form or verdict rule of the candidates,
anatomy or adjudication moved at any point.

RECORD TABLES (frozen after calibration pass 1, 19/19 gates;
run 2 must reproduce bit-for-bit up to the WALL line):
* CENSUS: mains w9/w12/w13/w26 N = 184/151/168/364 POSITIVE_
  PREFIX; controls re-derived 25/21/27; 1586 QP equilibria,
  residual worst 1.0e-08 (bar 1e-6), masses integer-exact; w40
  (N = 591) early-stopped at mass 597; mp flip wards (dps 40):
  EPSTEIN sign det G_25/G_26 = +1/-1, SMOOTH G_27/G_28 = +1/-1;
  mp energy ward (dps 60) max |E_mp - E_f64| = 0.0e+00 nats
  (bar 1e-6): the milli-decade branch gaps are exact, not f64
  noise.
* LEG A ANATOMY (a1): the critical parity-swap at the control
  flips is a SHORT-RANGE OPPOSITE-SIGN BOUNDARY PAIR -- median
  |i - o| = 2 over the anatomy windows (EPSTEIN 341<->339 /
  184->182 d = 2 at the flip, SMOOTH 363->364 d = 1 throughout,
  SCRAMBLE 72<->75 d = 3 / 278<->274 d = 4), weight signs
  opposite by construction => SWAP_SHORT_RANGE.  (a2) the SAME
  structure sits on MAIN w9 at [18, 29] (pair 364<->365, d = 1,
  gap 0.013-0.018 dec from n = 24 on): control flip-degree gaps
  0.0045/0.0339 (EPST), 0.1981/0.1950 (SMOOTH), 0.0142/0.0054
  (SCR) vs MAIN anatomy gaps 0.0133..0.5279 -- full overlap
  (MAIN min 0.0133 < control max 0.1981) => SWAP_STAT_NOT_
  SEPARATING: no 1-swap observable separates MAIN-at-no-flip
  from control-at-flip => SELECTION_EXTENSIVE_AFTER_ALL (the
  r255 LOWDIM(1) reading is hereby revised: the 0.2-dec swap
  EXISTS at the flip degree, but the missing information is NOT
  a 1-dimensional selection error -- the parity of the energy-
  ordered configuration is wrong on EXTENDED stretches on every
  world).  (a3) branch crossings vs true flips: EPSTEIN
  crossing 9 vs flip 25 (off 16), SMOOTH 19 vs 27 (off 8),
  SCRAMBLE 16 vs 21 (off 5) => LEVEL_CROSSING_REFUTED; MAIN w9
  lower-branch parity switches below N-1: 45 (45 would-be
  flips, zero true ones; odd-lower stretches up to 11 degrees
  with gaps up to 0.20 dec while det G stays positive).
  |gamma| anatomy (gate side): true lg10|gamma| at the flips
  +1.16 (EPST) / +0.41 (SMOOTH) / -0.89 (SCR; the SCRAMBLE flip
  is NOT a jump -- the r254 jump statement holds on EPSTEIN/
  SMOOTH only, disclosed); at the model crossing degrees the
  true values are -0.61 / -0.61 / -0.57: NO jump where the
  model crosses -- the jump belongs to the resummed chain at
  the TRUE flips, not to the branch crossings.
* LEG B CANDIDATES (first flips; true 25/21/27, tail truths
  184/153/170/367/592 = N + (0, 2, 2, 3, 1)):
    P1 two-branch: EPST 8, SCR 15, SMOOTH 18 -- 0/3 within +-2
      (systematically EARLY by 17/6/9 degrees); MAIN first
      false flips w9 39 / w12 16 / w13 18 / w26 51 => arm 3
      0/4; tail offsets j = -145/-135/-150/-313/-525 vs
      (0, 2, 2, 3, 1) => 0/5; per-degree missign fractions
      0.34/0.46/0.37/0.44 on the mains.
    P2 selection rule: EPST 2, SCR 11, SMOOTH 17 -- 0/3 (the
      LOWDIM swap correction does NOT repair the placement; it
      flips EARLIER than the bare rule on every control); MAIN
      11/14/11/28 => 0/4; tail -173/-137/-157/-336/-525 => 0/5;
      missign 0.57/0.37/0.71/0.43.
    P3 hybrid hysteresis (THETA 0.05): EPST None, SCR 15,
      SMOOTH 19 -- 0/3; MAIN first false flips 181/None/None/
      None (the 0.05-dec bar suppresses the shallow noise
      entirely on w12/w13/w26, but the deep w9 odd stretch
      punches through at 181 -- three degrees BEFORE the true
      forced-tail flip 184 and still below N-1: a near-miss
      that is honestly a false positive) => arm 3 0/4; tail
      w9 j = -3, others None => 0/5.
  => no candidate passes any arm fully.  PARAMETRIX_FAILED.
* LEG C TYPING: (i) the rate is NOT the obstacle (r255 b2 held
  it 4/4, imported); the SELECTION is: misselection is
  systematically EARLY (6..17 degrees before truth on every
  control, every candidate), missign fractions 0.34-0.71;
  (ii) every candidate is too flip-happy on MAIN (first false
  positive at degree 11-181 of 151-364; even the hysteresis
  candidate that is clean on 3/4 windows breaks on w9); (iii)
  the crossing mechanism DOES NOT EXIST at the flip degree:
  the parity-resolved branches cross 5-16 degrees early, and
  on MAIN w9 they cross 45 times without a single true flip;
  the true sign is carried by COHERENT CANCELLATION across the
  configuration ensemble (the odd branch sits BELOW the even
  branch by up to 0.20 dec over 9+ consecutive degrees on
  SMOOTH and MAIN while det G stays positive) -- a resummation
  effect that no dominant-configuration model at any k-swap
  resolution sees (a 1-swap signed partition resummation was
  scratch-tested pre-spec: the parity-keeping entropy dominates
  the bracket, sign unchanged).  THE PARAMETRIX GAP IS A
  RESUMMATION GAP, NOT A SELECTION GAP.
* LEG D: m1 minor-oracle mutant FLAGGED (rows/sg_h), sealed
  scopes CLEAN (10 predictor functions, 0 hits); m2 wrong
  Vandermonde exponent: 47.6 dec at (w9, n = 21) (bar 10,
  LOUD); m3 bare-r255 anchor: EPSTEIN 8, SMOOTH 18 reproduced
  EXACTLY; toy: 0 parity-flip swaps exist, all candidate signs
  +1 on 13/13 masses.
* VERDICT: PARAMETRIX_FAILED(selection wrong on 3/3 controls +
  MAIN false positives; typed i+ii+iii) + LEVEL_CROSSING_
  REFUTED(EPST 9 vs 25, SMOOTH 19 vs 27, SCR 16 vs 21; MAIN 45
  switches) + SWAP_STAT_NOT_SEPARATING + SELECTION_EXTENSIVE_
  AFTER_ALL; 19/19 gates, wall 155.5 s full / 9.7 s smoke.
  READING: the analytic half of the micro-falsifier stays OPEN
  with the obstacle NAMED and MEASURED -- the orientation is
  not a saddle-selection observable at any 1-swap resolution;
  the minimal analytic object that could carry it must resum
  the near-degenerate configuration ensemble coherently (the
  r257 minor scan does exactly that, exactly), and the r255
  LOWDIM(1) selection reading is revised to SELECTION_
  EXTENSIVE_AFTER_ALL.
AMENDMENTS AFTER FREEZE: NONE.

NO RH CLAIM IN EITHER DIRECTION.  NOT evidence for or against RH.
"""

from __future__ import annotations

import argparse
import ast
import hashlib
import math
import os
import sys
import time

import numpy as np
import mpmath as mp

HERE = os.path.dirname(os.path.abspath(__file__))
if HERE not in sys.path:
    sys.path.insert(0, HERE)

import bordered_hankel_probe as BH           # noqa: E402 r244
import centered_basefiber_probe as CB        # noqa: E402 r250
import hirota_sign_probe as HS               # noqa: E402 r226
import port_integrable_kernel_probe as PIK   # noqa: E402 v881
import principal_bessel_probe as PB          # noqa: E402 r243
import szego_equilibrium_probe as SZ         # noqa: E402 r232a
import v563_paper2_readouts as core          # noqa: E402 READ-ONLY

MAINS = (9, 12, 13, 26)
TAIL_WINDOWS = (9, 12, 13, 26, 40)
PRIOR_OFFSETS = (0, 2, 2, 3, 1)
CTRL_FLIPS = {"EPSTEIN": 25, "SCRAMBLE": 21, "SMOOTH": 27}
ANAT_WIN = {"EPSTEIN": (22, 27), "SMOOTH": (24, 29),
            "SCRAMBLE": (18, 23), "MAIN": (18, 29)}
EXT = 6
CTRL_PAD = 11
QP_ITERS = 8000
QP_TOL = 1e-8
QP_RES_BAR = 1e-6
STAB_MAX = 400
STAB_FLOOR = -1e-13
N_SEED = 6
THETA = 0.05
FLIP_TOL = 2
SHORTRANGE_BAR = 3
TOY_M = 64
TOY_MASSES = tuple(range(5, 18))
MP_FLIP_DPS = 40
MP_EN_DPS = 60
MP_EN_BAR = 1e-6
M2_DEG = 21
M2_LOUD_DEC = 10.0
M3_ANCHOR = {"EPSTEIN": 8, "SMOOTH": 18}
L10 = math.log(10.0)
PRED_FUNCS = ("psel_top", "pparity", "penergy", "pswap", "pstab",
              "pstab_keep", "pbranch", "pred_p2", "pred_p1_sign",
              "pred_p3_seq")
PRED_FORBIDDEN = {"rows", "lg_h", "sg_h", "gam_next", "nf", "fb",
                  "hv", "Fv", "rho", "hlog", "lgt", "wpack",
                  "bord_chain", "linalg", "slogdet", "det",
                  "eigvalsh", "eigh", "eig", "inv", "solve",
                  "cholesky", "qr", "svd"}
CAL_VERDICT = (
    "PARAMETRIX_FAILED(selection wrong on 3/3 controls + MAIN "
    "false positives; typed i+ii+iii) + LEVEL_CROSSING_REFUTED"
    "(EPST 9 vs 25, SMOOTH 19 vs 27, SCR 16 vs 21; MAIN 45 "
    "switches) + SWAP_STAT_NOT_SEPARATING + "
    "SELECTION_EXTENSIVE_AFTER_ALL")

SPEC_SHA = hashlib.sha256(__doc__.encode("utf-8")).hexdigest()
T0_WALL = time.time()
CHECKS: list = []


def check(name, ok, detail):
    ok = bool(ok)
    CHECKS.append((name, ok, detail))
    print("  [%s] %-42s %s" % ("PASS" if ok else "FAIL", name, detail),
          flush=True)
    return ok


def info(msg):
    print("  [INFO] " + msg, flush=True)


def section(t):
    print("\n" + "-" * 78 + "\n" + t + "\n" + "-" * 78, flush=True)


def firewall_audit():
    """standing zero/prime firewall + the sealed predictor scope
    audit: the parametrix may not secretly be the determinant."""
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    forb = {"zeta" + "zero", "n" + "zeros", "prime" + "range",
            "is" + "prime", "gram" + "point"}
    bad = []
    for node in ast.walk(tree):
        nm = node.attr if isinstance(node, ast.Attribute) else (
            node.id if isinstance(node, ast.Name) else None)
        if nm and nm.lower() in forb:
            bad.append("%s@%d" % (nm, node.lineno))
    hits = []
    for fn in PRED_FUNCS:
        hits += predictor_scope_audit(fn)
    ok = (not bad) and (not hits)
    return ok, ("NO zero/prime oracles; predictor scope CLEAN: %d "
                "sealed functions consume node positions + signed "
                "weights + the QP minimizer + closed-form energy/"
                "swap formulas only (chain identifiers AND linalg "
                "resummation primitives excluded: %s); ground "
                "truth enters anatomy targets and gates only"
                % (len(PRED_FUNCS), sorted(PRED_FORBIDDEN))
                if ok else "; ".join(bad + hits))


def predictor_scope_audit(funcname):
    """walk ONLY the named function's subtree; flag any forbidden
    identifier / attribute / string constant."""
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    hits = []
    for node in ast.walk(tree):
        if isinstance(node, ast.FunctionDef) and node.name == funcname:
            for sub in ast.walk(node):
                nm = None
                if isinstance(sub, ast.Attribute):
                    nm = sub.attr
                elif isinstance(sub, ast.Name):
                    nm = sub.id
                elif isinstance(sub, ast.Constant) \
                        and isinstance(sub.value, str):
                    nm = sub.value
                if nm in PRED_FORBIDDEN:
                    hits.append("%s:%s@%d" % (funcname, nm,
                                              sub.lineno))
    return hits


# --------------------------- sealed predictor functions (BLIND)
def psel_top(dens, n):
    """S*_n: top-n nodes by QP mass, stable tie-break by index
    (r255 sealed rounding rule)."""
    order = np.lexsort((np.arange(len(dens)), -dens))
    b = np.zeros(len(dens), bool)
    b[order[:int(n)]] = True
    return b


def pparity(sgw, b):
    """parity(S) = prod sign(wt_j) over the selected subset."""
    return -1 if (int(np.sum(sgw[b] < 0)) % 2) else 1


def penergy(A, V, b):
    """exact discrete energy E(S) = rho_S^T A rho_S + V^T rho_S."""
    r = b.astype(float)
    return float(r @ (A @ r)) + float(V @ r)


def pswap(A, V, b):
    """closed-form single-swap energy field dE[i, o] = base_o -
    base_i - 2 A_io, base = 2 (A rho_S) + V (r255 leg-C form)."""
    r = b.astype(float)
    base = 2.0 * (A @ r) + V
    iS = np.flatnonzero(b)
    iO = np.flatnonzero(~b)
    dE = (base[iO][None, :] - base[iS][:, None]
          - 2.0 * A[np.ix_(iS, iO)])
    return dE, iS, iO


def pstab(A, V, b):
    """greedy best-single-swap descent to a 1-swap-stable saddle."""
    b = b.copy()
    for _ in range(STAB_MAX):
        dE, iS, iO = pswap(A, V, b)
        k = int(np.argmin(dE))
        ii, oo = np.unravel_index(k, dE.shape)
        if dE[ii, oo] >= STAB_FLOOR:
            break
        b[iS[ii]] = False
        b[iO[oo]] = True
    return b


def pstab_keep(A, V, sgw, b):
    """greedy descent restricted to parity-KEEPING swaps (stays on
    one branch)."""
    b = b.copy()
    for _ in range(STAB_MAX):
        dE, iS, iO = pswap(A, V, b)
        keep = (sgw[iS][:, None] * sgw[iO][None, :]) > 0
        dE = np.where(keep, dE, np.inf)
        k = int(np.argmin(dE))
        ii, oo = np.unravel_index(k, dE.shape)
        if dE[ii, oo] >= STAB_FLOOR:
            break
        b[iS[ii]] = False
        b[iO[oo]] = True
    return b


def pbranch(A, V, sgw, b0):
    """parity-resolved two-branch minima from the QP top-n seed:
    free stabilize + keep-stabilize -> (p0, E0); opposite branch
    from the N_SEED cheapest parity-flip seeds + keep descent ->
    E1.  Returns (p0, E0, E1, gap_dec, i*, o*, b_stable)."""
    bst = pstab(A, V, b0)
    bst = pstab_keep(A, V, sgw, bst)
    p0 = pparity(sgw, bst)
    E0 = penergy(A, V, bst)
    dE, iS, iO = pswap(A, V, bst)
    mask = (sgw[iS][:, None] * sgw[iO][None, :]) < 0
    dEm = np.where(mask, dE, np.inf)
    if not np.any(mask):
        return p0, E0, float("inf"), float("inf"), -1, -1, bst
    k = int(np.argmin(dEm))
    ci, co = np.unravel_index(k, dEm.shape)
    flat = np.argsort(dEm, axis=None)[:N_SEED]
    E1 = float("inf")
    for kk in flat:
        ii, oo = np.unravel_index(kk, dEm.shape)
        if not np.isfinite(dEm[ii, oo]):
            continue
        b1 = bst.copy()
        b1[iS[ii]] = False
        b1[iO[oo]] = True
        b1 = pstab_keep(A, V, sgw, b1)
        E1 = min(E1, penergy(A, V, b1))
    return (p0, E0, E1, (E1 - E0) / L10, int(iS[ci]),
            int(iO[co]), bst)


def pred_p1_sign(p0, gap_dec):
    """P1: sign(D_n) = parity of the LOWER branch (gap >= 0 by
    stability: the free minimum owns the sign)."""
    return p0 if gap_dec >= 0.0 else -p0


def pred_p2(A, V, sgw, dens, n):
    """P2: raw r255 parity + LOWDIM swap correction (flip iff the
    best parity-flipping swap from the RAW top-n has dE < 0)."""
    b = psel_top(dens, n)
    p = pparity(sgw, b)
    dE, iS, iO = pswap(A, V, b)
    mask = (sgw[iS][:, None] * sgw[iO][None, :]) < 0
    if not np.any(mask):
        return p
    m = float(np.min(np.where(mask, dE, np.inf)))
    return -p if m < 0.0 else p


def pred_p3_seq(p0s, gaps, theta):
    """P3: branch sign with hysteresis -- a switch is accepted only
    when the opposite branch is lower by more than theta decades
    relative to the current state (threshold-event discipline)."""
    out = []
    cur = None
    for p0, g in zip(p0s, gaps):
        if cur is None:
            cur = p0
        elif p0 != cur and g > theta:
            cur = p0
        out.append(cur)
    return out


# ------------------------------------------------- oracle mutant
def oracle_pred(p, n_hi):
    """DELIBERATE MUST-FAIL MUTANT (m1): reads the chain sign field
    -- the predictor AST audit must FLAG this scope."""
    return [r["n"] for r in p["rows"][:n_hi] if r["sg_h"] < 0]


# ------------------------------------------------------ gate side
def union_arrays(d):
    return (np.concatenate([d["xs"], d["ys"]]),
            np.concatenate([d["ws"], -d["vs"]]))


def truth_sgdet(rows, n_hi):
    """sign(det G_n) = prod_{k<n} sg h_k (gate side)."""
    sg = {0: 1}
    s = 1
    for k in range(min(len(rows), n_hi)):
        s *= int(rows[k]["sg_h"])
        sg[k + 1] = s
    return sg


def world_sweep(d, masses, anat_degs=frozenset()):
    """QP warm sweep + per-mass predictor data for all candidates.
    Consumes SOURCE data only; truth joined outside."""
    x, wt, A, Lip, V = CB.eq_field(d)
    sgw = np.sign(wt)
    dens = None
    res_worst = 0.0
    mass_ok = True
    out = dict(ns=[], p0=[], gap=[], sgP2=[], ci=[], co=[])
    anat = {}
    for n in masses:
        dens, res = SZ.solve_qp(A, Lip, V, float(n), rho0=dens,
                                iters=QP_ITERS, tol=QP_TOL)
        res_worst = max(res_worst, res)
        mass_ok = mass_ok and (int(round(float(np.sum(dens)))) == n)
        b0 = psel_top(dens, n)
        p0, E0, E1, gap, ci, co, bst = pbranch(A, V, sgw, b0)
        out["ns"].append(n)
        out["p0"].append(p0)
        out["gap"].append(gap)
        out["ci"].append(ci)
        out["co"].append(co)
        out["sgP2"].append(pred_p2(A, V, sgw, dens, n))
        if n in anat_degs:
            rk = np.lexsort((np.arange(len(dens)), -dens))
            rank = np.empty(len(dens), int)
            rank[rk] = np.arange(len(dens))
            anat[n] = dict(
                p0=p0, gap=gap, i=ci, o=co,
                dio=abs(co - ci) if ci >= 0 else -1,
                sgi=int(sgw[ci]) if ci >= 0 else 0,
                sgo=int(sgw[co]) if co >= 0 else 0,
                rk_o=int(rank[co]) - n + 1 if co >= 0 else -1,
                rk_i=n - int(rank[ci]) if ci >= 0 else -1,
                E0=E0, E1=E1, bst=bst.copy())
    out["ns"] = np.asarray(out["ns"], int)
    out["p0"] = np.asarray(out["p0"], int)
    out["gap"] = np.asarray(out["gap"], float)
    out["sgP2"] = np.asarray(out["sgP2"], int)
    return out, anat, res_worst, mass_ok, (x, wt, A, V, sgw)


def cand_signs(sw):
    """per-degree model sign(D_n) for P1/P2/P3 from the sweep."""
    sg1 = np.array([pred_p1_sign(p, g)
                    for p, g in zip(sw["p0"], sw["gap"])], int)
    sg2 = sw["sgP2"]
    sg3 = np.asarray(pred_p3_seq(list(sw["p0"]), list(sw["gap"]),
                                 THETA), int)
    return {"P1": sg1, "P2": sg2, "P3": sg3}


def first_flip(ns, sg):
    """first degree n with model h-sign sg(D_{n+1}) sg(D_n) < 0."""
    for i in range(len(ns) - 1):
        if ns[i + 1] == ns[i] + 1 and sg[i + 1] * sg[i] < 0:
            return int(ns[i])
    return None


def missign_frac(ns, sg, sgdet):
    hit = tot = 0
    for i, n in enumerate(ns):
        if int(n) in sgdet:
            tot += 1
            hit += int(sg[i] != sgdet[int(n)])
    return hit / max(tot, 1)


def mp_flip_ward(xu, wu, nlist, dps):
    """exact-precision determinants of the scaled-Cheb source Gram
    at the sealed flip-adjacent sizes (r257 verbatim, GATE side)."""
    mp.mp.dps = dps
    lo, hi = float(np.min(xu)), float(np.max(xu))
    x0 = mp.mpf(0.5 * (lo + hi))
    rh = mp.mpf(0.5 * (hi - lo))
    xs = [mp.mpf(float(v)) for v in xu]
    ws = [mp.mpf(float(v)) for v in wu]
    tv = [(x - x0) / rh for x in xs]
    n_hi = max(nlist)
    P = [[mp.mpf(1)] * len(xs), [2 * t for t in tv]]
    for _k in range(2, n_hi):
        P.append([2 * t * a - b
                  for t, a, b in zip(tv, P[-1], P[-2])])
    G = mp.matrix(n_hi, n_hi)
    for i in range(n_hi):
        for j in range(i, n_hi):
            v = mp.fsum(w * a * b for w, a, b in zip(ws, P[i], P[j]))
            G[i, j] = v
            G[j, i] = v
    return {n: int(mp.sign(mp.det(G[:n, :n]))) for n in nlist}


def mp_energy(xu, wu, b, dps):
    """the discrete saddle energy of config b in mp arithmetic
    (ward w2, GATE side)."""
    mp.mp.dps = dps
    idx = np.flatnonzero(b)
    xs = [mp.mpf(float(xu[i])) for i in idx]
    ws = [mp.mpf(float(abs(wu[i]))) for i in idx]
    E = -mp.fsum(mp.log(w) for w in ws)
    for a_ in range(len(xs)):
        for b_ in range(a_ + 1, len(xs)):
            E -= 2 * mp.log(abs(xs[a_] - xs[b_]))
    return float(E)


def toy_block():
    """discrete Chebyshev-U toy (w3): positive weights -> no
    parity-flip swap exists; candidates must be flip-free."""
    xt = np.sort(np.cos(np.pi * (np.arange(TOY_M) + 0.5) / TOY_M))
    wtt = (1.0 - xt * xt) * (np.pi / TOY_M)
    Dm = np.abs(xt[:, None] - xt[None, :])
    np.fill_diagonal(Dm, 1.0)
    At = -np.log(Dm)
    np.fill_diagonal(At, 0.0)
    v = np.ones(TOY_M) / math.sqrt(TOY_M)
    for _ in range(80):
        v2 = At @ v
        nv = float(np.linalg.norm(v2))
        v = v2 / nv
    Lipt = 2.0 * nv
    Vt = -np.log(wtt)
    sgt = np.sign(wtt)
    dens = None
    res_w = 0.0
    p0s, gaps, sg2 = [], [], []
    nflipswaps = 0
    for n in TOY_MASSES:
        dens, res = SZ.solve_qp(At, Lipt, Vt, float(n), rho0=dens,
                                iters=QP_ITERS, tol=QP_TOL)
        res_w = max(res_w, res)
        b0 = psel_top(dens, n)
        p0, _E0, _E1, gap, ci, _co, _b = pbranch(At, Vt, sgt, b0)
        nflipswaps += int(ci >= 0)
        p0s.append(p0)
        gaps.append(gap)
        sg2.append(pred_p2(At, Vt, sgt, dens, n))
    sg3 = pred_p3_seq(p0s, gaps, THETA)
    par_ok = all(p == 1 for p in p0s) and all(s == 1 for s in sg2) \
        and all(s == 1 for s in sg3)
    return dict(res=res_w, par_ok=par_ok, nflip=nflipswaps,
                n_masses=len(TOY_MASSES))


# --------------------------------------------------------------- main
def main():
    par = argparse.ArgumentParser()
    par.add_argument("--smoke", action="store_true")
    args = par.parse_args()
    smoke = args.smoke

    print("=" * 78)
    print("parametrix_pass_probe -- PRIME.PORT.RHP.PARAMETRIX."
          "PASS.01 (round 259)")
    print("SPEC_SHA %s   F_DEF_SHA %s (imported r243)"
          % (SPEC_SHA[:16], PB.F_DEF_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 masses 2..42 + controls + toy; "
                        "tails/w40/mp wards skipped)" if smoke
                        else "FULL RECORD"))
    print("=" * 78)

    section("S0  FIREWALL + PREDEFINITION")
    okf, det = firewall_audit()
    check("G01-firewall+predictor-scope", okf, det)
    check("G02-predefinition", True,
          "candidates sealed: P1 two-branch (parity of the lower "
          "parity-resolved branch), P2 r255 parity + LOWDIM swap "
          "correction, P3 branch sign with hysteresis THETA %.2f "
          "dec; arms: control flips +-%d, tail offsets %s at N + "
          "j, MAIN clean to N-1 on %s; anatomy windows %s; "
          "stabilizer max %d swaps, %d branch seeds; must-fail "
          "bars m2 >= %.0f dec at (w9, n = %d), m3 exact %s; ALL "
          "bars + verdict rules sealed in the frozen spec BEFORE "
          "evaluation (amendment a1 disclosed)"
          % (THETA, FLIP_TOL, str(PRIOR_OFFSETS),
             str(MAINS), str(ANAT_WIN), STAB_MAX,
             N_SEED, M2_LOUD_DEC, M2_DEG, str(M3_ANCHOR)))

    # ---------------- S1: census + controls
    section("S1  CENSUS + CONTROLS")
    packs = {kz: BH.wpack(kz) for kz in
             ((9,) if smoke else MAINS)}
    rr9 = core.build_window(9)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE = PIK.lambda_eps(N_E)
    nn_idx = np.nonzero(np.abs(lamE) > 1e-12)[0]
    ug9, uw9 = PB.smooth_comb(rr9["alpha"])
    ctrl_defs = (("EPSTEIN", dict(comb=(
        np.log(nn_idx.astype(float)),
        2.0 * lamE[nn_idx] / np.sqrt(nn_idx.astype(float))))),
        ("SCRAMBLE", dict(scramble_seed=1)),
        ("SMOOTH", dict(comb=(ug9, uw9))))
    ctrl = {c: BH.wpack(9, base_kw=kw) for c, kw in ctrl_defs}
    okC = all(packs[kz]["nf"] is None for kz in packs)
    okCf = all(ctrl[c]["nf"] == CTRL_FLIPS[c] for c in ctrl)
    check("G10-census-controls", okC and okCf,
          "MAIN free prefix positive at full depth (%s); control "
          "flips re-derived %s (ground truth, gates/anatomy only)"
          % ("; ".join("w%d N=%d" % (kz, packs[kz]["N"])
                       for kz in packs),
             str({c: ctrl[c]["nf"] for c in ctrl})))

    # ---------------- S2: toy anchor
    section("S2  CHEBYSHEV TOY ANCHOR (w3)")
    toy = toy_block()
    ok_toy = (toy["res"] <= QP_RES_BAR and toy["par_ok"]
              and toy["nflip"] == 0)
    check("G20-toy-anchor", ok_toy,
          "QP residual %.1e (bar %.0e); positive weights: %d "
          "parity-flip swaps exist over %d masses (must be 0); "
          "all candidate signs +1 on all masses: %s -- the sign "
          "layer is exactly trivial cap-free, all candidates "
          "flip-free by construction"
          % (toy["res"], QP_RES_BAR, toy["nflip"],
             toy["n_masses"], str(toy["par_ok"])))

    # ---------------- S3: sweeps
    section("S3  SWEEPS (QP + branch data at every mass)")
    res_worst = 0.0
    mass_ok = True
    nQP = 0
    SW = {}
    ANAT = {}
    SRC = {}
    for kz in packs:
        p = packs[kz]
        N = p["N"]
        masses = (list(range(2, 43)) if smoke
                  else list(range(2, N + EXT + 1)))
        adeg = (set(range(*ANAT_WIN["MAIN"])) | {ANAT_WIN["MAIN"][1]}
                if kz == 9 else set())
        sw, an, rw, mo, src = world_sweep(p["d"], masses, adeg)
        res_worst = max(res_worst, rw)
        mass_ok = mass_ok and mo
        nQP += len(masses)
        SW["w%d" % kz] = sw
        ANAT["w%d" % kz] = an
        SRC["w%d" % kz] = src
        info("w%-3d N=%d: %d masses swept" % (kz, N, len(masses)))
    for c in ctrl:
        nf = ctrl[c]["nf"]
        top = nf + (8 if smoke else CTRL_PAD)
        a0, a1 = ANAT_WIN[c]
        adeg = set(range(a0, a1 + 1))
        sw, an, rw, mo, src = world_sweep(
            ctrl[c]["d"], list(range(2, top + 1)), adeg)
        res_worst = max(res_worst, rw)
        mass_ok = mass_ok and mo
        nQP += top - 1
        SW[c] = sw
        ANAT[c] = an
        SRC[c] = src
        info("%-8s nf=%d: swept 2..%d" % (c, nf, top))
    # w40 tail sweep with early stop (arm 2 only, disclosed)
    ff_w40 = {}
    if not smoke:
        d40 = HS.window_data(40)
        N40 = d40["n_max"]
        x, wt, A, Lip, V = CB.eq_field(d40)
        sgw = np.sign(wt)
        dens = None
        p0s, gaps, sg2 = [], [], []
        ns40 = []
        for n in range(2, N40 + EXT + 1):
            dens, res = SZ.solve_qp(A, Lip, V, float(n), rho0=dens,
                                    iters=QP_ITERS, tol=QP_TOL)
            res_worst = max(res_worst, res)
            b0 = psel_top(dens, n)
            p0, _E0, _E1, gap, _ci, _co, _b = pbranch(A, V, sgw, b0)
            p0s.append(p0)
            gaps.append(gap)
            sg2.append(pred_p2(A, V, sgw, dens, n))
            ns40.append(n)
            nQP += 1
            sg3 = pred_p3_seq(p0s, gaps, THETA)
            sg1 = [pred_p1_sign(p, g) for p, g in zip(p0s, gaps)]
            ff = {c: first_flip(np.asarray(ns40),
                                np.asarray(s, int))
                  for c, s in (("P1", sg1), ("P2", sg2),
                               ("P3", sg3))}
            if all(v is not None for v in ff.values()):
                ff_w40 = ff
                break
        else:
            ff_w40 = ff
        info("w40 N=%d: early-stopped at mass %d (first flips %s)"
             % (N40, ns40[-1], str(ff_w40)))
    check("G30-sweep-qp-wards", res_worst <= QP_RES_BAR and mass_ok,
          "QP residual worst %.1e (bar %.0e) over %d equilibria; "
          "every rounded mass integer-exact; predictor data = "
          "(p0, branch gap, P2 sign, critical swap) per mass, "
          "source-only" % (res_worst, QP_RES_BAR, nQP))

    # ---------------- S4: mp wards
    section("S4  MP WARDS (gate side)")
    if smoke:
        check("G31-mp-flip-wards", True, "SMOKE: skipped")
        check("G32-mp-energy-ward", True, "SMOKE: skipped")
    else:
        xuE, wuE = union_arrays(ctrl["EPSTEIN"]["d"])
        xuS, wuS = union_arrays(ctrl["SMOOTH"]["d"])
        sE = mp_flip_ward(xuE, wuE, (25, 26), MP_FLIP_DPS)
        sS = mp_flip_ward(xuS, wuS, (27, 28), MP_FLIP_DPS)
        ok_w1 = (sE[25] > 0 and sE[26] < 0
                 and sS[27] > 0 and sS[28] < 0)
        check("G31-mp-flip-wards", ok_w1,
              "exact-precision (dps %d) determinants of the source "
              "Gram: EPSTEIN sign det G_25/G_26 = %+d/%+d, SMOOTH "
              "G_27/G_28 = %+d/%+d -- the ground truth the "
              "candidates are judged against is exact arithmetic"
              % (MP_FLIP_DPS, sE[25], sE[26], sS[27], sS[28]))
        # configs are indexed in the SORTED union order (the
        # union_setup convention): use the sweep's source arrays
        xS, wtS = SRC["SMOOTH"][0], SRC["SMOOTH"][1]
        dev_e = 0.0
        for n in (27, 28):
            an = ANAT["SMOOTH"][n]
            E_mp = mp_energy(xS, wtS, an["bst"], MP_EN_DPS)
            dev_e = max(dev_e, abs(E_mp - an["E0"]))
        check("G32-mp-energy-ward", dev_e <= MP_EN_BAR,
              "SMOOTH stable-saddle energies at degrees {27, 28} "
              "recomputed at dps %d: max |E_mp - E_f64| = %.1e "
              "nats (bar %.0e) -- the milli-decade branch gaps "
              "are not f64 noise" % (MP_EN_DPS, dev_e, MP_EN_BAR))

    # ---------------- S5: leg A anatomy
    section("S5  LEG A -- SADDLE SELECTION ANATOMY")
    dio_ctrl = []
    gap_ctrl_flip = []
    for c in ("EPSTEIN", "SMOOTH", "SCRAMBLE"):
        nf = ctrl[c]["nf"]
        note = []
        for n in sorted(ANAT[c]):
            a = ANAT[c][n]
            note.append("n=%d p0 %+d gap %+.4f swap %d->%d "
                        "(d %d, sgw %+d/%+d, rk_i %d rk_o %d)"
                        % (n, a["p0"], a["gap"], a["i"], a["o"],
                           a["dio"], a["sgi"], a["sgo"],
                           a["rk_i"], a["rk_o"]))
            dio_ctrl.append(a["dio"])
            if n in (nf, nf + 1):
                gap_ctrl_flip.append(a["gap"])
        info("%s (flip %d): %s" % (c, nf, "; ".join(note)))
    med_dio = float(np.median(dio_ctrl))
    shortrange = med_dio <= SHORTRANGE_BAR
    tok_a1 = ("SWAP_SHORT_RANGE" if shortrange
              else "SWAP_LONG_RANGE")
    check("G40-anatomy-critical-swap", True,
          "(a1) the critical parity-swap over the control anatomy "
          "windows: median |i - o| = %.1f (bar %d) => %s; weight-"
          "sign class always opposite (parity swap by "
          "construction); boundary ranks printed above"
          % (med_dio, SHORTRANGE_BAR, tok_a1))
    gap_main = [ANAT["w9"][n]["gap"] for n in sorted(ANAT["w9"])]
    note_m = "; ".join("n=%d gap %+.4f swap d=%d"
                       % (n, ANAT["w9"][n]["gap"],
                          ANAT["w9"][n]["dio"])
                       for n in sorted(ANAT["w9"]))
    sep = (min(gap_main) > max(gap_ctrl_flip)
           if gap_ctrl_flip and gap_main else False)
    tok_a2 = ("SWAP_STAT_SEPARATES" if sep
              else "SWAP_STAT_NOT_SEPARATING")
    check("G41-anatomy-main-vs-control", True,
          "(a2) MAIN w9 at %s: %s; control flip-degree gaps "
          "%s dec, MAIN anatomy gaps min %.4f dec => %s "
          "(sealed rule: separation iff MAIN min > control max "
          "%.4f)" % (str(ANAT_WIN["MAIN"]), note_m,
                     str(["%.4f" % g for g in gap_ctrl_flip]),
                     min(gap_main), tok_a2,
                     max(gap_ctrl_flip) if gap_ctrl_flip else -1))
    # (a3) crossings
    cross = {}
    for c in ("EPSTEIN", "SMOOTH", "SCRAMBLE"):
        sw = SW[c]
        sg1 = np.array([pred_p1_sign(p, g)
                        for p, g in zip(sw["p0"], sw["gap"])], int)
        cr = None
        for i, n in enumerate(sw["ns"]):
            if sg1[i] < 0:
                cr = int(n)
                break
        cross[c] = cr
    lc_ok = all(cross[c] is not None
                and abs(cross[c] - ctrl[c]["nf"]) <= FLIP_TOL
                for c in ("EPSTEIN", "SMOOTH"))
    sw9 = SW["w9"]
    sg1_9 = np.array([pred_p1_sign(p, g)
                      for p, g in zip(sw9["p0"], sw9["gap"])], int)
    lim9 = packs[9]["N"] - 1
    nsw9 = int(np.sum((np.diff(sg1_9) != 0)
                      & (sw9["ns"][1:] <= lim9)))
    tok_a3 = ("LEVEL_CROSSING_AT_FLIP" if lc_ok
              else "LEVEL_CROSSING_REFUTED")
    # gamma anatomy at flips vs at model crossings (gate side)
    gnote = []
    for c in ("EPSTEIN", "SMOOTH", "SCRAMBLE"):
        rows = ctrl[c]["rows"]
        nf = ctrl[c]["nf"]
        lgf = (rows[nf]["lg_h"] - rows[nf - 1]["lg_h"]) / L10
        cr = cross[c]
        lgc = ((rows[cr]["lg_h"] - rows[cr - 1]["lg_h"]) / L10
               if cr is not None and 1 <= cr < len(rows)
               else float("nan"))
        gnote.append("%s true lg|gamma|@flip %+.2f vs @model-"
                     "crossing(%s) %+.2f" % (c, lgf, str(cr), lgc))
    check("G42-anatomy-level-crossing", True,
          "(a3) branch crossing vs true flip: %s => %s; MAIN w9 "
          "lower-branch parity switches below N-1: %d (each a "
          "would-be flip, zero true ones); jump anatomy (gate "
          "side): %s -- the |gamma| > 1 jump belongs to the "
          "true chain at the TRUE flips, not to the branch "
          "crossings"
          % ("; ".join("%s crossing %s vs flip %d"
                       % (c, str(cross[c]), ctrl[c]["nf"])
                       for c in ("EPSTEIN", "SMOOTH", "SCRAMBLE")),
             tok_a3, nsw9, "; ".join(gnote)))

    # ---------------- S6: leg B blind adjudication
    section("S6  LEG B -- CANDIDATE ADJUDICATION (blind)")
    CN = ("P1", "P2", "P3")
    arm1 = {c: True for c in CN}
    arm1_note = {c: [] for c in CN}
    for w in ("EPSTEIN", "SCRAMBLE", "SMOOTH"):
        sw = SW[w]
        cs = cand_signs(sw)
        nf = ctrl[w]["nf"]
        for c in CN:
            ff = first_flip(sw["ns"], cs[c])
            hit = ff is not None and abs(ff - nf) <= FLIP_TOL
            arm1[c] = arm1[c] and hit
            arm1_note[c].append("%s %s (true %d, %s)"
                                % (w[:4], str(ff), nf,
                                   "HIT" if hit else "MISS"))
    check("G50-arm1-control-flips", True,
          "first-flip per candidate (tol +-%d): %s"
          % (FLIP_TOL, " | ".join("%s: %s" % (c, "; ".join(
              arm1_note[c])) for c in CN)))
    arm3 = {c: True for c in CN}
    ffm = {c: {} for c in CN}
    mfr = {c: {} for c in CN}
    for kz in packs:
        p = packs[kz]
        sw = SW["w%d" % kz]
        cs = cand_signs(sw)
        sgd = truth_sgdet(p["rows"], p["N"])
        for c in CN:
            # pairs (n, n+1) with n + 1 <= N test the free pivots
            # h_n up to n = N - 1 exactly
            ok_ns = sw["ns"] <= p["N"]
            ff = first_flip(sw["ns"][ok_ns], cs[c][ok_ns])
            ffm[c][kz] = ff
            arm3[c] = arm3[c] and (ff is None)
            mfr[c][kz] = missign_frac(sw["ns"], cs[c], sgd)
    check("G51-arm3-main-clean", True,
          "MAIN first false flip below N-1 per candidate: %s; "
          "per-degree missign fractions: %s"
          % (" | ".join("%s: %s" % (c, str(ffm[c])) for c in CN),
             " | ".join("%s: %s" % (c, str(
                 {k: "%.2f" % v for k, v in mfr[c].items()}))
                 for c in ("P1", "P2"))))
    arm2 = {c: True for c in CN}
    if smoke:
        check("G52-arm2-forced-tail", True, "SMOKE: skipped")
        for c in CN:
            arm2[c] = False
    else:
        tl_note = {c: [] for c in CN}
        for i, w in enumerate(TAIL_WINDOWS):
            d = HS.window_data(w)
            N = d["n_max"]
            rows_x = BH.bord_chain(d["xs"], d["ws"], d["ys"],
                                   d["vs"], d["xs"][:2],
                                   d["ws"][:2] * 0.0, d["ys"][:2],
                                   d["vs"][:2] * 0.0, N + EXT + 1)
            truth = next((r["n"] for r in rows_x
                          if r["sg_h"] < 0), None)
            for c in CN:
                if w == 40:
                    ff = ff_w40.get(c)
                else:
                    sw = SW["w%d" % w]
                    ff = first_flip(sw["ns"], cand_signs(sw)[c])
                off = None if ff is None else ff - N
                hit = (ff == truth and off == PRIOR_OFFSETS[i])
                arm2[c] = arm2[c] and hit
                tl_note[c].append("w%d %s(j=%s)"
                                  % (w, str(ff), str(off)))
        check("G52-arm2-forced-tail", True,
              "predicted first flips vs truth %s at N + %s: %s"
              % (str((184, 153, 170, 367, 592)),
                 str(PRIOR_OFFSETS),
                 " | ".join("%s: %s" % (c, "; ".join(tl_note[c]))
                            for c in CN)))

    # ---------------- S7: must-fails
    section("S7  MUST-FAILS")
    hits_orc = predictor_scope_audit("oracle_pred")
    check("G60-minor-oracle-flagged", bool(hits_orc),
          "the deliberately chain-reading mutant is FLAGGED by "
          "the predictor AST audit (%s) while the 10 sealed "
          "scopes stay clean (G01): the blindness claim is "
          "machine-enforced"
          % ("; ".join(hits_orc) if hits_orc else "NOT FLAGGED"))
    # m2 (amendment a1): wrong Vandermonde exponent at the sealed
    # degree -- the pair energy counted once instead of twice
    a21 = ANAT["w9"][M2_DEG]
    _x9, _wt9, A9, _V9, _sg9 = SRC["w9"]
    r21 = a21["bst"].astype(float)
    q21 = float(r21 @ (A9 @ r21))
    m2_dev = 0.5 * abs(q21) / L10
    ok_m2 = m2_dev >= M2_LOUD_DEC
    check("G61-wrong-exponent-loud", ok_m2,
          "pair energy counted once (E' = q/2 + V r) moves the "
          "stable-saddle energy at (w9, n = %d) by %.1f dec (bar "
          "%.0f) -- the sealed energy form is load-bearing; NOTE "
          "(a1): a swapped-branch mutant is flip-invariant by "
          "construction (global parity negation cancels in "
          "sg(D_{n+1}) sg(D_n)), disclosed"
          % (M2_DEG, m2_dev, M2_LOUD_DEC))
    # m3: bare r255 parity rule anchor
    ok_m3 = True
    m3_note = []
    for c in ("EPSTEIN", "SMOOTH"):
        sw = SW[c]
        # bare rule = P2 without the correction: parity of the raw
        # QP top-n (recomputed on the control range, cheap)
        x2, wt2, A2, Lip2, V2 = CB.eq_field(ctrl[c]["d"])
        sgw2 = np.sign(wt2)
        dens = None
        sgs = []
        for n in sw["ns"]:
            dens, _ = SZ.solve_qp(A2, Lip2, V2, float(n),
                                  rho0=dens, iters=QP_ITERS,
                                  tol=QP_TOL)
            sgs.append(pparity(sgw2, psel_top(dens, int(n))))
        ffb = first_flip(sw["ns"], np.asarray(sgs, int))
        ok_m3 = ok_m3 and (ffb == M3_ANCHOR[c])
        m3_note.append("%s bare first flip %s (r255 record %d)"
                       % (c, str(ffb), M3_ANCHOR[c]))
    check("G62-r255-anchor", ok_m3,
          "P2 WITHOUT the swap correction reproduces the r255 "
          "misplacements EXACTLY: %s -- the correction term is "
          "real and this round is tied to the r255 record"
          % "; ".join(m3_note))

    # ---------------- S8: verdict
    section("S8  VERDICT")
    check("G80-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED (a parametrix "
          "adjudication moves no edge); what the round adds: the "
          "saddle-selection anatomy (critical swap, MAIN-vs-"
          "control separation test, branch-crossing bill), three "
          "sealed analytic candidates with a blind protocol, and "
          "the typed obstacle of the analytic falsifier half")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        full = [c for c in CN if arm1[c] and arm2[c] and arm3[c]]
        partial = [c for c in CN
                   if arm1[c] or arm2[c] or arm3[c]]
        if full:
            top = "PARAMETRIX_PASSED(%s, +-%d)" % (full[0],
                                                   FLIP_TOL)
        elif partial:
            top = ("PARAMETRIX_PARTIAL(%s: arms %s)"
                   % (partial[0],
                      str((arm1[partial[0]], arm2[partial[0]],
                           arm3[partial[0]]))))
        else:
            top = ("PARAMETRIX_FAILED(selection wrong on 3/3 "
                   "controls + MAIN false positives; typed "
                   "i+ii+iii)")
        toks = [top, "%s(EPST %s vs 25, SMOOTH %s vs 27, SCR %s "
                "vs 21; MAIN %d switches)"
                % (tok_a3, str(cross["EPSTEIN"]),
                   str(cross["SMOOTH"]), str(cross["SCRAMBLE"]),
                   nsw9), tok_a2]
        toks.append("SELECTION_EXTENSIVE_AFTER_ALL" if not sep
                    else "SELECTION_LOWDIM_CONFIRMED")
        verd = " + ".join(toks)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G81-verdict", npass == len(CHECKS),
          "%s%s -- MEASURED: swap anatomy, branch crossings, "
          "candidate bills (flips / tail / MAIN-clean / missign "
          "fractions); OPEN: the analytic falsifier half (the "
          "obstacle is a RESUMMATION gap: the true sign is "
          "coherent cancellation across the configuration "
          "ensemble, not a dominant-configuration event); the "
          "r257 coefficient-field pass, the budget bound and the "
          "base law stand; NO RH claim"
          % (verd, " (SMOKE)" if smoke else ""))
    wall = time.time() - T0_WALL
    check("G99-runtime", wall <= 1800.0,
          "WALL %.1f s (bar 1800)" % wall)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    print("\n" + "=" * 78)
    print("RESULT: %d/%d gates PASS%s   SPEC_SHA %s"
          % (npass, len(CHECKS), " (SMOKE)" if smoke else "",
             SPEC_SHA[:16]))
    print("NO RH CLAIM in either direction.")
    print("=" * 78)
    return 0 if npass == len(CHECKS) else 1


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

# --------------------------------------------------------------- harness
_PF_RE = re.compile(r"^\s*\[(PASS|FAIL)\]\s+(\S+)", re.M)
_RES_RE = re.compile(
    r"RESULT:\s+(\d+)/(\d+)\s+gates PASS\s+SPEC_SHA\s+([0-9a-f]+)")


def _probe_file(name):
    cand = os.path.abspath(os.path.join(
        _HERE, os.pardir, "experiments", "tfpt-discovery", name + ".py"))
    return cand if os.path.isfile(cand) else None


def _exec_probe(name, src):
    """Execute one embedded frozen probe source BYTE-EXACT in its own
    module namespace (round-31 convention); capture and re-emit
    stdout; return (stdout, exit_code, byte_equal_or_None)."""
    if src[:1] == "\n":
        src = src[1:]
    path = _probe_file(name)
    same = None
    if path is not None:
        with open(path, encoding="utf-8") as fh:
            same = (fh.read() == src)
    fname = path or os.path.abspath(__file__)
    mod = types.ModuleType(name)
    mod.__file__ = fname
    sys.modules[name] = mod
    buf = io.StringIO()
    code = 0
    with contextlib.redirect_stdout(buf):
        try:
            exec(compile(src, fname, "exec"), mod.__dict__)
            entry = mod.__dict__.get("main") or mod.__dict__.get("run")
            if callable(entry):
                rc = entry()
                code = 0 if rc is None else int(rc)
        except SystemExit as exc:
            code = 0 if exc.code is None else int(exc.code)
        except Exception:                            # regression guard
            import traceback
            traceback.print_exc(file=sys.stdout)
            code = 99
    out = buf.getvalue()
    sys.stdout.write(out)
    sys.stdout.flush()
    return out, code, same


def _gate(name, out, code, same, exp_n, exp_sha, gates):
    marks = _PF_RE.findall(out)
    n = len(marks)
    fails = sorted({tok for st, tok in marks if st == "FAIL"})
    m = _RES_RE.search(out)
    res_ok = (m is not None and int(m.group(1)) == exp_n
              and int(m.group(2)) == exp_n and m.group(3) == exp_sha)
    ok = (n == exp_n and not fails and code == 0 and res_ok
          and same is not False)
    gates.append(ok)
    prov = ("byte-exact vs experiments source" if same is True else
            "embedded copy (source file not present)" if same is None
            else "SOURCE MISMATCH")
    print("\n[%s] PATTERN GATE %s: %d checks (exp %d) | FAILs %s | "
          "RESULT line %s (exp %d/%d SPEC_SHA %s) | exit %d (exp 0)"
          "\n      provenance: %s"
          % ("PASS" if ok else "FAIL", name, n, exp_n,
             ",".join(fails) if fails else "none",
             "matched" if res_ok else "MISSING/WRONG", exp_n, exp_n,
             exp_sha, code, prov), flush=True)
    return ok


_PLAN = (
    ('baseborder_factorial_probe', _SRC_0, 21, 'c7aa9f46889414c4'),
    ('coupledtau_probe', _SRC_1, 26, '73d8247f6de36a2b'),
    ('budget_anatomy_probe', _SRC_2, 27, '28026ae6b0750098'),
    ('parametrix_pass_probe', _SRC_3, 19, 'e79da4f43d63213a'),
)


def run():
    t0 = time.time()
    print("=" * 74)
    print('v959 -- PRIME.PORT.RHP.COUPLEDTAU.TERMINAL.01 (rounds 256/257/258/259,')
    print('ADJUDICATED at the finite-identity level): the coupled-tau / terminal-')
    print('budget dictionary -- positive-prefix firewall + 2x2 causal census, the')
    print('coupled two-term tau recursion with its bilinear corollary, the blind')
    print('coefficient-field predictor, the exact Schur budget telescope with the')
    print('one-inequality terminal reduction, and the three parametrix no-gos')
    print("(frozen probes embedded byte-exact and executed verbatim; NO RH claim)")
    print("=" * 74, flush=True)
    gates = []
    _coupledtau_terminal_theorems(gates)
    for name, src, exp_n, exp_sha in _PLAN:
        print("\n" + "-" * 74)
        print("EMBEDDED FROZEN PROBE: %s" % name)
        print("-" * 74, flush=True)
        out, code, same = _exec_probe(name, src)
        _gate(name, out, code, same, exp_n, exp_sha, gates)
    ok = all(gates)
    print("\n" + "=" * 74)
    print("v959: %d/%d gates passed (5 module-own exact checks + 4 "
          "pattern gates) | runtime %.1f s"
          % (sum(gates), len(gates), time.time() - t0))
    print('the wall problem has its most compact form to date: the pair (tau,')
    print('tau^aug) closes under an exact two-term recursion whose bilinear form')
    print('is a manifest square -- the base alone carries the sign, the border')
    print('only nonnegative magnitude, and the entire fiber positivity is the ONE')
    print('terminal inequality q_N = rho_{N-1}/(5/7) < 1 (5/7 typed FLOOR_IMPORTED,')
    print('derivation open); the frozen micro-falsifier is passed blind at the')
    print('coefficient-field level while the parametrix half stays honestly open')
    print('(resummation gap, not selection gap; level crossing and one-swap')
    print('statistics refuted; the mass-majorant class dead).')
    print('PRIME.PORT.RHP.COUPLEDTAU.TERMINAL.01 [E]; the campaign continues as')
    print('PRIME.PORT.RHP.FULLSOURCE.BASEFIBER.01 [O] with the two named terminal')
    print('edges registered as PRIME.PORT.COUPLEDTAU.TERMINAL_CROSSRATIO.01 [O]')
    print('and PRIME.PORT.FULLSOURCE.PREFIX_RESUMMATION.01 [O].')
    print('Mincut base 4 / refined 5 unchanged; NO RH claim.')
    print("[%s] v959 VERDICT GATE" % ("PASS" if ok else "FAIL"))
    return 0 if ok else 1


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