#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""v953 -- PRIME.FEWATOM.REDUCTION.01: A_{v_0} >= 0 (OBJECT-A) +
THE ONE-LINE SIGN-LAW MECHANISM + THE HORIZON LADDERS of round 197,
WITH THE BUGHUNT-X KA SCOPE RIDER VERBATIM AND THE STURM CONTINUUM
CERTIFICATE RECOMPUTED IN-MODULE at h = 4, 5 (the Bughunt-X
mathematical deliverable folded into this promotion -- the bughunt
round itself stays experiments-side per process-round precedent).

THE HEADLINE (KA-scoped): the collapsing direction's mode
polynomial A_{v_0}(t) = sum_k v_k cos(om_k t) is NONNEGATIVE ON
[0, L] AT ALL 14 RUNGS -- a nodeless positive bump peaked exactly
at L/2, zero sign changes, negative-mass fraction exactly 0, with
a POSITIVE minimum at the window edge whose ladder (log10
A_min/A_max = -5.02 -> -43.30) IS the jr_0 ladder.  THE KA SCOPE
RIDER (Bughunt X F1 MAJOR, adopted VERBATIM on every surface
carrying this headline): "an allen 14 Sprossen GITTER-zertifiziert
(N = 16K) mit Nullklassen-Bar 1e-30 (an h = 15/16/20 liegt das
Minimum UNTERHALB der Bar-Aufloesung des Gates -- der positive
Wert dort ist Print-Evidenz, nicht Gate-Zertifikat);
Kontinuums-Nichtnegativitaet auf [0, L] und der positive
Minimumswert sind durch Bughunt X per exakter Sturm-Kette bei
h = 4, 5, 13, 20 ZERTIFIZIERT (eigene Rechnung, eskalierte dps)."
The r197 gate class is retyped GRID-MEASURED; THE HEADLINE IS TRUE
AND NOW STRONGER: Bughunt X certified CONTINUUM nonnegativity by
exact-rational Sturm chains at h = 4, 5 (exact Fractions: zero
roots in (-1, 1], P(+-1) > 0) and h = 13, 20 (coefficients rounded
at 2^-200/2^-340 with strict subtracted floors BEFORE root
counting: A > 0 on ALL of [0, L]), and re-verified jr_0 at h = 20
with dps 170 (~127 digits of sign headroom).  THIS MODULE
RECOMPUTES THE h = 4, 5 CERTIFICATES: own wall build (own sieve,
own arch quadratures, BH9/BH10 lineage), mp inverse iteration for
v_0, exact dyadic Fractions, the Chebyshev conversion A(t) =
P(cos(2 pi t/L)) and the INTEGER primitive-PRS Sturm chain --
ZERO roots of P in (-1, 1] and P(+-1) > 0, hence A_{v_0} > 0 on
ALL of [0, L], continuum-certified, no floats in the chain.

THE ONE-LINE MECHANISM (the sign law reduced): if A_{v_0} >= 0 on
[0, L] then EVERY autocorrelation g(u) = int_0^{L-u} A A(. + u) dt
>= 0 by inspection, so every atom contributes t_q = -2 w_q
g(log q) <= 0 -- the v951 sign law (n+ = 0 at all 14 rungs) has a
one-line mechanism; recomputed in-run at h = 4, 5: g(u_q) > 0 at
every non-commensurate atom lag, the q = h atom EXACTLY ZERO, the
budget resplit lambda_0 = P + A + t_2 + t_3 + Tail exact, and the
horizon Q99 = (1, q = 2) at both rungs.  THE KC PRECISION RIDER
(adopted): the "edge minimum IS the jr_0 ladder" identification is
exact UN-NORMALIZED (the grid min = A(0) = the jr_0 NUMERATOR
exactly -- verified in-run at h = 4, 5); the printed RATIO differs
by the r198 parity-misalignment factor (1 - amax/sum|v| =
0.4-0.65%, invisible at print precision); the r197/r198 pair is
CONSISTENT.

THE HORIZON LADDERS (pinned; the scale-relativity rider MANDATORY):
Q99 = (1, q = 2) at h = 4-13 and (2, q = 3) at h = 14-20 incl. the
holdout -- HORIZON-BOUNDED-{2, 3} at the budget scale; THE HONEST
COUNTERWEIGHT: at the demand scale (tail <= lambda_0) the horizon
consumes EVERY resolvable atom at every rung (qtau_frac 1.00,
dexgap 7.5 -> 82.0) -- QUANTIFIER COMPRESSION IS SCALE-RELATIVE;
the reduction is FEWATOM-REDUCTION-STRUCTURAL-VALID with the
mandatory rider NOT-A-COMPLEXITY-DROP-IN-H (every ingredient is a
functional of v_0(h); only the atom quantifier compresses); ANY
LOSSY TAIL BOUND IS CERTIFICATION-DEAD (the measured geometric
majorant overshoots lambda_0 by 4.6-77.5 dex).  DECAY (pinned):
the edge-power model wins decisively (R^2 0.966-0.994 vs
0.815-0.854), the exponent p_g grows 7.14 -> 39.17 -- NOT
UNIVERSAL, and NOT tau-tracking either (P3 refuted honest: r_tau
falls 0.778 -> 0.356); the mechanism candidate that DOES track is
THE JET-CONVOLUTION LAW p_g ~ 4 MJET + 1 (typed band-approximate
measured-law, honestly flagged as the r182/v941 alignment
structure in ACF coordinates); the weight candidate c = 1/2 dead
by 28x.  WORLDS: few-atom localization is an ATOM-WORLD
phenomenon with the shape mechanism EPSTEIN-SEPARATING (EPSTEIN
breaks the shape: profile node, rmin -0.481, 10/24 negative lags;
SCRARITH keeps the shape, loses localization; SMOOTH has no
localization at all, w99/L = 0.92); the r172 witness preserves
the signs but FLATTENS the ACF ladder by up to 3.6 dex at 0.19%
direction cost -- a witness detector at magnitude level.

OBJECT-A (the Bughunt-X X6 targeting result, adopted): the round's
new concrete target "prove A_{v_0(h)} >= 0 for all h" is THE ONE
GENUINELY NEW TRACTABLE OBJECT of the arc (three names = two
objects + one class name: r195's cofinal domination IS wall
positivity = OBJECT-W; r198's pole-vs-hopping balance is the CLASS
NAME of the same OBJECT-W); OBJECT-A is v_0(h)-quantified, yields
PROVEN only the sign law, and holds NO lever on wall positivity --
per-rung Sturm-certified through h = 20 (Bughunt X) and
re-certified at h = 4, 5 in this module; the candidate proof route
(Perron-Frobenius/Krein-Rutman) was NAMED, NOT CONSUMED, and is
adjudicated in v954.

RE-RUN GREEN AS TYPED AT PROMOTION: fewatom_reduction_probe.py
round 197 (note DXX (520), contract PRIME.FEWATOM.REDUCTION.01),
25/25 gates, SPEC_SHA 35fb341bb281b04b (verified byte-identical
before and after the appended KA/KC CORRECTION-OF-RECORD block,
note DXXIV), record 790 s + 811 s deterministic re-run
(timing-normalized diff empty, three smokes + one calibration
pass, all logs kept, two pre-freeze amendments disclosed: A1
edge-window fit; A2 direct jet-convolution gate), re-run at
promotion 830.7 s, 25/25 -- log kept as
fewatom_reduction_probe.promo_rerun.log.

HONEST TYPING: PROVEN = the h = 4, 5 continuum Sturm certificates,
the one-line mechanism implication, the budget resplit, the
un-normalized KC identification (recomputed in-run); MEASURED =
the nonneg/horizon/decay/world/witness ladders (pinned,
GRID-MEASURED per KA).  THE RESIDUE (canonical, notes
DII/DXVI/DXXIV): {H1 AND H2 AND H3}-cofinal (mod D = 0.0042) +
{census-forall-k == LOOP} + {H-PIN = the one lambda-uniform edge
of {L1, WPD}; WPD non-lambda legs: extension instantiated, TAILWPD
world-front}.  Census cardinality 4 UNCHANGED.  NOT evidence for
or against the Riemann Hypothesis in either direction.  NO RH
CLAIM.

PROVENANCE: discovery probe fewatom_reduction_probe.py (round 197,
2026-08-21, note DXX; KA/KC CORRECTION-OF-RECORD block per note
DXXIV (524)); consumes v951 (the ACF law and sign law this round
mechanizes); externally covered by Bughunt X (round 199, note
DXXIII, bughunt10_probe.py SPEC 5551aa7b967230f1: F1 MAJOR
adjudicated THE HEADLINE IS TRUE with the STRONGER certification
class -- the exact-rational Sturm chains at h = 4, 5, 13, 20 this
module recomputes at h = 4, 5; F3/KC the un-normalized
identification).  Python-only per GATE.WOLFRAM.02.
"""
from __future__ import annotations

import math
import time
from fractions import Fraction

import mpmath as mp

T_ALL = time.time()

# ---------------------------------------------------------------- pinned
PIN_SPEC_R197 = "35fb341bb281b04b"
PIN_SPEC_BH10 = "5551aa7b967230f1"
PIN_RMIN = {4: -5.02, 5: -7.54, 13: -26.29, 15: -31.07,
            16: -33.63, 20: -43.30}    # log10(A_min/A_max), POSITIVE min
PIN_TPEAK = 0.500                      # at every rung
PIN_NSC = 0
PIN_ETA = 0.0
PIN_HORIZ = {"lo": (1, 2), "hi": (2, 3)}   # (n99, q99)
PIN_QTAUF = 1.00
PIN_DEXGAP = (7.5, 82.0)
PIN_R2_POW = (0.966, 0.994)
PIN_R2_EXP = (0.815, 0.854)
PIN_PG = (7.141, 39.169)
PIN_RTAU = (0.7776, 0.3555)            # falls: P3 refuted
PIN_CHALF_X = 28
PIN_JETCONV_DEV = (0.006, 0.43)
PIN_EPSTEIN = {"rmin": -0.481, "eta": 0.185, "gneg": 10}
PIN_SMOOTH_W99 = 0.920
PIN_WIT = {"flatten_dex": 3.6, "cost_pct": 0.19, "ovl": 0.998106}
PIN_KC_PARITY = (0.004, 0.0065)        # 1 - amax/sum|v| at h = 4/5
PIN_TAIL_OVERSHOOT = (4.6, 77.5)       # dex vs lambda_0

RMIN_TOL = 0.11
N_CHECKS = 10
EXPECTED = "A-V0-NONNEGATIVE-STURM-CERTIFIED"

CHECKS: list[tuple[str, bool]] = []
FAILS: list[str] = []


def check(name, ok, detail=""):
    ok = bool(ok)
    CHECKS.append((name, ok))
    if not ok:
        FAILS.append(name.split()[0])
    print("  [%s] %-52s %s" % ("PASS" if ok else "FAIL", name, detail))
    return ok


def section(title):
    print("\n" + "=" * 74)
    print(title)
    print("=" * 74)


# ------------------------------------------------------ own wall builder
def r_of(w):
    if w == 0:
        return mp.mpf("0.25")
    return mp.exp(-w / 2) / (-mp.expm1(-2 * w)) - 1 / (2 * w)


def own_cell(h, dps):
    """Fully own build of the documented even-sector MAIN wall
    (r171-r198 conventions; the BH9/BH10 own-code lineage, warded
    there against the record tables of three rounds): M = Mpole +
    March - Mprime, om_k = k pi/a, K = ceil(1.25 h log h), norms
    sqrt(2a)/sqrt(a), prime-power atoms (log q, log p/sqrt q)."""
    with mp.workdps(dps):
        aa = mp.log(h) / 2
        K = int(math.ceil(1.25 * h * math.log(h)))
        L = 2 * aa
        oms = [k * mp.pi / aa for k in range(K)]
        par = [mp.mpf((-1.0) ** k) for k in range(K)]
        jvec = [mp.mpf(0)]
        for i in range(1, K):
            o = oms[i]
            npts = int(mp.floor(L * o / mp.pi))
            pts = ([mp.mpf(0)]
                   + [j * mp.pi / o for j in range(1, npts + 1)]
                   + [L])
            jvec.append(mp.quad(lambda w, o=o: mp.sin(o * w)
                                * r_of(w), pts) + mp.si(L * o) / 2)
        icap = int(h)
        comp = [False] * (icap + 1)
        nlist = []
        for p in range(2, icap + 1):
            if comp[p]:
                continue
            for m in range(p * p, icap + 1, p):
                comp[m] = True
            q = p
            while q <= icap:
                nlist.append((q, p))
                q *= p
        nlist.sort()
        atoms = [(mp.log(q), mp.log(p) / mp.sqrt(q)) for q, p in nlist]
        qs = [q for q, _p in nlist]
        pj = [sum((w * mp.sin(o * u) for u, w in atoms), mp.mpf(0))
              for o in oms]
        Mpole = mp.zeros(K, K)
        March = mp.zeros(K, K)
        Mprime = mp.zeros(K, K)
        ipv = [par[i] * mp.sinh(aa / 2) / (mp.mpf(1) / 4 + oms[i] ** 2)
               for i in range(K)]
        for i in range(K):
            for j in range(K):
                Mpole[i, j] = 2 * ipv[i] * ipv[j]
        for i in range(K):
            for j in range(i):
                sg = par[i] * par[j]
                den = oms[j] ** 2 - oms[i] ** 2
                March[i, j] = March[j, i] = (
                    -2 * sg * (oms[i] * jvec[i]
                               - oms[j] * jvec[j]) / den)
                pod = 2 * sg * (oms[i] * pj[i] - oms[j] * pj[j]) / den
                Mprime[i, j] += pod
                Mprime[j, i] += pod
        for i in range(K):
            o = oms[i]
            if i == 0:
                f0 = L
                psi_d = lambda w: L - w                # noqa: E731
            else:
                f0 = aa
                psi_d = (lambda w, o=o: (aa - w / 2) * mp.cos(o * w)
                         - mp.sin(o * w) / (2 * o))
            integrand = (lambda w, f0=f0, psi_d=psi_d:
                         (f0 * mp.exp(-2 * w)
                          - psi_d(w) * mp.exp(-w / 2))
                         / (-mp.expm1(-2 * w)))
            npts = max(int(mp.floor(L * o / mp.pi)), 1) if i else 1
            base = [mp.mpf(0), mp.mpf("1e-6"), mp.mpf("1e-3"),
                    mp.mpf("0.05"), L]
            if i:
                base += [j * mp.pi / o for j in range(1, npts + 1)]
            pts = sorted(set(p for p in base if p <= L))
            body = mp.quad(integrand, pts)
            tail = -f0 / 2 * mp.log1p(-mp.exp(-2 * L))
            March[i, i] += -f0 * (mp.euler + mp.log(mp.pi)) \
                + 2 * (body + tail)
            pdiag = sum((w * ((aa - u / 2) * mp.cos(o * u)
                              - mp.sin(o * u) / (2 * o))
                         if i else w * (L - u)
                         for u, w in atoms), mp.mpf(0))
            Mprime[i, i] += 2 * pdiag
        # Raw = D_par N M N D_par entry-wise (norms cancel out)
        RawP = mp.zeros(K, K)
        RawA = mp.zeros(K, K)
        RawPr = mp.zeros(K, K)
        for i in range(K):
            for j in range(K):
                sg = par[i] * par[j]
                RawP[i, j] = Mpole[i, j] * sg
                RawA[i, j] = March[i, j] * sg
                RawPr[i, j] = Mprime[i, j] * sg
        RawW = RawP + RawA - RawPr
        for i in range(K):
            for j in range(i):
                for Mb in (RawW, RawP, RawA, RawPr):
                    sym = (Mb[i, j] + Mb[j, i]) / 2
                    Mb[i, j] = Mb[j, i] = sym
        return dict(K=K, aa=aa, L=L, oms=oms,
                    b=[o * o for o in oms], atoms=atoms, qs=qs,
                    RawW=RawW, RawP=RawP, RawA=RawA, RawPr=RawPr)


def bottom_vec(Raw, K):
    """mp inverse iteration (3 LU solves) + residual ward."""
    x = mp.matrix([mp.mpf(1)] * K)
    for _ in range(3):
        x = mp.lu_solve(Raw, x)
        x = x / mp.sqrt(sum(x[i] ** 2 for i in range(K)))
    v = [x[i] for i in range(K)]
    Rv = [sum(Raw[i, j] * v[j] for j in range(K)) for i in range(K)]
    lam = sum(v[i] * Rv[i] for i in range(K))
    res = max(abs(Rv[i] - lam * v[i]) for i in range(K))
    return v, lam, res


def W_atom(u, oms, b, L, K):
    W = mp.zeros(K, K)
    for i in range(K):
        for j in range(i):
            W[i, j] = 2 * (oms[i] * mp.sin(oms[i] * u)
                           - oms[j] * mp.sin(oms[j] * u)) / (b[i] - b[j])
            W[j, i] = W[i, j]
    W[0, 0] = 2 * (u - L)
    for k in range(1, K):
        W[k, k] = mp.sin(oms[k] * u) / oms[k] \
            + (u - L) * mp.cos(oms[k] * u)
    return W


# ------------------------------------------------- exact Sturm machinery
def frac_of_mpf(x) -> Fraction:
    sign, man, exp, _bc = mp.mpf(x)._mpf_
    v = Fraction(man, 1) * (Fraction(2) ** exp)
    return -v if sign else v


def cheb_poly(vF):
    """P(x) = sum v_k T_k(x), exact Fraction coefficients (asc)."""
    K = len(vF)
    Tprev = [Fraction(1)]
    Tcur = [Fraction(0), Fraction(1)]
    P = [Fraction(0)] * K
    P[0] += vF[0]
    if K > 1:
        P[1] += vF[1]
    for k in range(2, K):
        Tnext = [Fraction(0)] * (k + 1)
        for i, c in enumerate(Tcur):
            Tnext[i + 1] += 2 * c
        for i, c in enumerate(Tprev):
            Tnext[i] -= c
        for i, c in enumerate(Tnext):
            P[i] += vF[k] * c
        Tprev, Tcur = Tcur, Tnext
    while len(P) > 1 and P[-1] == 0:
        P.pop()
    return P


def polyval_frac(P, x):
    acc = Fraction(0)
    for c in reversed(P):
        acc = acc * x + c
    return acc


def _int_poly(P):
    emax = 0
    for c in P:
        d = c.denominator
        e = d.bit_length() - 1
        assert d == (1 << e), "non-dyadic coefficient"
        emax = max(emax, e)
    return [int(c * (1 << emax)) for c in P]


def _content(P):
    g = 0
    for c in P:
        g = math.gcd(g, abs(c))
    return g if g else 1


def _prem_even(A, B):
    """Pseudo-remainder with EVEN powers of lc(B) (sign-faithful)."""
    A = A[:]
    dB = len(B) - 1
    lb = B[-1]
    lb2 = lb * lb
    while len(A) - 1 >= dB and any(A):
        if A[-1] == 0:
            A.pop()
            continue
        off = len(A) - 1 - dB
        coef = A[-1] * lb
        A = [c * lb2 for c in A]
        for i in range(len(B)):
            A[off + i] -= coef * B[i]
        while len(A) > 1 and A[-1] == 0:
            A.pop()
        if len(A) - 1 < dB:
            break
    while len(A) > 1 and A[-1] == 0:
        A.pop()
    return A


def _ipolyval(P, num, den):
    n = len(P) - 1
    acc = 0
    for i, c in enumerate(P):
        acc += c * (num ** i) * (den ** (n - i))
    return acc


def sturm_roots(Pfrac, a, b):
    """#distinct real roots in (a, b] via the INTEGER primitive-PRS
    Sturm chain (exact; the BH10 route -- the naive Fraction chain
    explodes at high degree)."""
    P = _int_poly(Pfrac)
    g = _content(P)
    P = [c // g for c in P]
    dP = [P[i] * i for i in range(1, len(P))]
    g = _content(dP)
    dP = [c // g for c in dP]
    chain = [P, dP]
    while len(chain[-1]) > 1:
        R = _prem_even(chain[-2], chain[-1])
        if not any(R):
            break
        g = _content(R)
        R = [-c // g for c in R]
        chain.append(R)

    def sigma(x: Fraction):
        signs = []
        for Q in chain:
            v = _ipolyval(Q, x.numerator, x.denominator)
            if v != 0:
                signs.append(1 if v > 0 else -1)
        return sum(1 for i in range(len(signs) - 1)
                   if signs[i] != signs[i + 1])

    return sigma(a) - sigma(b)


def part():
    # ================================================ A: the certificates
    section("A. THE WALL AT h = 4, 5 + THE STURM CONTINUUM "
            "CERTIFICATES (own build)")
    dat = {}
    okA = True
    for h in (4, 5):
        dps = 60
        ce = own_cell(h, dps)
        with mp.workdps(dps):
            K, L, oms = ce["K"], ce["L"], ce["oms"]
            v0, lam0, res = bottom_vec(ce["RawW"], K)
            froW = mp.sqrt(sum(ce["RawW"][i, j] ** 2
                               for i in range(K) for j in range(K)))
            Amid = sum(v0[k] * mp.cos(oms[k] * L / 2)
                       for k in range(K))
            if Amid < 0:
                v0 = [-t for t in v0]
            N = 16 * K
            Av = [sum(v0[k] * mp.cos(2 * mp.pi * ((k * j) % N) / N)
                      for k in range(K)) for j in range(N // 2 + 1)]
            amax, amin = max(Av), min(Av)
            rmin = float(mp.log(amin / amax, 10)) if amin > 0 \
                else float("nan")
            jpeak = max(range(len(Av)), key=lambda j: Av[j])
            A0 = sum(v0)
            sab = sum(abs(t) for t in v0)
            dat[h] = dict(ce=ce, v0=v0, lam0=lam0, N=N, Av=Av,
                          amax=amax, amin=amin, A0=A0, sab=sab)
            okA = okA and lam0 > 0 and res / froW < 1e-12 \
                and amin > 0 and Av[0] == amin \
                and abs(rmin - PIN_RMIN[h]) < RMIN_TOL \
                and abs(jpeak / float(N) - 0.5) < 1e-9 \
                and A0 > 0
    check("A1 the wall rebuilt OWN at h = 4, 5 (v_0, profile, "
          "record match)", okA,
          "own sieve + own arch quadratures + mp inverse iteration "
          "(residual ward < 1e-12 rel): lambda_0 > 0 at both "
          "rungs; the profile A_{v_0} on the N = 16K grid is a "
          "nodeless positive bump with the minimum AT THE EDGE "
          "(j = 0), peak EXACTLY at L/2, and log10(A_min/A_max) "
          "matching the record ladder (%.2f / %.2f, tol %.2f); "
          "A_0 = sum v_k > 0 (the jr_0 numerator sign)"
          % (PIN_RMIN[4], PIN_RMIN[5], RMIN_TOL))

    okB = True
    sturm_info = []
    for h in (4, 5):
        v0 = dat[h]["v0"]
        vF = [frac_of_mpf(t) for t in v0]
        P = cheb_poly(vF)
        nr = sturm_roots(P, Fraction(-1), Fraction(1))
        p1 = polyval_frac(P, Fraction(1))
        pm1 = polyval_frac(P, Fraction(-1))
        sturm_info.append((h, len(P) - 1, nr))
        okB = okB and nr == 0 and p1 > 0 and pm1 > 0
    check("A2 THE STURM CONTINUUM CERTIFICATE at h = 4, 5 (exact, "
          "no floats)", okB,
          "A(t) = P(cos(2 pi t/L)) with P = sum v_k T_k EXACT "
          "dyadic Fractions of the computed direction; the INTEGER "
          "primitive-PRS Sturm chain counts ZERO roots of P in "
          "(-1, 1] and P(+-1) > 0 (degrees/roots: %s): A_{v_0} > 0 "
          "on ALL of [0, L] -- CONTINUUM nonnegativity, not grid "
          "measurement; the Bughunt-X certification class (KA) "
          "recomputed in-module at the exact rungs; BH10 extends "
          "it to h = 13, 20 with rounded coefficients + strict "
          "subtracted floors (SPEC %s)"
          % (str(sturm_info), PIN_SPEC_BH10))

    okC = True
    # the implication A >= 0 ==> g(u) = int_0^{L-u} A A(.+u) >= 0 is
    # monotonicity of the integral of a nonnegative product -- the
    # machine content here is the exhibit at the actual rungs:
    for h in (4, 5):
        ce, v0 = dat[h]["ce"], dat[h]["v0"]
        K, L, oms, b = ce["K"], ce["L"], ce["oms"], ce["b"]
        with mp.workdps(60):
            tqs = []
            for (u, w), q in zip(ce["atoms"], ce["qs"]):
                W = W_atom(u, oms, b, L, K)
                g = -sum(v0[i] * W[i, j] * v0[j] for i in range(K)
                         for j in range(K)) / 2
                tqs.append((q, w * (-2) * g, g))
            zb = mp.mpf("1e-30") * max(abs(t[1]) for t in tqs)
            npos = sum(1 for _q, tq, _g in tqs if tq > zb)
            okC = okC and npos == 0
            for q, tq, g in tqs:
                if q == h:
                    okC = okC and abs(tq) <= zb
                else:
                    okC = okC and g > 0
    check("A3 THE ONE-LINE MECHANISM exhibited (g > 0 at every "
          "atom; n+ = 0)", okC,
          "A_{v_0} >= 0 on [0, L] ==> every autocorrelation "
          "g(u) = int_0^{L-u} A A(. + u) dt >= 0 by inspection "
          "==> every atom contributes t_q = -2 w_q g(log q) <= 0: "
          "exhibited at h = 4, 5 -- g(u_q) > 0 at every "
          "non-commensurate atom lag, the q = h atom EXACTLY ZERO "
          "(zero class 1e-30), n+ = 0 (the v951 sign law's "
          "mechanism, one line given the Sturm certificate)")

    okD = True
    for h in (4, 5):
        ce, v0 = dat[h]["ce"], dat[h]["v0"]
        lam0 = dat[h]["lam0"]
        K = ce["K"]
        with mp.workdps(60):
            P_ = sum(v0[i] * ce["RawP"][i, j] * v0[j]
                     for i in range(K) for j in range(K))
            A_b = sum(v0[i] * ce["RawA"][i, j] * v0[j]
                      for i in range(K) for j in range(K))
            Pr = -sum(v0[i] * ce["RawPr"][i, j] * v0[j]
                      for i in range(K) for j in range(K))
            okD = okD and abs(lam0 - (P_ + A_b + Pr)) \
                < mp.mpf("1e-25") * (abs(P_) + abs(A_b))
            # horizon: smallest ascending-q prefix within 1% of Pr
            tqs = []
            for (u, w), q in zip(ce["atoms"], ce["qs"]):
                W = W_atom(u, ce["oms"], ce["b"], ce["L"], K)
                g = -sum(v0[i] * W[i, j] * v0[j] for i in range(K)
                         for j in range(K)) / 2
                tqs.append((q, -2 * w * g))
            guard = mp.mpf("1e-6") * (abs(P_) + abs(A_b))
            acc = mp.mpf(0)
            n99, q99 = None, None
            for i, (q, tq) in enumerate(tqs):
                acc += tq
                if abs(acc - Pr) <= mp.mpf("0.01") * abs(Pr) + guard:
                    n99, q99 = i + 1, q
                    break
            okD = okD and (n99, q99) == PIN_HORIZ["lo"]
    check("A4 the budget resplit exact + the horizon Q99 = "
          "(1, q = 2) at h = 4, 5", okD,
          "lambda_0 == P + A + sum_q t_q to < 1e-25 rel (mp "
          "consistency; the v951 budget resplit is definitional "
          "and verified); the 1%%-horizon is (n99, q99) = (1, 2) "
          "at both rungs -- ONE atom (q = 2) carries the prime "
          "total at the budget scale, matching the record "
          "(%s at h = 4-13, %s at h = 14-20 incl. holdout)"
          % (str(PIN_HORIZ["lo"]), str(PIN_HORIZ["hi"])))

    # ================================================ B: KA/KC + pinned
    section("B. THE KA/KC CORRECTIONS + THE PINNED LADDERS")
    okE = True
    for h in (4, 5):
        amax, sab = dat[h]["amax"], dat[h]["sab"]
        amin, A0 = dat[h]["amin"], dat[h]["A0"]
        with mp.workdps(60):
            okE = okE and abs(amin - A0) < mp.mpf("1e-45") * abs(A0)
            parity = float(1 - amax / sab)
            okE = okE and PIN_KC_PARITY[0] * 0.5 < parity \
                < PIN_KC_PARITY[1] * 2
    check("B1 KC RECOMPUTED: the edge minimum IS A_0 = the jr_0 "
          "numerator (un-normalized)", okE,
          "grid min == A(0) == sum_k v_k EXACTLY at h = 4, 5 "
          "(< 1e-45 rel): the r197 identification is exact "
          "UN-NORMALIZED; the printed RATIO differs by the r198 "
          "parity-misalignment factor 1 - amax/sum|v| (measured "
          "here inside the record band %.1f-%.2f%%): the "
          "r197/r198 pair is CONSISTENT -- the two statements are "
          "logically independent and both measured TRUE (KC "
          "adopted)" % (PIN_KC_PARITY[0] * 100,
                        PIN_KC_PARITY[1] * 100))

    okF = PIN_RMIN[15] < -30 and PIN_RMIN[16] < -30 \
        and PIN_RMIN[20] < -40 and PIN_TPEAK == 0.5 \
        and PIN_NSC == 0 and PIN_ETA == 0.0
    check("B2 KA ADOPTED: the gate class is GRID-MEASURED; the "
          "headline TRUE AND STRONGER", okF,
          "the record nonneg ladder (log10 A_min/A_max = -5.02 -> "
          "-43.30, t_peak = L/2, zero sign changes, eta = 0 at all "
          "14 rungs) is GITTER-zertifiziert (N = 16K) with "
          "zero-class bar 1e-30 -- at h = 15/16/20 the minimum "
          "(%.2f/%.2f/%.2f) sits BELOW the bar's resolution: the "
          "positive value there is PRINT EVIDENCE, not gate "
          "certificate (KA retype); CONTINUUM nonnegativity and "
          "the positive minimum are CERTIFIED by Bughunt X's exact "
          "Sturm chains at h = 4, 5, 13, 20 (own code, escalated "
          "dps; jr_0 re-verified at h = 20 with dps 170, ~127 "
          "digits of headroom) -- and recomputed at h = 4, 5 in "
          "THIS module (A2); future profile sign gates use a "
          "sign-resolving bar" % (PIN_RMIN[15], PIN_RMIN[16],
                                  PIN_RMIN[20]))

    okG = PIN_QTAUF == 1.00 and PIN_DEXGAP[0] < PIN_DEXGAP[1] \
        and PIN_TAIL_OVERSHOOT[1] > PIN_TAIL_OVERSHOOT[0] > 0
    check("B3 HORIZON-BOUNDED-{2, 3} + THE SCALE-RELATIVITY RIDER "
          "(mandatory)", okG,
          "Q99 = (1, q = 2) at h = 4-13 and (2, q = 3) at h = "
          "14-20 INCL. THE HOLDOUT (budget scale); THE HONEST "
          "COUNTERWEIGHT: at the demand scale (tail <= lambda_0) "
          "the horizon consumes EVERY resolvable atom at every "
          "rung (qtau_frac %.2f, dexgap %.1f -> %.1f) -- "
          "QUANTIFIER COMPRESSION IS SCALE-RELATIVE; "
          "FEWATOM-REDUCTION-STRUCTURAL-VALID carries the "
          "MANDATORY rider NOT-A-COMPLEXITY-DROP-IN-H (every "
          "ingredient is a functional of v_0(h)); ANY LOSSY TAIL "
          "BOUND IS CERTIFICATION-DEAD (majorant overshoot "
          "%.1f-%.1f dex vs lambda_0)"
          % (PIN_QTAUF, PIN_DEXGAP[0], PIN_DEXGAP[1],
             PIN_TAIL_OVERSHOOT[0], PIN_TAIL_OVERSHOOT[1]))

    okH = PIN_R2_POW[0] > PIN_R2_EXP[1] \
        and PIN_RTAU[0] > PIN_RTAU[1] and PIN_CHALF_X >= 10 \
        and PIN_JETCONV_DEV[0] < PIN_JETCONV_DEV[1]
    check("B4 the decay adjudication (edge-power; NOT universal; "
          "P3 refuted)", okH,
          "the edge-power model wins decisively (R^2 %.3f-%.3f vs "
          "exponential %.3f-%.3f); the exponent p_g grows %.2f -> "
          "%.2f -- NOT UNIVERSAL, and NOT tau-tracking either (P3 "
          "REFUTED honest: r_tau falls %.4f -> %.4f); the "
          "candidate that DOES track is THE JET-CONVOLUTION LAW "
          "p_g ~ 4 MJET + 1 (dev %.3f-%.2f, typed BAND-APPROXIMATE "
          "measured-law -- the r182/v941 alignment structure in "
          "ACF coordinates, NOT new arithmetic); the weight "
          "candidate c = 1/2 dead by %dx"
          % (PIN_R2_POW[0], PIN_R2_POW[1], PIN_R2_EXP[0],
             PIN_R2_EXP[1], PIN_PG[0], PIN_PG[1], PIN_RTAU[0],
             PIN_RTAU[1], PIN_JETCONV_DEV[0], PIN_JETCONV_DEV[1],
             PIN_CHALF_X))

    okI = PIN_EPSTEIN["rmin"] < 0 and PIN_EPSTEIN["gneg"] > 0 \
        and PIN_SMOOTH_W99 > 0.9 and PIN_WIT["ovl"] > 0.99
    check("B5 worlds + witness (shape EPSTEIN-separating; ladder "
          "flattened)", okI,
          "few-atom localization is an ATOM-WORLD phenomenon with "
          "the shape mechanism EPSTEIN-SEPARATING: EPSTEIN breaks "
          "the shape (profile node, rmin %.3f, eta %.3f, %d/24 "
          "negative lags) while keeping one-signed atom ladders "
          "(P4 partially refuted, honest); SCRARITH keeps the "
          "shape, loses localization (m99 3 vs 1); SMOOTH has NO "
          "localization (w99/L = %.3f); the r172 witness preserves "
          "the signs but FLATTENS the ACF ladder by up to %.1f dex "
          "at %.2f%% direction cost (ovl %.6f) -- the deep-atom "
          "readings are a witness detector at magnitude level"
          % (PIN_EPSTEIN["rmin"], PIN_EPSTEIN["eta"],
             PIN_EPSTEIN["gneg"], PIN_SMOOTH_W99,
             PIN_WIT["flatten_dex"], PIN_WIT["cost_pct"],
             PIN_WIT["ovl"]))

    # ================================================ C: OBJECT-A
    section("C. OBJECT-A (the X6 targeting result, adopted)")
    okJ = True
    check("C1 OBJECT-A: the ONE genuinely new tractable target "
          "(no positivity lever)", okJ,
          "the Bughunt-X X6 adjudication ADOPTED: three names = "
          "two objects + one class name -- r195/v951's cofinal "
          "domination IS wall positivity (OBJECT-W); r198/v954's "
          "pole-vs-hopping balance is the CLASS NAME of the same "
          "OBJECT-W (attacking it as new would repeat the BH8-X1 "
          "error); and 'A_{v_0(h)} >= 0 for all h' is the "
          "GENUINELY DISTINCT OBJECT-A -- v_0(h)-quantified, "
          "yields PROVEN only the sign law, NO lever on wall "
          "positivity claimed; per-rung Sturm-certified through "
          "h = 20 (BH10) and re-certified at h = 4, 5 here; the "
          "PF/KR candidate route NAMED NOT CONSUMED (adjudicated "
          "in v954); census cardinality 4 UNCHANGED; NOT RH "
          "evidence")

    print("\n  [TYPED] A_{v_0} >= 0: GRID-MEASURED at all 14 rungs")
    print("  (KA rider verbatim), CONTINUUM-CERTIFIED by exact Sturm")
    print("  chains at h = 4, 5 (recomputed here) and 13, 20 (BH10);")
    print("  the sign law has a one-line mechanism; OBJECT-A is the")
    print("  one new tractable target.  NO RH claim.")
    return 0


def run():
    global CHECKS, FAILS
    CHECKS = []
    FAILS = []
    print("=" * 74)
    print("v953 -- PRIME.FEWATOM.REDUCTION.01 (A_{v_0} >= 0 with the "
          "KA scope rider;")
    print("the Sturm continuum certificates at h = 4, 5 recomputed "
          "in-module; the")
    print("one-line sign-law mechanism; the horizon ladders; "
          "OBJECT-A; round 197 +")
    print("the Bughunt-X certification; NO RH claim)")
    print("=" * 74)
    rc = part()
    n_run, fails = len(CHECKS), list(FAILS)
    verdict = EXPECTED if (rc == 0 and not fails) else "MIXED"
    ok = (rc == 0 and n_run == N_CHECKS and not fails
          and verdict == EXPECTED)
    print("\n" + "=" * 74)
    print("v953: %d/%d checks passed | verdict %s | runtime %.1f s"
          % (n_run - len(fails), n_run, verdict, time.time() - T_ALL))
    print("PINNING: the wall + v_0 + profile + Sturm certificates + "
          "sign-law")
    print("exhibit + budget resplit + horizon recomputed in-run at "
          "h = 4, 5 (own")
    print("build); the nonneg/decay/horizon/world/witness ladders "
          "PINNED from")
    print("fewatom_reduction_probe.py (SPEC %s, 25/25, record"
          % PIN_SPEC_R197)
    print("790 s + 811 s deterministic re-run, KA/KC correction "
          "block appended")
    print("spec-hash-invariant, RE-RUN GREEN AS TYPED AT PROMOTION "
          "830.7 s, 25/25)")
    print("and the Bughunt-X record (SPEC %s, 30/30)." % PIN_SPEC_BH10)
    print("NOT RH evidence; NO RH claim.")
    print("[%s] PATTERN GATE: expected %d checks, zero fails, verdict "
          "%s (got %d, fails %s)"
          % ("PASS" if ok else "FAIL", N_CHECKS, EXPECTED, n_run,
             fails or "none"))
    print("--- PRIME.FEWATOM.REDUCTION.01 nonnegativity + Sturm "
          "certificates: %d passed, %d failed ---"
          % (n_run - len(fails), len(fails)))
    return 0 if ok else 1


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