#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""v966 -- PRIME.L2.REDUCTION_CHAIN.01 (rounds 296/297/298/299/300, ADJUDICATED at the finite-identity level plus the typed measurement legs): THE L2 REDUCTION CHAIN -- the reviewer DENS fork closed honestly (r296 DENS_WORLD_BLIND: the 92.5-pct DENS top curvature axis is NOT identifiable with any sealed arithmetic density and NOT the L*-gradient direction at the sealed bar) and, on the re-routed L2 front, the four-round chain r297 -> r300 that REDUCES the delta' > 0.21 target of the generic half to ONE remaining inequality -- frozen as ONE module.  (A) THE r296 DENS FORK (measured, honest negative, lane closed): the reviewer hard fork on the r292 curvature axis -- ONE hash-sealed candidate library frozen BEFORE any cosine (T1 = grad lambda_max(E_184) via Hellmann-Feynman, FD ward 3.8e-7; the von Mangoldt / local-metric / kernel-diagonal families; the 4-dim moment-gradient subspace; 8 nulls + decoy), primary metric = the in-span cosine on the 29-direction span; SEALED VERDICT DENS_WORLD_BLIND: THE COUPLING NUMBER cos(e_top, grad lambda_max) = +0.394 sits BELOW the sealed 0.40 bar (noise max 0.331, noise+pad 0.431; miss 0.006, honest), the lam3 control couples HARDER (-0.574) -- what coupling exists is a near-crossing eigenvalue-BAND property, not top-specific; every arithmetic candidate <= 0.38; the only above-chance structure (the moment subspace, 0.825) HOLDS on both dead controls (0.571/0.603 >= 0.40) and the sealed world-downgrade fires PART -> BLIND (disclosed tension: the absolute collapse bar is conservative for subspace members; rule unmoved) -- THE DENS-IDENTITY LANE IS CLOSED, resources move to L2 (the pre-adjudicated reviewer routing).  (B) THE r297 TARGET INEQUALITY (the L2 lane opened): the exact slope decomposition slope(eps_F2/M) = (1/2)[slope(pref) + sigma] with sigma := slope(S_F/M^2) makes delta'(F2) > 0.21 EQUIVALENT to the frozen TARGET INEQUALITY sigma <= sigma* := 2(slope(eps_c2/M) - 0.21) - slope(pref) = -0.516 -- the weakest sufficient input bound, all constants live; measured sigma = -0.714: THE TRUTH CLEARS THE TARGET WITH 0.198 SIGMA MARGIN (0.099 in delta') -- what is missing is not room, it is provenance; the m2 pad-sharpness is EXACT ARITHMETIC: sigma* composes to delta' = 0.21 exactly, the pad-dropped mutant to 0 (re-proved module-own in Fractions, T1); all three classical provenance routes VALID 47/47 but SLOPE-FAIL (B1 pair-identity delta' -0.112: the max pair gap falls at -0.535 where <= -1.178 would suffice; B2 node-density delta' -0.097: positions near-equidistributed with FALLING D_rank 0.024 / -0.42 -- provable terrain -- but the mass imbalance GROWS +0.244; B3 Fejer/Parseval delta' -0.097 with THE SURPRISE: the chain is EXACTLY ORTHOGONAL w.r.t. the WINDOW measure, devs 0.000 world-blind, the Fractions-proved Parseval sum rule attaches verbatim) => CHAIN_PROVENANCE_PARTIAL(B3, slope miss 0.307 = 0.21 - (-0.097) EXACT); THE MAGNITUDE WALL NAMED: every source-pure majorization of the P-variance through MAGNITUDES pays a growing max/mean imbalance factor (+0.22..+0.24) -- the signed structure carrying sigma = -0.71 is what |.|-chains cannot see.  (C) THE r298 EXACT TRANSFER (the sign-preserving decomposition): with Delta := border (-) window and the frozen positional Fejer block kernel, S_F IS the quadratic form B(beta, beta) and splits EXACTLY (8.8e-16 of scale, 47 worlds) as S_F = B(omega, omega) + B(Delta, omega + beta) -- the difference-of-squares split, NOTHING passes through magnitudes (the |Delta| mutant breaks by ~1.7 of scale LOUD -- the r297 magnitude error certified as a must-fail); the linear corollary MEASURED: the window image of the drive functional VANISHES at float precision (the drive is 100 pct transfer at the linear level); SEALED VERDICT TRANSFER_DOMINANT: the window main term is EMPTY (med -3.94 dec, two decades below S_F, slope -1.386 collapsing; NOT the r259/r261 near-cancellation pattern), the cross term negligible (med -1.4e-4) => S_F ~ B(PDelta, PDelta): THE VDC INPUT IS THE FEJER ENERGY OF THE DIFFERENCE MEASURE ITSELF, share med 0.99, T > 0 on 42/42; the in-T sign cancellation (med 1.69, +0.207) localizes the r297 imbalance INSIDE T, and the Leg-D bycatch unifies the two r297 gap halves (sp(block mass, |t_j|) med +0.69, BROAD_BASED).  (D) THE r299 DECAY SPLIT (the frequency anatomy): the module-own exact spectral representation B = (1/L) sum_k F_H(theta_k) |Dhat(k)|^2 (wards 7.1e-16, 47 worlds) is LOWPASS (band shares 0.93/0.04/0.02 -- sigma is a low-frequency phenomenon); THE STRUCTURAL FIND: FULL-SUPPORT overlap on 42/42 rungs -- Delta_fresh == 0 identically, Delta IS a pure c-value difference measure on ONE shared node set, and the relative c-difference does NOT fall (cconv 0.86, +0.045): the decay is aggregate cancellation of a non-converging difference profile; the ET/Abel route FAILS LOUD (composed +1.948 = 1.504 + 0.444 EXACT vs sigma* -0.516: position bounds compose away the cancellation -- the r297 magnitude wall recurs at the frequency level; MASS_TARGET missed by 2.46); THE LIVE EDGE fires: the diagonal D = sum PDelta_j^2 ALREADY falls fast enough (sl_D = -0.571 <= sigma* = -0.516, margin 0.055) and the pair ratio B/D (med 1.29) FALLS (-0.168) => DECAY_SPLIT with the frozen rest pair DIAG_TARGET + ratio flatness (CVALUE_TARGET on the B3 side); bycatch: the first world-separating sign class of the lane -- the O-sign separates MAIN (O_POS, reinforcing, O < 0 on 13/42 only) from both dead controls (O_NEG), disclosed WORLD_SENSITIVE.  (E) THE r300 DIAGONAL ANATOMY (the refined freeze): in the exact participation coordinates of the ONE positive vector |PDelta| (n_eff = L1^2/D, fill = D/(mx x L1)) the diagonal decay decomposes EXACTLY: sl_D = 2 sl_L1 - sl_neff = 2(+0.196) - (+0.963) = -0.571 (dev 6.7e-16) and sl_D = sl_mx + sl_L1 + sl_fill = -0.542 + 0.196 - 0.225 (dev 4.4e-16) -- THE ENTIRE DIAGONAL DECAY IS PARTICIPATION GROWTH ('many small instead of few large' as a measured identity; n_eff grows ~N, sp +0.96); BOTH magnitude factorizations fail exactly as r297 predicted (B1 chain-norm CS -0.592 + 0.208 = -0.384 EXACT, misses sigma* AND the |dw| identity census BREAKS -- the proven sum rule does NOT attach to the difference measure, the chain-norm shortcut closed honestly; B2 max x L1 -0.542 + 0.196 = -0.346 EXACT, misses by 0.170 -- the max IS atom-controlled, mx/maxatom med 1.07: the irreducible loss is the fill decay -0.225, invisible to every max x mass bound); SEALED VERDICTS DIAG_SPLIT(B3/NEFF_TARGET) + RATIO_BOUNDED_STRUCTURAL: the exact kernel envelope F_H(theta) <= min(H, 1/(H sin^2(theta/2))) majorizes B/D <= R_env (med 1.61) and R_env itself FALLS (-0.122 <= +0.05) on 47/47 -- THE RATIO HALF OF THE REST PAIR IS SETTLED AT THE STRUCTURAL LEVEL (the lobe-width heuristic refuted, sp -0.47); the refined freeze is ONE inequality: NEFF_TARGET -- prove slope(n_eff) >= 2 sl_L1 - sigma* = +0.908 (measured +0.963, margin 0.055; disclosed: an exact reparametrization of DIAG_TARGET -- the derivation content is the D_rank bridge, falling -0.117, sp(D_rank, n_eff) = -0.81, real but correlational); second world-separating class: FILL separates MAIN (FILL_LOW) from both dead controls (FILL_HIGH).  THE CHAIN STATE (the wave-9 content): [NEFF_TARGET, open] ==> sl_D <= sigma* (r300 exact participation algebra) ==> with RATIO_BOUNDED_STRUCTURAL sigma <= sigma* (r299/r300) ==> the r297 target inequality ==> the v964-S0 vdC theorem ==> delta' > 0.21 on the generic half (exceptions: 6 via the r287 F2 certificates, kz15 exact-finite via r270) -- the L2 lemma stands REDUCED TO ONE INEQUALITY; the executing round 301 (NEFF_TARGET) is IN FLIGHT at this promotion cut and NOT consumed.  THE MODULE-OWN EXACT SECTION S0 (pure Fractions, no probe imports): (T1) the r297 sigma*-COMPOSITION ARITHMETIC: delta'(sigma*(pad)) == pad for every rational slope pair -- the sealed sigma* composes to delta' = 21/100 exactly and the pad-dropped mutant to 0 exactly (the r297-m2 sharpness as an identity, two independent rational witnesses); (T2) the r298 DECOMPOSITION IDENTITY on the exact positional Fejer block form B(u, v) = (1/H) sum_t W_t(u) W_t(v): B(beta, beta) == B(omega, omega) + B(beta - omega, beta + omega) identically (bilinear difference-of-squares; the r298 hand toy reproduced EXACTLY: S_F = 3 = 1 + 2, attribution T_diag = 1 / T_cross = 1; a second 5-block H = 3 rational witness; the lag-side Fejer identity B == sum (1 - |h|/H) A(h) exact with the (1 - |h|/(H+1)) mutant breaking by exactly 2/3 on the toy; the |Delta| magnitude mutant breaking by exactly 4); (T3) the r300 PARTICIPATION IDENTITY as exact algebra: D x n_eff == L1^2 and D == mx x L1 x fill identically on rational vectors, ratio-multiplicativity across ladder points (the exact content of sl_D = 2 sl_L1 - sl_neff), the record-decimal consistency 2(196/1000) - 963/1000 == -571/1000 and 2(196/1000) + 516/1000 == 908/1000 with margin 55/1000 EXACT in BOTH coordinates (the disclosed r300 equivalence machine-checked), the signed-sum mutant breaking by exactly 8/3 on (1, -1, 1) and the D <= mx^2 mutant breaking on (2, 1, 1) while D <= mx x L1 holds; (T4) the r300 KERNEL ENVELOPE as an exact inequality: F_H expressed as an exact rational function of s = sin^2(theta/2) (H = 2: 2(1 - s); H = 3: (3 - 4s)^2/3), F_H(s) <= min(H, 1/(H s)) on a rational grid with EXACT EQUALITY WITNESSES on both branches (H = 2: s = 0 and s = 1/2; H = 3: s = 0 and s = 1/4) and the halved-envelope mutant breaking at the witness; (V1-V5) the five SEALED VERDICT BARS as exact decision logic on the record aggregates (Fractions): r296 -> DENS_WORLD_BLIND (base PARTIAL, world-downgrade fires; tipping mutants: a collapsing control keeps PARTIAL, T1 at 0.40 fires PART), r297 -> CHAIN_PROVENANCE_PARTIAL(B3) with the 0.307 slope miss exact, r298 -> TRANSFER_DOMINANT (mutants land SUBDOMINANT / UNSTABLE at the sealed clause boundaries), r299 -> LOWPASS + DECAY_SPLIT(B2, B3), r300 -> DIAG_SPLIT(B3) + RATIO_BOUNDED_STRUCTURAL (mutants: sl_neff below need -> STILL_EMPIRICAL, growing R_env -> RATIO_EMPIRICAL); (V6) the CHAIN COMPOSITION gate: the reduction diagram instantiated on the records with every link margin printed and the single open input named.  ONE module from five probes (39/39 + 27/27 + 28/28 + 32/32 + 31/31 full records, zero fails after the disclosed calibration amendments; discovery probes dens_identity_probe.py, vdc_chain_provenance_probe.py, window_border_transfer_probe.py, fejer_decay_probe.py, diag_target_probe.py, rounds 296-300, notes DCXXXV/DCXXXVI/DCXXXVII/DCXXXVIII/DCXXXIX, 2026-08-26, embedded BYTE-EXACT and executed verbatim in their sealed --smoke stage at promotion -- the wave-4 embedding convention: full records sealed experiments-side and re-verified by rh/verification/run_rh.py), plus the module-own exact section S0 above.  WHAT THE CHAIN DOES NOT SAY (honest boundary): delta' > 0.21 is NOT proved -- NEFF_TARGET (slope(n_eff) >= +0.908) is the ONE remaining inequality and it is OPEN (PRIME.L2.NEFF_TARGET.01 [O]; the D_rank bridge is correlational, not causal; round 301 in flight, NOT consumed); every slope is MEASURED on 42 rungs only, no cofinal law is claimed; the exception scalar's positivity beyond the measured 42 stays open; the DENS closure is a finite-window negative at the sealed bars, not a nonexistence theorem; L* itself stays THE open center (PRIME.LSTAR.SUBORDINATION.01 [O]; Lean lstar_subordination, rh/lean/RH/Window.lean).  Mincut base 4 / refined 5 UNCHANGED (a reduction-plus-closure 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 dens_identity_probe.py (39/39 full,
smoke 12/12, SPEC_SHA ffb413c80cddc1d3, amendments a1-a4 disclosed
pre-freeze -- evenness-gate conditioning at libm precision, FD
coordinate/step re-anchoring at the measured margin-valid scale,
the r294 0.989 share re-typed as the training-form record, the
hardening repetition pinned to the actual best member),
vdc_chain_provenance_probe.py (27/27 full == smoke, SPEC_SHA
e42a76eb8ae71422, amendments a1 index bugfix + a2 reporting
disclosed), window_border_transfer_probe.py (28/28 full == smoke,
SPEC_SHA 05e831bec627aee6, amendments a1 toy-constant hand-
arithmetic fix + a2 reporting disclosed), fejer_decay_probe.py
(32/32 full == smoke, SPEC_SHA f432e94450ad545d, amendments a1
O-sign class per sealed spec + a2 reporting disclosed),
diag_target_probe.py (31/31 full == smoke, SPEC_SHA
55218b5db8ece163, amendment a1 scale floor on the degenerate
SMOOTH Delta == 0 disclosed); rounds 296-300, notes
DCXXXV/DCXXXVI/DCXXXVII/DCXXXVIII/DCXXXIX, 2026-08-26.
WAVE-4 EMBEDDING CONVENTION (as in v960..v965): frozen sources
embedded BYTE-EXACT and executed verbatim in isolated namespaces in
their sealed --smoke stage (deterministic, seconds each); printed
SPEC SHAs pinned and gated; byte-equality ward vs experiments/
tfpt-discovery/ inside the pattern gates; the full-mode records
(gate counts above, wall times 81/47.8/46.9/48.3/48.1 s) are sealed
experiments-side and re-verified by rh/verification/run_rh.py.  The
probes consume the READ-ONLY deployed core v563_paper2_readouts.py
and the frozen experiments-side libraries (imports printed in their
headers); the execution order follows the round order so later
probes import earlier ones from the embedded byte-exact sources
(sys.modules convention: r298 imports the embedded r297, r299 the
embedded r297/r298, r300 the embedded r297/r298/r299; r296 imports
the frozen wave-8 probes r290/r291/r292 from the experiments tree,
none from this wave).  Round 301 (NEFF_TARGET) is in flight at this
promotion cut and NOT consumed.

FIREWALL: no zeros, no prime-table oracles (AST scans inside the
probes); RNG only in declared direction/corpus/ensemble seeds;
ground truth (branch labels, survival records, route tables) enters
gates only; NO promotion of NEFF_TARGET (the open inequality is
registered [O], not claimed); 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 machinery (pure Fractions; the
# ---------------- r297 sigma*-composition, the r298 Fejer block
# ---------------- decomposition, the r300 participation identity,
# ---------------- the r300 kernel envelope and the five sealed
# ---------------- verdict bars are re-derived from scratch at
# ---------------- module level -- no probe imports)
def _compose_delta(sl_c2, sl_pref, sigma):
    """the r297 exact slope decomposition read backwards:
    delta'(F2) = sl_c2 - (1/2) (sl_pref + sigma)  (exact)."""
    return sl_c2 - (sl_pref + sigma) / 2


def _sigma_star(sl_c2, sl_pref, pad):
    """the r297 frozen target level: the weakest sufficient input
    bound sigma* = 2 (sl_c2 - pad) - sl_pref (exact); the m2 mutant
    drops the pad (pad = 0)."""
    return 2 * (sl_c2 - pad) - sl_pref


def _wt_sums(P, H):
    """the sliding H-window sums W_t of a block vector P (the
    v964-S0 / r298 positional Fejer convention; exact)."""
    m = len(P)
    return [sum(P[j] for j in range(max(0, t - H + 1), min(m, t + 1)))
            for t in range(m + H - 1)]


def _fejer_bil(u, v, H):
    """the exact positional Fejer block form
    B(u, v) = (1/H) sum_t W_t(u) W_t(v)."""
    Wu, Wv = _wt_sums(u, H), _wt_sums(v, H)
    return sum(a * b for a, b in zip(Wu, Wv)) / _Fr(H)


def _autocorr(P, h):
    """the exact block autocorrelation A(h) = sum_j P_j P_{j+h}."""
    m = len(P)
    return sum(P[j] * P[j + h] for j in range(m - h))


def _fejer_lag(P, H, wrong_denominator=False):
    """the lag-side Fejer window sum sum_{|h|<H} (1 - |h|/H) A(h)
    (exact; == B(P, P) by the v964-S0 identity); the mutant flag
    replaces H by H + 1 in the weight only (the r299-m1 form)."""
    den = H + 1 if wrong_denominator else H
    tot = _autocorr(P, 0)
    for h in range(1, H):
        tot += 2 * (1 - _Fr(h, den)) * _autocorr(P, h)
    return tot


def _participation(P, signed_mutant=False):
    """the r300 participation coordinates of a block vector (exact):
    D = sum P^2, L1 = sum |P|, mx = max |P|, n_eff = L1^2 / D,
    fill = D / (mx L1); the mutant replaces L1^2 by the SIGNED sum
    squared (the r300-m1 form)."""
    D = sum(p * p for p in P)
    L1 = sum(abs(p) for p in P)
    mx = max(abs(p) for p in P)
    num = (sum(P)) ** 2 if signed_mutant else L1 * L1
    return dict(D=D, L1=L1, mx=mx, neff=num / D, fill=D / (mx * L1))


def _fh_of_s(H, s):
    """the Fejer kernel F_H(theta) = sin^2(H theta/2)/(H sin^2
    (theta/2)) as an EXACT rational function of s = sin^2(theta/2)
    for H = 2, 3 (double/triple-angle algebra):
    H = 2: 4 s (1 - s) / (2 s) = 2 (1 - s);
    H = 3: s (3 - 4 s)^2 / (3 s) = (3 - 4 s)^2 / 3."""
    if H == 2:
        return 2 * (1 - s)
    if H == 3:
        return (3 - 4 * s) ** 2 / _Fr(3)
    raise ValueError("exact form implemented for H = 2, 3 only")


def _envelope(H, s, halved_mutant=False):
    """the r300 exact kernel envelope min(H, 1/(H s)) at s =
    sin^2(theta/2) (s = 0 read as the theta -> 0 limit H); the
    mutant halves the second branch (1/(2 H s))."""
    if s == 0:
        return _Fr(H)
    second = 1 / (_Fr(2 * H) * s) if halved_mutant else 1 / (_Fr(H) * s)
    return min(_Fr(H), second)


# --------- frozen record aggregates (rounds 296-300; exact decimal
# --------- pins as Fractions where the printed record is exact;
# --------- ground truth sealed probe-side, re-verified by the
# --------- embedded pattern gates below and by run_rh.py)
_D = lambda num, den=1000: _Fr(num, den)          # noqa: E731
_R296 = dict(best=_D(825), best_single=_D(394),
             ctrl=(_D(571), _D(603)),
             t1=_D(394), noise=_D(331),
             bar_id=_D(800), bar_part=_D(400), pad=_D(100),
             lam3=_D(-574), windows_hold=3)
_R297 = dict(sigma=_D(-714), sigma_star=_D(-516),
             sl_c2=_D(196), sl_pref=_D(489), pad=_D(210),
             routes=(_D(-112), _D(-97), _D(-97)),
             ident_b3=True, valid=(47, 47, 47))
_R298 = dict(share=_D(99, 100), main_dec=_D(-394, 100),
             sf_dec=_D(-200, 100), sl_main=_D(-1386),
             sl_T=_D(-698), unstable_factor=_Fr(10),
             sub_share=_Fr(1, 2), sub_margin=_D(50))
_R299 = dict(low=_D(93, 100), lowpass_bar=_D(75, 100),
             broad_bar=_D(50, 100),
             sl_pos=_D(1504), sl_mass=_D(444), composed=_D(1948),
             sl_D=_D(-571), ratio_slope=_D(-168),
             ratio_grow=_D(50), ov=_Fr(1), xa=_Fr(0),
             ov_bar=_D(75, 100), xa_bar=_D(50, 100),
             full_overlap=42)
_R300 = dict(sl_neff=_D(963), sl_L1=_D(196), sl_mx=_D(-542),
             sl_fill=_D(-225), sl_D=_D(-571),
             b1=( _D(-592), _D(208)), b2_composed=_D(-346),
             needed=_D(908), dd_slope=_D(-117),
             renv_slope=_D(-122), ratio_grow=_D(50),
             ident_dw_breaks=True)


def _bar_r296(best_single, best_all, t1, ctrl, R):
    """the sealed r296 identity bar as exact decision logic: the
    IDENTITY award (>= 0.80) is open to single-direction members
    (T1/T2/T3/T4) ONLY; the PARTIAL band (0.40 <= max < 0.80) runs
    over the eligible library INCLUDING the T5 subspace root share;
    then the sealed world-downgrade (one level) iff NO control
    collapses (both >= 0.40); T1 is always reported separately
    against bar / noise / noise+pad."""
    if best_single >= R["bar_id"]:
        base = "DENS_ARITHMETIC_IDENTITY"
    elif best_all >= R["bar_part"]:
        base = "DENS_PARTIAL"
    else:
        base = "DENS_WORLD_BLIND"
    collapsed = any(c < R["bar_part"] for c in ctrl)
    down = (base != "DENS_WORLD_BLIND") and not collapsed
    final = {"DENS_ARITHMETIC_IDENTITY": "DENS_PARTIAL",
             "DENS_PARTIAL": "DENS_WORLD_BLIND"}[base] if down else base
    t1_class = ("COUPLED" if t1 >= R["bar_part"] else
                "BELOW_BAR_ABOVE_NOISE" if t1 > R["noise"] else
                "NOISE_LEVEL")
    return base, final, t1_class


def _bar_r297(sigma, sigma_star, routes, ident_b3, pad):
    """the sealed r297 adjudication as exact decision logic:
    SLOPE_OK per route iff delta'_route > pad; PROVEN needs B3
    SLOPE_OK + IDENT (+ one-signed weights, structurally false);
    PARTIAL iff some route VALID and (SLOPE_OK or IDENT); the
    target margin and the B3 slope miss are exact."""
    slope_ok = [d > pad for d in routes]
    if slope_ok[2] and ident_b3:
        verdict = "CHAIN_PROVENANCE_PROVEN"
    elif any(slope_ok) or ident_b3:
        verdict = "CHAIN_PROVENANCE_PARTIAL"
    else:
        verdict = "INPUT_STILL_EMPIRICAL"
    return verdict, sigma_star - sigma, pad - routes[2]


def _bar_r298(main_dec, sf_dec, share, sl_T, sl_main, R):
    """the sealed r298 three-way adjudication (exact decision
    logic on the printed decades/medians): UNSTABLE iff
    med(MAIN/S_F) >= 10 (i.e. main_dec - sf_dec >= 1 decade);
    SUBDOMINANT iff not unstable and share < 1/2 and
    sl_T <= sl_main - 0.05; else DOMINANT."""
    if main_dec - sf_dec >= 1:
        return "DECOMPOSITION_UNSTABLE"
    if share < R["sub_share"] and sl_T <= sl_main - R["sub_margin"]:
        return "TRANSFER_SUBDOMINANT"
    return "TRANSFER_DOMINANT"


def _bar_r299(low, sl_pos, sl_mass, sl_D, ratio_slope, ov, xa,
              sigma_star, R):
    """the sealed r299 band + decay adjudication (exact): band tag
    LOWPASS iff low >= 0.75 / BROADBAND iff < 0.50 / else MIXED;
    B1_OK iff sl_pos + sl_mass <= sigma*; B2_OK iff sl_D <= sigma*
    and ratio slope <= +0.05; B3_OK iff OV_DOM (ov >= 0.75 and
    xa <= 0.50); DERIVED iff sl_pos <= sigma* and sl_mass <= 0;
    SPLIT iff any route fires; else STILL_EMPIRICAL."""
    band = ("LOWPASS" if low >= R["lowpass_bar"] else
            "BROADBAND" if low < R["broad_bar"] else "MIXED_BAND")
    b1 = sl_pos + sl_mass <= sigma_star
    b2 = sl_D <= sigma_star and ratio_slope <= R["ratio_grow"]
    b3 = ov >= R["ov_bar"] and xa <= R["xa_bar"]
    if sl_pos <= sigma_star and sl_mass <= 0:
        verd = "DECAY_DERIVED"
    elif b1 or b2 or b3:
        verd = "DECAY_SPLIT"
    else:
        verd = "DECAY_STILL_EMPIRICAL"
    return band, (b1, b2, b3), verd


def _bar_r300(b1_composed, b2_composed, sl_neff, needed, dd_slope,
              ident_dw_breaks, renv_slope, sigma_star, R):
    """the sealed r300 diag + ratio adjudication (exact): B1_OK iff
    the chain-norm composition meets sigma*; B2_OK iff the max x L1
    composition meets sigma*; B3_OK iff sl_neff >= needed and the
    D_rank(Delta) slope falls; DERIVED iff B1_OK and the |dw|
    identity census HOLDS; SPLIT iff any route fires; RATIO is
    BOUNDED_STRUCTURAL iff slope(R_env) <= +0.05."""
    b1 = b1_composed <= sigma_star
    b2 = b2_composed <= sigma_star
    b3 = sl_neff >= needed and dd_slope < 0
    if b1 and not ident_dw_breaks:
        verd = "DIAG_DERIVED"
    elif b1 or b2 or b3:
        verd = "DIAG_SPLIT"
    else:
        verd = "DIAG_STILL_EMPIRICAL"
    ratio = ("RATIO_BOUNDED_STRUCTURAL"
             if renv_slope <= R["ratio_grow"] else "RATIO_EMPIRICAL")
    return (b1, b2, b3), verd, ratio


def _l2_reduction_chain(gates):
    """The L2 reduction chain: the module-own exact skeleton
    (T1-T4, pure Fractions) plus the five sealed verdict bars as
    exact decision logic on the record aggregates (V1-V5) plus the
    chain-composition gate (V6)."""

    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 L2 reduction chain "
          "(T1-T4 + V1-V6)")
    print("-" * 74, flush=True)

    # ---- T1 the r297 sigma*-composition arithmetic (exact)
    pad = _Fr(21, 100)
    wit = ((_Fr(196, 1000), _Fr(489, 1000)),
           (_Fr(7, 31), _Fr(355, 719)))            # two rational pairs
    ok_t1 = all(_compose_delta(c2, pf, _sigma_star(c2, pf, pad)) == pad
                for c2, pf in wit)
    chk("T1-sigma-star-composition", ok_t1,
        "delta'(sigma*(pad)) == pad = 21/100 EXACTLY for both "
        "rational witnesses (incl. the record pair sl_c2 = 0.196, "
        "sl_pref = 0.489) -- the r297 target level is the exact "
        "preimage of the 0.21 demand")
    ok_t1m = all(_compose_delta(c2, pf, _sigma_star(c2, pf, 0)) == 0
                 for c2, pf in wit) and not (0 > pad)
    chk("T1m-pad-dropped-mutant", ok_t1m,
        "the pad-dropped mutant (DELTA_NEED -> 0) composes to "
        "delta' = 0 EXACTLY, which fails the > 0.21 demand -- the "
        "pad term is load-bearing (the r297-m2 sharpness)")

    # ---- T2 the r298 decomposition identity (exact block form)
    H2 = 2
    beta = [_Fr(2), _Fr(-2), _Fr(1)]
    omega = [_Fr(1), _Fr(-1), _Fr(0)]
    delta = [b - w for b, w in zip(beta, omega)]
    both = [b + w for b, w in zip(beta, omega)]
    S_F = _fejer_bil(beta, beta, H2)
    MAIN = _fejer_bil(omega, omega, H2)
    T = _fejer_bil(delta, both, H2)
    T_diag = _fejer_bil(delta, delta, H2)
    T_cross = 2 * _fejer_bil(delta, omega, H2)
    ok_t2 = (S_F == 3 and MAIN == 1 and T == 2
             and S_F == MAIN + T and T == T_diag + T_cross
             and T_diag == 1 and T_cross == 1)
    chk("T2-decomposition-identity-toy", ok_t2,
        "the r298 hand toy EXACT: S_F = B(beta,beta) = 3 == "
        "B(omega,omega) + B(Delta,omega+beta) = 1 + 2; components "
        "T_diag = B(PDelta,PDelta) = 1, T_cross = 2 B(PDelta,"
        "Pomega) = 1 (the a1-corrected constants)")
    beta5 = [_Fr(3, 2), _Fr(-1, 3), _Fr(2, 7), _Fr(-5, 4), _Fr(1, 6)]
    omeg5 = [_Fr(1, 5), _Fr(2, 3), _Fr(-3, 8), _Fr(1, 2), _Fr(-2, 9)]
    d5 = [b - w for b, w in zip(beta5, omeg5)]
    s5 = [b + w for b, w in zip(beta5, omeg5)]
    ok_t2b = all(
        _fejer_bil(beta5, beta5, H) ==
        _fejer_bil(omeg5, omeg5, H) + _fejer_bil(d5, s5, H)
        and _fejer_bil(d5, s5, H) ==
        _fejer_bil(d5, d5, H) + 2 * _fejer_bil(d5, omeg5, H)
        for H in (2, 3))
    chk("T2b-decomposition-general", ok_t2b,
        "the difference-of-squares split holds IDENTICALLY on a "
        "second 5-block rational witness at H = 2 AND H = 3 (pure "
        "bilinearity: B(b,b) - B(w,w) = B(b-w, b+w) exactly)")
    ok_t2c = (_fejer_lag(delta, H2) == T_diag
              and _fejer_lag(beta5, 3) == _fejer_bil(beta5, beta5, 3))
    chk("T2c-lag-identity", ok_t2c,
        "the lag-side Fejer identity sum (1 - |h|/H) A(h) == "
        "B(P, P) EXACT on both witnesses (the v964-S0 window-sum "
        "identity re-computed)")
    brk = _fejer_lag(delta, H2, wrong_denominator=True)
    ok_t2d = (T_diag - brk == _Fr(2, 3))
    chk("T2d-wrong-weight-mutant", ok_t2d,
        "the (1 - |h|/(H+1)) mutant gives 1/3 vs 1 on the toy -- "
        "break exactly 2/3 LOUD (the r299-m1 form)")
    absd = [abs(x) for x in delta]
    ok_t2e = (_fejer_bil(absd, absd, H2) - T_diag == 4)
    chk("T2e-magnitude-mutant", ok_t2e,
        "|Delta| for Delta breaks the energy by exactly 4 on the "
        "toy (5 vs 1) -- the sign structure is load-bearing (the "
        "r297 magnitude wall / r298-m2 / r299-m2 as one exact "
        "fact)")

    # ---- T3 the r300 participation identity (exact algebra)
    vecs = ([_Fr(1), _Fr(-1), _Fr(1)],
            [_Fr(2), _Fr(1), _Fr(1)],
            [_Fr(3, 7), _Fr(-2, 5), _Fr(1, 4), _Fr(-5, 6)])
    ok_t3 = True
    for P in vecs:
        c = _participation(P)
        ok_t3 = ok_t3 and (c["D"] * c["neff"] == c["L1"] ** 2
                           and c["D"] == c["mx"] * c["L1"] * c["fill"]
                           and c["fill"] <= 1)
    p1, p2 = _participation(vecs[0]), _participation(vecs[2])
    ok_t3 = ok_t3 and (
        (p2["D"] / p1["D"]) * (p2["neff"] / p1["neff"])
        == (p2["L1"] / p1["L1"]) ** 2)
    chk("T3-participation-identity", ok_t3,
        "D x n_eff == L1^2 and D == mx x L1 x fill EXACT on three "
        "rational vectors, with the ratio form (D2/D1)(neff2/neff1)"
        " == (L12/L11)^2 across ladder points -- the exact content "
        "of sl_D = 2 sl_L1 - sl_neff")
    R = _R300
    ok_t3b = (2 * R["sl_L1"] - R["sl_neff"] == _Fr(-571, 1000)
              and R["sl_mx"] + R["sl_L1"] + R["sl_fill"]
              == _Fr(-571, 1000)
              and 2 * R["sl_L1"] - _R297["sigma_star"]
              == _Fr(908, 1000)
              and R["sl_neff"] - _Fr(908, 1000) == _Fr(55, 1000)
              and _R297["sigma_star"] - _R299["sl_D"]
              == _Fr(55, 1000)
              and R["b1"][0] + R["b1"][1] == _Fr(-384, 1000)
              and R["sl_mx"] + R["sl_L1"] == R["b2_composed"])
    chk("T3b-record-decimal-consistency", ok_t3b,
        "the frozen record decimals compose EXACTLY: sl_D = "
        "2(0.196) - 0.963 = -0.571 = -0.542 + 0.196 - 0.225 (both "
        "decompositions), NEFF need = 2(0.196) + 0.516 = 0.908 "
        "with margin 0.055 EXACT in both coordinates (the "
        "disclosed r300 DIAG<->NEFF equivalence machine-checked), "
        "B1 = -0.592 + 0.208 = -0.384, B2 = -0.542 + 0.196 = "
        "-0.346")
    m1 = _participation(vecs[0], signed_mutant=True)
    ok_t3c = (_participation(vecs[0])["neff"] - m1["neff"]
              == _Fr(8, 3))
    c2 = _participation(vecs[1])
    ok_t3c = ok_t3c and (c2["D"] > c2["mx"] ** 2
                         and c2["D"] <= c2["mx"] * c2["L1"])
    chk("T3c-participation-mutants", ok_t3c,
        "the signed-sum mutant breaks n_eff by exactly 8/3 on "
        "(1,-1,1) -- CAUGHT (r300-m1); the D <= mx^2 claim breaks "
        "on (2,1,1) (6 > 4) while D <= mx x L1 holds (8) -- the "
        "L1 factor is load-bearing (r300-m2)")

    # ---- T4 the r300 kernel envelope (exact inequality)
    grid = [_Fr(k, 24) for k in range(0, 25)]
    ok_t4 = all(_fh_of_s(H, s) <= _envelope(H, s)
                for H in (2, 3) for s in grid)
    eq_wit = (_fh_of_s(2, _Fr(0)) == _envelope(2, _Fr(0)) == 2,
              _fh_of_s(2, _Fr(1, 2)) == _envelope(2, _Fr(1, 2)) == 1,
              _fh_of_s(3, _Fr(0)) == _envelope(3, _Fr(0)) == 3,
              _fh_of_s(3, _Fr(1, 4)) == _envelope(3, _Fr(1, 4))
              == _Fr(4, 3))
    chk("T4-kernel-envelope", ok_t4 and all(eq_wit),
        "F_H(s) <= min(H, 1/(H s)) EXACT on the 25-point rational "
        "grid for H = 2, 3 with EQUALITY WITNESSES on both "
        "branches: H = 2 at s = 0 (F = 2 = H) and s = 1/2 (F = 1 "
        "= 1/(2s)); H = 3 at s = 0 (F = 3) and s = 1/4 (F = 4/3 = "
        "1/(3s)) -- the r300 ratio majorant is pure kernel algebra")
    ok_t4m = (_fh_of_s(2, _Fr(1, 2))
              > _envelope(2, _Fr(1, 2), halved_mutant=True))
    chk("T4m-halved-envelope-mutant", ok_t4m,
        "the halved-envelope claim 1/(2 H s) breaks at the s = 1/2 "
        "witness (1 > 1/2) -- CAUGHT: the envelope constant is "
        "sharp")

    # ---- V1 the r296 sealed bar (exact decision logic)
    R6 = _R296
    base, final, t1c = _bar_r296(R6["best_single"], R6["best"],
                                 R6["t1"], R6["ctrl"], R6)
    ok_v1 = (base == "DENS_PARTIAL" and final == "DENS_WORLD_BLIND"
             and t1c == "BELOW_BAR_ABOVE_NOISE"
             and R6["t1"] < R6["noise"] + R6["pad"]
             and abs(R6["lam3"]) > R6["t1"])
    chk("V1-r296-verdict-bar", ok_v1,
        "record aggregates -> base DENS_PARTIAL(T5 0.825), the "
        "world-downgrade fires (controls 0.571/0.603 >= 0.40, not "
        "collapsed) -> DENS_WORLD_BLIND; T1 coupling 0.394 < 0.40 "
        "bar, > 0.331 noise, < 0.431 noise+pad; |lam3| = 0.574 > "
        "T1 -- the coupling is a band property: THE DENS LANE IS "
        "CLOSED at the sealed rules")
    _, f_m1, _ = _bar_r296(R6["best_single"], R6["best"], R6["t1"],
                           (_Fr(399, 1000), R6["ctrl"][1]), R6)
    b_m2, _, t1_m2 = _bar_r296(R6["best_single"], R6["best"],
                               _Fr(400, 1000), R6["ctrl"], R6)
    ok_v1m = (f_m1 == "DENS_PARTIAL" and t1_m2 == "COUPLED"
              and b_m2 == "DENS_PARTIAL")
    chk("V1m-r296-tipping-mutants", ok_v1m,
        "one control at 0.399 -> collapsed -> NO downgrade "
        "(DENS_PARTIAL stands); T1 at exactly 0.40 -> COUPLED -- "
        "both clause boundaries have teeth")

    # ---- V2 the r297 sealed bar (exact decision logic)
    R7 = _R297
    verd7, marg7, miss7 = _bar_r297(R7["sigma"], R7["sigma_star"],
                                    R7["routes"], R7["ident_b3"],
                                    R7["pad"])
    ok_v2 = (verd7 == "CHAIN_PROVENANCE_PARTIAL"
             and R7["sigma"] <= R7["sigma_star"]
             and marg7 == _Fr(198, 1000)
             and marg7 / 2 == _Fr(99, 1000)
             and miss7 == _Fr(307, 1000))
    chk("V2-r297-verdict-bar", ok_v2,
        "sigma = -0.714 <= sigma* = -0.516 with margin 0.198 "
        "EXACT (= 0.099 in delta'); no route SLOPE_OK (-0.112/"
        "-0.097/-0.097 vs need > 0.21); B3 VALID + IDENT -> "
        "CHAIN_PROVENANCE_PARTIAL(B3, slope miss 0.307 = 0.21 - "
        "(-0.097) EXACT)")
    verd7m, _, _ = _bar_r297(R7["sigma"], R7["sigma_star"],
                             (R7["routes"][0], R7["routes"][1],
                              _Fr(211, 1000)), True, R7["pad"])
    ok_v2m = verd7m == "CHAIN_PROVENANCE_PROVEN"
    chk("V2m-r297-tipping-mutant", ok_v2m,
        "a hypothetical B3 delta' of +0.211 (> pad) with IDENT "
        "would fire PROVEN -- the SLOPE_OK clause is the live "
        "boundary, exactly where rounds 298-300 kept digging")

    # ---- V3 the r298 sealed bar (exact decision logic)
    R8 = _R298
    verd8 = _bar_r298(R8["main_dec"], R8["sf_dec"], R8["share"],
                      R8["sl_T"], R8["sl_main"], R8)
    ok_v3 = (verd8 == "TRANSFER_DOMINANT"
             and R8["sf_dec"] - R8["main_dec"] == _Fr(194, 100))
    chk("V3-r298-verdict-bar", ok_v3,
        "MAIN med -3.94 dec sits 1.94 decades BELOW S_F med -2.00 "
        "(EMPTY, not huge: med(MAIN/S_F) << 10, not UNSTABLE); "
        "share 0.99 >= 0.5 and sl_|T| -0.698 > sl_MAIN -1.386 -> "
        "not SUBDOMINANT -> TRANSFER_DOMINANT: S_F ~ B(PDelta,"
        "PDelta), the vdC input IS the Delta Fejer energy")
    m_uns = _bar_r298(_Fr(-1, 1), R8["sf_dec"], R8["share"],
                      R8["sl_T"], R8["sl_main"], R8)
    m_sub = _bar_r298(R8["main_dec"], R8["sf_dec"], _Fr(4, 10),
                      _Fr(-150, 100), R8["sl_main"], R8)
    ok_v3m = (m_uns == "DECOMPOSITION_UNSTABLE"
              and m_sub == "TRANSFER_SUBDOMINANT")
    chk("V3m-r298-tipping-mutants", ok_v3m,
        "MAIN one decade ABOVE S_F -> UNSTABLE (the r259/r261 "
        "pattern the round explicitly did NOT find); share 0.40 "
        "with fast-falling T -> SUBDOMINANT -- both sealed "
        "boundaries have teeth")

    # ---- V4 the r299 sealed bar (exact decision logic)
    R9 = _R299
    band9, fires9, verd9 = _bar_r299(
        R9["low"], R9["sl_pos"], R9["sl_mass"], R9["sl_D"],
        R9["ratio_slope"], R9["ov"], R9["xa"], _R297["sigma_star"],
        R9)
    ok_v4 = (band9 == "LOWPASS" and fires9 == (False, True, True)
             and verd9 == "DECAY_SPLIT"
             and R9["sl_pos"] + R9["sl_mass"] == R9["composed"]
             and _R297["sigma_star"] - R9["sl_D"] == _Fr(55, 1000))
    chk("V4-r299-verdict-bar", ok_v4,
        "band LOWPASS (0.93 >= 0.75); B1 composed = 1.504 + 0.444 "
        "= +1.948 EXACT, fails sigma* LOUD (the ET/Abel magnitude "
        "wall); B2_OK (sl_D -0.571 <= -0.516, margin 0.055 EXACT; "
        "ratio slope -0.168 <= +0.05) and B3_OK (OV_DOM 1.00/0.00,"
        " full-support overlap 42/42) -> DECAY_SPLIT with the "
        "frozen rest pair DIAG_TARGET + ratio flatness")
    _, f9m, v9m = _bar_r299(R9["low"], R9["sl_pos"], R9["sl_mass"],
                            _Fr(-50, 100), _Fr(6, 100),
                            _Fr(60, 100), _Fr(60, 100),
                            _R297["sigma_star"], R9)
    ok_v4m = (f9m == (False, False, False)
              and v9m == "DECAY_STILL_EMPIRICAL")
    chk("V4m-r299-tipping-mutants", ok_v4m,
        "sl_D at -0.50 (> sigma*) + growing ratio + MIXED overlap "
        "-> every route dies -> DECAY_STILL_EMPIRICAL -- the B2 "
        "margin 0.055 is exactly what keeps the lane alive")

    # ---- V5 the r300 sealed bar (exact decision logic)
    R0 = _R300
    fires0, verd0, ratio0 = _bar_r300(
        R0["b1"][0] + R0["b1"][1], R0["b2_composed"], R0["sl_neff"],
        R0["needed"], R0["dd_slope"], R0["ident_dw_breaks"],
        R0["renv_slope"], _R297["sigma_star"], R0)
    ok_v5 = (fires0 == (False, False, True) and verd0 == "DIAG_SPLIT"
             and ratio0 == "RATIO_BOUNDED_STRUCTURAL"
             and _R297["sigma_star"] - R0["b2_composed"]
             == _Fr(-170, 1000))
    chk("V5-r300-verdict-bar", ok_v5,
        "B1 -0.384 and B2 -0.346 both FAIL sigma* -0.516 (B2 miss "
        "0.170 EXACT; the fill decay -0.225 is the invisible "
        "part); B3 fires (sl_neff +0.963 >= +0.908, D_rank(Delta) "
        "-0.117 falling) -> DIAG_SPLIT(B3/NEFF_TARGET); the |dw| "
        "census BREAKS so DERIVED is unreachable; slope(R_env) "
        "-0.122 <= +0.05 -> RATIO_BOUNDED_STRUCTURAL: the ratio "
        "half of the r299 rest pair is settled structurally")
    f0a, v0a, _ = _bar_r300(R0["b1"][0] + R0["b1"][1],
                            R0["b2_composed"], _Fr(900, 1000),
                            R0["needed"], R0["dd_slope"], True,
                            R0["renv_slope"], _R297["sigma_star"],
                            R0)
    _, _, r0b = _bar_r300(R0["b1"][0] + R0["b1"][1],
                          R0["b2_composed"], R0["sl_neff"],
                          R0["needed"], R0["dd_slope"], True,
                          _Fr(6, 100), _R297["sigma_star"], R0)
    ok_v5m = (f0a == (False, False, False)
              and v0a == "DIAG_STILL_EMPIRICAL"
              and r0b == "RATIO_EMPIRICAL")
    chk("V5m-r300-tipping-mutants", ok_v5m,
        "sl_neff at +0.900 (< +0.908 need) kills B3 -> "
        "DIAG_STILL_EMPIRICAL; a growing envelope (+0.06) -> "
        "RATIO_EMPIRICAL -- the 0.055 margin and the falling "
        "R_env are exactly the two live clauses")

    # ---- V6 the chain composition (the wave-9 statement)
    sl_D_from_neff = 2 * R0["sl_L1"] - R0["sl_neff"]
    # the delta' link uses the ALGEBRAIC sigma* (T1): the printed
    # record level -0.516 is rounded from the unrounded ladder
    # slopes (disclosed r297), the composition identity is exact
    delta_at_target = _compose_delta(
        _R297["sl_c2"], _R297["sl_pref"],
        _sigma_star(_R297["sl_c2"], _R297["sl_pref"], _Fr(21, 100)))
    ok_v6 = (R0["sl_neff"] >= R0["needed"]                # NEFF (measured)
             and sl_D_from_neff <= _R297["sigma_star"]    # => DIAG
             and ratio0 == "RATIO_BOUNDED_STRUCTURAL"     # ratio half
             and _R297["sigma"] <= _R297["sigma_star"]    # => target
             and delta_at_target == _Fr(21, 100))         # => delta'
    chk("V6-chain-composition", ok_v6,
        "THE REDUCTION DIAGRAM instantiated on the records: "
        "[NEFF_TARGET slope(n_eff) >= +0.908, measured +0.963, "
        "margin 0.055 -- THE ONE OPEN INEQUALITY, r301 in flight, "
        "not consumed] ==> sl_D <= sigma* (exact participation "
        "algebra, T3) ==> with RATIO_BOUNDED_STRUCTURAL sigma <= "
        "sigma* ==> the r297 target inequality (measured margin "
        "0.198) ==> the v964-S0 vdC theorem ==> delta' = 0.21 + "
        "margin > 0.21 on the generic half (T1 composition exact; "
        "exceptions 6 via r287 F2 + kz15 exact-finite via r270) "
        "-- NO link is claimed proved beyond its typed status")

    print("\n  S0 complete: %d exact/logic gates" % len(gates),
        flush=True)


# ---------------------------------------------------------- embedded
# ---------------------------------------------------------- probes
_SRC_0 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""dens_identity_probe -- PRIME.PORT.LSTAR.DENS_IDENTITY.01
(round 296): IS THE 92.5-PERCENT DENS TOP AXIS MATHEMATICALLY
IDENTIFIABLE AND COUPLED TO THE L* EXTREMIZER?  The curvature
arc (r290-r295, wave 8 = v965) sealed: the margin Hesse form at
MAIN is RANK-1-dominated in the L2 spectral metric (92.5 pct of
sum|lam| in ONE eigendirection e_top, lam_top -0.418), the top
axis is a pure DENS combination (DENS05 +1.00 / DENS04 -0.71 /
DENS03 +0.69 / DENS01 +0.53), NOT the SMOOTH axis (|cos| 0.07)
and NOT the ridge; the mechanism is window-constant (r294 DENS
shares w7/w9/w11 = 0.795/0.989/0.834); EPSTEIN has NO curvature
structure (first- and second-order structureless, ratio
5.4e-15).  THE ONE QUESTION OF THIS ROUND (hard fork, reviewer
contract): identify the OBJECT -- no new survival predictors,
no functional lottery.  The main comparison partner T1 is the
profile-space direction the L* margin is most sensitive to:
grad_delta lambda_max(E_{N_w}) via Hellmann-Feynman from the
extremal eigenvector phi* (with int p*^2 dmu = 1 the envelope
theorem gives dlam = int p*^2 d(dnu) - lam int p*^2 d(dmu); the
exact fold map pulls this back to the signed-density grid with
the s_l = 4 sin^2(pi l / L) / (2 L) envelope).  NOT a proof
round: no L* claim, no bound mechanism, no asymptotic law.

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

MACHINERY IMPORTED VERBATIM (no duplication): r292 CF.{unit_dir,
pol_of_d2, expand_of_d2, proj_coords, rich_devs} + the sealed
r292 constants (HESS_EQ_HS, H_PAIR_H, GCUT, D2_FLOOR, POL_TOL,
seeds 292100+/292200+, N_ATOM); r291 RA.{subset_move, atom_ints,
AMP_PAD}; r290 PFP.{measure_density, dir_frac, dir_dens, lag_of,
interp_density, NEAR, DEAD}; r284 LS.{split_by_fold, atom_labels,
christoffel_rows}; r283 FS.{mu_chain_f64, b_matrix_f64}; r280
BL.{grad_ext, dir_opt, theta_of_dir, union_of_ctx,
sign_chain_f64}; r278 MS.ctx_build; r276 MF.{local_gaps,
pert_jit, conserve_comb}; v881 PIK.{build_rung, grid_density,
folded_measure, lambda_eps}; r243 PB.smooth_comb; paircorr
PC.{Grid, gen_model}; v563 core READ-ONLY.  The r294 window
protocol (12-direction window-own Hessian, seeds 294700 + 50 wi,
extraction dose cap, ladder halving max 3) is rebuilt VERBATIM
for the window-own e_top at w7/w11.

INDEX FIREWALL (binding, r238-r295 discipline): ground truth
(minC, crossings, margins) enters GATES and the measurement
channels (the Hesse forms -- disclosed measurement-consuming as
in r292/r294) only; the sealed source-pure constructors consume
densities / combs / grid geometry / kernel degrees / seeds ONLY
(AST scope audit); no zero/prime oracles anywhere (AST firewall;
atom classes via the r254/r284 world-blind tent matching +
integer root extraction inside LS.atom_labels).

METRIC DISCLOSURE (design-time, sealed BEFORE any evaluation):
e_top exists ONLY inside the 29-direction span D (it is an
eigenvector of the span-restricted form); the sealed PRIMARY
identity metric is therefore the IN-SPAN cosine
cos(e_top, P_D T) with P_D the exact Euclidean L2 projector onto
span(D) (r292 proj_coords, eigencut pseudo-solve, no fitting).
The raw grid cosine cos(e_top, T), the span capture
|P_D T|_2 / |T|_2 and the LAG-coordinate cosine (the L2 angle in
the r289/r290 lag coordinate where theta_eq lives; theta_eq
itself is an L1 object with no inner product, r292 disclosure)
are reported as honesty columns for EVERY candidate.  The noise
reference (T6) passes through the IDENTICAL pipeline.

LEG 0 -- ANCHOR REGRESSION (all gated): w9 record (S 367/263/
104, minC 184, crossing 185, margin 1.68e-4 rel 0.01, z_v
-3.149 tol 0.02, b34 -0.105 tol 0.01); theta_eq metric (REF
125.75 rel 1e-3, inversion 1e-12, pinned quadruple devs <=
0.15); control flips EPST/SCR/SMOOTH/HL2 = 25/21/27/25; r280
ridge anchor (theta_up 3.87e-5 rel 0.05, endpoint minC 185,
top-9 atoms == r291); THE L* SPECTRAL ANCHOR (r284/r286):
lambda_max(E_184) = 0.99983248 (abs tol 1e-6), top-5 eigs ==
r283 records (tol 1e-4), margin == 1 - lambda_max identity,
crossing 185 == minC + 1; EPSTEIN first-order flatness (|c_25|
<= 1e-9, theta_up >= 1e9); r292 EIGEN-ANCHOR on the verbatim
rebuilt 29-direction Hessian: trace share 0.925 tol 0.01,
lam_top -0.418 rel 0.02, SMOOTH |cos| 0.07 tol 0.03, ridge
L2-diagonal rank 28/29, top-4 loadings == (DENS05 +1.00, DENS04
-0.71, DENS03 +0.69, DENS01 +0.53) tol 0.05 after sign
canonicalization (DENS05 loading positive); the 29-direction
DENS coefficient share is reported as a MEASUREMENT (a3: the
published r294 0.989 is the share of the 18-direction TRAINING
form (H_tr, G_tr) -- a different object; no record exists for
the 29-direction share, so it carries no gate).

LEG A -- THE CANDIDATE LIBRARY (sealed BEFORE any measurement;
every member built by the ONE source-pure constructor
build_candidate, same eta_0 conservation projection, same L2
normalization; weight-coordinate members pulled back to density
space through the adjoint of the exact fold map = the s_l
envelope, the SAME map that carries grad lambda):
  T1 GRAD_LMAX (the main test): grad_delta lambda_max(E_184)
    via Hellmann-Feynman from phi* (formula above); WARD:
    finite-difference crosscheck on 6 sealed coordinates (per
    channel the 3 even grid-pair moves with the LARGEST
    analytic directional derivative -- a2: the ward verifies
    the formula where the FD signal is resolvable; the
    tiny-gradient folds sit at the f64 eigensolver noise floor
    ~1e-14, disclosed -- with the resolvability floor
    |g| t >= 1e-9; Richardson pair t, t/2 at t = 1.25e-6 max|d|
    -- a2 step fix: the hull-edge folds carry margin curvature
    so large that the first-drawn 1e-5 scale left an O(t^4)
    Richardson residual of 2e-3; the pure-truncation O(t^2)
    convergence was measured over a 5-step ladder and the pair
    re-anchored at the measured margin-valid scale, the exact
    r292-a1 pattern), rel dev <= 1e-4 on every coordinate.
    T1B/T1C: the gradients of the 2nd/3rd top eigenvalues
    (same formula, phi_2/phi_3) as CONTROL directions --
    excluded from the identity award, disclosed.
  T2 LAMBDA FAMILY (von Mangoldt on the support): Lambda(n) =
    log p at every union fold whose tent match carries an
    integer n = p^k (LS.atom_labels classes K1/KHI); PRIME-only
    (k = 1); PRIME-POWER-only (k >= 2).
  T3 LOCAL METRIC FAMILY: local fold-gap deviations (nearest
    union-neighbor distance minus mean); logarithmic density
    1/(f D) per fold; the r289 fraction profile (signed sub-cell
    offset u_match/D - f of the tent-matched comb atom).
  T4 KERNEL DIAGONALS at the nu atoms (degree N_w, r284
    construction): the Christoffel function v_k / diag_k, the
    E-kernel diagonal diag_k = v_k K_n(y_k), the CD-kernel
    diagonal K_n(y_k).
  T5 MOMENT GRADIENTS: grad_delta of the first 4 moments of
    mutilde (dd_l = s_l x_f^j on the support, j = 1..4),
    entering as a SUBSPACE via the projection share
    |P_T5 e_top|^2 (chance level of a 4-dim subspace disclosed
    via two pinned null quadruples).
  T6 NULL CONTROLS: 8 conservation-gated random on-support
    density directions (seeds 296100+, r290 dir_dens class)
    through the identical cosine pipeline; their MAX |cos| is
    the honest noise reference; one pinned DECOY (seed 296199)
    is smuggled through the candidate pipeline as must-fail m4.

LEG B -- THE IDENTITY TEST (the one question): for every
candidate the in-span |cos| (PRIMARY), the raw and the lag
cosines and the span capture.  SEALED BARS (in the code BEFORE
any cosine evaluation): |cos| >= 0.80 for T1 or a T2/T3/T4
member => DENS_ARITHMETIC_IDENTITY(member, cos); 0.40 <=
max|cos| < 0.80 over the eligible library (incl. the T5 root
share) => DENS_PARTIAL(member, cos); max|cos| < 0.40 AND below
the noise reference + 0.1 => DENS_WORLD_BLIND (below 0.40 but
above noise + 0.1 stays DENS_WORLD_BLIND with the above-noise
flag disclosed).  The T1 value is ALWAYS reported separately:
cos(e_top, grad lambda_max) is the COUPLING NUMBER of the round.

LEG C -- WORLD AND WINDOW HARDENING (identity discipline):
  (c1) WORLD CONTRAST at EPST and SCR: no structured e_top
    exists there by r292; measured instead: the world-own top
    curvature direction inside a 12-direction DENS span (seeds
    296300+/296350+, world-own margin channel 1 - rho_{minC_c}
    at the world's OWN wall degree, r292 ladder with the r294
    halving rule max 3), against the SAME candidate
    construction built world-own.  SEALED COLLAPSE RULE: the
    control match collapses iff the control top diagonal fails
    the Richardson stability (devs > 0.1 -- no structured axis,
    the r292 EPSTEIN expectation) OR |cos_c| < 0.40.  A
    non-collapsing control => the match is construction-trivial
    => DOWNGRADE one level (disclosed).  a4: the repetition
    rebuilds the ACTUAL best member world-own -- single
    directions via the one sealed constructor, the T5 subspace
    via the world-own moment-gradient span root share (null
    reference then = the two null-quadruple roots).
  (c2) WINDOW TRANSPORT at w7 and w11 (r294 protocol verbatim:
    window-own wall NREF_w 59/63, 12-direction window Hessian,
    seeds 294700 + 50 wi, dose cap, ladder halving; DENS share
    regression 0.795/0.834 tol 0.05): window-own e_top vs the
    window-own best-candidate construction (kernel degree
    NREF_w), in-span cosine in the window span (T5 via the a4
    subspace rule), window nulls seeds 296700 + 50 wi; the T1
    coupling is measured per window ALWAYS.  SEALED BAR: the
    verdict class holds in >= 2 of 3 windows (w9 + w7 + w11;
    the w9 entry is the adjudicated BASE class), else DOWNGRADE
    one level (disclosed).  No hardening applies to a BLIND
    base.

LEG D -- THE BRIDGE TABLE (only on IDENTITY/PARTIAL, small,
measurement only): if T1 is the best match, the decomposition
of grad lambda_max inside the arithmetic library (raw cosines
T1 vs every T2/T3/T4 member + the T5 share of T1) -- ONE table,
no interpretation.  If a T2/T3/T4 member matches but T1 does
NOT (|cos_T1| < 0.40 while best >= 0.40): THE ANOMALY -- DENS
would be arithmetic but NOT L*-coupled; documented prominently.

LEG E -- MUST-FAILS (each loud): (m1) Hellmann-Feynman with
the WRONG normalization factor (nu weight dropped from
p*(y_k)^2 = lam phi_k^2 / v_k) must be CAUGHT by the FD ward
(rel dev >> 1e-4) on a sealed nu coordinate; (m2) a candidate
built WITHOUT the eta_0 conservation projection must be CAUGHT
by the exact conservation gate; (m3) SEAL BREAK simulated: a
candidate added AFTER the cosine evaluation changes the sealed
library hash -- CAUGHT by the hash auditor; (m4) the pinned
random DECOY smuggled through the candidate pipeline must stay
at or below the noise reference + 0.1 (must NOT fire the
identity).  Scope audits: the sealed constructors consume
densities/combs/geometry/degrees/seeds ONLY; fragment audit (no
fit primitives).  STOP LIST (anti-gates, binding): NO L* claim,
NO bound mechanism, NO asymptotic law, NO derived 5/7, NO new
survival predictor, NO posthoc candidate, NO RH claim;
r243..r295 stand.

SEALED CONSTANTS: MAIN window 9; N_REF 184; CROSS_REC 185;
MINC_REC 184; S_REC (367, 263, 104); MARGIN_REC 1.68e-4 rel
0.01; ZV_REC -3.149 tol 0.02; B34_REC -0.105 tol 0.01;
CTRL_FLIPS EPST 25 / SCR 21 / SMOOTH 27 / HL2 25 (seed 101);
THUP_REC 3.87e-5 rel 0.05; RIDGE_MINC_REC 185; REF_REC 125.75
rel 1e-3; pinned metric quadruple (seeds 290000/1/2 at 1e-3 +
290010 at 3e-4, tol 0.15); LAM184_REC 0.99983248 abs 1e-6;
R283_TOP5 (0.99983, 0.99874, 0.99597, 0.98461, 0.96408) tol
1e-4; EPST_C_BAR 1e-9 / EPST_THUP_MIN 1e9; r292 REBUILD ==
(HESS_EQ_HS, H_PAIR_H, GCUT, seeds 292100+/292200+, 29
directions) VERBATIM with SHARE_REC 0.925 tol 0.01 / LAMTOP_REC
-0.418 rel 0.02 / COS_SM_REC 0.07 tol 0.03 / RIDGE_RANK 28 /
LOADINGS (DENS05 +1.00, DENS04 -0.71, DENS03 +0.69, DENS01
+0.53) tol 0.05 (29-dir DENS share typed MEASUREMENT, a3); T1
FD ward: 6 coordinates (per channel the 3 largest |analytic
pair derivative|, a2), FD_T 1.25e-6 x max|d| (a2 step fix),
FD_MIN 1e-9 resolvability floor, Richardson pair (t, t/2),
FD_BAR 1e-4; MOM_K 4; NULLS 8 seeds
296100+ / DECOY 296199; COS_ID 0.80 / COS_PART 0.40 / NULL_PAD
0.10 (noise reference = max of the 8 nulls, disclosed
conservative q95 estimator at n = 8); CONTROLS EPST/SCR: 12
DENS directions seeds 296300+/296350+, nulls 8 seeds
296500+/296550+, world-own REF_c, r292 ladder + halving max 3,
RICH_TOL 0.1; WINDOWS (7, 11): r294 constants VERBATIM (W_SEED
294700 + 50 wi, N_ATOM_W 4 / N_FRAC_W 4 / N_DENS_W 3, dose cap
f_ex = min(1, 1e-3 / (2 theta_up_w)), ladder halving max 3,
W_EXT 8/32), NREF_REC {7: 59, 11: 63}, crossing NREF + 1, DENS
SHARE REC {7: 0.795, 11: 0.834} tol 0.05, window nulls 8 seeds
296700 + 50 wi; WINDOW CLASS RULE >= 2 of 3; runtime <= 1800 s;
smoke = toys + firewall + scopes + w9 regression + m1(toy)/m3
mutants (anchors, legs, adjudications skipped).
PRE-SPEC SCOPING (disclosed): every record number is a
published r280/r283/r284/r286/r290/r291/r292/r294 record
adopted as-is; the candidate library with its constructions,
the in-span primary metric with its honesty columns, the bars,
the noise rule, the collapse and window rules, the downgrade
logic and the must-fail set were fixed at design time from the
published records and the reviewer contract BEFORE any cosine
evaluation; the library hash is sealed in S0; no candidate is
added or removed after the first evaluation; no bar, band or
rule was tuned after the record freeze.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  [exactly one of] DENS_ARITHMETIC_IDENTITY(member, cos) /
    DENS_PARTIAL(member, cos) / DENS_WORLD_BLIND(best, cos,
    noise) -- after the disclosed hardening downgrades
  + T1_COUPLING(cos_span, raw, lag, capture) [always]
  + COS_TABLE(all candidates, all four columns, noise
    reference) [always]
  + WORLD_CONTRAST(EPST/SCR collapse verdicts) [always]
  + WINDOW_TRANSPORT(w7/w9/w11 classes, DENS shares) [always]
  + BRIDGE_TABLE(...) [on IDENTITY/PARTIAL only] /
    ANOMALY(...) [if arithmetic-but-not-T1].
Honesty before beauty: cosines, captures, shares and the
control/window contrasts are MEASUREMENTS on finite profile
spaces; the Hesse forms consume measured margins (disclosed, as
in r292/r294); e_top is span-limited and the in-span metric is
the sealed primary reading of exactly that limitation; a
passing identity is a FINITE-WINDOW alignment statement about
w7/w9/w11, not a mechanism theorem; no verdict claims L*, a
bound mechanism, a derived 5/7 or an asymptotic law.

RECORD TABLES (frozen from the record run; calibration
protocol, chronology honest: smoke pass 1 = 11/12 exposing a1;
smoke pass 2 = 12/12 (0.2 s); calibration pass 1 = first full
evaluation = 36/39, wall 80 s, exposing a2 (coordinate rule) +
a3 + a4 (below); calibration pass 2 = 37/39, wall 81 s,
exposing the a2 STEP fix (the hull-edge margin curvature
leaves a 2e-3 Richardson residual at the first-drawn 1e-5
scale; the pure O(t^2) truncation convergence was measured on
a 5-step ladder and the pair re-anchored at 1.25e-6 max|d|);
calibration pass 3 = 39/39, wall 81 s = the record physics;
one display-only wording fix in the G70 message before the
record freeze (no number, bar or rule changed); record
run1/run2 = 39/39, byte-identical up to WALL.  DISCLOSED
CALIBRATION AMENDMENTS (all found and fixed BEFORE the record
freeze; no physics bar, library member, sealed seed or verdict
rule moved): (a1) the library evenness gate was drawn at exact
zero while the s_l envelope is even only to libm precision
(~1e-17 at mirrored sin arguments) -- re-drawn at 1e-12
relative (gate conditioning); (a2) the FD ward coordinates
were first drawn as the largest-|d| grid pairs, whose
gradients sit at the f64 eigensolver noise floor (measured
devs up to 0.39 at |g| ~ 1e-10) -- re-drawn as the per-channel
largest |analytic pair derivative| with the 1e-9 resolvability
floor, plus the step fix above (both measurement-domain, the
r292-a1 pattern); (a3) the G33 gate cited the r294 0.989 DENS
share, which is the share of the 18-direction TRAINING form
(H_tr, G_tr) -- a different object from the 29-direction share
(measured 0.935, no published record): the clause was removed
and the value typed MEASUREMENT; (a4) the hardening repetition
was first coded to substitute T1 for the subspace member --
re-drawn to repeat the ACTUAL best member (T5 via world/window-
own moment-span root share, null reference = null-quadruple
roots) and the w9 window-class entry pinned to the adjudicated
base class.  AMENDMENTS AFTER FREEZE: NONE (the record-table
insertion below is the only post-freeze edit, which IS the
protocol).
RECORD VERDICT = DENS_WORLD_BLIND(T5_MOMENTS 0.825 downgraded;
WORLD-DOWNGRADE) + T1_COUPLING(cos_span +0.394, raw +0.048,
lag +0.394, capture 0.123) + COS_TABLE(T1 0.394; T2 -0.095 /
+0.002 / +0.130; T3 0.000 / -0.320 / +0.006; T4 +0.183 /
+0.002 / +0.378; noise 0.331; T5 root 0.825) + WORLD_CONTRAST(
EPST HELD 0.571, SCR HELD 0.603) + WINDOW_TRANSPORT(w7 ID /
w9 PART / w11 ID, 3/3 hold; DENS shares 0.795 / 0.935 / 0.834).
Key numbers.  ANCHORS: w9 S 367/263/104, minC 184, crossing
185, margin 1.6752e-4, z_v -3.149, b34 -0.105; REF 125.7462,
quadruple devs (0.059, 0.125, 0.117, 0.028); flips 25/21/27/25;
theta_up 3.8733e-5, endpoint 185, top9 == r291;
lambda_max(E_184) = 0.99983248 (dev 4.1e-9), top-5 == r283
(max dev 4.9e-6), margin identity 1.1e-15, crossing == minC+1;
EPST c_25 -1.99e-11, theta_up 5.03e10.  R292 REBUILD: share
0.9249, lam_top -0.4183, SMOOTH |cos| 0.0737, ridge rank
28/29, loadings DENS05 +1.00 / DENS04 -0.71 / DENS03 +0.69 /
DENS01 +0.53; polarization crosscheck worst 0.018.  T1 WARD:
worst rel dev 3.8e-7 <= 1e-4 on the 6 sealed coordinates
(folds 1/3/5 mu + 2/4/6 nu -- the gradient lives at the
SHALLOW-u HULL EDGE, exactly the r284 extremal-anatomy
region), lam identity exact.  COS TABLE (span/raw/lag/
capture): T1 +0.394/+0.048/+0.394/0.123; T2_ALL -0.095/-0.029/
-0.095/0.306, T2_PRIME +0.002/.../0.241, T2_PP +0.130/.../
0.346; T3_LOCALGAP +0.000 (capture 0.000: the gap profile is
CONSTANT 1 on the 367/368-occupied fold grid and dies in the
eta_0 projection -- an honest degenerate member, disclosed),
T3_LOGDENS -0.320/-0.034/-0.319/0.105, T3_FRAC289 +0.006;
T4_CHR +0.183, T4_EDIAG +0.002, T4_CDDIAG +0.378/0.145;
CONTROL rows: grad lam2 +0.366, grad lam3 -0.574 (the 3rd
eigen-gradient couples HARDER than the top -- the coupling is
a near-crossing BAND property, not top-specific, honest);
T5_MOMENTS root share 0.825 (share 0.680) vs null-quadruple
roots 0.437 / 0.350; T6 nulls 0.056..0.331 (max 0.331), decoy
0.115.  HARDENING: EPST (wall 25, margin 2.08e-3) top-diag
Richardson devs <= 5e-5 STABLE -- the EPST MARGIN channel at
its own wall degree carries real curvature structure (r292's
flatness was the log-h channel at degree 184, a different
object, disclosed); T5-at-EPST 0.571 / SCR 0.603 both >= 0.40
=> NOT COLLAPSED => the sealed WORLD-DOWNGRADE fires (PART ->
BLIND); DISCLOSED TENSION: the control values sit BELOW their
own null-quadruple maxima (0.758 / 0.691) -- for a 4-dim
subspace inside a 12-dim span the absolute 0.40 collapse bar
is nearly unreachable by construction, so the downgrade is
CONSERVATIVE (the sealed rule stands, the tension is the
disclosure); windows w7/w11: NREF 59/64 crossing NREF+1, DENS
shares 0.795/0.834 == r294, T5_w 0.930/0.942 vs window null
maxima 0.923/0.734, T1_w 0.179/0.314 (below window noise);
window classes ID/ID, 3/3 hold, no window downgrade.
MUST-FAILS: m1 CAUGHT (rel 1.0 >> 1e-4), m2 CAUGHT (eta_0 rel
1.0), m3 CAUGHT (hash mismatch), m4 HELD (0.115 <= 0.431);
scopes + fragments CLEAN.  Runtime 81 s full / 0.2 s smoke;
run1/run2 identical up to WALL.
READING (typed MEASUREMENT): the reviewer fork lands on
DENS_WORLD_BLIND under the sealed rules -- the 92.5-pct DENS
top axis is NOT identifiable with any member of the sealed
arithmetic library: every T2/T3/T4 candidate stays under 0.4
(von Mangoldt families <= 0.13, 1/log 0.32, kernel diagonals
<= 0.38, all within reach of the 0.331 noise reference), and
THE COUPLING NUMBER cos(e_top, grad lambda_max) = +0.394 sits
BELOW the sealed 0.40 bar (above the noise max 0.331, below
noise + pad 0.431): the DENS axis is NOT (at w9, in-span) the
direction that controls the L* extremizer -- and the lam2/lam3
control rows (+0.37 / -0.57) show what coupling there is
spreads over the near-crossing eigenvalue BAND rather than
picking the top eigenvalue; the only above-chance structure is
the 4-dim MOMENT-GRADIENT subspace (root share 0.825 at w9 vs
~0.4 chance; window-stable at 0.93/0.94 but AT the window
chance level 0.92/0.73, and present at 0.57/0.60 on both dead
controls) -- under the sealed collapse rule this is
CONSTRUCTION-ADJACENT structure (low-moment smoothness of
curvature tops is world-generic), not a MAIN identity; the
sealed rule downgrades the T5 partial to BLIND, and the
disclosed tension (the 0.40 collapse bar is conservative for
subspace members) is left standing as-is: no bar moved after
sight.  Honest negatives, explicit: T1 misses PART by 0.006 --
the fork answer is BLIND, not a near-miss celebration; the
raw-grid overlap of e_top with EVERY candidate is <= 0.08
while the in-span values reach 0.39, and every candidate's
span capture is <= 0.36: what alignment exists lives INSIDE
the 29-direction span, and the raw-grid geometry of e_top is
dominated by structure that no on-support arithmetic profile
in this library represents.
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 curvature_form_probe as CF                   # noqa: E402 r292
import ridge_anatomy_probe as RA                    # noqa: E402 r291
import profile_functional_probe as PFP              # noqa: E402 r290
import lstar_two_measure_probe as LS                # noqa: E402 r284
import fullsource_quasidefiniteness_probe as FS     # noqa: E402 r283
import metric_stability_probe as MS                 # noqa: E402 r278
import minimal_firewall_probe as MF                 # noqa: E402 r276
import budget_localization_probe as BL              # noqa: E402 r280
import port_integrable_kernel_probe as PIK          # noqa: E402 v881
import principal_bessel_probe as PB                 # noqa: E402 r243
import paircorr_margin_probe as PC                  # noqa: E402
import v563_paper2_readouts as core                 # noqa: E402 READ-ONLY

MAIN_KZ = 9
N_REF = 184
CROSS_REC = 185
MINC_REC = 184
S_REC = (367, 263, 104)
MARGIN_REC = 1.68e-4
MARGIN_TOL = 0.01
ZV_REC = -3.149
ZV_TOL = 0.02
B34_REC = -0.105
B34_TOL = 0.01
CTRL_FLIPS = {"EPST": 25, "SCR": 21, "SMOOTH": 27, "HL2": 25}
HL2_SEED = 101
THUP_REC = 3.87e-5
THUP_TOL = 0.05
RIDGE_MINC_REC = 185
REF_REC = 125.75
REF_TOL = 1e-3
CAL_SEEDS = (290000, 290001, 290002)
T3_SEED = 290010
T3_THETA = 3e-4
T3_TOL = 0.15
THETA_CAL = 1e-3
ETA0_BAR = 1e-12
R291_TOP9 = (2, 3, 5, 13, 11, 4, 29, 7, 89)
AMP_PAD = RA.AMP_PAD

# r292 verbatim (imported, not redeclared)
HESS_EQ_HS = CF.HESS_EQ_HS
H_PAIR_H = CF.H_PAIR_H
GCUT = CF.GCUT
D2_FLOOR = CF.D2_FLOOR
POL_TOL = CF.POL_TOL
RICH_TOL = CF.RICH_TOL
NDIR_FRAC = CF.NDIR_FRAC
SEED_FRAC = CF.SEED_FRAC
NDIR_DENS = CF.NDIR_DENS
SEED_DENS = CF.SEED_DENS
N_ATOM = CF.N_ATOM
NEAR = PFP.NEAR

# r292/r294 eigen-anchor records
R292_SHARE_REC = 0.925
R292_SHARE_TOL = 0.01
R292_LAMTOP_REC = -0.418
R292_LAMTOP_TOL = 0.02
R292_COS_SM_REC = 0.07
R292_COS_SM_TOL = 0.03
R292_RIDGE_RANK_REC = 28
R292_LOADINGS = (("DENS05", 1.00), ("DENS04", -0.71),
                 ("DENS03", 0.69), ("DENS01", 0.53))
R292_LOAD_TOL = 0.05
W9_DENS_SHARE_REC = 0.989
W9_DENS_SHARE_TOL = 0.02

# L* spectral anchors (r283/r284/r286 records)
LAM184_REC = 0.99983248
LAM184_TOL = 1e-6
R283_TOP5 = (0.99983, 0.99874, 0.99597, 0.98461, 0.96408)
TOP5_TOL = 1e-4
EPST_C_BAR = 1e-9
EPST_THUP_MIN = 1e9

# T1 ward
FD_NCOORD = 3            # per channel (3 mu + 3 nu)
FD_T = 1.25e-6           # x max|d| (a2 step fix), pair (t, t/2)
FD_BAR = 1e-4
FD_MIN = 1e-9            # a2 resolvability floor |g| t >= FD_MIN

# library seal
MOM_K = 4
NDIR_NULL = 8
SEED_NULL = 296100
SEED_DECOY = 296199
COS_ID = 0.80
COS_PART = 0.40
NULL_PAD = 0.10
LIB_ELIGIBLE = ("T1_GRAD_LMAX",
                "T2_LAMBDA_ALL", "T2_LAMBDA_PRIME", "T2_LAMBDA_PP",
                "T3_LOCALGAP", "T3_LOGDENS", "T3_FRAC289",
                "T4_CHRISTOFFEL", "T4_EDIAG", "T4_CDDIAG")
LIB_CONTROL = ("T1B_GRAD_LAM2", "T1C_GRAD_LAM3")
LIB_SUBSPACE = "T5_MOMENTS"
LIB_SEAL = hashlib.sha256(repr(
    (LIB_ELIGIBLE, LIB_CONTROL, LIB_SUBSPACE, MOM_K,
     NDIR_NULL, SEED_NULL, SEED_DECOY,
     COS_ID, COS_PART, NULL_PAD)).encode("utf-8")).hexdigest()

# controls (world contrast)
CTRL_WORLDS = ("EPST", "SCR")
N_DENS_CTRL = 12
SEED_CTRL = {"EPST": 296300, "SCR": 296350}
NNULL_CTRL = 8
SEED_CTRL_NULL = {"EPST": 296500, "SCR": 296550}
LADDER_MAX_HALVE = 3

# windows (r294 verbatim)
W_LIST = (7, 11)
W_SEED_BASE = 294700
W_SEED_STEP = 50
N_ATOM_W = 4
N_FRAC_W = 4
N_DENS_W = 3
W_EXT = 8
W_EXT2 = 32
W_NREF_REC = {7: 59, 11: 63}
W_DENS_SHARE_REC = {7: 0.795, 11: 0.834}
W_DENS_SHARE_TOL = 0.05
NNULL_WIN = 8
SEED_WIN_NULL = {7: 296700, 11: 296750}
WIN_CLASS_NEED = 2       # of 3 windows

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; atom classes via the "
                       "r254/r284 world-blind tent matching + integer "
                       "root extraction inside LS.atom_labels; record "
                       "numbers enter gates and record tables only"
                       if not bad else "; ".join(bad))


def antigate_fragment_audit():
    frags = ("poly" + "fit", "curve_" + "fit", "lst" + "sq",
             "mini" + "mize", "Line" + "arRegression")
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    hits = []
    for node in ast.walk(tree):
        nm = None
        if isinstance(node, ast.Attribute):
            nm = node.attr
        elif isinstance(node, ast.Name):
            nm = node.id
        elif isinstance(node, ast.FunctionDef):
            nm = node.name
        if nm and any(f in nm for f in frags):
            hits.append("%s@%d" % (nm, node.lineno))
    return hits


CONSTRUCTORS = ("kernel_pack", "grad_of_pack", "eta0_project",
                "cand_density", "fold_gaps", "frac_offsets",
                "moment_grad", "build_candidate", "cos_pair",
                "lag_cos_pair", "sub_share")
SCOPE_FORBIDDEN = {"minC", "mc", "zv", "onsets_true", "MINC_REC",
                   "CROSS_REC", "ZV_REC", "sg_h", "lgh", "s_meas",
                   "CTRL_FLIPS", "W_NREF_REC"}


def scope_audit(funcname, forbidden):
    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 forbidden:
                    hits.append("%s@%d" % (nm, sub.lineno))
    return hits


def s_env(L):
    """the exact fold-map envelope s_l = 4 sin^2(pi l / L) / (2 L)
    (grid geometry only; the per-grid-point weight sensitivity of
    the folded measure, v881 folded_measure verbatim)."""
    ll = np.arange(L)
    return 4.0 * np.sin(math.pi * ll / L) ** 2 / (2.0 * L)


# ============== sealed source-pure constructors (AST-audited)
def kernel_pack(d, L, n):
    """two-measure kernel bundle of a signed density at degree n:
    fold split (v881 folded_measure verbatim), mu chain, B =
    sqrt(v) P_i(y), Bx = sqrt(w) P_i(x), eigendecomposition of
    E_n = B B^T, cumulative Christoffel rows.  Consumes density +
    grid + degree only."""
    d = np.asarray(d, float)
    xs, ws, fp = PIK.folded_measure(d, L, +1.0)
    ys, vs, fn = PIK.folded_measure(d, L, -1.0)
    al, sb, h0 = FS.mu_chain_f64(xs, ws, int(n))
    B = FS.b_matrix_f64(al, sb, h0, ys, vs, int(n))
    Bx = FS.b_matrix_f64(al, sb, h0, xs, ws, int(n))
    ev, V = np.linalg.eigh(B @ B.T)
    cum = LS.christoffel_rows(B)
    return dict(xs=xs, ws=ws, fp=fp, ys=ys, vs=vs, fn=fn,
                n=int(n), B=B, Bx=Bx, ev=ev, V=V, cum=cum)


def grad_of_pack(pk, d, L, kth=1):
    """Hellmann-Feynman gradient of the kth-from-top eigenvalue
    of E_n in signed-density space: with the extremal polynomial
    p* normalized int p*^2 dmu = 1 the envelope theorem gives
    dlam = int p*^2 d(dnu) - lam int p*^2 d(dmu); the fold map
    contributes the s_l envelope per grid point (mu points carry
    -lam s_l p*(x)^2, nu points -s_l p*(y)^2).  Consumes the
    kernel pack + density + grid only."""
    lam = float(pk["ev"][-kth])
    phi = pk["V"][:, -kth]
    c = pk["B"].T @ phi
    chat = c / math.sqrt(max(float(c @ c), 1e-300))
    pmu = (pk["Bx"] @ chat) ** 2 / pk["ws"]
    pnu = lam * phi * phi / pk["vs"]
    sl = s_env(L)
    fold = np.minimum(np.arange(L), L - np.arange(L))
    imu = {int(f): i for i, f in enumerate(pk["fp"])}
    inu = {int(f): i for i, f in enumerate(pk["fn"])}
    d = np.asarray(d, float)
    G = np.zeros(L)
    for l in range(L):
        f = int(fold[l])
        if d[l] > 0.0 and f in imu:
            G[l] = -lam * sl[l] * pmu[imu[f]]
        elif d[l] < 0.0 and f in inu:
            G[l] = -sl[l] * pnu[inu[f]]
    return G, lam


def eta0_project(dd, L):
    """exact eta_0 conservation projection on the own support
    (r290 dir_dens convention): the s_l component is removed so
    that sum dd_l s_l == 0 exactly."""
    dd = np.asarray(dd, float).copy()
    sl = s_env(L)
    supp = dd != 0.0
    if not np.any(supp):
        return dd
    coef = float(np.sum(dd * sl)) \
        / max(float(np.sum(sl[supp] ** 2)), 1e-300)
    dd[supp] -= coef * sl[supp]
    return dd


def cand_density(folds, vals, L):
    """weight-coordinate candidate pulled back to signed-density
    space through the ADJOINT of the exact fold map (value at
    fold f enters grid points l = f and L - f with the s_l
    envelope -- the same map that carries grad lambda), then
    eta_0-projected exactly.  Consumes folds + values + grid."""
    dd = np.zeros(L)
    sl = s_env(L)
    for f, v in zip(np.asarray(folds, np.int64), vals):
        l1 = int(f)
        l2 = (L - l1) % L
        dd[l1] = float(v) * sl[l1]
        if l2 != l1:
            dd[l2] = float(v) * sl[l2]
    return eta0_project(dd, L)


def fold_gaps(folds):
    """local fold-gap per union fold: distance to the nearest
    other union fold (fold-index units)."""
    fr = np.asarray(folds, np.int64)
    fs = np.sort(fr)
    out = np.zeros(len(fr), float)
    for i, f in enumerate(fr):
        j = int(np.searchsorted(fs, f))
        cand = []
        if j > 0:
            cand.append(int(f - fs[j - 1]))
        if j + 1 < len(fs):
            cand.append(int(fs[j + 1] - f))
        out[i] = float(min(cand)) if cand else 0.0
    return out


def frac_offsets(folds, D, uu, mm):
    """the r289 fraction profile: signed sub-cell offset
    u_match / D - f of the best tent-matched comb atom per union
    fold (r284 atom_labels matching rule; 0 if unmatched)."""
    order = np.argsort(uu)
    uus = np.asarray(uu, float)[order]
    mms = np.asarray(mm, float)[order]
    out = []
    for f in np.asarray(folds, np.int64):
        si = float(f) * D
        lo = int(np.searchsorted(uus, si - D, side="right"))
        hi = int(np.searchsorted(uus, si + D, side="left"))
        best_w, best_u = -1.0, None
        for t in range(lo, hi):
            vt = 1.0 - abs(si - uus[t]) / D
            if vt > 0.0 and abs(mms[t]) * vt > best_w:
                best_w, best_u = abs(mms[t]) * vt, float(uus[t])
        out.append(0.0 if best_u is None
                   else (best_u / D - float(f)))
    return np.asarray(out, float)


def moment_grad(d0, L, j):
    """grad_delta of the j-th moment of mutilde in signed-density
    space: dd_l = s_l x_{fold(l)}^j on the support of d0,
    eta_0-projected (j = 0 is exactly the projected-out
    direction and excluded)."""
    d0 = np.asarray(d0, float)
    sl = s_env(L)
    fold = np.minimum(np.arange(L), L - np.arange(L))
    x = np.cos(2.0 * math.pi * fold / float(L))
    dd = np.where(d0 != 0.0, sl * x ** int(j), 0.0)
    return eta0_project(dd, L)


def build_candidate(name, d, L, D, uu, mm, n):
    """the ONE sealed candidate constructor (identical at MAIN,
    controls and windows): returns the eta_0-projected signed-
    density direction of the named library member.  Consumes the
    density, grid geometry, the comb and the kernel degree only."""
    d = np.asarray(d, float)
    fp, wp, fn, vn, xp, yn = LS.split_by_fold(d, L)
    if name.startswith("T1"):
        kth = {"T1_GRAD_LMAX": 1, "T1B_GRAD_LAM2": 2,
               "T1C_GRAD_LAM3": 3}[name]
        pk = kernel_pack(d, L, n)
        G, _lam = grad_of_pack(pk, d, L, kth)
        return eta0_project(G, L)
    folds_u = np.concatenate([np.asarray(fp, np.int64),
                              np.asarray(fn, np.int64)])
    if name.startswith("T2"):
        labs = LS.atom_labels(folds_u, D, uu, mm)
        mode = name.split("_")[-1]
        vals = []
        for cls, p, _dev in labs:
            lp = math.log(p) if (cls > 0 and p > 1) else 0.0
            if mode == "ALL":
                vals.append(lp if cls > 0 else 0.0)
            elif mode == "PRIME":
                vals.append(lp if cls == 1 else 0.0)
            else:
                vals.append(lp if cls == 2 else 0.0)
        return cand_density(folds_u, vals, L)
    if name == "T3_LOCALGAP":
        g = fold_gaps(folds_u)
        return cand_density(folds_u, g - float(np.mean(g)), L)
    if name == "T3_LOGDENS":
        vals = [1.0 / (float(f) * D) if f >= 1 else 0.0
                for f in folds_u]
        return cand_density(folds_u, vals, L)
    if name == "T3_FRAC289":
        return cand_density(folds_u,
                            frac_offsets(folds_u, D, uu, mm), L)
    pk = kernel_pack(d, L, n)
    diag = pk["cum"][:, int(n) - 1]
    vs = pk["vs"]
    if name == "T4_CHRISTOFFEL":
        vals = vs / np.maximum(diag, 1e-300)
    elif name == "T4_EDIAG":
        vals = diag
    else:                                    # T4_CDDIAG
        vals = diag / np.maximum(vs, 1e-300)
    return cand_density(np.asarray(fn, np.int64), vals, L)


def cos_pair(u, v):
    """plain L2 cosine of two grid vectors."""
    u = np.asarray(u, float)
    v = np.asarray(v, float)
    nn = float(np.linalg.norm(u)) * float(np.linalg.norm(v))
    return float(u @ v) / max(nn, 1e-300)


def lag_cos_pair(u, v, M):
    """L2 cosine in the LAG coordinate (the linear r289/r290
    completeness coordinate; theta_eq is an L1 object with no
    inner product -- this is the disclosed L2 robustness angle
    in the coordinate theta_eq lives in)."""
    lu = PFP.lag_of(np.asarray(u, float), M)
    lv = PFP.lag_of(np.asarray(v, float), M)
    return cos_pair(lu, lv)


def sub_share(W, e):
    """projection share |P_W e|^2 / |e|^2 of a vector on the
    span of the columns of W (Gram eigencut pseudo-solve, no
    fitting)."""
    W = np.asarray(W, float)
    e = np.asarray(e, float)
    G = W.T @ W
    wG, UG = np.linalg.eigh(G)
    keep = wG >= GCUT * max(float(wG[-1]), 1e-300)
    Ui = UG[:, keep]
    b = W.T @ e
    a = Ui @ ((Ui.T @ b) / wG[keep])
    Pe = W @ a
    return float(Pe @ Pe) / max(float(e @ e), 1e-300)


# ============== must-fail mutants
def mutant_hf_noweight(pk, d, L):
    """m1 MUST-FAIL: Hellmann-Feynman with the WRONG
    normalization factor -- the nu weight is dropped from
    p*(y_k)^2 = lam phi_k^2 / v_k.  The FD ward must CATCH the
    distortion loudly."""
    lam = float(pk["ev"][-1])
    phi = pk["V"][:, -1]
    sl = s_env(L)
    fold = np.minimum(np.arange(L), L - np.arange(L))
    inu = {int(f): i for i, f in enumerate(pk["fn"])}
    d = np.asarray(d, float)
    G = np.zeros(L)
    for l in range(L):
        f = int(fold[l])
        if d[l] < 0.0 and f in inu:
            G[l] = -sl[l] * lam * phi[inu[f]] ** 2   # /v_k MISSING
    return G


def mutant_unprojected_candidate(folds, vals, L):
    """m2 MUST-FAIL: the candidate pullback WITHOUT the eta_0
    projection -- the conservation gate must CATCH it."""
    dd = np.zeros(L)
    sl = s_env(L)
    for f, v in zip(np.asarray(folds, np.int64), vals):
        l1 = int(f)
        l2 = (L - l1) % L
        dd[l1] = float(v) * sl[l1]
        if l2 != l1:
            dd[l2] = float(v) * sl[l2]
    return dd


def mutant_posthoc_library():
    """m3 MUST-FAIL: a candidate added AFTER evaluation (seal
    break simulated) -- the library hash auditor must CATCH the
    mismatch."""
    broken = LIB_ELIGIBLE + ("T7_POSTHOC_BEST",)
    return hashlib.sha256(repr(
        (broken, LIB_CONTROL, LIB_SUBSPACE, MOM_K,
         NDIR_NULL, SEED_NULL, SEED_DECOY,
         COS_ID, COS_PART, NULL_PAD)).encode("utf-8")).hexdigest()


def class_of(c):
    """sealed verdict class of an absolute cosine."""
    c = abs(float(c))
    if c >= COS_ID:
        return "ID"
    if c >= COS_PART:
        return "PART"
    return "BLIND"


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

    print("=" * 78)
    print("dens_identity_probe -- PRIME.PORT.LSTAR."
          "DENS_IDENTITY.01 (round 296)")
    print("SPEC_SHA %s   (r292 CF %s / r290 PFP %s / r284 LS %s)"
          % (SPEC_SHA[:16], CF.SPEC_SHA[:16], PFP.SPEC_SHA[:16],
             LS.SPEC_SHA[:16]))
    print("mode: %s" % ("SMOKE (toys + firewall + scopes + w9 "
                        "regression + m1-toy/m3 mutants; anchors, "
                        "legs, adjudications skipped)"
                        if smoke else "FULL RECORD"))
    print("=" * 78)

    section("S0  FIREWALL + PREDEFINITION + LIBRARY SEAL")
    okf, det = firewall_audit()
    check("G01-firewall", okf, det)
    check("G02-predefinition", True,
          "sealed BEFORE evaluation: the candidate library (12 "
          "members + T5 subspace + 8 nulls + decoy) with the ONE "
          "source-pure constructor, the in-span PRIMARY metric "
          "with raw/lag/capture honesty columns, the bars 0.80/"
          "0.40 with the noise rule, the world-collapse and "
          "window-class hardening with the downgrade logic, the "
          "T1 FD ward and the must-fail set; the Hesse forms are "
          "honestly typed measurement-consuming (r292/r294 "
          "protocol); the STOP list forbids any L* claim, any "
          "new survival predictor and any posthoc candidate")
    check("G03-library-seal", len(LIB_ELIGIBLE) == 10
          and len(LIB_CONTROL) == 2,
          "LIBRARY HASH SEALED: sha256 = %s (10 eligible + 2 "
          "control members + %s(k=%d) + %d nulls seeds %d+ + "
          "decoy %d; bars ID %.2f / PART %.2f / pad %.2f inside "
          "the hash)" % (LIB_SEAL[:16], LIB_SUBSPACE, MOM_K,
                         NDIR_NULL, SEED_NULL, SEED_DECOY,
                         COS_ID, COS_PART, NULL_PAD))

    # ---------------- S1 toys
    section("S1  TOYS -- HELLMANN-FEYNMAN, PROJECTION, LAG, "
            "CANDIDATE PULLBACK")
    x_t = np.array([0.9, 0.4, -0.2, -0.7])
    w_t = np.array([1.0, 0.5, 0.25, 0.125])
    y_t = np.array([0.6, -0.5])
    v_t = np.array([0.03, 0.01])
    n_t = 3

    def lam_toy(w2, v2):
        al2, sb2, h02 = FS.mu_chain_f64(x_t, np.asarray(w2), n_t)
        B2 = FS.b_matrix_f64(al2, sb2, h02, y_t,
                             np.asarray(v2), n_t)
        return float(np.linalg.eigvalsh(B2 @ B2.T)[-1])

    al_t, sb_t, h0_t = FS.mu_chain_f64(x_t, w_t, n_t)
    B_t = FS.b_matrix_f64(al_t, sb_t, h0_t, y_t, v_t, n_t)
    Bx_t = FS.b_matrix_f64(al_t, sb_t, h0_t, x_t, w_t, n_t)
    ev_t, V_t = np.linalg.eigh(B_t @ B_t.T)
    lam_t = float(ev_t[-1])
    phi_t = V_t[:, -1]
    c_t = B_t.T @ phi_t
    chat_t = c_t / math.sqrt(float(c_t @ c_t))
    gw_an = -lam_t * (Bx_t @ chat_t) ** 2 / w_t
    gv_an = lam_t * phi_t * phi_t / v_t
    h_t = 1e-7
    dev_t = 0.0
    for i in range(len(w_t)):
        w2p = w_t.copy()
        w2p[i] += h_t
        w2m = w_t.copy()
        w2m[i] -= h_t
        g_num = (lam_toy(w2p, v_t) - lam_toy(w2m, v_t)) / (2 * h_t)
        dev_t = max(dev_t, abs(g_num / gw_an[i] - 1.0))
    for k in range(len(v_t)):
        v2p = v_t.copy()
        v2p[k] += h_t
        v2m = v_t.copy()
        v2m[k] -= h_t
        g_num = (lam_toy(w_t, v2p) - lam_toy(w_t, v2m)) / (2 * h_t)
        dev_t = max(dev_t, abs(g_num / gv_an[k] - 1.0))
    check("G10-toy-hellmann-feynman", dev_t <= 1e-5,
          "HAND TWO-MEASURE TOY (4 mu + 2 nu atoms, n = 3): the "
          "envelope-theorem gradient dlam/dw_f = -lam p*(x_f)^2 "
          "and dlam/dv_k = p*(y_k)^2 (int p*^2 dmu = 1) matches "
          "central differences on EVERY coordinate, worst rel "
          "dev %.1e <= 1e-5 -- the Hellmann-Feynman route is "
          "exact" % dev_t)
    # projection / cosine toy
    V3 = np.zeros((3, 2))
    V3[0, 0] = 1.0
    V3[0, 1] = 1.0
    V3[1, 1] = 1.0
    wG3, UG3 = np.linalg.eigh(V3.T @ V3)
    T3v = np.array([1.0, 2.0, 5.0])
    a3 = CF.proj_coords(V3, wG3, UG3, GCUT, T3v)
    PT3 = V3 @ a3
    e3 = np.array([0.0, 1.0, 0.0])
    cs3 = cos_pair(e3, PT3)
    cap3 = float(np.linalg.norm(PT3)) / float(np.linalg.norm(T3v))
    sh3 = sub_share(np.eye(3)[:, :2],
                    np.array([1.0, 1.0, 1.0]) / math.sqrt(3.0))
    ok_t2 = (float(np.max(np.abs(PT3 - np.array([1.0, 2.0, 0.0]))))
             <= 1e-12
             and abs(cs3 - 2.0 / math.sqrt(5.0)) <= 1e-12
             and abs(cap3 - math.sqrt(5.0 / 30.0)) <= 1e-12
             and abs(sh3 - 2.0 / 3.0) <= 1e-12)
    check("G11-toy-projection-cos", ok_t2,
          "HAND PROJECTION (V = (e1, e1+e2), T = (1,2,5)): P T = "
          "(1,2,0) exact; cos(e2, PT) = 2/sqrt(5) exact; capture "
          "= sqrt(5/30) exact; subspace share of (1,1,1)/sqrt(3) "
          "on span(e1,e2) = 2/3 exact")
    # lag-cosine toy on grid_density images (even house densities)
    L_t = 8
    M_t = L_t // 2 + 1
    ca = np.zeros(M_t)
    ca[1] = 1.0
    cb = np.zeros(M_t)
    cb[2] = 1.0
    da = PIK.grid_density(ca)
    db = PIK.grid_density(cb)
    lca = PFP.lag_of(da, M_t)
    ok_t3 = (float(np.max(np.abs(lca - ca))) <= 1e-12
             and abs(lag_cos_pair(da, da, M_t) - 1.0) <= 1e-12
             and abs(lag_cos_pair(da, db, M_t)) <= 1e-12)
    check("G12-toy-lag-cos", ok_t3,
          "LAG-COSINE TOY (grid_density images, L = 8): inversion "
          "lag(grid_density(c)) == c exact; self-cosine 1, "
          "disjoint-mode cosine 0 -- the lag coordinate is the "
          "exact linear robustness coordinate")
    # candidate pullback toy
    dd_t4 = cand_density((1, 2), (2.0, -1.0), L_t)
    sl_t4 = s_env(L_t)
    # a1 (calibration, disclosed): the s_l envelope is even only
    # to libm precision (sin at mirrored arguments differs at
    # ~1e-17); the evenness gate is drawn at 1e-12 RELATIVE.
    mx_t4 = max(float(np.max(np.abs(dd_t4))), 1e-300)
    ok_ev4 = all(abs(dd_t4[l] - dd_t4[(L_t - l) % L_t])
                 <= 1e-12 * mx_t4 for l in range(L_t))
    eta_t4 = abs(float(np.sum(dd_t4 * sl_t4)))
    raw_t4 = mutant_unprojected_candidate((1, 2), (2.0, -1.0), L_t)
    ok_t4 = (ok_ev4 and eta_t4 <= 1e-15
             and raw_t4[1] == 2.0 * sl_t4[1]
             and raw_t4[7] == 2.0 * sl_t4[7]
             and raw_t4[2] == -1.0 * sl_t4[2])
    check("G13-toy-cand-density", ok_t4,
          "CANDIDATE PULLBACK TOY (folds (1,2), values (2,-1), "
          "L = 8): even placement at l and L-l with the s_l "
          "envelope exact; eta_0 after projection = %.1e "
          "(<= 1e-15)" % eta_t4)

    # ---------------- S2 w9 + anchors
    section("S2  W9 REGRESSION + METRIC + RIDGE + L* SPECTRAL "
            "ANCHORS")
    ctx9 = MS.ctx_build(MAIN_KZ)
    d9 = np.asarray(ctx9["darm"], float)
    L9 = int(ctx9["L"])
    uu9 = np.asarray(ctx9["uu"], float)
    mm9 = np.asarray(ctx9["mm"], float)
    M9 = L9 // 2 + 1
    rr9 = core.build_window(MAIN_KZ)
    D9 = float(rr9["D"])
    M0 = PFP.measure_density(d9, L9)
    margin9 = 1.0 - M0["rho"][N_REF]
    ok_w9 = ((M0["S"], M0["Sp"], M0["Sm"]) == S_REC
             and M0["minC"] == MINC_REC
             and M0["cross"] == CROSS_REC
             and abs(margin9 / MARGIN_REC - 1.0) <= MARGIN_TOL
             and abs(M0["zv"] - ZV_REC) <= ZV_TOL
             and abs(M0["b34"] - B34_REC) <= B34_TOL)
    check("G20-w9-regression", ok_w9,
          "w9 through the r290 channel: S = %d (mu %d / nu %d), "
          "minC = %s, crossing = %s, margin %.4e (rec %.2e), z_v "
          "= %+.3f, b34 = %+.3f"
          % (M0["S"], M0["Sp"], M0["Sm"], str(M0["minC"]),
             str(M0["cross"]), margin9, MARGIN_REC, M0["zv"],
             M0["b34"]))
    if smoke:
        gv_mut = lam_t * phi_t * phi_t          # /v_k MISSING
        dev_m1t = max(abs(gv_mut[k] / gv_an[k] - 1.0)
                      for k in range(len(v_t)))
        check("G80-mustfail-hf-norm", dev_m1t > 0.5,
              "m1 TOY (nu weight dropped from p*(y)^2 = lam "
              "phi^2 / v): mutant deviates from the exact toy "
              "gradient by rel %.2f > 0.5 -- the wrong "
              "normalization is loud; the real FD catch runs in "
              "the full record" % dev_m1t)
        bad_hash = mutant_posthoc_library()
        check("G82-mustfail-seal-break", bad_hash != LIB_SEAL,
              "m3 SEAL BREAK (posthoc candidate T7 injected): "
              "library hash %s != sealed %s -- CAUGHT by the "
              "hash auditor" % (bad_hash[:12], LIB_SEAL[:12]))
        hits_s = []
        for fn_ in CONSTRUCTORS:
            hits_s += scope_audit(fn_, SCOPE_FORBIDDEN)
        ag_s = antigate_fragment_audit()
        check("G84-scope-audits", not hits_s and not ag_s,
              "the %d sealed source-pure constructors consume "
              "densities/combs/geometry/degrees/seeds ONLY (%s); "
              "fragment audit: %s"
              % (len(CONSTRUCTORS),
                 "CLEAN" if not hits_s else "; ".join(hits_s),
                 "CLEAN" if not ag_s else "; ".join(ag_s)))
        return finish(smoke)

    # metric anchor (r290-a1 coordinate, pinned quadruple verbatim)
    g_loc = MF.local_gaps(uu9)
    Dg9 = 2.0 * ctx9["alpha"] / ctx9["M"]
    REF = 0.5 * float(np.sum(mm9 * g_loc)) / Dg9

    def lag_l1(dd):
        return float(np.sum(np.abs(PFP.lag_of(dd, M9))))

    c_back = PFP.lag_of(d9, M9)
    inv_dev = float(np.max(np.abs(PIK.grid_density(c_back) - d9))) \
        / max(float(np.max(np.abs(d9))), 1e-300)
    devs_c = []
    cons_c = True
    for th_c, seed_c in [(THETA_CAL, s_) for s_ in CAL_SEEDS] \
            + [(T3_THETA, T3_SEED)]:
        u2c, m2c = MF.pert_jit(uu9, mm9, th_c, seed_c, False)
        cons_c = cons_c and MF.conserve_comb(
            "P2_JIT", uu9, mm9, u2c, m2c, th_c)
        d2c = np.asarray(PIK.build_rung(MAIN_KZ,
                                        comb=(u2c, m2c))["d"], float)
        devs_c.append(abs(lag_l1(d2c - d9) / REF / th_c - 1.0))
    ok_met = (abs(REF / REF_REC - 1.0) <= REF_TOL
              and inv_dev <= 1e-12 and cons_c
              and max(devs_c) <= T3_TOL)
    check("G21-metric-anchor", ok_met,
          "theta_eq metric (r290-a1 LAG coordinate, pinned "
          "quadruple VERBATIM): analytic REF = %.4f (rec %.2f); "
          "inversion identity rel %.1e; jitter devs %s <= %.2f, "
          "conservation exact"
          % (REF, REF_REC, inv_dev,
             str([round(v, 3) for v in devs_c]), T3_TOL))
    # control worlds (r292 constructions verbatim)
    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]
    uE = np.log(nn_idx.astype(float))
    mE = 2.0 * lamE[nn_idx] / np.sqrt(nn_idx.astype(float))
    ug9, uw9 = PB.smooth_comb(rr9["alpha"])
    gpc = PC.Grid()
    comb_hl, _tag = PC.gen_model(gpc, "HL2", HL2_SEED)
    ctx_c = {"EPST": MS.ctx_build(MAIN_KZ, comb=(uE, mE)),
             "SCR": MS.ctx_build(MAIN_KZ, scramble_seed=1),
             "SMOOTH": MS.ctx_build(MAIN_KZ, comb=(ug9, uw9)),
             "HL2": MS.ctx_build(MAIN_KZ, comb=comb_hl)}
    d_worlds = {w: np.asarray(ctx_c[w]["darm"], float)
                for w in ctx_c}
    worlds_meas = {w: PFP.measure_density(d_worlds[w], L9)
                   for w in d_worlds}
    ok_fl = all(worlds_meas[w]["minC"] == CTRL_FLIPS[w]
                for w in CTRL_FLIPS)
    check("G22-control-flips", ok_fl,
          "control flips through this channel: %s == records "
          "(25/21/27/25)"
          % str({w: worlds_meas[w]["minC"] for w in CTRL_FLIPS}))
    # ridge anchor (r280 rebuilt verbatim) + top-9 atom ranking
    GE = BL.grad_ext(ctx9, N_REF + 2)
    xi = BL.dir_opt(GE["gR"], GE["gL"], GE["gaps"], N_REF)
    th_up, th_kill, _cvec = BL.theta_of_dir(GE["gR"], GE["gL"],
                                            GE["gaps"], xi, N_REF)
    du_ridge = 2.0 * th_up * GE["gaps"] * xi
    uR, mR = RA.subset_move(uu9, mm9, du_ridge, np.ones(len(uu9)))
    dR = np.asarray(PIK.build_rung(MAIN_KZ, comb=(uR, mR))["d"],
                    float)
    MRi = PFP.measure_density(dR, L9)
    du1 = GE["gaps"] * xi
    cj = np.where(du1 > 0, du1 * GE["gR"][:, N_REF],
                  du1 * GE["gL"][:, N_REF])
    nn_at = RA.atom_ints(uu9)
    order = np.argsort(cj)
    top9 = tuple(int(v) for v in nn_at[order[:N_ATOM]])
    ok_ridge = (abs(th_up / THUP_REC - 1.0) <= THUP_TOL
                and th_kill > th_up
                and MRi["minC"] == RIDGE_MINC_REC
                and MF.conserve_comb("P2_JIT", uu9, mm9, uR, mR,
                                     2.0 * th_up * AMP_PAD)
                and top9 == R291_TOP9)
    check("G23-ridge-anchor", ok_ridge,
          "r280 RIDGE ANCHOR: theta_up = %.4e (rec %.2e), "
          "theta_kill = %.2e; OPT endpoint minC = %s == %d; "
          "conservation exact; top-9 atoms %s == the r291 record"
          % (th_up, THUP_REC, th_kill, str(MRi["minC"]),
             RIDGE_MINC_REC, str(top9)))
    # L* spectral anchor (r283/r284/r286 records)
    PK9 = kernel_pack(d9, L9, N_REF)
    lam184 = float(PK9["ev"][-1])
    top5 = PK9["ev"][-5:][::-1]
    dev_top5 = max(abs(float(top5[i]) - R283_TOP5[i])
                   for i in range(5))
    dev_mid = abs((1.0 - lam184) - margin9)
    ok_lstar = (abs(lam184 - LAM184_REC) <= LAM184_TOL
                and dev_top5 <= TOP5_TOL
                and dev_mid <= 1e-12
                and M0["cross"] == MINC_REC + 1)
    check("G24-lstar-spectral-anchor", ok_lstar,
          "THE L* OBJECT: lambda_max(E_184) = %.8f (rec %.8f, "
          "dev %.1e <= %.0e); top-5 eigs == r283 (max dev %.1e "
          "<= %.0e); margin identity 1 - lambda_max == 1 - "
          "rho_184 (dev %.1e); crossing %d == minC + 1 (r283 "
          "theorem)" % (lam184, LAM184_REC,
                        abs(lam184 - LAM184_REC), LAM184_TOL,
                        dev_top5, TOP5_TOL, dev_mid, CROSS_REC))
    # EPSTEIN first-order flatness anchor (r292 verbatim)
    mcE0 = worlds_meas["EPST"]["minC"]
    GEe = BL.grad_ext(ctx_c["EPST"], mcE0 + 2)
    xiE = BL.dir_opt(GEe["gR"], GEe["gL"], GEe["gaps"], mcE0)
    tuE, _tkE, cE = BL.theta_of_dir(GEe["gR"], GEe["gL"],
                                    GEe["gaps"], xiE, mcE0)
    ok_ef = abs(cE[mcE0]) <= EPST_C_BAR and tuE >= EPST_THUP_MIN
    check("G25-epstein-flatness-anchor", ok_ef,
          "EPSTEIN first-order flatness (own wall degree %d): "
          "c_%d = %.2e (bar %.0e), theta_up = %.2e >= %.0e -- "
          "the r291/r292 flat-wall anchor"
          % (mcE0, mcE0, cE[mcE0], EPST_C_BAR, tuE,
             EPST_THUP_MIN))

    # ---------------- S3 r292 Hessian rebuilt verbatim -> e_top
    section("S3  LEG 0b -- r292 HESSIAN REBUILT VERBATIM "
            "(29 sealed directions) -> e_top")

    def margin_at(dvec):
        meas = PFP.measure_density(dvec, L9)
        if meas["rho"] is None or meas["cross"] is None \
                or meas["cross"] <= N_REF:
            return float("nan")
        return 1.0 - meas["rho"][N_REF]

    m00 = margin_at(d9)
    dd_R = dR - d9
    dirsD = []
    for wn in ("SMOOTH", "SCR", "EPST"):
        dirsD.append(("W_" + wn, d_worlds[wn] - d9))
    dirsD.append(("RIDGE", dd_R))
    ok_dcons = True
    for j in range(N_ATOM):
        mask = np.zeros(len(uu9))
        mask[order[j]] = 1.0
        u2, m2 = RA.subset_move(uu9, mm9, du_ridge, mask)
        ok_dcons = ok_dcons and MF.conserve_comb(
            "P2_JIT", uu9, mm9, u2, m2, 2.0 * th_up * AMP_PAD)
        ddj = np.asarray(PIK.build_rung(MAIN_KZ,
                                        comb=(u2, m2))["d"],
                         float) - d9
        dirsD.append(("ATOM%02d_n%d" % (j, int(nn_at[order[j]])),
                      ddj))
    for i in range(NDIR_FRAC):
        dd, (u2, m2) = PFP.dir_frac(uu9, mm9, MAIN_KZ, d9,
                                    THETA_CAL, SEED_FRAC + i)
        ok_dcons = ok_dcons and MF.conserve_comb(
            "P2_JIT", uu9, mm9, u2, m2, THETA_CAL)
        dirsD.append(("FRAC%02d" % i, dd))
    sl9 = s_env(L9)
    for i in range(NDIR_DENS):
        dd = PFP.dir_dens(d9, L9, SEED_DENS + i)
        eta0 = abs(float(np.sum(dd * sl9)))
        ok_dcons = ok_dcons and eta0 <= ETA0_BAR \
            * max(float(np.sum(np.abs(dd * sl9))), 1.0)
        dirsD.append(("DENS%02d" % i, dd))
    names_D = [n for n, _d in dirsD]
    vhat = {n: CF.unit_dir(dd, lag_l1(dd), REF) for n, dd in dirsD}
    check("G30-direction-set", ok_dcons and len(dirsD) == 29,
          "SEALED DIRECTION SET D (r292 verbatim): %d directions "
          "= 3 world axes + ridge + %d atoms (conservation "
          "exact) + %d FRAC (seeds 292100+) + %d DENS (seeds "
          "292200+, eta_0 exact); all theta_eq-normalized"
          % (len(dirsD), N_ATOM, NDIR_FRAC, NDIR_DENS))
    nD = len(dirsD)
    d2_tab = {}
    ok_finA = True
    for name in names_D:
        v = vhat[name]
        ests = []
        for h in HESS_EQ_HS:
            mp_ = margin_at(d9 + v * h)
            mn_ = margin_at(d9 - v * h)
            ok_finA = ok_finA and math.isfinite(mp_) \
                and math.isfinite(mn_)
            ests.append((mp_ - 2.0 * m00 + mn_) / (h * h))
        d2_tab[name] = ests
    diag_mid = {n: d2_tab[n][1] for n in names_D}
    check("G31-diagonal-census", ok_finA,
          "DIAGONAL d2 census (r292 a1 ladder %s, all finite): "
          "worlds %s; RIDGE %.2f; DENS [%.3g..%.3g]"
          % (str(HESS_EQ_HS),
             str({n: "%.1f" % d2_tab[n][0] for n in names_D[:3]}),
             d2_tab["RIDGE"][0],
             min(d2_tab[n][0] for n in names_D[23:]),
             max(d2_tab[n][0] for n in names_D[23:])))
    Hmat = np.zeros((nD, nD))
    for i in range(nD):
        Hmat[i, i] = diag_mid[names_D[i]]
    sel_pairs = [(0, 1), (0, 2), (1, 2), (0, 3), (1, 3), (2, 3)]
    sel_pairs += [(3, 4 + j) for j in range(N_ATOM)]
    ok_finP = True
    pol_dev_max = 0.0
    n_pairs = 0
    d2sum_cache = {}
    for i in range(nD):
        for j in range(i + 1, nD):
            u, v = vhat[names_D[i]], vhat[names_D[j]]
            h = H_PAIR_H
            msp = margin_at(d9 + (u + v) * h)
            msn = margin_at(d9 - (u + v) * h)
            mdp = margin_at(d9 + (u - v) * h)
            mdn = margin_at(d9 - (u - v) * h)
            ok_finP = ok_finP and all(math.isfinite(x)
                                      for x in (msp, msn, mdp,
                                                mdn))
            d2su = (msp - 2.0 * m00 + msn) / (h * h)
            d2di = (mdp - 2.0 * m00 + mdn) / (h * h)
            Hij = CF.pol_of_d2(d2su, d2di)
            Hmat[i, j] = Hmat[j, i] = Hij
            d2sum_cache[(i, j)] = d2su
            n_pairs += 1
    for (i, j) in sel_pairs:
        Hij = Hmat[i, j]
        Hexp = CF.expand_of_d2(d2sum_cache[(i, j)],
                               diag_mid[names_D[i]],
                               diag_mid[names_D[j]])
        dev = abs(Hij - Hexp) / max(abs(Hij), D2_FLOOR)
        pol_dev_max = max(pol_dev_max, dev)
    check("G32-polarization-matrix", ok_finP
          and pol_dev_max <= POL_TOL,
          "FULL POLARIZATION MATRIX (r292 verbatim): %d pairs at "
          "h = %.3g (all finite); %d selected pairs pass the "
          "expansion crosscheck (worst rel dev %.3f <= %.2f)"
          % (n_pairs, H_PAIR_H, len(sel_pairs), pol_dev_max,
             POL_TOL))
    Vmat = np.stack([vhat[n] for n in names_D], axis=1)
    Gmat = Vmat.T @ Vmat
    wG, UG = np.linalg.eigh(Gmat)
    keep = wG >= GCUT * wG[-1]
    Uk = UG[:, keep]
    Wk = Uk / np.sqrt(wG[keep])[None, :]
    Ared = Wk.T @ Hmat @ Wk
    lam, Y = np.linalg.eigh(Ared)
    o_l = np.argsort(-np.abs(lam))
    lam_s = lam[o_l]
    Evec = Vmat @ (Wk @ Y[:, o_l])
    tr_abs = float(np.sum(np.abs(lam_s)))
    share1 = abs(lam_s[0]) / max(tr_abs, 1e-300)
    coef_top = (Wk @ Y[:, o_l])[:, 0]
    # a2: sign canonicalization pinned to the DENS05 loading
    i_d05 = names_D.index("DENS05")
    if coef_top[i_d05] < 0.0:
        coef_top = -coef_top
        Evec[:, 0] = -Evec[:, 0]
    e_top = Evec[:, 0]
    coef_n = coef_top / max(float(np.max(np.abs(coef_top))),
                            1e-300)
    o_c = np.argsort(-np.abs(coef_n))
    load4 = [(names_D[i], float(coef_n[i])) for i in o_c[:4]]
    ok_load = all(load4[i][0] == R292_LOADINGS[i][0]
                  and abs(load4[i][1] - R292_LOADINGS[i][1])
                  <= R292_LOAD_TOL for i in range(4))
    vSMn = vhat["W_SMOOTH"]
    cos_sm = abs(cos_pair(vSMn, e_top))
    l2n2 = {n: float(vhat[n] @ vhat[n]) for n in names_D}
    diag_l2 = {n: diag_mid[n] / max(l2n2[n], 1e-300)
               for n in names_D}
    Hrr = diag_l2["RIDGE"]
    diag_sorted = sorted((abs(diag_l2[n]) for n in names_D),
                         reverse=True)
    rank_rr = 1 + sum(1 for v in diag_sorted if v > abs(Hrr))
    dens_idx = [i for i, n in enumerate(names_D)
                if n.startswith("DENS")]
    share_dens9 = float(np.sum(coef_top[dens_idx] ** 2)) \
        / max(float(np.sum(coef_top ** 2)), 1e-300)
    ok_r292 = (abs(share1 - R292_SHARE_REC) <= R292_SHARE_TOL
               and abs(lam_s[0] / R292_LAMTOP_REC - 1.0)
               <= R292_LAMTOP_TOL
               and abs(cos_sm - R292_COS_SM_REC)
               <= R292_COS_SM_TOL
               and rank_rr == R292_RIDGE_RANK_REC
               and ok_load)
    check("G33-r292-etop-anchor", ok_r292,
          "r292 SPECTROSCOPY REPRODUCED: trace share %.4f == "
          "0.925, lam_top %.4f == -0.418, SMOOTH |cos| %.4f == "
          "0.07, ridge L2-rank %d/29 == 28; e_top loadings "
          "(sign pinned to DENS05) %s == r292 record (tol "
          "%.2f); 29-dir DENS coefficient share %.3f typed "
          "MEASUREMENT (a3: the r294 0.989 is the 18-direction "
          "training-form share, a different object) -- e_top is "
          "the sealed round object"
          % (share1, lam_s[0], cos_sm, rank_rr,
             str([(n, round(v, 2)) for n, v in load4]),
             R292_LOAD_TOL, share_dens9))

    # ---------------- S4 LEG A: T1 gradient + library
    section("S4  LEG A -- T1 = GRAD LAMBDA_MAX (FD WARD) + THE "
            "SEALED LIBRARY")
    G_raw, lam_chk = grad_of_pack(PK9, d9, L9, 1)

    def lam_fd_eval(dv):
        xs2, ws2, fp2 = PIK.folded_measure(dv, L9, +1.0)
        ys2, vs2, fn2 = PIK.folded_measure(dv, L9, -1.0)
        ok_split = (np.array_equal(fp2, PK9["fp"])
                    and np.array_equal(fn2, PK9["fn"]))
        al2, sb2, h02 = FS.mu_chain_f64(xs2, ws2, N_REF)
        B2 = FS.b_matrix_f64(al2, sb2, h02, ys2, vs2, N_REF)
        return float(np.linalg.eigvalsh(B2 @ B2.T)[-1]), ok_split

    # a2: FD-resolvable coordinates -- per channel the 3 even
    # pair moves with the LARGEST |analytic directional
    # derivative| (tiny-gradient folds sit at the f64
    # eigensolver noise floor ~1e-14, disclosed)
    half = [l for l in range(1, L9 // 2) if d9[l] != 0.0]

    def pair_g(l):
        return abs(G_raw[l] + G_raw[(L9 - l) % L9])

    mu_l = sorted([l for l in half if d9[l] > 0],
                  key=pair_g)[-FD_NCOORD:]
    nu_l = sorted([l for l in half if d9[l] < 0],
                  key=pair_g)[-FD_NCOORD:]
    t0 = FD_T * float(np.max(np.abs(d9)))
    fd_rows = []
    ok_fd = True
    ok_res = True
    ok_split_all = True
    for l in mu_l + nu_l:
        e = np.zeros(L9)
        e[l] = 1.0
        e[(L9 - l) % L9] = 1.0
        g_an = float(G_raw @ e)
        ok_res = ok_res and abs(g_an) * t0 >= FD_MIN
        gs = []
        for t in (t0, t0 / 2.0):
            lp, okp = lam_fd_eval(d9 + t * e)
            lmn, okm = lam_fd_eval(d9 - t * e)
            ok_split_all = ok_split_all and okp and okm
            gs.append((lp - lmn) / (2.0 * t))
        g_rich = (4.0 * gs[1] - gs[0]) / 3.0
        dev = abs(g_rich / g_an - 1.0) if g_an != 0.0 \
            else float("inf")
        ok_fd = ok_fd and dev <= FD_BAR
        fd_rows.append((l, g_an, g_rich, dev))
    worst_fd = max(r[3] for r in fd_rows)
    check("G40-t1-gradient-fdward", ok_fd and ok_res
          and ok_split_all and abs(lam_chk - lam184) <= 1e-14,
          "T1 = grad lambda_max(E_184) via Hellmann-Feynman "
          "(phi*, int p*^2 dmu = 1): FD ward on the %d sealed "
          "coordinates (a2: per channel the 3 largest |analytic "
          "pair derivative|, resolvability |g| t >= %.0e "
          "holds, Richardson pair at the re-measured margin-"
          "valid step t = %.3g max|d|): worst rel "
          "dev %.1e <= %.0e; fold split invariant at every FD "
          "point; lam identity %.1e -- the gradient is EXACT to "
          "ward precision"
          % (len(fd_rows), FD_MIN, FD_T, worst_fd, FD_BAR,
             abs(lam_chk - lam184)))
    # library construction (sealed constructor, one per member)
    CAND = {}
    for nm in LIB_ELIGIBLE + LIB_CONTROL:
        CAND[nm] = build_candidate(nm, d9, L9, D9, uu9, mm9,
                                   N_REF)
    T5cols = np.stack([moment_grad(d9, L9, j)
                       for j in range(1, MOM_K + 1)], axis=1)
    NULLS = [PFP.dir_dens(d9, L9, SEED_NULL + i)
             for i in range(NDIR_NULL)]
    decoy = PFP.dir_dens(d9, L9, SEED_DECOY)
    ok_cons = True
    ok_even = True
    for nm, dd in list(CAND.items()) \
            + [("T5_M%d" % j, T5cols[:, j - 1])
               for j in range(1, MOM_K + 1)] \
            + [("NULL%02d" % i, NULLS[i])
               for i in range(NDIR_NULL)] + [("DECOY", decoy)]:
        eta0 = abs(float(np.sum(dd * sl9)))
        ok_cons = ok_cons and eta0 <= ETA0_BAR \
            * max(float(np.sum(np.abs(dd * sl9))), 1.0)
        mx_dd = max(float(np.max(np.abs(dd))), 1e-300)
        ok_even = ok_even and all(
            abs(dd[l] - dd[(L9 - l) % L9]) <= 1e-12 * mx_dd
            for l in range(0, L9, 37))
    check("G41-library-conservation",
          ok_cons and ok_even and len(CAND) == 12,
          "SEALED LIBRARY BUILT (one constructor, hash-sealed "
          "members): 12 members + T5(%d) + %d nulls + decoy; "
          "eta_0 exact (<= %.0e rel) and even on ALL %d vectors "
          "-- same conservation projection, same pullback"
          % (MOM_K, NDIR_NULL, ETA0_BAR,
             len(CAND) + MOM_K + NDIR_NULL + 1))

    # ---------------- S5 LEG B: the identity test
    section("S5  LEG B -- THE IDENTITY TEST (in-span primary, "
            "sealed bars)")

    def cos_cols(T):
        a = CF.proj_coords(Vmat, wG, UG, GCUT, T)
        PT = Vmat @ a
        cs = cos_pair(e_top, PT)
        cap = float(np.linalg.norm(PT)) \
            / max(float(np.linalg.norm(T)), 1e-300)
        return cs, cos_pair(e_top, T), \
            lag_cos_pair(e_top, PT, M9), cap

    tab = {}
    for nm in LIB_ELIGIBLE + LIB_CONTROL:
        tab[nm] = cos_cols(CAND[nm])
    null_cos = [abs(cos_cols(dd)[0]) for dd in NULLS]
    noise_ref = max(null_cos)
    decoy_cos = abs(cos_cols(decoy)[0])
    # T5 subspace: in-span share of e_top on the projected T5 span
    T5span = np.stack([Vmat @ CF.proj_coords(Vmat, wG, UG, GCUT,
                                             T5cols[:, j])
                       for j in range(MOM_K)], axis=1)
    sh_t5 = sub_share(T5span, e_top)
    cos_t5 = math.sqrt(max(sh_t5, 0.0))
    nullq = []
    for q0 in (0, 4):
        Wq = np.stack([Vmat @ CF.proj_coords(
            Vmat, wG, UG, GCUT, NULLS[q0 + j])
            for j in range(4)], axis=1)
        nullq.append(math.sqrt(max(sub_share(Wq, e_top), 0.0)))
    for nm in LIB_ELIGIBLE + LIB_CONTROL:
        cs, cr, cl, cap = tab[nm]
        info("%-16s cos_span %+.3f | raw %+.3f | lag %+.3f | "
             "capture %.3f%s"
             % (nm, cs, cr, cl, cap,
                "  [CONTROL row]" if nm in LIB_CONTROL else ""))
    info("T5_MOMENTS       root share %.3f (share %.4f; null "
         "quadruple roots %.3f / %.3f)"
         % (cos_t5, sh_t5, nullq[0], nullq[1]))
    info("T6 NULLS         |cos_span| %s -> noise reference "
         "(max) %.3f; DECOY %.3f"
         % (str([round(v, 3) for v in null_cos]), noise_ref,
            decoy_cos))
    check("G50-cos-table", all(math.isfinite(t[0])
                               for t in tab.values()),
          "COS TABLE measured (in-span primary + raw/lag/capture "
          "honesty columns, printed above); T5 root share %.3f; "
          "all values finite" % cos_t5)
    check("G51-noise-reference", noise_ref < COS_ID,
          "NOISE REFERENCE (max of %d nulls through the "
          "IDENTICAL pipeline, conservative q95 estimator at "
          "n = %d, disclosed): %.3f; null-quadruple subspace "
          "roots %.3f / %.3f (the 4-dim chance level of T5, "
          "disclosed)" % (NDIR_NULL, NDIR_NULL, noise_ref,
                          nullq[0], nullq[1]))
    # sealed adjudication
    elig_vals = {nm: abs(tab[nm][0]) for nm in LIB_ELIGIBLE}
    elig_vals["T5_MOMENTS"] = cos_t5
    best_nm = max(elig_vals, key=lambda k: elig_vals[k])
    best_c = elig_vals[best_nm]
    id_hits = [nm for nm in LIB_ELIGIBLE
               if abs(tab[nm][0]) >= COS_ID]
    if id_hits:
        base_nm = max(id_hits, key=lambda k: abs(tab[k][0]))
        base_verd = "DENS_ARITHMETIC_IDENTITY(%s, |cos| %.3f)" \
            % (base_nm, abs(tab[base_nm][0]))
        base_cls = "ID"
    elif best_c >= COS_PART:
        base_nm = best_nm
        base_verd = "DENS_PARTIAL(%s, |cos| %.3f)" % (best_nm,
                                                      best_c)
        base_cls = "PART"
    else:
        base_nm = best_nm
        above = best_c >= noise_ref + NULL_PAD
        base_verd = ("DENS_WORLD_BLIND(best %s %.3f%s)"
                     % (best_nm, best_c,
                        ", ABOVE-NOISE FLAG (>= %.3f + %.2f), "
                        "disclosed" % (noise_ref, NULL_PAD)
                        if above else
                        ", below noise %.3f + %.2f"
                        % (noise_ref, NULL_PAD)))
        base_cls = "BLIND"
    check("G52-identity-adjudication", True,
          "SEALED RULE (ID iff |cos| >= %.2f for T1 or a "
          "T2/T3/T4 member; PART iff max >= %.2f; else BLIND "
          "with the noise clause): best = %s (%.3f) -> BASE %s"
          % (COS_ID, COS_PART, best_nm, best_c,
             base_verd.split("(")[0]))
    t1c = tab["T1_GRAD_LMAX"]
    check("G53-t1-coupling", True,
          "THE COUPLING NUMBER OF THE ROUND (always reported): "
          "cos(e_top, grad lambda_max) = %+.3f in-span (raw "
          "%+.3f, lag %+.3f, capture %.3f); eigen-specificity "
          "controls: grad lam2 %+.3f, grad lam3 %+.3f (excluded "
          "from the identity award, disclosed)"
          % (t1c[0], t1c[1], t1c[2], t1c[3],
             tab["T1B_GRAD_LAM2"][0], tab["T1C_GRAD_LAM3"][0]))

    # ---------------- S6 LEG C: world + window hardening
    section("S6  LEG C -- WORLD CONTRAST (EPST/SCR) + WINDOW "
            "TRANSPORT (w7/w11)")

    def hess_span_etop(d0, Lx, dirs, margin_f, m00x):
        """gate-side: span Hessian (r292 ladder + r294 halving)
        -> top eigenaxis in the span + Richardson devs of the
        top-|diag| direction."""
        names = [n for n, _ in dirs]
        vx = {n: dd for n, dd in dirs}
        ladder = list(HESS_EQ_HS)
        n_halve = 0
        diag_x = {}
        ests_x = {}
        for _try in range(LADDER_MAX_HALVE + 1):
            fin = True
            for n in names:
                ests = []
                for h in ladder:
                    mp_ = margin_f(d0 + vx[n] * h)
                    mn_ = margin_f(d0 - vx[n] * h)
                    fin = fin and math.isfinite(mp_) \
                        and math.isfinite(mn_)
                    ests.append((mp_ - 2.0 * m00x + mn_)
                                / (h * h))
                diag_x[n] = ests[1]
                ests_x[n] = ests
            if fin:
                break
            ladder = [h / 2.0 for h in ladder]
            n_halve += 1
        hp = ladder[1]
        k = len(names)
        Hx = np.zeros((k, k))
        fin_p = True
        for i in range(k):
            Hx[i, i] = diag_x[names[i]]
            for j in range(i + 1, k):
                u, v = vx[names[i]], vx[names[j]]
                msp = margin_f(d0 + (u + v) * hp)
                msn = margin_f(d0 - (u + v) * hp)
                mdp = margin_f(d0 + (u - v) * hp)
                mdn = margin_f(d0 - (u - v) * hp)
                fin_p = fin_p and all(math.isfinite(x)
                                      for x in (msp, msn, mdp,
                                                mdn))
                if not fin_p:
                    continue
                d2su = (msp - 2.0 * m00x + msn) / (hp * hp)
                d2di = (mdp - 2.0 * m00x + mdn) / (hp * hp)
                Hx[i, j] = Hx[j, i] = CF.pol_of_d2(d2su, d2di)
        Vx = np.stack([vx[n] for n in names], axis=1)
        Gx = Vx.T @ Vx
        wGx, UGx = np.linalg.eigh(Gx)
        keepx = wGx >= GCUT * wGx[-1]
        Ukx = UGx[:, keepx]
        Wkx = Ukx / np.sqrt(wGx[keepx])[None, :]
        Ax = Wkx.T @ Hx @ Wkx
        lamx, Yx = np.linalg.eigh(Ax)
        ox = np.argsort(-np.abs(lamx))
        coefx = (Wkx @ Yx[:, ox])[:, 0]
        e_x = Vx @ coefx
        i_top = max(range(k),
                    key=lambda i: abs(diag_x[names[i]]))
        rdv = CF.rich_devs(ests_x[names[i_top]])
        rich_ok = rdv is not None and max(rdv) <= RICH_TOL
        return dict(e=e_x, V=Vx, wG=wGx, UG=UGx, coef=coefx,
                    names=names, n_halve=n_halve, fin=fin_p,
                    lam_top=float(lamx[ox[0]]), rich_ok=rich_ok,
                    rich=rdv, hp=hp)

    def span_cos(bundle, T):
        a = CF.proj_coords(bundle["V"], bundle["wG"],
                           bundle["UG"], GCUT, T)
        PT = bundle["V"] @ a
        return cos_pair(bundle["e"], PT)

    def span_root_share(bundle, cols):
        """root share of the bundle top axis on the span-
        projected column subspace (the a4 subspace repetition)."""
        W = np.stack([bundle["V"] @ CF.proj_coords(
            bundle["V"], bundle["wG"], bundle["UG"], GCUT, c)
            for c in cols], axis=1)
        return math.sqrt(max(sub_share(W, bundle["e"]), 0.0))

    def best_repeat(bundle, d_x, L_x, D_x, u_x, m_x, n_x):
        """a4: rebuild the ACTUAL best member world/window-own:
        single directions via the one sealed constructor, the
        T5 subspace via the own moment-gradient span root
        share."""
        if base_nm == "T5_MOMENTS":
            cols = [moment_grad(d_x, L_x, j)
                    for j in range(1, MOM_K + 1)]
            return span_root_share(bundle, cols)
        T_x = build_candidate(base_nm, d_x, L_x, D_x, u_x, m_x,
                              n_x)
        return abs(span_cos(bundle, T_x))

    def null_reference(bundle, d_x, L_x, seed0, nn):
        """noise reference matched to the best-member type:
        single-direction |cos| values, or null-quadruple root
        shares when the best member is the T5 subspace."""
        dirs = [PFP.dir_dens(d_x, L_x, seed0 + i)
                for i in range(nn)]
        if base_nm == "T5_MOMENTS":
            return [span_root_share(bundle, dirs[0:4]),
                    span_root_share(bundle, dirs[4:8])]
        return [abs(span_cos(bundle, dd)) for dd in dirs]

    # (c1) world contrast at EPST and SCR
    ctrl_res = {}
    for cn in CTRL_WORLDS:
        d_c = d_worlds[cn]
        n_c = int(worlds_meas[cn]["minC"])
        u_c = np.asarray(ctx_c[cn]["uu"], float)
        m_c = np.asarray(ctx_c[cn]["mm"], float)
        g_lc = MF.local_gaps(u_c)
        Dg_c = 2.0 * ctx_c[cn]["alpha"] / ctx_c[cn]["M"]
        REF_c = 0.5 * float(np.sum(m_c * g_lc)) / Dg_c

        def margin_c(dv, n_c=n_c):
            me = PFP.measure_density(dv, L9)
            if me["rho"] is None or me["cross"] is None \
                    or me["cross"] <= n_c:
                return float("nan")
            return 1.0 - me["rho"][n_c]

        m0c = margin_c(d_c)
        dirs_c = []
        for i in range(N_DENS_CTRL):
            dd = PFP.dir_dens(d_c, L9, SEED_CTRL[cn] + i)
            dirs_c.append(("CD%02d" % i,
                           CF.unit_dir(dd, lag_l1(dd), REF_c)))
        bun = hess_span_etop(d_c, L9, dirs_c, margin_c, m0c)
        cs_c = best_repeat(bun, d_c, L9, D9, u_c, m_c, n_c)
        nl_c = null_reference(bun, d_c, L9, SEED_CTRL_NULL[cn],
                              NNULL_CTRL)
        collapsed = (not bun["rich_ok"]) or cs_c < COS_PART
        ctrl_res[cn] = dict(cs=cs_c, coll=collapsed,
                            rich_ok=bun["rich_ok"],
                            nmax=max(nl_c), m0=m0c,
                            n_halve=bun["n_halve"],
                            lam_top=bun["lam_top"])
        check("G6%d-%s-contrast" % (0 if cn == "EPST" else 1,
                                    cn.lower()),
              bun["fin"] and math.isfinite(cs_c),
              "%s WORLD CONTRAST (own wall degree %d, margin_0 "
              "%.3g, 12 DENS dirs, ladder halved %dx): top-diag "
              "Richardson %s (devs %s); |cos_c(%s)| = %.3f "
              "(null max %.3f) -> %s"
              % (cn, n_c, m0c, bun["n_halve"],
                 "STABLE (structured own axis, disclosed)"
                 if bun["rich_ok"] else
                 "UNSTABLE (no structured axis)",
                 str([round(v, 4) for v in (bun["rich"] or [])]),
                 base_nm, cs_c, max(nl_c),
                 "COLLAPSED" if collapsed else
                 "NOT COLLAPSED (construction-trivial risk)"))
    world_ok = all(ctrl_res[cn]["coll"] for cn in CTRL_WORLDS)
    check("G62-world-hardening", True,
          "SEALED COLLAPSE RULE (collapse iff Richardson-"
          "unstable OR |cos_c| < %.2f): EPST %s, SCR %s -> "
          "world hardening %s"
          % (COS_PART,
             "COLLAPSED" if ctrl_res["EPST"]["coll"] else "HELD",
             "COLLAPSED" if ctrl_res["SCR"]["coll"] else "HELD",
             "PASSED (match is world-specific)" if world_ok
             else "FAILED -> DOWNGRADE one level (disclosed)"))
    # (c2) window transport w7 / w11 (r294 protocol verbatim)
    win_res = {}
    for wi, kz in enumerate(W_LIST):
        wsd = W_SEED_BASE + W_SEED_STEP * wi
        ctxw = MS.ctx_build(kz)
        dw0 = np.asarray(ctxw["darm"], float)
        Lw = int(ctxw["L"])
        uuw = np.asarray(ctxw["uu"], float)
        mmw = np.asarray(ctxw["mm"], float)
        Mw = Lw // 2 + 1
        Dw = float(core.build_window(kz)["D"])
        m0w_meas = PFP.measure_density(dw0, Lw)
        nref_w = int(m0w_meas["minC"])
        ok_wall = (m0w_meas["cross"] is not None
                   and m0w_meas["cross"] == nref_w + 1
                   and nref_w == W_NREF_REC[kz])

        def margin_w(dv, nref_w=nref_w, Lw=Lw):
            me = PFP.measure_density(dv, Lw)
            if me["rho"] is None or me["cross"] is None \
                    or me["cross"] <= nref_w:
                return float("nan")
            return 1.0 - me["rho"][nref_w]

        m00w = margin_w(dw0)
        g_lw = MF.local_gaps(uuw)
        Dgw = 2.0 * ctxw["alpha"] / ctxw["M"]
        REFw = 0.5 * float(np.sum(mmw * g_lw)) / Dgw

        def lag_l1w(dd, Mw=Mw):
            return float(np.sum(np.abs(PFP.lag_of(dd, Mw))))

        GEw = BL.grad_ext(ctxw, nref_w + 2)
        xiw = BL.dir_opt(GEw["gR"], GEw["gL"], GEw["gaps"],
                         nref_w)
        thw, _thkw, _cw = BL.theta_of_dir(GEw["gR"], GEw["gL"],
                                          GEw["gaps"], xiw,
                                          nref_w)
        du_rw = 2.0 * thw * GEw["gaps"] * xiw
        f_ex = min(1.0, THETA_CAL / (2.0 * thw))
        du1w = GEw["gaps"] * xiw
        cjw = np.where(du1w > 0, du1w * GEw["gR"][:, nref_w],
                       du1w * GEw["gL"][:, nref_w])
        ordw = np.argsort(cjw)
        dirs_w = []
        okc = True
        uRw, mRw = RA.subset_move(uuw, mmw, f_ex * du_rw,
                                  np.ones(len(uuw)))
        okc = okc and MF.conserve_comb(
            "P2_JIT", uuw, mmw, uRw, mRw,
            f_ex * 2.0 * thw * AMP_PAD)
        dirs_w.append(("RIDGE", np.asarray(PIK.build_rung(
            kz, comb=(uRw, mRw))["d"], float) - dw0))
        for j in range(N_ATOM_W):
            mk = np.zeros(len(uuw))
            mk[ordw[j]] = 1.0
            u2, m2 = RA.subset_move(uuw, mmw, f_ex * du_rw, mk)
            okc = okc and MF.conserve_comb(
                "P2_JIT", uuw, mmw, u2, m2,
                f_ex * 2.0 * thw * AMP_PAD)
            dirs_w.append(("ATOM%02d" % j, np.asarray(
                PIK.build_rung(kz, comb=(u2, m2))["d"],
                float) - dw0))
        for i in range(N_FRAC_W):
            dd, (u2, m2) = PFP.dir_frac(uuw, mmw, kz, dw0,
                                        THETA_CAL, wsd + i)
            okc = okc and MF.conserve_comb(
                "P2_JIT", uuw, mmw, u2, m2, THETA_CAL)
            dirs_w.append(("FRAC%02d" % i, dd))
        slw = s_env(Lw)
        for i in range(N_DENS_W):
            dd = PFP.dir_dens(dw0, Lw, wsd + 10 + i)
            eta0 = abs(float(np.sum(dd * slw)))
            okc = okc and eta0 <= ETA0_BAR \
                * max(float(np.sum(np.abs(dd * slw))), 1.0)
            dirs_w.append(("DENS%02d" % i, dd))
        dirs_wu = [(n, CF.unit_dir(dd, lag_l1w(dd), REFw))
                   for n, dd in dirs_w]
        bun_w = hess_span_etop(dw0, Lw, dirs_wu, margin_w, m00w)
        dens_iw = [i for i, n in enumerate(bun_w["names"])
                   if n.startswith("DENS")]
        cf_w = bun_w["coef"]
        share_w = float(np.sum(cf_w[dens_iw] ** 2)) \
            / max(float(np.sum(cf_w ** 2)), 1e-300)
        # window-own best repetition + T1 coupling (always)
        cs_w = best_repeat(bun_w, dw0, Lw, Dw, uuw, mmw, nref_w)
        if base_nm != "T1_GRAD_LMAX":
            t1_w = abs(span_cos(bun_w, build_candidate(
                "T1_GRAD_LMAX", dw0, Lw, Dw, uuw, mmw, nref_w)))
        else:
            t1_w = cs_w
        nl_w = null_reference(bun_w, dw0, Lw, SEED_WIN_NULL[kz],
                              NNULL_WIN)
        ok_share = abs(share_w - W_DENS_SHARE_REC[kz]) \
            <= W_DENS_SHARE_TOL
        win_res[kz] = dict(cs=cs_w, t1=t1_w, cls=class_of(cs_w),
                           share=share_w, nmax=max(nl_w),
                           nref=nref_w)
        check("G6%d-window-w%d" % (3 + wi, kz),
              okc and ok_wall and bun_w["fin"] and ok_share,
              "WINDOW w%d (r294 protocol verbatim, seeds %d+): "
              "NREF_w %d == rec (cross %s == NREF+1), theta_up "
              "%.3e, f_ex %.3f, ladder halved %dx; top-axis DENS "
              "share %.3f == r294 %.3f (tol %.2f); window-own "
              "|cos(%s)| = %.3f (T1_w %.3f, null max %.3f, "
              "12-dim span chance ~0.29 disclosed) -> class %s"
              % (kz, wsd, nref_w, str(m0w_meas["cross"]), thw,
                 f_ex, bun_w["n_halve"], share_w,
                 W_DENS_SHARE_REC[kz], W_DENS_SHARE_TOL, base_nm,
                 cs_w, t1_w, max(nl_w), win_res[kz]["cls"]))
    cls_rank = {"BLIND": 0, "PART": 1, "ID": 2}
    cls_w9 = base_cls          # a4: w9 = the adjudicated class
    classes3 = {9: cls_w9}
    classes3.update({kz: win_res[kz]["cls"] for kz in W_LIST})
    n_hold = sum(1 for kz in classes3
                 if cls_rank[classes3[kz]] >= cls_rank[base_cls])
    window_ok = (base_cls == "BLIND") or n_hold >= WIN_CLASS_NEED
    check("G65-window-hardening", True,
          "SEALED WINDOW RULE (class holds on >= %d of 3 "
          "windows): classes %s vs base %s -> %d/3 hold -> "
          "window hardening %s"
          % (WIN_CLASS_NEED,
             str({("w%d" % k): classes3[k]
                  for k in sorted(classes3)}), base_cls, n_hold,
             "PASSED" if window_ok else
             "FAILED -> DOWNGRADE one level (disclosed)"))
    # downgrades
    final_cls = base_cls
    trail = []
    if base_cls != "BLIND":
        if not world_ok:
            final_cls = {"ID": "PART", "PART": "BLIND"}[final_cls]
            trail.append("WORLD-DOWNGRADE")
        if not window_ok and final_cls != "BLIND":
            final_cls = {"ID": "PART", "PART": "BLIND"}[final_cls]
            trail.append("WINDOW-DOWNGRADE")
    if final_cls == base_cls:
        final_verd = base_verd
    elif final_cls == "PART":
        final_verd = "DENS_PARTIAL(%s, |cos| %.3f; %s)" \
            % (base_nm, best_c, "+".join(trail))
    else:
        final_verd = "DENS_WORLD_BLIND(%s %.3f downgraded; %s)" \
            % (base_nm, best_c, "+".join(trail))

    # ---------------- S7 LEG D: bridge table
    section("S7  LEG D -- BRIDGE TABLE (measurement only)")
    if final_cls in ("ID", "PART") and base_nm == "T1_GRAD_LMAX":
        T1v = CAND["T1_GRAD_LMAX"]
        btab = {nm: cos_pair(T1v, CAND[nm])
                for nm in LIB_ELIGIBLE if nm != "T1_GRAD_LMAX"}
        sh_t1_t5 = sub_share(T5cols, T1v)
        check("G70-bridge-table", True,
              "BRIDGE (which arithmetic density carries the L* "
              "gradient itself; raw on-support cosines, ONE "
              "table, no interpretation): %s; T5 share of T1 "
              "%.4f" % (str({k: round(v, 3)
                             for k, v in btab.items()}),
                        sh_t1_t5))
        anomaly = ""
    elif final_cls in ("ID", "PART"):
        t1_val = abs(tab["T1_GRAD_LMAX"][0])
        anomaly = (" THE ANOMALY: %s matches (%.3f) but T1 does "
                   "NOT (%.3f < %.2f) -- DENS would be "
                   "arithmetic but NOT L*-coupled"
                   % (base_nm, best_c, t1_val, COS_PART)
                   if t1_val < COS_PART else "")
        check("G70-bridge-table", True,
              "best match is %s (not T1);%s T1 coupling %.3f "
              "reported in G53" % (base_nm,
                                   anomaly if anomaly
                                   else " no anomaly (T1 also "
                                   ">= PART bar);", t1_val))
    else:
        anomaly = ""
        check("G70-bridge-table", True,
              "FINAL class BLIND (base %s via %s): no bridge "
              "table (sealed: leg D only on final IDENTITY/"
              "PARTIAL); T1 coupling reported in G53"
              % (base_cls, base_nm))

    # ---------------- S8 must-fails + scopes
    section("S8  MUST-FAILS + SCOPE AUDITS")
    G_mut = mutant_hf_noweight(PK9, d9, L9)
    l_m1 = nu_l[0]
    e_m1 = np.zeros(L9)
    e_m1[l_m1] = 1.0
    e_m1[(L9 - l_m1) % L9] = 1.0
    g_an_m1 = float(G_mut @ e_m1)
    g_ref = [r for r in fd_rows if r[0] == l_m1][0]
    dev_m1 = abs(g_an_m1 / g_ref[2] - 1.0)
    check("G80-mustfail-hf-norm", dev_m1 > FD_BAR,
          "m1 WRONG NORMALIZATION (nu weight dropped from "
          "p*(y)^2): mutant directional derivative off by rel "
          "%.1e >> %.0e vs the measured FD value -- CAUGHT by "
          "the ward" % (dev_m1, FD_BAR))
    fp9 = np.asarray(PK9["fp"], np.int64)
    dd_m2 = mutant_unprojected_candidate(
        fp9[:40], np.ones(40), L9)
    eta_m2 = abs(float(np.sum(dd_m2 * sl9))) \
        / max(float(np.sum(np.abs(dd_m2 * sl9))), 1e-300)
    check("G81-mustfail-unprojected", eta_m2 > ETA0_BAR,
          "m2 UNPROJECTED CANDIDATE: |eta_0| rel %.1e > %.0e -- "
          "CAUGHT by the exact conservation gate; mass-moving "
          "candidates cannot pass" % (eta_m2, ETA0_BAR))
    bad_hash = mutant_posthoc_library()
    check("G82-mustfail-seal-break", bad_hash != LIB_SEAL,
          "m3 SEAL BREAK (posthoc candidate injected after "
          "evaluation): hash %s != sealed %s -- CAUGHT; the "
          "library is frozen by hash BEFORE the first cosine"
          % (bad_hash[:12], LIB_SEAL[:12]))
    check("G83-mustfail-decoy", decoy_cos <= noise_ref + NULL_PAD,
          "m4 DECOY (pinned random seed %d smuggled through the "
          "candidate pipeline): |cos| %.3f <= noise %.3f + %.2f "
          "-- HELD below the reference; a random direction "
          "cannot fire the identity"
          % (SEED_DECOY, decoy_cos, noise_ref, NULL_PAD))
    hits = []
    for fn_ in CONSTRUCTORS:
        hits += scope_audit(fn_, SCOPE_FORBIDDEN)
    ag_hits = antigate_fragment_audit()
    check("G84-scope-audits", not hits and not ag_hits,
          "the %d sealed source-pure constructors consume "
          "densities/combs/geometry/degrees/seeds ONLY (%s); "
          "the Hesse forms and margin channels are OUTSIDE the "
          "source-pure list and honestly typed measurement-"
          "consuming; fragment audit: %s"
          % (len(CONSTRUCTORS),
             "CLEAN" if not hits else "; ".join(hits),
             "CLEAN" if not ag_hits else "; ".join(ag_hits)))

    # ---------------- S9 honesty + verdict
    section("S9  HONESTY LEDGER + VERDICT")
    check("G90-honesty-ledger", True,
          "cosines, captures, shares and contrasts are "
          "MEASUREMENTS on finite profile spaces; e_top is "
          "span-limited and the in-span primary metric is the "
          "sealed honest reading of exactly that limitation "
          "(raw/lag/capture disclosed per candidate); the Hesse "
          "forms consume measured margins (r292/r294 protocol); "
          "the control Richardson typing and the 12-dim window "
          "chance level are disclosed; a passing class is a "
          "finite-window alignment statement, not a mechanism "
          "theorem")
    check("G95-stoplist", True,
          "STOP LIST held: NO L* claim, no bound mechanism, no "
          "asymptotic law, no derived 5/7, no new survival "
          "predictor, no posthoc candidate, no posthoc window, "
          "no RH claim; what the round adds: the sealed identity "
          "adjudication of the DENS top axis against the "
          "candidate library with the T1 coupling number and "
          "the world/window hardening; r243..r295 stand")
    parts_v = [final_verd]
    parts_v.append("T1_COUPLING(cos_span %+.3f, raw %+.3f, lag "
                   "%+.3f, capture %.3f)"
                   % (t1c[0], t1c[1], t1c[2], t1c[3]))
    parts_v.append("COS_TABLE(span %s; noise %.3f; T5 root %.3f)"
                   % (str({nm: round(tab[nm][0], 3)
                           for nm in LIB_ELIGIBLE}), noise_ref,
                      cos_t5))
    parts_v.append("WORLD_CONTRAST(EPST %s %.3f, SCR %s %.3f)"
                   % ("COLLAPSED" if ctrl_res["EPST"]["coll"]
                      else "HELD", ctrl_res["EPST"]["cs"],
                      "COLLAPSED" if ctrl_res["SCR"]["coll"]
                      else "HELD", ctrl_res["SCR"]["cs"]))
    parts_v.append("WINDOW_TRANSPORT(%s; shares w7 %.3f / w9 "
                   "%.3f / w11 %.3f)"
                   % (str({("w%d" % k): classes3[k]
                           for k in sorted(classes3)}),
                      win_res[7]["share"], share_dens9,
                      win_res[11]["share"]))
    if anomaly:
        parts_v.append("ANOMALY(%s)" % anomaly.strip())
    verd = " + ".join(parts_v)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G96-verdict", npass == len(CHECKS),
          "%s -- the DENS-identity fork answered by measurement; "
          "NO L* claim, NO RH claim" % verd)
    return finish(smoke)


def finish(smoke):
    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"""vdc_chain_provenance_probe -- PRIME.PORT.L2.
VDC_CHAIN_PROVENANCE.01 (round 297): the CHAIN ORIGIN of the
vdC input -- can the P-variance / autocorrelation scaling (the
INPUT of the proven v964-S0 van der Corput inequality) be derived
SOURCE-PURELY from the chain structure, as a provable statement
instead of a measurement?  Context (sealed record inputs): wave 7
(v964) proved the vdC inequality |sum P|^2 <= ((m + H - 1)/H) x
sum_{|h|<H} (1 - |h|/H) A(h) EXACTLY in Fractions (S0 section,
covering identity + Cauchy-Schwarz, wrong-prefactor must-fail) and
ledgered PRIME.PORT.L2.VDC_LEMMA.01 [O] with the documented rest:
the CHAIN PROVENANCE of the input scaling; r287 (SPEC 761d88fa)
measured delta'(F2_VDC) = +0.309 > DELTA_NEED = 0.21 world-blind
at the frozen H = ceil(sqrt(m)), cert 6/7 + 38/42; r272 located
the task (a mechanism must supply N^{-delta'}, delta' > 0.21, of
the available gamma_true = 0.45) and r273 showed the decay is
GENERIC (root-scale baseline, perturbation-insensitive -- no
arithmetic fingerprint); r270 certified kz15 exact-finitely
(reserve 0.0268).  Reviewer routing (r296 fork): the DENS lane is
closed (DENS_WORLD_BLIND) -- resources move to the L2 front, "the
mathematically more classical attack surface": vdC theorem
(proved) + input scaling (open) = delta' > 0.21 as a theorem on
the generic half, with a 0.24 exponent pad.

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

THE OBJECT (r269/r270/r271/r287 machinery imported verbatim):
t_{N-2} = sum_b ct_b (r244 chain rows, r266 eval); F = 0.20 edge
split t = t_edge + R; Z = t_{N-2} + chain, Z_local = t_edge +
chain; maximal same-sign runs of the bx-sorted bulk with masses
M_i and exact signed sums s_i; level-2 blocks (r270 convention,
offset 0) P_j = s_{2j} + s_{2j+1}, odd tail its own block; the
FROZEN vdC window H = max(2, ceil(sqrt(m))); the vdC INPUT
S_F := sum_{|h|<H} (1 - |h|/H) A(h) = (1/H) sum_t W_t^2 (the
Fejer window sum, v964-S0 identity) and A(0) = sum_j P_j^2 (the
P-variance).  Demand scale M_W = sqrt(5/7); DELTA_NEED = 0.21
(r272 record); halves log-slope estimator (r272, deterministic,
exactly additive over products).  EVERY input object here is
SOURCE-PURE (atoms, weights, chain rows, run partition): the
input anatomy needs no truth-side quantity.

LEG 0 -- ANCHOR REGRESSION (record wards, all bands disclosed
r270/r272/r287 record numbers): r287 core bit-near (delta'(F2) =
+0.309 tol 0.01 at the frozen H rule, cert 6/7 exceptions +
38/42 ladder, kz15 F2 miss 0.10 dec tol 0.02); r272 wards
(sp(N, eps_c2) +0.67 tol 0.05, gamma_true +0.453 tol 0.05,
slope(eps_c2/M) +0.196 tol 0.01, exception P-sign alternation
med in [0.34, 0.44]); r270 kz15 reserve in [0.020, 0.035]; the
v964-S0 vdC set RE-COMPUTED (not re-proved) in exact Fractions
on the frozen rational sequences: Fejer window-sum identity,
H-fold covering identity, the vdC inequality at every H with the
H = 1 equality witness, the wrong-prefactor must-fail 14 < 16.

LEG A -- THE INPUT ANATOMY (the target inequality; every slope a
halves log-slope on the N-sorted 42-rung ladder): the exact slope
decomposition slope(eps_F2/M) = (1/2) x [slope(pref) + sigma]
with pref = (m + H - 1)/H and sigma := slope(S_F / M^2) (gated
EXACTLY, additivity bar 1e-9).  delta'(F2) > DELTA_NEED is
therefore EQUIVALENT to the TARGET INEQUALITY (frozen fine-type
TARGET_INEQUALITY_FROZEN):
  sigma  <=  sigma* := 2 x (slope(eps_c2/M) - DELTA_NEED)
                         - slope(pref)
-- the WEAKEST sufficient input bound, all constants printed from
the ladder (expectation from the records: sigma* ~ -0.53 vs the
measured truth sigma ~ -0.72; the 0.24 exponent pad of the lane
in sigma coordinates ~ 0.19).  PAD TABLE: the allowed loss at
every stage of the chain (Fejer step S_F <= H x A(0); block step
A(0) <= 2 sum s_i^2; CS step; mass step) printed as slope
budgets.  Per-rung certification variant printed on the 7
exceptions: S_F < (H/(m + H - 1)) x (M_W - |Z_local|)^2.

LEG B -- CHAIN-PROVENANCE ROUTES (the core; each an exact
per-rung inequality chain on the real builders, each consuming
ONLY source-side objects, AST scope audit; worlds test on
EPSTEIN / SCRAMBLE -- the statement must be world-blind, here a
STRENGTH: the generic half needs no arithmetic):
(B1) THREE-TERM / PAIR-IDENTITY ROUTE: by the r271 alternation
  identity |B_j| = |M_{2j} - M_{2j+1}| EXACTLY, so A(0) =
  sum B_j^2 + [m odd] tail^2 <= gapmax x eps_c2 with gapmax =
  max(pair gaps, tail) and eps_c2 the sealed r269 pair bound:
  eps_B1 = sqrt((m + H - 1) x gapmax x eps_c2) -- a per-rung
  EXACT theorem (vdC + Fejer step + pair identity); the
  provenance question is the SCALING of gapmax/M (the Jacobi
  near-balance of adjacent run masses): measured, printed, and
  the route's delta'_B1 adjudicated against DELTA_NEED.
(B2) ROOT-SCALE / NODE-DENSITY ROUTE (r273 trace): A(0) <=
  2 sum_i M_i^2 <= 2 x maxM x sumM (exact); the node-density
  content: run boundaries are sign changes of the chain value
  ct on the sorted support (Sturm count) -- census: run count m
  vs N (alpha_m), run-length distribution, the mass imbalance
  imb = n_runs x maxM / sumM and its slope, and the ET-style
  equidistribution discrepancies of the boundary positions
  (rank coordinate D_rank and |ct|-mass coordinate D_mass,
  both deterministic sups against the uniform CDF): does pure
  node density supply the decay WITHOUT arithmetic?
(B3) FEJER-POSITIVITY / PARSEVAL ROUTE: per-run Cauchy-Schwarz
  against the |bw| measure: s_i^2 <= (sum_run |bw|) x
  (sum_run |bw| (bx v2 fac)^2), summed: sum s_i^2 <= wrunmax x
  Q_abs (exact); the IDENTITY CANDIDATE: sum_b W x^2 v2^2 ==
  e1^2 n_{N-1} + alh^2 n_{N-2} + gam^2 e3^2 n_{N-3} (diagonal
  form, orthogonality-assuming), where the SYMBOLIC sum
  rule sum w x^2 pi_k^2 = h_{k+1} + a_k^2 h_k + b_k^2 h_{k-1}
  is PROVED in exact Fractions on a small rational measure
  (monic three-term chain, orthogonality + Parseval-type norm
  identity, module-own), and the numeric identity census on the
  REAL chain classifies orthogonality/norm/second-moment
  deviations (sealed classification HOLDS <= 1e-6 / NEAR <=
  1e-3 / BREAKS, relative) on THREE sealed candidate measures:
  BORDER = union(dsm), WINDOW = union(d), WDIFF = WINDOW with
  negated BORDER appended -- MAIN + EPSTEIN + SCRAMBLE (the
  identity must be world-blind); the tautological full-cross
  prediction (recursion residual) is a WARD (bar 1e-9 rel);
  the signed-to-absolute gap (wrunmax x Q_abs) / sum s_i^2 is
  the route's named structural obstruction (the border weights
  are mixed-sign by construction: ws > 0, -vs < 0), measured
  with slope.
FOR EACH ROUTE: validity of every chain step exact on 47 worlds
(bar 1e-9 x scale); delta'_route = slope(eps_c2/M) -
slope(eps_route/M) vs DELTA_NEED; loss anatomy (decades med +
slope per step); exact verification of the chains on >= 3
window sizes (the 42 ladder windows + mains w9/w13; the
symbolic identities on small Fractions windows).

LEG C -- THE THEOREM COMPOSITION (fires ONLY on B success =
adjudicated PROVEN or PARTIAL with slope coverage): CANDIDATE
THEOREM (L2 generic half) printed with every constant explicit:
target inequality (Leg B route) + vdC (v964-S0, proved) + pad
arithmetic -> delta' > 0.21 on the generic half; scope: the 42
measured rungs (N in [142, 878]), h < H = ceil(sqrt(m)); the 7
exceptions cleanly excluded (6 via the r287 F2 certificates,
kz15 via the r270 exact-finite certificate).  The wave-9
promotion candidate -- NOT promoted here.  If Leg B fails,
Leg C is void and the probe documents PRECISELY where every
route breaks (the gap object of the lane).

LEG D -- KZ15 MARGINAL NOTE (small): per route, does eps_route
certify kz15 (need = M_W - |Z_local| at the razor, record
0.292)?  Expected structurally OUTSIDE (the routes majorize
eps_F2 which already misses by 0.10 dec) -- then the r270
exact-finite certification remains the permanent closure
(clarity, not a problem).

LEG E -- WARDS / MUST-FAILS (>= 4 mutants): (m1) WRONG vdC
PREFACTOR m/H (exact Fractions, v964-S0 anchor): breaks on
P = (1,1,1,1), H = 2 with 14 < 16 -- CAUGHT; (m2) PAD-DROPPED
TARGET (sharpness): sigma* computed WITHOUT the pad term
(DELTA_NEED -> 0) composes to delta' = 0 <= 0.21 EXACTLY (bar
1e-12) while the sealed sigma* composes to delta' = DELTA_NEED
exactly -- the pad term is load-bearing; (m3) PERTURBED FEJER
WEIGHT: the window-sum identity with (1 - |h|/(H + 1)) breaks
LOUDLY on the toy sequence (>= 1e-6 abs); (m4) WORLD-BLINDNESS
BREAK: a route builder consuming the withheld terminal drive
key (gift mutant) AND a builder consuming the branch label
(branch-peek mutant) must both be FLAGGED by the AST scope
audit.  Scope hygiene: every route builder consumes source-side
objects only (BOUND_FORBIDDEN set); fragment audit (no fit
primitives); TOY EXACTNESS (bar 1e-14): hand-checked sequences
reproduce the block builder, the vdC window core (H = 2,
sum W^2 = 6, S_F = 3), the B1 chain (Mr = (3,1,2,4,1): gaps
(2,2), tail 1, eps_c2 = 5, gapmax = 2, A0 = 9 <= 10), the B2
chain (sum M^2 = 31 <= maxM x sumM = 44; A0 = 9 <= 2 x 31) and
the B3 CS step on a two-run toy; contribution ward, block
identity, autocorr/Fejer identity per rung; SMOOTH anchor
(alias <= 1e-12, q_N <= 1e-20); mp SAMPLES (dps 60): kz15 (bar
1e-8) + the two deepest rungs (bar 3e-6).

SEALED ADJUDICATION (frozen BEFORE evaluation): per route
VALID = every chain step holds on 47 worlds (bar 1e-9);
SLOPE_OK = delta'_route > DELTA_NEED; IDENT(B3) = orthogonality
+ diag second-moment identity HOLDS (<= 1e-6 rel) on at least
one sealed measure, on MAIN AND both broken-arithmetic
controls.  CHAIN_PROVENANCE_PROVEN(Bx) iff VALID and SLOPE_OK
and every non-universal factor of the composed bound reduces to
a chain identity (operationally reachable only by B3: IDENT
holds AND the signed-to-absolute step is exact, i.e. the bulk
weights are one-signed -- disclosed expectation: structurally
FALSE on the border union, ws > 0 vs -vs < 0);
CHAIN_PROVENANCE_PARTIAL(best route by (SLOPE_OK, delta'),
gap) iff some route is VALID and (SLOPE_OK or IDENT) -- gap =
the named measured factor / slope miss; else
INPUT_STILL_EMPIRICAL(the measured common obstruction).
Leg C fires iff PROVEN or (PARTIAL with SLOPE_OK).

INDEX FIREWALL (binding, r238-r296 discipline): w = window (kz),
N_w = builder depth, k/n = chain degree; ground truth (branch
labels, the true R/t/Z values) enters GATES and census tables
only; no zero/prime oracles anywhere (AST firewall); no fit
primitives (fragment audit).  MACHINERY IMPORTED VERBATIM: r269
PBB.mask_edge + PBB.runs_split + PBB.bound_pairsum +
PBB.mp_drive, r287 L2D.blocks_level2 + L2D.bound_vdc +
L2D.vdc_window + L2D.halves_slope + L2D.autocorr_full, r244
BH.wpack + BH.spearman, r257 CT.union_arrays, r260
TX.drive_arrays, r263 CA.g_gap, r266 BR.eval_scaled, v881 PIK,
r243 PB.smooth_comb.  B PROVENANCE: B_w = S_{N-2} + 5/7
(r241/r243 IMPORTED floor, never fitted).  COFINAL LADDER
(pre-sealed): frame-A h <= 900, 42 rungs, (N, kz)-sorted;
exception set {kz15, 20, 22, 36, 38, 39, 52}.

SEALED CONSTANTS: MAIN windows (9, 13); controls w9 EPSTEIN /
SCRAMBLE(seed 1) / SMOOTH, flips 25/21/27; H_CAP 900; B57 = 5/7;
M_W = sqrt(5/7); CHEAP_EXPECT 35; EXC_KZ_EXPECT (15, 20, 22, 36,
38, 39, 52); EDGE_F 0.20 (FROZEN); PAIR_OFFSET 0 (FROZEN);
DELTA_NEED 0.21; H rule = max(2, ceil(sqrt(m))) (FROZEN);
DEG_OFFS (1, 0, -1) around N-2 (the recursion triple); MEAS =
(BORDER, WINDOW, WDIFF) (FROZEN candidate measures); ID_HOLDS
1e-6; ID_NEAR 1e-3 (relative classification bars); REC_BAR 1e-9
(tautological recursion ward, rel); TB_WARD bars 1e-9 main
N <= 400 / 3e-6 deep / 1e-6 controls; VAL_BAR 1e-9; ID_BAR
1e-12; AC_BAR 1e-9; ADD_BAR 1e-9 (slope additivity); TOY_BAR
1e-14; SHARP_BAR 1e-12 (m2 pad arithmetic); MUT_MIN 1e-6;
R287_DELTA_F2 +0.309 tol 0.01; R287_CERT (6, 38); R287_KZ15_MISS
0.10 tol 0.02; R272_SP_EPS +0.67 tol 0.05; R272_GAMMA_TRUE
0.453 tol 0.05; R272_SL_C2 +0.196 tol 0.01; R270_ALT_BAND
(0.34, 0.44); RESERVE_BAND (0.020, 0.035); MP_DPS 60; MP_T_BAR
1e-8 (kz15); MP_DEEP_BAR 3e-6 (two deepest rungs); SM_Q_BAR
1e-20; SM_ALIAS_BAR 1e-12; KZ_ANCHOR 15; runtime <= 1800 s;
smoke = w9 + controls + Fractions section + toys + scope audits
+ route numerics + identity census at w9 (ladder, slopes,
target inequality, adjudication, mp wards skipped).  DISCLOSED
PRE-SPEC INPUT (no scratch run of this probe): every
reproduction band is an r270/r272/r287 RECORD number adopted
as-is; sigma*'s expected magnitude is derived arithmetic from
the r287 record slopes, disclosed above; nothing tuned.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  TARGET_INEQUALITY_FROZEN(sigma* with all constants, sigma
    measured, pad table)
+ ROUTE_TABLE(B1/B2/B3: valid n/47, delta'_route, identity
    status, break point)
+ [exactly one of] CHAIN_PROVENANCE_PROVEN(Bx, ...) /
    CHAIN_PROVENANCE_PARTIAL(Bx, gap) /
    INPUT_STILL_EMPIRICAL(the measured common obstruction)
+ [iff fired] CANDIDATE_THEOREM(L2 generic half, constants)
+ KZ15_NOTE(covered / structurally outside; r270 stands)
+ [if any control gate breaks] LOCAL_MODEL_MAIN_FITTED.
Honesty before beauty: no verdict claims a cofinal law or an
asymptotic mechanism; every slope is MEASURED on 42 rungs only;
a VALID + SLOPE_OK route is a per-rung exact theorem WITH A
MEASURED LADDER EXPONENT (the r287 F2 typing), not a proof of
the m-dependence; the exception scalar's positivity beyond the
measured 42 stays OPEN; r243-r296 stand.

RECORD TABLES (frozen from the record run; calibration protocol:
smoke pass 1 CRASHED on an index bug in the B1 builder --
amendment a1 (the r287 pairing-index convention restored, a code
bugfix, no bar or rule touched); smoke pass 2 = 27/27; amendment
a2 after smoke pass 2 (REPORTING ONLY: the ROUTE_TABLE identity
field shows the best sealed measure, the G61 text carries the
measure-transfer honesty clause, the break label renamed -- no
bar, band, rule or verdict rule moved); calibration pass 1 =
first full evaluation, 27/27 gates, wall 47.8 s, NO further
amendment; pass 2 = the record run, identical to pass 1 in every
printed figure up to WALL and the source line numbers inside the
scope-audit prints (shifted by this insertion); the only
post-freeze edit is this record-table insertion, which IS the
protocol):
CAL_VERDICT = TARGET_INEQUALITY_FROZEN(sigma* -0.516, sigma
-0.714, margin 0.198 in sigma = 0.099 in delta') + ROUTE_TABLE(
B1_PAIRGAP valid 47/47 delta' -0.112 BREAK@gapmax scaling;
B2_NODEDENS valid 47/47 delta' -0.097 BREAK@mass imbalance
growth; B3_PARSEVAL valid 47/47 delta' -0.097 IDENT HOLDS(
WINDOW) BREAK@measure transfer + signed-to-absolute gap) +
CHAIN_PROVENANCE_PARTIAL(B3_PARSEVAL, gap: slope miss 0.307) +
KZ15_NOTE(structurally outside: B1 0.57 / B2 0.86 / B3 0.91
dec; r270 exact-finite certificate remains the permanent
closure).
Key numbers.  S2: contribution ward 2.1e-13 main / 3.9e-13 deep
/ 2.4e-8 controls; block + autocorr identities worst 6.3e-16 /
2.7e-15 on 47 worlds; r272 wards exact (sp +0.67, gamma_true
+0.453, reserve 0.0268, alt med 0.39); r287 F2 regression exact
(delta' +0.309, cert 6/7 + 38/42, kz15 miss 0.096 dec, sl_c2
+0.196).  S3: v964-S0 recheck green in Fractions (window
identity + covering + vdC at every H + witness 36 == 36; m1
wrong prefactor 14 < 16 CAUGHT; m3 perturbed Fejer breaks by
2.00e+0 LOUD); the SYMBOLIC B3 sum rule PROVED exact on the
rational 4-node measure (orthogonality dev 0, Parseval-type
x^2 identity dev 0, pure Fractions); m4a/m4b FLAGGED by the
scope audit.  S4 (Leg A): additivity dev 2.6e-16; sl_c2 +0.196,
sl_pref +0.489, sigma = -0.714 <= sigma* = -0.516: THE TRUTH
SATISFIES THE TARGET INEQUALITY with 0.198 sigma margin -- what
is missing is not room, it is provenance; pad table (slope
budgets): Fejer step +0.607, block step -0.012, CS step +0.217;
per-exception certification form: kz15 +0.19 dec OVER, the
other six all under (kz20 -0.25 .. kz22 -0.83); m2 pad
arithmetic exact (0.210000000000 / 0.0).  S5 B1 (valid 47/47):
delta'_B1 = -0.112; gapmax/M slope -0.535 (sufficient <=
-1.178): the MAX pair gap falls far slower than the mean
amplitude (r272 B_amp -0.81) -- the Jacobi near-balance is a
MEAN statement, its extreme is not chain-controlled; loss med
0.88 dec.  S6 B2 (valid 47/47): delta'_B2 = -0.097; alpha_m
+1.006, run-length med 2.0 at every depth; D_rank med 0.024
(slope -0.42, falling!) vs D_mass med 0.154: the boundary
POSITIONS are near-equidistributed -- provable terrain -- but
the MASS is not; the obstruction is the imbalance n x maxM /
sumM slope +0.244 (max/mean run mass GROWS with N): pure node
density supplies the COUNT, not the decay (the r273 root-scale
mechanism sits in the mass profile).  S7 B3 (valid 47/47): THE
SURPRISE OF THE ROUND -- the chain is EXACTLY ORTHOGONAL w.r.t.
the WINDOW measure (union(d)): cross med 0.000, diag identity
dev 0.000, worst 0.000 across kz15/kz20/mains/EPST/SCR, while
BORDER (cross med 1.101) and WDIFF (1.086) BREAK: the Parseval
attachment point EXISTS -- the symbolic sum rule holds verbatim
on the window union; what remains is the MEASURE TRANSFER
(the vdC input lives on the BORDER union) and the signed-to-
absolute gap (wrx x Qabs)/sum s^2 med 4.3, slope +0.217 (the
mixed-sign border weights); recursion ward 7.5e-13; delta'_B3 =
-0.097, wrunmax slope -0.570.  S9: no route SLOPE_OK; B3 is
VALID + IDENT => CHAIN_PROVENANCE_PARTIAL(B3, slope miss
0.307); Leg C VOID; kz15 structurally outside for all three
routes, r270 stands.  SMOOTH alias 2.4e-14, q_N 4.2e-25; mp
wards kz15 2.9e-10, kz64 9.3e-9, kz52 6.6e-8; every chain step
holds on EPST/SCR by the same algebra (world-blind, 47/47).
READING (typed, no upgrade): the round DELIVERS the frozen
target inequality (sigma <= 2(sl_c2 - 0.21) - sl_pref, all
constants live) and shows the truth clears it with ~0.2 sigma
margin -- but ALL THREE classical provenance routes miss the
slope at the same wall: every source-pure majorization of the
P-variance through MAGNITUDES (|B_j|, M_i, |bw|) pays a
max/mean imbalance factor that grows (+0.22..+0.24 slope) and
eats the pad; the SIGNED structure that carries sigma = -0.71
(the pairwise cancellation already absorbed into the P_j
magnitudes, r287) is exactly what magnitude chains cannot see.
The two REAL assets the round leaves for the lane: (1) the
chain IS exactly orthogonal on the window union -- the Parseval
sum rule attaches there verbatim, so the missing piece is a
bordered-form transfer statement (window -> border union), a
concrete named object; (2) the run-boundary positions are
near-equidistributed with FALLING discrepancy (D_rank med
0.024, slope -0.42) -- the node-count side is provable terrain;
the mass imbalance (+0.24) is the single quantity a future
equidistribution argument must control.  Runtime 47.8 s full /
0.7 s smoke; run1/run2 identical up to WALL.  AMENDMENTS AFTER
FREEZE: NONE beyond the disclosed a1/a2 (records inserted per
protocol; no bar, band, rule or verdict rule moved).

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
from fractions import Fraction as Fr

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 cancellation_adjudication_probe as CA   # noqa: E402 r263
import coupledtau_probe as CT                  # noqa: E402 r257
import terminal_crossratio_probe as TX         # noqa: E402 r260
import border_resolvent_identity_probe as BR   # noqa: E402 r266
import phase_bulk_bound_probe as PBB           # noqa: E402 r269
import l2_deterministic_cancellation_probe as L2D  # noqa: E402 r287
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)
CTRL_FLIPS = {"EPSTEIN": 25, "SCRAMBLE": 21, "SMOOTH": 27}
H_CAP = 900
B57 = 5.0 / 7.0
M_W = math.sqrt(B57)
CHEAP_EXPECT = 35
EXC_KZ_EXPECT = (15, 20, 22, 36, 38, 39, 52)
TB_WARD_BAR = 1e-9
TB_WARD_BAR_DEEP = 3e-6
TB_WARD_BAR_CTRL = 1e-6
DEEP_N = 400
VAL_BAR = 1e-9
ID_BAR = 1e-12
AC_BAR = 1e-9
ADD_BAR = 1e-9
TOY_BAR = 1e-14
SHARP_BAR = 1e-12
MUT_MIN = 1e-6
EDGE_F = 0.20
PAIR_OFFSET = 0
DELTA_NEED = 0.21
DEG_OFFS = (1, 0, -1)
MEAS = ("BORDER", "WINDOW", "WDIFF")
ID_HOLDS = 1e-6
ID_NEAR = 1e-3
REC_BAR = 1e-9
R287_DELTA_F2 = 0.309
R287_DF2_TOL = 0.01
R287_CERT = (6, 38)
R287_KZ15_MISS = 0.10
R287_KZ15_TOL = 0.02
R272_SP_EPS = 0.67
R272_SP_TOL = 0.05
R272_GAMMA_TRUE = 0.453
R272_GT_TOL = 0.05
R272_SL_C2 = 0.196
R272_SL_TOL = 0.01
R270_ALT_BAND = (0.34, 0.44)
RESERVE_BAND = (0.020, 0.035)
MP_DPS = 60
MP_T_BAR = 1e-8
MP_DEEP_BAR = 3e-6
SM_Q_BAR = 1e-20
SM_ALIAS_BAR = 1e-12
KZ_ANCHOR = 15
ROUTE_ORDER = ("B1_PAIRGAP", "B2_NODEDENS", "B3_PARSEVAL")

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; every readout "
                       "consumes node positions + signed weights + "
                       "the r244 chain rows; ground truth (branch "
                       "labels, true R/t/Z) enters gates and census "
                       "tables only"
                       if not bad else "; ".join(bad))


def antigate_fragment_audit():
    """AST scan for forbidden method families (identifiers only;
    the fragment table itself is assembled from split strings)."""
    frags = ("cand_" + "unroll", "poly" + "fit", "curve_" + "fit",
             "lst" + "sq", "mini" + "mize", "Line" + "arRegression")
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    hits = []
    for node in ast.walk(tree):
        nm = None
        if isinstance(node, ast.Attribute):
            nm = node.attr
        elif isinstance(node, ast.Name):
            nm = node.id
        elif isinstance(node, ast.FunctionDef):
            nm = node.name
        if nm and any(f in nm for f in frags):
            hits.append("%s@%d" % (nm, node.lineno))
    return hits


BOUND_FORBIDDEN = {"t" + "_term", "Z", "Zl", "margin", "M" + "_W",
                   "loss", "R" + "_bulk", "truth", "rho",
                   "g" + "_branch", "need"}


def scope_audit(funcname, forbidden):
    """walk ONLY the named function's subtree; flag any withheld/
    truth-side identifier or dict key from the sealed set."""
    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 forbidden:
                    hits.append("%s@%d" % (nm, sub.lineno))
    return hits


# ---------------- v964-S0 recheck machinery (exact Fractions; the
# ---------------- proven vdC set RE-COMPUTED, not re-proved)
def fr_autocorr(P, h):
    m = len(P)
    return sum(P[j] * P[j + h] for j in range(m - h))


def fr_window_sums(P, H):
    m = len(P)
    out = []
    for t in range(-(H - 1), m):
        out.append(sum(P[j] for j in range(max(0, t),
                                           min(m, t + H))))
    return out


def fr_fejer_windowsum(P, H, perturbed=False):
    """sum_{|h|<H} (1 - |h|/H) A(h); the m3 mutant flag replaces
    the Fejer weight by (1 - |h|/(H + 1)) -- must break the
    window-sum identity LOUDLY."""
    den = H + 1 if perturbed else H
    tot = Fr(0)
    for h in range(-(H - 1), H):
        tot += (1 - Fr(abs(h), den)) * fr_autocorr(P, abs(h))
    return tot


def fr_vdc_bound_sq(P, H, prefactor_m_only=False):
    m = len(P)
    pref = Fr(m, H) if prefactor_m_only else Fr(m + H - 1, H)
    return pref * fr_fejer_windowsum(P, H)


FR_SEQS = (
    [Fr(2), Fr(-2), Fr(1)],
    [Fr(1), Fr(1)],
    [Fr(1), Fr(1), Fr(1), Fr(1)],
    [Fr(3, 7), Fr(-2, 9), Fr(5, 11), Fr(1, 4), Fr(1, 3),
     Fr(-3, 8), Fr(2, 5), Fr(7, 13), Fr(-1, 6)],
    [Fr(2, 3), Fr(-6, 5), Fr(1, 2), Fr(-3, 7), Fr(1),
     Fr(1, 3), Fr(-1, 2), Fr(5, 4)],
    [Fr((-1) ** j * (j + 1), 2 * j + 3) for j in range(12)],
)


def fr_symbolic_sumrule():
    """the SYMBOLIC B3 sum rule, module-own, exact Fractions: on
    the rational 4-node measure x = (0, 1, 2, 3), w = (1, 2, 1, 3)
    build the monic three-term chain pi_0..pi_3 (a_k = <x pi_k,
    pi_k>/h_k, b_k = h_k/h_{k-1}) and verify (i) orthogonality
    sum w pi_a pi_b == 0 for a != b, (ii) the Parseval-type
    second-moment identity sum w x^2 pi_k^2 == h_{k+1} + a_k^2
    h_k + b_k^2 h_{k-1} for k = 1 (all exact)."""
    xs = [Fr(0), Fr(1), Fr(2), Fr(3)]
    ws = [Fr(1), Fr(2), Fr(1), Fr(3)]
    n = len(xs)
    pis = [[Fr(1)] * n]
    a_ = []
    b_ = []
    hs = [sum(w * p * p for w, p in zip(ws, pis[0]))]
    for k in range(3):
        ak = sum(w * x * p * p for w, x, p in zip(ws, xs, pis[k])) \
            / hs[k]
        bk = (hs[k] / hs[k - 1]) if k >= 1 else Fr(0)
        nxt = []
        for i in range(n):
            v = (xs[i] - ak) * pis[k][i]
            if k >= 1:
                v -= bk * pis[k - 1][i]
            nxt.append(v)
        pis.append(nxt)
        a_.append(ak)
        b_.append(bk)
        hs.append(sum(w * p * p for w, p in zip(ws, nxt)))
    worst_orth = Fr(0)
    for a in range(4):
        for b in range(a):
            worst_orth = max(worst_orth,
                             abs(sum(w * pis[a][i] * pis[b][i]
                                     for i, w in enumerate(ws))))
    k = 1
    lhs = sum(w * x * x * p * p
              for w, x, p in zip(ws, xs, pis[k]))
    rhs = hs[k + 1] + a_[k] ** 2 * hs[k] + b_[k] ** 2 * hs[k - 1]
    return worst_orth, abs(lhs - rhs)


# ---------------- sealed source-pure route builders.  Every route
# ---------------- builder consumes ONLY source-side objects (run
# ---------------- masses, atoms, weights, chain rows); the withheld
# ---------------- terminal drive key, the branch label and every
# ---------------- target-side identifier are forbidden in scope
# ---------------- (AST audit against BOUND_FORBIDDEN).
def route_b1(Mr, H):
    """B1 THREE-TERM / PAIR-IDENTITY route: by the exact r271
    alternation identity |B_j| = |M_{2j} - M_{2j+1}|: A(0) <=
    gapmax x eps_c2 with gapmax = max(pair gaps, tail); composed
    eps_B1 = sqrt((m_blk + H - 1) x gapmax x eps_c2)."""
    nr = len(Mr)
    if nr == 0:
        return dict(eps=0.0, gapmax=0.0, a0b=0.0, e_c2=0.0)
    gaps = [abs(Mr[i] - Mr[i + 1])
            for i in range(PAIR_OFFSET, nr - 1, 2)]
    odd = (nr - PAIR_OFFSET) % 2 == 1
    tail = Mr[-1] if odd else 0.0
    vals = gaps + ([tail] if odd else [])
    gapmax = max(vals) if vals else 0.0
    e_c2 = sum(gaps) + tail
    m_blk = (nr + 1) // 2
    a0_bound = gapmax * e_c2
    eps = math.sqrt(max((m_blk + H - 1) * a0_bound, 0.0))
    return dict(eps=eps, gapmax=gapmax, a0b=a0_bound, e_c2=e_c2)


def route_b2(Mr, H):
    """B2 ROOT-SCALE / NODE-DENSITY route: A(0) <= 2 sum M_i^2 <=
    2 x maxM x sumM (exact); composed eps_B2 = sqrt((m_blk + H -
    1) x 2 x maxM x sumM); imbalance = n_runs x maxM / sumM."""
    nr = len(Mr)
    if nr == 0:
        return dict(eps=0.0, mx=0.0, sm=0.0, m2=0.0, imb=0.0)
    mx = max(Mr)
    sm = sum(Mr)
    m2 = sum(v * v for v in Mr)
    m_blk = (nr + 1) // 2
    eps = math.sqrt((m_blk + H - 1) * 2.0 * mx * sm)
    return dict(eps=eps, mx=mx, sm=sm, m2=m2,
                imb=nr * mx / max(sm, 1e-300))


def route_b3(bw_runs, f_runs, H):
    """B3 FEJER / PARSEVAL route: per-run Cauchy-Schwarz against
    the |bw| measure: s_i^2 <= (sum_run |bw|) x (sum_run |bw|
    f^2) with f = bx v2 fac; summed: sum s_i^2 <= wrunmax x
    Q_abs; composed eps_B3 = sqrt((m_blk + H - 1) x 2 x wrunmax
    x Q_abs)."""
    nr = len(bw_runs)
    if nr == 0:
        return dict(eps=0.0, wrx=0.0, qabs=0.0, cs_sum=0.0)
    wr = [float(np.sum(np.abs(w))) for w in bw_runs]
    qr = [float(np.sum(np.abs(w) * f * f))
          for w, f in zip(bw_runs, f_runs)]
    wrx = max(wr)
    qabs = sum(qr)
    cs_sum = sum(a * b for a, b in zip(wr, qr))
    m_blk = (nr + 1) // 2
    eps = math.sqrt((m_blk + H - 1) * 2.0 * wrx * qabs)
    return dict(eps=eps, wrx=wrx, qabs=qabs, cs_sum=cs_sum)


def mutant_gift_bound(rc, Mr):
    """m4a MUST-FAIL MUTANT: a 'route bound' oriented by the
    withheld ground-truth terminal drive key -- the scope audit
    must FLAG this."""
    s = math.copysign(1.0, rc["t_term"])
    return s * route_b1(Mr, 2)["eps"]


def mutant_branch_peek(rc, Mr):
    """m4b MUST-FAIL MUTANT (world-blindness break simulated): a
    'route bound' that consumes the branch label to pick its
    constant -- the scope audit must FLAG this."""
    c = 0.5 if rc["g_branch"] >= 0.0 else 2.0
    return c * route_b2(Mr, 2)["eps"]


def chain_quads(rows, N, X, W):
    """the B3 identity census objects on one candidate measure
    (X, W): scaled chain values v_k at the recursion triple
    degrees, norms n_k = sum W v_k^2, normalized crosses, the
    second moment q2 = sum W x^2 v_{N-2}^2, the tautological
    full-cross prediction (recursion ward) and the diagonal-only
    (orthogonality-assuming) prediction."""
    degs = [N - 2 + o for o in DEG_OFFS]        # N-1, N-2, N-3
    v = {d: BR.eval_scaled(rows, X, d) for d in degs}
    n_ = {d: float(np.sum(W * v[d] * v[d])) for d in degs}
    cr = {}
    for i, a in enumerate(degs):
        for b in degs[:i]:
            den = math.sqrt(max(abs(n_[a]) * abs(n_[b]), 1e-300))
            cr[(a, b)] = float(np.sum(W * v[a] * v[b])) / den
    # recursion coefficients at degree N-2 (scaled coordinates)
    alh = rows[N - 2]["alh"]
    gam = rows[N - 3]["gam_next"]
    e1 = math.exp(rows[N - 1]["Ls"] - rows[N - 2]["Ls"])
    e3 = math.exp(rows[N - 3]["Ls"] - rows[N - 2]["Ls"])
    c = {N - 1: e1, N - 2: alh, N - 3: gam * e3}
    q2 = float(np.sum(W * X * X * v[N - 2] * v[N - 2]))
    pred_full = 0.0
    for a in degs:
        for b in degs:
            pred_full += c[a] * c[b] * float(np.sum(W * v[a] * v[b]))
    pred_diag = sum(c[d] * c[d] * n_[d] for d in degs)
    return dict(n=n_, cr=cr, q2=q2, pf=pred_full, pd=pred_diag)


# ---------------------------------------------- toy exact tools
def toy_routes():
    """hand-checked deterministic sequences: the B1/B2/B3 chains
    must reproduce EXACTLY (bar 1e-14)."""
    worst = 0.0
    # runs Mr = (3,1,2,4,1), signs alternating: s = (3,-1,2,-4,1)
    Mr = [3.0, 1.0, 2.0, 4.0, 1.0]
    S = [3.0, -1.0, 2.0, -4.0, 1.0]
    P = L2D.blocks_level2(S)                    # [2, -2, 1]
    A0 = sum(v * v for v in P)                  # 9
    b1 = route_b1(Mr, 2)
    # gaps (2, 2), tail 1 -> gapmax 2, e_c2 5, a0_bound 10 >= 9
    worst = max(worst, abs(b1["gapmax"] - 2.0),
                abs(b1["e_c2"] - 5.0), abs(b1["a0b"] - 10.0))
    worst = max(worst, max(A0 - b1["a0b"], 0.0))
    # eps_B1 = sqrt((3 + 2 - 1) * 10) = sqrt(40)
    worst = max(worst, abs(b1["eps"] - math.sqrt(40.0)))
    b2 = route_b2(Mr, 2)
    # sum M^2 = 31 <= maxM x sumM = 44; A0 = 9 <= 2 x 31
    worst = max(worst, abs(b2["m2"] - 31.0), abs(b2["mx"] - 4.0),
                abs(b2["sm"] - 11.0))
    worst = max(worst, max(b2["m2"] - b2["mx"] * b2["sm"], 0.0))
    worst = max(worst, max(A0 - 2.0 * b2["m2"], 0.0))
    # eps_B2 = sqrt((3 + 2 - 1) * 2 * 44) = sqrt(352)
    worst = max(worst, abs(b2["eps"] - math.sqrt(352.0)))
    # B3 CS on a two-run toy: run1 w = (1, 2), f = (1, -1) ->
    # s1 = w.f = -1, |s1|^2 = 1 <= (3)(3) = 9; run2 w = (-1,),
    # f = (2,) -> s2^2 = 4 <= (1)(4)
    bwr = [np.array([1.0, 2.0]), np.array([-1.0])]
    fr_ = [np.array([1.0, -1.0]), np.array([2.0])]
    b3 = route_b3(bwr, fr_, 2)
    worst = max(worst, abs(b3["wrx"] - 3.0),
                abs(b3["qabs"] - 7.0), abs(b3["cs_sum"] - 13.0))
    s1 = float(np.sum(bwr[0] * fr_[0]))
    s2 = float(np.sum(bwr[1] * fr_[1]))
    worst = max(worst, max(s1 * s1 - 9.0, 0.0),
                max(s2 * s2 - 4.0, 0.0))
    worst = max(worst,
                max(s1 * s1 + s2 * s2 - b3["cs_sum"], 0.0),
                max(b3["cs_sum"] - b3["wrx"] * b3["qabs"], 0.0))
    # vdC window core reproduction on P (r287 toy): H = 2,
    # sum W^2 = 6, S_F = 3, eps = sqrt(6)
    f2 = L2D.bound_vdc(P)
    worst = max(worst, abs(f2["H"] - 2), abs(f2["s2"] - 6.0),
                abs(f2["s2"] / f2["H"] - 3.0),
                abs(f2["eps"] - math.sqrt(6.0)))
    # Fejer step S_F <= H x A(0): 3 <= 18
    worst = max(worst, max(f2["s2"] / f2["H"] - f2["H"] * A0, 0.0))
    return worst


# --------------------------------------------------------------- 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("vdc_chain_provenance_probe -- PRIME.PORT.L2."
          "VDC_CHAIN_PROVENANCE.01 (round 297)")
    print("SPEC_SHA %s   R269_SHA %s (imported)   R287_SHA %s "
          "(imported)"
          % (SPEC_SHA[:16], PBB.SPEC_SHA[:16], L2D.SPEC_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 + controls + Fractions section "
                        "+ toys + scope audits + route numerics + "
                        "identity census at w9; ladder, slopes, "
                        "target inequality, adjudication, mp wards "
                        "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,
          "THE L2 CHAIN-PROVENANCE ROUND (reviewer routing after "
          "the r296 DENS close): the vdC machine is a THEOREM "
          "(v964-S0, exact Fractions) -- its INPUT (the P-variance"
          " / autocorrelation scaling) is so far only MEASURED; "
          "this round freezes the weakest sufficient input bound "
          "(TARGET_INEQUALITY, Leg A) and tests THREE source-pure "
          "chain-provenance routes (B1 pair-identity, B2 node-"
          "density/root-scale per the r273 trace, B3 Fejer/"
          "Parseval with the symbolic sum rule proved in "
          "Fractions); DELTA_NEED %.2f (r272 record), pad "
          "gamma_true 0.45 (r272/r273: generic, perturbation-"
          "insensitive); world-blind validity ADMISSIBLE (L2 is "
          "the generic half); ALL bars, rules and verdicts sealed "
          "BEFORE evaluation (pre-spec input = r270/r272/r287 "
          "record numbers, disclosed)" % DELTA_NEED)

    # ---------------- S1: census + controls (r287 scaffold verbatim)
    section("S1  CENSUS + CONTROLS")
    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)
    if smoke:
        ladder = []
        okL = True
    else:
        kzs = [kz for kz in core.frame_a_zones()
               if PIK.build_rung(kz)["h"] <= H_CAP]
        ladder = [BH.wpack(kz) for kz in kzs]
        ladder.sort(key=lambda p: (p["N"], p["kz"]))
        okL = (len(ladder) == 42
               and all(p["nf"] is None for p in ladder))
    check("G10-census-controls", okC and okCf and okL,
          "MAIN free prefix positive at full depth (%s, N = %s); "
          "control flips re-derived %s; cofinal ladder %d rungs "
          "POSITIVE_PREFIX %s, N in [%s, %s]"
          % (str(sorted(packs)),
             str({t: packs[t]["N"] for t in packs}),
             str({c: ctrl[c]["nf"] for c in ctrl}),
             len(ladder),
             "42/42" if okL and ladder else ("n/a (SMOKE)"
                                             if smoke else "FAIL"),
             ladder[0]["N"] if ladder else "-",
             ladder[-1]["N"] if ladder else "-"))

    pool = ladder if not smoke else [packs["w9"]]
    mains = [packs["w%d" % kz] for kz in windows]

    def rung_rec(p):
        N = p["N"]
        rows = p["rows"]
        r, t, ap, bp = TX.drive_arrays(rows, N)
        g = CA.g_gap(r[:N - 1], t, ap, bp)
        chain = ap[N - 2] * r[N - 2] + bp[N - 2] * r[N - 3]
        Z = t[N - 2] + chain
        xu, wu = CT.union_arrays(p["d"])
        bx, bw = CT.union_arrays(p["dsm"])
        lo = min(float(np.min(xu)), float(np.min(bx)))
        hi = max(float(np.max(xu)), float(np.max(bx)))
        v2 = BR.eval_scaled(rows, bx, N - 2)
        fac = math.exp(rows[N - 2]["Ls"] - rows[N - 1]["Ls"]) \
            / math.sqrt(abs(rows[N - 1]["eta"]))
        ct = bw * bx * v2 * fac
        o = np.argsort(bx, kind="stable")
        return dict(kz=p["kz"], N=N, g_branch=g, Z=Z, chain=chain,
                    t_term=float(t[N - 2]), ct=ct, bx=bx, bw=bw,
                    v2=v2, fac=fac, xu=xu, wu=wu, o=o, lo=lo,
                    hi=hi, p=p)

    recs = [rung_rec(p) for p in pool]
    mrecs = [rung_rec(p) for p in mains]
    crecs = {c: rung_rec(ctrl[c]) for c in ctrl}
    cheap = [rc for rc in recs if rc["g_branch"] >= 0.0]
    exc = [rc for rc in recs if rc["g_branch"] < 0.0]
    exc_kz = tuple(sorted(rc["kz"] for rc in exc))
    if smoke:
        check("G11-branch-reproduction", recs[0]["g_branch"] >= 0.0,
              "SMOKE: w9 branch %s (g %+.3f); ladder "
              "decomposition skipped"
              % ("CHEAP" if recs[0]["g_branch"] >= 0 else
                 "EXCEPTION", recs[0]["g_branch"]))
    else:
        check("G11-branch-reproduction",
              len(cheap) == CHEAP_EXPECT
              and exc_kz == tuple(sorted(EXC_KZ_EXPECT))
              and all(rc["g_branch"] >= 0 for rc in mrecs),
              "r263 branch rule reproduced EXACTLY: cheap %d/42, "
              "exception set %s == the named 7; mains %s"
              % (len(cheap), str(exc_kz),
                 "; ".join("w%d g %+.3f CHEAP" % (rc["kz"],
                                                  rc["g_branch"])
                           for rc in mrecs)))

    # ---------------- S2: decomposition + identities + record wards
    section("S2  EXACT DECOMPOSITION + IDENTITIES + RECORD WARDS")
    tb_worst = 0.0
    tb_deep = 0.0
    tb_ctrl = 0.0
    for rc in recs + mrecs:
        absum = float(np.sum(np.abs(rc["ct"])))
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(absum, 1e-300)
        rc["absum"] = absum
        if rc["N"] > DEEP_N:
            tb_deep = max(tb_deep, dev)
        else:
            tb_worst = max(tb_worst, dev)
    for c in crecs:
        rc = crecs[c]
        rc["absum"] = float(np.sum(np.abs(rc["ct"])))
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(rc["absum"], 1e-300)
        tb_ctrl = max(tb_ctrl, dev)
    check("G20-contribution-ward", tb_worst <= TB_WARD_BAR
          and tb_deep <= TB_WARD_BAR_DEEP
          and tb_ctrl <= TB_WARD_BAR_CTRL,
          "sum_b ct_b == t_{N-2} on %d rungs + %d mains + 3 "
          "controls: worst dev/absmass %.1e main N<=%d (bar %.0e) "
          "/ %.1e deep (bar %.0e) / %.1e controls (bar %.0e)"
          % (len(recs), len(mrecs), tb_worst, DEEP_N,
             TB_WARD_BAR, tb_deep, TB_WARD_BAR_DEEP, tb_ctrl,
             TB_WARD_BAR_CTRL))

    def eval_rung(rc):
        o = rc["o"]
        bxs = rc["bx"][o]
        cts = rc["ct"][o]
        bws = rc["bw"][o]
        v2s = rc["v2"][o]
        ed = PBB.mask_edge(bxs, rc["lo"], rc["hi"], EDGE_F)
        t_loc = float(np.sum(cts[ed]))
        cb = cts[~ed]
        wb = bws[~ed]
        fb = (bxs * v2s)[~ed] * rc["fac"]
        runs = PBB.runs_split(cb)
        Mr = [float(np.sum(np.abs(cb[a:b]))) for a, b, _s in runs]
        Sr = [float(np.sum(cb[a:b])) for a, b, _s in runs]
        sg = [s for _a, _b, s in runs]
        alt_ok = all(sg[i + 1] == -sg[i]
                     for i in range(len(sg) - 1))
        R = sum(Sr)
        sabs = sum(abs(v) for v in Sr)
        P = L2D.blocks_level2(Sr)
        e_c2 = PBB.bound_pairsum(Mr)
        f2 = L2D.bound_vdc(P)
        H = f2["H"]
        S_F = f2["s2"] / H
        A0 = sum(v * v for v in P)
        Zl = t_loc + rc["chain"]
        alt, lag = L2D.block_sign_stats(P)
        bw_runs = [wb[a:b] for a, b, _s in runs]
        f_runs = [fb[a:b] for a, b, _s in runs]
        b1 = route_b1(Mr, H)
        b2 = route_b2(Mr, H)
        b3 = route_b3(bw_runs, f_runs, H)
        # node-density census (B2): boundary discrepancies
        nb = len(cb)
        nr = len(runs)
        d_rank = 0.0
        d_mass = 0.0
        if nr > 1 and nb > 0:
            cmass = np.cumsum(np.abs(cb))
            tot = max(float(cmass[-1]), 1e-300)
            for i, (a, b, _s) in enumerate(runs[:-1]):
                d_rank = max(d_rank,
                             abs(b / nb - (i + 1) / nr))
                d_mass = max(d_mass,
                             abs(float(cmass[b - 1]) / tot
                                 - (i + 1) / nr))
        rl_med = float(np.median([b - a for a, b, _s in runs])) \
            if runs else 0.0
        return dict(Mr=Mr, Sr=Sr, alt_ok=alt_ok, R=R, sabs=sabs,
                    P=P, e_c2=e_c2, f2=f2, H=H, S_F=S_F, A0=A0,
                    Zl=Zl, alt=alt, lag=lag, m=len(P), nr=nr,
                    b1=b1, b2=b2, b3=b3, d_rank=d_rank,
                    d_mass=d_mass, rl_med=rl_med,
                    sum_s2=sum(v * v for v in Sr))

    all_rc = recs + mrecs
    for rc in all_rc:
        rc["ev"] = eval_rung(rc)
    for c in crecs:
        crecs[c]["ev"] = eval_rung(crecs[c])

    alt_all = all(rc["ev"]["alt_ok"] for rc in all_rc)
    bid_worst = 0.0
    ac_worst = 0.0
    for rc in all_rc + [crecs[c] for c in crecs]:
        ev = rc["ev"]
        bid_worst = max(bid_worst,
                        abs(sum(ev["P"]) - ev["R"])
                        / max(abs(ev["R"]), 1e-300))
        A = L2D.autocorr_full(ev["P"])
        s_all = A[0] + 2.0 * float(np.sum(A[1:]))
        ac_worst = max(ac_worst,
                       abs(s_all - sum(ev["P"]) ** 2)
                       / max(A[0], 1e-300))
    check("G21-block-and-autocorr-identity",
          alt_all and bid_worst <= ID_BAR and ac_worst <= AC_BAR,
          "runs alternate on every world AND sum P == R exact "
          "(worst rel %.1e, bar %.0e) AND (sum P)^2 == A(0) + 2 "
          "sum A(h) exact (worst %.1e x A(0), bar %.0e) over %d "
          "worlds" % (bid_worst, ID_BAR, ac_worst, AC_BAR,
                      len(all_rc) + len(crecs)))

    Ns = [rc["N"] for rc in recs]
    eps_c2_rel = [rc["ev"]["e_c2"] / M_W for rc in recs]
    if not smoke:
        sp_eps = BH.spearman(Ns, eps_c2_rel)
        Ct_s = [abs(rc["ev"]["R"]) / max(rc["ev"]["sabs"], 1e-300)
                for rc in recs]
        gamma_true = -L2D.halves_slope(Ns, Ct_s)
        rc15 = next(r_ for r_ in recs if r_["kz"] == KZ_ANCHOR)
        slack15 = M_W - abs(rc15["Z"])
        ok15 = RESERVE_BAND[0] <= slack15 <= RESERVE_BAND[1]
        alt_exc = [rc["ev"]["alt"] for rc in recs
                   if rc["g_branch"] < 0.0]
        alt_med = float(np.median(alt_exc))
        ok_alt = R270_ALT_BAND[0] <= alt_med <= R270_ALT_BAND[1]
        check("G22-r272-reproduction-wards",
              abs(sp_eps - R272_SP_EPS) <= R272_SP_TOL
              and abs(gamma_true - R272_GAMMA_TRUE) <= R272_GT_TOL
              and ok15 and ok_alt,
              "sp(N, eps_c2) %+.2f (ref %+.2f), gamma_true %+.3f "
              "(ref %+.3f), kz15 true reserve %.4f in %s (the "
              "r270 exact-finite anchor), exception P-sign alt "
              "med %.2f in %s"
              % (sp_eps, R272_SP_EPS, gamma_true,
                 R272_GAMMA_TRUE, slack15, str(RESERVE_BAND),
                 alt_med, str(R270_ALT_BAND)))
        # r287 F2 regression (bit-near record reproduction)
        sl_c2 = L2D.halves_slope(Ns, eps_c2_rel)
        eF2_rel = [rc["ev"]["f2"]["eps"] / M_W for rc in recs]
        sl_F2 = L2D.halves_slope(Ns, eF2_rel)
        delta_F2 = sl_c2 - sl_F2
        cert7 = 0
        cert42 = 0
        for rc in recs:
            ev = rc["ev"]
            mg = M_W - (abs(ev["Zl"]) + ev["f2"]["eps"])
            if mg > 0.0:
                cert42 += 1
                if rc["g_branch"] < 0.0:
                    cert7 += 1
        ev15 = rc15["ev"]
        need15 = M_W - abs(ev15["Zl"])
        miss15 = math.log10(ev15["f2"]["eps"] / need15) \
            if need15 > 0 else float("inf")
        check("G23-r287-f2-regression",
              abs(delta_F2 - R287_DELTA_F2) <= R287_DF2_TOL
              and cert7 == R287_CERT[0] and cert42 == R287_CERT[1]
              and abs(miss15 - R287_KZ15_MISS) <= R287_KZ15_TOL
              and abs(sl_c2 - R272_SL_C2) <= R272_SL_TOL,
              "the r287 F2_VDC record recomputed at the frozen H "
              "rule: delta'(F2) %+.3f (ref %+.3f), cert %d/7 + "
              "%d/42 (ref %d/%d), kz15 miss %.3f dec (ref %.2f), "
              "slope(eps_c2/M) %+.3f (ref %+.3f) -- the round "
              "stands on the recorded machine state"
              % (delta_F2, R287_DELTA_F2, cert7, cert42,
                 R287_CERT[0], R287_CERT[1], miss15,
                 R287_KZ15_MISS, sl_c2, R272_SL_C2))
    else:
        sl_c2 = float("nan")
        check("G22-r272-reproduction-wards", True,
              "SMOKE: skipped (needs the 42-rung ladder)")
        check("G23-r287-f2-regression", True,
              "SMOKE: skipped (needs the 42-rung ladder)")

    # ---------------- S3: exact section + toys + audits + mutants
    section("S3  EXACT SECTION (FRACTIONS) + TOYS + SCOPE AUDITS")
    okv = True
    for P in FR_SEQS:
        m = len(P)
        s = sum(P)
        for Hh in range(1, m + 1):
            W = fr_window_sums(P, Hh)
            okv &= (len(W) == m + Hh - 1)
            okv &= (fr_fejer_windowsum(P, Hh)
                    == Fr(1, Hh) * sum(w * w for w in W))
            okv &= (sum(W) == Hh * s)
            okv &= (s * s <= fr_vdc_bound_sq(P, Hh))
    Peq = [Fr(1)] * 6
    okv &= (sum(Peq) ** 2 == fr_vdc_bound_sq(Peq, 1))
    check("G30-v964-s0-recheck", okv,
          "the PROVEN v964-S0 vdC set RE-COMPUTED exact in "
          "Fractions on all %d frozen sequences: Fejer window-sum "
          "identity, H-fold covering identity, |sum P|^2 <= "
          "((m + H - 1)/H) x windowsum at every H, H = 1 equality "
          "witness 36 == 36 -- the machine this round feeds is a "
          "THEOREM" % len(FR_SEQS))
    w_orth, w_id = fr_symbolic_sumrule()
    check("G31-symbolic-sumrule", w_orth == 0 and w_id == 0,
          "the B3 SYMBOLIC sum rule PROVED exact in Fractions on "
          "the rational 4-node measure: monic three-term chain "
          "orthogonality dev %s, Parseval-type second-moment "
          "identity sum w x^2 pi_k^2 == h_{k+1} + a_k^2 h_k + "
          "b_k^2 h_{k-1} dev %s -- the identity CANDIDATE exists "
          "as abstract algebra; whether the REAL border chain "
          "attaches to it is the S7 census"
          % (str(w_orth), str(w_id)))
    toy_worst = toy_routes()
    check("G32-toy-exactness", toy_worst <= TOY_BAR,
          "hand-checked sequences reproduce EXACTLY (worst dev "
          "%.1e, bar %.0e): blocks [2,-2,1]; vdC H=2 sumW2=6 "
          "S_F=3 eps=sqrt(6); B1 gaps (2,2) tail 1 gapmax 2 "
          "e_c2 5 A0 9 <= 10 eps sqrt(40); B2 sumM2 31 <= 44 "
          "eps sqrt(352); B3 CS two-run toy wrx 3 qabs 7 "
          "cs_sum 13" % (toy_worst, TOY_BAR))
    h_b1 = scope_audit("route_b1", BOUND_FORBIDDEN)
    h_b2 = scope_audit("route_b2", BOUND_FORBIDDEN)
    h_b3 = scope_audit("route_b3", BOUND_FORBIDDEN)
    h_cq = scope_audit("chain_quads", BOUND_FORBIDDEN)
    h_gift = scope_audit("mutant_gift_bound", BOUND_FORBIDDEN)
    h_peek = scope_audit("mutant_branch_peek", BOUND_FORBIDDEN)
    ag_hits = antigate_fragment_audit()
    clean = not (h_b1 or h_b2 or h_b3 or h_cq)
    check("G33-scope-audits", clean and bool(h_gift)
          and bool(h_peek) and not ag_hits,
          "the three route builders + the identity census consume "
          "source-side objects only "
          "(no truth-side identifier in scope%s); m4a gift mutant "
          "FLAGGED (%s); m4b branch-peek mutant (simulated world-"
          "blindness break) FLAGGED (%s); fragment audit: %s"
          % ("" if clean else " VIOLATION",
             "; ".join(h_gift) if h_gift else "NOT FLAGGED",
             "; ".join(h_peek) if h_peek else "NOT FLAGGED",
             "CLEAN" if not ag_hits else "; ".join(ag_hits)))
    P4 = [Fr(1)] * 4
    wrong = fr_vdc_bound_sq(P4, 2, prefactor_m_only=True)
    ok_m1 = (wrong == 14 and sum(P4) ** 2 == 16 and wrong < 16
             and fr_vdc_bound_sq(P4, 2) >= 16)
    Pt = [Fr(2), Fr(-2), Fr(1)]
    Wt = fr_window_sums(Pt, 2)
    brk3 = abs(float(fr_fejer_windowsum(Pt, 2, perturbed=True)
                     - Fr(1, 2) * sum(w * w for w in Wt)))
    check("G34-mustfails-m1-m3", ok_m1 and brk3 >= MUT_MIN,
          "m1 WRONG PREFACTOR m/H: 14 < 16 = |sum P|^2 on "
          "P = (1,1,1,1), H = 2 EXACT (correct bound 35/2) -- "
          "CAUGHT; m3 PERTURBED FEJER weight (1 - |h|/(H+1)) "
          "breaks the window-sum identity by %.2e (>= %.0e) "
          "LOUD -- every constant in the sealed forms is "
          "load-bearing" % (brk3, MUT_MIN))

    # ---------------- S4: Leg A -- the target inequality
    section("S4  LEG A: THE TARGET INEQUALITY (VDC INPUT ANATOMY)")
    # validity of the universal chain steps on ALL worlds (gate)
    val_worst = {nm: -1e300 for nm in ROUTE_ORDER}
    fej_worst = -1e300
    a0_worst = {"B1_PAIRGAP": -1e300, "B2_NODEDENS": -1e300,
                "B3_PARSEVAL": -1e300}
    for rc in all_rc + [crecs[c] for c in crecs]:
        ev = rc["ev"]
        sc = max(abs(ev["A0"]), 1e-300)
        # Fejer step S_F <= H x A(0)
        fej_worst = max(fej_worst, (ev["S_F"] - ev["H"] * ev["A0"])
                        / sc)
        # A(0) <= gapmax x eps_c2 (B1); <= 2 sum M^2 <= 2 mx sm
        # (B2); <= 2 sum s^2 <= 2 wrx qabs (B3)
        a0_worst["B1_PAIRGAP"] = max(
            a0_worst["B1_PAIRGAP"], (ev["A0"] - ev["b1"]["a0b"]) / sc)
        a0_worst["B2_NODEDENS"] = max(
            a0_worst["B2_NODEDENS"],
            (ev["A0"] - 2.0 * ev["b2"]["m2"]) / sc,
            (ev["b2"]["m2"] - ev["b2"]["mx"] * ev["b2"]["sm"]) / sc)
        a0_worst["B3_PARSEVAL"] = max(
            a0_worst["B3_PARSEVAL"],
            (ev["A0"] - 2.0 * ev["sum_s2"]) / sc,
            (ev["sum_s2"] - ev["b3"]["cs_sum"]) / sc,
            (ev["b3"]["cs_sum"]
             - ev["b3"]["wrx"] * ev["b3"]["qabs"]) / sc)
        for nm, key in (("B1_PAIRGAP", "b1"), ("B2_NODEDENS", "b2"),
                        ("B3_PARSEVAL", "b3")):
            val_worst[nm] = max(val_worst[nm],
                                (abs(ev["R"]) - ev[key]["eps"])
                                / max(abs(ev["R"]), 1e-300))
    ok_val = (fej_worst <= VAL_BAR
              and all(a0_worst[nm] <= VAL_BAR for nm in ROUTE_ORDER)
              and all(val_worst[nm] <= VAL_BAR
                      for nm in ROUTE_ORDER))
    check("G40-route-validity-wards", ok_val,
          "every chain step EXACT on %d worlds (incl. the broken-"
          "arithmetic controls -- WORLD-BLIND by the same "
          "algebra): Fejer step slack %.1e; A(0) majorization "
          "slacks %s; route validity |R| <= eps slacks %s (bar "
          "%.0e)"
          % (len(all_rc) + len(crecs), fej_worst,
             str({nm[:2]: "%+.1e" % a0_worst[nm]
                  for nm in ROUTE_ORDER}),
             str({nm[:2]: "%+.1e" % val_worst[nm]
                  for nm in ROUTE_ORDER}), VAL_BAR))
    if not smoke:
        pref = [(rc["ev"]["m"] + rc["ev"]["H"] - 1) / rc["ev"]["H"]
                for rc in recs]
        sf_rel = [rc["ev"]["S_F"] / (M_W * M_W) for rc in recs]
        sl_pref = L2D.halves_slope(Ns, pref)
        sigma = L2D.halves_slope(Ns, sf_rel)
        add_dev = abs(sl_F2 - 0.5 * (sl_pref + sigma))
        sigma_star = 2.0 * (sl_c2 - DELTA_NEED) - sl_pref
        pad_sig = sigma_star - sigma
        check("G41-slope-additivity", add_dev <= ADD_BAR,
              "the exact decomposition slope(eps_F2/M) = (1/2) x "
              "[slope(pref) + sigma]: dev %.1e (bar %.0e); "
              "sl_pref %+.3f, sigma = slope(S_F/M^2) %+.3f"
              % (add_dev, ADD_BAR, sl_pref, sigma))
        # pad table: slope budgets of the universal steps
        fej_sl = L2D.halves_slope(
            Ns, [rc["ev"]["H"] * rc["ev"]["A0"]
                 / max(rc["ev"]["S_F"], 1e-300) for rc in recs])
        blk_sl = L2D.halves_slope(
            Ns, [2.0 * rc["ev"]["sum_s2"]
                 / max(rc["ev"]["A0"], 1e-300) for rc in recs])
        cs_sl = L2D.halves_slope(
            Ns, [rc["ev"]["b3"]["wrx"] * rc["ev"]["b3"]["qabs"]
                 / max(rc["ev"]["sum_s2"], 1e-300) for rc in recs])
        tgt_note = []
        for rc in sorted(exc, key=lambda r_: r_["kz"]):
            ev = rc["ev"]
            need = M_W - abs(ev["Zl"])
            allow = (ev["H"] / (ev["m"] + ev["H"] - 1)) * need * need \
                if need > 0 else 0.0
            tgt_note.append("kz%d %.2f dec" % (
                rc["kz"],
                math.log10(ev["S_F"] / max(allow, 1e-300))))
        check("G42-target-inequality-frozen", True,
              "TARGET_INEQUALITY_FROZEN: sigma <= sigma* = "
              "2 x (slope(eps_c2/M) - DELTA_NEED) - slope(pref) = "
              "2 x (%+.3f - %.2f) - %+.3f = %+.3f; measured sigma "
              "%+.3f => the TRUTH SATISFIES the target with %.3f "
              "sigma margin (%.3f in delta'); PAD TABLE (slope "
              "budgets of the universal steps): Fejer step %+.3f, "
              "block step %+.3f, CS step %+.3f; per-exception "
              "certification form S_F < H/(m+H-1) x (M_W-|Zl|)^2 "
              "(dec over): %s"
              % (sl_c2, DELTA_NEED, sl_pref, sigma_star, sigma,
                 pad_sig, 0.5 * pad_sig, fej_sl, blk_sl, cs_sl,
                 "; ".join(tgt_note)))
        # m2 pad-sharpness arithmetic
        d_with = sl_c2 - 0.5 * (sl_pref + sigma_star)
        sigma_nopad = 2.0 * sl_c2 - sl_pref
        d_nopad = sl_c2 - 0.5 * (sl_pref + sigma_nopad)
        check("G43-mustfail-pad-dropped", abs(d_with - DELTA_NEED)
              <= SHARP_BAR and abs(d_nopad) <= SHARP_BAR
              and d_nopad <= DELTA_NEED,
              "m2 PAD-DROPPED TARGET (sharpness): the sealed "
              "sigma* composes to delta' = %.12f == DELTA_NEED "
              "exactly; dropping the pad term (DELTA_NEED -> 0) "
              "composes to delta' = %.1e <= 0.21 -- the chain "
              "would NOT deliver: the pad term is load-bearing "
              "(bar %.0e)" % (d_with, d_nopad, SHARP_BAR))
    else:
        sigma = sigma_star = sl_pref = float("nan")
        check("G41-slope-additivity", True, "SMOKE: skipped")
        check("G42-target-inequality-frozen", True,
              "SMOKE: skipped")
        check("G43-mustfail-pad-dropped", True, "SMOKE: skipped")

    # ---------------- S5/S6: B1 + B2 censuses
    section("S5  LEG B1 (PAIR-IDENTITY) + B2 (NODE DENSITY)")
    show = (sorted(exc, key=lambda r_: r_["kz"]) + mrecs
            if not smoke else mrecs)
    for rc in show:
        ev = rc["ev"]
        info("kz%-3d N%-4d %-4s m %-3d H %-2d  |R| %.4f  F2 %.3f"
             "  B1 %.3f (gapmax %.4f)  B2 %.3f (imb %.2f)  B3 "
             "%.3f (wrx %.2e)"
             % (rc["kz"], rc["N"],
                "EXC" if rc["g_branch"] < 0 else "chp", ev["m"],
                ev["H"], abs(ev["R"]), ev["f2"]["eps"],
                ev["b1"]["eps"], ev["b1"]["gapmax"],
                ev["b2"]["eps"], ev["b2"]["imb"],
                ev["b3"]["eps"], ev["b3"]["wrx"]))
    if not smoke:
        routes = {}
        for nm, key in (("B1_PAIRGAP", "b1"), ("B2_NODEDENS", "b2"),
                        ("B3_PARSEVAL", "b3")):
            e_rel = [rc["ev"][key]["eps"] / M_W for rc in recs]
            sl_ = L2D.halves_slope(Ns, e_rel)
            dp_ = sl_c2 - sl_
            med_dec = float(np.median(
                [math.log10(max(v, 1e-300)) for v in e_rel]))
            loss = float(np.median(
                [math.log10(rc["ev"][key]["eps"]
                            / max(abs(rc["ev"]["R"]), 1e-300))
                 for rc in recs]))
            routes[nm] = dict(sl=sl_, dp=dp_, med=med_dec,
                              loss=loss)
        gap_sl = L2D.halves_slope(
            Ns, [rc["ev"]["b1"]["gapmax"] / M_W for rc in recs])
        gap_need = 2.0 * (sl_c2 - DELTA_NEED) - L2D.halves_slope(
            Ns, [rc["ev"]["m"] + rc["ev"]["H"] - 1
                 for rc in recs]) - sl_c2
        check("G50-b1-census", True,
              "B1 PAIR-IDENTITY route: delta'_B1 %+.3f (need > "
              "%.2f); the provenance carrier gapmax/M slope %+.3f "
              "(sufficient would be <= %+.3f): the MAX pair gap "
              "falls far slower than the mean amplitude (r272 "
              "B_amp -0.81) -- the Jacobi near-balance is a MEAN "
              "statement, its extreme is not chain-controlled; "
              "loss med %.2f dec; eps med %+.2f dec vs M"
              % (routes["B1_PAIRGAP"]["dp"], DELTA_NEED, gap_sl,
                 gap_need, routes["B1_PAIRGAP"]["loss"],
                 routes["B1_PAIRGAP"]["med"]))
        alpha_m = L2D.halves_slope(Ns, [rc["ev"]["nr"]
                                        for rc in recs])
        imb_sl = L2D.halves_slope(Ns, [rc["ev"]["b2"]["imb"]
                                       for rc in recs])
        dr_med = float(np.median([rc["ev"]["d_rank"]
                                  for rc in recs]))
        dm_med = float(np.median([rc["ev"]["d_mass"]
                                  for rc in recs]))
        dr_sl = L2D.halves_slope(Ns, [max(rc["ev"]["d_rank"],
                                          1e-300) for rc in recs])
        rl_med = float(np.median([rc["ev"]["rl_med"]
                                  for rc in recs]))
        check("G51-b2-census", True,
              "B2 NODE-DENSITY route: delta'_B2 %+.3f (need > "
              "%.2f); alpha_m(runs) %+.3f, run-length med %.1f; "
              "ET-style boundary discrepancies: D_rank med %.3f "
              "(slope %+.2f) vs D_mass med %.3f -- the boundary "
              "POSITIONS are near-equidistributed (provable "
              "terrain), the MASS is not; the obstruction is the "
              "imbalance n x maxM / sumM slope %+.3f (max/mean "
              "run mass GROWS with N): pure node density supplies "
              "the COUNT, not the decay"
              % (routes["B2_NODEDENS"]["dp"], DELTA_NEED, alpha_m,
                 rl_med, dr_med, dr_sl, dm_med, imb_sl))
    else:
        routes = {}
        check("G50-b1-census", True, "SMOKE: skipped")
        check("G51-b2-census", True, "SMOKE: skipped")

    # ---------------- S7: B3 identity census
    section("S7  LEG B3: THE PARSEVAL IDENTITY CENSUS")
    id_pool = (mrecs + [crecs[c] for c in ("EPST", "SCR")]) \
        if smoke else \
        ([rc for rc in recs if rc["kz"] in (KZ_ANCHOR, 20)]
         + mrecs + [crecs[c] for c in ("EPST", "SCR")])
    rec_worst = 0.0
    id_status = {}
    for meas in MEAS:
        crosses = []
        devs = []
        for rc in id_pool:
            N = rc["N"]
            rows = rc["p"]["rows"]
            if meas == "BORDER":
                X, W = rc["bx"], rc["bw"]
            elif meas == "WINDOW":
                X, W = rc["xu"], rc["wu"]
            else:
                X = np.concatenate([rc["xu"], rc["bx"]])
                W = np.concatenate([rc["wu"], -rc["bw"]])
            cq = chain_quads(rows, N, X, W)
            rec_worst = max(rec_worst,
                            abs(cq["q2"] - cq["pf"])
                            / max(abs(cq["q2"]), 1e-300))
            crosses.append(max(abs(v) for v in cq["cr"].values()))
            devs.append(abs(cq["q2"] - cq["pd"])
                        / max(abs(cq["q2"]), 1e-300))
            rc.setdefault("cq", {})[meas] = cq
        cmed = float(np.median(crosses))
        dmed = float(np.median(devs))
        wm = max(max(crosses), max(devs))
        st = ("HOLDS" if wm <= ID_HOLDS
              else ("NEAR" if wm <= ID_NEAR else "BREAKS"))
        id_status[meas] = (st, cmed, dmed, wm)
        info("measure %-7s orth-cross med %.3f  diag-identity dev "
             "med %.3f  worst %.3f  => %s"
             % (meas, cmed, dmed, wm, st))
    check("G60-recursion-ward", rec_worst <= REC_BAR,
          "the tautological full-cross prediction (the three-term "
          "recursion in scaled coordinates, all 9 cross terms) "
          "reproduces sum W x^2 v2^2 on every (world, measure): "
          "worst rel dev %.1e (bar %.0e) -- the recursion algebra "
          "is exact; ONLY orthogonality is in question"
          % (rec_worst, REC_BAR))
    id_holds = [m for m in MEAS if id_status[m][0] == "HOLDS"]
    ident_ok = bool(id_holds)
    check("G61-b3-identity-census", True,
          "the chain is %s w.r.t. the sealed candidate "
          "measures: %s -- %s"
          % (("ORTHOGONAL on " + "/".join(id_holds))
             if ident_ok else "NOT orthogonal",
             "; ".join("%s %s (cross med %.3f, diag dev med %.3f)"
                       % (m, id_status[m][0], id_status[m][1],
                          id_status[m][2]) for m in MEAS),
             "the symbolic sum rule ATTACHES on that measure (an "
             "exact chain-norm identity exists there); the vdC "
             "input lives on the BORDER union -- the transfer "
             "between the measures is the remaining provenance "
             "step" if ident_ok else
             "the r244 bordered-Hankel chain is orthogonal w.r.t. "
             "the full bordered form, NOT a plain union -- the "
             "Parseval route has no attachment point on these "
             "measures (the named break)"))
    if not smoke:
        ag_ratio = [rc["ev"]["b3"]["wrx"] * rc["ev"]["b3"]["qabs"]
                    / max(rc["ev"]["sum_s2"], 1e-300)
                    for rc in recs]
        ag_sl = L2D.halves_slope(Ns, ag_ratio)
        wrx_sl = L2D.halves_slope(
            Ns, [rc["ev"]["b3"]["wrx"] for rc in recs])
        check("G62-b3-census", True,
              "B3 PARSEVAL route: delta'_B3 %+.3f (need > %.2f); "
              "wrunmax slope %+.3f; the signed-to-absolute gap "
              "(wrx x Qabs) / sum s^2: med %.1f, slope %+.3f -- "
              "the mixed-sign border weights (ws > 0, -vs < 0 by "
              "construction) put the |.|-chain above the signed "
              "truth by a GROWING factor: the structural break "
              "of the route"
              % (routes["B3_PARSEVAL"]["dp"], DELTA_NEED, wrx_sl,
                 float(np.median(ag_ratio)), ag_sl))
    else:
        check("G62-b3-census", True, "SMOKE: skipped")

    # ---------------- S8: worlds + anchors + mp wards
    section("S8  WORLDS + ANCHORS + MP WARDS")
    rowsS = ctrl["SMOOTH"]["rows"]
    NS = ctrl["SMOOTH"]["N"]
    scT = [abs(rowsS[k]["tb"] * math.exp(rowsS[k]["Ls"]
                                         - rowsS[k + 1]["Ls"]))
           for k in range(NS - 1)]
    alias = max(scT[2:]) / max(scT[0], scT[1])
    qS = float(ctrl["SMOOTH"]["rho"][NS - 1]) / B57
    evS = crecs["SMOOTH"]["ev"]
    okSv = abs(evS["R"]) <= evS["b1"]["eps"] + VAL_BAR
    check("G70-smooth-anchor", alias <= SM_ALIAS_BAR
          and abs(qS) <= SM_Q_BAR and okSv,
          "SMOOTH: drive alias %.1e <= %.0e; q_N = %.1e <= %.0e; "
          "route validity holds trivially on the self-aliased "
          "source (%s)"
          % (alias, SM_ALIAS_BAR, qS, SM_Q_BAR,
             "OK" if okSv else "BROKEN"))
    if not smoke:
        mp_note = []
        ok_mp = True
        rc15 = next(r_ for r_ in recs if r_["kz"] == KZ_ANCHOR)
        t15 = PBB.mp_drive(rc15["p"], MP_DPS)
        d15 = abs(t15 - rc15["t_term"])
        ok_mp = ok_mp and (d15 <= MP_T_BAR)
        mp_note.append("kz15 (N %d) dev %.1e (bar %.0e)"
                       % (rc15["N"], d15, MP_T_BAR))
        for rc in recs[-2:]:
            t_mp = PBB.mp_drive(rc["p"], MP_DPS)
            dv = abs(t_mp - rc["t_term"])
            ok_mp = ok_mp and (dv <= MP_DEEP_BAR)
            mp_note.append("kz%d (N %d, DEEPEST) dev %.1e (bar "
                           "%.0e)" % (rc["kz"], rc["N"], dv,
                                      MP_DEEP_BAR))
        check("G71-mp-deep-wards", ok_mp,
              "mp (dps %d) terminal drive at the trend-critical "
              "rungs: %s" % (MP_DPS, "; ".join(mp_note)))
    else:
        check("G71-mp-deep-wards", True, "SMOKE: skipped")

    # ---------------- S9: adjudication + Legs C/D + verdict
    section("S9  ADJUDICATION + LEG C/D + VERDICT")
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the frozen target inequality (the weakest "
          "sufficient vdC input bound with all constants), the "
          "three-route provenance census with exact validity, "
          "the identity census of the border chain, and the "
          "named gap object -- NO new certificate promoted, NO "
          "bound modification of the sealed forms")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        elig = {}
        for nm in ROUTE_ORDER:
            elig[nm] = dict(
                valid=(val_worst[nm] <= VAL_BAR
                       and a0_worst[nm] <= VAL_BAR),
                slope_ok=(routes[nm]["dp"] > DELTA_NEED),
                ident=(nm == "B3_PARSEVAL" and ident_ok))
        # PROVEN reachable only by B3 with IDENT + exact abs step
        # (disclosed expectation: structurally false) -- checked:
        bulk_onesign = all(
            float(np.min(rc["bw"])) > 0.0
            or float(np.max(rc["bw"])) < 0.0 for rc in mrecs)
        proven = [nm for nm in ("B3_PARSEVAL",)
                  if elig[nm]["valid"] and elig[nm]["slope_ok"]
                  and elig[nm]["ident"] and bulk_onesign]
        part = [nm for nm in ROUTE_ORDER
                if elig[nm]["valid"]
                and (elig[nm]["slope_ok"] or elig[nm]["ident"])]
        tab = []
        breaks = {"B1_PAIRGAP": "gapmax scaling (max vs mean)",
                  "B2_NODEDENS": "mass imbalance growth",
                  "B3_PARSEVAL": "measure transfer + "
                                 "signed-to-absolute gap"}
        for nm in ROUTE_ORDER:
            tab.append("%s valid %s delta' %+.3f%s %s"
                       % (nm,
                          "47/47" if elig[nm]["valid"] else "FAIL",
                          routes[nm]["dp"],
                          (" IDENT " + ("HOLDS(%s)"
                                        % "/".join(id_holds)
                                        if ident_ok else "BREAKS"))
                          if nm == "B3_PARSEVAL" else "",
                          "SLOPE_OK" if elig[nm]["slope_ok"]
                          else "BREAK@" + breaks[nm]))
        parts = ["TARGET_INEQUALITY_FROZEN(sigma* %+.3f, sigma "
                 "%+.3f, margin %.3f in sigma = %.3f in delta')"
                 % (sigma_star, sigma, sigma_star - sigma,
                    0.5 * (sigma_star - sigma))]
        parts.append("ROUTE_TABLE(%s)" % "; ".join(tab))
        w = None
        if proven:
            w = proven[0]
            parts.append("CHAIN_PROVENANCE_PROVEN(%s, delta' "
                         "%+.3f > %.2f)" % (w, routes[w]["dp"],
                                            DELTA_NEED))
            fired = True
        elif part:
            w = max(part, key=lambda nm: (elig[nm]["slope_ok"],
                                          routes[nm]["dp"]))
            gap = ("slope miss %.3f" % (DELTA_NEED
                                        - routes[w]["dp"])
                   if not elig[w]["slope_ok"] else breaks[w])
            parts.append("CHAIN_PROVENANCE_PARTIAL(%s, gap: %s)"
                         % (w, gap))
            fired = elig[w]["slope_ok"]
        else:
            parts.append("INPUT_STILL_EMPIRICAL(common "
                         "obstruction: every universal "
                         "majorization of A(0) through magnitudes "
                         "pays a max/mean imbalance factor that "
                         "GROWS and eats the pad; the true input "
                         "sigma %+.3f lives in the SIGNED block "
                         "structure that no |.|-chain sees)"
                         % sigma)
            fired = False
        # Leg C
        if fired and w is not None:
            info("CANDIDATE THEOREM (L2 generic half): for every "
                 "rung of the sealed ladder (N in [%d, %d], H = "
                 "ceil(sqrt(m))): |R| <= eps_%s (exact chain, "
                 "constants: pref (m+H-1), route factors printed "
                 "above) AND slope(eps_%s/M) <= slope(eps_c2/M) "
                 "- %.2f (MEASURED hypothesis, 42 rungs) => "
                 "delta' > %.2f on the generic half; exceptions: "
                 "6 via the r287 F2 certificates, kz15 via the "
                 "r270 exact-finite certificate.  NOT promoted "
                 "(wave-9 candidate)."
                 % (min(Ns), max(Ns), w, w, DELTA_NEED,
                    DELTA_NEED))
        else:
            info("Leg C VOID (no route carries).  The gap object "
                 "of the lane: a signed/bordered-form sum rule "
                 "(the r244 bordered Hankel form itself, not a "
                 "plain union measure) OR a mass-profile "
                 "equidistribution statement (D_rank is flat and "
                 "small -- node positions are provable terrain; "
                 "the mass imbalance is the obstruction).")
        # Leg D: kz15 note
        rc15 = next(r_ for r_ in recs if r_["kz"] == KZ_ANCHOR)
        ev15 = rc15["ev"]
        need15 = M_W - abs(ev15["Zl"])
        kz_note = []
        covered = False
        for nm, key in (("B1", "b1"), ("B2", "b2"), ("B3", "b3")):
            e_ = ev15[key]["eps"]
            if e_ < need15:
                covered = True
                kz_note.append("%s cert %+.4f" % (nm, need15 - e_))
            else:
                kz_note.append("%s miss %.2f dec"
                               % (nm, math.log10(e_ / need15)))
        parts.append("KZ15_NOTE(%s: %s; r270 exact-finite "
                     "certificate %s)"
                     % ("covered" if covered
                        else "structurally outside",
                        "; ".join(kz_note),
                        "redundant" if covered
                        else "remains the permanent closure"))
        verd = " + ".join(parts)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G96-verdict", npass == len(CHECKS),
          "%s%s -- SATZ (machine-gated): the v964-S0 recheck, the "
          "symbolic sum rule, every route chain step (world-blind"
          " 47/47); MEASURED: every slope, imbalance, gap and "
          "margin (42 rungs only); OPEN: the chain origin of the "
          "vdC input beyond the named gap object, the cofinal "
          "step H5, kz15 beyond r270; 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"""window_border_transfer_probe -- PRIME.PORT.L2.
WINDOW_BORDER_TRANSFER.01 (round 298): the TRANSFER STATEMENT
from the WINDOW measure (where the chain is exactly orthogonal,
r297-S7) to the BORDER form (where the vdC input lives) -- does
an exact or low-loss decomposition of the vdC input S_F exist
that PRESERVES the signed structure instead of losing it to
magnitudes?  Context (sealed record inputs): r297 (SPEC e42a76eb,
27/27) froze the target inequality sigma := slope(S_F/M_W^2) <=
sigma* = -0.516 (measured sigma = -0.714, margin 0.198) and named
the gap object: every magnitude majorization of A(0) pays a
GROWING max/mean imbalance factor (+0.22..+0.24 slope); the two
assets: (1) the chain is EXACTLY ORTHOGONAL w.r.t. the WINDOW
union (union(d)): cross/diag devs 0.000 world-blind, and the
Parseval sum rule sum w x^2 pi_k^2 = h_{k+1} + a_k^2 h_k + b_k^2
h_{k-1} is PROVED in Fractions (r297-G31) -- but the vdC input
lives on the BORDER union (union(dsm), mixed-sign weights ws > 0
/ -vs < 0) where orthogonality breaks (~1.1); (2) run-boundary
POSITIONS are near-equidistributed with falling discrepancy
(D_rank med 0.024, slope -0.42) while the MASS imbalance grows
(+0.244).  r287: the vdC theorem delivers delta'(F2) = +0.309 >
DELTA_NEED = 0.21 world-blind; kz15 permanently closed via r270.

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

THE OBJECT (r269/r287/r297 machinery imported verbatim):
t_{N-2} = sum_b ct_b (r244 chain rows, r266 eval); F = 0.20 edge
split; maximal same-sign runs of the bx-sorted bulk; level-2
blocks P_j (r270 convention, offset 0); FROZEN vdC window H =
max(2, ceil(sqrt(m))); the vdC input S_F = (1/H) sum_t W_t^2
(v964-S0 identity).  THE TWO MEASURES (r297-sealed candidates):
WINDOW omega = union(d) (atoms xu, weights wu = (ws, -vs) of the
arithmetic comb), BORDER beta = union(dsm) (atoms bx, weights bw
= (ws, -vs) of the smooth comb); both mixed-sign by construction.
THE TRANSFER OBJECT (frozen): Delta := beta (-) omega, the exact
signed difference measure (atoms concat(bx, xu), weights
concat(bw, -wu) -- four signed atom classes).  THE FROZEN
POSITIONAL FEJER KERNEL: S_F is EXACTLY the quadratic form
B(u, v) = (1/H) sum_t W_t(u) W_t(v) (W_t = sliding H-window sums
over the block axis) evaluated on the block aggregation of the
border atoms; the kernel data (edge mask over the combined hull
[lo, hi] at EDGE_F, the block partition = positional intervals of
the border bulk runs with midpoint breakpoints, the frozen H) is
read off the BORDER structure ONCE per rung and then applied to
ANY atom list positionally (c(x) = w x v2(x) fac, edge atoms
dropped, block index by breakpoint search).  This extends the
block functional to omega and Delta CANONICALLY and makes S_F
measure-quadratic: with P_mu the aggregated block vector of
measure mu, PDelta = Pbeta - Pomega EXACTLY, and

  S_F  =  B(Pbeta, Pbeta)
       =  B(Pomega, Pomega)  +  B(PDelta, Pbeta + Pomega)
       =  MAIN               +  T(Delta)          (EXACT identity)

-- the difference-of-squares split of the Fejer form; T(Delta) =
B(Delta, beta + omega) is LINEAR in Delta and carries the full
signed structure (nothing passes through |.|); per-block
attribution t_j = PDelta_j x phi_j with phi = Fejer * (Pbeta +
Pomega) (convolution), sum_j t_j = T exactly; components T =
B(PDelta, PDelta) + 2 B(PDelta, Pomega) = T_diag + T_cross.  The
PARSEVAL ANCHOR of the main-term side: on omega the chain is
exactly orthogonal (r297), the proven sum rule attaches verbatim
(re-proved in Fractions here, wrong-b^2 mutant CAUGHT), and the
LINEAR corollary holds: sum_a wu_a xu_a v2(xu_a) = 0 EXACTLY
(x pi_{N-2} = pi_{N-1} + a pi_{N-2} + b pi_{N-3} is orthogonal
to pi_0 on omega) -- the window image of the drive functional
VANISHES: at the linear level the drive is 100 pct transfer;
the open question of this round is the QUADRATIC split.

LEG 0 -- ANCHOR REGRESSION (r297 record numbers adopted as-is,
disclosed): sigma = -0.714 tol 0.01, sigma* = -0.516 tol 0.01
(sl_c2 +0.196 tol 0.01, sl_pref +0.489 tol 0.01); WINDOW
orthogonality HOLDS (cross + diag devs <= 1e-6) on the id pool
(kz15, kz20, mains, EPSTEIN, SCRAMBLE) while BORDER breaks
(cross med in [0.8, 1.4]); the Parseval sum rule re-proved exact
in Fractions (dev 0); D_rank med 0.024 tol 0.005 with slope
-0.42 tol 0.05; mass-imbalance slope +0.244 tol 0.01;
contribution + block + autocorr identity wards (r297 bars).

LEG A -- THE EXACT BORDER DECOMPOSITION (structure first):
(A1) Delta anatomy census: atom counts / |mass| / signed mass of
  the four classes (border-ws > 0, border--vs < 0, window-ws,
  window--vs), exact support overlap count, edge shares -- the
  concrete sign structure of Delta printed.
(A2) DECOMPOSITION_EXACT gates: (i) KERNEL REPRODUCTION: the
  frozen positional kernel reproduces S_F from the raw border
  atoms against the sealed r287 pipeline (blocks_level2 +
  bound_vdc) to <= 1e-12 rel on all 47 worlds (42 rungs + 2
  mains + EPSTEIN/SCRAMBLE/SMOOTH -- far beyond the required 6
  rungs x 3 worlds); (ii) THE IDENTITY: S_F = MAIN + T(Delta)
  to <= 1e-12 of the decomposition scale max(S_F, MAIN, |T|) on
  all 47 worlds; (iii) ATTRIBUTION: sum_j t_j = T and T =
  T_diag + T_cross (<= 1e-9 rel); (iv) the LINEAR WINDOW ZERO:
  |sum wu x v2| / sum |wu x v2| <= 1e-9 main (N <= 400) / 3e-6
  deep / 1e-6 controls (the orthogonality corollary).
  Fine type: DECOMPOSITION_EXACT(S_F = B(omega, omega) +
  B(Delta, omega + beta), frozen positional Fejer kernel).

LEG B -- THE TRANSFER-TERM SCALING (the decision; all slopes
r272 halves log-slopes on the N-sorted 42-rung ladder): measure
slope(MAIN/M_W^2), slope(|T|/M_W^2), the recomposition ward
(per-rung exact identity = the sigma additivity carrier), the
share census sh = |T|/S_F (med + slope), the T sign census, the
component split (T_diag med, T_cross med), the in-T sign
cancellation canc_T = sum_j |t_j| / |T| (med + slope), and the
class shares of sum_j |PDelta_j|.  SEALED ADJUDICATION (frozen
BEFORE evaluation, exactly one fires):
  DECOMPOSITION_UNSTABLE  iff med(MAIN/S_F) >= 10.0 (both terms
    an order above S_F, near-cancellation between main and
    transfer -- then THIS cancellation is the object; the third
    recurrence of the resummation pattern, explicitly cross-
    referenced against r259 (prefix resummation) and r261
    (fullsource free-prefix));
  TRANSFER_SUBDOMINANT    iff not UNSTABLE and med(sh) < 0.5
    and slope(|T|/M^2) <= slope(MAIN/M^2) - 0.05 (T falls
    faster and is minority -- Leg C fires);
  TRANSFER_DOMINANT       otherwise (T carries sigma; the
    precise gap object is the signed Delta structure -- its
    anatomy is the delivery: which classes carry T, how much
    sign cancellation lives INSIDE T).
WORLD CONTROLS: the decomposition is exact on EPSTEIN/SCRAMBLE
by the same algebra; the CLASS (unstable / T-minority /
T-majority by the same med rules at the single control rung) is
compared against MAIN -- a class break is NOT a gate failure but
a disclosed finding (WORLD_SENSITIVE tag in the verdict).

LEG C -- THE CANDIDATE THEOREM (fires ONLY on
TRANSFER_SUBDOMINANT): CANDIDATE THEOREM (window-border
transfer) printed with every constant explicit: the exact
decomposition (Leg A) + the proven Parseval sum rule on omega +
the D_rank equidistribution asset + transfer subdominance
(measured) + the r297 target inequality sigma <= sigma* + the
v964-S0 vdC theorem => delta' > 0.21 on the generic half; scope
the 42 measured rungs (N in [142, 878]); exceptions: 6 via the
r287 F2 certificates, kz15 via the r270 exact-finite
certificate.  Wave-9 promotion candidate -- NOT promoted here.
Otherwise Leg C is VOID without substitute and the precise gap
object is documented.

LEG D -- MASS-IMBALANCE BYCATCH (small): is the growing
imbalance imb = n_runs x maxM / sumM carried by few outlier
runs or broad?  Sealed: top-1/top-3 mass shares (med), the
drop-imbalances imb_d1 / imb_d3 (argmax run(s) removed) with
slopes; OUTLIER_CARRIED iff slope(imb_d3) <= 0.5 x slope(imb),
else BROAD_BASED.  Connection of the two gap halves: per-rung
Spearman(block mass Mb_j, |t_j|) (med) + the argmax coincidence
fraction -- do the mass-imbalance carriers coincide with the
T(Delta) carriers?

LEG E -- WARDS / MUST-FAILS (>= 4 mutants): (m1) WRONG-b^2 SUM
RULE (exact Fractions, module-own): the Parseval sum rule with
coefficient b_k instead of b_k^2 breaks on the rational 4-node
measure (dev != 0) -- CAUGHT; (m2) MAGNITUDE DELTA (|Delta|
instead of Delta): T computed from the magnitude aggregation
|c_a| breaks the exact identity LOUDLY (>= 1e-6 of the
decomposition scale, measured on w9 + both mains) -- the r297
magnitude error, now a must-fail; (m3) KERNEL-PERTURBED
RECOMPOSITION: the Fejer form at H + 1 breaks the toy identity
(S_F(H=2) = 3 vs 7/3 at H=3, break 2/3 >= 1e-6) -- CAUGHT;
(m4a/m4b) WORLD-BLINDNESS BREAK: a builder consuming the
withheld terminal drive key AND a builder consuming the branch
label are both FLAGGED by the AST scope audit.  Scope hygiene:
the kernel builders (block_breaks, aggregate_blocks, fejer_bil,
fejer_apply) consume positions + weights + chain values only
(BOUND_FORBIDDEN set); fragment audit (no fit primitives); TOY
EXACTNESS (bar 1e-14): the hand toy (border atoms (0..4), ct
(3,-1,2,-4,1) -> Pbeta (2,-2,1), H = 2, S_F = 3; window atoms
(0.5, 2.5), c (1,-1) -> Pomega (1,-1,0), MAIN = 1; PDelta
(1,-1,1), T = 2; MAIN + T = 3 = S_F; attribution t = (1.5, 1,
-0.5) sums to 2; T_diag = 1, T_cross = 1) reproduces the
whole pipeline EXACTLY; mp SAMPLES (dps 60): kz15 (bar 1e-8) +
the two deepest rungs (bar 3e-6); SMOOTH anchor (alias <=
1e-12, q_N <= 1e-20).

INDEX FIREWALL (binding, r238-r297 discipline): w = window (kz),
N_w = builder depth, k/n = chain degree; ground truth (branch
labels, the true R/t/Z values) enters GATES and census tables
only; no zero/prime oracles anywhere (AST firewall); no fit
primitives (fragment audit).  MACHINERY IMPORTED VERBATIM: r269
PBB.mask_edge + PBB.runs_split + PBB.mp_drive, r287
L2D.blocks_level2 + L2D.bound_vdc + L2D.halves_slope +
L2D.autocorr_full, r297 VCP.chain_quads + VCP.fr_symbolic_sumrule
(the proven set re-computed, not re-proved), r244 BH.wpack +
BH.spearman, r257 CT.union_arrays, r260 TX.drive_arrays, r263
CA.g_gap, r266 BR.eval_scaled, v881 PIK, r243 PB.smooth_comb.
B PROVENANCE: B_w = S_{N-2} + 5/7 (r241/r243 IMPORTED floor,
never fitted).  COFINAL LADDER (pre-sealed): frame-A h <= 900,
42 rungs, (N, kz)-sorted; exception set {kz15, 20, 22, 36, 38,
39, 52}.

SEALED CONSTANTS: MAIN windows (9, 13); controls w9 EPSTEIN /
SCRAMBLE(seed 1) / SMOOTH, flips 25/21/27; H_CAP 900; B57 = 5/7;
M_W = sqrt(5/7); CHEAP_EXPECT 35; EXC_KZ_EXPECT (15, 20, 22, 36,
38, 39, 52); EDGE_F 0.20 (FROZEN); PAIR_OFFSET 0 (FROZEN);
DELTA_NEED 0.21; H rule = max(2, ceil(sqrt(m))) (FROZEN); KER_BAR
1e-12 (kernel reproduction, rel S_F); DEC_BAR 1e-12 (identity,
rel decomposition scale); ATTR_BAR 1e-9 (attribution +
components); LIN_BARS 1e-9 main N <= 400 / 3e-6 deep / 1e-6
controls (linear window zero); UNSTABLE_FACTOR 10.0; SUB_SHARE
0.5; SUB_MARGIN 0.05; OUT_FACTOR 0.5 (Leg D); ID_HOLDS 1e-6;
BORDER_CROSS_BAND (0.8, 1.4); R297_SIGMA -0.714 tol 0.01;
R297_SIGMA_STAR -0.516 tol 0.01; R297_SL_C2 +0.196 tol 0.01;
R297_SL_PREF +0.489 tol 0.01; R297_DRANK_MED 0.024 tol 0.005;
R297_DRANK_SL -0.42 tol 0.05; R297_IMB_SL +0.244 tol 0.01;
TB_WARD bars 1e-9 main N <= 400 / 3e-6 deep / 1e-6 controls;
ID_BAR 1e-12; AC_BAR 1e-9; TOY_BAR 1e-14; MUT_MIN 1e-6; MP_DPS
60; MP_T_BAR 1e-8; MP_DEEP_BAR 3e-6; SM_Q_BAR 1e-20;
SM_ALIAS_BAR 1e-12; KZ_ANCHOR 15; runtime <= 1800 s; smoke = w9
+ controls + Fractions section + toys + scope audits + the full
decomposition gates at w9 (ladder, slopes, adjudication, Legs
C/D, mp wards skipped).  DISCLOSED PRE-SPEC INPUT (no scratch
run of this probe): every reproduction band is an r297 RECORD
number adopted as-is; the linear window zero is derived algebra
(orthogonality corollary), disclosed above as an expectation,
not tuned; the three Leg-B outcomes are sealed symmetrically --
the disclosed structural prior (the linear functional is 100
pct transfer) makes UNSTABLE or DOMINANT plausible, but no rule
was chosen to favor an outcome.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  DECOMPOSITION_EXACT(S_F = B(omega,omega) + B(Delta,omega+beta),
    Delta = border (-) window, frozen positional Fejer kernel,
    worst devs, worlds n/47)
+ TRANSFER_TABLE(MAIN med dec + slope, |T| med dec + slope,
    share med + slope, T sign census, T_diag/T_cross med,
    canc_T med + slope, Delta class shares)
+ [exactly one of] TRANSFER_SUBDOMINANT(...) /
    TRANSFER_DOMINANT(anatomy) /
    DECOMPOSITION_UNSTABLE(factor; r259/r261 crossref)
+ [iff fired] CANDIDATE_THEOREM(window-border transfer,
    constants)
+ IMBALANCE_NOTE(OUTLIER_CARRIED / BROAD_BASED, connection
    stats)
+ [if any control gate breaks] LOCAL_MODEL_MAIN_FITTED
+ [if the control class differs] WORLD_SENSITIVE(disclosed).
Honesty before beauty: the decomposition is an EXACT finite
identity, but every slope, share and class is MEASURED on 42
rungs only; no verdict claims a cofinal law; the kernel
extension to omega is canonical-positional, not unique -- it is
the sealed choice of this round; the exception scalar's
positivity beyond the measured 42 stays OPEN; r243-r297 stand.

RECORD TABLES (frozen from the record run; calibration protocol:
smoke pass 1 = 26/28 -- the toy gate G31 failed on a HAND-
ARITHMETIC error in the expected T-component constants (the
correct split of the toy T = 2 is T_diag = B(PDelta, PDelta) = 1
and T_cross = 2 B(PDelta, Pomega) = 1, not 1.5/0.5; PDelta +
2 Pomega = Pbeta + Pomega makes the identity obvious) --
amendment a1 (the toy constants and the spec toy line corrected;
no bar, band, rule or verdict rule touched; all real-data gates
were already green in smoke pass 1); smoke pass 2 = 28/28;
calibration pass 1 = first full evaluation, 28/28 gates, wall
46.9 s, adjudication fired TRANSFER_DOMINANT; amendment a2 after
calibration pass 1 (REPORTING ONLY: the G31 gate text still
printed the pre-a1 toy constants -- text aligned, no number
moved); calibration pass 2 identical to pass 1 in every printed
figure; record run1/run2 after this insertion, identical up to
WALL; the only post-freeze edits are a1/a2 and this record-table
insertion, which IS the protocol):
CAL_VERDICT = DECOMPOSITION_EXACT(worst identity dev 8.8e-16 of
the decomposition scale, kernel reproduction worst 7.5e-16,
attribution worst 5.4e-16, 47/47 worlds) + TRANSFER_TABLE(MAIN
med -3.94 dec sl -1.386; |T| med -2.01 dec sl -0.698; share med
0.99 sl +0.016; T < 0 on 0/42; T_diag med -2.14 dec, T_cross
med -1.44e-4; canc_T med 1.69 sl +0.207; Delta class shares
b+/b-/w+/w- 0.55/0.00/0.26/0.18) + TRANSFER_DOMINANT(the signed
Delta structure is the precised gap object) + IMBALANCE_NOTE(
BROAD_BASED: sl(imb) +0.244 vs drop-top-1 +0.188 / drop-top-3
+0.197; sp(Mb, |t_j|) med +0.69, argmax coincidence 13/42).
Key numbers.  S2: contribution ward 2.1e-13 main / 3.9e-13 deep
/ 2.4e-8 controls; block + autocorr identities worst 6.3e-16 /
2.7e-15 on 47 worlds; r297 anchors bit-near (sigma -0.714,
sigma* -0.516, sl_c2 +0.196, sl_pref +0.489, margin 0.198;
D_rank med 0.024 sl -0.42, imb sl +0.244; orth WINDOW HOLDS
worst 5.1e-7 / BORDER cross med 1.101 in band).  S3: the sum
rule re-proved exact in Fractions (orth dev 0, identity dev 0,
module-own == r297-G31); m1 wrong-b^2 dev 806/343 != 0 CAUGHT;
toys exact (worst 0.0); m3 kernel-perturbed break 2/3 exact
LOUD; m4a/m4b FLAGGED by the scope audit.  S4: Delta anatomy
(w9): border 361 ws-atoms (+) / 6 -vs-atoms (-) vs window 263 /
104, support overlap 367 (PARTIALLY SHARED unions); bulk
|c|-mass shares b+/b-/w+/w- 0.60/0.00/0.25/0.16; the LINEAR
WINDOW ZERO now MEASURED: |sum wu x v2| / sum |wu x v2| worst
2.2e-12 main / 6.4e-12 deep / 5.0e-7 controls -- the window
image of the drive functional VANISHES at float precision: the
drive is 100 pct transfer at the LINEAR level, on all 47
worlds.  S5 (the decision): the OPPOSITE of the r259/r261
near-cancellation pattern -- the window main term is EMPTY, not
huge: MAIN/M^2 med -3.94 dec (two decades BELOW S_F med -2.00
dec), slope -1.386 (collapsing); T = S_F - MAIN is positive on
42/42 rungs with share med 0.99 and slope -0.698 ~ sigma; the
component split localizes further: T_cross = 2 B(PDelta,
Pomega) med -1.4e-4 (negligible) => S_F ~ B(PDelta, PDelta):
THE VDC INPUT IS THE FEJER ENERGY OF THE DIFFERENCE MEASURE
ITSELF; the in-T sign cancellation sum|t_j|/|T| med 1.69 with
slope +0.207 -- the r297 imbalance growth (+0.217 CS step)
reappears INSIDE T as the growing gap between |t_j|-mass and
the signed sum; exception rungs sh 0.99-1.00, canc_T 1.14
(kz39) .. 1.83 (kz52); controls EPST/SCR same class T-MAJORITY
-- WORLD-BLIND, no tag.  S6: Leg C VOID (no substitute).  S7
Leg D: BROAD_BASED -- dropping the top-1/top-3 mass runs
lowers the imbalance slope from +0.244 to +0.188/+0.197 but
does NOT kill it (bar for OUTLIER_CARRIED was <= +0.122): the
growth is broad; the connection stat is real: sp(block mass,
|t_j|) med +0.69 -- the mass-heavy blocks ARE the T-heavy
blocks (argmax coincidence 13/42): the two r297 gap halves
(mass imbalance, signed transfer) are ONE structure seen twice.
S8: m2 magnitude-Delta breaks the exact identity by 1.7e+0
(w9) / 5.1e-1 (w13) of the decomposition scale LOUD -- the
r297 magnitude error certified as a mustfail; SMOOTH alias
2.4e-14, q_N 4.2e-25; mp wards kz15 2.9e-10, kz64 9.3e-9,
kz52 6.6e-8.  READING (typed, no upgrade): the round DELIVERS
the transfer statement the lane asked for, and it is SHARPER
than hoped: S_F = B(omega,omega) + B(Delta,omega+beta) is
exact, world-blind and sign-preserving -- and on the real
chain the window main term VANISHES at both levels (linear:
exactly, by orthogonality; quadratic: med two decades below,
slope -1.39), while the omega-Delta cross term is negligible
(med -1.4e-4).  So the exact development collapses to S_F ~
B(PDelta, PDelta) + [exact tiny corrections]: the vdC input IS
the Fejer block energy of the border-minus-window difference
measure.  The provenance question is now maximally localized:
sigma = -0.714 is the decay exponent of ONE named source-pure
quantity, the Delta Fejer energy, whose in-block sign
cancellation (canc_T med 1.69, growing +0.21) carries exactly
the structure every |.|-chain loses (m2: factor ~1.7 of scale).
NOT a bound, NOT a theorem yet -- but the gap object of the
lane is no longer 'some magnitude chain misses sigma': it is
'prove the Fejer-energy decay of Delta', with the Leg-D
unification (the mass-imbalance carriers are the same blocks)
as the concrete geometric handle for wave 9.  Runtime 46.9 s
full / 0.2 s smoke; run1/run2 identical up to WALL.
AMENDMENTS AFTER FREEZE: NONE beyond the disclosed a1/a2
(records inserted per protocol; no bar, band, rule or verdict
rule moved).

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
from fractions import Fraction as Fr

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 cancellation_adjudication_probe as CA   # noqa: E402 r263
import coupledtau_probe as CT                  # noqa: E402 r257
import terminal_crossratio_probe as TX         # noqa: E402 r260
import border_resolvent_identity_probe as BR   # noqa: E402 r266
import phase_bulk_bound_probe as PBB           # noqa: E402 r269
import l2_deterministic_cancellation_probe as L2D  # noqa: E402 r287
import vdc_chain_provenance_probe as VCP       # noqa: E402 r297
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)
CTRL_FLIPS = {"EPSTEIN": 25, "SCRAMBLE": 21, "SMOOTH": 27}
H_CAP = 900
B57 = 5.0 / 7.0
M_W = math.sqrt(B57)
CHEAP_EXPECT = 35
EXC_KZ_EXPECT = (15, 20, 22, 36, 38, 39, 52)
TB_WARD_BAR = 1e-9
TB_WARD_BAR_DEEP = 3e-6
TB_WARD_BAR_CTRL = 1e-6
DEEP_N = 400
ID_BAR = 1e-12
AC_BAR = 1e-9
KER_BAR = 1e-12
DEC_BAR = 1e-12
ATTR_BAR = 1e-9
LIN_BAR = 1e-9
LIN_BAR_DEEP = 3e-6
LIN_BAR_CTRL = 1e-6
TOY_BAR = 1e-14
MUT_MIN = 1e-6
EDGE_F = 0.20
PAIR_OFFSET = 0
DELTA_NEED = 0.21
UNSTABLE_FACTOR = 10.0
SUB_SHARE = 0.5
SUB_MARGIN = 0.05
OUT_FACTOR = 0.5
ID_HOLDS = 1e-6
BORDER_CROSS_BAND = (0.8, 1.4)
R297_SIGMA = -0.714
R297_SIGMA_TOL = 0.01
R297_SIGMA_STAR = -0.516
R297_SSTAR_TOL = 0.01
R297_SL_C2 = 0.196
R297_SL_C2_TOL = 0.01
R297_SL_PREF = 0.489
R297_SL_PREF_TOL = 0.01
R297_DRANK_MED = 0.024
R297_DRANK_TOL = 0.005
R297_DRANK_SL = -0.42
R297_DRANK_SL_TOL = 0.05
R297_IMB_SL = 0.244
R297_IMB_SL_TOL = 0.01
MP_DPS = 60
MP_T_BAR = 1e-8
MP_DEEP_BAR = 3e-6
SM_Q_BAR = 1e-20
SM_ALIAS_BAR = 1e-12
KZ_ANCHOR = 15

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; every readout "
                       "consumes node positions + signed weights + "
                       "the r244 chain rows; ground truth (branch "
                       "labels, true R/t/Z) enters gates and census "
                       "tables only"
                       if not bad else "; ".join(bad))


def antigate_fragment_audit():
    """AST scan for forbidden method families (identifiers only;
    the fragment table itself is assembled from split strings)."""
    frags = ("cand_" + "unroll", "poly" + "fit", "curve_" + "fit",
             "lst" + "sq", "mini" + "mize", "Line" + "arRegression")
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    hits = []
    for node in ast.walk(tree):
        nm = None
        if isinstance(node, ast.Attribute):
            nm = node.attr
        elif isinstance(node, ast.Name):
            nm = node.id
        elif isinstance(node, ast.FunctionDef):
            nm = node.name
        if nm and any(f in nm for f in frags):
            hits.append("%s@%d" % (nm, node.lineno))
    return hits


BOUND_FORBIDDEN = {"t" + "_term", "Z", "Zl", "margin", "M" + "_W",
                   "loss", "R" + "_bulk", "truth", "rho",
                   "g" + "_branch", "need"}


def scope_audit(funcname, forbidden):
    """walk ONLY the named function's subtree; flag any withheld/
    truth-side identifier or dict key from the sealed set."""
    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 forbidden:
                    hits.append("%s@%d" % (nm, sub.lineno))
    return hits


# ---------------- exact Fractions section: the Parseval sum rule
# ---------------- (module-own re-proof + the m1 wrong-b^2 mutant)
def fr_parseval_sumrule(wrong_b=False):
    """the Parseval-type sum rule on the rational 4-node measure
    x = (0, 1, 2, 3), w = (1, 2, 1, 3) (r297-G31 verbatim): monic
    three-term chain pi_0..pi_3, orthogonality dev + the identity
    sum w x^2 pi_k^2 == h_{k+1} + a_k^2 h_k + b_k^2 h_{k-1} for
    k = 1, exact.  wrong_b replaces b_k^2 by b_k on the RHS --
    the m1 mutant, must break (dev != 0)."""
    xs = [Fr(0), Fr(1), Fr(2), Fr(3)]
    ws = [Fr(1), Fr(2), Fr(1), Fr(3)]
    n = len(xs)
    pis = [[Fr(1)] * n]
    a_ = []
    b_ = []
    hs = [sum(w * p * p for w, p in zip(ws, pis[0]))]
    for k in range(3):
        ak = sum(w * x * p * p for w, x, p in zip(ws, xs, pis[k])) \
            / hs[k]
        bk = (hs[k] / hs[k - 1]) if k >= 1 else Fr(0)
        nxt = []
        for i in range(n):
            v = (xs[i] - ak) * pis[k][i]
            if k >= 1:
                v -= bk * pis[k - 1][i]
            nxt.append(v)
        pis.append(nxt)
        a_.append(ak)
        b_.append(bk)
        hs.append(sum(w * p * p for w, p in zip(ws, nxt)))
    worst_orth = Fr(0)
    for a in range(4):
        for b in range(a):
            worst_orth = max(worst_orth,
                             abs(sum(w * pis[a][i] * pis[b][i]
                                     for i, w in enumerate(ws))))
    k = 1
    lhs = sum(w * x * x * p * p
              for w, x, p in zip(ws, xs, pis[k]))
    bco = b_[k] if wrong_b else b_[k] ** 2
    rhs = hs[k + 1] + a_[k] ** 2 * hs[k] + bco * hs[k - 1]
    return worst_orth, abs(lhs - rhs)


# ---------------- the frozen positional Fejer kernel machinery.
# ---------------- Source-pure: positions, weights and chain
# ---------------- values only; the withheld terminal drive key,
# ---------------- the branch label and every target-side
# ---------------- identifier are forbidden in scope (AST audit).
def block_breaks(bxs_bulk, runs):
    """midpoint breakpoints between consecutive level-2 block
    position intervals of the border bulk (runs = r269
    runs_split output on the sorted bulk; blocks = adjacent run
    pairs from PAIR_OFFSET 0, odd tail its own block).  Returns
    (breaks ascending, m blocks, per-atom block index)."""
    nr = len(runs)
    m = (nr - PAIR_OFFSET + 1) // 2 if nr else 0
    jb = np.zeros(len(bxs_bulk), dtype=int)
    for i, (a, b, _s) in enumerate(runs):
        jb[a:b] = i // 2
    brk = []
    for j in range(m - 1):
        a_last = runs[min(2 * j + 1, nr - 1)][1] - 1
        b_first = runs[2 * (j + 1)][0]
        brk.append(0.5 * (bxs_bulk[a_last] + bxs_bulk[b_first]))
    return np.asarray(brk, dtype=float), m, jb


def aggregate_blocks(xs, cs, lo, hi, brk, m):
    """positional block aggregation of ANY atom list: edge atoms
    (r268 mask on the combined hull) dropped, block index by
    breakpoint search, values summed per block -> P vector."""
    xs = np.asarray(xs, dtype=float)
    cs = np.asarray(cs, dtype=float)
    ed = PBB.mask_edge(xs, lo, hi, EDGE_F)
    xb = xs[~ed]
    cb = cs[~ed]
    if m == 0 or len(xb) == 0:
        return np.zeros(max(m, 0))
    j = np.searchsorted(brk, xb)
    return np.bincount(j, weights=cb, minlength=m)


def window_vec(P, H):
    """the sliding H-window sums of the zero-padded block vector
    (m + H - 1 windows; the v964-S0 Fejer core)."""
    m = len(P)
    p = np.zeros(m + 2 * (H - 1))
    p[H - 1:H - 1 + m] = np.asarray(P, dtype=float)
    c = np.concatenate(([0.0], np.cumsum(p)))
    return c[H:] - c[:-H]


def fejer_bil(Pa, Pb, H):
    """the Fejer block bilinear form B(u, v) = (1/H) sum_t
    W_t(u) W_t(v) = sum_{j,j'} (1 - |j - j'|/H)+ u_j v_{j'}."""
    return float(np.sum(window_vec(Pa, H) * window_vec(Pb, H))) / H


def fejer_apply(v, H):
    """phi = K v with K the Fejer block kernel (symmetric
    convolution) -- the per-block attribution carrier."""
    kern = np.array([1.0 - abs(h) / H for h in range(-(H - 1), H)])
    return np.convolve(np.asarray(v, dtype=float), kern,
                       mode="same")


def mutant_gift_bound(rc, P):
    """m4a MUST-FAIL MUTANT: a 'transfer term' oriented by the
    withheld ground-truth terminal drive key -- the scope audit
    must FLAG this."""
    s = math.copysign(1.0, rc["t_term"])
    return s * fejer_bil(P, P, 2)


def mutant_branch_peek(rc, P):
    """m4b MUST-FAIL MUTANT (world-blindness break simulated): a
    'main term' that consumes the branch label to pick its
    constant -- the scope audit must FLAG this."""
    c = 0.5 if rc["g_branch"] >= 0.0 else 2.0
    return c * fejer_bil(P, P, 2)


# ---------------------------------------------- toy exact tools
def toy_transfer():
    """the hand toy (spec Leg E): border atoms (0..4) with ct
    (3,-1,2,-4,1); window atoms (0.5, 2.5) with c (1,-1); H = 2.
    Every pipeline stage must reproduce EXACTLY (bar 1e-14)."""
    worst = 0.0
    bx = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
    ct = np.array([3.0, -1.0, 2.0, -4.0, 1.0])
    lo, hi = -10.0, 14.0                 # edge zones miss all atoms
    ed = PBB.mask_edge(bx, lo, hi, EDGE_F)
    worst = max(worst, float(np.sum(ed)))
    runs = PBB.runs_split(ct)
    brk, m, jb = block_breaks(bx, runs)
    worst = max(worst, abs(m - 3),
                float(np.max(np.abs(jb - np.array([0, 0, 1, 1, 2])))),
                float(np.max(np.abs(brk - np.array([1.5, 3.5])))))
    Pb = aggregate_blocks(bx, ct, lo, hi, brk, m)
    worst = max(worst,
                float(np.max(np.abs(Pb - np.array([2.0, -2.0, 1.0])))))
    H = 2
    sf = fejer_bil(Pb, Pb, H)
    worst = max(worst, abs(sf - 3.0))
    f2 = L2D.bound_vdc(list(Pb))
    worst = max(worst, abs(f2["s2"] / f2["H"] - sf))
    Pw = aggregate_blocks(np.array([0.5, 2.5]),
                          np.array([1.0, -1.0]), lo, hi, brk, m)
    worst = max(worst,
                float(np.max(np.abs(Pw - np.array([1.0, -1.0, 0.0])))))
    main = fejer_bil(Pw, Pw, H)
    Pd = Pb - Pw
    T = fejer_bil(Pd, Pb + Pw, H)
    worst = max(worst, abs(main - 1.0), abs(T - 2.0),
                abs(main + T - sf))
    phi = fejer_apply(Pb + Pw, H)
    tj = Pd * phi
    worst = max(worst,
                float(np.max(np.abs(tj
                                    - np.array([1.5, 1.0, -0.5])))),
                abs(float(np.sum(tj)) - T))
    td = fejer_bil(Pd, Pd, H)
    tc = 2.0 * fejer_bil(Pd, Pw, H)
    worst = max(worst, abs(td - 1.0), abs(tc - 1.0),
                abs(td + tc - T))
    return worst


def toy_mustfail_m3():
    """m3 KERNEL-PERTURBED RECOMPOSITION (toy level): the Fejer
    form at H + 1 breaks the toy identity: S_F(H=2) = 3 vs
    S_F(H=3) = 7/3 -- break 2/3, LOUD."""
    Pb = np.array([2.0, -2.0, 1.0])
    return abs(fejer_bil(Pb, Pb, 3) - fejer_bil(Pb, Pb, 2))


# --------------------------------------------------------------- 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("window_border_transfer_probe -- PRIME.PORT.L2."
          "WINDOW_BORDER_TRANSFER.01 (round 298)")
    print("SPEC_SHA %s   R287_SHA %s (imported)   R297_SHA %s "
          "(imported)"
          % (SPEC_SHA[:16], L2D.SPEC_SHA[:16], VCP.SPEC_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 + controls + Fractions section "
                        "+ toys + scope audits + decomposition "
                        "gates at w9; ladder, slopes, adjudication, "
                        "Legs C/D, mp wards 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,
          "THE WINDOW-BORDER TRANSFER ROUND (the r297 asset-1 "
          "attachment point): the chain is exactly orthogonal on "
          "the WINDOW union and the Parseval sum rule is proved "
          "there; the vdC input S_F lives on the BORDER union; "
          "this round freezes Delta := border (-) window and the "
          "positional Fejer block kernel, and tests the EXACT "
          "sign-preserving split S_F = B(omega,omega) + "
          "B(Delta,omega+beta) = MAIN + T(Delta); three sealed "
          "outcomes (SUBDOMINANT / DOMINANT / UNSTABLE with "
          "r259/r261 crossref); DELTA_NEED %.2f, sigma* %.3f "
          "(r297 records); disclosed structural prior: the "
          "LINEAR window functional vanishes exactly "
          "(orthogonality corollary) -- the drive is 100 pct "
          "transfer at the linear level; ALL bars, rules and "
          "verdicts sealed BEFORE evaluation"
          % (DELTA_NEED, R297_SIGMA_STAR))

    # ---------------- S1: census + controls (r297 scaffold verbatim)
    section("S1  CENSUS + CONTROLS")
    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)
    if smoke:
        ladder = []
        okL = True
    else:
        kzs = [kz for kz in core.frame_a_zones()
               if PIK.build_rung(kz)["h"] <= H_CAP]
        ladder = [BH.wpack(kz) for kz in kzs]
        ladder.sort(key=lambda p: (p["N"], p["kz"]))
        okL = (len(ladder) == 42
               and all(p["nf"] is None for p in ladder))
    check("G10-census-controls", okC and okCf and okL,
          "MAIN free prefix positive at full depth (%s, N = %s); "
          "control flips re-derived %s; cofinal ladder %d rungs "
          "POSITIVE_PREFIX %s, N in [%s, %s]"
          % (str(sorted(packs)),
             str({t: packs[t]["N"] for t in packs}),
             str({c: ctrl[c]["nf"] for c in ctrl}),
             len(ladder),
             "42/42" if okL and ladder else ("n/a (SMOKE)"
                                             if smoke else "FAIL"),
             ladder[0]["N"] if ladder else "-",
             ladder[-1]["N"] if ladder else "-"))

    pool = ladder if not smoke else [packs["w9"]]
    mains = [packs["w%d" % kz] for kz in windows]

    def rung_rec(p):
        N = p["N"]
        rows = p["rows"]
        r, t, ap, bp = TX.drive_arrays(rows, N)
        g = CA.g_gap(r[:N - 1], t, ap, bp)
        chain = ap[N - 2] * r[N - 2] + bp[N - 2] * r[N - 3]
        Z = t[N - 2] + chain
        xu, wu = CT.union_arrays(p["d"])
        bx, bw = CT.union_arrays(p["dsm"])
        lo = min(float(np.min(xu)), float(np.min(bx)))
        hi = max(float(np.max(xu)), float(np.max(bx)))
        v2 = BR.eval_scaled(rows, bx, N - 2)
        v2w = BR.eval_scaled(rows, xu, N - 2)
        fac = math.exp(rows[N - 2]["Ls"] - rows[N - 1]["Ls"]) \
            / math.sqrt(abs(rows[N - 1]["eta"]))
        ct = bw * bx * v2 * fac
        cw = wu * xu * v2w * fac
        o = np.argsort(bx, kind="stable")
        return dict(kz=p["kz"], N=N, g_branch=g, Z=Z, chain=chain,
                    t_term=float(t[N - 2]), ct=ct, bx=bx, bw=bw,
                    v2=v2, fac=fac, xu=xu, wu=wu, cw=cw, o=o,
                    lo=lo, hi=hi, p=p)

    recs = [rung_rec(p) for p in pool]
    mrecs = [rung_rec(p) for p in mains]
    crecs = {c: rung_rec(ctrl[c]) for c in ctrl}
    cheap = [rc for rc in recs if rc["g_branch"] >= 0.0]
    exc = [rc for rc in recs if rc["g_branch"] < 0.0]
    exc_kz = tuple(sorted(rc["kz"] for rc in exc))
    if smoke:
        check("G11-branch-reproduction", recs[0]["g_branch"] >= 0.0,
              "SMOKE: w9 branch %s (g %+.3f); ladder "
              "decomposition skipped"
              % ("CHEAP" if recs[0]["g_branch"] >= 0 else
                 "EXCEPTION", recs[0]["g_branch"]))
    else:
        check("G11-branch-reproduction",
              len(cheap) == CHEAP_EXPECT
              and exc_kz == tuple(sorted(EXC_KZ_EXPECT))
              and all(rc["g_branch"] >= 0 for rc in mrecs),
              "r263 branch rule reproduced EXACTLY: cheap %d/42, "
              "exception set %s == the named 7; mains %s"
              % (len(cheap), str(exc_kz),
                 "; ".join("w%d g %+.3f CHEAP" % (rc["kz"],
                                                  rc["g_branch"])
                           for rc in mrecs)))

    # ---------------- S2: decomposition + identities + r297 anchors
    section("S2  EXACT DECOMPOSITION + IDENTITIES + R297 ANCHORS")
    tb_worst = 0.0
    tb_deep = 0.0
    tb_ctrl = 0.0
    for rc in recs + mrecs:
        absum = float(np.sum(np.abs(rc["ct"])))
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(absum, 1e-300)
        if rc["N"] > DEEP_N:
            tb_deep = max(tb_deep, dev)
        else:
            tb_worst = max(tb_worst, dev)
    for c in crecs:
        rc = crecs[c]
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(float(np.sum(np.abs(rc["ct"]))), 1e-300)
        tb_ctrl = max(tb_ctrl, dev)
    check("G20-contribution-ward", tb_worst <= TB_WARD_BAR
          and tb_deep <= TB_WARD_BAR_DEEP
          and tb_ctrl <= TB_WARD_BAR_CTRL,
          "sum_b ct_b == t_{N-2} on %d rungs + %d mains + 3 "
          "controls: worst dev/absmass %.1e main N<=%d (bar %.0e) "
          "/ %.1e deep (bar %.0e) / %.1e controls (bar %.0e)"
          % (len(recs), len(mrecs), tb_worst, DEEP_N,
             TB_WARD_BAR, tb_deep, TB_WARD_BAR_DEEP, tb_ctrl,
             TB_WARD_BAR_CTRL))

    def eval_rung(rc):
        o = rc["o"]
        bxs = rc["bx"][o]
        cts = rc["ct"][o]
        bws = rc["bw"][o]
        ed = PBB.mask_edge(bxs, rc["lo"], rc["hi"], EDGE_F)
        cb = cts[~ed]
        xb = bxs[~ed]
        wb = bws[~ed]
        runs = PBB.runs_split(cb)
        Mr = [float(np.sum(np.abs(cb[a:b]))) for a, b, _s in runs]
        Sr = [float(np.sum(cb[a:b])) for a, b, _s in runs]
        sg = [s for _a, _b, s in runs]
        alt_ok = all(sg[i + 1] == -sg[i]
                     for i in range(len(sg) - 1))
        R = sum(Sr)
        P = L2D.blocks_level2(Sr)
        e_c2 = PBB.bound_pairsum(Mr)
        f2 = L2D.bound_vdc(P)
        H = f2["H"]
        S_F = f2["s2"] / H
        Zl = float(np.sum(cts[ed])) + rc["chain"]
        # ---- the frozen positional kernel (from the border bulk)
        brk, m, jb = block_breaks(xb, runs)
        Pb = np.bincount(jb, weights=cb, minlength=m) \
            if m else np.zeros(0)
        agg_dev = float(np.max(np.abs(Pb - np.array(P)))) \
            / max(max(abs(v) for v in P), 1e-300) if m else 0.0
        sf_ker = fejer_bil(Pb, Pb, H)
        ker_dev = abs(sf_ker - S_F) / max(S_F, 1e-300)
        # ---- window side through the SAME kernel
        Pw = aggregate_blocks(rc["xu"], rc["cw"], rc["lo"],
                              rc["hi"], brk, m)
        main = fejer_bil(Pw, Pw, H)
        Pd = Pb - Pw
        T = fejer_bil(Pd, Pb + Pw, H)
        scale = max(S_F, main, abs(T), 1e-300)
        dec_dev = abs(S_F - main - T) / scale
        phi = fejer_apply(Pb + Pw, H)
        tj = Pd * phi
        attr_dev = abs(float(np.sum(tj)) - T) / scale
        t_diag = fejer_bil(Pd, Pd, H)
        t_cross = 2.0 * fejer_bil(Pd, Pw, H)
        comp_dev = abs(t_diag + t_cross - T) / scale
        # ---- magnitude-Delta mutant (m2): |c| aggregation
        Pb_abs = aggregate_blocks(xb, np.abs(cb), rc["lo"],
                                  rc["hi"], brk, m)
        Pw_abs = aggregate_blocks(rc["xu"], np.abs(rc["cw"]),
                                  rc["lo"], rc["hi"], brk, m)
        T_mut = fejer_bil(Pb_abs - Pw_abs, Pb + Pw, H)
        m2_break = abs(S_F - main - T_mut) / scale
        # ---- linear window zero (full support, edge included)
        lin_dev = abs(float(np.sum(rc["cw"]))) \
            / max(float(np.sum(np.abs(rc["cw"]))), 1e-300)
        # ---- class split of the Delta anatomy
        Pb_p = aggregate_blocks(xb[wb > 0], cb[wb > 0], rc["lo"],
                                rc["hi"], brk, m)
        Pb_n = aggregate_blocks(xb[wb <= 0], cb[wb <= 0], rc["lo"],
                                rc["hi"], brk, m)
        wpos = rc["wu"] > 0
        Pw_p = aggregate_blocks(rc["xu"][wpos], rc["cw"][wpos],
                                rc["lo"], rc["hi"], brk, m)
        Pw_n = aggregate_blocks(rc["xu"][~wpos], rc["cw"][~wpos],
                                rc["lo"], rc["hi"], brk, m)
        cls = [float(np.sum(np.abs(v)))
               for v in (Pb_p, Pb_n, Pw_p, Pw_n)]
        tot_cls = max(sum(cls), 1e-300)
        cls = [v / tot_cls for v in cls]
        # ---- node-density census (r297-B2 continuity, Leg D)
        nb = len(cb)
        nr = len(runs)
        d_rank = 0.0
        if nr > 1 and nb > 0:
            for i, (a, b, _s) in enumerate(runs[:-1]):
                d_rank = max(d_rank, abs(b / nb - (i + 1) / nr))
        mx = max(Mr) if Mr else 0.0
        sm = sum(Mr) if Mr else 0.0
        imb = nr * mx / max(sm, 1e-300)
        Ms = sorted(Mr, reverse=True)
        s1 = Ms[0] / max(sm, 1e-300) if Ms else 0.0
        s3 = sum(Ms[:3]) / max(sm, 1e-300) if Ms else 0.0
        M_d1 = Ms[1:]
        M_d3 = Ms[3:]
        imb_d1 = (len(M_d1) * M_d1[0] / max(sum(M_d1), 1e-300)) \
            if M_d1 else 0.0
        imb_d3 = (len(M_d3) * M_d3[0] / max(sum(M_d3), 1e-300)) \
            if M_d3 else 0.0
        Mb = [Mr[i] + (Mr[i + 1] if i + 1 < nr else 0.0)
              for i in range(0, nr, 2)]
        sp_conn = BH.spearman(Mb, list(np.abs(tj))) \
            if m >= 3 else 0.0
        coin = int(int(np.argmax(np.abs(tj))) ==
                   int(np.argmax(Mb))) if m else 0
        return dict(Mr=Mr, Sr=Sr, alt_ok=alt_ok, R=R, P=P,
                    e_c2=e_c2, f2=f2, H=H, S_F=S_F, Zl=Zl,
                    m=len(P), nr=nr, brk=brk, Pb=Pb, Pw=Pw, Pd=Pd,
                    agg_dev=agg_dev, ker_dev=ker_dev, main=main,
                    T=T, dec_dev=dec_dev, tj=tj,
                    attr_dev=attr_dev, t_diag=t_diag,
                    t_cross=t_cross, comp_dev=comp_dev,
                    m2_break=m2_break, lin_dev=lin_dev, cls=cls,
                    d_rank=d_rank, imb=imb, s1=s1, s3=s3,
                    imb_d1=imb_d1, imb_d3=imb_d3,
                    sp_conn=sp_conn, coin=coin)

    all_rc = recs + mrecs
    for rc in all_rc:
        rc["ev"] = eval_rung(rc)
    for c in crecs:
        crecs[c]["ev"] = eval_rung(crecs[c])

    alt_all = all(rc["ev"]["alt_ok"] for rc in all_rc)
    bid_worst = 0.0
    ac_worst = 0.0
    for rc in all_rc + [crecs[c] for c in crecs]:
        ev = rc["ev"]
        bid_worst = max(bid_worst,
                        abs(sum(ev["P"]) - ev["R"])
                        / max(abs(ev["R"]), 1e-300))
        A = L2D.autocorr_full(ev["P"])
        s_all = A[0] + 2.0 * float(np.sum(A[1:]))
        ac_worst = max(ac_worst,
                       abs(s_all - sum(ev["P"]) ** 2)
                       / max(A[0], 1e-300))
    check("G21-block-and-autocorr-identity",
          alt_all and bid_worst <= ID_BAR and ac_worst <= AC_BAR,
          "runs alternate on every world AND sum P == R exact "
          "(worst rel %.1e, bar %.0e) AND (sum P)^2 == A(0) + 2 "
          "sum A(h) exact (worst %.1e x A(0), bar %.0e) over %d "
          "worlds" % (bid_worst, ID_BAR, ac_worst, AC_BAR,
                      len(all_rc) + len(crecs)))

    Ns = [rc["N"] for rc in recs]
    if not smoke:
        eps_c2_rel = [rc["ev"]["e_c2"] / M_W for rc in recs]
        sl_c2 = L2D.halves_slope(Ns, eps_c2_rel)
        pref = [(rc["ev"]["m"] + rc["ev"]["H"] - 1) / rc["ev"]["H"]
                for rc in recs]
        sl_pref = L2D.halves_slope(Ns, pref)
        sf_rel = [rc["ev"]["S_F"] / (M_W * M_W) for rc in recs]
        sigma = L2D.halves_slope(Ns, sf_rel)
        sigma_star = 2.0 * (sl_c2 - DELTA_NEED) - sl_pref
        check("G22-r297-target-anchors",
              abs(sigma - R297_SIGMA) <= R297_SIGMA_TOL
              and abs(sigma_star - R297_SIGMA_STAR) <= R297_SSTAR_TOL
              and abs(sl_c2 - R297_SL_C2) <= R297_SL_C2_TOL
              and abs(sl_pref - R297_SL_PREF) <= R297_SL_PREF_TOL,
              "the r297 target-inequality set recomputed bit-near: "
              "sigma %+.3f (ref %+.3f), sigma* %+.3f (ref %+.3f), "
              "sl_c2 %+.3f (ref %+.3f), sl_pref %+.3f (ref %+.3f) "
              "-- the truth margin %.3f sigma stands"
              % (sigma, R297_SIGMA, sigma_star, R297_SIGMA_STAR,
                 sl_c2, R297_SL_C2, sl_pref, R297_SL_PREF,
                 sigma_star - sigma))
        dr_med = float(np.median([rc["ev"]["d_rank"]
                                  for rc in recs]))
        dr_sl = L2D.halves_slope(Ns, [max(rc["ev"]["d_rank"],
                                          1e-300) for rc in recs])
        imb_sl = L2D.halves_slope(Ns, [rc["ev"]["imb"]
                                       for rc in recs])
        check("G23-r297-census-anchors",
              abs(dr_med - R297_DRANK_MED) <= R297_DRANK_TOL
              and abs(dr_sl - R297_DRANK_SL) <= R297_DRANK_SL_TOL
              and abs(imb_sl - R297_IMB_SL) <= R297_IMB_SL_TOL,
              "the r297 asset-2 census recomputed: D_rank med "
              "%.3f (ref %.3f) slope %+.2f (ref %+.2f, falling "
              "-- provable terrain), mass-imbalance slope %+.3f "
              "(ref %+.3f, the growing half)"
              % (dr_med, R297_DRANK_MED, dr_sl, R297_DRANK_SL,
                 imb_sl, R297_IMB_SL))
    else:
        sigma = sigma_star = sl_c2 = sl_pref = float("nan")
        check("G22-r297-target-anchors", True,
              "SMOKE: skipped (needs the 42-rung ladder)")
        check("G23-r297-census-anchors", True,
              "SMOKE: skipped (needs the 42-rung ladder)")

    # ---------------- S3: exact section + toys + audits + m1/m3
    section("S3  EXACT SECTION (FRACTIONS) + TOYS + SCOPE AUDITS")
    w_o, w_i = fr_parseval_sumrule(wrong_b=False)
    v_o, v_i = VCP.fr_symbolic_sumrule()
    _o2, w_mut = fr_parseval_sumrule(wrong_b=True)
    check("G30-sumrule-and-m1", w_o == 0 and w_i == 0
          and v_o == 0 and v_i == 0 and w_mut != 0,
          "the Parseval sum rule RE-PROVED exact in Fractions "
          "(module-own orth dev %s, identity dev %s; r297-G31 "
          "import devs %s/%s); m1 WRONG-b^2 mutant (b_k for "
          "b_k^2) breaks by %s != 0 -- CAUGHT: the squared "
          "recurrence norm ratio is load-bearing"
          % (str(w_o), str(w_i), str(v_o), str(v_i), str(w_mut)))
    toy_worst = toy_transfer()
    check("G31-toy-exactness", toy_worst <= TOY_BAR,
          "the hand toy reproduces the WHOLE pipeline EXACTLY "
          "(worst dev %.1e, bar %.0e): border (0..4)/(3,-1,2,-4,"
          "1) -> Pbeta (2,-2,1), breaks (1.5, 3.5), S_F = 3 == "
          "kernel form; window (0.5, 2.5)/(1,-1) -> Pomega "
          "(1,-1,0), MAIN = 1; PDelta (1,-1,1), T = 2, MAIN + T "
          "== S_F; attribution (1.5, 1, -0.5) sums to T; T_diag "
          "1 + T_cross 1 == T" % (toy_worst, TOY_BAR))
    h_bb = scope_audit("block_breaks", BOUND_FORBIDDEN)
    h_ag = scope_audit("aggregate_blocks", BOUND_FORBIDDEN)
    h_fb = scope_audit("fejer_bil", BOUND_FORBIDDEN)
    h_fa = scope_audit("fejer_apply", BOUND_FORBIDDEN)
    h_gift = scope_audit("mutant_gift_bound", BOUND_FORBIDDEN)
    h_peek = scope_audit("mutant_branch_peek", BOUND_FORBIDDEN)
    ag_hits = antigate_fragment_audit()
    clean = not (h_bb or h_ag or h_fb or h_fa)
    check("G32-scope-audits", clean and bool(h_gift)
          and bool(h_peek) and not ag_hits,
          "the kernel builders (block_breaks, aggregate_blocks, "
          "fejer_bil, fejer_apply) consume positions + weights + "
          "chain values only (no truth-side identifier in "
          "scope%s); m4a gift mutant FLAGGED (%s); m4b "
          "branch-peek mutant FLAGGED (%s); fragment audit: %s"
          % ("" if clean else " VIOLATION",
             "; ".join(h_gift) if h_gift else "NOT FLAGGED",
             "; ".join(h_peek) if h_peek else "NOT FLAGGED",
             "CLEAN" if not ag_hits else "; ".join(ag_hits)))
    m3_break = toy_mustfail_m3()
    check("G33-mustfail-m3", m3_break >= MUT_MIN
          and abs(m3_break - 2.0 / 3.0) <= 1e-12,
          "m3 KERNEL-PERTURBED RECOMPOSITION: the Fejer form at "
          "H + 1 breaks the toy identity by %.6f (= 2/3 exact, "
          ">= %.0e) LOUD -- the frozen H is load-bearing in the "
          "kernel, not a free dial" % (m3_break, MUT_MIN))

    # ---------------- S4: Leg A -- the exact decomposition
    section("S4  LEG A: DELTA ANATOMY + DECOMPOSITION_EXACT")
    rc9 = mrecs[0] if not smoke else recs[0]
    n_bp = int(np.sum(rc9["bw"] > 0))
    n_bn = len(rc9["bw"]) - n_bp
    n_wp = int(np.sum(rc9["wu"] > 0))
    n_wn = len(rc9["wu"]) - n_wp
    overlap = len(np.intersect1d(rc9["bx"], rc9["xu"]))
    cls9 = rc9["ev"]["cls"]
    check("G40-delta-anatomy", True,
          "Delta = border (-) window, FOUR signed atom classes "
          "(w9): border ws %d atoms (+) / -vs %d atoms (-) vs "
          "window ws %d / -vs %d; exact support overlap %d "
          "(the unions are %s); bulk |c|-mass shares of the "
          "classes b+/b-/w+/w- = %.2f/%.2f/%.2f/%.2f -- the "
          "mixed-sign structure the r297 |.|-chains lost is "
          "carried atomwise here"
          % (n_bp, n_bn, n_wp, n_wn, overlap,
             "FULLY DISJOINT" if overlap == 0
             else "PARTIALLY SHARED",
             cls9[0], cls9[1], cls9[2], cls9[3]))
    pool_all = all_rc + [crecs[c] for c in crecs]
    agg_w = max(rc["ev"]["agg_dev"] for rc in pool_all)
    ker_w = max(rc["ev"]["ker_dev"] for rc in pool_all)
    check("G41-kernel-reproduction", agg_w <= KER_BAR
          and ker_w <= KER_BAR,
          "the frozen positional kernel REPRODUCES the sealed "
          "r287 pipeline from raw border atoms on %d worlds: "
          "block aggregation vs blocks_level2 worst %.1e; "
          "(1/H) sum W^2 vs bound_vdc S_F worst %.1e (bar %.0e) "
          "-- S_F IS the Fejer quadratic form B(beta, beta)"
          % (len(pool_all), agg_w, ker_w, KER_BAR))
    dec_w = max(rc["ev"]["dec_dev"] for rc in pool_all)
    att_w = max(max(rc["ev"]["attr_dev"], rc["ev"]["comp_dev"])
                for rc in pool_all)
    check("G42-decomposition-exact", dec_w <= DEC_BAR
          and att_w <= ATTR_BAR,
          "DECOMPOSITION_EXACT: S_F = B(omega,omega) + "
          "B(Delta,omega+beta) = MAIN + T(Delta) on %d worlds, "
          "worst dev %.1e of the decomposition scale (bar %.0e); "
          "attribution sum_j t_j == T and T_diag + T_cross == T "
          "worst %.1e (bar %.0e) -- the split is an exact finite "
          "identity, sign structure fully preserved"
          % (len(pool_all), dec_w, DEC_BAR, att_w, ATTR_BAR))
    lin_m = max((rc["ev"]["lin_dev"] for rc in all_rc
                 if rc["N"] <= DEEP_N), default=0.0)
    lin_d = max((rc["ev"]["lin_dev"] for rc in all_rc
                 if rc["N"] > DEEP_N), default=0.0)
    lin_c = max(crecs[c]["ev"]["lin_dev"] for c in crecs)
    check("G43-linear-window-zero", lin_m <= LIN_BAR
          and lin_d <= LIN_BAR_DEEP and lin_c <= LIN_BAR_CTRL,
          "the LINEAR WINDOW ZERO (orthogonality corollary "
          "x pi_{N-2} perp pi_0 on omega): |sum wu x v2| / "
          "sum |wu x v2| worst %.1e main N<=%d (bar %.0e) / "
          "%.1e deep (bar %.0e) / %.1e controls (bar %.0e) -- "
          "the window image of the drive functional VANISHES: "
          "the drive is 100 pct transfer at the linear level"
          % (lin_m, DEEP_N, LIN_BAR, lin_d, LIN_BAR_DEEP,
             lin_c, LIN_BAR_CTRL))
    # orthogonality census (r297-S7 verbatim, WINDOW + BORDER)
    id_pool = (mrecs + [crecs[c] for c in ("EPST", "SCR")]) \
        if smoke else \
        ([rc for rc in recs if rc["kz"] in (KZ_ANCHOR, 20)]
         + mrecs + [crecs[c] for c in ("EPST", "SCR")])
    orth = {}
    for meas in ("WINDOW", "BORDER"):
        crosses = []
        devs = []
        for rc in id_pool:
            X, W = ((rc["xu"], rc["wu"]) if meas == "WINDOW"
                    else (rc["bx"], rc["bw"]))
            cq = VCP.chain_quads(rc["p"]["rows"], rc["N"], X, W)
            crosses.append(max(abs(v) for v in cq["cr"].values()))
            devs.append(abs(cq["q2"] - cq["pd"])
                        / max(abs(cq["q2"]), 1e-300))
        orth[meas] = (float(np.median(crosses)),
                      max(max(crosses), max(devs)))
    ok_orth = (orth["WINDOW"][1] <= ID_HOLDS
               and BORDER_CROSS_BAND[0] <= orth["BORDER"][0]
               <= BORDER_CROSS_BAND[1])
    check("G44-orthogonality-anchor", ok_orth,
          "the r297-S7 census recomputed on %d worlds: WINDOW "
          "orthogonality HOLDS (worst cross+diag dev %.1e <= "
          "%.0e) while BORDER breaks (cross med %.3f in %s) -- "
          "the attachment point and the break, both bit-near "
          "the record" % (len(id_pool), orth["WINDOW"][1],
                          ID_HOLDS, orth["BORDER"][0],
                          str(BORDER_CROSS_BAND)))

    # ---------------- S5: Leg B -- the transfer-term scaling
    section("S5  LEG B: TRANSFER SCALING + SEALED ADJUDICATION")
    show = (sorted(exc, key=lambda r_: r_["kz"]) + mrecs
            if not smoke else mrecs)
    for rc in show:
        ev = rc["ev"]
        info("kz%-3d N%-4d %-4s m %-3d H %-2d  S_F %.4f  MAIN "
             "%.3f  T %+.3f  sh %.2f  canc_T %.2f"
             % (rc["kz"], rc["N"],
                "EXC" if rc["g_branch"] < 0 else "chp",
                ev["m"], ev["H"], ev["S_F"], ev["main"], ev["T"],
                abs(ev["T"]) / max(ev["S_F"], 1e-300),
                float(np.sum(np.abs(ev["tj"])))
                / max(abs(ev["T"]), 1e-300)))
    if not smoke:
        main_rel = [rc["ev"]["main"] / (M_W * M_W) for rc in recs]
        absT_rel = [max(abs(rc["ev"]["T"]), 1e-300) / (M_W * M_W)
                    for rc in recs]
        sl_main = L2D.halves_slope(Ns, main_rel)
        sl_T = L2D.halves_slope(Ns, absT_rel)
        sh = [abs(rc["ev"]["T"]) / max(rc["ev"]["S_F"], 1e-300)
              for rc in recs]
        rmain = [rc["ev"]["main"] / max(rc["ev"]["S_F"], 1e-300)
                 for rc in recs]
        sh_med = float(np.median(sh))
        sh_sl = L2D.halves_slope(Ns, [max(v, 1e-300) for v in sh])
        rmain_med = float(np.median(rmain))
        n_neg = sum(1 for rc in recs if rc["ev"]["T"] < 0.0)
        canc = [float(np.sum(np.abs(rc["ev"]["tj"])))
                / max(abs(rc["ev"]["T"]), 1e-300) for rc in recs]
        canc_med = float(np.median(canc))
        canc_sl = L2D.halves_slope(Ns, canc)
        td_med = float(np.median(
            [math.log10(max(rc["ev"]["t_diag"], 1e-300))
             for rc in recs]))
        tc_med = float(np.median([rc["ev"]["t_cross"]
                                  for rc in recs]))
        main_med = float(np.median(
            [math.log10(max(v, 1e-300)) for v in main_rel]))
        absT_med = float(np.median(
            [math.log10(max(v, 1e-300)) for v in absT_rel]))
        sf_med = float(np.median(
            [math.log10(max(rc["ev"]["S_F"] / (M_W * M_W),
                            1e-300)) for rc in recs]))
        cls_med = [float(np.median([rc["ev"]["cls"][i]
                                    for rc in recs]))
                   for i in range(4)]
        check("G50-transfer-table", True,
              "TRANSFER_TABLE (42 rungs): MAIN/M^2 med %+.2f dec "
              "slope %+.3f; |T|/M^2 med %+.2f dec slope %+.3f; "
              "S_F/M^2 med %+.2f dec (sigma %+.3f); share "
              "|T|/S_F med %.2f slope %+.3f; T < 0 on %d/42; "
              "T_diag med %+.2f dec, T_cross med %+.3g; in-T "
              "cancellation sum|t_j|/|T| med %.2f slope %+.3f; "
              "Delta class shares b+/b-/w+/w- med "
              "%.2f/%.2f/%.2f/%.2f"
              % (main_med, sl_main, absT_med, sl_T, sf_med,
                 sigma, sh_med, sh_sl, n_neg, td_med, tc_med,
                 canc_med, canc_sl, cls_med[0], cls_med[1],
                 cls_med[2], cls_med[3]))
        # world controls: same class rules at the control rungs
        def classify(rm, s_):
            if rm >= UNSTABLE_FACTOR:
                return "UNSTABLE"
            return "T-MINORITY" if s_ < SUB_SHARE else "T-MAJORITY"
        ctl_cls = {}
        for c in ("EPST", "SCR"):
            ev = crecs[c]["ev"]
            ctl_cls[c] = classify(
                ev["main"] / max(ev["S_F"], 1e-300),
                abs(ev["T"]) / max(ev["S_F"], 1e-300))
        main_cls = classify(rmain_med, sh_med)
        world_blind = all(ctl_cls[c] == main_cls for c in ctl_cls)
        check("G51-world-controls", True,
              "the decomposition class at the control rungs "
              "(same sealed med rules): MAIN %s vs %s -- %s "
              "(a class break is a disclosed finding, not a "
              "gate failure; the identity itself is world-blind "
              "by the same algebra, G42)"
              % (main_cls,
                 str({c: ctl_cls[c] for c in sorted(ctl_cls)}),
                 "WORLD-BLIND" if world_blind
                 else "WORLD_SENSITIVE (disclosed)"))
        # sealed adjudication
        if rmain_med >= UNSTABLE_FACTOR:
            outcome = "DECOMPOSITION_UNSTABLE"
        elif sh_med < SUB_SHARE and sl_T <= sl_main - SUB_MARGIN:
            outcome = "TRANSFER_SUBDOMINANT"
        else:
            outcome = "TRANSFER_DOMINANT"
        check("G52-adjudication", True,
              "SEALED RULE fired: %s (med(MAIN/S_F) %.1f vs "
              "UNSTABLE_FACTOR %.0f; share med %.2f vs %.1f; "
              "slope(|T|) %+.3f vs slope(MAIN) %+.3f - %.2f)"
              % (outcome, rmain_med, UNSTABLE_FACTOR, sh_med,
                 SUB_SHARE, sl_T, sl_main, SUB_MARGIN))
    else:
        outcome = "SMOKE_NO_ADJUDICATION"
        world_blind = True
        main_cls = "n/a"
        ctl_cls = {}
        sl_main = sl_T = sh_med = sh_sl = rmain_med = float("nan")
        canc_med = canc_sl = main_med = absT_med = float("nan")
        td_med = tc_med = float("nan")
        n_neg = -1
        cls_med = [float("nan")] * 4
        check("G50-transfer-table", True, "SMOKE: skipped")
        check("G51-world-controls", True, "SMOKE: skipped")
        check("G52-adjudication", True, "SMOKE: skipped")

    # ---------------- S6: Leg C (conditional)
    section("S6  LEG C: THE CANDIDATE THEOREM (CONDITIONAL)")
    if outcome == "TRANSFER_SUBDOMINANT":
        info("CANDIDATE THEOREM (window-border transfer, L2 "
             "generic half): for every rung of the sealed ladder "
             "(N in [%d, %d], H = ceil(sqrt(m))): S_F = "
             "B(omega,omega) + B(Delta,omega+beta) EXACTLY (this "
             "round); B(omega,omega) is Parseval-controlled on "
             "the orthogonal side (proved sum rule + D_rank "
             "equidistribution, slope %+.3f <= sigma* %+.3f "
             "REQUIRED: %s) and T(Delta) is subdominant "
             "(share med %.2f, slope gap %+.3f); with the r297 "
             "target inequality sigma <= sigma* and the v964-S0 "
             "vdC theorem => delta' > %.2f on the generic half; "
             "exceptions: 6 via the r287 F2 certificates, kz15 "
             "via the r270 exact-finite certificate.  Wave-9 "
             "promotion candidate -- NOT promoted here."
             % (min(Ns), max(Ns), sl_main, sigma_star,
                "MET" if sl_main <= sigma_star else "NOT MET "
                "(disclosed: the composition is conditional)",
                sh_med, sl_main - sl_T, DELTA_NEED))
        fired = True
    else:
        info("Leg C VOID without substitute (outcome %s).  The "
             "precisely narrowed gap object is documented in the "
             "verdict." % outcome)
        fired = False
    check("G60-leg-c", True,
          "Leg C %s -- fires ONLY on TRANSFER_SUBDOMINANT by the "
          "sealed rule; no post-hoc rescue"
          % ("FIRED (candidate printed, NOT promoted)" if fired
             else "VOID"))

    # ---------------- S7: Leg D -- mass-imbalance bycatch
    section("S7  LEG D: MASS-IMBALANCE BYCATCH")
    if not smoke:
        sl_imb = L2D.halves_slope(Ns, [rc["ev"]["imb"]
                                       for rc in recs])
        sl_d1 = L2D.halves_slope(
            Ns, [max(rc["ev"]["imb_d1"], 1e-300) for rc in recs])
        sl_d3 = L2D.halves_slope(
            Ns, [max(rc["ev"]["imb_d3"], 1e-300) for rc in recs])
        s1_med = float(np.median([rc["ev"]["s1"] for rc in recs]))
        s3_med = float(np.median([rc["ev"]["s3"] for rc in recs]))
        outlier = sl_d3 <= OUT_FACTOR * sl_imb
        sp_med = float(np.median([rc["ev"]["sp_conn"]
                                  for rc in recs]))
        n_coin = sum(rc["ev"]["coin"] for rc in recs)
        check("G70-imbalance-bycatch", True,
              "IMBALANCE_NOTE: %s -- slope(imb) %+.3f vs "
              "drop-top-1 %+.3f / drop-top-3 %+.3f (OUTLIER iff "
              "d3 <= %.1f x imb); top-1/top-3 mass shares med "
              "%.2f/%.2f; CONNECTION of the gap halves: "
              "sp(block mass, |t_j|) med %+.2f, argmax "
              "coincidence %d/42 -- %s"
              % ("OUTLIER_CARRIED" if outlier else "BROAD_BASED",
                 sl_imb, sl_d1, sl_d3, OUT_FACTOR, s1_med,
                 s3_med, sp_med, n_coin,
                 "the mass carriers and the T carriers largely "
                 "coincide" if sp_med >= 0.5 else
                 "the two gap halves are structurally separate"))
    else:
        outlier = False
        sl_imb = sl_d1 = sl_d3 = sp_med = float("nan")
        n_coin = -1
        check("G70-imbalance-bycatch", True, "SMOKE: skipped")

    # ---------------- S8: must-fail m2 + anchors + mp wards
    section("S8  MUSTFAIL M2 + ANCHORS + MP WARDS")
    m2_pool = mrecs + ([recs[0]] if smoke else [])
    m2_min = min(rc["ev"]["m2_break"] for rc in m2_pool)
    m2_note = "; ".join("w%d %.1e" % (rc["kz"],
                                      rc["ev"]["m2_break"])
                        for rc in m2_pool)
    check("G80-mustfail-m2", m2_min >= MUT_MIN,
          "m2 MAGNITUDE DELTA (|c| aggregation instead of the "
          "signed c -- the r297 magnitude error as a mustfail): "
          "the exact identity breaks by %s of the decomposition "
          "scale (all >= %.0e) LOUD -- the sign structure of "
          "Delta is load-bearing; any |.|-transfer loses the "
          "object" % (m2_note, MUT_MIN))
    rowsS = ctrl["SMOOTH"]["rows"]
    NS = ctrl["SMOOTH"]["N"]
    scT = [abs(rowsS[k]["tb"] * math.exp(rowsS[k]["Ls"]
                                         - rowsS[k + 1]["Ls"]))
           for k in range(NS - 1)]
    alias = max(scT[2:]) / max(scT[0], scT[1])
    qS = float(ctrl["SMOOTH"]["rho"][NS - 1]) / B57
    evS = crecs["SMOOTH"]["ev"]
    okSd = evS["dec_dev"] <= DEC_BAR
    check("G81-smooth-anchor", alias <= SM_ALIAS_BAR
          and abs(qS) <= SM_Q_BAR and okSd,
          "SMOOTH: drive alias %.1e <= %.0e; q_N = %.1e <= %.0e; "
          "the decomposition identity holds trivially on the "
          "self-aliased source (%s)"
          % (alias, SM_ALIAS_BAR, qS, SM_Q_BAR,
             "OK" if okSd else "BROKEN"))
    if not smoke:
        mp_note = []
        ok_mp = True
        rc15 = next(r_ for r_ in recs if r_["kz"] == KZ_ANCHOR)
        t15 = PBB.mp_drive(rc15["p"], MP_DPS)
        d15 = abs(t15 - rc15["t_term"])
        ok_mp = ok_mp and (d15 <= MP_T_BAR)
        mp_note.append("kz15 (N %d) dev %.1e (bar %.0e)"
                       % (rc15["N"], d15, MP_T_BAR))
        for rc in recs[-2:]:
            t_mp = PBB.mp_drive(rc["p"], MP_DPS)
            dv = abs(t_mp - rc["t_term"])
            ok_mp = ok_mp and (dv <= MP_DEEP_BAR)
            mp_note.append("kz%d (N %d, DEEPEST) dev %.1e (bar "
                           "%.0e)" % (rc["kz"], rc["N"], dv,
                                      MP_DEEP_BAR))
        check("G82-mp-deep-wards", ok_mp,
              "mp (dps %d) terminal drive at the trend-critical "
              "rungs: %s" % (MP_DPS, "; ".join(mp_note)))
    else:
        check("G82-mp-deep-wards", True, "SMOKE: skipped")

    # ---------------- S9: verdict
    section("S9  VERDICT")
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the exact sign-preserving window-border "
          "decomposition of the vdC input on the frozen "
          "positional Fejer kernel, its measured scaling census, "
          "the sealed three-way adjudication, and the Leg-D "
          "bycatch -- NO new certificate promoted, NO bound "
          "modification of the sealed forms")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        parts = ["DECOMPOSITION_EXACT(S_F = B(omega,omega) + "
                 "B(Delta,omega+beta), Delta = border (-) window, "
                 "frozen positional Fejer kernel, worst dev "
                 "%.1e, %d/%d worlds)"
                 % (dec_w, len(pool_all), len(pool_all))]
        parts.append("TRANSFER_TABLE(MAIN med %+.2f dec sl "
                     "%+.3f; |T| med %+.2f dec sl %+.3f; share "
                     "med %.2f sl %+.3f; T<0 %d/42; canc_T med "
                     "%.2f sl %+.3f)"
                     % (main_med, sl_main, absT_med, sl_T,
                        sh_med, sh_sl, n_neg, canc_med, canc_sl))
        if outcome == "DECOMPOSITION_UNSTABLE":
            parts.append("DECOMPOSITION_UNSTABLE(med MAIN/S_F "
                         "%.1f >= %.0f: main and transfer are "
                         "near-cancelling large copies -- THIS "
                         "cancellation is the object; the THIRD "
                         "recurrence of the resummation pattern, "
                         "crossref r259 prefix resummation + "
                         "r261 fullsource free-prefix)"
                         % (rmain_med, UNSTABLE_FACTOR))
        elif outcome == "TRANSFER_SUBDOMINANT":
            parts.append("TRANSFER_SUBDOMINANT(share med %.2f < "
                         "%.1f, slope gap %+.3f >= %.2f)"
                         % (sh_med, SUB_SHARE, sl_main - sl_T,
                            SUB_MARGIN))
            parts.append("CANDIDATE_THEOREM(window-border "
                         "transfer, printed in S6, wave-9 "
                         "candidate NOT promoted)")
        else:
            parts.append("TRANSFER_DOMINANT(share med %.2f; T "
                         "anatomy: T_diag med %+.2f dec, "
                         "T_cross med %+.3g, class shares "
                         "b+/b-/w+/w- %.2f/%.2f/%.2f/%.2f, "
                         "in-T cancellation med %.2f -- the "
                         "signed Delta structure is the "
                         "precised gap object)"
                         % (sh_med, td_med, tc_med, cls_med[0],
                            cls_med[1], cls_med[2], cls_med[3],
                            canc_med))
        parts.append("IMBALANCE_NOTE(%s: sl imb %+.3f vs d1 "
                     "%+.3f / d3 %+.3f; sp(Mb,|t_j|) med %+.2f, "
                     "argmax coincidence %d/42)"
                     % ("OUTLIER_CARRIED" if outlier
                        else "BROAD_BASED", sl_imb, sl_d1,
                        sl_d3, sp_med, n_coin))
        if not world_blind:
            parts.append("WORLD_SENSITIVE(main %s vs %s -- "
                         "disclosed finding)"
                         % (main_cls, str(ctl_cls)))
        verd = " + ".join(parts)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G96-verdict", npass == len(CHECKS),
          "%s%s -- SATZ (machine-gated): the decomposition "
          "identity, the kernel reproduction, the attribution, "
          "the linear window zero, the Fractions sum rule (all "
          "world-blind); MEASURED: every slope, share, class "
          "and connection stat (42 rungs only); OPEN: the "
          "cancellation mechanism between MAIN and T (if "
          "UNSTABLE) / the Delta anatomy theorem (if DOMINANT), "
          "the cofinal step H5, kz15 beyond r270; 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"""fejer_decay_probe -- PRIME.PORT.L2.FEJER_DECAY.01 (round 299):
the DECAY ANATOMY of the Delta Fejer energy -- can the decay of
B(PDelta, PDelta) (the r297 target sigma <= sigma* = -0.516) be
derived SOURCE-PURELY from position equidistribution (provable
terrain) plus a controllable statement about the signed mass
structure?  Context (sealed record inputs): r297 (SPEC e42a76eb)
froze the target inequality sigma := slope(S_F/M_W^2) <= sigma* =
-0.516 (measured sigma = -0.714, margin 0.198) and left two
assets: exact window orthogonality + falling boundary-position
discrepancy (D_rank med 0.024, slope -0.42) against growing mass
imbalance (+0.244); r298 (SPEC 05e831be) proved the exact
sign-preserving split S_F = B(omega,omega) + B(Delta,omega+beta)
on the frozen positional Fejer kernel and adjudicated
TRANSFER_DOMINANT: the window main term is EMPTY (med -3.94 dec,
slope -1.386), the cross term negligible (med -1.4e-4), so
S_F ~ B(PDelta, PDelta) -- THE VDC INPUT IS THE FEJER ENERGY OF
THE DIFFERENCE MEASURE; sigma is ITS decay exponent; the in-T
sign cancellation sum|t_j|/|T| (med 1.69) GROWS at +0.207 -- the
enemy of every magnitude route; the sign mixing of Delta sits in
the c-values (6 negative atoms only; w9: 367 exact position
overlaps between the unions).  kz15 permanently closed via r270;
the 6 exceptions via the r287 F2 certificates.

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

THE OBJECT (r269/r287/r297/r298 machinery imported verbatim):
t_{N-2} = sum_b ct_b (r244 chain rows, r266 eval); F = 0.20 edge
split; maximal same-sign runs of the bx-sorted bulk; level-2
blocks (r270 convention); FROZEN vdC window H = max(2,
ceil(sqrt(m))); the frozen positional Fejer block kernel (r298:
block_breaks + aggregate_blocks + fejer_bil + fejer_apply,
imported verbatim); PDelta = Pbeta - Pomega; the round's central
quantity is the DELTA FEJER ENERGY B := B(PDelta, PDelta) =
(1/H) sum_t W_t(PDelta)^2.  THE EXACT SPECTRAL REPRESENTATION
(module-own, the h-decomposition of the frozen kernel): with L =
the smallest power of two >= 2 x (m + H) (FROZEN rule; L >=
2m - 1 kills circular aliasing, L >= m + H - 1 keeps the Fejer
support intact) and Dhat(k) = FFT_L(PDelta),

  B  =  (1/L) sum_k F_H(theta_k) |Dhat(k)|^2,      theta_k = 2 pi k / L,

with F_H(theta) = |sum_{j<H} e^{-ij theta}|^2 / H >= 0 the Fejer
kernel (computed as the padded FFT of the H-ones window, no
sin singularity) -- an EXACT finite identity (recomposition
gated <= 1e-9 rel on all 47 worlds; Parseval mean identity
(1/L) sum_k |Dhat|^2 = sum_j PDelta_j^2 gated too; every term
nonnegative).  F_H is a LOW-PASS kernel with main lobe |theta|
<= 2 pi / H (disclosed structural prior: the LOW band is
kernel-favored; the bands measure where |Dhat|^2 puts its
energy INSIDE the weighted form).

LEG 0 -- ANCHOR REGRESSION (r297/r298 record numbers adopted
as-is, disclosed): sigma = -0.714 tol 0.01, sigma* = -0.516 tol
0.01 (sl_c2 +0.196, sl_pref +0.489, tol 0.01); D_rank med 0.024
tol 0.005 slope -0.42 tol 0.05; imbalance slope +0.244 tol 0.01;
the r298 decomposition recomputed bit-near: identity/kernel
devs <= 1e-12, attribution <= 1e-9, share med 0.99 tol 0.02,
slope(MAIN) -1.386 tol 0.05, slope(|T|) -0.698 tol 0.05, T > 0
on 42/42, canc_T med 1.69 tol 0.05 slope +0.207 tol 0.02,
|T_cross med| <= 1e-3, w9 support overlap == 367 EXACT, linear
window zero <= 1e-9 main / 3e-6 deep / 1e-6 controls; the r297
Parseval sum rule re-computed exact in Fractions (import).

LEG A -- THE FREQUENCY ANATOMY OF DELTA (where does the energy
live?): per rung the exact spectral split of B into the three
FROZEN bands LOW (|theta| <= 2 pi / H, the Fejer main lobe),
MID (2 pi / H < |theta| <= pi / 2), EDGE (|theta| > pi / 2);
band shares (med) + band-energy slopes on the 42-rung ladder;
the mean-vs-max census: mean_k |Dhat|^2 = sum PDelta_j^2 (the
Parseval identity -- the mean IS the B2 diagonal, disclosed)
and max_k |Dhat|^2 with slopes; the half/90-pct energy
frequencies q50/q90 in main-lobe units theta x H / (2 pi).
SEALED BAND ADJUDICATION (exactly one): LOWPASS iff
med(share_LOW) >= 0.75 (few low frequencies dominate -- their
individual decay is the provable-terrain shape); BROADBAND iff
med(share_LOW) < 0.50; else MIXED_BAND.  Fine type:
SPECTRUM_MAP(band shares, slopes, mean/max decay, tag).

LEG B -- THE DECAY DERIVATION ROUTES (the core; every route an
exact per-rung statement on all 47 worlds, source-pure, AST
scope audit):
(B1) ERDOS-TURAN / ABEL ROUTE (position x mass, the provable
  terrain): per frequency the EXACT factorization |Dhat(k)| <=
  Dpos(theta_k) x V(PDelta) with Dpos(theta) = min(m,
  1/|sin(theta/2)|) (pure geometric-sum position bound on the
  block lattice) and V = sum_j |PDelta_{j+1} - PDelta_j| +
  |PDelta_{m-1}| (the Abel mass term, v964-S0 T4 form); the
  composed bound B <= V^2 x Phi_pos with Phi_pos = (1/L) sum_k
  F_H(theta_k) Dpos(theta_k)^2 (position/kernel factor,
  universal on the block lattice); slopes sl_pos = slope(
  Phi_pos), sl_mass = slope(V^2/M^2), exact slope additivity
  gated (<= 1e-9); MASS_TARGET_FROZEN printed as a standalone
  target inequality: slope(V^2/M^2) <= sigma* - sl_pos (needed
  vs measured, MET/NOT MET); census: the r297 D_rank statistic
  now on Delta itself (sup-discrepancy of the bulk Delta atom
  positions against uniform on the bulk hull, med + slope).
(B2) PAIR-CORRELATION ROUTE: the exact split B = D + O with
  D = sum_j PDelta_j^2 (diagonal, positive, magnitudes) and
  O = 2 sum_{1<=h<H} (1 - h/H) A(h) (off-diagonal, signed);
  recomposition ward <= 1e-12 of scale; slopes sl_D, sl_|O|,
  O sign census, ratio B/D (med + slope).  Does the energy fall
  because D falls (a density statement) or because O cancels
  increasingly (then the pair phase is the object)?  Crossref
  disclosed: r287 found the BORDER block sequence REINFORCES
  ((sum P)^2 > sum P^2 on 39/44) -- whether PDelta shares this
  is measured here, not assumed.
(B3) OVERLAP ROUTE (the r298 anatomy trace): the EXACT split
  Delta = Delta_overlap (+) Delta_fresh by EXACT position
  equality between the unions (w9: 367 shared positions;
  Delta_overlap is a pure c-VALUE difference there); component
  vectors P_ov + P_fr = PDelta gated <= 1e-12; energy
  recomposition B = B(ov,ov) + 2 B(ov,fr) + B(fr,fr) gated <=
  1e-9 of the component scale; shares (med + slopes); the
  c-CONVERGENCE census at shared positions: cconv = sum_p
  |c_beta(p) - c_omega(p)| / sum_p |c_beta(p)| (med + slope) --
  if Delta_overlap dominates, the decay is a statement about
  the CONVERGENCE of the c-values (border -> window),
  connectable to the proven sum rule.  SEALED dominance class:
  OV_DOM iff med(B_ov/B) >= 0.75 and med(|B_x|/B) <= 0.50;
  FR_DOM symmetric on B_fr; else MIXED_OVERLAP.
SEALED DECAY ADJUDICATION (frozen BEFORE evaluation, exactly
one fires): route validity = every exact ward on 47 worlds;
  B1_OK iff valid and sl_pos + sl_mass <= sigma*;
  B2_OK iff valid and sl_D <= sigma* and slope(B/D) <= +0.05;
  B3_OK iff valid and class OV_DOM;
  DECAY_DERIVED(B1)  iff B1 valid and sl_pos <= sigma* and
    sl_mass <= 0.0 (the position/kernel factor alone meets the
    target and the mass factor is non-growing -- the only fully
    provable-terrain outcome; disclosed expectation: ambitious);
  DECAY_SPLIT(fired routes, rest targets frozen)  iff not
    DERIVED and (B1_OK or B2_OK or B3_OK) -- each firing route
    prints its frozen rest target (B1: MASS_TARGET; B2:
    DIAG_TARGET = prove the diagonal density decay; B3:
    CVALUE_TARGET = prove the c-value convergence rate);
  DECAY_STILL_EMPIRICAL(measured common obstruction) otherwise.
WORLD CONTROLS: the identities/wards hold on EPSTEIN/SCRAMBLE
by the same algebra (gates); the CLASSES (band tag, O sign,
overlap dominance, by the same med rules at the single control
rung) are compared against MAIN -- a class break is a disclosed
finding (WORLD_SENSITIVE tag), not a gate failure.

LEG C -- THEOREM COMPOSITION (fires ONLY on DECAY_DERIVED or on
DECAY_SPLIT with its frozen rest target as explicit hypothesis):
CANDIDATE THEOREM printed with every constant: Leg-B bound (+
frozen rest hypothesis if SPLIT) => sigma <= sigma* => the r297
target inequality => v964-S0 vdC => delta' > 0.21 on the
generic half; scope the 42 measured rungs (N in [142, 878]);
exceptions: 6 via r287 F2, kz15 via r270.  Wave-9 promotion
candidate -- NOT promoted here.  Otherwise Leg C is VOID
without substitute and the rest object is documented.

LEG D -- THE IN-T CANCELLATION LOCUS (bycatch, ONE table, no
interpretation): the magnitude spectrum B_abs = B(|PDelta|,
|PDelta|) >= B EXACTLY (window sums of magnitudes majorize,
gated); the cancellation gap G = B_abs - B band-resolved
(G_band = E_abs_band - E_band): band shares of G vs band shares
of B (med); block side: c_j = |t_j| - t_j (the r298 attribution,
nonnegative, positive exactly on cancelling blocks),
sp(block mass Mb, c_j) med + argmax coincidence n/42, next to
the r298 anchor sp(Mb, |t_j|) med.

LEG E -- WARDS / MUST-FAILS (>= 4 mutants + 2 scope mutants):
(m1) WRONG FEJER WEIGHT in the frequency decomposition: the lag
  recomposition with (1 - |h|/(H+1)) breaks the toy identity
  (B(PDelta=(1,-1,1), H=2) = 1 vs 1/3 -- break 2/3 EXACT) --
  CAUGHT; (m2) MAGNITUDE PAIR ROUTE (|PDelta| instead of
  PDelta): B(|PDelta|,|PDelta|) differs from B LOUDLY (>= 1e-6
  of scale on w9 + w13; toy 5 vs 1, break 4 exact) -- the pair
  phase is load-bearing; (m3) TOLERANT OVERLAP SPLIT (position
  tolerance 1e-3 instead of exact equality, toy): border (1.0,
  2.0)/(2,-1) + window (1.0005, 3.0)/(1,1), single block, H=2:
  the exact split has EMPTY overlap (B_ov = 0, B_fr = 1), the
  tolerant split moves energy between the classes (B_ov = 1,
  B_fr = 4) while BOTH recompose to B = 1 -- the recomposition
  is silent, the component shift is CAUGHT (>= 1e-6): the
  exact-equality convention is load-bearing; (m4) ERDOS-TURAN
  PREFACTOR FAMILY (exact Fractions, module-own, attaching to
  v964-S0 T4): (a) the Abel bound |sum P| <= D* x V re-proved
  on the frozen rational sequences with the toy record D* = 1,
  V = 2 on P = (2,-2,1); the DROPPED-TERMINAL mutant gives
  bound 0 < 2 on P = (1,1) -- CAUGHT; (b) the exact theta =
  pi/2 leg (e^{-i theta} = -i, Gaussian-rational pairs): the
  Abel resummation identity u = sum (c_n - c_{n+1}) E_n exact
  on c = (3,-1,2) (u = 1 + i, dev 0), the geometric position
  bound |E_n|^2 <= 1/sin^2(pi/4) = 2 with the n = 1 EQUALITY
  witness, |u|^2 = 2 <= max|E|^2 x V^2 = 162 exact; the HALVED
  position prefactor mutant (claim |E_n|^2 <= 1) breaks at the
  witness (2 > 1) -- CAUGHT; (m5a/m5b) WORLD-BLINDNESS BREAK:
  a builder consuming the withheld terminal drive key AND a
  builder consuming the branch label are both FLAGGED by the
  AST scope audit.  Scope hygiene: the new builders
  (spec_decomp, band_energies, et_factors, pair_split,
  overlap_split) consume positions + weights + chain values
  only (BOUND_FORBIDDEN set); fragment audit (no fit
  primitives); TOY EXACTNESS: the r298 hand kernel toy extended
  by a window atom AT a border position (border (0..4)/(3,-1,2,
  -4,1), window (1.0, 2.5)/(1,-1), H = 2): Pbeta (2,-2,1),
  Pomega (1,-1,0), PDelta (1,-1,1), B = 1; overlap = {1.0},
  P_ov = (-2,0,0), P_fr = (3,-1,1), B_ov = 4, B_fr = 7, B_x =
  -10, sum = 1 EXACT (bar 1e-14) -- the components are LARGE
  against their sum: the signed structure lives in the split;
  cconv toy = 2; pair toy D = 3, O = -2; ET toy V = 5; spectral
  toys at FFT precision (bar 1e-12): recomposition == 1,
  Parseval == 3, band sum == B; SMOOTH anchor (alias <= 1e-12,
  q_N <= 1e-20); mp SAMPLES (dps 60): kz15 (bar 1e-8) + the two
  deepest rungs (bar 3e-6).

INDEX FIREWALL (binding, r238-r298 discipline): w = window (kz),
N_w = builder depth, k/n = chain degree; ground truth (branch
labels, the true R/t/Z values) enters GATES and census tables
only; no zero/prime oracles anywhere (AST firewall); no fit
primitives (fragment audit).  MACHINERY IMPORTED VERBATIM: r298
WBT.block_breaks + WBT.aggregate_blocks + WBT.fejer_bil +
WBT.fejer_apply, r269 PBB.mask_edge + PBB.runs_split +
PBB.mp_drive, r287 L2D.blocks_level2 + L2D.bound_vdc +
L2D.halves_slope + L2D.autocorr_full, r297 VCP.chain_quads +
VCP.fr_symbolic_sumrule (the proven set re-computed, not
re-proved), r244 BH.wpack + BH.spearman, r257 CT.union_arrays,
r260 TX.drive_arrays, r263 CA.g_gap, r266 BR.eval_scaled, v881
PIK, r243 PB.smooth_comb.  B PROVENANCE: B_w = S_{N-2} + 5/7
(r241/r243 IMPORTED floor, never fitted).  COFINAL LADDER
(pre-sealed): frame-A h <= 900, 42 rungs, (N, kz)-sorted;
exception set {kz15, 20, 22, 36, 38, 39, 52}.

SEALED CONSTANTS: MAIN windows (9, 13); controls w9 EPSTEIN /
SCRAMBLE(seed 1) / SMOOTH, flips 25/21/27; H_CAP 900; B57 = 5/7;
M_W = sqrt(5/7); CHEAP_EXPECT 35; EXC_KZ_EXPECT (15, 20, 22, 36,
38, 39, 52); EDGE_F 0.20 (FROZEN); PAIR_OFFSET 0 (FROZEN);
DELTA_NEED 0.21; H rule = max(2, ceil(sqrt(m))) (FROZEN); L rule
= smallest power of two >= 2 x (m + H) (FROZEN); BANDS: LOW
|theta| <= 2 pi / H, MID <= pi / 2, EDGE else (FROZEN);
LOWPASS_BAR 0.75; BROAD_BAR 0.50; SPEC_BAR 1e-9 (spectral
recomposition + Parseval + abs-majorization, rel scale); ET_BAR
1e-9 (per-frequency Abel slack + composed bound, rel); ADD_BAR
1e-9 (slope additivity); PAIR_BAR 1e-12 (pair split, rel scale);
PART_BAR 1e-12 (overlap partition, rel max|PDelta|); EN_BAR 1e-9
(overlap energy recomposition, rel component scale);
RATIO_GROW 0.05; OV_DOM_BAR 0.75; XA_BAR 0.50; MASS_FLAT 0.0;
TOL_MUT 1e-3 (m3 mutant tolerance); KER_BAR/DEC_BAR 1e-12;
ATTR_BAR 1e-9; LIN_BARS 1e-9 main N <= 400 / 3e-6 deep / 1e-6
controls; TB_WARD bars 1e-9 / 3e-6 / 1e-6; ID_BAR 1e-12; AC_BAR
1e-9; TOY_BAR 1e-14; TOY_FFT_BAR 1e-12; MUT_MIN 1e-6; R297
anchors sigma -0.714 / sigma* -0.516 / sl_c2 +0.196 / sl_pref
+0.489 (tol 0.01), D_rank med 0.024 tol 0.005 slope -0.42 tol
0.05, imb slope +0.244 tol 0.01; R298 anchors share med 0.99
tol 0.02, sl_MAIN -1.386 tol 0.05, sl_|T| -0.698 tol 0.05,
T > 0 on 42/42, canc med 1.69 tol 0.05, canc slope +0.207 tol
0.02, |tc med| <= 1e-3, OVERLAP_W9 == 367 EXACT; MP_DPS 60;
MP_T_BAR 1e-8; MP_DEEP_BAR 3e-6; SM_Q_BAR 1e-20; SM_ALIAS_BAR
1e-12; KZ_ANCHOR 15; runtime <= 1800 s; smoke = w9 + controls +
Fractions section + toys + scope audits + every exact ward at
w9 (ladder, slopes, adjudications, Legs C/D aggregates, mp
wards skipped).  DISCLOSED PRE-SPEC INPUT (no scratch run of
this probe): every reproduction band is an r297/r298 RECORD
number adopted as-is; the low-pass structure of F_H and the
Parseval mean identity are derived algebra, disclosed above;
the three adjudication outcomes are sealed symmetrically -- the
disclosed structural priors (kernel low-pass favor; r297: the
border-P magnitudes REINFORCE; the mass imbalance grows) make
STILL_EMPIRICAL plausible, but no rule was chosen to favor an
outcome.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  SPECTRUM_MAP(band shares LOW/MID/EDGE med, band slopes,
    mean/max |Dhat|^2 slopes, q50/q90 med, band tag)
+ ROUTE_TABLE(B1 valid n/47 sl_pos sl_mass composed-vs-sigma*;
    B2 valid n/47 sl_D sl_|O| O-sign census B/D med + slope;
    B3 valid n/47 shares ov/x/fr med, cconv med + slope, class)
+ MASS_TARGET(the frozen standalone rest inequality of B1:
    needed vs measured, MET/NOT MET)
+ [exactly one of] DECAY_DERIVED(B1, ...) / DECAY_SPLIT(fired
    routes + frozen rest targets) / DECAY_STILL_EMPIRICAL(
    measured common obstruction)
+ [iff fired] CANDIDATE_THEOREM(decay composition, constants)
+ CANC_LOCUS(band shares of G vs B, sp(Mb, c_j) med,
    coincidence n/42, sp(Mb, |t_j|) med)
+ [if any control gate breaks] LOCAL_MODEL_MAIN_FITTED
+ [if a control class differs] WORLD_SENSITIVE(disclosed).
Honesty before beauty: the spectral representation, the ET
factorization, the pair split and the overlap split are EXACT
finite identities/inequalities, but every slope, share and
class is MEASURED on 42 rungs only; no verdict claims a cofinal
law; Phi_pos is universal on the block lattice -- the
equidistribution content enters through the block aggregation
and is measured (D_rank on Delta), not proved here; the
exception scalar's positivity beyond the measured 42 stays
OPEN; r243-r298 stand.

RECORD TABLES (frozen from the record run; calibration protocol:
smoke pass 1 = 32/32 (0.3 s, no amendment); calibration pass 1 =
first full evaluation, 32/32 gates, wall 48.3 s; amendments
AFTER calibration pass 1: a1 (the G71 world-blindness
conjunction did not include the O-sign class the sealed spec
text names -- code aligned with the spec, expected and realized
effect: the WORLD_SENSITIVE tag fires as a disclosed finding;
no bar, band or gate rule moved) + a2 (REPORTING ONLY: the G55
census additionally prints the full-support overlap count --
the calibration pass showed the unions share EVERY position);
calibration pass 2 = 32/32, identical to pass 1 in every printed
figure up to WALL and the disclosed a1/a2 lines; record run1/
run2 after this insertion, identical up to WALL; the only
post-freeze edits are a1/a2 and this record-table insertion,
which IS the protocol):
CAL_VERDICT = SPECTRUM_MAP(band shares LOW/MID/EDGE med
0.93/0.04/0.02; band-energy slopes -0.758/-0.014/-0.979; mean
|Dhat|^2 slope -0.571 (== the B2 diagonal), max slope -0.444;
q50 med 0.19 / q90 med 0.62 main-lobe units; LOWPASS -- the
Delta energy is concentrated INSIDE the Fejer main lobe: the
decay is a low-frequency phenomenon, not broadband) +
ROUTE_TABLE(B1 valid 47/47: sl_pos +1.504, sl_mass +0.444,
composed +1.948 FAILS sigma* -0.516 by 2.464 -- the position/
kernel factor Phi_pos GROWS and the Abel mass term V^2 grows
too: the ET route composes away the cancellation, the r297
magnitude-wall pattern recurs at the frequency level; B2 valid
47/47: sl_D -0.571 MEETS sigma* -0.516 (margin 0.055), sl_|O|
-0.815, O < 0 on 13/42 only (the PDelta pair field REINFORCES
in the majority -- the r287 border pattern carries over), B/D
med 1.29 slope -0.168 FALLING; B3 valid 47/47: shares ov/x/fr
med +1.00/+0.00/+0.00, FULL-SUPPORT overlap on 42/42 rungs --
THE STRUCTURAL FINDING: the border and window unions share
EVERY position, Delta_fresh == 0 identically, Delta IS a pure
c-value difference measure; cconv med 0.86 slope +0.045 (the
RELATIVE c-difference does NOT fall), class OV_DOM) +
MASS_TARGET(needed slope(V^2/M^2) <= sigma* - sl_pos = -2.021;
measured +0.444: NOT MET by 2.464) + DECAY_SPLIT(B2(
DIAG_TARGET: prove sl_D <= sigma*, measured -0.571, + ratio
flatness, measured -0.168) | B3(CVALUE_TARGET: prove the
c-value convergence rate, cconv slope +0.045)) +
CANDIDATE_THEOREM(conditional, printed in S6, wave-9 candidate
NOT promoted) + CANC_LOCUS(G = B_abs - B band shares
1.01/-0.01/-0.00 vs B 0.93/0.04/0.02 -- the cancellation gap
is ENTIRELY low-band; sp(Mb, c_j) med -0.01, argmax coincidence
3/42 -- the cancellation carriers are NOT the mass blocks;
r298 anchor sp(Mb, |t_j|) med +0.69) + WORLD_SENSITIVE(MAIN
LOWPASS/O_POS/OV_DOM vs EPST LOWPASS/O_NEG/OV_DOM + SCR
LOWPASS/O_NEG/OV_DOM -- the off-diagonal SIGN class separates
MAIN from the broken-arithmetic controls at their own rungs;
disclosed finding).
Key numbers.  S2: contribution ward 2.1e-13 main / 3.9e-13
deep / 2.4e-8 controls; block + autocorr identities worst
6.3e-16 / 2.7e-15 on 47 worlds; r297 anchors bit-near (sigma
-0.714, sigma* -0.516, sl_c2 +0.196, sl_pref +0.489; D_rank
med 0.024 sl -0.42, imb sl +0.244); r298 anchors bit-near
(identity 8.8e-16, kernel 7.5e-16, attribution 5.4e-16; lin
zero 2.2e-12 / 6.4e-12 / 5.0e-7; share med 0.99, sl_MAIN
-1.386, sl_|T| -0.698, T < 0 on 0/42, canc 1.69 sl +0.207, tc
med -1.4e-4, overlap w9 367; r297 sum rule import devs 0/0).
S3: the Fractions ET section exact (Abel resummation identity
dev 0, position bound slack 0 with the n = 1 equality witness,
|u|^2 = 2 <= 162); m4a dropped-terminal 0 < 2 CAUGHT, m4b
halved prefactor breaks by 1 at the witness CAUGHT; toys exact
(worst 0.0 exact / 0.0 FFT); m1 wrong-weight break 0.666667 =
2/3 exact LOUD; m3 tolerant-split component shift 3.0 + count
shift 1 with SILENT recomposition (dev 0.0) CAUGHT.  S4:
spectral wards worst recomposition 7.1e-16, Parseval 3.9e-16,
band sum 3.5e-16, magnitude-majorization slack 0.0, 47/47
worlds.  S5: B1 per-frequency slack -7.8e-1 (the bound holds
with 0.78 x sum|PDelta| margin), composed slack 0.0,
additivity dev 6.1e-16; D_rank(Delta) med 0.016 slope -0.12
(the Delta support inherits the falling equidistribution); B2
pair ward worst 8.2e-16; B3 partition worst 0.0, energy
recomposition worst 0.0; exception rungs in-table: sh_low
0.94 (kz22, kz52) .. 0.99 (kz39), cconv 0.70 (kz22) .. 0.94
(kz15, kz52); w13 is the only shown rung with O < 0 (-3.2e-3).
S8: m2 magnitude-pair break 1.3e+0 (w9) / 4.6e+0 (w13) of B
LOUD; SMOOTH alias 2.4e-14, q_N 4.2e-25, wards trivially
exact; mp wards kz15 2.9e-10, kz64 9.3e-9, kz52 6.6e-8.
READING (typed, no upgrade): the round DELIVERS the frequency
anatomy the lane asked for, and the answer is SHARPER than the
question: (1) the Delta Fejer energy is LOWPASS (med 0.93 in
the main lobe) -- sigma is a low-frequency phenomenon; (2) the
unions share their FULL support on 42/42 rungs: Delta is a
pure c-value difference measure -- the transfer object of r298
degenerates to ONE weight profile on ONE shared node set,
and the c-difference is relatively FLAT (cconv 0.86, +0.045):
the decay does NOT come from pointwise c-convergence but from
aggregate cancellation of a non-converging difference profile;
(3) the ET/Abel composition FAILS loudly (composed +1.948,
MASS_TARGET missed by 2.46) -- the r297 magnitude wall recurs
at the frequency level: position bounds compose away the
cancellation; (4) the LIVE EDGE is B2: the diagonal
sum PDelta_j^2 ALREADY falls fast enough (sl_D -0.571 <=
sigma* -0.516, margin 0.055) and the pair ratio B/D (med 1.29)
FALLS (-0.168) -- proving the two frozen rest statements
(DIAG_TARGET: a magnitude-density bound on ONE positive
quantity; RATIO flatness: the off-diagonal reinforcement does
not grow) would close the input gap through the vdC machine;
the sealed adjudication fired DECAY_SPLIT with this rest pair
frozen, Leg C printed the conditional composition.  Bycatch:
the in-T cancellation gap is entirely low-band and NOT carried
by the mass blocks (sp -0.01 vs the +0.69 energy coupling) --
the r297 imbalance growth and the in-T cancellation live in
the SAME band but on DIFFERENT blocks; and the O-sign class
separates MAIN (reinforcing) from both dead controls
(cancelling) -- the first world-separating sign class of the
L2 lane, disclosed as WORLD_SENSITIVE.  Runtime 48.3 s full /
0.3 s smoke; run1/run2 identical up to WALL.  AMENDMENTS AFTER
FREEZE: NONE beyond the disclosed a1/a2 (records inserted per
protocol; no bar, band, rule or verdict rule moved).

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
from fractions import Fraction as Fr

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 cancellation_adjudication_probe as CA   # noqa: E402 r263
import coupledtau_probe as CT                  # noqa: E402 r257
import terminal_crossratio_probe as TX         # noqa: E402 r260
import border_resolvent_identity_probe as BR   # noqa: E402 r266
import phase_bulk_bound_probe as PBB           # noqa: E402 r269
import l2_deterministic_cancellation_probe as L2D  # noqa: E402 r287
import vdc_chain_provenance_probe as VCP       # noqa: E402 r297
import window_border_transfer_probe as WBT     # noqa: E402 r298
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)
CTRL_FLIPS = {"EPSTEIN": 25, "SCRAMBLE": 21, "SMOOTH": 27}
H_CAP = 900
B57 = 5.0 / 7.0
M_W = math.sqrt(B57)
CHEAP_EXPECT = 35
EXC_KZ_EXPECT = (15, 20, 22, 36, 38, 39, 52)
TB_WARD_BAR = 1e-9
TB_WARD_BAR_DEEP = 3e-6
TB_WARD_BAR_CTRL = 1e-6
DEEP_N = 400
ID_BAR = 1e-12
AC_BAR = 1e-9
KER_BAR = 1e-12
DEC_BAR = 1e-12
ATTR_BAR = 1e-9
LIN_BAR = 1e-9
LIN_BAR_DEEP = 3e-6
LIN_BAR_CTRL = 1e-6
SPEC_BAR = 1e-9
ET_BAR = 1e-9
ADD_BAR = 1e-9
PAIR_BAR = 1e-12
PART_BAR = 1e-12
EN_BAR = 1e-9
LOWPASS_BAR = 0.75
BROAD_BAR = 0.50
RATIO_GROW = 0.05
OV_DOM_BAR = 0.75
XA_BAR = 0.50
MASS_FLAT = 0.0
TOL_MUT = 1e-3
TOY_BAR = 1e-14
TOY_FFT_BAR = 1e-12
MUT_MIN = 1e-6
EDGE_F = 0.20
PAIR_OFFSET = 0
DELTA_NEED = 0.21
R297_SIGMA = -0.714
R297_SIGMA_TOL = 0.01
R297_SIGMA_STAR = -0.516
R297_SSTAR_TOL = 0.01
R297_SL_C2 = 0.196
R297_SL_C2_TOL = 0.01
R297_SL_PREF = 0.489
R297_SL_PREF_TOL = 0.01
R297_DRANK_MED = 0.024
R297_DRANK_TOL = 0.005
R297_DRANK_SL = -0.42
R297_DRANK_SL_TOL = 0.05
R297_IMB_SL = 0.244
R297_IMB_SL_TOL = 0.01
R298_SH_MED = 0.99
R298_SH_TOL = 0.02
R298_SL_MAIN = -1.386
R298_SL_MAIN_TOL = 0.05
R298_SL_T = -0.698
R298_SL_T_TOL = 0.05
R298_CANC_MED = 1.69
R298_CANC_TOL = 0.05
R298_CANC_SL = 0.207
R298_CANC_SL_TOL = 0.02
R298_TC_ABS = 1e-3
R298_OVERLAP_W9 = 367
MP_DPS = 60
MP_T_BAR = 1e-8
MP_DEEP_BAR = 3e-6
SM_Q_BAR = 1e-20
SM_ALIAS_BAR = 1e-12
KZ_ANCHOR = 15

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; every readout "
                       "consumes node positions + signed weights + "
                       "the r244 chain rows; ground truth (branch "
                       "labels, true R/t/Z) enters gates and census "
                       "tables only"
                       if not bad else "; ".join(bad))


def antigate_fragment_audit():
    """AST scan for forbidden method families (identifiers only;
    the fragment table itself is assembled from split strings)."""
    frags = ("cand_" + "unroll", "poly" + "fit", "curve_" + "fit",
             "lst" + "sq", "mini" + "mize", "Line" + "arRegression")
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    hits = []
    for node in ast.walk(tree):
        nm = None
        if isinstance(node, ast.Attribute):
            nm = node.attr
        elif isinstance(node, ast.Name):
            nm = node.id
        elif isinstance(node, ast.FunctionDef):
            nm = node.name
        if nm and any(f in nm for f in frags):
            hits.append("%s@%d" % (nm, node.lineno))
    return hits


BOUND_FORBIDDEN = {"t" + "_term", "Z", "Zl", "margin", "M" + "_W",
                   "loss", "R" + "_bulk", "truth", "rho",
                   "g" + "_branch", "need"}


def scope_audit(funcname, forbidden):
    """walk ONLY the named function's subtree; flag any withheld/
    truth-side identifier or dict key from the sealed set."""
    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 forbidden:
                    hits.append("%s@%d" % (nm, sub.lineno))
    return hits


# ---------------- exact Fractions section: the Erdos-Turan / Abel
# ---------------- legs (module-own; the m4 prefactor mutant family)
FR_SEQS = (
    [Fr(2), Fr(-2), Fr(1)],
    [Fr(1), Fr(1)],
    [Fr(1), Fr(1), Fr(1), Fr(1)],
    [Fr(3, 7), Fr(-2, 9), Fr(5, 11), Fr(1, 4), Fr(1, 3),
     Fr(-3, 8), Fr(2, 5), Fr(7, 13), Fr(-1, 6)],
    [Fr(2, 3), Fr(-6, 5), Fr(1, 2), Fr(-3, 7), Fr(1),
     Fr(1, 3), Fr(-1, 2), Fr(5, 4)],
    [Fr((-1) ** j * (j + 1), 2 * j + 3) for j in range(12)],
)


def fr_abel_bound(P, drop_terminal=False):
    """the v964-S0 T4 Abel/Erdos-Turan bound D* x V (exact); the
    mutant flag drops the terminal magnitude term of V -- must
    break on P = (1, 1) with bound 0 < 2."""
    m = len(P)
    sig = [1 if p > 0 else (-1 if p < 0 else 0) for p in P]
    a = [abs(p) for p in P]
    dstar = max(abs(sum(sig[:n + 1])) for n in range(m))
    var = sum(abs(a[j + 1] - a[j]) for j in range(m - 1))
    V = var if drop_terminal else (a[m - 1] + var)
    return dstar * V, dstar, V


def fr_et_pi2(halved=False):
    """the exact theta = pi/2 position/mass leg (e^{-i theta} =
    -i; Gaussian-rational arithmetic as (re, im) Fraction pairs)
    on c = (3, -1, 2): (i) the Abel resummation identity u =
    sum_n (c_n - c_{n+1}) E_n (c_m := 0) EXACT; (ii) the
    geometric position bound |E_n|^2 <= 1/sin^2(pi/4) = 2 with
    the n = 1 equality witness; (iii) |u|^2 <= max|E|^2 x V^2.
    halved flags the position-prefactor mutant (claim |E_n|^2
    <= 1) -- must break at the witness (2 > 1)."""
    def cadd(a, b):
        return (a[0] + b[0], a[1] + b[1])

    def cmul(a, b):
        return (a[0] * b[0] - a[1] * b[1],
                a[0] * b[1] + a[1] * b[0])

    def csca(s, a):
        return (s * a[0], s * a[1])

    def cabs2(a):
        return a[0] * a[0] + a[1] * a[1]

    mi = (Fr(0), Fr(-1))                     # e^{-i pi/2} = -i
    c = [Fr(3), Fr(-1), Fr(2)]
    m = len(c)
    w = [(Fr(1), Fr(0))]
    for _ in range(m - 1):
        w.append(cmul(w[-1], mi))
    u = (Fr(0), Fr(0))
    for cj, wj in zip(c, w):
        u = cadd(u, csca(cj, wj))
    E = []
    run = (Fr(0), Fr(0))
    for wj in w:
        run = cadd(run, wj)
        E.append(run)
    c_ext = c + [Fr(0)]
    u_abel = (Fr(0), Fr(0))
    for n in range(m):
        u_abel = cadd(u_abel, csca(c_ext[n] - c_ext[n + 1], E[n]))
    dev_abel = cabs2((u[0] - u_abel[0], u[1] - u_abel[1]))
    pos2 = Fr(1) if halved else Fr(2)        # 1/sin^2(pi/4) = 2
    worst_pos = max(cabs2(e) - pos2 for e in E)
    witness = (cabs2(E[1]) == 2)
    V = sum(abs(c_ext[n] - c_ext[n + 1]) for n in range(m))
    comp_ok = (cabs2(u) <= max(cabs2(e) for e in E) * V * V)
    return dict(dev_abel=dev_abel, worst_pos=worst_pos,
                witness=witness, V=V, u2=cabs2(u),
                comp_ok=comp_ok)


# ---------------- the module-own spectral / route builders.
# ---------------- Source-pure: block vectors (positions, weights,
# ---------------- chain values) only; the withheld terminal drive
# ---------------- key, the branch label and every target-side
# ---------------- identifier are forbidden in scope (AST audit).
def spec_decomp(P, H):
    """the exact spectral representation of the Fejer block form:
    B(P, P) = (1/L) sum_k F_H(theta_k) |Phat(k)|^2 with L the
    smallest power of two >= 2 (m + H) (FROZEN rule) and F_H the
    Fejer kernel from the padded FFT of the H-ones window."""
    P = np.asarray(P, dtype=float)
    m = len(P)
    L = 1
    while L < 2 * (m + H):
        L <<= 1
    ud = np.fft.fft(P, L)
    F = np.abs(np.fft.fft(np.ones(H), L)) ** 2 / H
    E = F * np.abs(ud) ** 2 / L
    k = np.arange(L)
    th = 2.0 * np.pi * np.minimum(k, L - k) / L
    return dict(L=L, ud=ud, F=F, E=E, th=th,
                B=float(np.sum(E)),
                pars=float(np.sum(np.abs(ud) ** 2)) / L,
                mx2=float(np.max(np.abs(ud) ** 2)))


def band_energies(th, E, H):
    """the FROZEN three-band split: LOW |theta| <= 2 pi / H (the
    Fejer main lobe), MID <= pi / 2, EDGE else."""
    lo = th <= 2.0 * np.pi / H + 1e-12
    mid = (~lo) & (th <= np.pi / 2.0 + 1e-12)
    ed = ~(lo | mid)
    return (float(np.sum(E[lo])), float(np.sum(E[mid])),
            float(np.sum(E[ed])))


def et_factors(P, H, sp):
    """the B1 Erdos-Turan / Abel factorization per frequency:
    |Phat(k)| <= Dpos(theta_k) x V with Dpos = min(m,
    1/|sin(theta/2)|) (pure geometric-sum position bound) and
    V = sum |diff| + |terminal| (the Abel mass term); composed
    B <= V^2 x Phi_pos, Phi_pos = (1/L) sum F Dpos^2."""
    P = np.asarray(P, dtype=float)
    m = len(P)
    V = (float(np.sum(np.abs(np.diff(P))))
         + (abs(float(P[-1])) if m else 0.0))
    th = sp["th"]
    with np.errstate(divide="ignore"):
        inv = np.where(th > 1e-15,
                       1.0 / np.abs(np.sin(th / 2.0)), float(m))
    dpos = np.minimum(inv, float(m))
    slack = float(np.max(np.abs(sp["ud"]) - dpos * V)) if m else 0.0
    phi = float(np.sum(sp["F"] * dpos * dpos)) / sp["L"]
    return dict(V=V, slack=slack, phi=phi, bound=V * V * phi)


def pair_split(P, H):
    """the B2 exact pair split B = D + O: D = sum P_j^2 (the
    diagonal = the Parseval mean), O = 2 sum_{1<=h<H}
    (1 - h/H) A(h) (the signed off-diagonal)."""
    A = L2D.autocorr_full(P)
    D = float(A[0]) if len(P) else 0.0
    O = 2.0 * float(sum((1.0 - h / float(H)) * A[h]
                        for h in range(1, min(H, len(A)))))
    return D, O


def overlap_split(bxs, cbs, xu, cw, lo, hi, brk, m, tol=0.0):
    """the B3 exact overlap partition of Delta by EXACT position
    equality between the unions (tol > 0 = the m3 mutant):
    Delta_overlap = all atoms at shared positions (border c,
    window -c), Delta_fresh = the rest; components aggregated
    through the frozen r298 positional kernel."""
    if tol > 0.0:
        mb = np.array([bool(np.any(np.abs(xu - x) <= tol))
                       for x in bxs])
        mw = np.array([bool(np.any(np.abs(bxs - x) <= tol))
                       for x in xu])
    else:
        mb = np.isin(bxs, xu)
        mw = np.isin(xu, bxs)
    P_ov = (WBT.aggregate_blocks(bxs[mb], cbs[mb], lo, hi, brk, m)
            - WBT.aggregate_blocks(xu[mw], cw[mw], lo, hi, brk, m))
    P_fr = (WBT.aggregate_blocks(bxs[~mb], cbs[~mb], lo, hi,
                                 brk, m)
            - WBT.aggregate_blocks(xu[~mw], cw[~mw], lo, hi,
                                   brk, m))
    return P_ov, P_fr, int(np.sum(mb)), int(np.sum(mw))


def cconv_census(bxs, cbs, xu, cw):
    """the c-convergence census on the EXACT shared positions:
    cconv = sum_p |c_beta(p) - c_omega(p)| / sum_p |c_beta(p)|
    (per-position sums; duplicate-safe via bincount)."""
    common = np.intersect1d(bxs, xu)
    if len(common) == 0:
        return 0.0, 0
    mb = np.isin(bxs, common)
    mw = np.isin(xu, common)
    cb_at = np.bincount(np.searchsorted(common, bxs[mb]),
                        weights=cbs[mb], minlength=len(common))
    cw_at = np.bincount(np.searchsorted(common, xu[mw]),
                        weights=cw[mw], minlength=len(common))
    num = float(np.sum(np.abs(cb_at - cw_at)))
    den = max(float(np.sum(np.abs(cb_at))), 1e-300)
    return num / den, len(common)


def mutant_gift_bound(rc, P):
    """m5a MUST-FAIL MUTANT: a 'decay bound' oriented by the
    withheld ground-truth terminal drive key -- the scope audit
    must FLAG this."""
    s = math.copysign(1.0, rc["t_term"])
    return s * WBT.fejer_bil(P, P, 2)


def mutant_branch_peek(rc, P):
    """m5b MUST-FAIL MUTANT (world-blindness break simulated): a
    'diagonal term' that consumes the branch label to pick its
    constant -- the scope audit must FLAG this."""
    c = 0.5 if rc["g_branch"] >= 0.0 else 2.0
    return c * float(np.sum(np.asarray(P) ** 2))


# ---------------------------------------------- toy exact tools
def toy_spectrum_pair_et():
    """the P-level hand toy PDelta = (1, -1, 1), H = 2: B = 1
    (A0 = 3, A1 = -2); spectral recomposition == 1 and Parseval
    == 3 at FFT precision; band sum == B; pair split D = 3,
    O = -2; ET V = 5, composed bound >= B, per-frequency slack
    <= 0.  Returns (worst_exact, worst_fft)."""
    Pd = np.array([1.0, -1.0, 1.0])
    H = 2
    B = WBT.fejer_bil(Pd, Pd, H)
    worst = abs(B - 1.0)
    sp = spec_decomp(Pd, H)
    wf = abs(sp["B"] - 1.0)
    wf = max(wf, abs(sp["pars"] - 3.0))
    e_lo, e_mid, e_ed = band_energies(sp["th"], sp["E"], H)
    wf = max(wf, abs(e_lo + e_mid + e_ed - 1.0))
    D, O = pair_split(Pd, H)
    worst = max(worst, abs(D - 3.0), abs(O + 2.0),
                abs(D + O - B))
    et = et_factors(Pd, H, sp)
    worst = max(worst, abs(et["V"] - 5.0))
    wf = max(wf, max(et["slack"], 0.0),
             max(B - et["bound"], 0.0))
    return worst, wf


def toy_overlap_exact():
    """the r298 kernel toy EXTENDED by a window atom AT a border
    position: border (0..4)/(3,-1,2,-4,1), window (1.0, 2.5)/
    (1,-1), H = 2 -> Pbeta (2,-2,1), Pomega (1,-1,0), PDelta
    (1,-1,1), B = 1; overlap = {1.0}: P_ov = (-2,0,0), P_fr =
    (3,-1,1); B_ov = 4, B_fr = 7, B_x = -10, sum = 1; cconv =
    2 (|c_beta - c_omega| = |-1 - 1| over |c_beta| = 1)."""
    bx = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
    ct = np.array([3.0, -1.0, 2.0, -4.0, 1.0])
    xu = np.array([1.0, 2.5])
    cwv = np.array([1.0, -1.0])
    lo, hi = -10.0, 14.0
    runs = PBB.runs_split(ct)
    brk, m, _jb = WBT.block_breaks(bx, runs)
    Pb = WBT.aggregate_blocks(bx, ct, lo, hi, brk, m)
    Pw = WBT.aggregate_blocks(xu, cwv, lo, hi, brk, m)
    Pd = Pb - Pw
    H = 2
    worst = float(np.max(np.abs(Pd - np.array([1.0, -1.0, 1.0]))))
    B = WBT.fejer_bil(Pd, Pd, H)
    worst = max(worst, abs(B - 1.0))
    P_ov, P_fr, n_b, n_w = overlap_split(bx, ct, xu, cwv, lo, hi,
                                         brk, m)
    worst = max(worst, abs(n_b - 1), abs(n_w - 1),
                float(np.max(np.abs(P_ov - np.array([-2.0, 0.0,
                                                     0.0])))),
                float(np.max(np.abs(P_fr - np.array([3.0, -1.0,
                                                     1.0])))))
    B_ov = WBT.fejer_bil(P_ov, P_ov, H)
    B_fr = WBT.fejer_bil(P_fr, P_fr, H)
    B_x = 2.0 * WBT.fejer_bil(P_ov, P_fr, H)
    worst = max(worst, abs(B_ov - 4.0), abs(B_fr - 7.0),
                abs(B_x + 10.0), abs(B_ov + B_x + B_fr - B))
    cc, n_c = cconv_census(bx, ct, xu, cwv)
    worst = max(worst, abs(cc - 2.0), abs(n_c - 1))
    return worst


def toy_mustfail_m1():
    """m1 WRONG FEJER WEIGHT: the lag recomposition of B with
    (1 - |h|/(H+1)) on PDelta = (1,-1,1), H = 2 gives 1/3
    instead of 1 -- break 2/3 EXACT, LOUD."""
    Pd = [1.0, -1.0, 1.0]
    H = 2
    A = L2D.autocorr_full(Pd)
    wrong = float(A[0]) + 2.0 * float(sum(
        (1.0 - h / float(H + 1)) * A[h]
        for h in range(1, min(H, len(A)))))
    return abs(wrong - WBT.fejer_bil(Pd, Pd, H))


def toy_mustfail_m3():
    """m3 TOLERANT OVERLAP SPLIT: border (1.0, 2.0)/(2,-1) +
    window (1.0005, 3.0)/(1,1), one block, H = 2.  Exact split:
    overlap EMPTY, B_ov = 0, B_fr = 1.  Tolerant split (1e-3):
    B_ov = 1, B_fr = 4 -- BOTH recompose to B = 1 (silent), the
    component shift is the catch.  Returns (component shift,
    worst silent recomposition dev, count shift)."""
    bx = np.array([1.0, 2.0])
    ct = np.array([2.0, -1.0])
    xu = np.array([1.0005, 3.0])
    cwv = np.array([1.0, 1.0])
    lo, hi = -10.0, 14.0
    brk = np.array([])
    m = 1
    H = 2
    Pd = (WBT.aggregate_blocks(bx, ct, lo, hi, brk, m)
          - WBT.aggregate_blocks(xu, cwv, lo, hi, brk, m))
    B = WBT.fejer_bil(Pd, Pd, H)
    outs = []
    for tol in (0.0, TOL_MUT):
        P_ov, P_fr, n_b, _n_w = overlap_split(bx, ct, xu, cwv,
                                              lo, hi, brk, m,
                                              tol=tol)
        B_ov = WBT.fejer_bil(P_ov, P_ov, H)
        B_fr = WBT.fejer_bil(P_fr, P_fr, H)
        B_x = 2.0 * WBT.fejer_bil(P_ov, P_fr, H)
        outs.append((B_ov, B_fr, abs(B_ov + B_x + B_fr - B), n_b))
    shift = max(abs(outs[0][0] - outs[1][0]),
                abs(outs[0][1] - outs[1][1]))
    silent = max(outs[0][2], outs[1][2])
    return shift, silent, abs(outs[0][3] - outs[1][3])


# --------------------------------------------------------------- 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("fejer_decay_probe -- PRIME.PORT.L2.FEJER_DECAY.01 "
          "(round 299)")
    print("SPEC_SHA %s   R297_SHA %s (imported)   R298_SHA %s "
          "(imported)"
          % (SPEC_SHA[:16], VCP.SPEC_SHA[:16], WBT.SPEC_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 + controls + Fractions section "
                        "+ toys + scope audits + every exact ward "
                        "at w9; ladder, slopes, adjudications, "
                        "Legs C/D aggregates, mp wards 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,
          "THE FEJER DECAY ROUND (the r298 gap object executed): "
          "S_F ~ B(PDelta, PDelta) is the vdC input; this round "
          "decomposes B EXACTLY into its frequency spectrum "
          "(module-own FFT representation of the frozen kernel) "
          "and tests THREE source-pure decay derivation routes "
          "(B1 Erdos-Turan position x mass, B2 pair/diagonal "
          "split, B3 exact overlap split with the c-convergence "
          "census); sealed outcomes DERIVED / SPLIT (frozen rest "
          "targets) / STILL_EMPIRICAL; sigma* %.3f, DELTA_NEED "
          "%.2f (r297 records); disclosed structural priors: F_H "
          "is low-pass (main lobe 2 pi / H), the spectral mean "
          "IS the B2 diagonal (Parseval), the r297 border-P "
          "magnitudes REINFORCE; ALL bars, bands, rules and "
          "verdicts sealed BEFORE evaluation"
          % (R297_SIGMA_STAR, DELTA_NEED))

    # ---------------- S1: census + controls (r298 scaffold verbatim)
    section("S1  CENSUS + CONTROLS")
    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)
    if smoke:
        ladder = []
        okL = True
    else:
        kzs = [kz for kz in core.frame_a_zones()
               if PIK.build_rung(kz)["h"] <= H_CAP]
        ladder = [BH.wpack(kz) for kz in kzs]
        ladder.sort(key=lambda p: (p["N"], p["kz"]))
        okL = (len(ladder) == 42
               and all(p["nf"] is None for p in ladder))
    check("G10-census-controls", okC and okCf and okL,
          "MAIN free prefix positive at full depth (%s, N = %s); "
          "control flips re-derived %s; cofinal ladder %d rungs "
          "POSITIVE_PREFIX %s, N in [%s, %s]"
          % (str(sorted(packs)),
             str({t: packs[t]["N"] for t in packs}),
             str({c: ctrl[c]["nf"] for c in ctrl}),
             len(ladder),
             "42/42" if okL and ladder else ("n/a (SMOKE)"
                                             if smoke else "FAIL"),
             ladder[0]["N"] if ladder else "-",
             ladder[-1]["N"] if ladder else "-"))

    pool = ladder if not smoke else [packs["w9"]]
    mains = [packs["w%d" % kz] for kz in windows]

    def rung_rec(p):
        N = p["N"]
        rows = p["rows"]
        r, t, ap, bp = TX.drive_arrays(rows, N)
        g = CA.g_gap(r[:N - 1], t, ap, bp)
        chain = ap[N - 2] * r[N - 2] + bp[N - 2] * r[N - 3]
        Z = t[N - 2] + chain
        xu, wu = CT.union_arrays(p["d"])
        bx, bw = CT.union_arrays(p["dsm"])
        lo = min(float(np.min(xu)), float(np.min(bx)))
        hi = max(float(np.max(xu)), float(np.max(bx)))
        v2 = BR.eval_scaled(rows, bx, N - 2)
        v2w = BR.eval_scaled(rows, xu, N - 2)
        fac = math.exp(rows[N - 2]["Ls"] - rows[N - 1]["Ls"]) \
            / math.sqrt(abs(rows[N - 1]["eta"]))
        ct = bw * bx * v2 * fac
        cw = wu * xu * v2w * fac
        o = np.argsort(bx, kind="stable")
        return dict(kz=p["kz"], N=N, g_branch=g, Z=Z, chain=chain,
                    t_term=float(t[N - 2]), ct=ct, bx=bx, bw=bw,
                    v2=v2, fac=fac, xu=xu, wu=wu, cw=cw, o=o,
                    lo=lo, hi=hi, p=p)

    recs = [rung_rec(p) for p in pool]
    mrecs = [rung_rec(p) for p in mains]
    crecs = {c: rung_rec(ctrl[c]) for c in ctrl}
    cheap = [rc for rc in recs if rc["g_branch"] >= 0.0]
    exc = [rc for rc in recs if rc["g_branch"] < 0.0]
    exc_kz = tuple(sorted(rc["kz"] for rc in exc))
    if smoke:
        check("G11-branch-reproduction", recs[0]["g_branch"] >= 0.0,
              "SMOKE: w9 branch %s (g %+.3f); ladder "
              "decomposition skipped"
              % ("CHEAP" if recs[0]["g_branch"] >= 0 else
                 "EXCEPTION", recs[0]["g_branch"]))
    else:
        check("G11-branch-reproduction",
              len(cheap) == CHEAP_EXPECT
              and exc_kz == tuple(sorted(EXC_KZ_EXPECT))
              and all(rc["g_branch"] >= 0 for rc in mrecs),
              "r263 branch rule reproduced EXACTLY: cheap %d/42, "
              "exception set %s == the named 7; mains %s"
              % (len(cheap), str(exc_kz),
                 "; ".join("w%d g %+.3f CHEAP" % (rc["kz"],
                                                  rc["g_branch"])
                           for rc in mrecs)))

    # ---------------- S2: decomposition + identities + anchors
    section("S2  EXACT DECOMPOSITION + R297/R298 ANCHORS")
    tb_worst = 0.0
    tb_deep = 0.0
    tb_ctrl = 0.0
    for rc in recs + mrecs:
        absum = float(np.sum(np.abs(rc["ct"])))
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(absum, 1e-300)
        if rc["N"] > DEEP_N:
            tb_deep = max(tb_deep, dev)
        else:
            tb_worst = max(tb_worst, dev)
    for c in crecs:
        rc = crecs[c]
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(float(np.sum(np.abs(rc["ct"]))), 1e-300)
        tb_ctrl = max(tb_ctrl, dev)
    check("G20-contribution-ward", tb_worst <= TB_WARD_BAR
          and tb_deep <= TB_WARD_BAR_DEEP
          and tb_ctrl <= TB_WARD_BAR_CTRL,
          "sum_b ct_b == t_{N-2} on %d rungs + %d mains + 3 "
          "controls: worst dev/absmass %.1e main N<=%d (bar %.0e) "
          "/ %.1e deep (bar %.0e) / %.1e controls (bar %.0e)"
          % (len(recs), len(mrecs), tb_worst, DEEP_N,
             TB_WARD_BAR, tb_deep, TB_WARD_BAR_DEEP, tb_ctrl,
             TB_WARD_BAR_CTRL))

    def eval_rung(rc):
        o = rc["o"]
        bxs = rc["bx"][o]
        cts = rc["ct"][o]
        ed = PBB.mask_edge(bxs, rc["lo"], rc["hi"], EDGE_F)
        cb = cts[~ed]
        xb = bxs[~ed]
        runs = PBB.runs_split(cb)
        Mr = [float(np.sum(np.abs(cb[a:b]))) for a, b, _s in runs]
        Sr = [float(np.sum(cb[a:b])) for a, b, _s in runs]
        sg = [s for _a, _b, s in runs]
        alt_ok = all(sg[i + 1] == -sg[i]
                     for i in range(len(sg) - 1))
        R = sum(Sr)
        P = L2D.blocks_level2(Sr)
        e_c2 = PBB.bound_pairsum(Mr)
        f2 = L2D.bound_vdc(P)
        H = f2["H"]
        S_F = f2["s2"] / H
        # ---- the frozen positional kernel (r298 verbatim)
        brk, m, jb = WBT.block_breaks(xb, runs)
        Pb = np.bincount(jb, weights=cb, minlength=m) \
            if m else np.zeros(0)
        agg_dev = float(np.max(np.abs(Pb - np.array(P)))) \
            / max(max(abs(v) for v in P), 1e-300) if m else 0.0
        sf_ker = WBT.fejer_bil(Pb, Pb, H)
        ker_dev = abs(sf_ker - S_F) / max(S_F, 1e-300)
        Pw = WBT.aggregate_blocks(rc["xu"], rc["cw"], rc["lo"],
                                  rc["hi"], brk, m)
        main = WBT.fejer_bil(Pw, Pw, H)
        Pd = Pb - Pw
        T = WBT.fejer_bil(Pd, Pb + Pw, H)
        scale = max(S_F, main, abs(T), 1e-300)
        dec_dev = abs(S_F - main - T) / scale
        phi = WBT.fejer_apply(Pb + Pw, H)
        tj = Pd * phi
        attr_dev = abs(float(np.sum(tj)) - T) / scale
        t_cross = 2.0 * WBT.fejer_bil(Pd, Pw, H)
        lin_dev = abs(float(np.sum(rc["cw"]))) \
            / max(float(np.sum(np.abs(rc["cw"]))), 1e-300)
        # ---- the central quantity: B = B(PDelta, PDelta)
        B_en = WBT.fejer_bil(Pd, Pd, H)
        comp_dev = abs(B_en + t_cross - T) / scale
        # ---- Leg A: exact spectral decomposition + bands
        sp = spec_decomp(Pd, H)
        b_sc = max(B_en, sp["B"], 1e-300)
        spec_dev = abs(sp["B"] - B_en) / b_sc
        D_diag, O_off = pair_split(Pd, H)
        pars_dev = abs(sp["pars"] - D_diag) / max(D_diag, 1e-300)
        e_lo, e_mid, e_ed = band_energies(sp["th"], sp["E"], H)
        band_dev = abs(e_lo + e_mid + e_ed - sp["B"]) / b_sc
        # half/90-pct energy frequencies in main-lobe units
        order = np.argsort(sp["th"], kind="stable")
        cum = np.cumsum(sp["E"][order])
        tot = max(float(cum[-1]), 1e-300)
        th_s = sp["th"][order]
        q50 = float(th_s[int(np.searchsorted(cum, 0.5 * tot))]) \
            * H / (2.0 * np.pi)
        q90 = float(th_s[int(np.searchsorted(cum, 0.9 * tot))]) \
            * H / (2.0 * np.pi)
        # ---- Leg B1: ET factors
        et = et_factors(Pd, H, sp)
        et_slack = et["slack"] / max(float(np.sum(np.abs(Pd))),
                                     1e-300)
        b1_slack = max(B_en - et["bound"], 0.0) / b_sc
        # D_rank on Delta itself: bulk atom positions (both
        # unions, edge-masked) against uniform on the bulk hull
        wed = PBB.mask_edge(rc["xu"], rc["lo"], rc["hi"], EDGE_F)
        xall = np.sort(np.concatenate([xb, rc["xu"][~wed]]))
        a_h = rc["lo"] + EDGE_F * (rc["hi"] - rc["lo"])
        b_h = rc["hi"] - EDGE_F * (rc["hi"] - rc["lo"])
        nn = len(xall)
        d_delta = float(np.max(np.abs(
            (np.arange(1, nn + 1) / nn)
            - (xall - a_h) / max(b_h - a_h, 1e-300)))) \
            if nn else 0.0
        # ---- Leg B2 ward
        pair_dev = abs(D_diag + O_off - B_en) \
            / max(abs(B_en), D_diag, abs(O_off), 1e-300)
        # ---- Leg B3: exact overlap split
        P_ov, P_fr, n_ovb, n_ovw = overlap_split(
            bxs, cts, rc["xu"], rc["cw"], rc["lo"], rc["hi"],
            brk, m)
        part_dev = float(np.max(np.abs(P_ov + P_fr - Pd))) \
            / max(float(np.max(np.abs(Pd))), 1e-300) if m else 0.0
        B_ov = WBT.fejer_bil(P_ov, P_ov, H)
        B_fr = WBT.fejer_bil(P_fr, P_fr, H)
        B_x = 2.0 * WBT.fejer_bil(P_ov, P_fr, H)
        en_sc = max(B_ov, B_fr, abs(B_x), abs(B_en), 1e-300)
        en_dev = abs(B_ov + B_x + B_fr - B_en) / en_sc
        cconv, n_common = cconv_census(bxs, cts, rc["xu"],
                                       rc["cw"])
        # ---- Leg D: magnitude spectrum + block carriers
        Pa = np.abs(Pd)
        B_abs = WBT.fejer_bil(Pa, Pa, H)
        spa = spec_decomp(Pa, H)
        ga_lo, ga_mid, ga_ed = band_energies(spa["th"], spa["E"],
                                             H)
        abs_slack = max(B_en - B_abs, 0.0) / max(B_abs, 1e-300)
        cj = np.abs(tj) - tj
        Mb = [Mr[i] + (Mr[i + 1] if i + 1 < len(Mr) else 0.0)
              for i in range(0, len(Mr), 2)]
        sp_cj = BH.spearman(Mb, list(cj)) if m >= 3 else 0.0
        sp_tj = BH.spearman(Mb, list(np.abs(tj))) if m >= 3 else 0.0
        coin = int(int(np.argmax(cj)) == int(np.argmax(Mb))) \
            if m else 0
        # ---- r297 census objects (anchors)
        nb = len(cb)
        nr = len(runs)
        d_rank = 0.0
        if nr > 1 and nb > 0:
            for i, (a, b, _s) in enumerate(runs[:-1]):
                d_rank = max(d_rank, abs(b / nb - (i + 1) / nr))
        mx = max(Mr) if Mr else 0.0
        sm = sum(Mr) if Mr else 0.0
        imb = nr * mx / max(sm, 1e-300)
        return dict(alt_ok=alt_ok, R=R, P=P, e_c2=e_c2, H=H,
                    S_F=S_F, m=m, nr=nr, Pb=Pb, Pw=Pw, Pd=Pd,
                    agg_dev=agg_dev, ker_dev=ker_dev, main=main,
                    T=T, dec_dev=dec_dev, tj=tj,
                    attr_dev=attr_dev, t_cross=t_cross,
                    comp_dev=comp_dev, lin_dev=lin_dev,
                    B=B_en, sp=sp, spec_dev=spec_dev,
                    pars_dev=pars_dev, e_lo=e_lo, e_mid=e_mid,
                    e_ed=e_ed, band_dev=band_dev, q50=q50,
                    q90=q90, mx2=sp["mx2"], et=et,
                    et_slack=et_slack, b1_slack=b1_slack,
                    d_delta=d_delta, D=D_diag, O=O_off,
                    pair_dev=pair_dev, P_ov=P_ov, P_fr=P_fr,
                    part_dev=part_dev, B_ov=B_ov, B_fr=B_fr,
                    B_x=B_x, en_dev=en_dev, cconv=cconv,
                    n_common=n_common, B_abs=B_abs,
                    abs_slack=abs_slack, g_lo=ga_lo, g_mid=ga_mid,
                    g_ed=ga_ed, sp_cj=sp_cj, sp_tj=sp_tj,
                    coin=coin, d_rank=d_rank, imb=imb)

    all_rc = recs + mrecs
    for rc in all_rc:
        rc["ev"] = eval_rung(rc)
    for c in crecs:
        crecs[c]["ev"] = eval_rung(crecs[c])
    pool_all = all_rc + [crecs[c] for c in crecs]

    alt_all = all(rc["ev"]["alt_ok"] for rc in all_rc)
    bid_worst = 0.0
    ac_worst = 0.0
    for rc in pool_all:
        ev = rc["ev"]
        bid_worst = max(bid_worst,
                        abs(sum(ev["P"]) - ev["R"])
                        / max(abs(ev["R"]), 1e-300))
        A = L2D.autocorr_full(ev["P"])
        s_all = A[0] + 2.0 * float(np.sum(A[1:]))
        ac_worst = max(ac_worst,
                       abs(s_all - sum(ev["P"]) ** 2)
                       / max(A[0], 1e-300))
    check("G21-block-and-autocorr-identity",
          alt_all and bid_worst <= ID_BAR and ac_worst <= AC_BAR,
          "runs alternate on every world AND sum P == R exact "
          "(worst rel %.1e, bar %.0e) AND (sum P)^2 == A(0) + 2 "
          "sum A(h) exact (worst %.1e x A(0), bar %.0e) over %d "
          "worlds" % (bid_worst, ID_BAR, ac_worst, AC_BAR,
                      len(pool_all)))

    Ns = [rc["N"] for rc in recs]
    if not smoke:
        eps_c2_rel = [rc["ev"]["e_c2"] / M_W for rc in recs]
        sl_c2 = L2D.halves_slope(Ns, eps_c2_rel)
        pref = [(rc["ev"]["m"] + rc["ev"]["H"] - 1) / rc["ev"]["H"]
                for rc in recs]
        sl_pref = L2D.halves_slope(Ns, pref)
        sf_rel = [rc["ev"]["S_F"] / (M_W * M_W) for rc in recs]
        sigma = L2D.halves_slope(Ns, sf_rel)
        sigma_star = 2.0 * (sl_c2 - DELTA_NEED) - sl_pref
        check("G22-r297-target-anchors",
              abs(sigma - R297_SIGMA) <= R297_SIGMA_TOL
              and abs(sigma_star - R297_SIGMA_STAR) <= R297_SSTAR_TOL
              and abs(sl_c2 - R297_SL_C2) <= R297_SL_C2_TOL
              and abs(sl_pref - R297_SL_PREF) <= R297_SL_PREF_TOL,
              "the r297 target-inequality set recomputed bit-near: "
              "sigma %+.3f (ref %+.3f), sigma* %+.3f (ref %+.3f), "
              "sl_c2 %+.3f (ref %+.3f), sl_pref %+.3f (ref %+.3f)"
              % (sigma, R297_SIGMA, sigma_star, R297_SIGMA_STAR,
                 sl_c2, R297_SL_C2, sl_pref, R297_SL_PREF))
        dr_med = float(np.median([rc["ev"]["d_rank"]
                                  for rc in recs]))
        dr_sl = L2D.halves_slope(Ns, [max(rc["ev"]["d_rank"],
                                          1e-300) for rc in recs])
        imb_sl = L2D.halves_slope(Ns, [rc["ev"]["imb"]
                                       for rc in recs])
        check("G23-r297-census-anchors",
              abs(dr_med - R297_DRANK_MED) <= R297_DRANK_TOL
              and abs(dr_sl - R297_DRANK_SL) <= R297_DRANK_SL_TOL
              and abs(imb_sl - R297_IMB_SL) <= R297_IMB_SL_TOL,
              "the r297 asset-2 census recomputed: D_rank med "
              "%.3f (ref %.3f) slope %+.2f (ref %+.2f), "
              "mass-imbalance slope %+.3f (ref %+.3f)"
              % (dr_med, R297_DRANK_MED, dr_sl, R297_DRANK_SL,
                 imb_sl, R297_IMB_SL))
    else:
        sigma = sigma_star = sl_c2 = sl_pref = float("nan")
        check("G22-r297-target-anchors", True,
              "SMOKE: skipped (needs the 42-rung ladder)")
        check("G23-r297-census-anchors", True,
              "SMOKE: skipped (needs the 42-rung ladder)")

    # ---- G24: r298 decomposition anchors
    dec_w = max(rc["ev"]["dec_dev"] for rc in pool_all)
    ker_w = max(max(rc["ev"]["ker_dev"], rc["ev"]["agg_dev"])
                for rc in pool_all)
    att_w = max(max(rc["ev"]["attr_dev"], rc["ev"]["comp_dev"])
                for rc in pool_all)
    lin_m = max((rc["ev"]["lin_dev"] for rc in all_rc
                 if rc["N"] <= DEEP_N), default=0.0)
    lin_d = max((rc["ev"]["lin_dev"] for rc in all_rc
                 if rc["N"] > DEEP_N), default=0.0)
    lin_c = max(crecs[c]["ev"]["lin_dev"] for c in crecs)
    rc9 = mrecs[0] if not smoke else recs[0]
    ov9 = len(np.intersect1d(rc9["bx"], rc9["xu"]))
    if not smoke:
        sh = [abs(rc["ev"]["T"]) / max(rc["ev"]["S_F"], 1e-300)
              for rc in recs]
        sh_med = float(np.median(sh))
        main_rel = [max(rc["ev"]["main"], 1e-300) / (M_W * M_W)
                    for rc in recs]
        sl_main = L2D.halves_slope(Ns, main_rel)
        absT_rel = [max(abs(rc["ev"]["T"]), 1e-300) / (M_W * M_W)
                    for rc in recs]
        sl_T = L2D.halves_slope(Ns, absT_rel)
        n_neg = sum(1 for rc in recs if rc["ev"]["T"] < 0.0)
        canc = [float(np.sum(np.abs(rc["ev"]["tj"])))
                / max(abs(rc["ev"]["T"]), 1e-300) for rc in recs]
        canc_med = float(np.median(canc))
        canc_sl = L2D.halves_slope(Ns, canc)
        tc_med = float(np.median([rc["ev"]["t_cross"]
                                  for rc in recs]))
        ok298 = (abs(sh_med - R298_SH_MED) <= R298_SH_TOL
                 and abs(sl_main - R298_SL_MAIN) <= R298_SL_MAIN_TOL
                 and abs(sl_T - R298_SL_T) <= R298_SL_T_TOL
                 and n_neg == 0
                 and abs(canc_med - R298_CANC_MED) <= R298_CANC_TOL
                 and abs(canc_sl - R298_CANC_SL) <= R298_CANC_SL_TOL
                 and abs(tc_med) <= R298_TC_ABS
                 and ov9 == R298_OVERLAP_W9)
        det298 = ("share med %.2f (ref %.2f), sl_MAIN %+.3f (ref "
                  "%+.3f), sl_|T| %+.3f (ref %+.3f), T<0 %d/42, "
                  "canc med %.2f sl %+.3f (ref %.2f/%+.3f), "
                  "tc med %+.2g, overlap w9 %d (ref %d)"
                  % (sh_med, R298_SH_MED, sl_main, R298_SL_MAIN,
                     sl_T, R298_SL_T, n_neg, canc_med, canc_sl,
                     R298_CANC_MED, R298_CANC_SL, tc_med, ov9,
                     R298_OVERLAP_W9))
    else:
        sh_med = sl_main = sl_T = float("nan")
        canc_med = canc_sl = tc_med = float("nan")
        n_neg = -1
        ok298 = (ov9 == R298_OVERLAP_W9)
        det298 = ("SMOKE: ladder anchors skipped; overlap w9 %d "
                  "(ref %d)" % (ov9, R298_OVERLAP_W9))
    v_o, v_i = VCP.fr_symbolic_sumrule()
    check("G24-r298-decomposition-anchors",
          dec_w <= DEC_BAR and ker_w <= KER_BAR
          and att_w <= ATTR_BAR and lin_m <= LIN_BAR
          and lin_d <= LIN_BAR_DEEP and lin_c <= LIN_BAR_CTRL
          and ok298 and v_o == 0 and v_i == 0,
          "the r298 record recomputed bit-near on %d worlds: "
          "identity dev %.1e (bar %.0e), kernel %.1e (bar %.0e), "
          "attribution %.1e (bar %.0e); linear window zero %.1e "
          "main / %.1e deep / %.1e controls; %s; r297 sum rule "
          "import devs %s/%s"
          % (len(pool_all), dec_w, DEC_BAR, ker_w, KER_BAR,
             att_w, ATTR_BAR, lin_m, lin_d, lin_c, det298,
             str(v_o), str(v_i)))

    # ---------------- S3: exact section + toys + audits + mutants
    section("S3  EXACT SECTION (FRACTIONS) + TOYS + SCOPE AUDITS")
    okA = True
    for P in FR_SEQS:
        b, _, _ = fr_abel_bound(P)
        okA &= (abs(sum(P)) <= b)
    b_toy, d_toy, v_toy = fr_abel_bound([Fr(2), Fr(-2), Fr(1)])
    okA &= (d_toy == 1 and v_toy == 2 and b_toy == 2)
    et2 = fr_et_pi2(halved=False)
    okA &= (et2["dev_abel"] == 0 and et2["worst_pos"] <= 0
            and et2["witness"] and et2["V"] == 9
            and et2["u2"] == 2 and et2["comp_ok"])
    check("G30-et-exact-section", okA,
          "the Erdos-Turan / Abel legs EXACT in Fractions: "
          "|sum P| <= D* x V on all %d frozen sequences (toy "
          "D* = 1, V = 2, bound 2 on (2,-2,1)); theta = pi/2 leg: "
          "Abel resummation identity dev %s, position bound "
          "|E_n|^2 <= 2 (worst slack %s) with the n = 1 EQUALITY "
          "witness, |u|^2 = %s <= max|E|^2 x V^2 = %s -- the "
          "position/mass factorization is exact algebra"
          % (len(FR_SEQS), str(et2["dev_abel"]),
             str(et2["worst_pos"]), str(et2["u2"]),
             str(2 * et2["V"] ** 2)))
    b_bad, _, _ = fr_abel_bound([Fr(1), Fr(1)], drop_terminal=True)
    et2m = fr_et_pi2(halved=True)
    check("G31-mustfail-m4-et-prefactors",
          b_bad == 0 and abs(Fr(2)) > b_bad
          and et2m["worst_pos"] == 1,
          "m4 ERDOS-TURAN PREFACTOR FAMILY (v964-S0 T4 anchor): "
          "(a) dropped-terminal mutant gives bound %s < 2 on "
          "P = (1, 1) -- CAUGHT; (b) halved position prefactor "
          "(claim |E_n|^2 <= 1) breaks at the equality witness "
          "by %s (2 > 1) -- CAUGHT: both factors are load-bearing"
          % (str(b_bad), str(et2m["worst_pos"])))
    toy_w, toy_f = toy_spectrum_pair_et()
    toy_w = max(toy_w, toy_overlap_exact())
    check("G32-toy-exactness", toy_w <= TOY_BAR
          and toy_f <= TOY_FFT_BAR,
          "the hand toys reproduce the WHOLE new pipeline: "
          "PDelta (1,-1,1) H 2 -> B = 1, pair D = 3 / O = -2, "
          "ET V = 5 (exact worst %.1e, bar %.0e); spectral "
          "recomposition == 1, Parseval == 3, band sum == B "
          "(FFT worst %.1e, bar %.0e); overlap toy border "
          "(0..4) + window (1.0, 2.5): P_ov (-2,0,0) / P_fr "
          "(3,-1,1), B_ov 4 + B_x -10 + B_fr 7 == 1, cconv 2 -- "
          "the components are LARGE against their sum"
          % (toy_w, TOY_BAR, toy_f, TOY_FFT_BAR))
    h_sd = scope_audit("spec_decomp", BOUND_FORBIDDEN)
    h_be = scope_audit("band_energies", BOUND_FORBIDDEN)
    h_et = scope_audit("et_factors", BOUND_FORBIDDEN)
    h_ps = scope_audit("pair_split", BOUND_FORBIDDEN)
    h_os = scope_audit("overlap_split", BOUND_FORBIDDEN)
    h_cc = scope_audit("cconv_census", BOUND_FORBIDDEN)
    h_gift = scope_audit("mutant_gift_bound", BOUND_FORBIDDEN)
    h_peek = scope_audit("mutant_branch_peek", BOUND_FORBIDDEN)
    ag_hits = antigate_fragment_audit()
    clean = not (h_sd or h_be or h_et or h_ps or h_os or h_cc)
    check("G33-scope-audits", clean and bool(h_gift)
          and bool(h_peek) and not ag_hits,
          "the new builders (spec_decomp, band_energies, "
          "et_factors, pair_split, overlap_split, cconv_census) "
          "consume block vectors / positions / weights only (no "
          "truth-side identifier in scope%s); m5a gift mutant "
          "FLAGGED (%s); m5b branch-peek mutant FLAGGED (%s); "
          "fragment audit: %s"
          % ("" if clean else " VIOLATION",
             "; ".join(h_gift) if h_gift else "NOT FLAGGED",
             "; ".join(h_peek) if h_peek else "NOT FLAGGED",
             "CLEAN" if not ag_hits else "; ".join(ag_hits)))
    m1_brk = toy_mustfail_m1()
    m3_shift, m3_silent, m3_cnt = toy_mustfail_m3()
    check("G34-mustfails-m1-m3", m1_brk >= MUT_MIN
          and abs(m1_brk - 2.0 / 3.0) <= 1e-12
          and m3_shift >= MUT_MIN and m3_cnt >= 1
          and m3_silent <= TOY_FFT_BAR,
          "m1 WRONG FEJER WEIGHT: the lag recomposition with "
          "(1 - |h|/(H+1)) breaks the toy identity by %.6f "
          "(= 2/3 exact) LOUD; m3 TOLERANT OVERLAP SPLIT (tol "
          "%.0e): component energy shift %.1f and count shift %d "
          "while BOTH splits recompose silently (dev %.1e) -- "
          "the exact-equality convention is load-bearing, the "
          "recomposition alone cannot catch it"
          % (m1_brk, TOL_MUT, m3_shift, int(m3_cnt), m3_silent))

    # ---------------- S4: Leg A -- the frequency anatomy
    section("S4  LEG A: SPECTRUM MAP (FREQUENCY ANATOMY OF DELTA)")
    spec_w = max(rc["ev"]["spec_dev"] for rc in pool_all)
    pars_w = max(rc["ev"]["pars_dev"] for rc in pool_all)
    band_w = max(rc["ev"]["band_dev"] for rc in pool_all)
    abs_w = max(rc["ev"]["abs_slack"] for rc in pool_all)
    check("G40-spectral-wards", spec_w <= SPEC_BAR
          and pars_w <= SPEC_BAR and band_w <= SPEC_BAR
          and abs_w <= SPEC_BAR,
          "the exact spectral representation on %d worlds: "
          "recomposition (1/L) sum F |Dhat|^2 == B worst %.1e; "
          "Parseval mean == sum PDelta^2 worst %.1e; band sum == "
          "B worst %.1e; magnitude majorization B <= B_abs slack "
          "%.1e (all bars %.0e) -- the h-decomposition of the "
          "frozen kernel is an exact finite identity"
          % (len(pool_all), spec_w, pars_w, band_w, abs_w,
             SPEC_BAR))
    if not smoke:
        shl = [rc["ev"]["e_lo"] / max(rc["ev"]["B"], 1e-300)
               for rc in recs]
        shm = [rc["ev"]["e_mid"] / max(rc["ev"]["B"], 1e-300)
               for rc in recs]
        she = [rc["ev"]["e_ed"] / max(rc["ev"]["B"], 1e-300)
               for rc in recs]
        shl_med = float(np.median(shl))
        shm_med = float(np.median(shm))
        she_med = float(np.median(she))
        sl_lo = L2D.halves_slope(Ns, [max(rc["ev"]["e_lo"], 1e-300)
                                      / (M_W * M_W) for rc in recs])
        sl_mid = L2D.halves_slope(
            Ns, [max(rc["ev"]["e_mid"], 1e-300) / (M_W * M_W)
                 for rc in recs])
        sl_ed = L2D.halves_slope(
            Ns, [max(rc["ev"]["e_ed"], 1e-300) / (M_W * M_W)
                 for rc in recs])
        sl_mean = L2D.halves_slope(
            Ns, [max(rc["ev"]["D"], 1e-300) / (M_W * M_W)
                 for rc in recs])
        sl_mx = L2D.halves_slope(
            Ns, [max(rc["ev"]["mx2"], 1e-300) / (M_W * M_W)
                 for rc in recs])
        q50_med = float(np.median([rc["ev"]["q50"]
                                   for rc in recs]))
        q90_med = float(np.median([rc["ev"]["q90"]
                                   for rc in recs]))
        if shl_med >= LOWPASS_BAR:
            band_tag = "LOWPASS"
        elif shl_med < BROAD_BAR:
            band_tag = "BROADBAND"
        else:
            band_tag = "MIXED_BAND"
        check("G41-spectrum-map", True,
              "SPECTRUM_MAP (42 rungs): band shares LOW/MID/EDGE "
              "med %.2f/%.2f/%.2f; band-energy slopes %+.3f/"
              "%+.3f/%+.3f; mean |Dhat|^2 slope %+.3f (== the B2 "
              "diagonal, Parseval), max slope %+.3f; q50 med "
              "%.2f / q90 med %.2f main-lobe units; SEALED TAG: "
              "%s (LOWPASS iff LOW med >= %.2f, BROADBAND iff < "
              "%.2f)"
              % (shl_med, shm_med, she_med, sl_lo, sl_mid, sl_ed,
                 sl_mean, sl_mx, q50_med, q90_med, band_tag,
                 LOWPASS_BAR, BROAD_BAR))
    else:
        shl_med = shm_med = she_med = float("nan")
        sl_lo = sl_mid = sl_ed = sl_mean = sl_mx = float("nan")
        q50_med = q90_med = float("nan")
        band_tag = "SMOKE"
        check("G41-spectrum-map", True, "SMOKE: skipped")

    # ---------------- S5: Leg B -- the derivation routes
    section("S5  LEG B: THE DECAY DERIVATION ROUTES")
    et_w = max(rc["ev"]["et_slack"] for rc in pool_all)
    b1_w = max(rc["ev"]["b1_slack"] for rc in pool_all)
    check("G50-b1-et-wards", et_w <= ET_BAR and b1_w <= ET_BAR,
          "B1 ERDOS-TURAN wards on %d worlds: per-frequency "
          "|Dhat| <= Dpos x V slack %.1e (rel sum|PDelta|); "
          "composed B <= V^2 x Phi_pos slack %.1e (rel B) -- "
          "the position/mass factorization holds exactly, "
          "world-blind by the same algebra (bars %.0e)"
          % (len(pool_all), et_w, b1_w, ET_BAR))
    pair_w = max(rc["ev"]["pair_dev"] for rc in pool_all)
    check("G52-b2-pair-ward", pair_w <= PAIR_BAR,
          "B2 PAIR ward on %d worlds: B == D + O exact (worst "
          "%.1e of scale, bar %.0e) -- diagonal magnitudes vs "
          "signed off-diagonal, nothing through |.|"
          % (len(pool_all), pair_w, PAIR_BAR))
    part_w = max(rc["ev"]["part_dev"] for rc in pool_all)
    en_w = max(rc["ev"]["en_dev"] for rc in pool_all)
    check("G53-b3-overlap-wards", part_w <= PART_BAR
          and en_w <= EN_BAR,
          "B3 OVERLAP wards on %d worlds: P_ov + P_fr == PDelta "
          "exact (worst %.1e rel max|PDelta|, bar %.0e); energy "
          "recomposition B_ov + B_x + B_fr == B (worst %.1e of "
          "the component scale, bar %.0e) -- the exact-equality "
          "partition is an identity"
          % (len(pool_all), part_w, PART_BAR, en_w, EN_BAR))
    show = (sorted(exc, key=lambda r_: r_["kz"]) + mrecs
            if not smoke else mrecs)
    for rc in show:
        ev = rc["ev"]
        info("kz%-3d N%-4d %-4s m %-3d H %-2d  B %.2e  sh_low "
             "%.2f  D %.2e  O %+.2e  s_ov %+.2f  cconv %.2f"
             % (rc["kz"], rc["N"],
                "EXC" if rc["g_branch"] < 0 else "chp",
                ev["m"], ev["H"], ev["B"], ev["e_lo"]
                / max(ev["B"], 1e-300), ev["D"], ev["O"],
                ev["B_ov"] / max(ev["B"], 1e-300), ev["cconv"]))
    if not smoke:
        # ---- B1 census
        sl_phi = L2D.halves_slope(Ns, [max(rc["ev"]["et"]["phi"],
                                           1e-300) for rc in recs])
        v2_rel = [max(rc["ev"]["et"]["V"], 1e-300) ** 2
                  / (M_W * M_W) for rc in recs]
        sl_v2 = L2D.halves_slope(Ns, v2_rel)
        bd_rel = [max(rc["ev"]["et"]["bound"], 1e-300)
                  / (M_W * M_W) for rc in recs]
        sl_bd = L2D.halves_slope(Ns, bd_rel)
        add_dev = abs(sl_bd - sl_phi - sl_v2)
        dd_med = float(np.median([rc["ev"]["d_delta"]
                                  for rc in recs]))
        dd_sl = L2D.halves_slope(Ns, [max(rc["ev"]["d_delta"],
                                          1e-300) for rc in recs])
        need_mass = sigma_star - sl_phi
        mass_met = sl_v2 <= need_mass
        check("G51-b1-census", add_dev <= ADD_BAR,
              "B1 census: sl_pos = slope(Phi_pos) %+.3f, sl_mass "
              "= slope(V^2/M^2) %+.3f, composed %+.3f (additivity "
              "dev %.1e, bar %.0e) vs sigma* %+.3f -- composed "
              "%s; MASS_TARGET_FROZEN: needed slope(V^2/M^2) <= "
              "sigma* - sl_pos = %+.3f, measured %+.3f -- %s; "
              "D_rank(Delta) med %.3f slope %+.2f (the Delta "
              "support%s)"
              % (sl_phi, sl_v2, sl_bd, add_dev, ADD_BAR,
                 sigma_star,
                 "MEETS the target" if sl_bd <= sigma_star
                 else "FAILS by %.3f" % (sl_bd - sigma_star),
                 need_mass, sl_v2,
                 "MET" if mass_met
                 else "NOT MET by %.3f" % (sl_v2 - need_mass),
                 dd_med, dd_sl,
                 " inherits the falling equidistribution"
                 if dd_sl < 0 else ": discrepancy NOT falling"))
        # ---- B2 census
        sl_D = L2D.halves_slope(Ns, [max(rc["ev"]["D"], 1e-300)
                                     / (M_W * M_W) for rc in recs])
        sl_absO = L2D.halves_slope(
            Ns, [max(abs(rc["ev"]["O"]), 1e-300) / (M_W * M_W)
                 for rc in recs])
        n_On = sum(1 for rc in recs if rc["ev"]["O"] < 0.0)
        ratio = [rc["ev"]["B"] / max(rc["ev"]["D"], 1e-300)
                 for rc in recs]
        rat_med = float(np.median(ratio))
        sl_rat = L2D.halves_slope(Ns, [max(v, 1e-300)
                                       for v in ratio])
        od_med = float(np.median([rc["ev"]["O"]
                                  / max(rc["ev"]["D"], 1e-300)
                                  for rc in recs]))
        check("G54-b2-census", True,
              "B2 census: sl_D %+.3f (the diagonal density; "
              "sigma* %+.3f: %s), sl_|O| %+.3f, O < 0 on %d/42 "
              "(crossref r287: the border-P blocks REINFORCE on "
              "39/44 -- PDelta measured here, not assumed), O/D "
              "med %+.2f, ratio B/D med %.2f slope %+.3f (grow "
              "bar %+.2f: %s)"
              % (sl_D, sigma_star,
                 "MEETS" if sl_D <= sigma_star else
                 "FAILS by %.3f" % (sl_D - sigma_star),
                 sl_absO, n_On, od_med, rat_med, sl_rat,
                 RATIO_GROW,
                 "flat enough" if sl_rat <= RATIO_GROW else
                 "GROWS by %.3f over bar" % (sl_rat - RATIO_GROW)))
        # ---- B3 census
        s_ov = [rc["ev"]["B_ov"] / max(rc["ev"]["B"], 1e-300)
                for rc in recs]
        s_fr = [rc["ev"]["B_fr"] / max(rc["ev"]["B"], 1e-300)
                for rc in recs]
        s_x = [rc["ev"]["B_x"] / max(rc["ev"]["B"], 1e-300)
               for rc in recs]
        sov_med = float(np.median(s_ov))
        sfr_med = float(np.median(s_fr))
        sx_med = float(np.median(s_x))
        sxa_med = float(np.median([abs(v) for v in s_x]))
        cc_med = float(np.median([rc["ev"]["cconv"]
                                  for rc in recs]))
        cc_sl = L2D.halves_slope(Ns, [max(rc["ev"]["cconv"],
                                          1e-300) for rc in recs])
        full_ov = sum(1 for rc in recs
                      if rc["ev"]["n_common"] == len(rc["bx"])
                      == len(rc["xu"]))
        if sov_med >= OV_DOM_BAR and sxa_med <= XA_BAR:
            b3_class = "OV_DOM"
        elif sfr_med >= OV_DOM_BAR and sxa_med <= XA_BAR:
            b3_class = "FR_DOM"
        else:
            b3_class = "MIXED_OVERLAP"
        check("G55-b3-census", True,
              "B3 census: energy shares ov/x/fr med %+.2f/%+.2f/"
              "%+.2f (|x| med %.2f); SEALED class %s (OV_DOM iff "
              "ov >= %.2f and |x| <= %.2f); FULL-SUPPORT overlap "
              "(the unions share EVERY position) on %d/42 rungs; "
              "c-convergence census at the shared positions: "
              "cconv med %.2f slope %+.3f -- %s"
              % (sov_med, sx_med, sfr_med, sxa_med, b3_class,
                 OV_DOM_BAR, XA_BAR, full_ov, cc_med, cc_sl,
                 "the c-values converge (falling)" if cc_sl < 0
                 else "the c-values do NOT converge"))
    else:
        sl_phi = sl_v2 = sl_bd = need_mass = float("nan")
        dd_med = dd_sl = float("nan")
        mass_met = False
        sl_D = sl_absO = rat_med = sl_rat = od_med = float("nan")
        n_On = -1
        sov_med = sfr_med = sx_med = sxa_med = float("nan")
        cc_med = cc_sl = float("nan")
        b3_class = "SMOKE"
        check("G51-b1-census", True, "SMOKE: skipped")
        check("G54-b2-census", True, "SMOKE: skipped")
        check("G55-b3-census", True, "SMOKE: skipped")

    # ---------------- S6: sealed decay adjudication + Leg C
    section("S6  SEALED DECAY ADJUDICATION + LEG C")
    if not smoke:
        b1_valid = (et_w <= ET_BAR and b1_w <= ET_BAR)
        b2_valid = (pair_w <= PAIR_BAR)
        b3_valid = (part_w <= PART_BAR and en_w <= EN_BAR)
        b1_ok = b1_valid and (sl_phi + sl_v2) <= sigma_star
        b2_ok = (b2_valid and sl_D <= sigma_star
                 and sl_rat <= RATIO_GROW)
        b3_ok = b3_valid and b3_class == "OV_DOM"
        derived = (b1_valid and sl_phi <= sigma_star
                   and sl_v2 <= MASS_FLAT)
        if derived:
            outcome = "DECAY_DERIVED"
        elif b1_ok or b2_ok or b3_ok:
            outcome = "DECAY_SPLIT"
        else:
            outcome = "DECAY_STILL_EMPIRICAL"
        fired = []
        if b1_ok:
            fired.append("B1(MASS_TARGET: slope(V^2/M^2) <= "
                         "%+.3f, measured %+.3f)"
                         % (need_mass, sl_v2))
        if b2_ok:
            fired.append("B2(DIAG_TARGET: prove sl_D <= sigma* "
                         "(measured %+.3f) + ratio flatness "
                         "(measured %+.3f))" % (sl_D, sl_rat))
        if b3_ok:
            fired.append("B3(CVALUE_TARGET: prove the c-value "
                         "convergence rate, cconv slope %+.3f)"
                         % cc_sl)
        check("G60-decay-adjudication", True,
              "SEALED RULE fired: %s (B1_OK %s: composed %+.3f "
              "vs sigma* %+.3f; B2_OK %s: sl_D %+.3f vs sigma*, "
              "ratio slope %+.3f vs %+.2f; B3_OK %s: class %s; "
              "DERIVED clause: sl_pos %+.3f <= sigma* %s AND "
              "sl_mass %+.3f <= %.1f %s)%s"
              % (outcome, b1_ok, sl_phi + sl_v2, sigma_star,
                 b2_ok, sl_D, sl_rat, RATIO_GROW, b3_ok,
                 b3_class, sl_phi,
                 "TRUE" if sl_phi <= sigma_star else "FALSE",
                 sl_v2, MASS_FLAT,
                 "TRUE" if sl_v2 <= MASS_FLAT else "FALSE",
                 ("; fired: " + " | ".join(fired)) if fired
                 else ""))
        if outcome != "DECAY_STILL_EMPIRICAL":
            hyp = ("" if derived else
                   " + the frozen rest hypothesis(es) [" +
                   " | ".join(fired) + "]")
            info("CANDIDATE THEOREM (Fejer decay composition, L2 "
                 "generic half): for every rung of the sealed "
                 "ladder (N in [%d, %d], H = ceil(sqrt(m))): the "
                 "Leg-B exact bound%s => sigma <= sigma* = %+.3f "
                 "=> the r297 target inequality => the v964-S0 "
                 "vdC theorem => delta' > %.2f on the generic "
                 "half; exceptions: 6 via the r287 F2 "
                 "certificates, kz15 via the r270 exact-finite "
                 "certificate.  Wave-9 promotion candidate -- "
                 "NOT promoted here."
                 % (min(Ns), max(Ns), hyp, sigma_star,
                    DELTA_NEED))
            legc = True
        else:
            info("Leg C VOID without substitute (outcome %s). "
                 "The measured common obstruction is documented "
                 "in the verdict." % outcome)
            legc = False
        check("G61-leg-c", True,
              "Leg C %s -- fires ONLY on DECAY_DERIVED or "
              "DECAY_SPLIT (frozen rest as explicit hypothesis) "
              "by the sealed rule; no post-hoc rescue"
              % ("FIRED (candidate printed, NOT promoted)"
                 if legc else "VOID"))
    else:
        outcome = "SMOKE_NO_ADJUDICATION"
        fired = []
        b1_ok = b2_ok = b3_ok = False
        check("G60-decay-adjudication", True, "SMOKE: skipped")
        check("G61-leg-c", True, "SMOKE: skipped")

    # ---------------- S7: Leg D -- the cancellation locus table
    section("S7  LEG D: IN-T CANCELLATION LOCUS (ONE TABLE)")
    if not smoke:
        gl = []
        gm = []
        ge = []
        for rc in recs:
            ev = rc["ev"]
            G = max(ev["B_abs"] - ev["B"], 1e-300)
            gl.append((ev["g_lo"] - ev["e_lo"]) / G)
            gm.append((ev["g_mid"] - ev["e_mid"]) / G)
            ge.append((ev["g_ed"] - ev["e_ed"]) / G)
        gl_med = float(np.median(gl))
        gm_med = float(np.median(gm))
        ge_med = float(np.median(ge))
        spcj_med = float(np.median([rc["ev"]["sp_cj"]
                                    for rc in recs]))
        sptj_med = float(np.median([rc["ev"]["sp_tj"]
                                    for rc in recs]))
        n_coin = sum(rc["ev"]["coin"] for rc in recs)
        check("G70-canc-locus-table", True,
              "CANC_LOCUS (no interpretation): gap G = B_abs - B "
              "band shares LOW/MID/EDGE med %.2f/%.2f/%.2f vs "
              "energy B shares %.2f/%.2f/%.2f; block side: "
              "sp(Mb, c_j = |t_j| - t_j) med %+.2f, argmax "
              "coincidence %d/42; r298 anchor sp(Mb, |t_j|) med "
              "%+.2f"
              % (gl_med, gm_med, ge_med, shl_med, shm_med,
                 she_med, spcj_med, n_coin, sptj_med))
    else:
        gl_med = gm_med = ge_med = float("nan")
        spcj_med = sptj_med = float("nan")
        n_coin = -1
        check("G70-canc-locus-table", True, "SMOKE: skipped")

    # ---- world-control classes (disclosed, never a failure)
    if not smoke:
        o_main = "O_NEG" if n_On > 21 else "O_POS"
        ctl_note = []
        world_blind = True
        for c in ("EPST", "SCR"):
            ev = crecs[c]["ev"]
            sh_c = ev["e_lo"] / max(ev["B"], 1e-300)
            if sh_c >= LOWPASS_BAR:
                tag_c = "LOWPASS"
            elif sh_c < BROAD_BAR:
                tag_c = "BROADBAND"
            else:
                tag_c = "MIXED_BAND"
            so_c = ev["B_ov"] / max(ev["B"], 1e-300)
            sf_c = ev["B_fr"] / max(ev["B"], 1e-300)
            sx_c = abs(ev["B_x"]) / max(ev["B"], 1e-300)
            if so_c >= OV_DOM_BAR and sx_c <= XA_BAR:
                cl3 = "OV_DOM"
            elif sf_c >= OV_DOM_BAR and sx_c <= XA_BAR:
                cl3 = "FR_DOM"
            else:
                cl3 = "MIXED_OVERLAP"
            osgn = "O_NEG" if ev["O"] < 0 else "O_POS"
            ctl_note.append("%s %s/%s/%s" % (c, tag_c, osgn, cl3))
            world_blind &= (tag_c == band_tag and osgn == o_main
                            and cl3 == b3_class)
        check("G71-world-controls", True,
              "the control classes (same sealed rules at the "
              "single control rung): MAIN %s/%s/%s vs %s -- %s "
              "(a class break is a disclosed finding, not a "
              "gate failure; the identities are world-blind by "
              "the same algebra, G40/G50-G53)"
              % (band_tag, o_main, b3_class,
                 str(ctl_note),
                 "WORLD-BLIND" if world_blind
                 else "WORLD_SENSITIVE (disclosed)"))
    else:
        world_blind = True
        ctl_note = []
        o_main = "n/a"
        check("G71-world-controls", True, "SMOKE: skipped")

    # ---------------- S8: mustfail m2 + anchors + mp wards
    section("S8  MUSTFAIL M2 + ANCHORS + MP WARDS")
    m2_pool = mrecs + ([recs[0]] if smoke else [])
    m2_vals = []
    for rc in m2_pool:
        ev = rc["ev"]
        m2_vals.append((rc["kz"],
                        (ev["B_abs"] - ev["B"])
                        / max(ev["B"], 1e-300)))
    m2_min = min(v for _k, v in m2_vals)
    check("G80-mustfail-m2", m2_min >= MUT_MIN,
          "m2 MAGNITUDE PAIR ROUTE (|PDelta| instead of PDelta): "
          "B(|PDelta|,|PDelta|) differs from B by %s of B (all "
          ">= %.0e) LOUD; toy 5 vs 1 (break 4 exact) -- the "
          "pair phase of the signed block field is load-bearing; "
          "any |.|-spectrum loses the object"
          % ("; ".join("w%d %.1e" % (k, v) for k, v in m2_vals),
             MUT_MIN))
    rowsS = ctrl["SMOOTH"]["rows"]
    NS = ctrl["SMOOTH"]["N"]
    scT = [abs(rowsS[k]["tb"] * math.exp(rowsS[k]["Ls"]
                                         - rowsS[k + 1]["Ls"]))
           for k in range(NS - 1)]
    alias = max(scT[2:]) / max(scT[0], scT[1])
    qS = float(ctrl["SMOOTH"]["rho"][NS - 1]) / B57
    evS = crecs["SMOOTH"]["ev"]
    okSd = (evS["spec_dev"] <= SPEC_BAR
            and evS["pair_dev"] <= PAIR_BAR
            and evS["en_dev"] <= EN_BAR)
    check("G81-smooth-anchor", alias <= SM_ALIAS_BAR
          and abs(qS) <= SM_Q_BAR and okSd,
          "SMOOTH: drive alias %.1e <= %.0e; q_N = %.1e <= %.0e; "
          "every exact ward holds trivially on the self-aliased "
          "source (%s)"
          % (alias, SM_ALIAS_BAR, qS, SM_Q_BAR,
             "OK" if okSd else "BROKEN"))
    if not smoke:
        mp_note = []
        ok_mp = True
        rc15 = next(r_ for r_ in recs if r_["kz"] == KZ_ANCHOR)
        t15 = PBB.mp_drive(rc15["p"], MP_DPS)
        d15 = abs(t15 - rc15["t_term"])
        ok_mp = ok_mp and (d15 <= MP_T_BAR)
        mp_note.append("kz15 (N %d) dev %.1e (bar %.0e)"
                       % (rc15["N"], d15, MP_T_BAR))
        for rc in recs[-2:]:
            t_mp = PBB.mp_drive(rc["p"], MP_DPS)
            dv = abs(t_mp - rc["t_term"])
            ok_mp = ok_mp and (dv <= MP_DEEP_BAR)
            mp_note.append("kz%d (N %d, DEEPEST) dev %.1e (bar "
                           "%.0e)" % (rc["kz"], rc["N"], dv,
                                      MP_DEEP_BAR))
        check("G82-mp-deep-wards", ok_mp,
              "mp (dps %d) terminal drive at the trend-critical "
              "rungs: %s" % (MP_DPS, "; ".join(mp_note)))
    else:
        check("G82-mp-deep-wards", True, "SMOKE: skipped")

    # ---------------- S9: verdict
    section("S9  VERDICT")
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the exact spectral decomposition of the Delta "
          "Fejer energy, the three-route decay derivation census "
          "with exact wards, the sealed three-way adjudication, "
          "the frozen MASS_TARGET rest inequality and the Leg-D "
          "locus table -- NO new certificate promoted, NO bound "
          "modification of the sealed forms")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        parts = ["SPECTRUM_MAP(LOW/MID/EDGE med %.2f/%.2f/%.2f, "
                 "band slopes %+.3f/%+.3f/%+.3f, mean sl %+.3f, "
                 "max sl %+.3f, q50 %.2f / q90 %.2f lobes, %s)"
                 % (shl_med, shm_med, she_med, sl_lo, sl_mid,
                    sl_ed, sl_mean, sl_mx, q50_med, q90_med,
                    band_tag)]
        parts.append("ROUTE_TABLE(B1 valid 47/47 sl_pos %+.3f "
                     "sl_mass %+.3f composed %+.3f vs sigma* "
                     "%+.3f; B2 valid 47/47 sl_D %+.3f sl_|O| "
                     "%+.3f O<0 %d/42 B/D med %.2f sl %+.3f; B3 "
                     "valid 47/47 shares %+.2f/%+.2f/%+.2f cconv "
                     "med %.2f sl %+.3f class %s)"
                     % (sl_phi, sl_v2, sl_bd, sigma_star, sl_D,
                        sl_absO, n_On, rat_med, sl_rat, sov_med,
                        sx_med, sfr_med, cc_med, cc_sl, b3_class))
        parts.append("MASS_TARGET(needed slope(V^2/M^2) <= %+.3f,"
                     " measured %+.3f: %s)"
                     % (need_mass, sl_v2,
                        "MET" if mass_met else "NOT MET by %.3f"
                        % (sl_v2 - need_mass)))
        if outcome == "DECAY_DERIVED":
            parts.append("DECAY_DERIVED(B1: sl_pos %+.3f <= "
                         "sigma* and sl_mass %+.3f <= 0)"
                         % (sl_phi, sl_v2))
            parts.append("CANDIDATE_THEOREM(printed in S6, "
                         "wave-9 candidate NOT promoted)")
        elif outcome == "DECAY_SPLIT":
            parts.append("DECAY_SPLIT(%s)" % " | ".join(fired))
            parts.append("CANDIDATE_THEOREM(conditional, printed "
                         "in S6, wave-9 candidate NOT promoted)")
        else:
            parts.append("DECAY_STILL_EMPIRICAL(measured common "
                         "obstruction: B1 pays the growing "
                         "position/kernel factor sl_pos %+.3f; "
                         "B2 diagonal sl_D %+.3f %s sigma* but "
                         "ratio B/D slope %+.3f %s the %+.2f "
                         "grow bar; B3 class %s)"
                         % (sl_phi, sl_D,
                            "MEETS" if sl_D <= sigma_star
                            else "FAILS",
                            sl_rat,
                            "within" if sl_rat <= RATIO_GROW
                            else "over", RATIO_GROW, b3_class))
        parts.append("CANC_LOCUS(G bands %.2f/%.2f/%.2f vs B "
                     "%.2f/%.2f/%.2f; sp(Mb, c_j) med %+.2f, "
                     "coincidence %d/42; sp(Mb, |t_j|) med %+.2f)"
                     % (gl_med, gm_med, ge_med, shl_med, shm_med,
                        she_med, spcj_med, n_coin, sptj_med))
        if not world_blind:
            parts.append("WORLD_SENSITIVE(MAIN %s/%s/%s vs %s -- "
                         "disclosed finding)"
                         % (band_tag, o_main, b3_class,
                            str(ctl_note)))
        verd = " + ".join(parts)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G96-verdict", npass == len(CHECKS),
          "%s%s -- SATZ (machine-gated): the spectral "
          "representation, the ET factorization, the pair split, "
          "the overlap partition, the Fractions ET section (all "
          "world-blind); MEASURED: every slope, share, class and "
          "locus stat (42 rungs only); OPEN: the decay derivation "
          "beyond the named rest object(s), the cofinal step H5, "
          "kz15 beyond r270; 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_4 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""diag_target_probe -- PRIME.PORT.L2.DIAG_TARGET.01 (round 300):
the DIAGONAL ANATOMY of the Delta Fejer energy -- can the diagonal
decay sl_D <= sigma* = -0.516 (the r299 frozen DIAG_TARGET, the
thin-margin living edge of the L2 chain) be derived SOURCE-PURELY
from the chain / density structure -- and the ratio flatness with
it?  Context (sealed record inputs): r297 (SPEC e42a76eb) froze
the target inequality sigma := slope(S_F/M_W^2) <= sigma* =
-0.516 (measured sigma = -0.714); r298 (SPEC 05e831be) proved
S_F = B(omega,omega) + B(Delta,omega+beta) exactly and found the
window main term EMPTY => S_F ~ B(PDelta, PDelta); r299 (SPEC
f432e944, 32/32) decomposed B exactly into its frequency spectrum
(LOWPASS, main-lobe share 0.93) and fired DECAY_SPLIT with the
frozen rest pair: (1) DIAG_TARGET -- prove sl_D <= sigma* for the
DIAGONAL D = sum_j PDelta_j^2 (measured sl_D = -0.571, margin
0.055, THIN); (2) RATIO FLATNESS -- B/D stays bounded (measured
med 1.29, slope -0.168 FALLING).  D is ONE positive quantity (a
sum of squares, no signs, no cancellation): the first place in
the lane where magnitude methods CAN in principle carry.  r299
structure fund: FULL-SUPPORT overlap 42/42 -- Delta is a pure
c-value difference on ONE shared node set (Delta_fresh == 0);
cconv med 0.86 slope +0.045 (no pointwise c-convergence).  kz15
permanently closed via r270; the 6 exceptions via the r287 F2
certificates.

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

THE OBJECT (r269/r287/r297/r298/r299 machinery imported
verbatim): t_{N-2} = sum_b ct_b (r244 chain rows, r266 eval);
F = 0.20 edge split; maximal same-sign runs of the bx-sorted
bulk; level-2 blocks (r270 convention); FROZEN vdC window H =
max(2, ceil(sqrt(m))); the frozen positional Fejer block kernel
(r298: block_breaks + aggregate_blocks + fejer_bil + fejer_apply)
and the r299 spectral machinery (spec_decomp with the frozen L
rule, band_energies, pair_split, overlap_split, cconv_census),
ALL imported verbatim; PDelta = Pbeta - Pomega; the round's
central quantity is the DIAGONAL D := sum_j PDelta_j^2 (== the
r299 Parseval mean (1/L) sum_k |Dhat(k)|^2, an exact identity)
and the RATIO B/D with B = B(PDelta, PDelta).

LEG 0 -- ANCHOR REGRESSION (r297/r298/r299 record numbers adopted
as-is, disclosed): sigma = -0.714 tol 0.01, sigma* = -0.516 tol
0.01 (sl_c2 +0.196, sl_pref +0.489, tol 0.01); D_rank med 0.024
tol 0.005 slope -0.42 tol 0.05; imbalance slope +0.244 tol 0.01;
the r298 decomposition bit-near (identity/kernel devs <= 1e-12,
attribution <= 1e-9, share med 0.99 tol 0.02, slope(MAIN) -1.386
tol 0.05, slope(|T|) -0.698 tol 0.05, T > 0 on 42/42, canc_T med
1.69 tol 0.05 slope +0.207 tol 0.02, |T_cross med| <= 1e-3, w9
support overlap == 367 EXACT, linear window zero <= 1e-9 main /
3e-6 deep / 1e-6 controls, r297 sum rule import devs 0/0); the
r299 route set recomputed bit-near: sl_D -0.571 tol 0.01, sl_|O|
-0.815 tol 0.01, O < 0 on 13/42 EXACT, ratio B/D med 1.29 tol
0.02 slope -0.168 tol 0.01, LOW band share med 0.93 tol 0.02,
q50 med 0.19 tol 0.02, cconv med 0.86 tol 0.02 slope +0.045 tol
0.01, D_rank(Delta) med 0.016 tol 0.005 slope -0.12 tol 0.05,
FULL-SUPPORT overlap on 42/42 EXACT.

LEG A -- THE DIAGONAL ANATOMY (what carries the -0.571?): per
rung the exact participation coordinates of the ONE positive
vector |PDelta|: L1 = sum_j |PDelta_j|, mx = max_j |PDelta_j|,
n_eff = L1^2 / D (participation number), fill = D / (mx x L1)
in (0, 1].  TWO EXACT slope decompositions (halves log-slopes
are exactly additive over products, gated <= 1e-9):
  (i)   sl_D  =  2 x slope(L1/M) - slope(n_eff)
                 [mass^2 scale  vs  effective-carrier count]
  (ii)  sl_D  =  slope(mx/M) + slope(L1/M) + slope(fill)
                 [max scale  +  L1 mass  +  fill factor]
-- which part carries the -0.571 is PRINTED, not assumed.
Class decomposition of the carrier (no prime oracle: the weight
SIGN class is the source-pure proxy): PDelta = A + Bv with A =
(Pb_ws - Pw_ws) (the ws-difference field) and Bv = (Pb_-vs -
Pw_-vs) (the -vs-difference field), recomposition gated <=
1e-12; energy shares sum A^2 / D, sum Bv^2 / D, cross.  Band
decomposition of D itself: the UNWEIGHTED Parseval split
(1/L) sum |Dhat|^2 over the frozen LOW/MID/EDGE bands (sum == D
gated).  Top-block share mx^2/D (med + slope).  Fine type
DIAG_ANATOMY(n_eff med + slope, both decompositions, class
shares, band shares, top share).

LEG B -- DERIVATION ROUTES FOR DIAG_TARGET (each an exact
per-rung inequality chain on the real builders, source-pure,
AST scope audit, worlds test on EPSTEIN/SCRAMBLE):
(B1) CHAIN-NORM ROUTE (the r297-asset attachment attempt): by
  the r299 full-support fund Delta is a pure c-value difference:
  at every shared position p, dc(p) = c_beta(p) - c_omega(p) =
  dw(p) x f(p) with dw = w_beta - w_omega (the weight
  difference) and f = x v2(x) fac (the chain factor) -- gated
  EXACTLY (the factorization ward); the per-block reconstruction
  P_rec = blocksum(dc) == P_ov gated <= 1e-9 (on the 42 rungs
  P_ov == PDelta identically, Delta_fresh == 0); per-block
  Cauchy-Schwarz against the |dw| measure: PDelta_j^2 =
  (sum_blk dw f)^2 <= (sum_blk |dw|) x (sum_blk |dw| f^2),
  summed: D <= wdmax x QabsD with wdmax = max_j sum_blk |dw|
  and QabsD = sum_bulk |dw| f^2 (the second moment of the |dw|
  measure -- a chain-quadratic, sum-rule-adjacent); slopes
  sl_wdmax, sl_Qd = slope(QabsD/M^2), composed = sl_wdmax +
  sl_Qd vs sigma*; the IDENTITY CENSUS: is the chain
  orthogonal w.r.t. the |dw| measure (VCP.chain_quads on the id
  pool, sealed classification HOLDS <= 1e-6 / NEAR <= 1e-3 /
  BREAKS)?  Only if it HOLDS does the proven Parseval sum rule
  attach to QabsD verbatim.
(B2) DENSITY / COUNT ROUTE: the exact factorization D <= mx x
  L1 (gated); composed = slope(mx/M) + slope(L1/M) vs sigma*;
  the MAX control census: is mx chain-controllable -- maxatom =
  max_bulk |dc| (a SINGLE c-value distance), slope(maxatom/M),
  and the block-internal reinforcement ratio mx/maxatom at the
  argmax block (med + slope).  Here the max is the TARGET
  quantity itself, not a loss factor -- the disclosed hope that
  the r297 max/mean imbalance curse does not apply verbatim.
(B3) EQUIDISTRIBUTION ROUTE: the needed n_eff growth is frozen
  as a standalone target: slope(n_eff) >= 2 x slope(L1/M) -
  sigma* (NEFF_TARGET; DISCLOSED HONESTY: by decomposition (i)
  this clause is algebraically EQUIVALENT to sl_D <= sigma* --
  a reparametrization, not progress by itself; the derivation
  content of B3 is the LINK to provable terrain: does n_eff
  grow along the falling boundary-position discrepancy?
  Census: slope(D_rank(Delta)) (must be falling), sp(N, n_eff),
  sp(D_rank(Delta), n_eff) over the 42 rungs).
SEALED DIAG ADJUDICATION (frozen BEFORE evaluation, exactly one
fires): route validity = every exact ward on 47 worlds;
  B1_OK iff valid and sl_wdmax + sl_Qd <= sigma*;
  B2_OK iff valid and sl_mx + sl_L1 <= sigma*;
  B3_OK iff valid and slope(n_eff) >= 2 sl_L1 - sigma* and
    slope(D_rank(Delta)) < 0;
  DIAG_DERIVED(B1) iff B1_OK and the |dw| identity census
    HOLDS (every factor of the composed bound reduces to a
    chain identity -- the only fully provable-terrain outcome;
    disclosed expectation: ambitious, the |dw| measure is a
    mixed difference measure);
  DIAG_SPLIT(fired routes, rest targets frozen) iff not DERIVED
    and (B1_OK or B2_OK or B3_OK) -- each firing route prints
    its frozen rest target (B1: QABS_TARGET = prove the wdmax /
    QabsD scaling; B2: MAXL1_TARGET = prove the two magnitude
    slopes of the ONE positive vector; B3: NEFF_TARGET = prove
    the n_eff growth from the falling D_rank);
  DIAG_STILL_EMPIRICAL(measured common obstruction) otherwise.

LEG C -- RATIO FLATNESS (the second frozen rest, smaller): the
needed statement is only BOUNDEDNESS of B/D.  The EXACT kernel
envelope F_H(theta) <= min(H, 1/(H sin^2(theta/2))) (pure
algebra: sin^2(H theta/2) <= 1) gives the exact per-rung
majorant B/D <= R_env := sum_k env(theta_k) |Dhat(k)|^2 /
sum_k |Dhat(k)|^2 (gated pointwise + composed on 47 worlds);
measured: med(R_env), slope(R_env), and the LOWPASS-width
census sp(B/D, q50) + slope(q50) over the ladder.  SEALED RATIO
ADJUDICATION: RATIO_BOUNDED_STRUCTURAL iff the envelope wards
hold on 47/47 and slope(R_env) <= +0.05 (the structural
majorant is non-growing on the measured ladder) -- DISCLOSED
HONESTY: R_env still consumes the measured spectrum shape; the
kernel side is structural, the spectral weighting is not;
RATIO_EMPIRICAL otherwise.

LEG D -- THEOREM COMPOSITION: fires ONLY on DIAG_DERIVED +
RATIO_BOUNDED_STRUCTURAL -- the full wave-9 candidate is
printed with every constant (Leg-B chain bound => sl_D <=
sigma* => with ratio boundedness sigma <= sigma* => the r297
target inequality => the v964-S0 vdC theorem => delta' > 0.21
on the generic half; exceptions 6 via r287 F2 + kz15 via r270).
NOT promoted.  OTHERWISE Leg D freezes the REFINED rest pair
(smaller than r299: exact needed-vs-measured inequalities in
the anatomy coordinates instead of the bare sl_D statement).

LEG E -- WARDS / MUST-FAILS (>= 4 mutants + 2 scope mutants):
(m1) PARTICIPATION FORMULA MUTANT: n_eff from the SIGNED sum
  (sum P)^2 / D instead of L1^2 / D breaks the toy exactly
  (P = (1,-1,1): 1/3 vs 3, break 8/3 EXACT) -- CAUGHT; (m2)
  SWAPPED MAX/L1 FACTORIZATION: the claim D <= mx^2 breaks on
  the toy (2,1,1) (6 > 4, break 2 EXACT) AND on the real mains
  LOUDLY (D - mx^2 >= 1e-6 x D) -- the L1 factor is
  load-bearing; (m3) WRONG h-INDEX SUM-RULE ATTACH (exact
  Fractions, module-own): the Parseval sum rule with h_{k+2}
  in place of h_{k+1} breaks on the rational 4-node measure
  (dev != 0) -- CAUGHT; (m4a/m4b) WORLD-BLINDNESS BREAK: a
  builder consuming the withheld terminal drive key AND a
  builder consuming the branch label are both FLAGGED by the
  AST scope audit.  WORLD-BLINDNESS OF THE D-DECAY ITSELF is
  TESTED, not assumed: the sealed anatomy classes (PART_HIGH
  iff n_eff/m >= 0.5; FILL_HIGH iff fill >= 0.5) at the
  EPST/SCR control rungs vs MAIN med -- a class break is a
  disclosed finding (WORLD_SENSITIVE), not a gate failure
  (crossref r299: the O-sign class already separates).  Scope
  hygiene: the new builders (participation, shared_delta,
  cs_block_route, ratio_envelope) consume positions + weights +
  chain values only (BOUND_FORBIDDEN set); fragment audit (no
  fit primitives); TOY EXACTNESS (bar 1e-14): participation on
  (1,-1,1) (D 3, L1 3, mx 1, n_eff 3, fill 1) and (2,1,1)
  (D 6, L1 4, mx 2, n_eff 8/3, fill 3/4); the shared-delta toy
  border (1,2)/(3,-1) [bw (1,-1), f (3,1)] vs window
  (1,2,3.5)/(1.5,1,...) [wu (0.5,1,2)]: dc (1.5,-2) == dw x f
  EXACT at both shared positions; the CS-route toy positions
  (0,1,2), dw (1,-2,1), f (1,2,1), one block: P_rec -2, wd 4,
  q 10, P^2 = 4 <= 40 = wd x q; the envelope toy PDelta =
  (1,-1,1), H = 2: B = 1, D = 3, B/D = 1/3 <= R_env gated at
  FFT precision; mp SAMPLES (dps 60): kz15 (bar 1e-8) + the
  two deepest rungs (bar 3e-6); SMOOTH anchor (alias <= 1e-12,
  q_N <= 1e-20).

INDEX FIREWALL (binding, r238-r299 discipline): w = window (kz),
N_w = builder depth, k/n = chain degree; ground truth (branch
labels, the true R/t/Z values) enters GATES and census tables
only; no zero/prime oracles anywhere (AST firewall); no fit
primitives (fragment audit).  MACHINERY IMPORTED VERBATIM: r298
WBT.block_breaks + WBT.aggregate_blocks + WBT.fejer_bil +
WBT.fejer_apply, r299 FDP.spec_decomp + FDP.band_energies +
FDP.pair_split + FDP.overlap_split + FDP.cconv_census, r269
PBB.mask_edge + PBB.runs_split + PBB.bound_pairsum +
PBB.mp_drive, r287 L2D.blocks_level2 + L2D.bound_vdc +
L2D.halves_slope + L2D.autocorr_full, r297 VCP.chain_quads +
VCP.fr_symbolic_sumrule (the proven set re-computed, not
re-proved), r244 BH.wpack + BH.spearman, r257 CT.union_arrays,
r260 TX.drive_arrays, r263 CA.g_gap, r266 BR.eval_scaled, v881
PIK, r243 PB.smooth_comb.  B PROVENANCE: B_w = S_{N-2} + 5/7
(r241/r243 IMPORTED floor, never fitted).  COFINAL LADDER
(pre-sealed): frame-A h <= 900, 42 rungs, (N, kz)-sorted;
exception set {kz15, 20, 22, 36, 38, 39, 52}.

SEALED CONSTANTS: MAIN windows (9, 13); controls w9 EPSTEIN /
SCRAMBLE(seed 1) / SMOOTH, flips 25/21/27; H_CAP 900; B57 = 5/7;
M_W = sqrt(5/7); CHEAP_EXPECT 35; EXC_KZ_EXPECT (15, 20, 22, 36,
38, 39, 52); EDGE_F 0.20 (FROZEN); PAIR_OFFSET 0 (FROZEN);
DELTA_NEED 0.21; H rule = max(2, ceil(sqrt(m))) (FROZEN); L rule
= smallest power of two >= 2 x (m + H) (FROZEN); BANDS: LOW
|theta| <= 2 pi / H, MID <= pi / 2, EDGE else (FROZEN); ADD_BAR
1e-9 (slope additivity); CLS_BAR 1e-12 (class recomposition,
rel max|PDelta|); DBAND_BAR 1e-9 (Parseval band sum of D, rel);
MAXL1_BAR 1e-9 (D <= mx L1 slack, rel D); DF_BAR 1e-9
(dc == dw x f, rel max|dc|); REC_BAR 1e-9 (P_rec == P_ov, rel
max|PDelta| floored at REC_FLOOR 1e-6 x contribution mass --
amendment a1: on the self-aliased SMOOTH source Delta == 0
identically and the raw scale degenerates to float noise);
CS_BAR 1e-9 (per-block CS + composed, rel D);
ENV_BAR 1e-9 (envelope pointwise x 1/H scale + composed ratio);
RATIO_GROW 0.05; ID_HOLDS 1e-6; ID_NEAR 1e-3; PART_CLS 0.5;
FILL_CLS 0.5; SPEC_BAR 1e-9; PAIR_BAR 1e-12; PART_BAR 1e-12;
EN_BAR 1e-9; KER_BAR/DEC_BAR 1e-12; ATTR_BAR 1e-9; LIN_BARS
1e-9 main N <= 400 / 3e-6 deep / 1e-6 controls; TB_WARD bars
1e-9 / 3e-6 / 1e-6; ID_BAR 1e-12; AC_BAR 1e-9; TOY_BAR 1e-14;
TOY_FFT_BAR 1e-12; MUT_MIN 1e-6; R297 anchors sigma -0.714 /
sigma* -0.516 / sl_c2 +0.196 / sl_pref +0.489 (tol 0.01),
D_rank med 0.024 tol 0.005 slope -0.42 tol 0.05, imb slope
+0.244 tol 0.01; R298 anchors share med 0.99 tol 0.02, sl_MAIN
-1.386 tol 0.05, sl_|T| -0.698 tol 0.05, T > 0 on 42/42, canc
med 1.69 tol 0.05, canc slope +0.207 tol 0.02, |tc med| <=
1e-3, OVERLAP_W9 == 367 EXACT; R299 anchors sl_D -0.571 tol
0.01, sl_|O| -0.815 tol 0.01, O < 0 == 13 EXACT, ratio med 1.29
tol 0.02 slope -0.168 tol 0.01, LOW share 0.93 tol 0.02, q50
0.19 tol 0.02, cconv 0.86 tol 0.02 slope +0.045 tol 0.01,
D_rank(Delta) med 0.016 tol 0.005 slope -0.12 tol 0.05,
FULL_OV == 42 EXACT; MP_DPS 60; MP_T_BAR 1e-8; MP_DEEP_BAR
3e-6; SM_Q_BAR 1e-20; SM_ALIAS_BAR 1e-12; KZ_ANCHOR 15; runtime
<= 1800 s; smoke = w9 + controls + Fractions section + toys +
scope audits + every exact ward at w9 (ladder, slopes,
adjudications, censuses, mp wards skipped).  DISCLOSED PRE-SPEC
INPUT (no scratch run of this probe): every reproduction band
is an r297/r298/r299 RECORD number adopted as-is; the two Leg-A
slope decompositions and the B3 clause equivalence are derived
algebra, disclosed above; the envelope bound is derived kernel
algebra; the adjudication outcomes are sealed symmetrically --
the disclosed structural priors (r297: magnitude majorizations
pay growing imbalance factors; r299: the ratio already falls)
make DIAG_SPLIT(B3) + RATIO_BOUNDED_STRUCTURAL plausible, but
no rule was chosen to favor an outcome.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  DIAG_ANATOMY(n_eff med + slope, sl_D = 2 sl_L1 - sl_neff =
    sl_mx + sl_L1 + sl_fill with both additivity devs, class
    shares A/Bv/cross, D band shares, top-block share)
+ ROUTE_TABLE(B1 valid n/47 sl_wdmax sl_Qd composed vs sigma*
    ident status; B2 valid n/47 sl_mx sl_L1 composed vs sigma*
    maxatom census; B3 needed vs measured n_eff growth,
    D_rank(Delta) slope, sp censuses)
+ [exactly one of] DIAG_DERIVED(B1, ...) / DIAG_SPLIT(fired
    routes + frozen rest targets) / DIAG_STILL_EMPIRICAL(
    measured common obstruction)
+ RATIO_TABLE(B/D med + slope, R_env med + slope, sp(B/D, q50),
    slope(q50))
+ [exactly one of] RATIO_BOUNDED_STRUCTURAL / RATIO_EMPIRICAL
+ [iff DERIVED + BOUNDED] CANDIDATE_THEOREM(all constants)
  [else] REST_FROZEN(the refined needed-vs-measured pair)
+ [if a control class differs] WORLD_SENSITIVE(disclosed).
Honesty before beauty: the participation identities, the
factorization dc = dw x f, the per-block Cauchy-Schwarz, the
max/L1 factorization and the kernel envelope are EXACT finite
identities/inequalities, but every slope, share and class is
MEASURED on 42 rungs only; B3's slope clause is an exact
reparametrization of DIAG_TARGET (disclosed above), its
derivation content is the D_rank link ONLY; R_env consumes the
measured spectrum shape; no verdict claims a cofinal law; the
exception scalar's positivity beyond the measured 42 stays
OPEN; r243-r299 stand.

RECORD TABLES (frozen from the record run; calibration protocol:
smoke pass 1 = 29/31 -- the G50 reconstruction ward divided by a
DEGENERATE scale on the self-aliased SMOOTH control (Delta == 0
identically there, max|PDelta| = float noise 1.3e-18) --
amendment a1 (the reconstruction scale floored at REC_FLOOR 1e-6
x the total contribution mass; a code-side normalization fix, no
bar, band, rule or verdict rule touched; every real-data ward
was already exact: MAIN/EPST/SCR devs <= 6.1e-16); smoke pass 2
= 31/31 (0.2 s); calibration pass 1 = first full evaluation,
31/31 gates, wall 48.1 s, NO further amendment; record run1/run2
after this insertion, identical up to WALL; the only post-freeze
edits are a1 and this record-table insertion, which IS the
protocol):
CAL_VERDICT = DIAG_ANATOMY(n_eff med 37.41 slope +0.963 -- the
effective-carrier count GROWS at ~N; the exact decomposition (i)
sl_D = 2 x sl_L1 - sl_neff = 2 x (+0.196) - (+0.963) = -0.571
(dev 6.7e-16): the ENTIRE diagonal decay is the participation
growth net of a mildly growing L1 mass -- 'many small instead of
few large' is now a measured identity; decomposition (ii) sl_D =
sl_mx + sl_L1 + sl_fill = -0.542 + 0.196 - 0.225 (dev 4.4e-16);
class shares A/Bv/cross med 0.64/0.16/+0.20 (the ws-difference
field carries ~2/3 of D); D band shares LOW/MID/EDGE med
0.27/0.26/0.46 -- D itself is BROADBAND: the r299 LOWPASS
character of B is PURE KERNEL WEIGHTING, not spectrum shape;
top-block share med 0.16 slope -0.513) + ROUTE_TABLE(B1 valid
47/47: sl_wdmax -0.592 + sl_Qd +0.208 = composed -0.384 FAILS
sigma* -0.516 by 0.133; the |dw| identity census BREAKS (cross
med 0.932, worst 4.35) -- the proven sum rule does NOT attach to
the difference measure: the chain-norm shortcut is closed,
honestly; B2 valid 47/47: sl_mx -0.542 + sl_L1 +0.196 = composed
-0.346 FAILS by 0.170; the MAX is atom-controlled (mx/maxatom
med 1.07 slope -0.110, slope(maxatom/M) -0.432 -- a single
c-value distance): the loss sits in L1 x fill, the fill decay
-0.225 is exactly what every max x mass factorization cannot
see; B3: needed slope(n_eff) >= 2 sl_L1 - sigma* = +0.908,
measured +0.963 MET (margin 0.055 -- the same thin margin in the
new coordinate, the disclosed equivalence); D_rank(Delta) slope
-0.117 FALLING; sp(N, n_eff) +0.96, sp(D_rank(Delta), n_eff)
-0.81 -- the carrier count grows WHERE the discrepancy falls:
the D_rank bridge is real but correlational) + DIAG_SPLIT(B3(
NEFF_TARGET: prove slope(n_eff) >= +0.908 from the falling
boundary discrepancy, measured +0.963)) + RATIO_TABLE(B/D med
1.29 slope -0.168; R_env med 1.61 slope -0.122 -- the exact
kernel-envelope majorant itself FALLS; sp(B/D, q50) -0.47,
slope(q50) -0.027 -- the ratio and the lobe width DECOUPLE: the
r299 lobe-width heuristic is refuted as the ratio mechanism) +
RATIO_BOUNDED_STRUCTURAL(envelope wards 47/47: pointwise slack
9.3e-18 x 1/H, composed slack <= 0; slope(R_env) -0.122 <=
+0.05 -- the ratio half of the r299 rest pair is settled at the
structural level on the measured ladder, the spectral-weighting
honesty clause stands) + REST_FROZEN(DIAG: slope(n_eff) >=
+0.908, measured +0.963, margin 0.055, with the D_rank
correlation sp -0.81 as the named bridge to provable terrain;
RATIO: slope(R_env) <= +0.05, measured -0.122 -- MET) +
WORLD_SENSITIVE(MAIN PART_LOW/FILL_LOW vs EPST PART_HIGH/
FILL_HIGH + SCR PART_LOW/FILL_HIGH -- the FILL class separates
MAIN from BOTH broken-arithmetic controls at their own rungs:
after the r299 O-sign class the SECOND world-separating class of
the lane, disclosed).
Key numbers.  S2: contribution ward 2.1e-13 main / 3.9e-13 deep
/ 2.4e-8 controls; block + autocorr identities worst 6.3e-16 /
2.7e-15 on 47 worlds; r297 anchors bit-near (sigma -0.714,
sigma* -0.516, sl_c2 +0.196, sl_pref +0.489; D_rank med 0.024
sl -0.42, imb sl +0.244); r298 anchors bit-near (identity
8.8e-16, kernel 7.5e-16, attribution 5.4e-16; lin zero 2.2e-12
/ 6.4e-12 / 5.0e-7; share med 0.99, sl_MAIN -1.386, sl_|T|
-0.698, T < 0 on 0/42, canc 1.69 sl +0.207, tc med -1.4e-4,
overlap w9 367; sum rule import devs 0/0); r299 anchors bit-near
(spectral wards 7.1e-16 / 3.9e-16 / 3.5e-16, pair 8.2e-16,
partition 0.0, energy 0.0; sl_D -0.571, sl_|O| -0.815, O < 0
13/42, ratio 1.29 / -0.168, LOW 0.93, q50 0.19, cconv 0.86 /
+0.045, dd 0.016 / -0.12, full overlap 42/42).  S3: module-own
sum rule exact (orth dev 0, identity dev 0; r297 import devs
0/0); m3 wrong-h break 9146/2759 != 0 CAUGHT; participation +
shared-delta + CS + envelope toys exact (worst 0.0 / FFT 0.0);
m1 break 8/3 exact CAUGHT; m2 toy break 2 exact + real w9
8.4e-1 / w13 7.2e-1 of D LOUD.  S4: anatomy wards worst class
recomposition 4.6e-16, D band sum 3.0e-16, D <= mx L1 slack
0.0 on 47 worlds.  S5: B1 wards worst dc == dw x f 2.6e-15,
P_rec == P_ov 3.6e-13, per-block CS slack 6.2e-18, composed
slack 0.0; exception rungs in-table: n_eff 16.1 (kz20) .. 77.8
(kz52), fill 0.37 (kz15, kz36) .. 0.53 (kz38), R_env 1.86 (w9)
.. 3.18 (kz39), B/D 0.58 (w13) .. 2.74 (kz39).  S8: SMOOTH
alias 2.4e-14, q_N 4.2e-25, wards trivially exact; mp wards
kz15 2.9e-10, kz64 9.3e-9, kz52 6.6e-8.
READING (typed, no upgrade): the round DELIVERS the anatomy the
lane asked for and RELOCATES the frozen rest onto named terrain:
(1) the diagonal decay is ENTIRELY a participation statement --
sl_D = 2 sl_L1 - sl_neff exactly, with the effective carrier
count growing at +0.963 (~N, sp(N, n_eff) +0.96) against an L1
mass growing at +0.196: the 'distribution of the Delta mass'
question is now ONE measured growth exponent; (2) BOTH magnitude
factorizations fail exactly the way r297 predicted (B1 -0.384,
B2 -0.346 vs sigma* -0.516) -- but the anatomy localizes WHY:
the max is fully atom-controlled (a single c-value distance,
ratio med 1.07), so the irreducible loss is the fill decay
-0.225 (the profile's internal evenness loss), invisible to any
max x mass bound; (3) the |dw| identity census BREAKS -- the
proven window sum rule does not attach to the difference
measure; the chain-norm shortcut is closed; (4) the RATIO half
of the r299 rest pair is SETTLED at the structural level:
RATIO_BOUNDED_STRUCTURAL fired (the exact kernel-envelope
majorant R_env med 1.61 falls at -0.122), and the lobe-width
heuristic is refuted (sp -0.47, wrong sign) -- the ratio is
kernel algebra, not spectrum geometry; (5) the refined freeze is
smaller than r299's: ONE inequality remains -- NEFF_TARGET:
prove slope(n_eff) >= 2 sl_L1 - sigma* (measured margin 0.055),
with the falling D_rank (slope -0.117) and its strong coupling
to n_eff (sp -0.81) as the named bridge to the provable
equidistribution terrain.  Bycatch: D itself is BROADBAND
(0.27/0.26/0.46) -- the low-pass character of sigma is pure
Fejer weighting; and the FILL class separates MAIN (FILL_LOW)
from both dead controls (FILL_HIGH) -- the second
world-separating class of the lane after the r299 O-sign class,
disclosed as WORLD_SENSITIVE.  Runtime 48.1 s full / 0.2 s
smoke; run1/run2 identical up to WALL.  AMENDMENTS AFTER FREEZE:
NONE beyond the disclosed a1 (records inserted per protocol; no
bar, band, rule or verdict rule moved).

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
from fractions import Fraction as Fr

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 cancellation_adjudication_probe as CA   # noqa: E402 r263
import coupledtau_probe as CT                  # noqa: E402 r257
import terminal_crossratio_probe as TX         # noqa: E402 r260
import border_resolvent_identity_probe as BR   # noqa: E402 r266
import phase_bulk_bound_probe as PBB           # noqa: E402 r269
import l2_deterministic_cancellation_probe as L2D  # noqa: E402 r287
import vdc_chain_provenance_probe as VCP       # noqa: E402 r297
import window_border_transfer_probe as WBT     # noqa: E402 r298
import fejer_decay_probe as FDP                # noqa: E402 r299
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)
CTRL_FLIPS = {"EPSTEIN": 25, "SCRAMBLE": 21, "SMOOTH": 27}
H_CAP = 900
B57 = 5.0 / 7.0
M_W = math.sqrt(B57)
CHEAP_EXPECT = 35
EXC_KZ_EXPECT = (15, 20, 22, 36, 38, 39, 52)
TB_WARD_BAR = 1e-9
TB_WARD_BAR_DEEP = 3e-6
TB_WARD_BAR_CTRL = 1e-6
DEEP_N = 400
ID_BAR = 1e-12
AC_BAR = 1e-9
KER_BAR = 1e-12
DEC_BAR = 1e-12
ATTR_BAR = 1e-9
LIN_BAR = 1e-9
LIN_BAR_DEEP = 3e-6
LIN_BAR_CTRL = 1e-6
SPEC_BAR = 1e-9
PAIR_BAR = 1e-12
PART_BAR = 1e-12
EN_BAR = 1e-9
ADD_BAR = 1e-9
CLS_BAR = 1e-12
DBAND_BAR = 1e-9
MAXL1_BAR = 1e-9
DF_BAR = 1e-9
REC_BAR = 1e-9
REC_FLOOR = 1e-6
CS_BAR = 1e-9
ENV_BAR = 1e-9
RATIO_GROW = 0.05
ID_HOLDS = 1e-6
ID_NEAR = 1e-3
PART_CLS = 0.5
FILL_CLS = 0.5
TOY_BAR = 1e-14
TOY_FFT_BAR = 1e-12
MUT_MIN = 1e-6
EDGE_F = 0.20
PAIR_OFFSET = 0
DELTA_NEED = 0.21
R297_SIGMA = -0.714
R297_SIGMA_TOL = 0.01
R297_SIGMA_STAR = -0.516
R297_SSTAR_TOL = 0.01
R297_SL_C2 = 0.196
R297_SL_C2_TOL = 0.01
R297_SL_PREF = 0.489
R297_SL_PREF_TOL = 0.01
R297_DRANK_MED = 0.024
R297_DRANK_TOL = 0.005
R297_DRANK_SL = -0.42
R297_DRANK_SL_TOL = 0.05
R297_IMB_SL = 0.244
R297_IMB_SL_TOL = 0.01
R298_SH_MED = 0.99
R298_SH_TOL = 0.02
R298_SL_MAIN = -1.386
R298_SL_MAIN_TOL = 0.05
R298_SL_T = -0.698
R298_SL_T_TOL = 0.05
R298_CANC_MED = 1.69
R298_CANC_TOL = 0.05
R298_CANC_SL = 0.207
R298_CANC_SL_TOL = 0.02
R298_TC_ABS = 1e-3
R298_OVERLAP_W9 = 367
R299_SL_D = -0.571
R299_SL_D_TOL = 0.01
R299_SL_ABSO = -0.815
R299_SL_ABSO_TOL = 0.01
R299_N_ONEG = 13
R299_RAT_MED = 1.29
R299_RAT_TOL = 0.02
R299_RAT_SL = -0.168
R299_RAT_SL_TOL = 0.01
R299_SH_LOW = 0.93
R299_SH_LOW_TOL = 0.02
R299_Q50 = 0.19
R299_Q50_TOL = 0.02
R299_CCONV = 0.86
R299_CCONV_TOL = 0.02
R299_CCONV_SL = 0.045
R299_CCONV_SL_TOL = 0.01
R299_DD_MED = 0.016
R299_DD_TOL = 0.005
R299_DD_SL = -0.12
R299_DD_SL_TOL = 0.05
R299_FULL_OV = 42
MP_DPS = 60
MP_T_BAR = 1e-8
MP_DEEP_BAR = 3e-6
SM_Q_BAR = 1e-20
SM_ALIAS_BAR = 1e-12
KZ_ANCHOR = 15

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; every readout "
                       "consumes node positions + signed weights + "
                       "the r244 chain rows; ground truth (branch "
                       "labels, true R/t/Z) enters gates and census "
                       "tables only"
                       if not bad else "; ".join(bad))


def antigate_fragment_audit():
    """AST scan for forbidden method families (identifiers only;
    the fragment table itself is assembled from split strings)."""
    frags = ("cand_" + "unroll", "poly" + "fit", "curve_" + "fit",
             "lst" + "sq", "mini" + "mize", "Line" + "arRegression")
    src = open(os.path.abspath(__file__), "r", encoding="utf-8").read()
    tree = ast.parse(src)
    hits = []
    for node in ast.walk(tree):
        nm = None
        if isinstance(node, ast.Attribute):
            nm = node.attr
        elif isinstance(node, ast.Name):
            nm = node.id
        elif isinstance(node, ast.FunctionDef):
            nm = node.name
        if nm and any(f in nm for f in frags):
            hits.append("%s@%d" % (nm, node.lineno))
    return hits


BOUND_FORBIDDEN = {"t" + "_term", "Z", "Zl", "margin", "M" + "_W",
                   "loss", "R" + "_bulk", "truth", "rho",
                   "g" + "_branch", "need"}


def scope_audit(funcname, forbidden):
    """walk ONLY the named function's subtree; flag any withheld/
    truth-side identifier or dict key from the sealed set."""
    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 forbidden:
                    hits.append("%s@%d" % (nm, sub.lineno))
    return hits


# ---------------- exact Fractions section: the Parseval sum rule
# ---------------- (module-own re-proof + the m3 wrong-h mutant)
def fr_parseval_sumrule(wrong_h=False):
    """the Parseval-type sum rule on the rational 4-node measure
    x = (0, 1, 2, 3), w = (1, 2, 1, 3) (r297-G31 / r298-G30
    verbatim): monic three-term chain pi_0..pi_3, orthogonality
    dev + the identity sum w x^2 pi_k^2 == h_{k+1} + a_k^2 h_k +
    b_k^2 h_{k-1} for k = 1, exact.  wrong_h replaces h_{k+1} by
    h_{k+2} on the RHS -- the m3 mutant, must break (dev != 0)."""
    xs = [Fr(0), Fr(1), Fr(2), Fr(3)]
    ws = [Fr(1), Fr(2), Fr(1), Fr(3)]
    n = len(xs)
    pis = [[Fr(1)] * n]
    a_ = []
    b_ = []
    hs = [sum(w * p * p for w, p in zip(ws, pis[0]))]
    for k in range(3):
        ak = sum(w * x * p * p for w, x, p in zip(ws, xs, pis[k])) \
            / hs[k]
        bk = (hs[k] / hs[k - 1]) if k >= 1 else Fr(0)
        nxt = []
        for i in range(n):
            v = (xs[i] - ak) * pis[k][i]
            if k >= 1:
                v -= bk * pis[k - 1][i]
            nxt.append(v)
        pis.append(nxt)
        a_.append(ak)
        b_.append(bk)
        hs.append(sum(w * p * p for w, p in zip(ws, nxt)))
    worst_orth = Fr(0)
    for a in range(4):
        for b in range(a):
            worst_orth = max(worst_orth,
                             abs(sum(w * pis[a][i] * pis[b][i]
                                     for i, w in enumerate(ws))))
    k = 1
    lhs = sum(w * x * x * p * p
              for w, x, p in zip(ws, xs, pis[k]))
    head = hs[k + 2] if wrong_h else hs[k + 1]
    rhs = head + a_[k] ** 2 * hs[k] + b_[k] ** 2 * hs[k - 1]
    return worst_orth, abs(lhs - rhs)


# ---------------- the module-own anatomy / route builders.
# ---------------- Source-pure: block vectors (positions, weights,
# ---------------- chain values) only; the withheld terminal drive
# ---------------- key, the branch label and every target-side
# ---------------- identifier are forbidden in scope (AST audit).
def participation(P):
    """the exact participation coordinates of the ONE positive
    vector |P|: D = sum P^2, L1 = sum |P|, mx = max |P|, n_eff =
    L1^2 / D, fill = D / (mx x L1) in (0, 1]; both product
    identities D = L1^2 / n_eff = mx x L1 x fill are exact by
    construction."""
    P = np.asarray(P, dtype=float)
    D = float(np.sum(P * P))
    L1 = float(np.sum(np.abs(P)))
    mx = float(np.max(np.abs(P))) if len(P) else 0.0
    n_eff = L1 * L1 / max(D, 1e-300)
    fill = D / max(mx * L1, 1e-300)
    return dict(D=D, L1=L1, mx=mx, neff=n_eff, fill=fill)


def shared_delta(bxs, cbs, bws, fxs, xu, cw, wu):
    """the per-position census on the EXACT shared support
    (duplicate-safe via bincount): aggregated c-difference dc =
    c_beta - c_omega, weight difference dw = w_beta - w_omega,
    and the chain position factor f (constant per position; mean
    over duplicates)."""
    common = np.intersect1d(bxs, xu)
    n = len(common)
    if n == 0:
        z = np.zeros(0)
        return dict(x=z, dc=z, dw=z, f=z, n=0)
    mb = np.isin(bxs, common)
    mw = np.isin(xu, common)
    ib = np.searchsorted(common, bxs[mb])
    iw = np.searchsorted(common, xu[mw])
    cb_at = np.bincount(ib, weights=cbs[mb], minlength=n)
    cw_at = np.bincount(iw, weights=cw[mw], minlength=n)
    bw_at = np.bincount(ib, weights=bws[mb], minlength=n)
    wu_at = np.bincount(iw, weights=wu[mw], minlength=n)
    cnt = np.maximum(np.bincount(ib, minlength=n), 1)
    f_at = np.bincount(ib, weights=fxs[mb], minlength=n) / cnt
    return dict(x=common, dc=cb_at - cw_at, dw=bw_at - wu_at,
                f=f_at, n=n)


def cs_block_route(xs, dc, dw, fv, lo, hi, brk, m):
    """the B1 chain-norm route on the shared support: edge mask
    (combined hull, EDGE_F), block index by breakpoint search,
    per-block Cauchy-Schwarz of the c-difference against the
    |dw| measure: P_j^2 = (sum_blk dw f)^2 <= (sum_blk |dw|) x
    (sum_blk |dw| f^2); composed: sum_j P_j^2 <= wdmax x QabsD."""
    xs = np.asarray(xs, dtype=float)
    ed = PBB.mask_edge(xs, lo, hi, EDGE_F)
    x = xs[~ed]
    c = np.asarray(dc, dtype=float)[~ed]
    w = np.asarray(dw, dtype=float)[~ed]
    f = np.asarray(fv, dtype=float)[~ed]
    if m == 0 or len(x) == 0:
        z = np.zeros(max(m, 0))
        return dict(P=z, wdmax=0.0, qabs=0.0, cs_worst=0.0,
                    maxatom=0.0)
    j = np.searchsorted(brk, x)
    P = np.bincount(j, weights=c, minlength=m)
    wd = np.bincount(j, weights=np.abs(w), minlength=m)
    q = np.bincount(j, weights=np.abs(w) * f * f, minlength=m)
    return dict(P=P, wdmax=float(np.max(wd)),
                qabs=float(np.sum(q)),
                cs_worst=float(np.max(P * P - wd * q)),
                maxatom=float(np.max(np.abs(c))))


def ratio_envelope(sp_, H):
    """the exact kernel-envelope majorant of the ratio B/D:
    F_H(theta) <= env(theta) = min(H, 1/(H sin^2(theta/2)))
    pointwise (pure algebra), so B/D <= R_env = sum env |Phat|^2
    / sum |Phat|^2.  Returns (pointwise slack x 1/H, R_env,
    composed ratio slack)."""
    th = sp_["th"]
    F = sp_["F"]
    with np.errstate(divide="ignore"):
        env = np.where(th > 1e-15,
                       1.0 / (H * np.sin(th / 2.0) ** 2), float(H))
    env = np.minimum(env, float(H))
    slack = float(np.max(F - env)) / H
    Ep = np.abs(sp_["ud"]) ** 2 / sp_["L"]
    Dp = max(float(np.sum(Ep)), 1e-300)
    r_env = float(np.sum(env * Ep)) / Dp
    b_over_d = float(np.sum(F * Ep)) / Dp
    return slack, r_env, b_over_d - r_env


def mutant_gift_bound(rc, P):
    """m4a MUST-FAIL MUTANT: a 'diagonal bound' oriented by the
    withheld ground-truth terminal drive key -- the scope audit
    must FLAG this."""
    s = math.copysign(1.0, rc["t_term"])
    return s * float(np.sum(np.asarray(P) ** 2))


def mutant_branch_peek(rc, P):
    """m4b MUST-FAIL MUTANT (world-blindness break simulated): a
    'participation count' that consumes the branch label to pick
    its constant -- the scope audit must FLAG this."""
    c = 0.5 if rc["g_branch"] >= 0.0 else 2.0
    return c * participation(P)["neff"]


# ---------------------------------------------- toy exact tools
def toy_participation():
    """participation on (1,-1,1): D 3, L1 3, mx 1, n_eff 3, fill
    1; on (2,1,1): D 6, L1 4, mx 2, n_eff 8/3, fill 3/4.  Plus
    the product identities.  Returns worst dev."""
    worst = 0.0
    p1 = participation([1.0, -1.0, 1.0])
    worst = max(worst, abs(p1["D"] - 3.0), abs(p1["L1"] - 3.0),
                abs(p1["mx"] - 1.0), abs(p1["neff"] - 3.0),
                abs(p1["fill"] - 1.0))
    p2 = participation([2.0, 1.0, 1.0])
    worst = max(worst, abs(p2["D"] - 6.0), abs(p2["L1"] - 4.0),
                abs(p2["mx"] - 2.0), abs(p2["neff"] - 8.0 / 3.0),
                abs(p2["fill"] - 0.75))
    for p in (p1, p2):
        worst = max(worst,
                    abs(p["D"] - p["L1"] ** 2 / p["neff"]),
                    abs(p["D"] - p["mx"] * p["L1"] * p["fill"]))
    return worst


def toy_mustfail_m1():
    """m1 PARTICIPATION FORMULA MUTANT: the signed sum (sum P)^2
    / D instead of L1^2 / D on P = (1,-1,1) gives 1/3 instead of
    3 -- break 8/3 EXACT."""
    P = np.array([1.0, -1.0, 1.0])
    D = float(np.sum(P * P))
    wrong = float(np.sum(P)) ** 2 / D
    return abs(wrong - participation(P)["neff"])


def toy_mustfail_m2():
    """m2 SWAPPED MAX/L1 FACTORIZATION: the claim D <= mx^2 on
    (2,1,1) breaks by 2 EXACT (6 > 4) while D <= mx x L1 = 8
    holds."""
    p = participation([2.0, 1.0, 1.0])
    good_slack = max(p["D"] - p["mx"] * p["L1"], 0.0)
    return p["D"] - p["mx"] ** 2, good_slack


def toy_shared_and_cs():
    """the shared-delta toy: border (1,2) with bw (1,-1), f
    (3,1) -> cb (3,-1); window (1,2,3.5) with wu (0.5,1,2), f
    (3,1,.) -> cw (1.5,1,.); shared = {1,2}: dc = (1.5,-2) ==
    dw x f = (0.5 x 3, -2 x 1) EXACT.  The CS-route toy:
    positions (0,1,2), dw (1,-2,1), f (1,2,1), one block: P_rec
    = -2, wd 4, q 10, P^2 = 4 <= 40 = wd x q.  Returns worst."""
    worst = 0.0
    bxs = np.array([1.0, 2.0])
    bws = np.array([1.0, -1.0])
    fb = np.array([3.0, 1.0])
    cbs = bws * fb
    xu = np.array([1.0, 2.0, 3.5])
    wu = np.array([0.5, 1.0, 2.0])
    fw = np.array([3.0, 1.0, 5.0])
    cw = wu * fw
    sd = shared_delta(bxs, cbs, bws, fb, xu, cw, wu)
    worst = max(worst, abs(sd["n"] - 2),
                float(np.max(np.abs(sd["dc"]
                                    - np.array([1.5, -2.0])))),
                float(np.max(np.abs(sd["dw"]
                                    - np.array([0.5, -2.0])))),
                float(np.max(np.abs(sd["dc"]
                                    - sd["dw"] * sd["f"]))))
    xs = np.array([0.0, 1.0, 2.0])
    dw = np.array([1.0, -2.0, 1.0])
    fv = np.array([1.0, 2.0, 1.0])
    dc = dw * fv
    cs = cs_block_route(xs, dc, dw, fv, -10.0, 14.0,
                        np.array([]), 1)
    worst = max(worst, float(np.max(np.abs(cs["P"]
                                           - np.array([-2.0])))),
                abs(cs["wdmax"] - 4.0), abs(cs["qabs"] - 10.0),
                abs(cs["cs_worst"] + 36.0),
                max(float(np.sum(cs["P"] ** 2))
                    - cs["wdmax"] * cs["qabs"], 0.0))
    return worst


def toy_envelope():
    """the envelope toy PDelta = (1,-1,1), H = 2: B = 1, D = 3,
    B/D = 1/3 <= R_env; pointwise slack <= 0; FFT precision."""
    Pd = np.array([1.0, -1.0, 1.0])
    H = 2
    sp_ = FDP.spec_decomp(Pd, H)
    slack, r_env, comp = ratio_envelope(sp_, H)
    worst = max(slack, 0.0)
    worst = max(worst, max(comp, 0.0))
    worst = max(worst, max(1.0 / 3.0 - r_env, 0.0))
    return worst


# --------------------------------------------------------------- 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("diag_target_probe -- PRIME.PORT.L2.DIAG_TARGET.01 "
          "(round 300)")
    print("SPEC_SHA %s   R298_SHA %s (imported)   R299_SHA %s "
          "(imported)"
          % (SPEC_SHA[:16], WBT.SPEC_SHA[:16], FDP.SPEC_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 + controls + Fractions section "
                        "+ toys + scope audits + every exact ward "
                        "at w9; ladder, slopes, adjudications, "
                        "censuses, mp wards 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,
          "THE DIAG-TARGET ROUND (the r299 frozen rest executed): "
          "the diagonal D = sum PDelta_j^2 already falls fast "
          "enough (record sl_D %.3f <= sigma* %.3f, margin 0.055 "
          "THIN); this round decomposes sl_D EXACTLY into "
          "participation coordinates (n_eff, L1, mx, fill), tests "
          "THREE source-pure derivation routes (B1 chain-norm CS "
          "on the |dw| measure + identity census, B2 max x L1 "
          "density factorization, B3 equidistribution/NEFF with "
          "the disclosed reparametrization honesty), and settles "
          "the ratio half through the exact kernel envelope; "
          "sealed outcomes DERIVED / SPLIT (frozen rests) / "
          "STILL_EMPIRICAL and BOUNDED_STRUCTURAL / EMPIRICAL; "
          "ALL bars, bands, rules and verdicts sealed BEFORE "
          "evaluation" % (R299_SL_D, R297_SIGMA_STAR))

    # ---------------- S1: census + controls (r299 scaffold verbatim)
    section("S1  CENSUS + CONTROLS")
    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)
    if smoke:
        ladder = []
        okL = True
    else:
        kzs = [kz for kz in core.frame_a_zones()
               if PIK.build_rung(kz)["h"] <= H_CAP]
        ladder = [BH.wpack(kz) for kz in kzs]
        ladder.sort(key=lambda p: (p["N"], p["kz"]))
        okL = (len(ladder) == 42
               and all(p["nf"] is None for p in ladder))
    check("G10-census-controls", okC and okCf and okL,
          "MAIN free prefix positive at full depth (%s, N = %s); "
          "control flips re-derived %s; cofinal ladder %d rungs "
          "POSITIVE_PREFIX %s, N in [%s, %s]"
          % (str(sorted(packs)),
             str({t: packs[t]["N"] for t in packs}),
             str({c: ctrl[c]["nf"] for c in ctrl}),
             len(ladder),
             "42/42" if okL and ladder else ("n/a (SMOKE)"
                                             if smoke else "FAIL"),
             ladder[0]["N"] if ladder else "-",
             ladder[-1]["N"] if ladder else "-"))

    pool = ladder if not smoke else [packs["w9"]]
    mains = [packs["w%d" % kz] for kz in windows]

    def rung_rec(p):
        N = p["N"]
        rows = p["rows"]
        r, t, ap, bp = TX.drive_arrays(rows, N)
        g = CA.g_gap(r[:N - 1], t, ap, bp)
        chain = ap[N - 2] * r[N - 2] + bp[N - 2] * r[N - 3]
        Z = t[N - 2] + chain
        xu, wu = CT.union_arrays(p["d"])
        bx, bw = CT.union_arrays(p["dsm"])
        lo = min(float(np.min(xu)), float(np.min(bx)))
        hi = max(float(np.max(xu)), float(np.max(bx)))
        v2 = BR.eval_scaled(rows, bx, N - 2)
        v2w = BR.eval_scaled(rows, xu, N - 2)
        fac = math.exp(rows[N - 2]["Ls"] - rows[N - 1]["Ls"]) \
            / math.sqrt(abs(rows[N - 1]["eta"]))
        ct = bw * bx * v2 * fac
        cw = wu * xu * v2w * fac
        o = np.argsort(bx, kind="stable")
        return dict(kz=p["kz"], N=N, g_branch=g, Z=Z, chain=chain,
                    t_term=float(t[N - 2]), ct=ct, bx=bx, bw=bw,
                    v2=v2, fac=fac, xu=xu, wu=wu, cw=cw, o=o,
                    lo=lo, hi=hi, p=p)

    recs = [rung_rec(p) for p in pool]
    mrecs = [rung_rec(p) for p in mains]
    crecs = {c: rung_rec(ctrl[c]) for c in ctrl}
    cheap = [rc for rc in recs if rc["g_branch"] >= 0.0]
    exc = [rc for rc in recs if rc["g_branch"] < 0.0]
    exc_kz = tuple(sorted(rc["kz"] for rc in exc))
    if smoke:
        check("G11-branch-reproduction", recs[0]["g_branch"] >= 0.0,
              "SMOKE: w9 branch %s (g %+.3f); ladder "
              "decomposition skipped"
              % ("CHEAP" if recs[0]["g_branch"] >= 0 else
                 "EXCEPTION", recs[0]["g_branch"]))
    else:
        check("G11-branch-reproduction",
              len(cheap) == CHEAP_EXPECT
              and exc_kz == tuple(sorted(EXC_KZ_EXPECT))
              and all(rc["g_branch"] >= 0 for rc in mrecs),
              "r263 branch rule reproduced EXACTLY: cheap %d/42, "
              "exception set %s == the named 7; mains %s"
              % (len(cheap), str(exc_kz),
                 "; ".join("w%d g %+.3f CHEAP" % (rc["kz"],
                                                  rc["g_branch"])
                           for rc in mrecs)))

    # ---------------- S2: decomposition + identities + anchors
    section("S2  EXACT DECOMPOSITION + R297/R298/R299 ANCHORS")
    tb_worst = 0.0
    tb_deep = 0.0
    tb_ctrl = 0.0
    for rc in recs + mrecs:
        absum = float(np.sum(np.abs(rc["ct"])))
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(absum, 1e-300)
        if rc["N"] > DEEP_N:
            tb_deep = max(tb_deep, dev)
        else:
            tb_worst = max(tb_worst, dev)
    for c in crecs:
        rc = crecs[c]
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(float(np.sum(np.abs(rc["ct"]))), 1e-300)
        tb_ctrl = max(tb_ctrl, dev)
    check("G20-contribution-ward", tb_worst <= TB_WARD_BAR
          and tb_deep <= TB_WARD_BAR_DEEP
          and tb_ctrl <= TB_WARD_BAR_CTRL,
          "sum_b ct_b == t_{N-2} on %d rungs + %d mains + 3 "
          "controls: worst dev/absmass %.1e main N<=%d (bar %.0e) "
          "/ %.1e deep (bar %.0e) / %.1e controls (bar %.0e)"
          % (len(recs), len(mrecs), tb_worst, DEEP_N,
             TB_WARD_BAR, tb_deep, TB_WARD_BAR_DEEP, tb_ctrl,
             TB_WARD_BAR_CTRL))

    def eval_rung(rc):
        o = rc["o"]
        bxs = rc["bx"][o]
        cts = rc["ct"][o]
        bws_s = rc["bw"][o]
        ed = PBB.mask_edge(bxs, rc["lo"], rc["hi"], EDGE_F)
        cb = cts[~ed]
        xb = bxs[~ed]
        runs = PBB.runs_split(cb)
        Mr = [float(np.sum(np.abs(cb[a:b]))) for a, b, _s in runs]
        Sr = [float(np.sum(cb[a:b])) for a, b, _s in runs]
        sg = [s for _a, _b, s in runs]
        alt_ok = all(sg[i + 1] == -sg[i]
                     for i in range(len(sg) - 1))
        R = sum(Sr)
        P = L2D.blocks_level2(Sr)
        e_c2 = PBB.bound_pairsum(Mr)
        f2 = L2D.bound_vdc(P)
        H = f2["H"]
        S_F = f2["s2"] / H
        # ---- the frozen positional kernel (r298 verbatim)
        brk, m, jb = WBT.block_breaks(xb, runs)
        Pb = np.bincount(jb, weights=cb, minlength=m) \
            if m else np.zeros(0)
        agg_dev = float(np.max(np.abs(Pb - np.array(P)))) \
            / max(max(abs(v) for v in P), 1e-300) if m else 0.0
        sf_ker = WBT.fejer_bil(Pb, Pb, H)
        ker_dev = abs(sf_ker - S_F) / max(S_F, 1e-300)
        Pw = WBT.aggregate_blocks(rc["xu"], rc["cw"], rc["lo"],
                                  rc["hi"], brk, m)
        main = WBT.fejer_bil(Pw, Pw, H)
        Pd = Pb - Pw
        T = WBT.fejer_bil(Pd, Pb + Pw, H)
        scale = max(S_F, main, abs(T), 1e-300)
        dec_dev = abs(S_F - main - T) / scale
        phi = WBT.fejer_apply(Pb + Pw, H)
        tj = Pd * phi
        attr_dev = abs(float(np.sum(tj)) - T) / scale
        t_cross = 2.0 * WBT.fejer_bil(Pd, Pw, H)
        lin_dev = abs(float(np.sum(rc["cw"]))) \
            / max(float(np.sum(np.abs(rc["cw"]))), 1e-300)
        B_en = WBT.fejer_bil(Pd, Pd, H)
        comp_dev = abs(B_en + t_cross - T) / scale
        # ---- r299 spectral machinery (imported verbatim)
        sp = FDP.spec_decomp(Pd, H)
        b_sc = max(B_en, sp["B"], 1e-300)
        spec_dev = abs(sp["B"] - B_en) / b_sc
        D_diag, O_off = FDP.pair_split(Pd, H)
        pars_dev = abs(sp["pars"] - D_diag) / max(D_diag, 1e-300)
        e_lo, e_mid, e_ed = FDP.band_energies(sp["th"], sp["E"], H)
        band_dev = abs(e_lo + e_mid + e_ed - sp["B"]) / b_sc
        order = np.argsort(sp["th"], kind="stable")
        cum = np.cumsum(sp["E"][order])
        tot = max(float(cum[-1]), 1e-300)
        th_s = sp["th"][order]
        q50 = float(th_s[int(np.searchsorted(cum, 0.5 * tot))]) \
            * H / (2.0 * np.pi)
        pair_dev = abs(D_diag + O_off - B_en) \
            / max(abs(B_en), D_diag, abs(O_off), 1e-300)
        # ---- r299 overlap split + cconv (imported verbatim)
        P_ov, P_fr, _n_b, _n_w = FDP.overlap_split(
            bxs, cts, rc["xu"], rc["cw"], rc["lo"], rc["hi"],
            brk, m)
        part_dev = float(np.max(np.abs(P_ov + P_fr - Pd))) \
            / max(float(np.max(np.abs(Pd))), 1e-300) if m else 0.0
        B_ov = WBT.fejer_bil(P_ov, P_ov, H)
        B_fr = WBT.fejer_bil(P_fr, P_fr, H)
        B_x = 2.0 * WBT.fejer_bil(P_ov, P_fr, H)
        en_sc = max(B_ov, B_fr, abs(B_x), abs(B_en), 1e-300)
        en_dev = abs(B_ov + B_x + B_fr - B_en) / en_sc
        cconv, n_common = FDP.cconv_census(bxs, cts, rc["xu"],
                                           rc["cw"])
        full_ov = int(n_common == len(rc["bx"]) == len(rc["xu"]))
        # ---- D_rank on Delta (r299 verbatim)
        wed = PBB.mask_edge(rc["xu"], rc["lo"], rc["hi"], EDGE_F)
        xall = np.sort(np.concatenate([xb, rc["xu"][~wed]]))
        a_h = rc["lo"] + EDGE_F * (rc["hi"] - rc["lo"])
        b_h = rc["hi"] - EDGE_F * (rc["hi"] - rc["lo"])
        nn = len(xall)
        d_delta = float(np.max(np.abs(
            (np.arange(1, nn + 1) / nn)
            - (xall - a_h) / max(b_h - a_h, 1e-300)))) \
            if nn else 0.0
        # ---- Leg A: participation anatomy of the ONE positive
        # ---- vector |PDelta|
        part = participation(Pd)
        mxl1_slack = max(part["D"] - part["mx"] * part["L1"], 0.0) \
            / max(part["D"], 1e-300)
        # class split A = ws-difference, Bv = -vs-difference
        mb_p = bws_s > 0
        Pb_p = WBT.aggregate_blocks(bxs[mb_p], cts[mb_p],
                                    rc["lo"], rc["hi"], brk, m)
        Pb_n = WBT.aggregate_blocks(bxs[~mb_p], cts[~mb_p],
                                    rc["lo"], rc["hi"], brk, m)
        wpos = rc["wu"] > 0
        Pw_p = WBT.aggregate_blocks(rc["xu"][wpos],
                                    rc["cw"][wpos], rc["lo"],
                                    rc["hi"], brk, m)
        Pw_n = WBT.aggregate_blocks(rc["xu"][~wpos],
                                    rc["cw"][~wpos], rc["lo"],
                                    rc["hi"], brk, m)
        Acl = Pb_p - Pw_p
        Bcl = Pb_n - Pw_n
        cls_dev = float(np.max(np.abs(Acl + Bcl - Pd))) \
            / max(float(np.max(np.abs(Pd))), 1e-300) if m else 0.0
        D_A = float(np.sum(Acl * Acl))
        D_B = float(np.sum(Bcl * Bcl))
        X_AB = 2.0 * float(np.sum(Acl * Bcl))
        # Parseval band split of D (unweighted spectrum)
        Ep = np.abs(sp["ud"]) ** 2 / sp["L"]
        d_lo, d_mid, d_ed = FDP.band_energies(sp["th"], Ep, H)
        dband_dev = abs(d_lo + d_mid + d_ed - part["D"]) \
            / max(part["D"], 1e-300)
        # ---- Leg C: exact kernel envelope of the ratio
        env_slack, r_env, env_comp = ratio_envelope(sp, H)
        # ---- Leg B1: shared-support factorization + CS route
        fxs = rc["bx"] * rc["v2"] * rc["fac"]
        sd = shared_delta(rc["bx"], rc["ct"], rc["bw"], fxs,
                          rc["xu"], rc["cw"], rc["wu"])
        df_dev = float(np.max(np.abs(sd["dc"]
                                     - sd["dw"] * sd["f"]))) \
            / max(float(np.max(np.abs(sd["dc"]))), 1e-300) \
            if sd["n"] else 0.0
        cs = cs_block_route(sd["x"], sd["dc"], sd["dw"], sd["f"],
                            rc["lo"], rc["hi"], brk, m)
        # a1 scale floor: on a self-aliased source (SMOOTH) Delta
        # is identically zero and max|PDelta| degenerates to float
        # noise; the reconstruction scale is floored at REC_FLOOR
        # x the total contribution mass (amendment a1, code-side
        # normalization fix -- no bar or rule moved)
        absm = float(np.sum(np.abs(rc["ct"]))) \
            + float(np.sum(np.abs(rc["cw"])))
        rec_scale = max(float(np.max(np.abs(Pd))) if m else 0.0,
                        REC_FLOOR * absm, 1e-300)
        rec_dev = float(np.max(np.abs(cs["P"] - P_ov))) \
            / rec_scale if m else 0.0
        D_ov = float(np.sum(cs["P"] ** 2))
        cs_worst = cs["cs_worst"] / max(part["D"], 1e-300)
        cs_comp = max(D_ov - cs["wdmax"] * cs["qabs"], 0.0) \
            / max(part["D"], 1e-300)
        return dict(alt_ok=alt_ok, R=R, P=P, e_c2=e_c2, H=H,
                    S_F=S_F, m=m, Pb=Pb, Pw=Pw, Pd=Pd,
                    agg_dev=agg_dev, ker_dev=ker_dev, main=main,
                    T=T, dec_dev=dec_dev, tj=tj,
                    attr_dev=attr_dev, t_cross=t_cross,
                    comp_dev=comp_dev, lin_dev=lin_dev,
                    B=B_en, sp=sp, spec_dev=spec_dev,
                    pars_dev=pars_dev, e_lo=e_lo, e_mid=e_mid,
                    e_ed=e_ed, band_dev=band_dev, q50=q50,
                    D=D_diag, O=O_off, pair_dev=pair_dev,
                    part_dev=part_dev, en_dev=en_dev,
                    cconv=cconv, full_ov=full_ov,
                    d_delta=d_delta, part=part,
                    mxl1_slack=mxl1_slack, cls_dev=cls_dev,
                    D_A=D_A, D_B=D_B, X_AB=X_AB, d_lo=d_lo,
                    d_mid=d_mid, d_ed=d_ed, dband_dev=dband_dev,
                    env_slack=env_slack, r_env=r_env,
                    env_comp=env_comp, df_dev=df_dev,
                    rec_dev=rec_dev, wdmax=cs["wdmax"],
                    qabs=cs["qabs"], cs_worst=cs_worst,
                    cs_comp=cs_comp, maxatom=cs["maxatom"],
                    D_ov=D_ov, Mr=Mr, nr=len(runs), sd=sd)

    all_rc = recs + mrecs
    for rc in all_rc:
        rc["ev"] = eval_rung(rc)
    for c in crecs:
        crecs[c]["ev"] = eval_rung(crecs[c])
    pool_all = all_rc + [crecs[c] for c in crecs]

    alt_all = all(rc["ev"]["alt_ok"] for rc in all_rc)
    bid_worst = 0.0
    ac_worst = 0.0
    for rc in pool_all:
        ev = rc["ev"]
        bid_worst = max(bid_worst,
                        abs(sum(ev["P"]) - ev["R"])
                        / max(abs(ev["R"]), 1e-300))
        A = L2D.autocorr_full(ev["P"])
        s_all = A[0] + 2.0 * float(np.sum(A[1:]))
        ac_worst = max(ac_worst,
                       abs(s_all - sum(ev["P"]) ** 2)
                       / max(A[0], 1e-300))
    check("G21-block-and-autocorr-identity",
          alt_all and bid_worst <= ID_BAR and ac_worst <= AC_BAR,
          "runs alternate on every world AND sum P == R exact "
          "(worst rel %.1e, bar %.0e) AND (sum P)^2 == A(0) + 2 "
          "sum A(h) exact (worst %.1e x A(0), bar %.0e) over %d "
          "worlds" % (bid_worst, ID_BAR, ac_worst, AC_BAR,
                      len(pool_all)))

    # ---- ladder aggregates (one block; every later gate reads st)
    Ns = [rc["N"] for rc in recs]
    st = {}
    if not smoke:
        def med(key):
            return float(np.median([rc["ev"][key] for rc in recs]))

        def med_f(fn):
            return float(np.median([fn(rc["ev"]) for rc in recs]))

        def slp(vals):
            return L2D.halves_slope(Ns, [max(v, 1e-300)
                                         for v in vals])

        eps_c2_rel = [rc["ev"]["e_c2"] / M_W for rc in recs]
        st["sl_c2"] = L2D.halves_slope(Ns, eps_c2_rel)
        pref = [(rc["ev"]["m"] + rc["ev"]["H"] - 1) / rc["ev"]["H"]
                for rc in recs]
        st["sl_pref"] = L2D.halves_slope(Ns, pref)
        st["sigma"] = slp([rc["ev"]["S_F"] / (M_W * M_W)
                           for rc in recs])
        st["sigma_star"] = 2.0 * (st["sl_c2"] - DELTA_NEED) \
            - st["sl_pref"]
        # r297 census: D_rank / imbalance recomputed from runs
        d_ranks = []
        imbs = []
        for rc in recs:
            o = rc["o"]
            bxs = rc["bx"][o]
            cts = rc["ct"][o]
            edm = PBB.mask_edge(bxs, rc["lo"], rc["hi"], EDGE_F)
            cbb = cts[~edm]
            runs = PBB.runs_split(cbb)
            Mr = [float(np.sum(np.abs(cbb[a:b])))
                  for a, b, _s in runs]
            nb = len(cbb)
            nr = len(runs)
            d_rank = 0.0
            if nr > 1 and nb > 0:
                for i, (a, b, _s) in enumerate(runs[:-1]):
                    d_rank = max(d_rank,
                                 abs(b / nb - (i + 1) / nr))
            d_ranks.append(d_rank)
            mx = max(Mr) if Mr else 0.0
            sm = sum(Mr) if Mr else 0.0
            imbs.append(nr * mx / max(sm, 1e-300))
        st["dr_med"] = float(np.median(d_ranks))
        st["dr_sl"] = slp(d_ranks)
        st["imb_sl"] = L2D.halves_slope(Ns, imbs)
        # r298 set
        st["sh_med"] = med_f(lambda ev: abs(ev["T"])
                             / max(ev["S_F"], 1e-300))
        st["sl_main"] = slp([max(rc["ev"]["main"], 1e-300)
                             / (M_W * M_W) for rc in recs])
        st["sl_T"] = slp([max(abs(rc["ev"]["T"]), 1e-300)
                          / (M_W * M_W) for rc in recs])
        st["n_negT"] = sum(1 for rc in recs if rc["ev"]["T"] < 0.0)
        canc = [float(np.sum(np.abs(rc["ev"]["tj"])))
                / max(abs(rc["ev"]["T"]), 1e-300) for rc in recs]
        st["canc_med"] = float(np.median(canc))
        st["canc_sl"] = L2D.halves_slope(Ns, canc)
        st["tc_med"] = med("t_cross")
        # r299 set
        st["sl_D"] = slp([rc["ev"]["D"] / (M_W * M_W)
                          for rc in recs])
        st["sl_absO"] = slp([abs(rc["ev"]["O"]) / (M_W * M_W)
                             for rc in recs])
        st["n_On"] = sum(1 for rc in recs if rc["ev"]["O"] < 0.0)
        ratio = [rc["ev"]["B"] / max(rc["ev"]["D"], 1e-300)
                 for rc in recs]
        st["rat_med"] = float(np.median(ratio))
        st["sl_rat"] = slp(ratio)
        st["shl_med"] = med_f(lambda ev: ev["e_lo"]
                              / max(ev["B"], 1e-300))
        st["q50_med"] = med("q50")
        st["sl_q50"] = slp([rc["ev"]["q50"] for rc in recs])
        st["cc_med"] = med("cconv")
        st["cc_sl"] = slp([rc["ev"]["cconv"] for rc in recs])
        st["dd_med"] = med("d_delta")
        st["dd_sl"] = slp([rc["ev"]["d_delta"] for rc in recs])
        st["full_ov"] = sum(rc["ev"]["full_ov"] for rc in recs)
        # Leg A anatomy
        st["neff_med"] = med_f(lambda ev: ev["part"]["neff"])
        st["sl_neff"] = slp([rc["ev"]["part"]["neff"]
                             for rc in recs])
        st["sl_L1"] = slp([rc["ev"]["part"]["L1"] / M_W
                           for rc in recs])
        st["sl_mx"] = slp([rc["ev"]["part"]["mx"] / M_W
                           for rc in recs])
        st["sl_fill"] = slp([rc["ev"]["part"]["fill"]
                             for rc in recs])
        st["add1"] = abs(st["sl_D"]
                         - (2.0 * st["sl_L1"] - st["sl_neff"]))
        st["add2"] = abs(st["sl_D"] - (st["sl_mx"] + st["sl_L1"]
                                       + st["sl_fill"]))
        st["clsA_med"] = med_f(lambda ev: ev["D_A"]
                               / max(ev["part"]["D"], 1e-300))
        st["clsB_med"] = med_f(lambda ev: ev["D_B"]
                               / max(ev["part"]["D"], 1e-300))
        st["clsX_med"] = med_f(lambda ev: ev["X_AB"]
                               / max(ev["part"]["D"], 1e-300))
        st["dlo_med"] = med_f(lambda ev: ev["d_lo"]
                              / max(ev["part"]["D"], 1e-300))
        st["dmid_med"] = med_f(lambda ev: ev["d_mid"]
                               / max(ev["part"]["D"], 1e-300))
        st["ded_med"] = med_f(lambda ev: ev["d_ed"]
                              / max(ev["part"]["D"], 1e-300))
        st["top_med"] = med_f(lambda ev: ev["part"]["mx"] ** 2
                              / max(ev["part"]["D"], 1e-300))
        st["sl_top"] = slp([rc["ev"]["part"]["mx"] ** 2
                            / max(rc["ev"]["part"]["D"], 1e-300)
                            for rc in recs])
        # Leg B slopes
        st["sl_wdmax"] = slp([rc["ev"]["wdmax"] for rc in recs])
        st["sl_qd"] = slp([rc["ev"]["qabs"] / (M_W * M_W)
                           for rc in recs])
        st["sl_maxatom"] = slp([rc["ev"]["maxatom"] / M_W
                                for rc in recs])
        st["mxma_med"] = med_f(lambda ev: ev["part"]["mx"]
                               / max(ev["maxatom"], 1e-300))
        st["sl_mxma"] = slp([rc["ev"]["part"]["mx"]
                             / max(rc["ev"]["maxatom"], 1e-300)
                             for rc in recs])
        st["sp_n_neff"] = BH.spearman(
            Ns, [rc["ev"]["part"]["neff"] for rc in recs])
        st["sp_dd_neff"] = BH.spearman(
            [rc["ev"]["d_delta"] for rc in recs],
            [rc["ev"]["part"]["neff"] for rc in recs])
        # Leg C ratio
        st["renv_med"] = med("r_env")
        st["sl_renv"] = slp([rc["ev"]["r_env"] for rc in recs])
        st["sp_rat_q50"] = BH.spearman(
            ratio, [rc["ev"]["q50"] for rc in recs])
        check("G22-r297-target-anchors",
              abs(st["sigma"] - R297_SIGMA) <= R297_SIGMA_TOL
              and abs(st["sigma_star"] - R297_SIGMA_STAR)
              <= R297_SSTAR_TOL
              and abs(st["sl_c2"] - R297_SL_C2) <= R297_SL_C2_TOL
              and abs(st["sl_pref"] - R297_SL_PREF)
              <= R297_SL_PREF_TOL,
              "the r297 target-inequality set recomputed bit-near: "
              "sigma %+.3f (ref %+.3f), sigma* %+.3f (ref %+.3f), "
              "sl_c2 %+.3f (ref %+.3f), sl_pref %+.3f (ref %+.3f)"
              % (st["sigma"], R297_SIGMA, st["sigma_star"],
                 R297_SIGMA_STAR, st["sl_c2"], R297_SL_C2,
                 st["sl_pref"], R297_SL_PREF))
        check("G23-r297-census-anchors",
              abs(st["dr_med"] - R297_DRANK_MED) <= R297_DRANK_TOL
              and abs(st["dr_sl"] - R297_DRANK_SL)
              <= R297_DRANK_SL_TOL
              and abs(st["imb_sl"] - R297_IMB_SL) <= R297_IMB_SL_TOL,
              "the r297 asset-2 census recomputed: D_rank med "
              "%.3f (ref %.3f) slope %+.2f (ref %+.2f), "
              "mass-imbalance slope %+.3f (ref %+.3f)"
              % (st["dr_med"], R297_DRANK_MED, st["dr_sl"],
                 R297_DRANK_SL, st["imb_sl"], R297_IMB_SL))
    else:
        check("G22-r297-target-anchors", True,
              "SMOKE: skipped (needs the 42-rung ladder)")
        check("G23-r297-census-anchors", True,
              "SMOKE: skipped (needs the 42-rung ladder)")

    dec_w = max(rc["ev"]["dec_dev"] for rc in pool_all)
    ker_w = max(max(rc["ev"]["ker_dev"], rc["ev"]["agg_dev"])
                for rc in pool_all)
    att_w = max(max(rc["ev"]["attr_dev"], rc["ev"]["comp_dev"])
                for rc in pool_all)
    lin_m = max((rc["ev"]["lin_dev"] for rc in all_rc
                 if rc["N"] <= DEEP_N), default=0.0)
    lin_d = max((rc["ev"]["lin_dev"] for rc in all_rc
                 if rc["N"] > DEEP_N), default=0.0)
    lin_c = max(crecs[c]["ev"]["lin_dev"] for c in crecs)
    rc9 = mrecs[0] if not smoke else recs[0]
    ov9 = len(np.intersect1d(rc9["bx"], rc9["xu"]))
    v_o, v_i = VCP.fr_symbolic_sumrule()
    if not smoke:
        ok298 = (abs(st["sh_med"] - R298_SH_MED) <= R298_SH_TOL
                 and abs(st["sl_main"] - R298_SL_MAIN)
                 <= R298_SL_MAIN_TOL
                 and abs(st["sl_T"] - R298_SL_T) <= R298_SL_T_TOL
                 and st["n_negT"] == 0
                 and abs(st["canc_med"] - R298_CANC_MED)
                 <= R298_CANC_TOL
                 and abs(st["canc_sl"] - R298_CANC_SL)
                 <= R298_CANC_SL_TOL
                 and abs(st["tc_med"]) <= R298_TC_ABS
                 and ov9 == R298_OVERLAP_W9)
        det298 = ("share med %.2f, sl_MAIN %+.3f, sl_|T| %+.3f, "
                  "T<0 %d/42, canc med %.2f sl %+.3f, tc med "
                  "%+.2g, overlap w9 %d (ref %d)"
                  % (st["sh_med"], st["sl_main"], st["sl_T"],
                     st["n_negT"], st["canc_med"], st["canc_sl"],
                     st["tc_med"], ov9, R298_OVERLAP_W9))
    else:
        ok298 = (ov9 == R298_OVERLAP_W9)
        det298 = ("SMOKE: ladder anchors skipped; overlap w9 %d "
                  "(ref %d)" % (ov9, R298_OVERLAP_W9))
    check("G24-r298-decomposition-anchors",
          dec_w <= DEC_BAR and ker_w <= KER_BAR
          and att_w <= ATTR_BAR and lin_m <= LIN_BAR
          and lin_d <= LIN_BAR_DEEP and lin_c <= LIN_BAR_CTRL
          and ok298 and v_o == 0 and v_i == 0,
          "the r298 record recomputed bit-near on %d worlds: "
          "identity dev %.1e (bar %.0e), kernel %.1e (bar %.0e), "
          "attribution %.1e (bar %.0e); linear window zero %.1e "
          "main / %.1e deep / %.1e controls; %s; r297 sum rule "
          "import devs %s/%s"
          % (len(pool_all), dec_w, DEC_BAR, ker_w, KER_BAR,
             att_w, ATTR_BAR, lin_m, lin_d, lin_c, det298,
             str(v_o), str(v_i)))
    spec_w = max(rc["ev"]["spec_dev"] for rc in pool_all)
    pars_w = max(rc["ev"]["pars_dev"] for rc in pool_all)
    band_w = max(rc["ev"]["band_dev"] for rc in pool_all)
    pair_w = max(rc["ev"]["pair_dev"] for rc in pool_all)
    partw = max(rc["ev"]["part_dev"] for rc in pool_all)
    en_w = max(rc["ev"]["en_dev"] for rc in pool_all)
    if not smoke:
        ok299 = (abs(st["sl_D"] - R299_SL_D) <= R299_SL_D_TOL
                 and abs(st["sl_absO"] - R299_SL_ABSO)
                 <= R299_SL_ABSO_TOL
                 and st["n_On"] == R299_N_ONEG
                 and abs(st["rat_med"] - R299_RAT_MED)
                 <= R299_RAT_TOL
                 and abs(st["sl_rat"] - R299_RAT_SL)
                 <= R299_RAT_SL_TOL
                 and abs(st["shl_med"] - R299_SH_LOW)
                 <= R299_SH_LOW_TOL
                 and abs(st["q50_med"] - R299_Q50) <= R299_Q50_TOL
                 and abs(st["cc_med"] - R299_CCONV)
                 <= R299_CCONV_TOL
                 and abs(st["cc_sl"] - R299_CCONV_SL)
                 <= R299_CCONV_SL_TOL
                 and abs(st["dd_med"] - R299_DD_MED) <= R299_DD_TOL
                 and abs(st["dd_sl"] - R299_DD_SL)
                 <= R299_DD_SL_TOL
                 and st["full_ov"] == R299_FULL_OV)
        det299 = ("sl_D %+.3f (ref %+.3f), sl_|O| %+.3f, O<0 "
                  "%d/42 (ref %d), ratio med %.2f sl %+.3f (ref "
                  "%.2f/%+.3f), LOW %.2f, q50 %.2f, cconv %.2f "
                  "sl %+.3f, dd %.3f sl %+.2f, full overlap "
                  "%d/42 (ref %d)"
                  % (st["sl_D"], R299_SL_D, st["sl_absO"],
                     st["n_On"], R299_N_ONEG, st["rat_med"],
                     st["sl_rat"], R299_RAT_MED, R299_RAT_SL,
                     st["shl_med"], st["q50_med"], st["cc_med"],
                     st["cc_sl"], st["dd_med"], st["dd_sl"],
                     st["full_ov"], R299_FULL_OV))
    else:
        ok299 = True
        det299 = "SMOKE: ladder anchors skipped"
    check("G25-r299-route-anchors",
          spec_w <= SPEC_BAR and pars_w <= SPEC_BAR
          and band_w <= SPEC_BAR and pair_w <= PAIR_BAR
          and partw <= PART_BAR and en_w <= EN_BAR and ok299,
          "the r299 exact machinery re-gated on %d worlds "
          "(spectral recomposition %.1e, Parseval %.1e, band sum "
          "%.1e, pair split %.1e, overlap partition %.1e, energy "
          "recomposition %.1e); %s"
          % (len(pool_all), spec_w, pars_w, band_w, pair_w,
             partw, en_w, det299))

    # ---------------- S3: exact section + toys + audits + mutants
    section("S3  EXACT SECTION (FRACTIONS) + TOYS + SCOPE AUDITS")
    w_o, w_i = fr_parseval_sumrule(wrong_h=False)
    _o2, w_mut = fr_parseval_sumrule(wrong_h=True)
    check("G30-sumrule-and-m3", w_o == 0 and w_i == 0
          and v_o == 0 and v_i == 0 and w_mut != 0,
          "the Parseval sum rule RE-PROVED exact in Fractions "
          "(module-own orth dev %s, identity dev %s; r297-G31 "
          "import devs %s/%s); m3 WRONG h-INDEX mutant (h_{k+2} "
          "for h_{k+1}) breaks by %s != 0 -- CAUGHT: the norm "
          "index of the sum-rule head is load-bearing"
          % (str(w_o), str(w_i), str(v_o), str(v_i), str(w_mut)))
    toy_w = max(toy_participation(), toy_shared_and_cs())
    toy_f = toy_envelope()
    check("G31-toy-exactness", toy_w <= TOY_BAR
          and toy_f <= TOY_FFT_BAR,
          "the hand toys reproduce the WHOLE new pipeline: "
          "participation (1,-1,1) -> D 3 / L1 3 / n_eff 3 / fill "
          "1 and (2,1,1) -> 6 / 4 / 8/3 / 3/4 with both product "
          "identities; shared-delta dc == dw x f exact on the "
          "border/window toy; CS route P_rec -2, wd 4, q 10, "
          "4 <= 40 (exact worst %.1e, bar %.0e); envelope toy "
          "B/D = 1/3 <= R_env at FFT precision (worst %.1e, "
          "bar %.0e)" % (toy_w, TOY_BAR, toy_f, TOY_FFT_BAR))
    h_pa = scope_audit("participation", BOUND_FORBIDDEN)
    h_sd = scope_audit("shared_delta", BOUND_FORBIDDEN)
    h_cs = scope_audit("cs_block_route", BOUND_FORBIDDEN)
    h_re = scope_audit("ratio_envelope", BOUND_FORBIDDEN)
    h_gift = scope_audit("mutant_gift_bound", BOUND_FORBIDDEN)
    h_peek = scope_audit("mutant_branch_peek", BOUND_FORBIDDEN)
    ag_hits = antigate_fragment_audit()
    clean = not (h_pa or h_sd or h_cs or h_re)
    check("G32-scope-audits", clean and bool(h_gift)
          and bool(h_peek) and not ag_hits,
          "the new builders (participation, shared_delta, "
          "cs_block_route, ratio_envelope) consume block vectors "
          "/ positions / weights only (no truth-side identifier "
          "in scope%s); m4a gift mutant FLAGGED (%s); m4b "
          "branch-peek mutant FLAGGED (%s); fragment audit: %s"
          % ("" if clean else " VIOLATION",
             "; ".join(h_gift) if h_gift else "NOT FLAGGED",
             "; ".join(h_peek) if h_peek else "NOT FLAGGED",
             "CLEAN" if not ag_hits else "; ".join(ag_hits)))
    m1_brk = toy_mustfail_m1()
    m2_brk, m2_good = toy_mustfail_m2()
    check("G33-mustfails-m1-m2-toys", m1_brk >= MUT_MIN
          and abs(m1_brk - 8.0 / 3.0) <= 1e-12
          and m2_brk >= MUT_MIN and abs(m2_brk - 2.0) <= 1e-12
          and m2_good <= TOY_BAR,
          "m1 PARTICIPATION FORMULA MUTANT (signed sum for L1): "
          "breaks the toy by %.6f (= 8/3 exact) CAUGHT; m2 "
          "SWAPPED MAX/L1 (claim D <= mx^2): breaks the toy by "
          "%.1f exact (6 > 4) while D <= mx x L1 holds (slack "
          "%.1e) -- the L1 factor is load-bearing"
          % (m1_brk, m2_brk, m2_good))

    # ---------------- S4: Leg A -- the diagonal anatomy
    section("S4  LEG A: DIAGONAL ANATOMY (PARTICIPATION)")
    cls_w = max(rc["ev"]["cls_dev"] for rc in pool_all)
    dband_w = max(rc["ev"]["dband_dev"] for rc in pool_all)
    mxl1_w = max(rc["ev"]["mxl1_slack"] for rc in pool_all)
    check("G40-anatomy-wards", cls_w <= CLS_BAR
          and dband_w <= DBAND_BAR and mxl1_w <= MAXL1_BAR,
          "the anatomy identities on %d worlds: class "
          "recomposition A + Bv == PDelta worst %.1e (bar %.0e); "
          "Parseval band sum == D worst %.1e (bar %.0e); the "
          "exact factorization D <= mx x L1 slack %.1e (bar "
          "%.0e) -- the participation coordinates are exact "
          "finite identities"
          % (len(pool_all), cls_w, CLS_BAR, dband_w, DBAND_BAR,
             mxl1_w, MAXL1_BAR))
    show = (sorted(exc, key=lambda r_: r_["kz"]) + mrecs
            if not smoke else mrecs)
    for rc in show:
        ev = rc["ev"]
        info("kz%-3d N%-4d %-4s m %-3d H %-2d  D %.2e  n_eff "
             "%.2f  fill %.2f  B/D %.2f  R_env %.2f  wdmax "
             "%.2e" % (rc["kz"], rc["N"],
                       "EXC" if rc["g_branch"] < 0 else "chp",
                       ev["m"], ev["H"], ev["part"]["D"],
                       ev["part"]["neff"], ev["part"]["fill"],
                       ev["B"] / max(ev["D"], 1e-300),
                       ev["r_env"], ev["wdmax"]))
    if not smoke:
        check("G41-anatomy-census", st["add1"] <= ADD_BAR
              and st["add2"] <= ADD_BAR,
              "DIAG_ANATOMY (42 rungs): n_eff med %.2f slope "
              "%+.3f; EXACT decomposition (i) sl_D = 2 x sl_L1 - "
              "sl_neff = 2 x (%+.3f) - (%+.3f) = %+.3f (dev "
              "%.1e); (ii) sl_D = sl_mx + sl_L1 + sl_fill = "
              "%+.3f %+.3f %+.3f (dev %.1e); class shares "
              "A/Bv/cross med %.2f/%.2f/%+.2f; D band shares "
              "LOW/MID/EDGE med %.2f/%.2f/%.2f; top-block share "
              "med %.2f slope %+.3f"
              % (st["neff_med"], st["sl_neff"], st["sl_L1"],
                 st["sl_neff"], st["sl_D"], st["add1"],
                 st["sl_mx"], st["sl_L1"], st["sl_fill"],
                 st["add2"], st["clsA_med"], st["clsB_med"],
                 st["clsX_med"], st["dlo_med"], st["dmid_med"],
                 st["ded_med"], st["top_med"], st["sl_top"]))
    else:
        check("G41-anatomy-census", True, "SMOKE: skipped")

    # ---------------- S5: Leg B -- the derivation routes
    section("S5  LEG B: DERIVATION ROUTES FOR DIAG_TARGET")
    df_w = max(rc["ev"]["df_dev"] for rc in pool_all)
    rec_w = max(rc["ev"]["rec_dev"] for rc in pool_all)
    cs_w = max(rc["ev"]["cs_worst"] for rc in pool_all)
    csc_w = max(rc["ev"]["cs_comp"] for rc in pool_all)
    check("G50-b1-wards", df_w <= DF_BAR and rec_w <= REC_BAR
          and cs_w <= CS_BAR and csc_w <= CS_BAR,
          "B1 wards on %d worlds: the factorization dc == dw x f "
          "at every shared position worst %.1e (bar %.0e) -- the "
          "r299 c-value-difference fund made computational; the "
          "block reconstruction P_rec == P_ov worst %.1e (bar "
          "%.0e); per-block Cauchy-Schwarz slack %.1e and "
          "composed D_ov <= wdmax x QabsD slack %.1e (bars %.0e, "
          "rel D) -- the chain-norm route is exact algebra"
          % (len(pool_all), df_w, DF_BAR, rec_w, REC_BAR,
             cs_w, csc_w, CS_BAR))
    # ---- B1 identity census on the |dw| measure (id pool)
    id_pool = (mrecs + [crecs[c] for c in ("EPST", "SCR")]) \
        if smoke else \
        ([rc for rc in recs if rc["kz"] in (KZ_ANCHOR, 20)]
         + mrecs + [crecs[c] for c in ("EPST", "SCR")])
    crosses = []
    devs = []
    for rc in id_pool:
        sd = rc["ev"]["sd"]
        if sd["n"] == 0:
            continue
        cq = VCP.chain_quads(rc["p"]["rows"], rc["N"], sd["x"],
                             np.abs(sd["dw"]))
        crosses.append(max(abs(v) for v in cq["cr"].values()))
        devs.append(abs(cq["q2"] - cq["pd"])
                    / max(abs(cq["q2"]), 1e-300))
    id_worst = max(max(crosses), max(devs)) if crosses else 0.0
    id_cmed = float(np.median(crosses)) if crosses else 0.0
    if id_worst <= ID_HOLDS:
        id_st = "HOLDS"
    elif id_worst <= ID_NEAR:
        id_st = "NEAR"
    else:
        id_st = "BREAKS"
    if not smoke:
        comp_b1 = st["sl_wdmax"] + st["sl_qd"]
        check("G51-b1-census", True,
              "B1 census: sl_wdmax %+.3f + sl_Qd %+.3f = composed "
              "%+.3f vs sigma* %+.3f -- %s; identity census on "
              "the |dw| measure (%d worlds): %s (cross med %.3f, "
              "worst %.3f; HOLDS bar %.0e) -- the proven sum "
              "rule %s to the difference measure"
              % (st["sl_wdmax"], st["sl_qd"], comp_b1,
                 st["sigma_star"],
                 "MEETS" if comp_b1 <= st["sigma_star"]
                 else "FAILS by %.3f"
                 % (comp_b1 - st["sigma_star"]),
                 len(id_pool), id_st, id_cmed, id_worst,
                 ID_HOLDS,
                 "ATTACHES" if id_st == "HOLDS"
                 else "does NOT attach"))
        comp_b2 = st["sl_mx"] + st["sl_L1"]
        check("G52-b2-census", True,
              "B2 census: sl_mx %+.3f + sl_L1 %+.3f = composed "
              "%+.3f vs sigma* %+.3f -- %s; MAX control: "
              "slope(maxatom/M) %+.3f (a single c-value "
              "distance), block/atom ratio mx/maxatom med %.2f "
              "slope %+.3f -- %s; the fill decay %+.3f is what "
              "the factorization cannot see"
              % (st["sl_mx"], st["sl_L1"], comp_b2,
                 st["sigma_star"],
                 "MEETS" if comp_b2 <= st["sigma_star"]
                 else "FAILS by %.3f"
                 % (comp_b2 - st["sigma_star"]),
                 st["sl_maxatom"], st["mxma_med"], st["sl_mxma"],
                 "the max IS atom-controlled"
                 if st["mxma_med"] <= 2.0
                 else "the max aggregates many atoms",
                 st["sl_fill"]))
        need_neff = 2.0 * st["sl_L1"] - st["sigma_star"]
        check("G53-b3-census", True,
              "B3 census (DISCLOSED: the slope clause is an exact "
              "reparametrization of DIAG_TARGET): NEFF_TARGET "
              "needed slope(n_eff) >= 2 sl_L1 - sigma* = %+.3f, "
              "measured %+.3f -- %s (margin %.3f); D_rank(Delta) "
              "slope %+.3f (%s); sp(N, n_eff) %+.2f, "
              "sp(D_rank(Delta), n_eff) %+.2f -- the D_rank link "
              "is %s"
              % (need_neff, st["sl_neff"],
                 "MET" if st["sl_neff"] >= need_neff
                 else "NOT MET by %.3f"
                 % (need_neff - st["sl_neff"]),
                 st["sl_neff"] - need_neff, st["dd_sl"],
                 "falling -- provable terrain"
                 if st["dd_sl"] < 0 else "NOT falling",
                 st["sp_n_neff"], st["sp_dd_neff"],
                 "real but correlational"
                 if abs(st["sp_dd_neff"]) >= 0.5
                 else "weak"))
    else:
        need_neff = float("nan")
        check("G51-b1-census", True,
              "SMOKE: |dw| identity census at w9 pool: %s (cross "
              "med %.3f)" % (id_st, id_cmed))
        check("G52-b2-census", True, "SMOKE: skipped")
        check("G53-b3-census", True, "SMOKE: skipped")

    # ---------------- S6: sealed diag adjudication + Leg D
    section("S6  SEALED DIAG ADJUDICATION + LEG D")
    b1_valid = (df_w <= DF_BAR and rec_w <= REC_BAR
                and cs_w <= CS_BAR and csc_w <= CS_BAR)
    b2_valid = (mxl1_w <= MAXL1_BAR)
    env_sw = max(rc["ev"]["env_slack"] for rc in pool_all)
    env_cw = max(rc["ev"]["env_comp"] / max(rc["ev"]["r_env"],
                                            1e-300)
                 for rc in pool_all)
    ratio_valid = (env_sw <= ENV_BAR and env_cw <= ENV_BAR)
    if not smoke:
        b3_valid = (st["add1"] <= ADD_BAR)
        b1_ok = b1_valid and (st["sl_wdmax"] + st["sl_qd"]
                              <= st["sigma_star"])
        b2_ok = b2_valid and (st["sl_mx"] + st["sl_L1"]
                              <= st["sigma_star"])
        b3_ok = (b3_valid and st["sl_neff"] >= need_neff
                 and st["dd_sl"] < 0.0)
        derived = b1_ok and id_st == "HOLDS"
        if derived:
            outcome = "DIAG_DERIVED"
        elif b1_ok or b2_ok or b3_ok:
            outcome = "DIAG_SPLIT"
        else:
            outcome = "DIAG_STILL_EMPIRICAL"
        fired = []
        if b1_ok:
            fired.append("B1(QABS_TARGET: prove the wdmax/QabsD "
                         "scaling, composed %+.3f)"
                         % (st["sl_wdmax"] + st["sl_qd"]))
        if b2_ok:
            fired.append("B2(MAXL1_TARGET: prove sl_mx + sl_L1 "
                         "<= sigma*, composed %+.3f)"
                         % (st["sl_mx"] + st["sl_L1"]))
        if b3_ok:
            fired.append("B3(NEFF_TARGET: prove slope(n_eff) >= "
                         "%+.3f from the falling D_rank, "
                         "measured %+.3f)"
                         % (need_neff, st["sl_neff"]))
        check("G60-diag-adjudication", True,
              "SEALED RULE fired: %s (B1_OK %s: composed %+.3f "
              "vs sigma* %+.3f, ident %s; B2_OK %s: composed "
              "%+.3f; B3_OK %s: needed %+.3f vs measured %+.3f, "
              "dd_sl %+.3f; DERIVED clause: B1_OK AND ident "
              "HOLDS)%s"
              % (outcome, b1_ok, st["sl_wdmax"] + st["sl_qd"],
                 st["sigma_star"], id_st, b2_ok,
                 st["sl_mx"] + st["sl_L1"], b3_ok, need_neff,
                 st["sl_neff"], st["dd_sl"],
                 ("; fired: " + " | ".join(fired)) if fired
                 else ""))
    else:
        outcome = "SMOKE_NO_ADJUDICATION"
        fired = []
        check("G60-diag-adjudication", True, "SMOKE: skipped")

    # ---------------- S7: Leg C -- the ratio flatness
    section("S7  LEG C: RATIO FLATNESS (KERNEL ENVELOPE)")
    check("G70-ratio-envelope-wards", ratio_valid,
          "the exact kernel envelope on %d worlds: F_H(theta) <= "
          "min(H, 1/(H sin^2(theta/2))) pointwise slack %.1e "
          "(x 1/H scale) and composed B/D <= R_env slack %.1e "
          "(rel R_env; bars %.0e) -- pure kernel algebra, "
          "world-blind" % (len(pool_all), env_sw, env_cw,
                           ENV_BAR))
    if not smoke:
        ratio_structural = (ratio_valid
                            and st["sl_renv"] <= RATIO_GROW)
        rat_out = ("RATIO_BOUNDED_STRUCTURAL" if ratio_structural
                   else "RATIO_EMPIRICAL")
        check("G71-ratio-adjudication", True,
              "SEALED RULE fired: %s -- RATIO_TABLE: B/D med "
              "%.2f slope %+.3f; R_env med %.2f slope %+.3f (grow "
              "bar %+.2f: %s); sp(B/D, q50) %+.2f, slope(q50) "
              "%+.3f -- %s; DISCLOSED: R_env consumes the "
              "measured spectrum shape (the kernel side is "
              "structural, the weighting is not)"
              % (rat_out, st["rat_med"], st["sl_rat"],
                 st["renv_med"], st["sl_renv"], RATIO_GROW,
                 "non-growing" if st["sl_renv"] <= RATIO_GROW
                 else "GROWS by %.3f over bar"
                 % (st["sl_renv"] - RATIO_GROW),
                 st["sp_rat_q50"], st["sl_q50"],
                 "the ratio IS the lobe-width coordinate"
                 if abs(st["sp_rat_q50"]) >= 0.5
                 else "the ratio and the lobe width decouple"))
    else:
        ratio_structural = False
        rat_out = "SMOKE_NO_ADJUDICATION"
        check("G71-ratio-adjudication", True, "SMOKE: skipped")

    # ---------------- Leg D: composition or refined freeze
    if not smoke:
        if outcome == "DIAG_DERIVED" and ratio_structural:
            info("CANDIDATE THEOREM (diagonal composition, L2 "
                 "generic half): for every rung of the sealed "
                 "ladder (N in [%d, %d], H = ceil(sqrt(m))): the "
                 "B1 chain bound D <= wdmax x QabsD with the "
                 "attached sum rule => sl_D <= sigma* = %+.3f; "
                 "with the structural ratio bound B/D <= R_env "
                 "(non-growing) => sigma <= sigma* => the r297 "
                 "target inequality => the v964-S0 vdC theorem "
                 "=> delta' > %.2f on the generic half; "
                 "exceptions: 6 via the r287 F2 certificates, "
                 "kz15 via the r270 exact-finite certificate.  "
                 "Wave-9 promotion candidate -- NOT promoted "
                 "here." % (min(Ns), max(Ns), st["sigma_star"],
                            DELTA_NEED))
            legd = "COMPOSED"
        else:
            info("REST_FROZEN (the refined pair, smaller than "
                 "r299): DIAG rest = NEFF_TARGET: prove "
                 "slope(n_eff) >= 2 x slope(L1/M) - sigma* = "
                 "%+.3f (measured %+.3f, margin %.3f; the D_rank "
                 "correlation sp %+.2f is the named bridge to "
                 "provable terrain); equivalently sl_mx + sl_L1 "
                 "+ sl_fill <= sigma* with the fill decay %+.3f "
                 "as the non-factorizable part.  RATIO rest = "
                 "slope(R_env) <= %+.2f (measured %+.3f -- %s)."
                 % (need_neff, st["sl_neff"],
                    st["sl_neff"] - need_neff, st["sp_dd_neff"],
                    st["sl_fill"], RATIO_GROW, st["sl_renv"],
                    "already MET structurally"
                    if ratio_structural else "NOT met"))
            legd = "REST_FROZEN"
        check("G61-leg-d", True,
              "Leg D %s -- the full candidate fires ONLY on "
              "DIAG_DERIVED + RATIO_BOUNDED_STRUCTURAL by the "
              "sealed rule; no post-hoc rescue"
              % ("FIRED (candidate printed, NOT promoted)"
                 if legd == "COMPOSED" else
                 "REST_FROZEN (refined targets printed)"))
    else:
        check("G61-leg-d", True, "SMOKE: skipped")

    # ---------------- S8: worlds + m2 real + anchors + mp wards
    section("S8  WORLD CLASSES + MUSTFAIL M2 (REAL) + MP WARDS")
    if not smoke:
        pm = float(np.median([rc["ev"]["part"]["neff"]
                              / max(rc["ev"]["m"], 1)
                              for rc in recs]))
        fm = float(np.median([rc["ev"]["part"]["fill"]
                              for rc in recs]))
        main_cls = ("PART_HIGH" if pm >= PART_CLS else "PART_LOW",
                    "FILL_HIGH" if fm >= FILL_CLS else "FILL_LOW")
        ctl_note = []
        world_blind = True
        for c in ("EPST", "SCR"):
            ev = crecs[c]["ev"]
            pc = ev["part"]["neff"] / max(ev["m"], 1)
            fc = ev["part"]["fill"]
            cls_c = ("PART_HIGH" if pc >= PART_CLS
                     else "PART_LOW",
                     "FILL_HIGH" if fc >= FILL_CLS
                     else "FILL_LOW")
            ctl_note.append("%s %s/%s" % (c, cls_c[0], cls_c[1]))
            world_blind &= (cls_c == main_cls)
        check("G80-world-controls", True,
              "the anatomy classes (same sealed med rules at the "
              "single control rung): MAIN %s/%s vs %s -- %s "
              "(TESTED, not assumed: a class break would be a "
              "disclosed finding; crossref r299: the O-sign "
              "class already separates)"
              % (main_cls[0], main_cls[1], str(ctl_note),
                 "WORLD-BLIND" if world_blind
                 else "WORLD_SENSITIVE (disclosed)"))
    else:
        world_blind = True
        main_cls = ("n/a", "n/a")
        ctl_note = []
        check("G80-world-controls", True, "SMOKE: skipped")
    m2_pool = mrecs + ([recs[0]] if smoke else [])
    m2_vals = []
    for rc in m2_pool:
        p_ = rc["ev"]["part"]
        m2_vals.append((rc["kz"], (p_["D"] - p_["mx"] ** 2)
                        / max(p_["D"], 1e-300)))
    m2_min = min(v for _k, v in m2_vals)
    check("G81-mustfail-m2-real", m2_min >= MUT_MIN,
          "m2 SWAPPED MAX/L1 on the real mains: D - mx^2 = %s of "
          "D (all >= %.0e) LOUD -- a single-block bound loses "
          "the object; the L1 mass factor is load-bearing"
          % ("; ".join("w%d %.1e" % (k, v) for k, v in m2_vals),
             MUT_MIN))
    rowsS = ctrl["SMOOTH"]["rows"]
    NS = ctrl["SMOOTH"]["N"]
    scT = [abs(rowsS[k]["tb"] * math.exp(rowsS[k]["Ls"]
                                         - rowsS[k + 1]["Ls"]))
           for k in range(NS - 1)]
    alias = max(scT[2:]) / max(scT[0], scT[1])
    qS = float(ctrl["SMOOTH"]["rho"][NS - 1]) / B57
    evS = crecs["SMOOTH"]["ev"]
    okSd = (evS["spec_dev"] <= SPEC_BAR
            and evS["pair_dev"] <= PAIR_BAR
            and evS["cls_dev"] <= CLS_BAR
            and evS["env_slack"] <= ENV_BAR)
    check("G82-smooth-anchor", alias <= SM_ALIAS_BAR
          and abs(qS) <= SM_Q_BAR and okSd,
          "SMOOTH: drive alias %.1e <= %.0e; q_N = %.1e <= %.0e; "
          "every exact ward holds trivially on the self-aliased "
          "source (%s)"
          % (alias, SM_ALIAS_BAR, qS, SM_Q_BAR,
             "OK" if okSd else "BROKEN"))
    if not smoke:
        mp_note = []
        ok_mp = True
        rc15 = next(r_ for r_ in recs if r_["kz"] == KZ_ANCHOR)
        t15 = PBB.mp_drive(rc15["p"], MP_DPS)
        d15 = abs(t15 - rc15["t_term"])
        ok_mp = ok_mp and (d15 <= MP_T_BAR)
        mp_note.append("kz15 (N %d) dev %.1e (bar %.0e)"
                       % (rc15["N"], d15, MP_T_BAR))
        for rc in recs[-2:]:
            t_mp = PBB.mp_drive(rc["p"], MP_DPS)
            dv = abs(t_mp - rc["t_term"])
            ok_mp = ok_mp and (dv <= MP_DEEP_BAR)
            mp_note.append("kz%d (N %d, DEEPEST) dev %.1e (bar "
                           "%.0e)" % (rc["kz"], rc["N"], dv,
                                      MP_DEEP_BAR))
        check("G83-mp-deep-wards", ok_mp,
              "mp (dps %d) terminal drive at the trend-critical "
              "rungs: %s" % (MP_DPS, "; ".join(mp_note)))
    else:
        check("G83-mp-deep-wards", True, "SMOKE: skipped")

    # ---------------- S9: verdict
    section("S9  VERDICT")
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the exact participation anatomy of the diagonal, "
          "the three-route derivation census with exact wards, "
          "the |dw| identity census, the exact kernel-envelope "
          "ratio majorant, the sealed two adjudications and the "
          "refined rest freeze -- NO new certificate promoted, "
          "NO bound modification of the sealed forms")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        parts = ["DIAG_ANATOMY(n_eff med %.2f sl %+.3f; sl_D = "
                 "2 sl_L1 - sl_neff = 2(%+.3f) - (%+.3f) = %+.3f "
                 "dev %.0e; = sl_mx %+.3f + sl_L1 %+.3f + "
                 "sl_fill %+.3f dev %.0e; class A/Bv/x med "
                 "%.2f/%.2f/%+.2f; D bands %.2f/%.2f/%.2f; top "
                 "share %.2f sl %+.3f)"
                 % (st["neff_med"], st["sl_neff"], st["sl_L1"],
                    st["sl_neff"], st["sl_D"], st["add1"],
                    st["sl_mx"], st["sl_L1"], st["sl_fill"],
                    st["add2"], st["clsA_med"], st["clsB_med"],
                    st["clsX_med"], st["dlo_med"], st["dmid_med"],
                    st["ded_med"], st["top_med"], st["sl_top"])]
        parts.append("ROUTE_TABLE(B1 valid 47/47 sl_wdmax %+.3f "
                     "sl_Qd %+.3f composed %+.3f vs sigma* %+.3f "
                     "ident %s; B2 valid 47/47 sl_mx %+.3f sl_L1 "
                     "%+.3f composed %+.3f maxatom sl %+.3f "
                     "mx/maxatom med %.2f; B3 needed %+.3f "
                     "measured %+.3f dd_sl %+.3f sp(dd, n_eff) "
                     "%+.2f)"
                     % (st["sl_wdmax"], st["sl_qd"],
                        st["sl_wdmax"] + st["sl_qd"],
                        st["sigma_star"], id_st, st["sl_mx"],
                        st["sl_L1"], st["sl_mx"] + st["sl_L1"],
                        st["sl_maxatom"], st["mxma_med"],
                        need_neff, st["sl_neff"], st["dd_sl"],
                        st["sp_dd_neff"]))
        if outcome == "DIAG_DERIVED":
            parts.append("DIAG_DERIVED(B1 + ident HOLDS)")
        elif outcome == "DIAG_SPLIT":
            parts.append("DIAG_SPLIT(%s)" % " | ".join(fired))
        else:
            parts.append("DIAG_STILL_EMPIRICAL(common "
                         "obstruction: both magnitude "
                         "factorizations pay the fill/imbalance "
                         "factor %+.3f; the reparametrized "
                         "target is not met)" % st["sl_fill"])
        parts.append("RATIO_TABLE(B/D med %.2f sl %+.3f; R_env "
                     "med %.2f sl %+.3f; sp(B/D, q50) %+.2f, "
                     "sl_q50 %+.3f)"
                     % (st["rat_med"], st["sl_rat"],
                        st["renv_med"], st["sl_renv"],
                        st["sp_rat_q50"], st["sl_q50"]))
        parts.append(rat_out)
        if outcome == "DIAG_DERIVED" and ratio_structural:
            parts.append("CANDIDATE_THEOREM(printed in S6/S7, "
                         "wave-9 candidate NOT promoted)")
        else:
            parts.append("REST_FROZEN(DIAG: slope(n_eff) >= "
                         "%+.3f measured %+.3f margin %.3f; "
                         "RATIO: slope(R_env) <= %+.2f measured "
                         "%+.3f)"
                         % (need_neff, st["sl_neff"],
                            st["sl_neff"] - need_neff,
                            RATIO_GROW, st["sl_renv"]))
        if not world_blind:
            parts.append("WORLD_SENSITIVE(MAIN %s/%s vs %s -- "
                         "disclosed finding)"
                         % (main_cls[0], main_cls[1],
                            str(ctl_note)))
        verd = " + ".join(parts)
    npass = sum(1 for _n, ok, _d in CHECKS if ok)
    check("G96-verdict", npass == len(CHECKS),
          "%s%s -- SATZ (machine-gated): the participation "
          "identities, the dc = dw x f factorization, the "
          "per-block CS chain, the max/L1 factorization, the "
          "kernel envelope, the Fractions sum rule (all "
          "world-blind); MEASURED: every slope, share, class and "
          "correlation (42 rungs only); OPEN: NEFF_TARGET beyond "
          "the measured margin, the cofinal step H5, kz15 beyond "
          "r270; 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 \(SMOKE\)\s+SPEC_SHA\s+"
    r"([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 in the sealed --smoke stage (wave-4 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
    argv_saved = sys.argv
    sys.argv = [fname, "--smoke"]
    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
        finally:
            sys.argv = argv_saved
    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, smoke stage) | "
          "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 = (
    ('dens_identity_probe', _SRC_0, 12, 'ffb413c80cddc1d3'),
    ('vdc_chain_provenance_probe', _SRC_1, 27, 'e42a76eb8ae71422'),
    ('window_border_transfer_probe', _SRC_2, 28, '05e831bec627aee6'),
    ('fejer_decay_probe', _SRC_3, 32, 'f432e94450ad545d'),
    ('diag_target_probe', _SRC_4, 31, '55218b5db8ece163'),
)


def run():
    t0 = time.time()
    print("=" * 74)
    print('v966 -- PRIME.L2.REDUCTION_CHAIN.01 (rounds 296-300):')
    print('THE L2 REDUCTION CHAIN -- the DENS fork closed, the delta\' > 0.21')
    print('target reduced to ONE inequality: (A) r296 DENS_WORLD_BLIND -- the')
    print('92.5-pct DENS top axis is NOT identifiable and NOT L*-coupled at')
    print('the sealed bar (coupling number +0.394 < 0.40; lam3 couples harder')
    print('-0.574): the DENS lane is CLOSED, resources route to L2; (B) r297')
    print('freezes the target inequality sigma <= sigma* = -0.516 (measured')
    print('-0.714, margin 0.198 -- what is missing is not room, it is')
    print('provenance) and names the magnitude wall; (C) r298 proves the exact')
    print('sign-preserving split S_F = B(omega,omega) + B(Delta,omega+beta):')
    print('the window main term is EMPTY, share 0.99 -- the vdC input IS the')
    print('Fejer energy of the difference measure; (D) r299 goes LOWPASS,')
    print('finds full-support overlap (Delta = a pure c-value difference),')
    print('kills ET/Abel loud (+1.948) and fires DECAY_SPLIT on the live pair')
    print('edge (sl_D -0.571 <= sigma*, ratio falling); (E) r300 proves the')
    print('exact participation split sl_D = 2 sl_L1 - sl_neff, closes both')
    print('magnitude routes honestly, settles the ratio half structurally')
    print('(kernel envelope, R_env falling) and freezes NEFF_TARGET:')
    print('slope(n_eff) >= +0.908 (measured +0.963, margin 0.055) -- the ONE')
    print('remaining inequality of the chain (r301 in flight, not consumed)')
    print("(frozen probes embedded byte-exact, sealed --smoke stage; NO RH claim)")
    print("=" * 74, flush=True)
    gates = []
    _l2_reduction_chain(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("v966: %d/%d gates passed (18 module-own checks + 5 "
          "pattern gates) | runtime %.1f s"
          % (sum(gates), len(gates), time.time() - t0))
    print('the L2 reduction chain stands: [NEFF_TARGET, open] ==> DIAG ==>')
    print('sigma <= sigma* ==> the r297 target ==> the v964-S0 vdC theorem')
    print('==> delta\' > 0.21 on the generic half -- every link exact or')
    print('structurally settled EXCEPT the one frozen inequality NEFF_TARGET')
    print('(slope(n_eff) >= +0.908, measured +0.963, margin 0.055; the D_rank')
    print('bridge sp -0.81 is real but correlational; PRIME.L2.NEFF_TARGET.01')
    print('[O], round 301 in flight, NOT consumed).  The DENS lane is closed')
    print('honestly (DENS_WORLD_BLIND at the sealed bars).  HONEST: no')
    print('cofinal law, exceptions certified finitely (6 via r287 F2, kz15')
    print('via r270); L* itself is NOT proved (PRIME.LSTAR.SUBORDINATION.01')
    print('[O], Lean lstar_subordination).')
    print('Mincut base 4 / refined 5 unchanged; NO RH claim.')
    print("[%s] v966 VERDICT GATE" % ("PASS" if ok else "FAIL"))
    return 0 if ok else 1


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