#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""v970 -- PRIME.EXTRACTION.ELEMENTWISE.01 [E] + PRIME.L2.RENYI3.MEASURED_COMPOSITION.01 [O] + PRIME.L2.RENYI3.SLIDING_BOUND.01 [O update] + PRIME.L2.RENYI3.PROVENANCE.01 [O update] (rounds 323-327 incl. the r326 Lean round, ADJUDICATED at the finite-identity level plus typed measurement legs): THE EXTRACTION REPAIR AND THE TERMINAL COMPOSITION -- after the wave-12 reviewer reallocation (55 terminal / 35 extraction / 10 formalization / 0 internal L*) the morning ran five items and this module freezes them.  (1) THE R323 CLEAN ABORT (no probe -- consumed as a NOTE): the planned L* indefinite-signature fork was aborted BY the binding reviewer adjudication (L* internally paused at allocation 0 percent, the selection geometry not pursued) at the END OF THE DESIGN PHASE, BEFORE any write access -- no probe created, no measurement run, no rh/ file touched, no INVENTORY entry, nothing counts as a round; post-abort suite verification run_rh --fast 73/73 with 103/103 pins.  (2) THE R324 QMAX x M2 ORIGIN ROUND (qmax_m2_origin_probe.py 36/36, SPEC dc36cacbebdaf53b; the round's ORIGINAL contract FA_PROVENANCE was executed and sealed FIRST as fa_provenance_probe.py 36/36, SPEC 9a6696f875718322 -- then the reviewer course correction arrived mid-round and SUPERSEDED it: the F_A-boundedness hunt demoted as a potentially unnecessarily strong statement, the cleaner decomposition is QMAX x M_2; the pre-work is BANKED as r324-pre, stays sealed and citable, its record consumed as disclosed anchors): PILEUP_GROWS_SUBCRITICAL(e_tot +0.172 < CRIT 0.224, halves +0.141/-0.160 both subcritical, the second FALLING -- DECIDED; by the reviewer contract a sufficient, first-class outcome) -- S0 EXACT: M_3 <= q_max x M_2 and M_2 <= q_max Fractions-proved (toy slack exactly 1/36, DOUBLE equality at the flat profile -- sharp), live 69 worlds slack 0.0; F_A DE-BLACK-BOXED: the identity F_A x B x log m == m x q_max holds at 2.7e-16 -- F_A is the rank-local normalization of m q_max, not an independent coordinate, the r321 bracket upper side == PhiH1 and the interpolation improves it by exactly M_2/q_max <= 1; S1 the pointwise M_2 export REFUTED (C_2 = 2.2557 mid-ladder, FAILS 7/39 -- exactly the banked spike set kz53/67/83/28/61/76/109 at +35..42 percent; the r302 DISTRIBUTIONAL export GO, stationarity KS 0.023/0.016 even tighter than the r302 core 0.043) -- the reviewer expectation honestly refuted; S2 the mechanism HALF AND HALF: the scale decomposition recomposes exactly (2.2e-16), fold multiplicity <= 2 on 69/69, the O(log m) SCALE COUNT CERTIFIES pointwise (C_NSC 2.0258, 0/39) but the per-scale mass O(1/m) is REFUTED (C_PIL 9.3583, 11/39) -- THE HARDNESS ANSWER: the near-critical windows are NOT multiscale convergence but ONE near-maximal heavy source scale at the argmax block (kz53: s0 carries 13.78 of G 13.02 at nsc 5 == ladder median; kz67: s0 = 22.38); S3 the COMPOSITION typed MEASURED: sum q^3 <= 8.941 (log m) m^{+0.172}/m^2 => N_3 >= m^{0.914}/sqrt(8.941 log m), N_2 >= N_3 (r306 exact chain) => N_2 >= m^0.888 for all m >= m_0* = 10^59.6 => the full chain to terminal_positive_main -- m_0* astronomical, the gap (274, 10^59.6) is the disclosed extrapolation hypothesis, no cofinal claim.  THE R328B CHAIN CORRECTION (independent adversarial chain audit, 2026-08-27, consumed as a CHAIN ANNOTATION -- the sealed r324 record is NOT edited): the record bar CRIT = 0.224 was derived from the ATOM-level need 0.888 (R302_ATOM_NEED for n_eff_atom); the composition functional N_2 = n_eff is BLOCK-level -- its need is 0.908 in N units, 908/1002 = 454/501 ~ 0.9062 in m units via sl_nact = +1.002, hence the chain-honest bar is CRIT = 2 x (1 - 454/501) = 94/501 ~ 0.188; THE VERDICT SURVIVES (e_tot +0.172 < 0.188, exact in S0-T5d) but any future e_tot in the window (0.188, 0.224) would fire falsely -- the future bar is 0.188; the chain-honest m_0* at need 454/501 is 10^238 (the record 10^59.6 belonged to the atom-level need; both astronomical, the qualitative statement unchanged); the printed pressure step 'N_2 >= m^0.888 => slope(n_eff) >= +0.908' is a NON-SEQUITUR as written (0.888 x 1.002 = 0.8898 < 0.908) -- the inference carries only via the full polylog form 1 - e/2 = 0.914 >= 0.9062 (margin +0.008); the S3 pressure line attributes the whole e_tot (incl. e_M2 +0.014) to the qmax factor -- correct as a product bound, misleading per-factor.  (3) THE R325 EXTRACTION-REPAIR FORK (extraction_order_probe.py 18/18, SPEC 31277f917dd04a7e final / freeze 57e50d366a62f2a6): ELEMENTWISE_STABILIZATION_GO primary + co-letters CANONICAL_MESH_REBUILD_GO + SIGNED_DEFECT_CORRECTION_GO(SIGN) + ANCHOR_ONLY_INSUFFICIENT -- the repair statement is a QUANTIFIER STATEMENT, not a mesh theory: on the NATIVE dense class (dyadic step-function autocorrelations, the v749 "Weil form of step functions" class, elements sealed by seed) ALL THREE channels (comb/arch/pole) of the canonical tower windows stabilize EXACTLY at the predicted finite anchor onset alpha* = (n_g + 1) D_0 / 2 (0.0/3.3e-18 above, 2.7e-2..5.3e-2 below) AND the value is CONSTANT under dyadic mesh refinement (comb 3.3e-18, arch 1.5e-15, pole 2.0e-17) -- NO mesh-cofinal ladder, NO transport, H_cof IS NOT NEEDED; variant B is the construction substrate of A (v749 T1.4b reproduced: every deployed window IS a directly rebuilt tower member at rel dev 0.0; rebuild ladder PD per stage), not an independent route; variant C is the quantified density step (the per-channel defect on the non-native C^2 class is ONE-SIGNED -- comb NEGATIVE, arch/pole POSITIVE -- falls at the D^2 class rate per channel inside the RIGOROUS interpolation envelope (D^2/8)||F''|| K_ch, controlled on its own, no wall margin anywhere), not an independent extraction; the anchor-only floor is real (E_tot constant nonzero +1.77e-4/+1.59e-4 -- the R319 false-floor mechanism on this probe's own elements).  (4) THE R326 LEAN ROUND (rh/lean/RH/Elementwise.lean -- already merged and green, consumed as a REPORT, NO Lean change ships with this module; artifacts re-verified by lake build + run_rh.py): the Level-C architecture implemented -- CanonicalPrimeWindow + SourceExactSpec + the construction theorem sourceExact_buildPrimeWindow PROVED (the wave-12 reviewer target "exactly one construction theorem": SourceExact ELIMINATED as a free assumption from the extraction route -- built windows provably carry their source; the relation to the opaque guard is a typed completion sorry, intended-true, unprovable by design), GridElement (the v749 class) built for real with PROVED compact support, the comb stabilization elementwise PROVED (onset a_0(f) = max(1, ceil(exp(steps x D0))) PREDEFINED from the support alone, corpus gauge 2 Lambda/sqrt n, NO mesh quantifier; honesty tie: the read IS the built window's comb channel, rfl per atom), arch/pole as opaque reads (r273/r320 convention extended) with typed classical sorrys, the EXTRACTION WITHOUT THE LADDER weil_nonneg_of_windowlocal PROVED (ONE finite instantiation per element -- Euclid anchor + native mesh; premise honestly typed on the plain form; the compression bridge bordered => plain named as the Prop BorderedCompressionBridge, no truth commitment) plus weil_nonneg_of_bordered (composition logic PROVED); SORRY CENSUS 5 -> 8 with THREE NEW previously-unformalizable typed Level-C statements (arch_elementwise_stabilization CLASSICAL/S2, pole_elementwise_stabilization CLASSICAL/S2, specFamily_sourceExact_completion CLASSICAL + DEFINITIONAL) -- the wave-12 reservation "the Level-C distance appears in no sorry" is thereby PARTIALLY DISCHARGED: the proof graph now shows Level C as named statements; the five legacy sorrys byte-identical; lake build green (8 intentional sorry warnings), run_rh --fast 75/75.  THE HONEST FORMULATION OF THE NEW CONNECTION (binding, verbatim): "two window-local lemmata (over the canonical family) + the elementwise architecture + cited classics (density, v912 continuity, the Weil criterion) => RH; open links: the arch/pole transcription (classical), the compression bridge, the source completion (definitional)".  (5) THE R327 FOLD-GROUP MASS CAP (group_mass_cap_probe.py 34/34, SPEC 11e4fd401ff77583 final / freeze 71f8b7b423a3f847): CAP_PARTIAL with anatomy letter SOURCE -- the r324 single heavy scale IS a single fold group at the two sharpest spikes, and the STRUCTURAL FINDING: on ALL 65 rungs the heaviest group of the argmax block is EXACTLY ONE beta/omega fold pair (one bulk + one window atom at one position, window-atom histogram [0, 65, 0]) with median alignment 1.000 (the two ancestors REINFORCE); kz53: the single pair carries 88.8 percent of the argmax block's atom mass at gap 0.076 (the second group 13x lighter) -- the spike is literally ONE bulk/window coincidence (kz67 the exception shape: 6 groups, bshare 0.416); position thirds [21, 29, 15] mid-heavy (the r322 mid/tail echo); the Lambda-pair cap REFUTED as a mid-ladder polylog (C_LV 1.1838 FAILS 19/39, named 0/4 -- the exact algebra hga <= 2 vmaxb holds at slack 0.0, the CONSTANT does not close), the direct group cap fails at A = 1 (18/39) and A = 2 (8/39, minimal A None), THE GROUP COUNT CERTIFIES pointwise (C_NG 2.6351, 0/39, named 4/4 -- the THIRD certified O(log m) count of the lane after C_NSC); exponents e(hgn/log m) = -0.200 FALLING, e_route = +0.106 < 0.224 but halves +0.411/-1.183 STRADDLE -- UNDECIDED by the sealed stability rule, HEAVY_GROUP_UNBOUNDED does NOT fire (the heavy-group coordinate DECAYS with depth: a shallow/mid phenomenon, not growth); Q3: no recomposition -- the r324 MEASURED chain (m_0* = 10^59.6) stays the honest end state of the route; THE TYPED DIRECTION: the spike cap, if it exists, is a statement about WHERE the single heavy beta/omega coincidence can SIT (the source geometry of the bulk/window pairing at one position), not about group count (certified) or multiplicity (proven).  THE MODULE-OWN EXACT SECTION S0 (pure Fractions and integer certificates, no probe imports, NO Lean call): (T1) the r324 interpolation M_3 <= q_max M_2 and M_2 <= q_max exact on rational witnesses (spread toy slack exactly 1/36, DOUBLE equality at the flat profile, equality at full concentration; both tightened-mutant directions CAUGHT); (T2) the F_A identity F_A x B x log m == m x q_max as exact algebra on a rational toy (B = medloc x m/log m: the identity is constructional, PhiH1 == (m q_max/log m)^2, the S0 interpolation improves the r321 upper side by exactly M_2/q_max <= 1; the dropped-gauge mutant F_A x B' x log m with B' = medloc x m breaks whenever log m != 1 -- CAUGHT); (T3) the r327 two-ancestor bound and group ledger exact on the sealed toy (block j*: group A = atoms (3, 2) at one position, group B = atom (1); second block atom (1): partition 5 + 1 == A1 = 6, chain m q_max = 12/7 <= ng x hgn = 20/7 slack 8/7, two-ancestor 5 <= 2 x 3 slack 1, the cancelling group (3, -2) has G1 = 1 vs gabs = 5 align 1/5 -- all EXACT; the drop-group mutant breaks the L1 recomposition by EXACTLY 1 LOUD, the wrong-window-max mutant bound 2 x 2 = 4 < hga = 5 breaks the ward by EXACTLY 1 CAUGHT); (T4) the r325 onset formula alpha* = (n_g + 1) D_0 / 2 as an EXACT TOY STABILIZATION (a rational grid element n_g = 4, D_0 = 1/4, x = (1, 2, -1, 1): the exact even piecewise-linear autocorrelation interpolant, rational atoms on and off the grid, the tent-window read with M = 2 alpha/D_0 lags -- the read EQUALS the exact atom sum 35/16 for every alpha >= alpha* = 5/8, DIFFERS below (15/8 at alpha = 1/2), and is CONSTANT under dyadic mesh refinement D_0 -> D_0/2 -> D_0/4 at fixed alpha >= alpha*; the nearest-neighbour mutant read misplaces the off-grid atom mass and breaks the identity -- CAUGHT); (T5) the m_0* composition arithmetic (the r324 log-space solver rule rebuilt verbatim: the smallest m with m^{CRIT - e} >= C log m on the multiplicative grid t *= 1.02 from ln 73 -- at the record parameters C = 8.941, e = +0.172 it lands 10^59.6; the exact exponent algebra 158/1000 + 14/1000 = 172/1000 < 224/1000 and 1 - e/2 = 914/1000 >= 888/1000 in pure Fractions; tipping mutants: e = CRIT and e supercritical return NONE, and the DISCLOSED pre-freeze calibration bug -- the linear-space search capped at 10^18 -- MISSES the root, rebuilt and CAUGHT; plus the r328B chain-audit gate S0-T5d: the block-level need 454/501 and the chain bar 94/501 exact, the verdict survival 172/1000 < 94/501 with margin 1957/125250, the non-sequitur 888/1000 x 1002/1000 < 908/1000 exact, the full-form margin 457/500 - 454/501 = 1957/250500, the chain-honest m_0* = 10^238 from the same solver, and the false-fire window mutant e = 1/5 -- SUBCRITICAL under the sealed bar, NOT under the chain bar, CAUGHT); (V1-V6) the SEALED VERDICT BARS as exact decision logic on the frozen record aggregates with tipping mutants at every live clause boundary: the r324-pre trees fa_tree/share_tree/compose_tree (record letters FA_BOUNDED_DISTRIBUTIONAL + QMAX_SHARE_OPEN + NOT_COMPOSED; mutants: outlier spikes fire FA_OUTLIERS_REAL, a certifying share fires QMAX_SHARE_PINNED and composes PROVENANCE_COMPOSED), the r324 six-letter origin tree (mutants: a leak fires TARGET_LEAK, a broken decomposition FA_RESTATEMENT, full certification QMAX_MULTISCALE_GO, straddling halves M2_GO_QMAX_OPEN, a supercritical exponent PILEUP_SUPERCRITICAL), the r325 five-letter primary tree with independent co-letters (mutants: each gate failure cascades in the sealed order down to NO_EXTRACTION_ARCHITECTURE), the r326 Lean bookkeeping bar (census 5 -> 8 == 5 + 3 named typed statements, the three proved kernel pieces, the five legacy sorrys byte-identical, lake green with exactly 8 intentional warnings, run_rh 75/75 -- any mismatch VOIDS the Lean claim), the r327 six-letter cap tree with the SOURCE/AGGREGATION anatomy rule (med named ratio 1.057 >= 0.5; mutants: a certifying lambda-pair cap fires LAMBDA_PAIR_CAP_GO and would recompose m_0*, agreeing supercritical halves fire HEAVY_GROUP_UNBOUNDED, a ledger break RECOMP_BREAK), and the r323 abort bar (clean iff zero writes and the post-abort suite pins hold); (V7) the WAVE-13 COMPOSITION gate: the five items compose to exactly the claim split -- PRIME.EXTRACTION.ELEMENTWISE.01 [E] (R325 GO + R326 implementation: the honest new-connection formulation verbatim), PRIME.L2.RENYI3.MEASURED_COMPOSITION.01 [O] (the r324 measured chain with the certified counts C_NSC/C_NG, the r327 SOURCE anatomy, the coincidence-geometry direction and the r328B chain note carried in the banked letter: block-level need 454/501, chain bar 0.188, m_0* chain-honest 10^238), the SLIDING_BOUND/PROVENANCE updates (F_A de-black-boxed, r324-pre banked) -- tipping mutants: a failing R325 gate voids the extraction claim, a supercritical exponent voids the composition claim, a Lean census mismatch voids the implementation leg -- each tip changes the composition, the split is not hard-wired.  FOUR probes embedded BYTE-EXACT (36/36 + 36/36 + 18/18 + 34/34 smoke == the sealed stage; full records 36/36 + 36/36 + 18/18 + 34/34 sealed experiments-side, re-verified by rh/verification/run_rh.py), executed verbatim in round order so that r324 imports the embedded r324-pre and r327 the embedded r324-pre AND r324 (sys.modules convention; all four also import the older frozen probe chains r244-r321 from the experiments tree, sealed by the v960..v969 byte wards and run_rh.py; r325 imports the READ-ONLY deployed verification cores v563/v716/v718/v696 by path).  WHAT THE MODULE DOES NOT SAY (honest boundary): NO inequality is promoted -- the measured composition certifies the MEASURED rungs (m <= 274) plus an explicitly typed extrapolation hypothesis and nothing beyond; the elementwise architecture is an ARCHITECTURE result -- the two true window-local Lean holes (lstar_subordination, terminal_positive_main) are UNCHANGED, the three new sorrys are typed OPEN statements (classical transcription + definitional completion), the compression bridge carries no truth commitment; the window-local positivity premise is proved NOWHERE; L* stays paused and open.  Mincut base 4 / refined 5 UNCHANGED (an architecture-plus-measurement 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 fa_provenance_probe.py (36/36 full ==
smoke, SPEC_SHA 9a6696f875718322, r324-pre -- sealed FIRST, then
superseded mid-round by the binding reviewer course correction and
BANKED; pre-run placeholder removal disclosed, record-table
insertion only), qmax_m2_origin_probe.py (36/36 full == smoke,
SPEC_SHA dc36cacbebdaf53b, r324 -- the round's binding contract;
one pre-freeze calibration-pass fix disclosed: the m_0* solver
moved from linear to log space, rule unchanged),
extraction_order_probe.py (18/18 full == smoke, SPEC_SHA
31277f917dd04a7e final / freeze 57e50d366a62f2a6, r325 -- pre-run
placeholder removal + three pre-freeze smoke-harness fixes
disclosed, record-table insertion only), group_mass_cap_probe.py
(34/34 full == smoke, SPEC_SHA 11e4fd401ff77583 final / freeze
71f8b7b423a3f847, r327 -- smoke + calibration pass with NO
amendment, record-table insertion only); rounds 324-pre/324/325/
327, notes DCLXX/DCLXIX/DCLXXII, 2026-08-27.  WAVE-4 EMBEDDING
CONVENTION (as in v960..v969): frozen sources embedded BYTE-EXACT
and executed verbatim in isolated namespaces in their sealed
--smoke stage (deterministic; smoke wall times 0.7/0.4/0.2/0.4 s);
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 34.2/~35/0.4/
36.4 s) are sealed experiments-side and re-verified by
rh/verification/run_rh.py.  The probes consume the READ-ONLY
deployed cores v563_paper2_readouts.py (all four) and v716/v718/
v696 (r325 only) 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: r324 imports
the embedded r324-pre; r327 imports the embedded r324-pre and
r324); all four import the older frozen probe libraries from the
experiments tree (sealed by the v960..v969 byte wards and
run_rh.py).  The Lean round r326 (notes DCLXXI --
rh/lean/RH/Elementwise.lean, census 5 -> 8, already merged and
green) is consumed as a REPORT -- its artifacts live in rh/lean/
and are re-verified by lake build + run_rh.py, NOT by this module;
its bookkeeping pins are gated in S0.  The r323 abort (notes
DCLXVII -- no probe, no write access, nothing counts as a round)
is consumed as a NOTE and gated as an abort-cleanliness pin.  No
round is in flight at this promotion cut.

FIREWALL: no zeros, no prime-table oracles (AST scans inside the
probes); RNG only in declared synthetic-build seeds (sealed,
collision-free, gated); ground truth (branch labels, survival
records) enters gates only; NO promotion of any inequality (the
measured composition is registered as a MEASURED chain [O] with a
typed extrapolation hypothesis, the elementwise repair as an
architecture [E] whose positivity premise is proved nowhere); NO
RH claim.  Python-only per GATE.WOLFRAM.02.
"""

import contextlib
import io
import math
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 and
# ---------------- integer certificates; the r324 interpolation and
# ---------------- F_A identity, the r327 group ledger, the r325
# ---------------- onset toy, the m_0* solver logic and the sealed
# ---------------- verdict bars are re-derived from scratch at
# ---------------- module level -- no probe imports, NO Lean call)
def _moments(q):
    """normalized rational profile moments: returns (qmax, M2, M3)
    for a nonnegative rational vector q with sum q == 1."""
    q = [_Fr(v) for v in q]
    assert sum(q) == 1 and all(v >= 0 for v in q)
    return max(q), sum(v * v for v in q), sum(v ** 3 for v in q)


def _interp_ok(q, wrong="none"):
    """the r324 S0 interpolation on a normalized rational profile:
    M_3 <= qmax x M_2 and M_2 <= qmax (pure algebra: q_j^3 <= qmax
    q_j^2 and q_j^2 <= qmax q_j termwise).  wrong='rev3' asserts
    qmax x M_2 <= M_3, wrong='rev2' asserts qmax <= M_2 -- both
    must FAIL on spread witnesses."""
    qmax, m2, m3 = _moments(q)
    if wrong == "rev3":
        return qmax * m2 <= m3
    if wrong == "rev2":
        return qmax <= m2
    return m3 <= qmax * m2 and m2 <= qmax


def _fa_identity(m, ell, qmax, medloc, wrong="none"):
    """the r324 S0 identity F_A x B x log m == m x q_max on a
    rational toy with the rational log stand-in ell: F_A = qmax /
    medloc (rank-local normalization), B = medloc x m / ell (the
    r321 source-pure baseline) -- the identity is constructional;
    PhiH1 = (F_A B)^2 == (m qmax / ell)^2.  wrong='gauge' uses the
    dropped-gauge B' = medloc x m (no /ell): must FAIL whenever
    ell != 1."""
    m, ell, qmax, medloc = _Fr(m), _Fr(ell), _Fr(qmax), _Fr(medloc)
    fa = qmax / medloc
    b = medloc * m if wrong == "gauge" else medloc * m / ell
    ident = (fa * b * ell == m * qmax)
    phih1 = (fa * (medloc * m / ell)) ** 2 == (m * qmax / ell) ** 2
    return ident and phih1


def _interp_improves(q, m, ell):
    """the S0 improvement of the r321 bracket upper side on a
    rational toy: rho_2 = m^2 M_3 / ell^2 <= PhiH1 x (M_2/qmax)
    <= PhiH1 with M_2/qmax <= 1 -- all exact."""
    qmax, m2, m3 = _moments(q)
    m, ell = _Fr(m), _Fr(ell)
    rho2 = m * m * m3 / (ell * ell)
    phih1 = (m * qmax / ell) ** 2
    return (rho2 <= phih1 * (m2 / qmax) <= phih1
            and m2 / qmax <= 1)


# --------- the r327 group ledger on the sealed rational toy
# --------- (block j*: group A = atoms (3, 2) at one position,
# --------- group B = atom (1); block 1: atom (1))
def _group_ledger(groups_by_block):
    """per-block group ledger: for each block a tuple of groups,
    each group a tuple of rational atom values.  Returns
    (x_blocks, L, partition_ok, l1_ok) where x_j = sum of group
    sums G1_g, gabs_g = sum of |atoms|, partition sum_g gabs ==
    A1_j and the L1 recomposition sum_j |sum_g G1_g| == L."""
    xs, part_ok = [], True
    for groups in groups_by_block:
        g1s = [sum(_Fr(a) for a in g) for g in groups]
        gabs = [sum(abs(_Fr(a)) for a in g) for g in groups]
        a1 = sum(abs(_Fr(a)) for g in groups for a in g)
        part_ok = part_ok and (sum(gabs) == a1)
        xs.append(sum(g1s))
    L = sum(abs(x) for x in xs)
    l1_ok = (sum(abs(x) for x in xs) == L)
    return xs, L, part_ok, l1_ok


def _two_ancestor_ok(group, vmax, mult_cap=2):
    """the r327 two-ancestor bound gabs_g <= mult_cap x vmax,
    exact."""
    gabs = sum(abs(_Fr(a)) for a in group)
    return gabs <= mult_cap * _Fr(vmax)


def _mutant_group_drop(g1s):
    """the r327 e1 mutant: an L1 'recomposition' that drops the
    last group -- must break by exactly the dropped |G1|."""
    g1s = [_Fr(v) for v in g1s]
    return sum(g1s[:-1])


def _mutant_wrong_window_max(atoms):
    """the r327 e2 mutant: the 'window maximum' on the truncated
    atom set (global max dropped)."""
    av = sorted(abs(_Fr(a)) for a in atoms)
    return av[-2]


# --------- the r325 onset toy (exact rational tent-window reads):
# --------- grid element n_g = 4, D_0 = 1/4, x = (1, 2, -1, 1);
# --------- autocorrelation a_d = D_0 sum_i x_i x_{i+d} (a_d = 0
# --------- for d >= n_g -- the closing zero knot); F = the even
# --------- piecewise-linear interpolant with knots d x D_0;
# --------- rational atoms (position, mass) on and off the grid.
_TOY_NG = 4
_TOY_D0 = _Fr(1, 4)
_TOY_X = (_Fr(1), _Fr(2), _Fr(-1), _Fr(1))
_TOY_ATOMS = ((_Fr(1, 8), _Fr(2)), (_Fr(7, 16), _Fr(3)),
              (_Fr(15, 16), _Fr(5)), (_Fr(9, 8), _Fr(1)))


def _toy_acf(d):
    if d >= _TOY_NG:
        return _Fr(0)
    return _TOY_D0 * sum(_TOY_X[i] * _TOY_X[i + d]
                         for i in range(_TOY_NG - d))


def _toy_F(u):
    """the exact even piecewise-linear interpolant at rational u
    (knots d x D_0; zero beyond the support n_g x D_0)."""
    u = abs(_Fr(u))
    t = u / _TOY_D0
    d = int(t)          # exact floor for nonnegative rationals
    frac = t - d
    return _toy_acf(d) + frac * (_toy_acf(d + 1) - _toy_acf(d))


def _toy_atom_sum():
    """the exact reference: -L_cat(F) convention dropped (sign
    irrelevant for the stabilization statement) -- the plain atom
    sum sum_n mu_n F(u_n), exact."""
    return sum(mu * _toy_F(u) for u, mu in _TOY_ATOMS)


def _toy_read(alpha, D, nearest=False):
    """the tent-window read at anchor alpha on the dyadic mesh D
    (native D_0 or a refinement): the window carries M = 2 alpha/D
    lags (lags 0..M-1); an atom at u in mesh cell d = floor(u/D)
    contributes its interpolated mass ONLY if both tent lags d and
    d + 1 are inside the window (d + 1 <= M - 1) -- the T115 tent
    assembly modeled exactly.  nearest=True is the r325 m2-class
    mutant: the atom mass is misplaced onto the nearest grid knot
    (nearest-neighbour read instead of the linear-interpolation
    read)."""
    alpha, D = _Fr(alpha), _Fr(D)
    M = int(2 * alpha / D)          # exact for dyadic D, rational alpha
    total = _Fr(0)
    for u, mu in _TOY_ATOMS:
        t = u / D
        d = int(t)
        if d + 1 > M - 1:
            continue
        if nearest:
            knot = d if (t - d) <= _Fr(1, 2) else d + 1
            total += mu * _toy_F(knot * D)
        else:
            total += mu * _toy_F(u)
    return total


# --------- the m_0* solver (the r324 S3 rule rebuilt verbatim:
# --------- log-space multiplicative grid) and its mutants
_CRIT = 0.224


def _m0_log10(C, e, crit=_CRIT):
    """the r324 log-space solve of m^{crit - e} >= C log m: t =
    ln m on the multiplicative grid t *= 1.02 from ln 73; a finite
    root exists iff crit - e > 0.  Returns log10(m_0*) or None.
    crit defaults to the sealed r324 bar 0.224 (atom-level need
    0.888); the audit-B chain-honest bar 2 x (1 - 908/1002) is
    passed explicitly in S0-T5d."""
    if crit - e <= 0.0:
        return None
    t = math.log(73.0)
    while t < 1e7:
        if t * (crit - e) >= math.log(C) + math.log(t):
            return t / math.log(10.0)
        t *= 1.02
    return None


def _m0_linear_mutant(C, e):
    """the DISCLOSED r324 pre-freeze calibration bug rebuilt: the
    linear-space search capped at 10^18 -- misses the astronomical
    root (returns None at the record parameters)."""
    if _CRIT - e <= 0.0:
        return None
    m = 73.0
    while m < 1e18:
        if m ** (_CRIT - e) >= C * math.log(m):
            return math.log10(m)
        m *= 2.0
    return None


# --------- frozen record aggregates (rounds 323/324-pre/324/325/
# --------- 326/327; exact decimal pins as Fractions where the
# --------- printed record is exact; ground truth sealed
# --------- probe-side / rh-side, re-verified by the embedded
# --------- pattern gates below and by run_rh.py)
_REC = dict(
    # r323 clean abort (note DCLXVII): no probe, no write access
    r323=dict(probes_created=0, files_written=0, inventory_rows=0,
              post_abort_suite=(73, 73), post_abort_pins=(103, 103)),
    # r324-pre fa_provenance_probe (36/36, BANKED)
    r324pre=dict(ks_fa=_Fr(982, 10 ** 4), ks_bar=_Fr(125, 10 ** 3),
                 p_max=_Fr(18, 200), p_min=_Fr(5, 100),
                 c_f=_Fr(3357, 1000), q95=_Fr(2583, 1000),
                 p_named=(_Fr(5, 1000), _Fr(0), _Fr(0)),
                 c_m2=_Fr(22557, 10 ** 4),
                 m2_viol=(53, 67, 83, 76, 61, 28, 109),
                 ks_thirds=(_Fr(230, 10 ** 4), _Fr(158, 10 ** 4),
                            _Fr(247, 10 ** 4)),
                 m2_inf=_Fr(2081, 1000), sigma_trend=_Fr(-584, 1000),
                 composed_viol=0, composed_named=4,
                 rsv=(_Fr(123, 100), _Fr(181, 100)),
                 fab_cal=_Fr(35261, 10 ** 4),
                 fab_test=_Fr(43380, 10 ** 4), fab_viol=4,
                 spikes_within=True, dist_ok=True, struct_ok=False,
                 stationary=True, cert_ok=False, named_ok=True),
    # r324 qmax_m2_origin_probe (36/36)
    r324=dict(c_nsc=_Fr(20258, 10 ** 4), nsc_viol=0,
              c_pil=_Fr(93583, 10 ** 4), pil_viol=11,
              c_inf=_Fr(17481, 10 ** 4), inf_viol=5,
              c_2=_Fr(22557, 10 ** 4), c2_viol=7,
              c_2small=_Fr(26130, 10 ** 4),
              e_g=_Fr(158, 1000), e_m2=_Fr(14, 1000),
              e_tot=_Fr(172, 1000), crit=_Fr(224, 1000),
              halves=(_Fr(141, 1000), _Fr(-160, 1000)),
              heavy=dict(kz53=(_Fr(13778, 1000), _Fr(13020, 1000), 5),
                         kz83=(_Fr(12707, 1000), _Fr(14150, 1000), 6),
                         kz67=(_Fr(22378, 1000), _Fr(13610, 1000), 7)),
              nsc_med=5, c_use=8.941, m0_l10=59.6, m_max=274,
              n2_need=_Fr(888, 1000), n3_exp=_Fr(914, 1000),
              leak=False, restate=False, go_all=False, decided=True,
              sub=True),
    # r325 extraction_order_probe (18/18)
    r325=dict(gate_a=True, gate_b=True, gate_c=True, floor=True,
              sign_subtype="SIGN",
              onset_below=(_Fr(265, 10 ** 4), _Fr(534, 10 ** 4),
                           _Fr(176, 10 ** 4)),
              mesh_const=("3.3e-18", "1.5e-15", "2.0e-17"),
              floor_vals=("+1.77e-04", "+1.59e-04"),
              mustfails=4),
    # r326 Lean round (report; artifacts merged and green rh/lean/)
    r326=dict(census_before=5, census_after=8, new_typed=3,
              new_names=("arch_elementwise_stabilization",
                         "pole_elementwise_stabilization",
                         "specFamily_sourceExact_completion"),
              proved_names=("sourceExact_buildPrimeWindow",
                            "comb_elementwise_stabilization",
                            "weil_nonneg_of_windowlocal"),
              legacy_identical=True, lake_green=True,
              lake_sorry_warnings=8, run_rh=(75, 75)),
    # r327 group_mass_cap_probe (34/34)
    r327=dict(ratio_named=(_Fr(1081, 1000), _Fr(1057, 1000),
                           _Fr(460, 1000)), ratio_bar=_Fr(1, 2),
              hist=(0, 65, 0), align_med=_Fr(1),
              kz53_bshare=_Fr(888, 1000), kz53_gap=_Fr(76, 1000),
              kz67_groups=6, kz67_bshare=_Fr(416, 1000),
              thirds=(21, 29, 15),
              c_lv=_Fr(11838, 10 ** 4), lv_viol=19, lv_named=0,
              hg_viol_a1=18, hg_viol_a2=8, min_a=None,
              c_ng=_Fr(26351, 10 ** 4), ng_viol=0, ng_named=4,
              e_hg=_Fr(-200, 1000), e_lv=_Fr(-261, 1000),
              e_ng=_Fr(293, 1000), e_m2=_Fr(14, 1000),
              e_route=_Fr(106, 1000),
              route_halves=(_Fr(411, 1000), _Fr(-1183, 1000)),
              envelope=_Fr(2616, 1000),
              leak=False, brk=False, lam_go=False, bal_go=False),
)


# --------- the sealed verdict bars as exact decision logic
def _fa_tree(spikes_within, dist_ok, struct_ok):
    """the r324-pre sealed F_A tree (rebuilt verbatim)."""
    if not spikes_within:
        return "FA_OUTLIERS_REAL"
    if dist_ok:
        return "FA_BOUNDED_DISTRIBUTIONAL"
    if struct_ok:
        return "FA_BOUNDED_STRUCTURAL"
    return "FA_OPEN"


def _share_tree(stationary, cert_ok, named_ok):
    """the r324-pre sealed share tree (rebuilt verbatim)."""
    if stationary and cert_ok and named_ok:
        return "QMAX_SHARE_PINNED"
    return "QMAX_SHARE_OPEN"


def _compose_tree(fa_v, sh_v):
    """the r324-pre sealed composition rule (rebuilt verbatim)."""
    if fa_v in ("FA_BOUNDED_DISTRIBUTIONAL",
                "FA_BOUNDED_STRUCTURAL") \
            and sh_v == "QMAX_SHARE_PINNED":
        return "PROVENANCE_COMPOSED"
    return "NOT_COMPOSED"


def _origin_tree(leak, restate, go_all, decided, sub):
    """the r324 sealed six-letter tree (rebuilt verbatim; total,
    exactly one fires)."""
    if leak:
        return "TARGET_LEAK"
    if restate:
        return "FA_RESTATEMENT"
    if go_all:
        return "QMAX_MULTISCALE_GO"
    if not decided:
        return "M2_GO_QMAX_OPEN"
    if sub:
        return "PILEUP_GROWS_SUBCRITICAL"
    return "PILEUP_SUPERCRITICAL"


def _r325_tree(gate_a, gate_b, gate_c, floor):
    """the r325 sealed primary tree (rebuilt verbatim; co-letters
    are recorded independently by the probe)."""
    if gate_a:
        return "ELEMENTWISE_STABILIZATION_GO"
    if gate_b:
        return "CANONICAL_MESH_REBUILD_GO"
    if gate_c:
        return "SIGNED_DEFECT_CORRECTION_GO"
    if floor:
        return "ANCHOR_ONLY_INSUFFICIENT"
    return "NO_EXTRACTION_ARCHITECTURE"


def _bar_r326(r, census_break=False, legacy_touched=False,
              lake_red=False):
    """the r326 Lean bookkeeping bar: census 5 -> 8 must equal
    5 + the three named typed statements, the three kernel pieces
    proved, the five legacy sorrys byte-identical, lake green with
    exactly 8 intentional warnings, run_rh 75/75 -- any mismatch
    VOIDS the Lean claim."""
    after = r["census_after"] + (1 if census_break else 0)
    ok = (after == r["census_before"] + r["new_typed"]
          and len(r["new_names"]) == r["new_typed"]
          and len(r["proved_names"]) == 3
          and r["legacy_identical"] and not legacy_touched
          and r["lake_green"] and not lake_red
          and r["lake_sorry_warnings"] == r["census_after"]
          and r["run_rh"] == (75, 75))
    if not ok:
        return "LEAN_CLAIM_VOID(recompose)"
    return ("LEVEL_C_NAMED(sourceExact_buildPrimeWindow PROVED + "
            "comb stabilization elementwise PROVED + "
            "weil_nonneg_of_windowlocal PROVED -- extraction "
            "without the ladder; census 5 -> 8 with three typed "
            "Level-C statements: arch/pole transcription CLASSICAL "
            "+ source completion DEFINITIONAL; the wave-12 "
            "reservation partially discharged)")


def _cap_tree(leak, brk, lam_go, bal_go, unbounded):
    """the r327 sealed six-letter tree (rebuilt verbatim)."""
    if leak:
        return "TARGET_LEAK"
    if brk:
        return "RECOMP_BREAK"
    if lam_go:
        return "LAMBDA_PAIR_CAP_GO"
    if bal_go:
        return "BALANCE_CAP_GO"
    if unbounded:
        return "HEAVY_GROUP_UNBOUNDED"
    return "CAP_PARTIAL"


def _anatomy_letter(ratios, bar):
    """the r327 sealed SOURCE/AGGREGATION rule: SOURCE iff the
    median named ratio >= RATIO_BAR."""
    rs = sorted(ratios)
    med = rs[len(rs) // 2]
    return "SOURCE" if med >= bar else "AGGREGATION"


def _bar_r323(r, wrote=False):
    """the r323 abort bar: clean iff zero writes of any kind and
    the post-abort suite pins hold."""
    ok = (not wrote and r["probes_created"] == 0
          and r["files_written"] == 0 and r["inventory_rows"] == 0
          and r["post_abort_suite"] == (73, 73)
          and r["post_abort_pins"] == (103, 103))
    if not ok:
        return "ABORT_DIRTY(a write happened -- recompose)"
    return ("ABORT_CLEAN(design phase only, before any write "
            "access; nothing counts as a round; run_rh --fast "
            "73/73 with 103/103 pins after the abort)")


def _wave13(r325_fails=False, supercritical=False,
            census_break=False):
    """the wave-13 composition: the five items compose to EXACTLY
    the claim split -- (i) the elementwise extraction repair [E]
    (R325 GO + R326 implementation), (ii) the measured terminal
    composition [O] (r324 chain + r327 anatomy), (iii) the
    SLIDING_BOUND/PROVENANCE updates.  The tipping inputs change
    the composition."""
    if r325_fails:
        ext = "EXTRACTION_CLAIM_VOID(no architecture -- recompose)"
    else:
        ext = ("ELEMENTWISE_BANKED(R325 GO + R326 Lean "
               "implementation; H_cof replaced as the target route)")
    if supercritical:
        comp = "COMPOSITION_VOID(supercritical -- the chain breaks)"
    else:
        comp = ("MEASURED_COMPOSITION_BANKED(subcritical +0.172, "
                "m_0* = 10^59.6, gap typed; C_NSC + C_NG certified; "
                "SOURCE anatomy; coincidence-geometry direction; "
                "r328B chain note: block-level need 454/501, "
                "chain bar 0.188 -- the verdict survives 0.172 < "
                "0.188, m_0* chain-honest 10^238)")
    if census_break:
        lean = "LEAN_LEG_VOID(census mismatch)"
    else:
        lean = "LEVEL_C_NAMED(census 8, three typed statements)"
    claims = ("PRIME.EXTRACTION.ELEMENTWISE.01 [E]; "
              "PRIME.L2.RENYI3.MEASURED_COMPOSITION.01 [O]; "
              "PRIME.L2.RENYI3.SLIDING_BOUND.01 [O update]; "
              "PRIME.L2.RENYI3.PROVENANCE.01 [O update]"
              if not (r325_fails or supercritical or census_break)
              else "CLAIM_SPLIT_INVALID(recompose)")
    return "%s | %s | %s | %s" % (ext, comp, lean, claims)


def _extraction_and_composition(gates):
    """the module-own exact section S0: every check appends its
    boolean to gates and prints house-style."""

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

    def section(t):
        print("\n--- %s " % t + "-" * max(0, 60 - len(t)), flush=True)

    section("S0-T1 the r324 interpolation (exact)")
    q_spread = (_Fr(1, 6), _Fr(1, 3), _Fr(1, 2))
    qmax, m2, m3 = _moments(q_spread)
    check("S0-T1a-interpolation-exact",
          _interp_ok(q_spread) and m3 == _Fr(1, 6)
          and qmax * m2 == _Fr(7, 36)
          and qmax * m2 - m3 == _Fr(1, 36)
          and qmax - m2 == _Fr(1, 9),
          "M_3 <= qmax x M_2 and M_2 <= qmax EXACT on the spread "
          "toy (1/6, 1/3, 1/2): M_3 = 1/6 <= 7/36 with slack "
          "EXACTLY 1/36, M_2 = 7/18 <= 1/2 with slack 1/9 -- the "
          "r324 S0 stage rebuilt in pure Fractions")
    qf, m2f, m3f = _moments((_Fr(1, 2), _Fr(1, 2)))
    q1, m21, m31 = _moments((_Fr(1),))
    check("S0-T1b-equality-cases",
          m3f == qf * m2f == _Fr(1, 4) and m2f == qf
          and m31 == q1 * m21 == 1 and m21 == q1,
          "DOUBLE equality at the flat profile (1/2, 1/2): M_3 = "
          "qmax M_2 = 1/4 AND M_2 = qmax = 1/2 (the interpolation "
          "is sharp at flat); equality again at full concentration "
          "(1,) -- both ends of the bracket are attained exactly")
    check("S0-T1c-interpolation-mutants",
          (not _interp_ok(q_spread, wrong="rev3"))
          and (not _interp_ok(q_spread, wrong="rev2")),
          "the reversed-inequality mutants claim 7/36 <= 1/6 and "
          "1/2 <= 7/18 -- both FALSE exact on the spread toy: both "
          "clauses of the interpolation are live, CAUGHT")

    section("S0-T2 the F_A identity (exact)")
    check("S0-T2a-fa-identity",
          _fa_identity(8, 2, _Fr(1, 2), _Fr(1, 8))
          and _fa_identity(12, _Fr(5, 2), _Fr(2, 5), _Fr(1, 10)),
          "F_A x B x log m == m x q_max EXACT on rational toys "
          "(m = 8, ell = 2, qmax = 1/2, medloc = 1/8: F_A = 4, "
          "B = 1/2, both sides 4; and a second witness) with "
          "PhiH1 == (m qmax/ell)^2 -- F_A is the rank-local "
          "normalization of m q_max, no black correction factor "
          "(the r324 de-black-boxing as pure algebra)")
    check("S0-T2b-fa-gauge-mutant",
          not _fa_identity(8, 2, _Fr(1, 2), _Fr(1, 8), wrong="gauge"),
          "the dropped-gauge mutant B' = medloc x m (no /log m) "
          "claims 8 == 4 -- FALSE exact whenever log m != 1: the "
          "gauge clause of the identity is live, CAUGHT")
    check("S0-T2c-bracket-improvement",
          _interp_improves(q_spread, 8, 2)
          and _interp_improves((_Fr(1, 2), _Fr(1, 2)), 6, _Fr(3, 2)),
          "the S0 interpolation improves the r321 bracket upper "
          "side by exactly M_2/qmax <= 1: rho_2 <= PhiH1 x "
          "(M_2/qmax) <= PhiH1 EXACT on the spread toy (7/9 < 1) "
          "and tight at the flat profile (M_2/qmax = 1)")

    section("S0-T3 the r327 group ledger (exact)")
    toy_blocks = (((_Fr(3), _Fr(2)), (_Fr(1),)), ((_Fr(1),),))
    xs, L, part_ok, l1_ok = _group_ledger(toy_blocks)
    m_toy = len(xs)
    mqmax = m_toy * max(abs(x) for x in xs) / L
    hga = _Fr(5)
    hgn = m_toy * hga / L
    ng = 2
    check("S0-T3a-group-ledger",
          xs == [_Fr(6), _Fr(1)] and L == 7 and part_ok and l1_ok
          and mqmax == _Fr(12, 7) and hgn == _Fr(10, 7)
          and mqmax <= ng * hgn
          and ng * hgn - mqmax == _Fr(8, 7),
          "the sealed r327 toy (block j*: group A = atoms (3, 2) "
          "at one position, group B = atom (1); block 1: atom "
          "(1)): x = (6, 1), L = 7, partition 5 + 1 == A1 = 6 "
          "EXACT, L1 recomposition EXACT, cap chain m qmax = 12/7 "
          "<= ng x hgn = 20/7 with slack EXACTLY 8/7")
    check("S0-T3b-two-ancestor",
          _two_ancestor_ok((_Fr(3), _Fr(2)), 3)
          and 2 * _Fr(3) - hga == 1
          and sum(_Fr(v) for v in (3, -2)) == 1
          and sum(abs(_Fr(v)) for v in (3, -2)) == 5
          and _Fr(1) / _Fr(5) == _Fr(1, 5),
          "the two-ancestor bound gabs = 5 <= MULT_CAP x vmax = "
          "2 x 3 with slack EXACTLY 1 (the proven fold "
          "multiplicity <= 2 as a mass statement); the cancelling "
          "group (3, -2) has G1 = 1 vs gabs = 5, alignment 1/5 "
          "EXACT -- alignment and mass are distinct exact "
          "coordinates")
    check("S0-T3c-group-mutants",
          _mutant_group_drop((_Fr(5), _Fr(1))) == 5
          and _Fr(6) - _mutant_group_drop((_Fr(5), _Fr(1))) == 1
          and _mutant_wrong_window_max((3, 2, 1)) == 2
          and hga - 2 * _mutant_wrong_window_max((3, 2, 1)) == 1,
          "the drop-group mutant returns 5 != 6 (the L1 "
          "recomposition breaks by EXACTLY the dropped |G1| = 1 "
          "-- LOUD); the wrong-window-max mutant bound 2 x 2 = 4 "
          "< hga = 5 breaks the two-ancestor ward by EXACTLY 1 -- "
          "CAUGHT")

    section("S0-T4 the r325 onset formula (exact toy stabilization)")
    ref = _toy_atom_sum()
    astar = _Fr(_TOY_NG + 1) * _TOY_D0 / 2
    above = [_toy_read(a, _TOY_D0)
             for a in (astar, _Fr(3, 4), _Fr(1), _Fr(2))]
    below = [_toy_read(a, _TOY_D0)
             for a in (_Fr(3, 8), _Fr(1, 2), _Fr(9, 16))]
    check("S0-T4a-onset-exact",
          ref == _Fr(35, 16) and astar == _Fr(5, 8)
          and all(v == ref for v in above)
          and all(v != ref for v in below),
          "the toy grid element (n_g = 4, D_0 = 1/4, x = (1, 2, "
          "-1, 1)): exact atom sum 35/16; the tent-window read "
          "EQUALS it for EVERY alpha >= alpha* = (n_g + 1) D_0/2 "
          "= 5/8 and DIFFERS below (15/8 at alpha = 1/2) -- the "
          "r325 onset formula as an EXACT finite stabilization, "
          "not a limit")
    refined = [_toy_read(_Fr(5, 8), _TOY_D0 / 2 ** k)
               for k in (0, 1, 2)]
    check("S0-T4b-mesh-constancy",
          all(v == ref for v in refined),
          "at fixed alpha = alpha* the read is CONSTANT under "
          "dyadic mesh refinement D_0 -> D_0/2 -> D_0/4 (all "
          "EXACTLY 35/16): the native mesh already carries the "
          "limit value -- no hidden mesh limit, the r325 "
          "mesh-constancy leg in pure Fractions")
    check("S0-T4c-nearest-mutant",
          _toy_read(_Fr(5, 8), _TOY_D0, nearest=True) != ref,
          "the nearest-neighbour mutant read (atom mass misplaced "
          "onto the nearest grid knot instead of the linear-"
          "interpolation read) breaks the identity on the off-grid "
          "atoms -- the r325 must-fail m2 class, CAUGHT exactly")

    section("S0-T5 the m_0* composition arithmetic")
    r4 = _REC["r324"]
    check("S0-T5a-exponent-algebra",
          r4["e_g"] + r4["e_m2"] == r4["e_tot"]
          and r4["e_tot"] < r4["crit"]
          and 1 - r4["e_tot"] / 2 == r4["n3_exp"]
          and r4["n3_exp"] >= r4["n2_need"]
          and all(h < r4["crit"] for h in r4["halves"])
          and r4["halves"][1] < 0,
          "the exact exponent algebra in pure Fractions: e_tot = "
          "158/1000 + 14/1000 = 172/1000 < CRIT 224/1000; N_3 "
          "exponent 1 - e/2 = 914/1000 >= the needed 888/1000; "
          "both stability halves subcritical, the second FALLING "
          "(-160/1000) -- DECIDED by the sealed rule")
    l10 = _m0_log10(r4["c_use"], float(r4["e_tot"]))
    check("S0-T5b-m0-solver",
          l10 is not None and abs(l10 - r4["m0_l10"]) <= 0.05,
          "the r324 log-space solver rule rebuilt verbatim "
          "(multiplicative grid t *= 1.02 from ln 73): at the "
          "record parameters C = 8.941, e = +0.172 it lands "
          "log10(m_0*) = %.2f == the record 10^59.6 -- the "
          "smallest m with m^{0.052} >= 8.941 log m is "
          "astronomical, the gap (274, m_0*) is the disclosed "
          "extrapolation hypothesis" % l10)
    check("S0-T5c-m0-mutants",
          _m0_log10(r4["c_use"], float(r4["crit"])) is None
          and _m0_log10(r4["c_use"], 0.30) is None
          and _m0_linear_mutant(r4["c_use"],
                                float(r4["e_tot"])) is None,
          "tipping mutants: e = CRIT (gap 0) and e = +0.30 "
          "(supercritical) return NONE -- no finite m_0* exists; "
          "the DISCLOSED pre-freeze calibration bug (linear-space "
          "search capped at 10^18) rebuilt: it MISSES the "
          "10^59.6 root and returns NONE -- the log-space fix was "
          "load-bearing, CAUGHT")
    # --- the AUDIT-B chain correction (r328B, independent chain
    # --- audit, 2026-08-27): the r324 record bar CRIT = 0.224 was
    # --- derived from the ATOM-level need 0.888 (R302_ATOM_NEED
    # --- for n_eff_atom); the composition functional N_2 = n_eff
    # --- is BLOCK-level -- its need is 0.908 in N units, i.e.
    # --- 908/1002 = 454/501 in m units via sl_nact = +1.002.  The
    # --- sealed r324 record is NOT edited (it stays as run); this
    # --- gate carries the correction as a chain annotation.
    need_m = _Fr(908, 1000) / _Fr(1002, 1000)
    crit_chain = 2 * (1 - need_m)
    l10c = _m0_log10(r4["c_use"], float(r4["e_tot"]),
                     crit=float(crit_chain))
    check("S0-T5d-chain-audit-correction",
          need_m == _Fr(454, 501)
          and crit_chain == _Fr(94, 501)
          and r4["e_tot"] < crit_chain
          and crit_chain - r4["e_tot"] == _Fr(1957, 125250)
          and _Fr(888, 1000) * _Fr(1002, 1000) < _Fr(908, 1000)
          and r4["n3_exp"] >= need_m
          and r4["n3_exp"] - need_m == _Fr(1957, 250500)
          and l10c is not None and abs(l10c - 238.3) <= 1.0
          and _Fr(1, 5) < r4["crit"]
          and _Fr(1, 5) > crit_chain,
          "the r328B chain-honest bar in exact Fractions: the "
          "block-level need is 908/1002 = 454/501 in m units "
          "(the r324 record used the ATOM-level need 888/1000), "
          "hence CRIT_chain = 2 x (1 - 454/501) = 94/501 ~ 0.188 "
          "< the sealed 0.224; THE VERDICT SURVIVES: e_tot = "
          "172/1000 < 94/501 EXACT (margin 1957/125250 ~ 0.016); "
          "the printed pressure step 'N_2 >= m^0.888 => "
          "slope(n_eff) >= +0.908' is a NON-SEQUITUR as written "
          "(888/1000 x 1002/1000 = 0.889776 < 908/1000 EXACT) -- "
          "the inference carries only via the full polylog form "
          "1 - e/2 = 914/1000 >= 454/501 (margin 1957/250500 ~ "
          "+0.008 EXACT); the chain-honest m_0* at need 454/501 "
          "is 10^%.1f ~ 10^238 (the record 10^59.6 belonged to "
          "the atom-level need); the window mutant e = 1/5 fires "
          "SUBCRITICAL under the sealed bar (1/5 < 28/125) but "
          "NOT under the chain bar (1/5 > 94/501) -- exactly the "
          "false-fire window (0.188, 0.224) the audit names, "
          "CAUGHT" % l10c)

    section("S0-V the sealed verdict bars (exact decision logic)")
    rp = _REC["r324pre"]
    fa_v = _fa_tree(rp["spikes_within"], rp["dist_ok"],
                    rp["struct_ok"])
    sh_v = _share_tree(rp["stationary"], rp["cert_ok"],
                       rp["named_ok"])
    check("S0-V1-r324pre",
          fa_v == "FA_BOUNDED_DISTRIBUTIONAL"
          and sh_v == "QMAX_SHARE_OPEN"
          and _compose_tree(fa_v, sh_v) == "NOT_COMPOSED"
          and _fa_tree(False, True, False) == "FA_OUTLIERS_REAL"
          and _fa_tree(True, False, True) == "FA_BOUNDED_STRUCTURAL"
          and _fa_tree(True, False, False) == "FA_OPEN"
          and _share_tree(True, True, True) == "QMAX_SHARE_PINNED"
          and _compose_tree(fa_v, "QMAX_SHARE_PINNED")
          == "PROVENANCE_COMPOSED"
          and rp["ks_fa"] <= rp["ks_bar"]
          and rp["p_max"] >= rp["p_min"]
          and rp["m2_viol"] == (53, 67, 83, 76, 61, 28, 109)
          and max(rp["ks_thirds"]) <= rp["ks_bar"]
          and rp["composed_viol"] == 0 and rp["composed_named"] == 4
          and rp["fab_test"] > rp["fab_cal"],
          "the r324-pre trees on the banked record: "
          "FA_BOUNDED_DISTRIBUTIONAL (KS 982/10000 <= 1/8, p_max "
          "18/200 >= 1/20 -- the ladder max 2.47 is INSIDE the "
          "stationary max law; envelope C_F 3357/1000) + "
          "QMAX_SHARE_OPEN (stationary EXACT thirds, but C_M2 "
          "22557/10000 violated by exactly the seven-rung set) + "
          "NOT_COMPOSED by seal; the composed census bound 0/39 "
          "with named 4/4 stays a census, not a certificate; "
          "mutants: outlier spikes fire FA_OUTLIERS_REAL, a "
          "certifying share fires PINNED and composes -- all TIP")
    check("S0-V2-r324",
          _origin_tree(r4["leak"], r4["restate"], r4["go_all"],
                       r4["decided"], r4["sub"])
          == "PILEUP_GROWS_SUBCRITICAL"
          and _origin_tree(True, False, False, True, True)
          == "TARGET_LEAK"
          and _origin_tree(False, True, False, True, True)
          == "FA_RESTATEMENT"
          and _origin_tree(False, False, True, True, True)
          == "QMAX_MULTISCALE_GO"
          and _origin_tree(False, False, False, False, True)
          == "M2_GO_QMAX_OPEN"
          and _origin_tree(False, False, False, True, False)
          == "PILEUP_SUPERCRITICAL"
          and r4["nsc_viol"] == 0 and r4["pil_viol"] == 11
          and r4["inf_viol"] == 5 and r4["c2_viol"] == 7
          and r4["heavy"]["kz53"][0] > r4["heavy"]["kz53"][1]
          and r4["heavy"]["kz53"][2] == r4["nsc_med"],
          "PILEUP_GROWS_SUBCRITICAL(+172/1000 < 224/1000) on the "
          "record: the scale count CERTIFIES (C_NSC 20258/10000, "
          "0/39) while the per-scale mass is REFUTED (C_PIL "
          "93583/10000, 11/39) -- the hardness answer: kz53's "
          "heavy scale 13.778 EXCEEDS its own G = 13.02 at nsc 5 "
          "== ladder median (ONE heavy source scale, not "
          "multiscale convergence); mutants: all five other "
          "letters fire on their tipped inputs -- all TIP")
    r5 = _REC["r325"]
    check("S0-V3-r325",
          _r325_tree(r5["gate_a"], r5["gate_b"], r5["gate_c"],
                     r5["floor"]) == "ELEMENTWISE_STABILIZATION_GO"
          and _r325_tree(False, True, True, True)
          == "CANONICAL_MESH_REBUILD_GO"
          and _r325_tree(False, False, True, True)
          == "SIGNED_DEFECT_CORRECTION_GO"
          and _r325_tree(False, False, False, True)
          == "ANCHOR_ONLY_INSUFFICIENT"
          and _r325_tree(False, False, False, False)
          == "NO_EXTRACTION_ARCHITECTURE"
          and r5["sign_subtype"] == "SIGN"
          and all(v > _Fr(1, 10 ** 6) for v in r5["onset_below"])
          and r5["mustfails"] == 4,
          "ELEMENTWISE_STABILIZATION_GO primary on the record "
          "(gate A: exact stabilization at the predicted onset on "
          "every sealed element + mesh constancy + comb identity; "
          "co-letters B/C(SIGN)/floor all carried independently: "
          "B = construction substrate, C = quantified density "
          "step, the anchor floor real); the below-onset reads "
          "genuinely differ (2.7e-2..5.3e-2 > ONSET_MIN); "
          "mutants: each gate failure cascades in the sealed "
          "order down to NO_EXTRACTION_ARCHITECTURE -- all TIP")
    r6 = _REC["r326"]
    check("S0-V4-r326",
          "LEVEL_C_NAMED" in _bar_r326(r6)
          and _bar_r326(r6, census_break=True)
          == "LEAN_CLAIM_VOID(recompose)"
          and _bar_r326(r6, legacy_touched=True)
          == "LEAN_CLAIM_VOID(recompose)"
          and _bar_r326(r6, lake_red=True)
          == "LEAN_CLAIM_VOID(recompose)"
          and r6["census_after"] == 8
          and set(r6["new_names"])
          == {"arch_elementwise_stabilization",
              "pole_elementwise_stabilization",
              "specFamily_sourceExact_completion"},
          "LEVEL_C_NAMED on the r326 report: census 5 -> 8 == "
          "5 + 3 named typed Level-C statements (arch/pole "
          "transcription CLASSICAL, source completion "
          "DEFINITIONAL), the three kernel pieces PROVED "
          "(sourceExact_buildPrimeWindow, comb stabilization "
          "elementwise, weil_nonneg_of_windowlocal), five legacy "
          "sorrys byte-identical, lake green with exactly 8 "
          "intentional warnings, run_rh 75/75; mutants: a census "
          "mismatch, a touched legacy sorry or a red lake build "
          "VOIDS the Lean claim -- all TIP")
    r7 = _REC["r327"]
    unbounded = (r7["e_route"] >= _Fr(224, 1000)
                 and r7["route_halves"][0] >= _Fr(224, 1000)
                 and r7["route_halves"][1] >= _Fr(224, 1000))
    check("S0-V5-r327",
          _cap_tree(r7["leak"], r7["brk"], r7["lam_go"],
                    r7["bal_go"], unbounded) == "CAP_PARTIAL"
          and _cap_tree(True, False, False, False, False)
          == "TARGET_LEAK"
          and _cap_tree(False, True, False, False, False)
          == "RECOMP_BREAK"
          and _cap_tree(False, False, True, False, False)
          == "LAMBDA_PAIR_CAP_GO"
          and _cap_tree(False, False, False, True, False)
          == "BALANCE_CAP_GO"
          and _cap_tree(False, False, False, False, True)
          == "HEAVY_GROUP_UNBOUNDED"
          and _anatomy_letter(r7["ratio_named"], r7["ratio_bar"])
          == "SOURCE"
          and _anatomy_letter((_Fr(1, 4), _Fr(1, 3), _Fr(2, 5)),
                              r7["ratio_bar"]) == "AGGREGATION"
          and r7["hist"] == (0, 65, 0)
          and r7["align_med"] == 1
          and r7["kz53_bshare"] == _Fr(888, 1000)
          and r7["lv_viol"] == 19 and r7["lv_named"] == 0
          and r7["min_a"] is None
          and r7["ng_viol"] == 0 and r7["ng_named"] == 4
          and r7["e_route"] < _Fr(224, 1000)
          and r7["route_halves"][0] > _Fr(224, 1000)
          and r7["route_halves"][1] < 0
          and abs(r7["e_hg"] + r7["e_ng"] + r7["e_m2"]
                  - r7["e_route"]) <= _Fr(2, 1000),
          "CAP_PARTIAL with anatomy SOURCE on the record (med "
          "named ratio 1057/1000 >= 1/2): on ALL 65 rungs the "
          "heaviest group is EXACTLY ONE beta/omega fold pair "
          "(histogram (0, 65, 0), alignment median 1 -- the "
          "ancestors REINFORCE); kz53 = ONE bulk/window "
          "coincidence at bshare 888/1000, gap 76/1000; the "
          "Lambda-pair cap REFUTED (19/39, named 0/4), the direct "
          "cap fails at both A, THE GROUP COUNT CERTIFIES (C_NG "
          "26351/10000, 0/39, named 4/4 -- the third O(log m) "
          "count); e_route 106/1000 < 224/1000 but the halves "
          "STRADDLE (+411 / -1183): HEAVY_GROUP_UNBOUNDED does "
          "NOT fire by the sealed stability rule; mutants: all "
          "five other letters fire on their tipped inputs, a "
          "sub-bar median flips the anatomy to AGGREGATION -- "
          "all TIP")
    check("S0-V6-r323",
          "ABORT_CLEAN" in _bar_r323(_REC["r323"])
          and _bar_r323(_REC["r323"], wrote=True)
          == "ABORT_DIRTY(a write happened -- recompose)",
          "ABORT_CLEAN on the r323 note: the L* fork was aborted "
          "by the binding reviewer adjudication at the end of the "
          "design phase, BEFORE any write access (no probe, no "
          "measurement, no rh/ file, no INVENTORY row -- nothing "
          "counts as a round); post-abort suite 73/73 with "
          "103/103 pins; mutant: any write fires ABORT_DIRTY -- "
          "TIPS")

    section("S0-V7 the wave-13 composition (the claim split)")
    real = _wave13()
    check("S0-V7-composition",
          real == ("ELEMENTWISE_BANKED(R325 GO + R326 Lean "
                   "implementation; H_cof replaced as the target "
                   "route) | MEASURED_COMPOSITION_BANKED("
                   "subcritical +0.172, m_0* = 10^59.6, gap "
                   "typed; C_NSC + C_NG certified; SOURCE "
                   "anatomy; coincidence-geometry direction; "
                   "r328B chain note: block-level need 454/501, "
                   "chain bar 0.188 -- the verdict survives "
                   "0.172 < 0.188, m_0* chain-honest 10^238) | "
                   "LEVEL_C_NAMED(census 8, three typed "
                   "statements) | "
                   "PRIME.EXTRACTION.ELEMENTWISE.01 [E]; "
                   "PRIME.L2.RENYI3.MEASURED_COMPOSITION.01 [O]; "
                   "PRIME.L2.RENYI3.SLIDING_BOUND.01 [O update]; "
                   "PRIME.L2.RENYI3.PROVENANCE.01 [O update]")
          and "EXTRACTION_CLAIM_VOID" in _wave13(r325_fails=True)
          and "COMPOSITION_VOID" in _wave13(supercritical=True)
          and "LEAN_LEG_VOID" in _wave13(census_break=True)
          and "CLAIM_SPLIT_INVALID" in _wave13(r325_fails=True),
          "the five items compose to EXACTLY the wave-13 claim "
          "split: the elementwise extraction repair banked [E] "
          "(R325 GO + R326 implementation with the honest "
          "new-connection formulation), the measured terminal "
          "composition registered [O] (the r324 chain with the "
          "certified counts, the r327 SOURCE anatomy and the "
          "coincidence-geometry direction), the SLIDING_BOUND/"
          "PROVENANCE updates typed; tipping mutants: a failing "
          "R325 gate voids the extraction claim, a supercritical "
          "exponent voids the composition, a Lean census mismatch "
          "voids the implementation leg -- each tip INVALIDATES "
          "the split: it is not hard-wired")

    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"""fa_provenance_probe -- PRIME.L2.RENYI3.FA_PROVENANCE.01
(round 324): THE F_A PROVENANCE ROUND -- the terminal main lane
after the r321 SLIDING_BOUND_GO.  r321 (SPEC e68883ad) sealed the
sliding cubic bound rho_2 <= 1.3056 x F_A^2 pointwise (0/39 test,
all four named violators inside with reserves 7.0..9.6; the G_SQ
constant is algebra-derived via the exact concentration bracket
qmax x PhiH1 <= rho_2 <= PhiH1 = (F_A B)^2; 21 small-m
certificates).  The remaining provenance question is SOURCE-PURE,
LOCAL and SPLIT IN TWO -- this round executes both halves:
  (a) IS F_A BOUNDED?  (measured max 2.47; the near-critical
      family kz53/kz83/kz67 is the TOP of the coordinate.)  Two
      candidate mechanisms, both source-pure testable:
      (a-i)  DISTRIBUTIONAL ROUTE: if the normalized block
             profile is stationary (r302: KS 0.043 over a 3x
             depth range, m2_inf = 1.973, 1/N transient, held-out
             0.002), then F_A is a max-statistic functional of
             ONE stationary distribution -- finite-sample extreme
             value scatter.  SEALED CONSTRUCTION: resample
             synthetic QMAX columns from the pooled normalized
             donor profile (donors = the ladder MINUS the three
             named spike rungs, declared-set warded; seeded rng,
             NRS = 200 replicates, one full ladder column per
             replicate, the imported r317 EFP.local_ratio applied
             to each synthetic column) -- the QQ census KS(F_A
             real, F_A* pooled) and the LADDER-MAX p-value p_max
             = P(max F_A* >= max F_A real) decide whether the
             spikes are INSIDE the stationarity scatter (then
             F_A <= C_F is a distribution-statement candidate,
             C_F = the resampled envelope) or REAL OUTLIERS.
      (a-ii) STRUCTURAL ROUTE: what is locally different at
             kz53/kz83/kz67?  NEW EXACT FACTORIZATION (derived
             algebra, disclosed, warded live): with j* = argmax_j
             |x_j|, A1_j = sum of |atom values| in block j, L =
             sum_j |x_j|:
                 QMAX = s x a,   s = |x_{j*}|/A1_{j*} <= 1
                                 (in-block signed survival,
                                  triangle inequality EXACT),
                                 a = A1_{j*}/L (the ATOM-MASS
                                 share of the argmax block).
             The spike census asks WHICH factor carries the named
             F_A spikes (rank-local ratios F_s, F_a via the
             imported EFP.local_ratio; sealed attribution rule:
             common carrier iff all three named spikes share one
             factor with ratio >= STRUCT_MIN = 1.5 while the
             other stays <= OTHER_MAX = 1.25), plus the fold/
             collision/edge-distance census of the argmax blocks.
             s <= 1 gives the EXACT majorant F_A <= FAB :=
             a/medloc (warded live); the structural bound
             certifies iff FAB is itself mid-ladder bounded
             (C_FAB frozen on the r316 cal window, 0 test
             violations demanded).
  (b) WHAT BOUNDS THE QMAX SHARE sigma = rho_2/(F_A B)^2 =
      rho_2/PhiH1 in [qmax, 1] (the r321 bracket)?  THE NAMED
      CONNECTION: the r302-proved M_2 stationarity pins the
      SECOND moment of the same normalized block profile -- the
      median-of-max shape route.  NEW EXACT INTERMEDIATE
      INEQUALITY (derived algebra, disclosed, Fractions-proved on
      the toy, warded live on every live world): with q_j =
      |x_j|/L, m2 = m x sum q^2 (the normalized second moment,
      the r302 object) and ymax = m x qmax:
          sum q^3 <= qmax x sum q^2   (exact)
          ==>  sigma <= m2 / ymax = m2 / (m x qmax),
      hence by the r321 bracket algebra (m x qmax = F_A B log m):
          rho_2 <= m2 x F_A x B / log m           (EXACT, pointwise)
          sum q^3 <= m2 x F_A x B x (log m) / m^2.
      m2 is a QUADRATIC source-pure column (no cubic target).
      SEALED CERTIFICATION: C_M2 = max m2 over the r316 mid-
      ladder calibration window (frozen; consumes NO cubic
      target); QMAX_SHARE_PINNED iff the r302 stationarity
      reproduces on THIS ladder (pooled normalized profile,
      three (N, kz)-sorted thirds, KS(G1,G3) <= KS_STAT = 0.125
      AND KS(G2,G3) <= KS_STAT, r302 rule verbatim) AND m2 <=
      C_M2 on every test rung (0 violations) AND the four named
      r316/r317 violators kz53/kz83/kz67/kz55 are ALL inside the
      composed bound rho_2 <= C_M2 x F_A x B / log m; otherwise
      QMAX_SHARE_OPEN with the full anatomy (sigma table,
      tightness sigma x ymax / m2, trends, 1/N census via the
      imported r302 fs_solve against m2_inf = 1.973).
TARGET COMPOSITION (only if (a) and (b) carry): "CANDIDATE
THEOREM (bounded coordinate)": F_A <= C_F (distribution- or
structure-statement) + the share bound ==> via the r321 bracket
the uniform pointwise Renyi-3 bound with explicit C -- the fiber
provenance reduced to two NAMED local statements about the
stationary block profile.

EXPLORATION ONLY (2026-08-27).  experiments/ level: NO promotion,
NO ledger row, NO marker moved, NO RH CLAIM in either direction.
Coexistence: the wave-12 worker (v969) and r323 (base fork) run
in parallel; this probe touches NOTHING outside its own file and
the strictly additive rh-sync.

THE OBJECT (r269/r287/r298/r302/r306/r314/r315/r316/r317/r321
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); the frozen
positional block machinery (r298 WBT.block_breaks +
WBT.aggregate_blocks); the r306 RY3.cubic_moments +
RY3.renyi3_ratio + RY3.calib_freeze; the r314 SCF.fold_genealogy
+ SCF.signed_cube_terms + SCF.flux_telescope +
SCF.collision_census; the r315 PHI.phi3_variants; the r316
TRB.two_regime_state + TRB.split_midladder; the r317
EFP.local_ratio + EFP.gap_threshold; the r321 CCP.local_median +
CCP.g_eval + CCP.g_calibrate + CCP.spearman_rank; the r302
UNIF.ks_two + UNIF.fs_solve, ALL imported verbatim; PDelta =
Pbeta - Pomega; x_j = (PDelta)_j.  NEW in this round (module-own,
source-pure where required): m2_qmax_state (the quadratic share
majorant), spike_factors (the exact QMAX = s x a factorization),
donor_pool + resample_qmax (the sealed stationary-null resampler,
seeded), qq_groups (the three-thirds stationarity split) and the
three sealed verdict trees fa_tree / share_tree / compose_tree.

SEALED ADJUDICATION (frozen BEFORE any evaluation of this round;
precedence disclosed -- distributional before structural because
a distribution-level statement is stronger than a per-window
majorant census; exactly one F_A letter and exactly one share
letter fire):
  F_A tree:    FA_OUTLIERS_REAL          iff p_max < P_MIN = 0.05
                   (the named spikes are NOT a stationarity
                   fluctuation -- then THAT is the finding),
               FA_BOUNDED_DISTRIBUTIONAL iff p_max >= P_MIN and
                   KS(F_A real, F_A* pooled) <= KS_FA = 0.125,
               FA_BOUNDED_STRUCTURAL     iff neither, and the
                   structural route certifies (common carrier
                   3/3 named AND FAB mid-ladder certified with
                   0 test violations),
               FA_OPEN                   otherwise.
  share tree:  QMAX_SHARE_PINNED iff STATIONARY (both KS clauses)
                   AND 0 m2 test violations AND named coverage
                   4/4 on the composed bound,
               QMAX_SHARE_OPEN   otherwise.
  composition: PROVENANCE_COMPOSED(C) iff the F_A letter is a
                   BOUNDED letter AND the share letter is PINNED
                   -- the candidate theorem is printed with every
                   measured constant; otherwise the two letters
                   stand alone.

LEG 0 -- ANCHOR REGRESSION (slim set, disclosed: the full
r314/r315 anchor chain is re-warded by the coexisting r321/r322
probes in the same suite; this round re-gates the r314 identity
wards plus the four record anchors its own legs consume): the
r314 identity wards live (REC3/TEL/BND bars); r306 C_2 = 1.069
(tol 0.005) first-5 freeze, 0/57; r316 rho anchors kz53/kz67/
kz55/kz83 = 1.0490/1.0536/0.4821/0.7790 (tol 0.005) + C_small
1.0694 (tol 0.005) at kz18 + ladder n = 65; r317 F_A top-3 ==
(kz53, kz83, kz67) ORDERED with values 2.47/2.39/2.38 (tol 0.01)
+ gap-B == {kz55, kz67} with THR_B 3.7157 (tol 0.005); r321 G_SQ
b = 1.3056 (tol 0.005) with 0 test violations and named coverage
4/4 (recomputed via the imported CCP.g_calibrate).

LEG A -- SEAL + PURITY + TOYS + LIVE WARDS: (A1) the sealed
definitions printed; the SOURCE-PURE coordinate/factor table
(rank, kz, N, m, QMAX, F_A, medloc, B, s, a, m2) printed BEFORE
any bound-side or resample table of this round.  (A2) SOURCE-
PURITY AUDITS: the AST identifier scan over the six module-own
builders (m2_qmax_state, spike_factors, donor_pool,
resample_qmax, qq_groups + the three verdict trees) must be
clean against BOUND_FORBIDDEN + PHI3_FORBIDDEN +
RESAMPLE_FORBIDDEN; the literal scan over the builders + trees
must be clean against the sealed record-literal set
R324_TABLE_LITERALS (r314+r315+r316+r317 set, r321 verbatim,
UNION the r321 record numbers); e1-e4 prove the audits bite.
(A3) TOY EXACTNESS (Fractions where the spec demands exact
intermediate inequalities): the share toy x = (1, -2, 3) in
exact Fractions: q = (1/6, 1/3, 1/2), sigma = 2/3, bracket 1/2
<= 2/3 <= 1 EXACT, m2 = 7/6, ymax = 3/2, majorant 7/9 with slack
1/9 EXACT; the flat toy x = (1, 1): sigma = 1 = upper bracket
EQUALITY = m2/ymax EQUALITY (the majorant is sharp at the flat
profile); the one-block toy x = (5, 0): sigma = 1 = qmax (lower
bracket EQUALITY at full concentration); the factor toy x =
(-1, 3) with A1 = (3, 3): s = 1, a = 3/4, QMAX = 3/4 = s x a
EXACT; the resampler determinism toy (same seed twice ->
identical, constant donor pool of ones -> QMAX* == 1/m EXACT);
the imported r302 toys re-warded (ks_two((1,2,3),(1.5,2.5)) ==
1/3, fs_solve((10,3),(40,1.5)) == (1, 20, 2)); the groups toy
(disjoint + covering EXACT); the three verdict trees on every
branch combination EXACT.  (A4) LIVE WARDS on every live world:
the r316 majorant chain + NORM x cube == rho_2 (r321 verbatim);
the r321 bracket restated as the SHARE bracket qmax <= sigma <=
1; THE NEW SHARE MAJORANT sigma <= m2/ymax (exact algebra, bar
CHAIN_BAR); the reconstruction QMAX == F_A x medloc and PhiH1 ==
(F_A B)^2 on the ladder (r321 verbatim); THE NEW FACTORIZATION
QMAX == s x a EXACT (bar 1e-12) on every live world.

LEG B -- THE DISTRIBUTIONAL ROUTE (a-i): the donor pool sealed
(declared donor set == ladder ranks minus the three NAMED_FA_KZ
ranks, set-warded; the pool is the concatenation of the per-rung
mean-1 normalized profiles y = m|x|/L); the resample census (NRS
= 200 seeded replicates, per replicate one synthetic QMAX column
of the full ladder geometry m_1..m_n, F_A* = EFP.local_ratio per
column): KS(F_A real, F_A* pooled), the per-named-rank p values,
p_max, the resampled envelope C_F = max over replicates x ranks
and the 95 percent replicate-max quantile as census.

LEG C -- THE STRUCTURAL ROUTE (a-ii): the factor censuses F_s =
local_ratio(s), F_a = local_ratio(a); the named-spike attribution
table (which factor carries, sealed rule); the argmax-block
geometry census (atom count, max fold multiplicity, rank-based
edge distance) for the named spikes vs the ladder median; the
exact majorant column FAB = a/medloc with its cal/test maxima
and violation count (the structural certification).

LEG D -- THE SHARE ROUTE (b): the stationarity re-run on THIS
ladder (three (N, kz)-sorted thirds via the sealed qq_groups,
pooled normalized profiles, KS table, per-group m2 medians, the
imported fs_solve 1/N census against the r302 m2_inf = 1.973 --
census, no bar: the ladder here is 65 rungs vs the r302 42); the
share anatomy table (rank, kz, m, qmax, sigma, majorant,
tightness sigma x ymax/m2) printed AFTER the source-pure table;
C_M2 frozen on the cal window; m2 test violations; the composed-
bound violations (algebra cross-check) and the named coverage.

LEG E -- WARDS / MUST-FAILS (>= 4 mutants + 2 scope mutants):
(e1) RESAMPLE READS THE REAL F_A VALUES: mutant_resample_peek
  consumes the real coordinate column (identifier FA_real in the
  sealed RESAMPLE_FORBIDDEN set) -- AST-FLAGGED, and on the toy
  it returns the real maximum EXACTLY (loud diff vs the honest
  constant-pool draw) -- CAUGHT twice.
(e2) STATIONARITY PROFILE CALIBRATED FROM THE SPIKE RUNGS:
  mutant_pool_spikes declares the named spike ranks as the donor
  set -- the declared-set ward must CATCH the mismatch EXACT
  (the real donor_pool declares the sealed complement EXACT).
(e3) SHARE BOUND CONSUMES rho_2 CIRCULARLY: mutant_share_posthoc
  re-derives the 'constant' from the evaluated bound column over
  the whole ladder (consumes rho) -- the BOUND_FORBIDDEN scope
  audit must FLAG it (AST-CAUGHT) AND on the sealed toy it
  returns a constant != the frozen cal-window rule's.
(e4) QQ WITH OVERLAPPING SPLITS: mutant_groups_overlap returns
  thirds whose neighbors share one rank -- the disjointness ward
  must measure intersection >= 1 on the mutant and 0/0/0 on the
  sealed qq_groups -- 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 module-own builders consume block values / atom masses /
  rank order / declared sets / seeds only; sigma itself is the
  TARGET-SIDE diagnostic (rho_2/PhiH1), computed OUTSIDE the
  audited builders and entering gates/censuses only, disclosed;
  fragment audit (no fit primitives; the 1/N solve is the
  imported r302 deterministic 2-point solve).

INDEX FIREWALL (binding, r238-r321 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; the cubic target sum q^3 / rho_2 enters GATES / anchors /
the share diagnostic / certification checks only, NEVER a
module-own builder (AST-warded); no zero/prime oracles anywhere
(AST firewall); no fit primitives (fragment audit).  MACHINERY
IMPORTED VERBATIM: r321 CCP.local_median + CCP.g_eval +
CCP.g_calibrate + CCP.spearman_rank, r317 EFP.local_ratio +
EFP.gap_threshold, r316 TRB.two_regime_state +
TRB.split_midladder, r315 PHI.phi3_variants, r314
SCF.fold_genealogy + SCF.signed_cube_terms + SCF.flux_telescope
+ SCF.collision_census, r306 RY3.cubic_moments +
RY3.renyi3_ratio + RY3.calib_freeze, r302 UNIF.ks_two +
UNIF.fs_solve, r298 WBT.block_breaks + WBT.aggregate_blocks,
r269 PBB.mask_edge + PBB.runs_split, r287 L2D.blocks_level2 +
L2D.halves_slope + L2D.autocorr_full, r244 BH.wpack, 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, r316/r317/r321 verbatim): frame-A h
<= 900, 42 rungs, (N, kz)-sorted; exception set {kz15, 20, 22,
36, 38, 39, 52}; EXTENSION: 900 < h <= 1300, first 15 by (N,
kz); EXT2: the r316 A5 rule (leftover pool + first 12 windows
1300 < h <= 1650, first 8 POSITIVE_PREFIX by (N, kz)).

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);
EXT_H_MAX 1300; K_EXT 15; EXT_NW_EXPECT (942, 1218); EXT2_H_MAX
1650; EXT2_POOL_CAP 12; K_EXT2 8; ATOM_BAR 1e-9; REC3_BAR 1e-13;
TEL_BAR 1e-13; BND_BAR 1e-13; CHAIN_BAR 1e-9; XW_BAR 1e-9;
DEG_FLOOR 1e-6; MULT_CAP 2; N_CAL 5; CAL_THIRD 3 (via TRB,
verbatim); CLS_W 5 (via EFP, verbatim); NRS 200; SEED_RS 324001;
KS_FA 0.125; P_MIN 0.05; KS_STAT 0.125 (r302 verbatim); FS_BAR
0.05 (census); STRUCT_MIN 1.5; OTHER_MAX 1.25; NAMED_FA_KZ (53,
83, 67); NAMED_KZ (53, 83, 67, 55); N_GRP3 3; MUT_MIN 1e-6;
TOY_BAR 1e-12; FR_BAR 1e-14; TB_WARD bars 1e-9 main N <= 400 /
3e-6 deep + ext + ext2 / 1e-6 controls; ID_BAR 1e-12; AC_BAR
1e-9; SA_BAR 1e-12 (QMAX == s x a); R306 anchor C_2 1.069 tol
0.005; R316 anchors RHO {53: 1.0490, 67: 1.0536, 55: 0.4821, 83:
0.7790} tol 0.005, C_SMALL 1.0694 tol 0.005 at kz18, N324 = 65;
R317 anchors FA_TOP {53: 2.47, 83: 2.39, 67: 2.38} tol 0.01
ORDERED, THR_B 3.7157 tol 0.005, B set (55, 67); R321 anchors
B_SQ 1.3056 tol 0.005, 0 test violations, named 4/4; M2INF_REF
1.973 (census only, disclosed -- the ladder here is 65 rungs vs
the r302 42-rung core, no bar); R324_TABLE_LITERALS = the sealed
r314+r315+r316+r317 forbidden set (r321 verbatim) UNION the r321
record set {1.3056, 1.1426, 1.4088, 15.95, 7.97, 2.71, 5.35,
-0.341, 0.122, 1.973, 2.15, 5.21, 3.4841, 7.9714, 7.4877,
7.4069, 0.3012, 0.03846, 0.3061}; runtime <= 1800 s; smoke = w9
+ controls + toys + scope/purity audits + the chain/bracket/
share/factor wards on w9 + controls + e1-e4 mutants; ladder,
extensions, anchors, resample, stationarity, certification and
adjudication skipped.
DISCLOSED PRE-SPEC INPUT (no scratch run of this probe): every
anchor band is an r306/r316/r317/r321 RECORD number adopted
as-is; the share majorant sigma <= m2/ymax, the factorization
QMAX = s x a, the bracket restatement and the composed transfer
rho_2 <= m2 F_A B/log m are derived algebra, disclosed above;
the resample null model is DISCLOSED as iid draws from the
pooled stationary profile (the r302 lag-1 anti-correlation of
the ATOM field is not modeled at block level -- a deviation of
the real F_A tail from the iid null is typed as the honest
letter, not repaired); NRS = 200, SEED_RS = 324001, KS_FA =
KS_STAT = 0.125 (the r302 bar reused), P_MIN = 0.05, STRUCT_MIN
= 1.5 and OTHER_MAX = 1.25 are coarse a-priori bars; the sealed
letters are symmetric -- FA_OUTLIERS_REAL and QMAX_SHARE_OPEN
are first-class findings, not failures; NO resample value, NO
KS distance, NO m2 constant, NO violation count of this round
was computed before this spec was frozen.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+';
exactly one F_A letter, exactly one share letter and exactly one
composition letter fire):
  R324_ANCHORS(identity wards, r306 C_2, r316 rho + C_small +
    n, r317 FA-top3 + gap-B, r321 b + 0 viol + named 4/4)
+ SEAL(share majorant + factorization + resampler + trees +
    purity audits + toys + live wards)
+ FA_DIST(KS QQ, p_max, per-named p, envelope C_F)
+ FA_STRUCT(factor censuses, named attribution, geometry census,
    FAB cal/test)
+ [exactly one of] FA_BOUNDED_DISTRIBUTIONAL /
    FA_BOUNDED_STRUCTURAL / FA_OUTLIERS_REAL / FA_OPEN
+ SHARE(stationarity KS table, m2 groups + 1/N census vs 1.973,
    sigma anatomy, tightness, C_M2, violations, named coverage)
+ [exactly one of] QMAX_SHARE_PINNED / QMAX_SHARE_OPEN
+ [exactly one of] PROVENANCE_COMPOSED(C) / NOT_COMPOSED
+ THEOREM(candidate text printed on PROVENANCE_COMPOSED)
+ MUSTFAIL_LEDGER(e1-e4 + scopes).
Honesty before beauty: the share majorant and the factorization
are EXACT algebra, but their certification constants (C_M2,
C_FAB) and every KS distance, p value, violation count and trend
are MEASURED on the finite ladder only; the resample null is a
DISCLOSED iid model of the stationary profile; a composed GO
fixes a certified statement ON THE MEASURED RUNGS with explicit
constants, it proves NO universal bound beyond them and NO
cofinal law; FA_OUTLIERS_REAL is the honest primary finding if
the spikes exceed the stationarity scatter -- it would type the
near-critical family as a STRUCTURAL feature, not a fluctuation,
and the provenance question would sharpen accordingly;
r243-r322 stand.

RECORD TABLES (frozen from the record run; calibration protocol:
smoke pass 1 = 36/36 (0.6 s), NO amendment; calibration pass 1 =
first full evaluation, 36/36, wall 34.2 s, NO amendment; record
run1/run2 after this insertion, identical up to WALL; PROTOCOL
DISCLOSURE: a drafting error had placed PREFILLED PLACEHOLDER
record tables into this spec BEFORE any run -- they were removed
COMPLETELY before the first smoke run and are disclosed here (the
r316/r317/r321 protocol-error class); the ONLY post-freeze edit
is this record-table insertion, which IS the protocol -- no bar,
band, rule or verdict rule moved):
CAL_VERDICT = R324_ANCHORS(identity wards 4.5e-17/4.7e-16/
4.1e-16 on 69 live worlds; r306 C_2 1.069 viol 0/57; r316 rho
kz53/kz67/kz55/kz83 = 1.0493/1.0536/0.4821/0.7791, C_small
1.0694 @ kz18, n = 65; r317 F_A top-3 (53, 83, 67) =
2.47/2.39/2.38 EXACT ORDERED, gap-B {55, 67} THR_B 3.7157; r321
b = 1.3056 = B_cal_max 1.1426 squared, 0/39 test violations,
named 4/4 -- ALL bit-near) + SEAL(purity clean: 0 id + 0 literal
hits on the audited builders/trees; Fractions toys EXACT (worst
rational dev 0): sigma 2/3 in [1/2, 1], majorant 7/9 slack 1/9,
flat double EQUALITY, one-block lower EQUALITY, factor toy 3/4 =
1 x 3/4; resampler deterministic (same seed identical, ones-pool
QMAX* == 1/m EXACT); r302 import toys exact; live wards on 69
live worlds: r316 chain 6.5e-16, NORM x cube 7.9e-16, share
bracket qmax <= sigma <= 1 slack 0.0, NEW share majorant sigma
<= m2/ymax worst rel slack 0.0 -- algebra-live, sigma ==
sum q^3/qmax^2 identity 1.2e-15, NEW QMAX == s x a worst
2.2e-16, ladder recon QMAX == F_A x medloc 1.6e-16, PhiH1 ==
(F_A B)^2 5.7e-16; source-pure table census: F_A 0.58/1.01/2.47
min/med/max (max kz53), s range 0.224..0.842, a range
0.0290..0.4884, m2 range 1.579..3.194 med 2.051) +
FA_DIST(donor pool 62 rungs / 8093 pooled normalized values,
spike ranks (33, 35, 59) = kz53/kz67/kz83 excluded by seal;
KS(F_A real 65, F_A* pooled 13000) = 0.0982 <= 0.125 -- the F_A
DISTRIBUTION is the stationary max-statistic scatter; p_max =
0.090 >= 0.05 (18/200 stationary replicate ladders reach the
real maximum 2.47 somewhere; replicate-max q95 = 2.583, envelope
C_F = 3.357); per-named p at rank: kz53 0.005 / kz83 0.000 /
kz67 0.000 -- at their SPECIFIC ranks the spikes are extreme,
disclosed with the letter) + FA_STRUCT(factor censuses F_s med
1.01 max 1.74 / F_a med 0.98 max 2.87; named attribution kz53
F_s 1.72/F_a 1.53 carrier s, kz83 1.35/1.61 carrier a, kz67
1.38/2.09 carrier a -- NO common carrier (sealed rule FAIL): the
spike family is mechanically HETEROGENEOUS; geometry census at
j*: kz53/kz83 argmax blocks are EDGE-ADJACENT (rank distance
0.01/0.04 vs ladder med 0.07) and atom-poor (6/6 vs med 10),
kz67 interior atom-rich (12, 0.23), multmax 2 = fold-normal on
all three; FAB = a/medloc cal max 3.5261 vs test max 4.3380
(ratio 1.23), 4 test violations (kz67/76/68/61) -- the
structural majorant does NOT certify) +
FA_BOUNDED_DISTRIBUTIONAL(p_max 0.090 >= 0.05 AND KS 0.0982 <=
0.125: F_A <= C_F = 3.357 (resampled envelope) is a
distribution-statement candidate -- the coordinate's ladder
maximum is INSIDE the stationary max law) + SHARE(stationarity
on THIS 65-rung ladder: thirds 22/22/21, pooled profiles
1081/2758/4750 values, KS(G1,G3) 0.0230 / KS(G2,G3) 0.0158 /
KS(G1,G2) 0.0247, ALL far under 0.125 -- STATIONARY incl. the
ext/ext2 strata, even tighter than the r302 core record 0.043;
m2 group medians 2.046/2.033/2.074, fs 1/N census m2_inf =
2.081 (r302 rec 1.973, dev 0.108 on a 50 pct longer ladder), B
= -8.2 (approach from BELOW here vs the r302 above, census),
held-out dev 0.017; sigma anatomy med/min/max
0.2136/0.0907/0.4852 (ladder max at small-m kz9; deep test max
kz38 0.359), trend over test -0.584 FALLING -- the r321 'share
falls faster than B^2 rises' mechanism measured directly;
tightness sigma x ymax/m2 med 0.57 max 0.79; C_M2 = 2.2557
frozen at cal (kz34); m2 test violations 7/39: kz53 3.1528 /
kz67 3.1938 / kz83 3.0490 / kz76 2.4992 / kz61 2.4711 / kz28
2.3585 / kz109 2.2857 -- the named spikes carry an m2 EXCESS 35
.. 42 pct above the mid-ladder constant (the F_A spike IS the m2
spike); composed bound rho_2 <= C_M2 x F_A x B/log m: 0/39 test
violations AND named coverage 4/4 (kz53 rsv 1.23 / kz83 1.35 /
kz67 1.23 / kz55 1.81) -- the composed bound HOLDS measured,
because the majorant tightness (med 0.57) absorbs the m2
excess; algebra transfer NOT closed: the m2 clause fails) +
QMAX_SHARE_OPEN(STATIONARY holds but the m2 mid-ladder
certification fails on 7 test rungs incl. all three named
spikes -- the median-of-max route pins the BULK share (32/39
rungs under C_M2, majorant reserve med 1.75x) but NOT the spike
rungs; the share provenance sharpens to: what bounds the m2
excess of the near-critical rungs?) + NOT_COMPOSED(FA letter
BOUNDED_DISTRIBUTIONAL + share letter OPEN -> no theorem by
seal) + MUSTFAIL_LEDGER(e1 AST-FLAGGED on FA_real + toy peek
2.0 == real max vs honest ones-pool 1.0, diff 1.0 LOUD; e2
declared (2, 5, 9) != sealed complement, set ward EXACT; e3
AST-FLAGGED on rho + toy posthoc 1.6667 != frozen cal rule
1.2000, diff 0.4667; e4 mutant overlaps (1, 1) vs sealed 0
EXACT disjoint + cover; m5a t_term / m5b g_branch FLAGGED).
READING (typed, no upgrade): the round answers both provenance
halves and the two answers POINT AT ONE OBJECT: (1) F_A letter =
FA_BOUNDED_DISTRIBUTIONAL -- the r302 stationarity EXPLAINS the
coordinate: the F_A distribution matches the iid stationary
max-statistic null (KS 0.098 <= 0.125) and the ladder MAXIMUM
2.47 sits inside the stationary max law (p_max 0.090; envelope
C_F 3.357, q95 2.583): the MAGNITUDE of the near-critical spikes
is a finite-sample property of the stationary profile -- F_A <=
C_F is available as a distribution-statement candidate, which
was question (a); (2) the honest tension is DISCLOSED and typed:
the per-rank p values at the named spikes are 0.005/0.000/0.000
-- WHERE the extremes sit (exactly the near-critical rungs, all
three) is NOT explained by the exchangeable null; the sealed
question (bounded coordinate = ladder-max law) is answered GO,
the rank-identity question is the sharpened residue; (3) the
structural census REFUTES a single mechanism: kz53 is a
SURVIVAL spike at an edge-adjacent atom-poor block (F_s 1.72,
rank edge distance 0.01, 6 atoms), kz67 an ATOM-MASS
concentration at an interior atom-rich block (F_a 2.09, 12
atoms), kz83 mixed (a-carried 1.61, edge-adjacent, atom-poor) --
the sealed common-carrier rule fails honestly and the exact
majorant F_A <= a/medloc does not mid-ladder certify (4
violations): no structural bound letter, the identity-first
question closes negative; (4) share letter = QMAX_SHARE_OPEN
with the mechanism measured: the NEW exact chain sigma <=
m2/(m qmax) (Fractions-proved, warded two-sided live on 69
worlds) converts M_2 stationarity into a pointwise share bound;
the stationarity itself reproduces on the 65-rung ladder EVEN
TIGHTER than the r302 core (KS 0.023/0.016 vs 0.043) with
m2_inf 2.081 census vs the r302 1.973 -- but the m2 mid-ladder
constant is violated by exactly the named spikes (+35..42 pct):
THE F_A SPIKE AND THE m2 SPIKE ARE THE SAME OBJECT seen in the
second vs third moment, and the sealed pin rule maps it to OPEN
by contract; (5) the round's strongest bycatch: the composed
bound rho_2 <= 2.2557 x F_A x B/log m holds 0/39 MEASURED with
named coverage 4/4 (reserves 1.23..1.81) and the share trend is
-0.584 falling -- the r321 mechanism ('the share falls faster
than B^2 rises') is now an algebra-backed measured statement,
LINEAR in F_A where r321's certificate was quadratic.  Honest
negatives: the composed theorem is NOT printed (share letter
OPEN by the sealed m2 clause -- the 0/39 composed record is a
census, not a certificate); the structural route delivers no
bound; the rank-identity residue (why the stationary extremes
sit exactly on the near-critical rungs) and the m2 excess of
those rungs are the SAME open object; nothing here bounds
anything beyond the measured rungs.  R325 direction (typed,
census-grade): the provenance question is now ONE local
question -- the second-moment excess of the near-critical rungs
(m2 3.05..3.19 vs ladder med 2.05) against the r302-stationary
bulk: EITHER extend the stationarity statement to the m2
TAIL LAW (does the per-rung m2 distribution over the ladder
follow the stationary null's m2 scatter?  the resample
machinery of this round applies verbatim to m2 columns), OR dig
the heterogeneous local geometry (edge-adjacent atom-poor
survival spike kz53 vs interior atom-mass spike kz67) at atom
level via the r314 genealogy of the argmax block.  Runtime
34.2 s full / 0.6 s smoke; run1/run2 identical up to WALL.
AMENDMENTS AFTER FREEZE: none except this record-table insertion
(and the disclosed pre-run placeholder removal).

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 window_border_transfer_probe as WBT     # noqa: E402 r298
import unif_target_probe as UNIF               # noqa: E402 r302
import renyi3_probe as RY3                     # noqa: E402 r306
import signed_cubic_flux_probe as SCF          # noqa: E402 r314
import phi3_functional_probe as PHI            # noqa: E402 r315
import two_regime_bound_probe as TRB           # noqa: E402 r316
import exception_families_probe as EFP         # noqa: E402 r317
import continuous_coordinate_probe as CCP      # noqa: E402 r321
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
EXT_H_MAX = 1300
K_EXT = 15
EXT_NW_EXPECT = (942, 1218)
EXT2_H_MAX = 1650
EXT2_POOL_CAP = 12
K_EXT2 = 8
ATOM_BAR = 1e-9
REC3_BAR = 1e-13
TEL_BAR = 1e-13
BND_BAR = 1e-13
CHAIN_BAR = 1e-9
XW_BAR = 1e-9
DEG_FLOOR = 1e-6
MULT_CAP = 2
N_CAL = 5
NRS = 200
SEED_RS = 324001
KS_FA = 0.125
P_MIN = 0.05
KS_STAT = 0.125
FS_BAR = 0.05
STRUCT_MIN = 1.5
OTHER_MAX = 1.25
NAMED_FA_KZ = (53, 83, 67)
NAMED_KZ = (53, 83, 67, 55)
N_GRP3 = 3
MUT_MIN = 1e-6
TOY_BAR = 1e-12
FR_BAR = 1e-14
SA_BAR = 1e-12
EDGE_F = 0.20
PAIR_OFFSET = 0
R306_C2 = 1.069
R306_C2_TOL = 0.005
N324_REF = 65
R316_RHO = {53: 1.0490, 67: 1.0536, 55: 0.4821, 83: 0.7790}
R316_RHO_TOL = 0.005
R316_CSMALL = 1.0694
R316_CSMALL_TOL = 0.005
R316_CSMALL_KZ = 18
R317_FA_TOP = {53: 2.47, 83: 2.39, 67: 2.38}
R317_FA_ORDER = (53, 83, 67)
R317_FA_TOL = 0.01
R317_THRB = 3.7157
R317_THRB_TOL = 0.005
R317_B_KZ = (55, 67)
R321_B_SQ = 1.3056
R321_B_TOL = 0.005
M2INF_REF = 1.973
R324_TABLE_LITERALS = frozenset(CCP.R32X_TABLE_LITERALS | {
    1.3056, 1.1426, 1.4088, 15.95, 7.97, 2.71, 5.35,
    -0.341, 0.122, 1.973, 2.15, 5.21, 3.4841, 7.9714,
    7.4877, 7.4069, 0.3012, 0.03846, 0.3061})

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"}
PHI3_FORBIDDEN = {"cube", "S" + "3", "cm",
                  "renyi3" + "_ratio", "cubic" + "_moments"}
RESAMPLE_FORBIDDEN = {"FA" + "_real", "rho"}


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


def literal_audit(funcname):
    """the RECORD-LITERAL audit: walk ONLY the named function's
    subtree and flag any numeric constant whose 4-decimal rounding
    lies in the sealed r314+r315+r316+r317+r321 record 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):
                if isinstance(sub, ast.Constant) \
                        and isinstance(sub.value, (int, float)) \
                        and not isinstance(sub.value, bool):
                    if round(float(sub.value), 4) \
                            in R324_TABLE_LITERALS:
                        hits.append("%s@%d" % (repr(sub.value),
                                               sub.lineno))
    return hits


# ---------------- module-own builders.  Source-pure: they consume
# ---------------- block values / atom masses / rank order /
# ---------------- declared sets / seeds only; the withheld
# ---------------- terminal drive key, the branch label, the cubic
# ---------------- target, the real coordinate column (resampler)
# ---------------- and the record literals are forbidden (AST
# ---------------- identifier scan + literal scan).  sigma itself
# ---------------- (rho_2/PhiH1) is the TARGET-SIDE diagnostic,
# ---------------- computed OUTSIDE these builders, disclosed.
def m2_qmax_state(vals):
    """the quadratic share-majorant state of one rung: on block
    values x with q = |x|/L: qm = max q, m2 = m x sum q^2 (the
    normalized second moment, the r302 object), ymx = m x qm,
    maj = m2/ymx -- the EXACT share majorant (sum q^3 <= qm x
    sum q^2 by algebra => sigma = sum q^3/qm^2 <= maj)."""
    ax = np.abs(np.asarray(vals, dtype=float))
    n = int(len(ax))
    tot = float(np.sum(ax))
    if n < 2 or tot <= 0.0:
        return dict(qm=0.0, m2=0.0, ymx=0.0, maj=0.0)
    q = ax / tot
    qm = float(np.max(q))
    m2 = float(n) * float(np.sum(q * q))
    ymx = float(n) * qm
    return dict(qm=qm, m2=m2, ymx=ymx, maj=m2 / max(ymx, 1e-300))


def spike_factors(vals, amass):
    """the EXACT factorization of the concentration coordinate at
    the argmax block: on block values x and per-block atom masses
    A1 (both length m), with j* = argmax |x|:
        s = |x_{j*}| / A1_{j*}   (in-block signed survival <= 1
                                  by the triangle inequality),
        a = A1_{j*} / L          (the atom-mass share),
    so that QMAX == s x a EXACTLY (warded live)."""
    ax = np.abs(np.asarray(vals, dtype=float))
    am = np.asarray(amass, dtype=float)
    tot = float(np.sum(ax))
    if len(ax) < 2 or tot <= 0.0:
        return dict(s=0.0, a=0.0, j=0)
    j = int(np.argmax(ax))
    s = float(ax[j]) / max(float(am[j]), 1e-300)
    a = float(am[j]) / tot
    return dict(s=s, a=a, j=j)


def donor_pool(ylists, donors):
    """the sealed stationary donor pool: concatenate the per-rung
    mean-1 normalized profiles over EXACTLY the declared donor
    rank tuple; returns (pool, declared) -- the declared set is
    warded against the sealed complement of the named spike ranks
    (the e2 mutant declares the spike ranks and is CAUGHT)."""
    donors = tuple(donors)
    pool = np.concatenate([np.asarray(ylists[i], dtype=float)
                           for i in donors]) \
        if donors else np.zeros(0)
    return pool, donors


def resample_qmax(pool, sizes, reps, seed):
    """the sealed stationary-null resampler: seeded rng; per
    replicate draw one synthetic profile of every declared size
    (iid from the pool, with replacement) and record its QMAX* =
    max/sum -- one full synthetic ladder column per replicate.
    Returns the (reps x n) array.  DISCLOSED null model: iid
    draws from the pooled stationary profile."""
    rng = np.random.default_rng(seed)
    npool = len(pool)
    out = np.zeros((int(reps), len(sizes)))
    for r in range(int(reps)):
        for i, sz in enumerate(sizes):
            idx = rng.integers(0, npool, size=int(sz))
            yv = pool[idx]
            tot = float(np.sum(yv))
            out[r, i] = float(np.max(yv)) / max(tot, 1e-300)
    return out


def qq_groups(n):
    """the sealed stationarity split: the (N, kz)-sorted ladder
    rank range 0..n-1 into three near-equal consecutive thirds
    (the r302 three-group protocol generalized to n rungs);
    pairwise disjoint and covering by construction -- warded
    exactly against the e4 overlap mutant."""
    parts = np.array_split(np.arange(int(n)), N_GRP3)
    return tuple(tuple(int(k) for k in p) for p in parts)


def fa_tree(spikes_within, dist_ok, struct_ok):
    """the sealed F_A verdict tree (booleans only; exactly one
    fires; precedence disclosed in the spec)."""
    if not spikes_within:
        return "FA_OUTLIERS_REAL"
    if dist_ok:
        return "FA_BOUNDED_DISTRIBUTIONAL"
    if struct_ok:
        return "FA_BOUNDED_STRUCTURAL"
    return "FA_OPEN"


def share_tree(stationary, cert_ok, named_ok):
    """the sealed share verdict tree (booleans only; exactly one
    fires)."""
    if stationary and cert_ok and named_ok:
        return "QMAX_SHARE_PINNED"
    return "QMAX_SHARE_OPEN"


def compose_tree(fa_v, sh_v):
    """the sealed composition rule (letters only)."""
    if fa_v in ("FA_BOUNDED_DISTRIBUTIONAL",
                "FA_BOUNDED_STRUCTURAL") \
            and sh_v == "QMAX_SHARE_PINNED":
        return "PROVENANCE_COMPOSED"
    return "NOT_COMPOSED"


def mutant_resample_peek(FA_real):
    """e1 MUST-FAIL MUTANT: a 'resampler' that reads the REAL
    coordinate column and returns its maximum (the null
    distribution collapses onto the observation) -- the
    RESAMPLE_FORBIDDEN scope audit must FLAG it, and on the toy
    it returns the real maximum EXACTLY, loudly different from
    the honest constant-pool draw."""
    return max(float(v) for v in FA_real)


def mutant_pool_spikes(ylists, spike_ranks):
    """e2 MUST-FAIL MUTANT: the donor pool built FROM the named
    spike rungs (the stationarity profile calibrated on exactly
    the rungs under adjudication) -- the declared-set ward must
    CATCH the mismatch EXACT."""
    ranks = tuple(spike_ranks)
    pool = np.concatenate([np.asarray(ylists[i], dtype=float)
                           for i in ranks])
    return pool, ranks


def mutant_share_posthoc(Fv, Bv, mv, rho):
    """e3 MUST-FAIL MUTANT: the share 'constant' re-derived from
    the evaluated bound column over the WHOLE ladder (consumes
    rho; covers every seen violator by construction) -- the
    BOUND_FORBIDDEN scope audit must FLAG it AND on the sealed
    toy it returns != the frozen cal-window rule's."""
    return max(r * math.log(float(mm)) / max(float(f) * float(b),
                                             1e-300)
               for f, b, mm, r in zip(Fv, Bv, mv, rho))


def mutant_groups_overlap(n):
    """e4 MUST-FAIL MUTANT: a three-thirds split whose neighbor
    groups share EXACTLY one rank -- the disjointness ward must
    measure intersection >= 1 on the mutant and 0/0/0 on the
    sealed qq_groups."""
    k = int(n) // 3
    g1 = tuple(range(0, k + 1))
    g2 = tuple(range(k, 2 * k + 1))
    g3 = tuple(range(2 * k, int(n)))
    return g1, g2, g3


def mutant_gift_bound(rc, P):
    """m5a MUST-FAIL MUTANT: a 'provenance orientation' consuming
    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.abs(P) ** 3))


def mutant_branch_peek(rc, P):
    """m5b MUST-FAIL MUTANT (world-blindness break simulated): a
    'provenance constant' consuming the branch label -- the scope
    audit must FLAG this."""
    c = 0.5 if rc["g_branch"] >= 0.0 else 2.0
    return c * float(np.sum(np.abs(P) ** 3))


# ---------------- exact Fractions section: the share algebra
# ---------------- decided as rational arithmetic on the toys
def fr_share_toys():
    """the share bracket + majorant in exact Fractions:
    (1) x = (1, -2, 3): q = (1/6, 1/3, 1/2); sigma = sum q^3 /
        qmax^2 = 2/3; bracket qmax = 1/2 <= 2/3 <= 1; m2 = m sum
        q^2 = 7/6; ymax = m qmax = 3/2; majorant m2/ymax = 7/9;
        slack 7/9 - 2/3 = 1/9 EXACT;
    (2) flat x = (1, 1): sigma = 1 (upper bracket EQUALITY) and
        m2/ymax = 1 (majorant EQUALITY -- sharp at flat);
    (3) one-block x = (5, 0): sigma = 1 = qmax (lower bracket
        EQUALITY at full concentration).
    Returns the worst rational deviation (must be 0)."""
    def state(xs):
        ax = [abs(Fr(v)) for v in xs]
        L = sum(ax)
        q = [v / L for v in ax]
        qm = max(q)
        sg = sum(v ** 3 for v in q) / qm ** 2
        m2 = Fr(len(q)) * sum(v * v for v in q)
        ymx = Fr(len(q)) * qm
        return q, qm, sg, m2, ymx

    devs = []
    q, qm, sg, m2, ymx = state((1, -2, 3))
    devs += [abs(sg - Fr(2, 3)), abs(qm - Fr(1, 2)),
             abs(m2 - Fr(7, 6)), abs(ymx - Fr(3, 2)),
             abs(m2 / ymx - Fr(7, 9)),
             abs((m2 / ymx - sg) - Fr(1, 9))]
    devs += [Fr(0) if qm <= sg <= Fr(1) else Fr(1)]
    q, qm, sg, m2, ymx = state((1, 1))
    devs += [abs(sg - 1), abs(m2 / ymx - 1)]
    q, qm, sg, m2, ymx = state((5, 0))
    devs += [abs(sg - 1), abs(qm - 1)]
    return max(devs)


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("fa_provenance_probe -- "
          "PRIME.L2.RENYI3.FA_PROVENANCE.01 (round 324)")
    print("SPEC_SHA %s   R321_SHA %s   R317_SHA %s   R302_SHA %s"
          % (SPEC_SHA[:16], CCP.SPEC_SHA[:16], EFP.SPEC_SHA[:16],
             UNIF.SPEC_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 + controls + toys + scope/"
                        "purity audits + chain/bracket/share/"
                        "factor wards + e1-e4; ladder, "
                        "extensions, anchors, resample, "
                        "stationarity, certification and "
                        "adjudication 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 F_A PROVENANCE ROUND (terminal main lane after the "
          "r321 SLIDING_BOUND_GO): (a) is F_A bounded -- "
          "distributional route (sealed stationary-null resample, "
          "NRS = %d, seed %d, donors = ladder minus the named "
          "spike ranks %s; QQ bar %.3f, ladder-max p bar %.2f) "
          "and structural route (EXACT factorization QMAX = s x "
          "a, attribution bars %.1f/%.2f, FAB mid-ladder "
          "certification); (b) what bounds the qmax share sigma "
          "= rho_2/(F_A B)^2 -- THE NEW EXACT CHAIN sigma <= "
          "m2/(m qmax) (algebra, Fractions-proved) converts the "
          "r302 M_2 stationarity into a pointwise share bound "
          "with mid-ladder constant C_M2; verdict trees "
          "FA_OUTLIERS_REAL / FA_BOUNDED_DISTRIBUTIONAL / "
          "FA_BOUNDED_STRUCTURAL / FA_OPEN and QMAX_SHARE_PINNED "
          "/ QMAX_SHARE_OPEN and PROVENANCE_COMPOSED / "
          "NOT_COMPOSED sealed BEFORE evaluation"
          % (NRS, SEED_RS, str(NAMED_FA_KZ), KS_FA, P_MIN,
             STRUCT_MIN, OTHER_MAX))
    frag = antigate_fragment_audit()
    sc_own = []
    for fn in ("m2_qmax_state", "spike_factors", "donor_pool",
               "resample_qmax", "qq_groups", "fa_tree",
               "share_tree", "compose_tree"):
        sc_own += scope_audit(fn, BOUND_FORBIDDEN)
        sc_own += scope_audit(fn, PHI3_FORBIDDEN)
        sc_own += scope_audit(fn, RESAMPLE_FORBIDDEN)
    sc_a = scope_audit("mutant_gift_bound", BOUND_FORBIDDEN)
    sc_b = scope_audit("mutant_branch_peek", BOUND_FORBIDDEN)
    check("G03-scope-audits", (not frag) and (not sc_own)
          and len(sc_a) >= 1 and len(sc_b) >= 1,
          "fragment audit clean (%d hits); the eight module-own "
          "builders/trees clean vs BOUND_FORBIDDEN + "
          "PHI3_FORBIDDEN + RESAMPLE_FORBIDDEN (%d hits); m5a "
          "gift-bound FLAGGED (%s); m5b branch-peek FLAGGED (%s)"
          % (len(frag), len(sc_own),
             sc_a[0] if sc_a else "MISS",
             sc_b[0] if sc_b else "MISS"))

    # ---------------- S1: census + controls (r321 scaffold verbatim)
    section("S1  CENSUS + CONTROLS + EXTENSIONS")
    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 = []
        ext = []
        ext2 = []
        okL = True
    else:
        kzs = []
        ekz = []
        ekz2 = []
        for kz in core.frame_a_zones():
            h = PIK.build_rung(kz)["h"]
            if h <= H_CAP:
                kzs.append(kz)
            elif h <= EXT_H_MAX:
                ekz.append(kz)
            elif h <= EXT2_H_MAX:
                ekz2.append((h, kz))
        ladder = [BH.wpack(kz) for kz in kzs]
        ladder.sort(key=lambda p: (p["N"], p["kz"]))
        epool = [BH.wpack(kz) for kz in ekz]
        epool.sort(key=lambda p: (p["N"], p["kz"]))
        ext = epool[:K_EXT]
        ekz2.sort()
        pool2 = epool[K_EXT:] + [BH.wpack(kz)
                                 for _h, kz in ekz2[:EXT2_POOL_CAP]]
        pool2.sort(key=lambda p: (p["N"], p["kz"]))
        ext2 = [p for p in pool2 if p["nf"] is None][:K_EXT2]
        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 "-"))
    if smoke:
        check("G12-extension-census", True, "SMOKE: skipped")
        check("G13-ext2-census", True, "SMOKE: skipped")
    else:
        check("G12-extension-census",
              len(ext) == K_EXT
              and ext[0]["N"] == EXT_NW_EXPECT[0]
              and ext[-1]["N"] == EXT_NW_EXPECT[1]
              and all(p["nf"] is None for p in ext),
              "r286-aligned extension: %d anchors, N_w %d..%d "
              "(expected %d..%d), POSITIVE_PREFIX %d/%d"
              % (len(ext), ext[0]["N"] if ext else -1,
                 ext[-1]["N"] if ext else -1, EXT_NW_EXPECT[0],
                 EXT_NW_EXPECT[1],
                 sum(1 for p in ext if p["nf"] is None), len(ext)))
        check("G13-ext2-census",
              len(ext2) <= K_EXT2
              and all(p["nf"] is None for p in ext2),
              "EXT2 (r316 A5 rule verbatim, census-grade): pool "
              "%d leftover + %d windows with %d < h <= %d; "
              "selected %d POSITIVE_PREFIX anchors, N_w %s..%s"
              % (len(epool) - K_EXT, min(len(ekz2), EXT2_POOL_CAP),
                 EXT_H_MAX, EXT2_H_MAX, len(ext2),
                 ext2[0]["N"] if ext2 else "-",
                 ext2[-1]["N"] if ext2 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)
        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
        v2w = BR.eval_scaled(rows, xu, N - 2)
        cw = wu * xu * v2w * fac
        o = np.argsort(bx, kind="stable")
        return dict(kz=p["kz"], N=N, g_branch=g,
                    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, nf=p["nf"])

    recs = [rung_rec(p) for p in pool]
    erecs = [rung_rec(p) for p in ext] if not smoke else []
    e2recs = [rung_rec(p) for p in ext2] if not smoke else []
    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:
        e_cheap = sum(1 for rc in erecs + e2recs
                      if rc["g_branch"] >= 0.0)
        e_exc = [rc["kz"] for rc in erecs + e2recs
                 if rc["g_branch"] < 0.0]
        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; "
              "EXT+EXT2 census (no sealed expectation): %d cheap "
              "/ %d exception %s"
              % (len(cheap), str(exc_kz),
                 "; ".join("w%d g %+.3f CHEAP" % (rc["kz"],
                                                  rc["g_branch"])
                           for rc in mrecs),
                 e_cheap, len(e_exc), str(e_exc)))

    # ---------------- S2: decomposition wards + eval
    section("S2  EXACT DECOMPOSITION + ATOMIC PRESENTATION WARDS")
    tb_worst = 0.0
    tb_deep = 0.0
    tb_ext = 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 rc in erecs + e2recs:
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(float(np.sum(np.abs(rc["ct"]))), 1e-300)
        tb_ext = max(tb_ext, 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_ext <= TB_WARD_BAR_DEEP
          and tb_ctrl <= TB_WARD_BAR_CTRL,
          "sum_b ct_b == t_{N-2} on %d rungs + %d ext + %d ext2 "
          "+ %d mains + 3 controls: worst dev/absmass %.1e main "
          "N<=%d (bar %.0e) / %.1e deep / %.1e ext+ext2 (bar "
          "%.0e) / %.1e controls (bar %.0e)"
          % (len(recs), len(erecs), len(e2recs), len(mrecs),
             tb_worst, DEEP_N, TB_WARD_BAR, tb_deep, tb_ext,
             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)
        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)
        brk, m, jb = WBT.block_breaks(xb, runs)
        Pb = np.bincount(jb, weights=cb, minlength=m) \
            if m else np.zeros(0)
        Pw = WBT.aggregate_blocks(rc["xu"], rc["cw"], rc["lo"],
                                  rc["hi"], brk, m)
        Pd = Pb - Pw
        cm = RY3.cubic_moments(Pd)
        absm = float(np.sum(np.abs(rc["ct"]))) \
            + float(np.sum(np.abs(rc["cw"])))
        degenerate = (cm["L1"] <= DEG_FLOOR * absm)
        # ---- raw atomic presentation (r313/r314 convention):
        edw = PBB.mask_edge(rc["xu"], rc["lo"], rc["hi"], EDGE_F)
        xw = rc["xu"][~edw]
        vw = -rc["cw"][~edw]
        jw = np.searchsorted(brk, xw) if m else np.zeros(0, int)
        jb2 = np.searchsorted(brk, xb) if m else np.zeros(0, int)
        mism = int(np.sum(jb2 != jb))
        pos_all = np.concatenate([xb, xw])
        val_all = np.concatenate([cb, vw])
        blk_all = np.concatenate([jb, jw]).astype(int)
        if m and not degenerate:
            gen = SCF.fold_genealogy(pos_all, val_all, blk_all, m)
            sct = SCF.signed_cube_terms(gen["G1"], gen["gblk"], m)
            ft = SCF.flux_telescope(gen["G1"], gen["ptr"], m)
            cc = SCF.collision_census(gen["mult"], gen["ptr"], m)
            x_dev = float(np.max(np.abs(sct["x"] - Pd))
                          / max(np.max(np.abs(Pd)), 1e-300))
            sig = sct["sig"]
            cube = sct["cube"]
            A1 = np.bincount(blk_all, weights=np.abs(val_all),
                             minlength=m)
            scale3 = float(np.sum(A1 ** 3))
            sc_j = np.maximum(A1 ** 3, 1e-300)
            C_far_flux = float(np.sum(sig * ft["F_end"]))
            C_bnd = float(np.sum(sig * ft["F_open"]))
            rec3 = abs(C_far_flux + sct["C_pair"] + sct["C_full"]
                       + C_bnd - cube) / max(scale3, 1e-300)
            tel_dev = float(np.max(np.abs(ft["F_end"]
                                          - sct["far"]) / sc_j))
            bnd_dev = float(np.max(np.abs(ft["F_open"]) / sc_j))
            mx_mult = int(np.max(gen["mult"])) if gen["ng"] else 0
            ph = PHI.phi3_variants(sct["x"], sct["Q2"], sct["Q3"],
                                   ft["F_end"], ft["F_open"],
                                   ft["edge_abs"], m)
            trs = TRB.two_regime_state(sct["x"], sct["Q2"],
                                       sct["Q3"], gen["G1"],
                                       gen["ptr"], ft["F_end"],
                                       ft["F_open"],
                                       ft["edge_abs"], m)
            rho2 = RY3.renyi3_ratio(cm["S3"], m, 2)
            mqs = m2_qmax_state(sct["x"])
            spf = spike_factors(sct["x"], A1)
            natm = np.bincount(blk_all, minlength=m)
            jst = spf["j"]
            k_j = int(natm[jst])
            mult_j = int(np.max(gen["mult"][gen["ptr"][jst]:
                                            gen["ptr"][jst + 1]])) \
                if gen["ptr"][jst + 1] > gen["ptr"][jst] else 0
            d_edge = min(jst, m - 1 - jst) / max(m - 1, 1)
        else:
            gen = sct = ft = cc = None
            x_dev = 0.0
            cube = 0.0
            rec3 = tel_dev = bnd_dev = 0.0
            C_bnd = 0.0
            mx_mult = 0
            A1 = np.zeros(0)
            ph = dict(a=0.0, b=0.0, c=0.0, nrm=0.0, dflux=0.0,
                      coll=0.0, bnd=0.0, fcix=0.0, L=0.0)
            trs = dict(nrm=0.0, coll=0.0, dflux=0.0, bnd=0.0,
                       fe=0.0, fcix=0.0, qmax=0.0, cnt3=0.0,
                       phiL1=0.0, phiL2=0.0, phiH1=0.0,
                       phiH2=0.0, L=0.0)
            rho2 = 0.0
            mqs = dict(qm=0.0, m2=0.0, ymx=0.0, maj=0.0)
            spf = dict(s=0.0, a=0.0, j=0)
            k_j = 0
            mult_j = 0
            d_edge = 0.0
        return dict(alt_ok=alt_ok, R=R, P=P, m=m, Pd=Pd, cm=cm,
                    degenerate=degenerate, mism=mism, x_dev=x_dev,
                    cube=cube, rec3=rec3, tel_dev=tel_dev,
                    bnd_dev=bnd_dev, C_bnd=C_bnd,
                    mx_mult=mx_mult, gen=gen, sct=sct, ft=ft,
                    cc=cc, ph=ph, trs=trs, rho2=rho2, A1=A1,
                    mqs=mqs, spf=spf, k_j=k_j, mult_j=mult_j,
                    d_edge=d_edge, pos_all=pos_all,
                    val_all=val_all, blk_all=blk_all, brk=brk)

    all_rc = recs + mrecs + erecs + e2recs
    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)))

    live = [rc for rc in pool_all if not rc["ev"]["degenerate"]]
    deg_note = [c for c in crecs if crecs[c]["ev"]["degenerate"]]
    x_w = max(rc["ev"]["x_dev"] for rc in live)
    mism_tot = sum(rc["ev"]["mism"] for rc in pool_all)
    check("G22-genealogy-completeness",
          x_w <= ATOM_BAR and mism_tot == 0,
          "the r314 fold genealogy covers every block value on %d "
          "live worlds (group-sum dev %.1e, bar %.0e); run "
          "assignment == breakpoint search (%d mismatches)%s"
          % (len(live), x_w, ATOM_BAR, mism_tot,
             "; DEGENERATE guard fired (pre-declared): "
             + ", ".join(deg_note) if deg_note else ""))

    # ---------------- S3: Leg 0 anchors (slim set, disclosed)
    section("S3  LEG 0 -- ANCHOR REGRESSION (slim: identity + "
            "r306/r316/r317/r321)")
    rec3_w = max(rc["ev"]["rec3"] for rc in live)
    tel_w = max(rc["ev"]["tel_dev"] for rc in live)
    bnd_w = max(rc["ev"]["bnd_dev"] for rc in live)
    check("G30-r314-identity-wards",
          rec3_w <= REC3_BAR and tel_w <= TEL_BAR
          and bnd_w <= BND_BAR,
          "the r314 identity live on %d live worlds: three-term "
          "recomposition dev %.1e (bar %.0e), telescope dev %.1e "
          "(bar %.0e), boundary %.1e (bar %.0e); DISCLOSED slim "
          "anchor set -- the full r314/r315 chain is re-warded "
          "by the coexisting r321/r322 probes in the same suite"
          % (len(live), rec3_w, REC3_BAR, tel_w, TEL_BAR, bnd_w,
             BND_BAR))
    if smoke:
        ev9s = recs[0]["ev"]
        info("SMOKE: w9 qmax %.4f m2 %.4f ymax %.2f maj %.4f "
             "sigma %.4f s %.4f a %.4f"
             % (ev9s["trs"]["qmax"], ev9s["mqs"]["m2"],
                ev9s["mqs"]["ymx"], ev9s["mqs"]["maj"],
                ev9s["rho2"] / max(ev9s["trs"]["phiH1"], 1e-300),
                ev9s["spf"]["s"], ev9s["spf"]["a"]))
        check("G31-r306-bound-live", True, "SMOKE: skipped")
        check("G32-r316-anchors", True, "SMOKE: skipped")
        check("G33-r317-anchors", True, "SMOKE: skipped")
        check("G34-r321-sliding-anchor", True, "SMOKE: skipped")
        srt = []
        n324 = 0
    else:
        srt57 = sorted(recs + erecs,
                       key=lambda rc: (rc["N"], rc["kz"]))
        rhoT2 = [rc["ev"]["rho2"] for rc in srt57]
        C2, _j, _d = RY3.calib_freeze(rhoT2, range(N_CAL))
        viol2 = sum(1 for v in rhoT2 if v > C2)
        check("G31-r306-bound-live",
              abs(C2 - R306_C2) <= R306_C2_TOL and viol2 == 0,
              "r306 pointwise bound live at A = 2: C_2 %.3f (rec "
              "%.3f tol %.3f, first-%d freeze), violations %d/%d"
              % (C2, R306_C2, R306_C2_TOL, N_CAL, viol2,
                 len(srt57)))
        srt_all = sorted(recs + erecs + e2recs,
                         key=lambda rc: (rc["N"], rc["kz"]))
        srt = [rc for rc in srt_all
               if rc["ev"]["mx_mult"] <= MULT_CAP]
        n324 = len(srt)
        rho_all = [rc["ev"]["rho2"] for rc in srt]
        m_all = [rc["ev"]["m"] for rc in srt]
        rho_kz = {rc["kz"]: rc["ev"]["rho2"] for rc in srt}
        sm_i, ca_i, te_i = TRB.split_midladder(n324)
        C_small = max(rho_all[i] for i in sm_i)
        j_cs = max(sm_i, key=lambda i: rho_all[i])
        check("G32-r316-anchors",
              n324 == N324_REF
              and all(abs(rho_kz.get(kz, -1.0) - R316_RHO[kz])
                      <= R316_RHO_TOL for kz in R316_RHO)
              and abs(C_small - R316_CSMALL) <= R316_CSMALL_TOL
              and srt[j_cs]["kz"] == R316_CSMALL_KZ,
              "r316 anchors reproduced: class ladder n = %d (rec "
              "%d); rho kz53/kz67/kz55/kz83 = %.4f/%.4f/%.4f/"
              "%.4f (rec %.4f/%.4f/%.4f/%.4f tol %.3f); C_small "
              "%.4f @ kz%d (rec %.4f @ kz%d)"
              % (n324, N324_REF, rho_kz.get(53, -1.0),
                 rho_kz.get(67, -1.0), rho_kz.get(55, -1.0),
                 rho_kz.get(83, -1.0), R316_RHO[53],
                 R316_RHO[67], R316_RHO[55], R316_RHO[83],
                 R316_RHO_TOL, C_small, srt[j_cs]["kz"],
                 R316_CSMALL, R316_CSMALL_KZ))
        qmax_col = [rc["ev"]["trs"]["qmax"] for rc in srt]
        phiL2_col = [rc["ev"]["trs"]["phiL2"] for rc in srt]
        FA_real = EFP.local_ratio(qmax_col)
        FB = EFP.local_ratio(phiL2_col)
        thrB, kB, gB = EFP.gap_threshold(FB)
        memB = tuple(sorted(srt[i]["kz"]
                            for i, v in enumerate(FB)
                            if v >= thrB))
        ordFA = sorted(range(n324), key=lambda i: -FA_real[i])
        top3_kz = tuple(srt[i]["kz"] for i in ordFA[:3])
        top3_val = {srt[i]["kz"]: FA_real[i] for i in ordFA[:3]}
        check("G33-r317-anchors",
              top3_kz == R317_FA_ORDER
              and all(abs(top3_val[kz] - R317_FA_TOP[kz])
                      <= R317_FA_TOL for kz in R317_FA_TOP)
              and memB == tuple(sorted(R317_B_KZ))
              and abs(thrB - R317_THRB) <= R317_THRB_TOL,
              "r317 anchors reproduced: F_A top-3 %s = "
              "%.2f/%.2f/%.2f (rec %s = %.2f/%.2f/%.2f tol "
              "%.2f, ORDERED); gap-B %s THR_B %.4f (rec %s / "
              "%.4f tol %.3f)"
              % (str(top3_kz), top3_val.get(top3_kz[0], -1),
                 top3_val.get(top3_kz[1], -1),
                 top3_val.get(top3_kz[2], -1),
                 str(R317_FA_ORDER), R317_FA_TOP[53],
                 R317_FA_TOP[83], R317_FA_TOP[67], R317_FA_TOL,
                 str(memB), thrB,
                 str(tuple(sorted(R317_B_KZ))), R317_THRB,
                 R317_THRB_TOL))
        medloc = CCP.local_median(qmax_col)
        Bcol = [medloc[i] * float(m_all[i])
                / math.log(float(m_all[i])) for i in range(n324)]
        parSQ, dSQ = CCP.g_calibrate("SQ", FA_real, rho_all,
                                     Bcol, ca_i)
        gv_sq = [CCP.g_eval("SQ", parSQ, FA_real[i])
                 for i in range(n324)]
        viol_sq = [i for i in te_i if rho_all[i] > gv_sq[i]]
        named_rank = {}
        for kz in NAMED_KZ:
            for i in range(n324):
                if srt[i]["kz"] == kz:
                    named_rank[kz] = i
        named_sq = sum(1 for kz in NAMED_KZ
                       if rho_all[named_rank[kz]]
                       <= gv_sq[named_rank[kz]])
        check("G34-r321-sliding-anchor",
              abs(parSQ[0] - R321_B_SQ) <= R321_B_TOL
              and not viol_sq and named_sq == 4
              and dSQ == tuple(ca_i),
              "r321 sliding bound reproduced: G_SQ b = %.4f (rec "
              "%.4f tol %.3f, = B_cal_max %.4f squared, source-"
              "pure), violations %d/%d test, named coverage "
              "%d/4, declared cal set EXACT"
              % (parSQ[0], R321_B_SQ, R321_B_TOL,
                 math.sqrt(parSQ[0]), len(viol_sq), len(te_i),
                 named_sq))

    # ---------------- S4: Leg A -- seal + purity + toys + wards
    section("S4  LEG A -- SEAL + PURITY + TOYS + LIVE WARDS + "
            "SOURCE-PURE TABLE")
    pure_lits = []
    for fn in ("m2_qmax_state", "spike_factors", "donor_pool",
               "resample_qmax", "qq_groups", "fa_tree",
               "share_tree", "compose_tree", "fr_share_toys"):
        pure_lits += literal_audit(fn)
    e1_hits = scope_audit("mutant_resample_peek",
                          RESAMPLE_FORBIDDEN)
    e3_hits = scope_audit("mutant_share_posthoc", BOUND_FORBIDDEN)
    check("G40-purity-audits",
          (not sc_own) and (not pure_lits)
          and len(e1_hits) >= 1 and len(e3_hits) >= 1,
          "SOURCE PURITY: the eight module-own builders/trees "
          "clean vs the three forbidden sets (%d id hits); the "
          "nine audited functions clean vs the sealed r314+r315+"
          "r316+r317+r321 record-literal set (%d literal hits); "
          "consumed inputs: block values / atom masses / rank "
          "order / declared sets / seeds -- sigma (rho_2/PhiH1) "
          "is the disclosed TARGET-SIDE diagnostic, computed "
          "outside the builders; e1 resample-peek FLAGGED (%s); "
          "e3 share-posthoc FLAGGED (%s)"
          % (len(sc_own), len(pure_lits),
             e1_hits[0] if e1_hits else "MISS",
             e3_hits[0] if e3_hits else "MISS"))
    # toys (Fractions exact + float cross + determinism)
    fr_dev = fr_share_toys()
    st_toy = m2_qmax_state([1.0, -2.0, 3.0])
    ok_st = (abs(st_toy["qm"] - 0.5) <= FR_BAR
             and abs(st_toy["m2"] - 7.0 / 6.0) <= FR_BAR
             and abs(st_toy["ymx"] - 1.5) <= FR_BAR
             and abs(st_toy["maj"] - 7.0 / 9.0) <= FR_BAR)
    sf_toy = spike_factors([-1.0, 3.0], [3.0, 3.0])
    ok_sf = (abs(sf_toy["s"] - 1.0) <= FR_BAR
             and abs(sf_toy["a"] - 0.75) <= FR_BAR
             and abs(sf_toy["s"] * sf_toy["a"] - 0.75) <= FR_BAR)
    ones = [np.ones(4), np.ones(5), np.ones(6)]
    pl_toy, dcl_toy = donor_pool(ones, (0, 1, 2))
    rs1 = resample_qmax(pl_toy, (4, 5), 3, 777)
    rs2 = resample_qmax(pl_toy, (4, 5), 3, 777)
    rs3 = resample_qmax(np.arange(1.0, 16.0), (4, 5), 3, 778)
    ok_rs = (np.array_equal(rs1, rs2)
             and abs(float(rs1[0, 0]) - 0.25) <= FR_BAR
             and abs(float(rs1[0, 1]) - 0.2) <= FR_BAR
             and not np.array_equal(rs1, rs3))
    k_toy = UNIF.ks_two([1.0, 2.0, 3.0], [1.5, 2.5])
    Af, Bf, pf = UNIF.fs_solve(10.0, 3.0, 40.0, 1.5, 20.0)
    ok_uf = (abs(k_toy - 1.0 / 3.0) <= FR_BAR
             and abs(Af - 1.0) <= FR_BAR
             and abs(Bf - 20.0) <= FR_BAR
             and abs(pf - 2.0) <= FR_BAR)
    g1t, g2t, g3t = qq_groups(10)
    ok_gr = (len(set(g1t) & set(g2t)) == 0
             and len(set(g2t) & set(g3t)) == 0
             and len(set(g1t) & set(g3t)) == 0
             and tuple(sorted(g1t + g2t + g3t)) == tuple(range(10)))
    fa_br = (fa_tree(False, True, True), fa_tree(True, True, False),
             fa_tree(True, False, True), fa_tree(True, False, False))
    sh_br = (share_tree(True, True, True),
             share_tree(True, True, False),
             share_tree(False, True, True))
    co_br = (compose_tree("FA_BOUNDED_DISTRIBUTIONAL",
                          "QMAX_SHARE_PINNED"),
             compose_tree("FA_BOUNDED_STRUCTURAL",
                          "QMAX_SHARE_PINNED"),
             compose_tree("FA_OUTLIERS_REAL", "QMAX_SHARE_PINNED"),
             compose_tree("FA_BOUNDED_DISTRIBUTIONAL",
                          "QMAX_SHARE_OPEN"))
    ok_tr = (fa_br == ("FA_OUTLIERS_REAL",
                       "FA_BOUNDED_DISTRIBUTIONAL",
                       "FA_BOUNDED_STRUCTURAL", "FA_OPEN")
             and sh_br == ("QMAX_SHARE_PINNED", "QMAX_SHARE_OPEN",
                           "QMAX_SHARE_OPEN")
             and co_br == ("PROVENANCE_COMPOSED",
                           "PROVENANCE_COMPOSED", "NOT_COMPOSED",
                           "NOT_COMPOSED"))
    check("G41-toy-exactness",
          fr_dev == 0 and ok_st and ok_sf and ok_rs and ok_uf
          and ok_gr and ok_tr,
          "Fractions share toys EXACT (worst rational dev %s): "
          "sigma 2/3 in [1/2, 1], m2 7/6, ymax 3/2, majorant 7/9 "
          "slack 1/9; flat double EQUALITY; one-block lower "
          "EQUALITY; float builder cross-ward <= %.0e; factor "
          "toy s 1 x a 3/4 == QMAX 3/4 EXACT; resampler: same "
          "seed identical, ones-pool QMAX* == 1/m EXACT, other "
          "seed differs; r302 import toys exact (ks 1/3, fs (1, "
          "20, 2)); groups toy disjoint + covering EXACT; "
          "verdict trees fa %s / share %s / compose %s EXACT"
          % (str(fr_dev), FR_BAR, str(fa_br), str(sh_br),
             str(co_br)))
    # live wards: r316 chain + share bracket + majorant + recon
    chain_w = 0.0
    xw_cube = 0.0
    brk_low = 0.0
    maj_w = 0.0
    sa_w = 0.0
    sig_id_w = 0.0
    for rc in live:
        ev = rc["ev"]
        trs = ev["trs"]
        nc = trs["nrm"] * ev["cube"]
        xw_cube = max(xw_cube, abs(nc - ev["rho2"])
                      / max(ev["rho2"], 1e-300))
        for a, b in ((nc, trs["phiL1"]),
                     (trs["phiL1"], trs["phiL2"]),
                     (trs["phiL2"], trs["phiH2"]),
                     (nc, trs["phiH1"])):
            chain_w = max(chain_w,
                          max(0.0, a - b) / max(b, 1e-300))
        sg = ev["rho2"] / max(trs["phiH1"], 1e-300)
        # share bracket qmax <= sigma <= 1 (the r321 bracket)
        brk_low = max(brk_low,
                      max(0.0, trs["qmax"] - sg),
                      max(0.0, sg - 1.0))
        # NEW share majorant sigma <= m2/ymax (exact algebra)
        maj_w = max(maj_w, max(0.0, sg - ev["mqs"]["maj"])
                    / max(ev["mqs"]["maj"], 1e-300))
        # sigma identity vs the direct cubic form (target-side)
        x_abs = np.abs(ev["sct"]["x"])
        Lx = float(np.sum(x_abs))
        qv = x_abs / max(Lx, 1e-300)
        sg2 = float(np.sum(qv ** 3)) \
            / max(float(np.max(qv)) ** 2, 1e-300)
        sig_id_w = max(sig_id_w, abs(sg - sg2) / max(sg2, 1e-300))
        # NEW factorization QMAX == s x a
        sa_w = max(sa_w, abs(trs["qmax"]
                             - ev["spf"]["s"] * ev["spf"]["a"])
                   / max(trs["qmax"], 1e-300))
    if smoke:
        rec_fa = 0.0
        ph_dev = 0.0
    else:
        rec_fa = max(abs(qmax_col[i] - FA_real[i] * medloc[i])
                     / max(qmax_col[i], 1e-300)
                     for i in range(n324))
        ph_dev = max(abs(srt[i]["ev"]["trs"]["phiH1"]
                         - (FA_real[i] * Bcol[i]) ** 2)
                     / max(srt[i]["ev"]["trs"]["phiH1"], 1e-300)
                     for i in range(n324))
    check("G42-live-wards",
          chain_w <= CHAIN_BAR and xw_cube <= XW_BAR
          and brk_low <= CHAIN_BAR and maj_w <= CHAIN_BAR
          and sig_id_w <= CHAIN_BAR and sa_w <= SA_BAR
          and rec_fa <= 1e-12 and ph_dev <= CHAIN_BAR,
          "the r316 chain live on %d live worlds (worst slack "
          "%.1e); NORM x cube == rho_2 (%.1e); share bracket "
          "qmax <= sigma <= 1 (worst %.1e); NEW share majorant "
          "sigma <= m2/ymax (worst rel slack %.1e -- the "
          "median-of-max route is algebra-live); sigma == "
          "sum q^3/qmax^2 identity (%.1e); NEW factorization "
          "QMAX == s x a (worst %.1e, bar %.0e)%s"
          % (len(live), chain_w, xw_cube, brk_low, maj_w,
             sig_id_w, sa_w, SA_BAR,
             "; ladder recon QMAX == F_A x medloc %.1e, PhiH1 "
             "== (F_A B)^2 %.1e" % (rec_fa, ph_dev)
             if not smoke else " (ladder wards SMOKE-skipped)"))
    if smoke:
        check("G43-coordinate-table", True, "SMOKE: skipped")
    else:
        s_col = [rc["ev"]["spf"]["s"] for rc in srt]
        a_col = [rc["ev"]["spf"]["a"] for rc in srt]
        m2_col = [rc["ev"]["mqs"]["m2"] for rc in srt]
        info("sealed SOURCE-PURE coordinate/factor table "
             "(printed BEFORE any bound-side or resample table "
             "of this round): rank kz N m QMAX F_A medloc B s a "
             "m2")
        for i, rc in enumerate(srt):
            info("%2d kz%-3d N %4d m %3d qmax %.4f FA %5.2f "
                 "med %.4f B %.4f s %.3f a %.4f m2 %.3f"
                 % (i, rc["kz"], rc["N"], m_all[i], qmax_col[i],
                    FA_real[i], medloc[i], Bcol[i], s_col[i],
                    a_col[i], m2_col[i]))
        check("G43-coordinate-table", True,
              "F_A range min/med/max %.2f/%.2f/%.2f (max at "
              "kz%d); s range %.3f..%.3f (survival <= 1 exact); "
              "a range %.4f..%.4f; m2 range %.3f..%.3f (med "
              "%.3f; the r302 med was ~2.03 on the 42-rung "
              "core, census)"
              % (min(FA_real), float(np.median(FA_real)),
                 max(FA_real),
                 srt[int(np.argmax(FA_real))]["kz"],
                 min(s_col), max(s_col), min(a_col), max(a_col),
                 min(m2_col), max(m2_col),
                 float(np.median(m2_col))))

    # ---------------- S5: Leg B -- the distributional route
    section("S5  LEG B -- DISTRIBUTIONAL ROUTE (stationary-null "
            "resample)")
    if smoke:
        check("G50-donor-seal", True, "SMOKE: skipped")
        check("G51-resample-census", True, "SMOKE: skipped")
    else:
        y_lists = []
        for rc in srt:
            x_abs = np.abs(rc["ev"]["sct"]["x"])
            Lx = float(np.sum(x_abs))
            y_lists.append(x_abs * (float(rc["ev"]["m"]) / Lx))
        spike_ranks = tuple(sorted(named_rank[kz]
                                   for kz in NAMED_FA_KZ))
        donors_sealed = tuple(i for i in range(n324)
                              if i not in spike_ranks)
        pool_y, dcl_don = donor_pool(y_lists, donors_sealed)
        check("G50-donor-seal", dcl_don == donors_sealed,
              "donor pool sealed: %d donor rungs (the ladder "
              "minus the named spike ranks %s = kz %s), %d "
              "pooled normalized values; declared set == sealed "
              "complement EXACT (the e2 mutant declares the "
              "spike ranks and is CAUGHT in S8)"
              % (len(donors_sealed), str(spike_ranks),
                 str([srt[i]["kz"] for i in spike_ranks]),
                 len(pool_y)))
        qs_rs = resample_qmax(pool_y, m_all, NRS, SEED_RS)
        FA_rs = np.array([EFP.local_ratio(list(qs_rs[r]))
                          for r in range(NRS)])
        ks_qq = UNIF.ks_two(FA_real, FA_rs.ravel())
        max_real = max(FA_real)
        max_rs = FA_rs.max(axis=1)
        p_max = float(np.mean(max_rs >= max_real))
        p_named = {kz: float(np.mean(FA_rs[:, named_rank[kz]]
                                     >= FA_real[named_rank[kz]]))
                   for kz in NAMED_FA_KZ}
        C_F_env = float(FA_rs.max())
        q95 = float(np.quantile(max_rs, 0.95))
        dist_ok = ks_qq <= KS_FA
        spikes_within = p_max >= P_MIN
        check("G51-resample-census", True,
              "RESAMPLE census (%d replicates, seed %d): "
              "KS(F_A real %d, F_A* pooled %d) = %.4f %s %.3f; "
              "per-named p at rank: %s; p_max = %.3f %s %.2f "
              "(real ladder max %.2f vs replicate-max q95 %.3f, "
              "envelope C_F = %.3f)"
              % (NRS, SEED_RS, n324, FA_rs.size, ks_qq,
                 "<=" if dist_ok else ">", KS_FA,
                 str({("kz%d" % kz): round(p_named[kz], 3)
                      for kz in NAMED_FA_KZ}),
                 p_max, ">=" if spikes_within else "<", P_MIN,
                 max_real, q95, C_F_env))

    # ---------------- S6: Leg C -- the structural route
    section("S6  LEG C -- STRUCTURAL ROUTE (factorization census "
            "+ F_A adjudication)")
    if smoke:
        check("G60-factor-census", True, "SMOKE: skipped")
        check("G61-struct-bound-census", True, "SMOKE: skipped")
        check("G62-fa-adjudication", True, "SMOKE: skipped")
        fa_verdict = "SMOKE_NO_ADJUDICATION"
    else:
        F_s = EFP.local_ratio(s_col)
        F_a = EFP.local_ratio(a_col)
        info("named-spike attribution (rank-local factor ratios, "
             "window W = %d): kz F_A F_s F_a carrier | argmax-"
             "block geometry: atoms multmax edge-dist"
             % EFP.CLS_W)
        carriers = []
        for kz in NAMED_FA_KZ:
            i = named_rank[kz]
            car = "a" if F_a[i] >= F_s[i] else "s"
            carriers.append((kz, car, F_s[i], F_a[i]))
            ev = srt[i]["ev"]
            info("  kz%-3d FA %.2f Fs %.2f Fa %.2f carrier %s | "
                 "atoms %d multmax %d dedge %.2f"
                 % (kz, FA_real[i], F_s[i], F_a[i], car,
                    ev["k_j"], ev["mult_j"], ev["d_edge"]))
        med_k = float(np.median([rc["ev"]["k_j"] for rc in srt]))
        med_mu = float(np.median([rc["ev"]["mult_j"]
                                  for rc in srt]))
        med_de = float(np.median([rc["ev"]["d_edge"]
                                  for rc in srt]))
        common = (len(set(c for _kz, c, _fs, _fa in carriers))
                  == 1)
        car0 = carriers[0][1]
        car_vals = [(fa if car0 == "a" else fs)
                    for _kz, _c, fs, fa in carriers]
        oth_vals = [(fs if car0 == "a" else fa)
                    for _kz, _c, fs, fa in carriers]
        struct_common = (common and min(car_vals) >= STRUCT_MIN
                         and max(oth_vals) <= OTHER_MAX)
        check("G60-factor-census", True,
              "factor censuses: F_s med %.2f max %.2f / F_a med "
              "%.2f max %.2f; named carriers %s -> common = %s "
              "(sealed rule: one factor >= %.1f on 3/3 while "
              "the other <= %.2f -> %s); geometry census: "
              "ladder med atoms %.0f / multmax %.0f / edge-dist "
              "%.2f (the named-spike rows printed above)"
              % (float(np.median(F_s)), max(F_s),
                 float(np.median(F_a)), max(F_a),
                 str([(kz, c) for kz, c, _f, _g in carriers]),
                 common, STRUCT_MIN, OTHER_MAX,
                 "PASS" if struct_common else "FAIL",
                 med_k, med_mu, med_de))
        FAB = [a_col[i] / max(medloc[i], 1e-300)
               for i in range(n324)]
        fab_ward = max(max(0.0, FA_real[i] - FAB[i])
                       / max(FAB[i], 1e-300)
                       for i in range(n324))
        C_FAB = max(FAB[i] for i in ca_i)
        viol_fab = [i for i in te_i if FAB[i] > C_FAB]
        struct_cert = (not viol_fab)
        struct_ok = struct_common and struct_cert
        check("G61-struct-bound-census", fab_ward <= CHAIN_BAR,
              "the EXACT structural majorant F_A <= FAB = "
              "a/medloc (via s <= 1; live ward worst slack "
              "%.1e): cal max C_FAB = %.4f vs test max %.4f "
              "(ratio %.2f); test violations %d/%d %s -> "
              "structural certification %s"
              % (fab_ward, C_FAB, max(FAB[i] for i in te_i),
                 max(FAB[i] for i in te_i) / max(C_FAB, 1e-300),
                 len(viol_fab), len(te_i),
                 str([srt[i]["kz"] for i in viol_fab])
                 if viol_fab else "[]",
                 "PASS" if struct_cert else "FAIL"))
        fa_verdict = fa_tree(spikes_within, dist_ok, struct_ok)
        det_fa = {
            "FA_OUTLIERS_REAL":
                "p_max %.3f < %.2f -- the named spikes are NOT "
                "a stationarity fluctuation (per-rank p %s); "
                "the F_A bulk QQ census: KS %.4f %s %.3f"
                % (p_max, P_MIN,
                   str({("kz%d" % kz): round(p_named[kz], 3)
                        for kz in NAMED_FA_KZ}), ks_qq,
                   "<=" if dist_ok else ">", KS_FA),
            "FA_BOUNDED_DISTRIBUTIONAL":
                "p_max %.3f >= %.2f AND KS %.4f <= %.3f -- "
                "F_A <= C_F = %.3f (resampled envelope) is a "
                "distribution-statement candidate"
                % (p_max, P_MIN, ks_qq, KS_FA, C_F_env),
            "FA_BOUNDED_STRUCTURAL":
                "the structural route certifies (common carrier "
                "%s, C_FAB %.4f, 0 test violations)"
                % (car0, C_FAB),
            "FA_OPEN":
                "neither route certifies (p_max %.3f, KS %.4f, "
                "struct_common %s, struct_cert %s)"
                % (p_max, ks_qq, struct_common, struct_cert)}
        check("G62-fa-adjudication", True,
              "exactly one sealed F_A letter fired: %s(%s)"
              % (fa_verdict, det_fa[fa_verdict]))

    # ---------------- S7: Leg D -- the share route
    section("S7  LEG D -- SHARE ROUTE (M_2 stationarity -> "
            "pointwise share bound)")
    if smoke:
        check("G70-stationarity", True, "SMOKE: skipped")
        check("G71-share-anatomy", True, "SMOKE: skipped")
        check("G72-m2-certification", True, "SMOKE: skipped")
        check("G73-share-adjudication", True, "SMOKE: skipped")
        sh_verdict = "SMOKE_NO_ADJUDICATION"
    else:
        g1, g2, g3 = qq_groups(n324)
        ovl = (len(set(g1) & set(g2)) + len(set(g2) & set(g3))
               + len(set(g1) & set(g3)))
        pool1 = np.concatenate([y_lists[i] for i in g1])
        pool2 = np.concatenate([y_lists[i] for i in g2])
        pool3 = np.concatenate([y_lists[i] for i in g3])
        ks13 = UNIF.ks_two(pool1, pool3)
        ks23 = UNIF.ks_two(pool2, pool3)
        ks12 = UNIF.ks_two(pool1, pool2)
        stationary = (ks13 <= KS_STAT and ks23 <= KS_STAT)
        m2_med = [float(np.median([m2_col[i] for i in g]))
                  for g in (g1, g2, g3)]
        N_med = [float(np.median([srt[i]["N"] for i in g]))
                 for g in (g1, g2, g3)]
        A_fs, B_fs, pred2 = UNIF.fs_solve(N_med[0], m2_med[0],
                                          N_med[2], m2_med[2],
                                          N_med[1])
        fs_dev = abs(pred2 - m2_med[1]) / max(m2_med[1], 1e-300)
        check("G70-stationarity",
              ovl == 0 and stationary,
              "STATIONARITY on THIS %d-rung ladder (three "
              "(N, kz)-sorted thirds %d/%d/%d, pooled "
              "normalized profiles %d/%d/%d values, overlaps "
              "%d): KS(G1,G3) %.4f / KS(G2,G3) %.4f / KS(G1,G2) "
              "%.4f vs the sealed %.3f -> %s; m2 group medians "
              "%.3f/%.3f/%.3f; 1/N census (imported r302 "
              "fs_solve, no bar): m2_inf = A = %.3f (r302 rec "
              "%.3f on the 42-rung core, dev %.3f), B = %+.1f, "
              "held-out dev %.3f (%s %.2f census)"
              % (n324, len(g1), len(g2), len(g3), len(pool1),
                 len(pool2), len(pool3), ovl, ks13, ks23, ks12,
                 KS_STAT,
                 "STATIONARY" if stationary else "DRIFTING",
                 m2_med[0], m2_med[1], m2_med[2], A_fs,
                 M2INF_REF, abs(A_fs - M2INF_REF), B_fs, fs_dev,
                 "<=" if fs_dev <= FS_BAR else ">", FS_BAR))
        sig_col = [srt[i]["ev"]["rho2"]
                   / max(srt[i]["ev"]["trs"]["phiH1"], 1e-300)
                   for i in range(n324)]
        maj_col = [srt[i]["ev"]["mqs"]["maj"] for i in range(n324)]
        tight = [sig_col[i] / max(maj_col[i], 1e-300)
                 for i in range(n324)]
        info("share anatomy (target-side sigma = rho_2/PhiH1, "
             "bound-side majorant m2/ymax): rank kz m qmax "
             "sigma maj tight [set]")
        setlab = {}
        for i in sm_i:
            setlab[i] = "SMALL"
        for i in ca_i:
            setlab[i] = "CAL"
        for i in te_i:
            setlab[i] = "TEST"
        for i in range(n324):
            info("%2d kz%-3d m %3d qmax %.4f sig %.4f maj %.4f "
                 "tgt %.2f %s"
                 % (i, srt[i]["kz"], m_all[i], qmax_col[i],
                    sig_col[i], maj_col[i], tight[i], setlab[i]))
        NsT = [srt[i]["N"] for i in te_i]
        sl_sig = L2D.halves_slope(
            NsT, [max(sig_col[i], 1e-300) for i in te_i])
        j_dp = max((i for i in te_i), key=lambda i: sig_col[i])
        check("G71-share-anatomy", True,
              "sigma med/min/max %.4f/%.4f/%.4f (ladder max at "
              "kz%d %s; deep test max at kz%d %.3f); trend over "
              "test %+.3f (falling = the r321 mechanism 'the "
              "share falls faster than B^2 rises' measured "
              "directly); tightness sigma x ymax/m2 med %.2f "
              "max %.2f -- the m2-route reserve"
              % (float(np.median(sig_col)), min(sig_col),
                 max(sig_col),
                 srt[int(np.argmax(sig_col))]["kz"],
                 setlab[int(np.argmax(sig_col))], srt[j_dp]["kz"],
                 sig_col[j_dp], sl_sig,
                 float(np.median(tight)), max(tight)))
        C_M2 = max(m2_col[i] for i in ca_i)
        j_cm = max(ca_i, key=lambda i: m2_col[i])
        viol_m2 = [i for i in te_i if m2_col[i] > C_M2]
        comp_bound = [C_M2 * FA_real[i] * Bcol[i]
                      / math.log(float(m_all[i]))
                      for i in range(n324)]
        viol_comp = [i for i in te_i
                     if rho_all[i] > comp_bound[i]]
        named_cov = {kz: rho_all[named_rank[kz]]
                     <= comp_bound[named_rank[kz]]
                     for kz in NAMED_KZ}
        n_named = sum(1 for kz in NAMED_KZ if named_cov[kz])
        named_ok = (n_named == len(NAMED_KZ))
        cert_ok = (not viol_m2)
        check("G72-m2-certification", True,
              "C_M2 = %.4f frozen at cal (kz%d; consumes NO "
              "cubic target -- m2 is the quadratic profile "
              "moment); m2 test violations %d/%d %s; composed "
              "bound rho_2 <= C_M2 x F_A x B/log m: violations "
              "%d/%d %s (algebra cross-check); named coverage "
              "%d/4: %s"
              % (C_M2, srt[j_cm]["kz"], len(viol_m2), len(te_i),
                 str([("kz%d" % srt[i]["kz"],
                       round(m2_col[i], 4)) for i in viol_m2])
                 if viol_m2 else "[]",
                 len(viol_comp), len(te_i),
                 str([srt[i]["kz"] for i in viol_comp])
                 if viol_comp else "[]", n_named,
                 str({("kz%d" % kz):
                      ("in rsv %.2f"
                       % (comp_bound[named_rank[kz]]
                          / max(rho_all[named_rank[kz]],
                                1e-300)))
                      if named_cov[kz] else
                      ("OUT %.4f > %.4f"
                       % (rho_all[named_rank[kz]],
                          comp_bound[named_rank[kz]]))
                      for kz in NAMED_KZ})))
        sh_verdict = share_tree(stationary, cert_ok, named_ok)
        check("G73-share-adjudication", True,
              "exactly one sealed share letter fired: %s(%s)"
              % (sh_verdict,
                 ("stationary + 0 m2 violations + named 4/4: "
                  "sum q^3 <= %.4f x F_A x B x log m / m^2 "
                  "certified on the measured test rungs" % C_M2)
                 if sh_verdict == "QMAX_SHARE_PINNED" else
                 "stationary %s, m2 cert %s (%d violations), "
                 "named %d/4 -- the bulk share is majorant-"
                 "covered, the spike rungs carry the m2 excess"
                 % (stationary, cert_ok, len(viol_m2),
                    n_named)))

    # ---------------- S8: Leg E -- must-fails
    section("S8  LEG E -- WARDS / MUST-FAILS")
    toy_fa = (1.0, 1.0, 2.0)
    peek = mutant_resample_peek(toy_fa)
    hon = resample_qmax(np.ones(9), (3,), 1, 999)
    ok_e1 = (len(e1_hits) >= 1 and abs(peek - 2.0) <= FR_BAR
             and abs(peek - 3.0 * float(hon[0, 0])) >= MUT_MIN)
    check("G80-e1-resample-peek", ok_e1,
          "e1 CAUGHT twice: the peeking 'resampler' consumes the "
          "real coordinate column -- AST-FLAGGED (%s) -- and on "
          "the toy returns the real max %.1f EXACTLY while the "
          "honest ones-pool draw gives %.4f x 3 = 1.0 (diff "
          "%.1f >= %.0e)"
          % (e1_hits[0] if e1_hits else "MISS", peek,
             float(hon[0, 0]), abs(peek - 1.0), MUT_MIN))
    toy_yl = [np.ones(3) * (i + 1.0) for i in range(10)]
    toy_spk = (2, 5, 9)
    toy_don = tuple(i for i in range(10) if i not in toy_spk)
    _plr, dclr = donor_pool(toy_yl, toy_don)
    _plm, dclm = mutant_pool_spikes(toy_yl, toy_spk)
    check("G81-e2-pool-spikes",
          dclr == toy_don and dclm == toy_spk
          and dclm != toy_don,
          "e2 CAUGHT: the mutant pool declares the spike ranks "
          "%s != the sealed donor complement %s (declared-set "
          "ward EXACT) -- calibrating the stationarity profile "
          "on the rungs under adjudication is structurally "
          "refused" % (str(dclm), str(toy_don)))
    toy_F = (1.0, 1.0, 1.0)
    toy_B = (1.0, 1.0, 1.0)
    toy_m = (math.e, math.e, math.e)
    toy_r = (0.5, 1.2, 1.6667)
    mut_c = mutant_share_posthoc(toy_F, toy_B, toy_m, toy_r)
    frz_c = max(1.2 * math.log(toy_m[1])
                / (toy_F[1] * toy_B[1]), 0.0)
    check("G82-e3-share-posthoc",
          len(e3_hits) >= 1 and abs(mut_c - 1.6667) <= 1e-9
          and abs(mut_c - frz_c) >= MUT_MIN,
          "e3 CAUGHT twice: the after-sight share 'constant' "
          "consumes the evaluated bound column over the whole "
          "ladder -- AST-FLAGGED (%s) -- and on the toy returns "
          "%.4f != the frozen cal-window rule's %.4f (diff "
          "%.4f >= %.0e); the real C_M2 consumes the quadratic "
          "m2 column on the declared cal window only"
          % (e3_hits[0] if e3_hits else "MISS", mut_c, frz_c,
             abs(mut_c - frz_c), MUT_MIN))
    g1m, g2m, g3m = mutant_groups_overlap(10)
    ovl_m = (len(set(g1m) & set(g2m)), len(set(g2m) & set(g3m)))
    g1r, g2r, g3r = qq_groups(10)
    ovl_r = (len(set(g1r) & set(g2r)) + len(set(g2r) & set(g3r))
             + len(set(g1r) & set(g3r)))
    check("G83-e4-groups-overlap",
          ovl_m == (1, 1) and ovl_r == 0,
          "e4 CAUGHT: the mutant thirds share ranks %s (measured "
          "overlaps %s) while the sealed qq_groups is disjoint + "
          "covering EXACT (overlaps %d) -- an in-sample QQ "
          "cannot slip through the disjointness ward"
          % (str((set(g1m) & set(g2m), set(g2m) & set(g3m))),
             str(ovl_m), ovl_r))

    # ---------------- S9: verdict
    section("S9  VERDICT")
    if smoke:
        co_verdict = "SMOKE_NO_ADJUDICATION"
        check("G90-composition", True, "SMOKE: skipped")
    else:
        co_verdict = compose_tree(fa_verdict, sh_verdict)
        if co_verdict == "PROVENANCE_COMPOSED":
            C_uni = C_M2 * C_F_env * max(Bcol[i]
                                         / math.log(float(
                                             m_all[i]))
                                         for i in range(n324)) \
                * 1.0
            info("CANDIDATE THEOREM (bounded coordinate; "
                 "measured on the %d-rung class ladder):" % n324)
            info("  F_A <= C_F = %.3f (%s) and sigma <= "
                 "C_M2/(m qmax) with C_M2 = %.4f (mid-ladder "
                 "frozen, M_2 stationarity), hence by the r321 "
                 "bracket sum q^3 <= C_M2 x F_A x B x log m / "
                 "m^2 <= %.3f x (log m)^2/m^2 on every measured "
                 "rung -- the fiber provenance reduced to the "
                 "two named local statements about the "
                 "stationary block profile."
                 % (C_F_env, fa_verdict, C_M2, C_uni))
            check("G90-composition", True,
                  "PROVENANCE_COMPOSED: theorem candidate "
                  "printed with explicit (C_F %.3f, C_M2 %.4f, "
                  "C_uni %.3f)" % (C_F_env, C_M2, C_uni))
        else:
            check("G90-composition", True,
                  "NOT_COMPOSED (FA letter = %s + share letter "
                  "= %s); no theorem printed by seal -- the two "
                  "letters and their censuses stand as the "
                  "round's record data"
                  % (fa_verdict, sh_verdict))
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the exact share majorant sigma <= m2/(m qmax) "
          "(the M_2-stationarity transfer), the exact QMAX = s "
          "x a factorization, the sealed stationary-null "
          "resample construction for F_A and the three sealed "
          "verdict trees -- NO new certificate promoted, NO "
          "universal bound claimed beyond the measured rungs")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        parts = ["R324_ANCHORS(identity %.1e, r306 C2 %.3f viol "
                 "%d/57, r316 n %d rho4 bit-near C_small %.4f, "
                 "r317 top3 %s thrB %.4f, r321 b %.4f viol %d "
                 "named %d/4)"
                 % (rec3_w, C2, viol2, n324, C_small,
                    str(top3_kz), thrB, parSQ[0], len(viol_sq),
                    named_sq)]
        parts.append("SEAL(majorant %.1e, factorization %.1e, "
                     "purity clean, toys exact)"
                     % (maj_w, sa_w))
        parts.append("FA_DIST(KS %.4f, p_max %.3f, p_named %s, "
                     "C_F %.3f, q95 %.3f)"
                     % (ks_qq, p_max,
                        str({kz: round(p_named[kz], 3)
                             for kz in NAMED_FA_KZ}),
                        C_F_env, q95))
        parts.append("FA_STRUCT(carriers %s common %s, F_a max "
                     "%.2f, FAB cal %.4f test %.4f viol %d)"
                     % (str([c for _k, c, _f, _g in carriers]),
                        struct_common, max(F_a), C_FAB,
                        max(FAB[i] for i in te_i),
                        len(viol_fab)))
        parts.append(fa_verdict)
        parts.append("SHARE(KS %.4f/%.4f/%.4f %s, m2_inf %.3f "
                     "vs rec %.3f, sigma med %.4f trend %+.3f, "
                     "tight med %.2f, C_M2 %.4f viol %d/%d, "
                     "comp viol %d, named %d/4)"
                     % (ks13, ks23, ks12,
                        "STATIONARY" if stationary else
                        "DRIFTING", A_fs, M2INF_REF,
                        float(np.median(sig_col)), sl_sig,
                        float(np.median(tight)), C_M2,
                        len(viol_m2), len(te_i), len(viol_comp),
                        n_named))
        parts.append(sh_verdict)
        parts.append(co_verdict)
        parts.append("THEOREM(%s)"
                     % ("printed"
                        if co_verdict == "PROVENANCE_COMPOSED"
                        else "not printed"))
        parts.append("MUSTFAIL_LEDGER(e1-e4 + scopes)")
        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 share majorant "
          "chain, the factorization, the bracket, the Fractions "
          "toys, the tree logic and the purity audits (exact / "
          "AST-decided); MEASURED: every KS distance, p value, "
          "constant, violation count, trend and census (the "
          "finite class ladder + 2 mains + 2 live controls; the "
          "resample null is a DISCLOSED iid model); OPEN: any "
          "bound beyond the measured rungs, the cofinal law, "
          "the provenance of the named spike concentration, "
          "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_1 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""qmax_m2_origin_probe -- PRIME.L2.RENYI3.QMAX_M2_ORIGIN.01
(round 324): THE QMAX x M2 ORIGIN ROUND -- the reviewer-sharpened
terminal main lane after the r321 SLIDING_BOUND_GO.

COURSE CORRECTION (binding reviewer adjudication, disclosed): the
round's ORIGINAL contract PRIME.L2.RENYI3.FA_PROVENANCE.01 was
executed and sealed FIRST (fa_provenance_probe.py, 36/36, SPEC_SHA
9a6696f8, deterministic; letters FA_BOUNDED_DISTRIBUTIONAL +
QMAX_SHARE_OPEN + NOT_COMPOSED) -- then the reviewer adjudication
arrived and SUPERSEDED the contract mid-round: the F_A-boundedness
hunt is DEMOTED as a potentially "unnecessarily strong statement
that creates an artificial wall" -- for the needed power N_2 >~
m^0.888 it suffices asymptotically that F_A log m = O(m^{0.112-
eps}); even F_A = O((log m)^B) is enough; the CLEANER
decomposition is QMAX x M_2.  This probe is the round's binding
contract; the sealed pre-work record is BANKED and imported
verbatim (the r302 M_2-stationarity reproduction on the 65-rung
ladder, the m2 = m x M_2 column with its mid-ladder freeze
2.2557 and its seven test violators, the share majorant algebra)
-- every banked number is re-gated as an ANCHOR below and every
banked outcome is DISCLOSED as known pre-spec.

THE NEW CONTRACT (reviewer verbatim, four stages):
S0 -- EXACT INTERPOLATION (machine-exact, Fractions): for
   normalized positive profiles q_j = |x_j|/L (sum q = 1):
       M_3 = sum q^3  <=  q_max x M_2   with  M_2 = sum q^2,
   plus M_2 <= q_max (same algebra) -- so
       rho_2 = m^2 M_3/(log m)^2 <= (m q_max)(m M_2)/(log m)^2.
   AND the exact algebraic relation between F_A, q_max and M_2
   DISCLOSED -- F_A must not stay a black correction factor: the
   IDENTITY  F_A x B == m q_max / log m  (B = medloc x m/log m,
   r321) holds by construction and is warded live; hence the
   r321 bracket qmax PhiH1 <= rho_2 <= (F_A B)^2 = PhiH1 reads
       PhiH1 = (m q_max)^2/(log m)^2,
   and the S0 interpolation IMPROVES its upper side by exactly
   the factor M_2/q_max <= 1: F_A is the rank-local
   NORMALIZATION of m q_max, not an independent coordinate.
S1 -- M_2 EXPORT: convert the banked r302 stationarity into a
   POINTWISE statement m x M_2(w) <= C_2 for all w with m >= m_0
   -- no fit, no halves-slope, no "stationary in census":
   pointwise certification on the full ladder (65 rungs incl.
   ext/ext2) with the MID-LADDER frozen constant (TRB split
   verbatim), small-m rungs certified individually, reserve
   trend printed.  DISCLOSED pre-spec (banked pre-work of this
   same round): at the mid-ladder freeze C_2 = 2.2557 the export
   is KNOWN to fail pointwise on 7/39 test rungs incl. the three
   named near-critical rungs (m2 3.05..3.19) -- the sealed rule
   is adopted verbatim anyway (r316 convention), NOT tuned
   around the known outcome; the honest state is re-measured and
   gated as an anchor.  The r302 DISTRIBUTIONAL export
   (stationarity of the pooled normalized profile, KS thirds
   bars 0.125) is re-gated separately -- the verdict tree
   distinguishes the two.
S2 -- THE MULTISCALE MAXIMUM BOUND (the core): wanted
       m x q_max(w) <= C_inf x (log m)^A  with fixed A, ideally
   A = 1.  The reviewer mechanism hypothesis (multiscale pileup
   bound) tested explicitly with FOUR measurements:
   (1) DECOMPOSE the argmax block's mass by SOURCE SCALES: the
       r313/r314 fold genealogy provides the atoms and fold
       groups of every block; the canonical scale of an atom is
       its dyadic magnitude bin s = floor(log2 (vmax/|v|))
       relative to the rung's maximal atom (the chain-row
       Ls-factor proxy, source-pure, disclosed); the
       decomposition MUST recompose exactly:
       sum_s mass(j*, s) == A1_{j*} (warded, mutant e1 LOUD);
   (2) per position at most TWO fold ancestors hit the same
       target (the PROVEN fold multiplicity <= 2): max group
       multiplicity == 2 UNIFORM re-warded on every live world
       (mutant e2: a 3-fold toy genealogy is REFUSED);
   (3) does each scale carry at most O(1/m) of the total
       profile at one block?  MEASURED: pil(w) = m x max_s
       mass(j*, s)/L, mid-ladder frozen C_PIL, pointwise test;
   (4) are there only O(log m) relevant scales?  MEASURED:
       nsc_rel(w) = # distinct scales s <= 2 log2 m present in
       the argmax block (the tail beyond the cutoff carries
       <= n_atoms x vmax/m^2, census), frozen C_NSC =
       max cal nsc_rel/log m, pointwise test.
   THE EXACT PILEUP CHAIN (algebra, warded live):
       m q_max = m |x_{j*}|/L <= m A1_{j*}/L = sum_s m
       mass(j*, s)/L <= nsc x pil,
   so (3) + (4) compose to m q_max <= C_PIL C_NSC log m -- the
   A = 1 form with explicit constants; the DIRECT pointwise
   certification m q_max <= C_INF log m (C_INF = max cal
   G/log m) is gated alongside.  The proof side consumes ONLY:
   source genealogy, fold multiplicity, local mass balance,
   number of active scales, canonical aggregation -- NOT M_3,
   not the terminal value, not the historical killer list, not
   a per-window optimized scalar, not a post-hoc class choice
   (AST + declared-rule wards; mutants e3/e4).  THE
   NEAR-CRITICAL WINDOWS AS HARDNESS TEST: the full scale
   profile of the argmax block at kz53/kz83/kz67 is printed --
   are they cases where many admissible scales pile up near-
   maximally at the same block (then they are NOT exceptions
   but the PILEUP TIP)?
S3 -- FULL COMPOSITION (do not stop at the Renyi inequality):
   q_max x M_2 => M_3 => N_3 => N_2 => Fejer/vdC target =>
   terminal_positive_main, all constants explicit, explicit
   m_0; all m < m_0 closed by the existing finite certificates
   ON THE MEASURED LADDER (disclosed: the measured ladder ends
   at m = 274; the asymptotic threshold m_0* where
   m^{0.224} >= C log m is computed explicitly and the gap is
   typed honestly).  If S2 delivers only a subcritical growth
   exponent: COMPOSE ANYWAY -- PILEUP_GROWS_SUBCRITICAL with
   measured exponent < 0.224 SUFFICES (the reviewer's 0.112 is
   the F_A-side equivalent of the same budget: the r321 route
   is quadratic in F_A, this route is LINEAR in m q_max, so the
   budget doubles: e(m q_max/log m) + e(m M_2) < 0.224 <=>
   N_2 >~ m^0.888 asymptotically).

SEALED VERDICTS (exactly one fires; total order):
   TARGET_LEAK                iff any purity/scope audit hit on
       the mechanism builders (the proof side consumed a
       forbidden object),
   FA_RESTATEMENT             iff the mechanism decomposition
       fails structurally (recomposition or pileup-chain ward
       breaks on a live world) -- the qmax route would
       degenerate to the r321 F_A calibration,
   QMAX_MULTISCALE_GO         iff S2 certifies pointwise (all
       four mechanism clauses + direct G <= C_INF log m, 0 test
       violations, named coverage 4/4) AND S1 certifies
       pointwise AND the r302 stationarity holds,
   M2_GO_QMAX_OPEN            iff the growth-exponent decision
       is UNSTABLE (the two test halves disagree about the
       criticality side) -- the banked distributional M_2
       export state and the pointwise state are printed inside,
   PILEUP_GROWS_SUBCRITICAL(e) iff the decided total exponent
       e = e(G/log m) + e(m M_2) < CRIT = 0.224 (composition
       printed -- NOT a failure by contract),
   PILEUP_SUPERCRITICAL       iff the decided exponent >= CRIT.

EXPLORATION ONLY (2026-08-27).  experiments/ level: NO promotion,
NO ledger row, NO marker moved, NO RH CLAIM in either direction.
Coexistence: the wave-12 worker (v969) and r325 run in parallel;
this probe touches NOTHING outside its own file and the strictly
additive rh-sync (existing entries byte-identical).

THE OBJECT (r269/r287/r298/r302/r306/r314/r315/r316/r317/r321
machinery + the round's own banked pre-work 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); the frozen positional block machinery
(r298); the r306 RY3.cubic_moments + RY3.renyi3_ratio +
RY3.calib_freeze; the r314 SCF.fold_genealogy +
SCF.signed_cube_terms + SCF.flux_telescope; the r315
PHI.phi3_variants; the r316 TRB.two_regime_state +
TRB.split_midladder; the r317 EFP.local_ratio; the r321
CCP.local_median; the r302 UNIF.ks_two + UNIF.fs_solve; the
r324-pre FAP.m2_qmax_state + FAP.qq_groups, ALL imported
verbatim; PDelta = Pbeta - Pomega; x_j = (PDelta)_j.  NEW in this
round (module-own, source-pure where required): scale_bins (the
canonical dyadic source-scale binning), pileup_state (the argmax-
block scale decomposition with the exact pileup chain), mult_ward
(the fold-multiplicity refusal) and the sealed origin_tree.

LEG 0 -- ANCHOR REGRESSION (slim set + the banked r324-pre
record, disclosed): the r314 identity wards live; r306 C_2 =
1.069 (tol 0.005) first-5 freeze, 0/57; r316 rho anchors kz53/
kz67/kz55/kz83 = 1.0490/1.0536/0.4821/0.7790 (tol 0.005) +
C_small 1.0694 at kz18 + n = 65; r321 G_SQ b = 1.3056 (tol
0.005) 0/39 + named 4/4; r324-PRE BANKED anchors (the pre-work
probe of this same round, reproduced bit-near): stationarity
thirds KS(G1,G3) 0.0230 / KS(G2,G3) 0.0158 (tol 0.005), m2
column med 2.051 (tol 0.01) range up to 3.194 (tol 0.01),
mid-ladder m2 freeze 2.2557 (tol 0.005) with the seven test
violators == {kz53, kz67, kz83, kz76, kz61, kz28, kz109} EXACT
as a set.

LEG A -- SEAL + PURITY + TOYS + LIVE WARDS: (A1) sealed
definitions printed; the SOURCE-PURE table (rank, kz, N, m,
qmax, G = m qmax, G/log m, m M_2, nsc, nsc_rel, pil) printed
BEFORE any certification table.  (A2) SOURCE-PURITY AUDITS: the
AST identifier scan over scale_bins + pileup_state + mult_ward +
origin_tree must be clean against BOUND_FORBIDDEN +
PHI3_FORBIDDEN (no M_3 read-back, no terminal value, no killer
list, no per-window scalar); the literal scan over the builders
must be clean against the sealed record-literal set
R324B_TABLE_LITERALS (the r314..r321 set UNION the r321 + r324-
pre record numbers); e3/e4 prove the audits bite.  (A3) TOY
EXACTNESS (Fractions): the interpolation toy q = (1/6, 1/3,
1/2): M_3 = 1/6 <= qmax M_2 = 7/36 (slack 1/36 EXACT), M_2 =
7/18 <= qmax = 1/2; the flat toy (1/2, 1/2): DOUBLE EQUALITY
M_3 = qmax M_2 = 1/4 and M_2 = qmax (the interpolation is sharp
at flat); the one-block toy (1, 0): equality at full
concentration; the PILEUP toy (block j* atoms (4, 2, 1) at
scales (0, 1, 2), second block (1), all positive): x = (7, 1),
m qmax = 7/4, per-scale m x share = (1, 1/2, 1/4), pil = 1, nsc
= 3, chain 7/4 <= 3 EXACT (slack 5/4), recomposition 4 + 2 + 1
== A1 = 7 EXACT; the drop-scale mutant breaks the recomposition
by exactly 1 (LOUD); the 3-fold toy genealogy is REFUSED by
mult_ward; the origin_tree on all six branches EXACT.  (A4)
LIVE WARDS on every live world: the r316 chain + NORM x cube ==
rho_2 (r321 verbatim); rho_2 == m^2 M_3/(log m)^2 (the r306
NORM identity restated); THE S0 INTERPOLATION M_3 <= qmax x M_2
AND M_2 <= qmax (exact algebra, bar CHAIN_BAR); THE S0 IDENTITY
F_A x B x log m == m x qmax on the ladder (F_A is no black
factor); THE PILEUP CHAIN m qmax <= nsc x pil AND the exact
recomposition sum_s mass(j*, s) == A1_{j*} (bar 1e-12).

LEG B -- S1 EXPORT (pointwise): split seal (TRB verbatim);
small-m certificates (C_2small = max over ranks 0..20); C_2 =
max m M_2 over the cal window FROZEN; test violations (0
demanded for the GO clause; the banked expectation is 7 --
disclosed); reserve min/med + trend; the named rungs printed.

LEG C -- S2 PILEUP (the four mechanism measurements + direct
certification + hardness census + growth exponent): mechanism
(1) recomposition ward; (2) multiplicity ward; (3) C_PIL = max
cal pil, test violations; (4) C_NSC = max cal nsc_rel/log m,
test violations; direct C_INF = max cal G/log m, test
violations + named coverage (kz53/kz83/kz67/kz55); the hardness
census: the full scale profile of the argmax block at the three
named near-critical rungs vs the ladder medians; the growth
exponents e_G = halves-slope of G/log m vs m over test, e_M2 =
halves-slope of m M_2 vs m over test, e_tot = e_G + e_M2 vs
CRIT = 0.224, stability = the two test halves must agree on the
criticality side (else UNDECIDED).

LEG D -- S3 COMPOSITION: printed ALWAYS with honest hypothesis
typing: M_3 <= (G/m)(m M_2)/m => rho_2 <= G x (m M_2)/(log m)^2
=> sum q^3 <= C x (log m)^{A}/m^2 (A = 1 on GO; A = 1 + slack
m^{e_tot} on the subcritical branch) => N_3 = (sum q^3)^{-1/2}
>= m/sqrt(C log m) => N_2 >= N_3 (r306 exact chain) => N_2 >=
m^0.888 for all m >= m_0* (m_0* computed explicitly:
the smallest m with m^{0.224} >= C log m) => slope(n_eff) >=
NEED = +0.908 => sl_D <= sigma* => sigma <= sigma* = -0.516 =>
the r297 target => the v964-S0 vdC theorem => delta' > 0.21
generic => the terminal_positive_main edge; all m < m_0 on the
MEASURED ladder closed by the finite certificates (r306 0/57 +
this round's tables); the gap between the measured maximum m =
274 and m_0* is DISCLOSED as the honest extrapolation
hypothesis -- no cofinal claim.

LEG E -- WARDS / MUST-FAILS (>= 4 mutants + 2 scope mutants):
(e1) SCALE DECOMPOSITION INCOMPLETE: mutant_scale_drop drops the
  deepest scale -- the recomposition ward must measure the exact
  break (LOUD >= MUT_MIN) while the real decomposition
  recomposes exactly (toy break == 1 EXACT).
(e2) PILEUP COUNT WITHOUT THE MULTIPLICITY BOUND:
  mutant_mult3_toy presents a genealogy with a 3-fold group --
  mult_ward must REFUSE it (max 3 > MULT_CAP) while every live
  world passes at exactly 2 -- CAUGHT.
(e3) M_3 READ-BACK: mutant_m3_readback consumes the cubic-moment
  record (cm/S3) -- the PHI3_FORBIDDEN scan must FLAG it
  (AST-CAUGHT) while the module-own builders stay clean.
(e4) CLASS/CUTOFF CHOICE AFTER SIGHT: mutant_scale_posthoc
  re-picks the relevant-scale cutoff to cover the seen violators
  (consumes rho) -- the BOUND_FORBIDDEN scope audit must FLAG it
  AND on the sealed toy it returns a cutoff != the canonical
  rule's -- CAUGHT twice.
(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.

INDEX FIREWALL (binding, r238-r321 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; the cubic target M_3 / rho_2 enters GATES / anchors /
composition checks only, NEVER a mechanism builder (AST-warded);
no zero/prime oracles anywhere (AST firewall); no fit primitives
(fragment audit; the growth exponent is the imported r272 dyadic
halves-slope, fit-free).  MACHINERY IMPORTED VERBATIM: r324-pre
FAP.m2_qmax_state + FAP.qq_groups, r321 CCP.local_median, r317
EFP.local_ratio, r316 TRB.two_regime_state + TRB.split_midladder,
r315 PHI.phi3_variants, r314 SCF.fold_genealogy +
SCF.signed_cube_terms + SCF.flux_telescope, r306
RY3.cubic_moments + RY3.renyi3_ratio + RY3.calib_freeze, r302
UNIF.ks_two + UNIF.fs_solve, r298 WBT.block_breaks +
WBT.aggregate_blocks, r269 PBB.mask_edge + PBB.runs_split, r287
L2D.blocks_level2 + L2D.halves_slope + L2D.autocorr_full, r244
BH.wpack, 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, r316/r321 verbatim):
frame-A h <= 900, 42 rungs, (N, kz)-sorted; exception set {kz15,
20, 22, 36, 38, 39, 52}; EXTENSION: 900 < h <= 1300, first 15 by
(N, kz); EXT2: the r316 A5 rule (leftover pool + first 12
windows 1300 < h <= 1650, first 8 POSITIVE_PREFIX by (N, kz)).

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);
EXT_H_MAX 1300; K_EXT 15; EXT_NW_EXPECT (942, 1218); EXT2_H_MAX
1650; EXT2_POOL_CAP 12; K_EXT2 8; ATOM_BAR 1e-9; REC3_BAR 1e-13;
TEL_BAR 1e-13; BND_BAR 1e-13; CHAIN_BAR 1e-9; XW_BAR 1e-9;
DEG_FLOOR 1e-6; MULT_CAP 2; N_CAL 5 (via TRB, verbatim); CLS_W 5
(via EFP, verbatim); KS_STAT 0.125 (r302 verbatim); SCUT_FAC 2.0
(relevant scales s <= 2 log2 m -- the tail beyond carries <=
n_atoms x vmax/m^2 by dyadic algebra, disclosed); A_SEAL 1;
CRIT_EXP 0.224 (= 2 x (1 - 0.888); the reviewer's 0.112 is the
F_A-side equivalent, disclosed); N2_EXP_NEED 0.888; NEED_SLOPE
0.908; SIGMA_STAR -0.516; DELTA_NEED 0.21; NAMED_KZ (53, 83, 67,
55); NAMED_FA_KZ (53, 83, 67); MUT_MIN 1e-6; TOY_BAR 1e-12;
FR_BAR 1e-14; SA_BAR 1e-12; TB_WARD bars 1e-9 main N <= 400 /
3e-6 deep + ext + ext2 / 1e-6 controls; ID_BAR 1e-12; AC_BAR
1e-9; R306 anchor C_2 1.069 tol 0.005; N324_REF 65; R316 RHO
{53: 1.0490, 67: 1.0536, 55: 0.4821, 83: 0.7790} tol 0.005,
C_SMALL 1.0694 tol 0.005 at kz18; R321 B_SQ 1.3056 tol 0.005;
R324PRE anchors: KS13 0.0230 / KS23 0.0158 tol 0.005, M2_MED
2.051 tol 0.01, M2_MAX 3.194 tol 0.01, C_M2 2.2557 tol 0.005,
M2_VIOL_SET {53, 67, 83, 76, 61, 28, 109} EXACT;
R324B_TABLE_LITERALS = the sealed r314+r315+r316+r317+r321
forbidden set (r324-pre verbatim) UNION the r324-pre record set
{0.0982, 3.357, 2.583, 2.2557, 3.1528, 3.1938, 3.049, 2.051,
3.194, 1.579, 2.081, -0.584, 1.746, 3.5261, 4.338, 0.023,
0.0158, 0.0247, 0.4852, 0.2136, 0.0907, 2.046, 2.033, 2.074};
runtime <= 1800 s; smoke = w9 + controls + toys + scope/purity
audits + the interpolation/identity/pileup wards on w9 +
controls + e1-e4 mutants; ladder, extensions, anchors, export,
certification, exponent and adjudication skipped.
DISCLOSED PRE-SPEC INPUT (no scratch run of THIS probe; the
sealed pre-work probe of this same round IS a disclosed input):
every anchor band is an r306/r316/r321/r324-pre RECORD number
adopted as-is; the interpolation M_3 <= qmax M_2, the identity
F_A B log m == m qmax, the pileup chain and the dyadic tail
bound are derived algebra, disclosed above; the S1 pointwise
outcome at the mid-ladder freeze (7/39 violations incl. the
named rungs) is KNOWN pre-spec from the banked pre-work and
disclosed -- the sealed rule is the house convention adopted
verbatim, not tuned; GENUINELY OPEN quantities of this round:
the scale profiles, nsc/nsc_rel/pil columns, C_PIL/C_NSC/C_INF,
all S2 violation counts, the hardness census and both growth
exponents -- NONE was computed before this spec was frozen;
SCUT_FAC = 2.0, A_SEAL = 1 and CRIT_EXP = 0.224 are a-priori
(the criticality budget is derived from the reviewer's N_2 >~
m^0.888 need by exact exponent algebra, disclosed above); the
six sealed letters are symmetric and total -- the tree maps
every outcome to exactly one letter by CONTRACT.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  R324_ANCHORS(identity wards, r306 C_2, r316 rho + C_small + n,
    r321 b, r324-pre KS + m2 census + freeze + violator set)
+ SEAL(interpolation + identity + pileup chain + purity audits
    + toys + live wards)
+ S1_EXPORT(C_2, small-m, violations, reserve, trend, named)
+ S2_PILEUP(mechanism (1)-(4) measurements, C_PIL/C_NSC/C_INF,
    violations, named coverage, hardness census, exponents)
+ [exactly one of] QMAX_MULTISCALE_GO / M2_GO_QMAX_OPEN /
    PILEUP_GROWS_SUBCRITICAL(e) / PILEUP_SUPERCRITICAL /
    FA_RESTATEMENT / TARGET_LEAK
+ S3_COMPOSITION(the full chain with explicit constants + m_0*
    + the disclosed measured-ladder gap; printed ALWAYS, typed)
+ MUSTFAIL_LEDGER(e1-e4 + scopes).
Honesty before beauty: the interpolation, the identity and the
pileup chain are EXACT algebra; every constant, violation count,
scale census and exponent is MEASURED on the finite ladder only;
the composition's step from the measured ladder (m <= 274) to
m_0* is an EXTRAPOLATION HYPOTHESIS, typed as such -- no cofinal
claim; a subcritical letter is a first-class outcome by the
reviewer contract, not a failure; the banked pre-work outcomes
are disclosed pre-spec inputs, and the pre-work probe stays
sealed and citable as its own record; r243-r322 stand.

RECORD TABLES (inserted AFTER the record run -- the only
amendment after freeze; run1/run2 byte-identical up to the
runtime line):
MAIN VERDICT: PILEUP_GROWS_SUBCRITICAL(e_tot +0.172 < CRIT
0.224; halves +0.141/-0.160 DECIDED) -- a sufficient,
first-class outcome by the reviewer contract, not a failure.
S0 (EXACT, live on 69 worlds): interpolation M_3 <= qmax M_2
worst slack 0.0; M_2 <= qmax worst 0.0; the identity F_A B
log m == m qmax worst 2.7e-16 -- F_A is the rank-local
normalization of m qmax, no black factor; rho_2 == m^2 M_3/
(log m)^2 worst 1.0e-15.
S1 EXPORT: C_2 = 2.2557 (mid-ladder freeze at kz34): POINTWISE
FAILS 7/39 [kz53 3.1528 / kz28 2.3585 / kz67 3.1938 / kz109
2.2857 / kz76 2.4992 / kz61 2.4711 / kz83 3.0490] (the banked
pre-work expectation, disclosed pre-spec); reserve min/med
0.71/1.10; test trend +0.014 (FLAT); small-m C_2small 2.6130;
DISTRIBUTIONAL export GO (stationarity KS 0.0230/0.0158 <=
0.125); ladder envelope C_2env = 3.1938.
S2 PILEUP (the four mechanism measurements): (1) the scale
decomposition recomposes EXACTLY (worst 2.2e-16); (2) fold
multiplicity <= 2 admitted on ALL 69 live worlds; (3) per-scale
mass C_PIL = 9.3583 (cal freeze) FAILS 11/39 (worst kz67
22.378 / kz53 13.778 / kz83 12.707; pil med 6.661 max 25.309
at kz55); (4) active scales nsc_rel/log m med 1.165 max 2.026,
C_NSC = 2.0258: HOLDS 0/39 -- the O(log m) scale count
CERTIFIES pointwise.  DIRECT: C_INF = 1.7481 FAILS 5/39 (kz53
2.724 / kz67 2.800 / kz76 1.971 / kz61 2.103 / kz83 2.567),
named coverage 1/4 -> S2 NOT-GO.  HARDNESS CENSUS (the
reviewer question ANSWERED): the named spikes are NOT
multiscale convergence -- ONE near-maximal source scale
dominates the argmax block: kz53 s0 = 13.78 of G 13.02 (nsc 5
== ladder med), kz83 s0 = 12.71 of G 14.15 (nsc 6), kz67 s0 =
22.38 of G 13.61 (nsc 7 vs med 5) -- the pileup tip is a
SINGLE HEAVY SCALE, not many-scale pileup; the reviewer
mechanism hypothesis is REFUTED in its clause (3) and
CONFIRMED in its clause (4).  EXPONENTS (fit-free dyadic
halves-slope vs m over 39 test rungs): e(G/log m) = +0.158,
e(m M_2) = +0.014, e_tot = +0.172 < 0.224 (stability halves
+0.141/-0.160, the second half FALLING) -- DECIDED
SUBCRITICAL.  Columns: G = m qmax 2.60/5.32/14.15 min/med/max
(max at kz83); G/log m med 1.137 max 2.800; nsc med 5 max 9.
S3 COMPOSITION (typed MEASURED, printed verbatim in S7): sum
q^3 <= 8.941 x (log m) x m^{+0.172}/m^2 => N_3 >= m^{0.914}/
sqrt(8.941 log m) and N_2 >= N_3 (r306 exact chain) => N_2 >=
m^0.888 for all m >= m_0* = 10^59.6 => slope(n_eff) >= +0.908
=> sigma <= -0.516 => the r297 target => the v964-S0 vdC
theorem => delta' > 0.21 => the terminal_positive_main edge;
all measured m <= 274 closed by the finite certificates; the
gap (274, 10^59.6) is the disclosed extrapolation hypothesis.

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 window_border_transfer_probe as WBT     # noqa: E402 r298
import unif_target_probe as UNIF               # noqa: E402 r302
import renyi3_probe as RY3                     # noqa: E402 r306
import signed_cubic_flux_probe as SCF          # noqa: E402 r314
import phi3_functional_probe as PHI            # noqa: E402 r315
import two_regime_bound_probe as TRB           # noqa: E402 r316
import exception_families_probe as EFP         # noqa: E402 r317
import continuous_coordinate_probe as CCP      # noqa: E402 r321
import fa_provenance_probe as FAP              # noqa: E402 r324-pre
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
EXT_H_MAX = 1300
K_EXT = 15
EXT_NW_EXPECT = (942, 1218)
EXT2_H_MAX = 1650
EXT2_POOL_CAP = 12
K_EXT2 = 8
ATOM_BAR = 1e-9
REC3_BAR = 1e-13
TEL_BAR = 1e-13
BND_BAR = 1e-13
CHAIN_BAR = 1e-9
XW_BAR = 1e-9
DEG_FLOOR = 1e-6
MULT_CAP = 2
N_CAL = 5
KS_STAT = 0.125
SCUT_FAC = 2.0
A_SEAL = 1
CRIT_EXP = 0.224
N2_EXP_NEED = 0.888
NEED_SLOPE = 0.908
SIGMA_STAR = -0.516
DELTA_NEED = 0.21
NAMED_KZ = (53, 83, 67, 55)
NAMED_FA_KZ = (53, 83, 67)
MUT_MIN = 1e-6
TOY_BAR = 1e-12
FR_BAR = 1e-14
SA_BAR = 1e-12
EDGE_F = 0.20
PAIR_OFFSET = 0
R306_C2 = 1.069
R306_C2_TOL = 0.005
N324_REF = 65
R316_RHO = {53: 1.0490, 67: 1.0536, 55: 0.4821, 83: 0.7790}
R316_RHO_TOL = 0.005
R316_CSMALL = 1.0694
R316_CSMALL_TOL = 0.005
R316_CSMALL_KZ = 18
R321_B_SQ = 1.3056
R321_B_TOL = 0.005
R324P_KS13 = 0.0230
R324P_KS23 = 0.0158
R324P_KS_TOL = 0.005
R324P_M2MED = 2.051
R324P_M2MED_TOL = 0.01
R324P_M2MAX = 3.194
R324P_M2MAX_TOL = 0.01
R324P_CM2 = 2.2557
R324P_CM2_TOL = 0.005
R324P_M2VIOL = (53, 67, 83, 76, 61, 28, 109)
R324B_TABLE_LITERALS = frozenset(FAP.R324_TABLE_LITERALS | {
    0.0982, 3.357, 2.583, 2.2557, 3.1528, 3.1938, 3.049,
    2.051, 3.194, 1.579, 2.081, -0.584, 1.746, 3.5261,
    4.338, 0.023, 0.0158, 0.0247, 0.4852, 0.2136, 0.0907,
    2.046, 2.033, 2.074})

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"}
PHI3_FORBIDDEN = {"cube", "S" + "3", "cm",
                  "renyi3" + "_ratio", "cubic" + "_moments"}


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


def literal_audit(funcname):
    """the RECORD-LITERAL audit: walk ONLY the named function's
    subtree and flag any numeric constant whose 4-decimal rounding
    lies in the sealed r314..r321 + r324-pre record 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):
                if isinstance(sub, ast.Constant) \
                        and isinstance(sub.value, (int, float)) \
                        and not isinstance(sub.value, bool):
                    if round(float(sub.value), 4) \
                            in R324B_TABLE_LITERALS:
                        hits.append("%s@%d" % (repr(sub.value),
                                               sub.lineno))
    return hits


# ---------------- module-own builders.  Source-pure: the
# ---------------- mechanism builders consume atom values / block
# ---------------- assignments / block values / group
# ---------------- multiplicities / rank order only; the withheld
# ---------------- terminal drive key, the branch label, the cubic
# ---------------- target M_3 and the record literals are
# ---------------- forbidden (AST identifier scan + literal scan).
def scale_bins(vals):
    """the canonical dyadic SOURCE-SCALE binning: s(atom) =
    floor(log2(vmax / |v|)) relative to the rung's maximal atom
    value (the chain-row Ls-factor proxy, disclosed); zero atoms
    get scale -1 (they carry no mass).  Consumes atom values
    only."""
    av = np.abs(np.asarray(vals, dtype=float))
    vmax = float(np.max(av)) if len(av) else 0.0
    out = np.full(len(av), -1, dtype=int)
    nz = av > 0.0
    if vmax > 0.0:
        out[nz] = np.floor(np.log2(vmax / av[nz])).astype(int)
    return out


def pileup_state(x, vals, blks):
    """the argmax-block SCALE DECOMPOSITION with the exact pileup
    chain: on block values x (length m), atom values vals and
    atom block assignments blks: j* = argmax |x|, L = sum |x|;
    the atoms of j* are decomposed by scale_bins(vals) (scales
    relative to the RUNG maximum); returns per-scale masses,
    nsc (# distinct scales present in j*), nsc_rel (# present
    scales s <= SCUT_FAC log2 m), tail (mass beyond the cutoff),
    pil = m x max_s mass_s / L, a1j = sum |v| over j*, and the
    chain terms -- m qmax <= nsc x pil is EXACT algebra (warded
    by the caller)."""
    ax = np.abs(np.asarray(x, dtype=float))
    av = np.abs(np.asarray(vals, dtype=float))
    m = int(len(ax))
    tot = float(np.sum(ax))
    if m < 2 or tot <= 0.0:
        return dict(j=0, nsc=0, nsc_rel=0, pil=0.0, a1j=0.0,
                    tail=0.0, scut=0, scales=(), masses=())
    j = int(np.argmax(ax))
    sb = scale_bins(av)
    mask = (np.asarray(blks, dtype=int) == j) & (sb >= 0)
    sj = sb[mask]
    vj = av[mask]
    scut = int(math.ceil(SCUT_FAC * math.log2(float(m))))
    scales = tuple(int(s) for s in sorted(set(int(s)
                                              for s in sj)))
    masses = tuple(float(np.sum(vj[sj == s])) for s in scales)
    nsc = len(scales)
    nsc_rel = sum(1 for s in scales if s <= scut)
    tail = float(sum(mv for s, mv in zip(scales, masses)
                     if s > scut))
    pil = float(m) * (max(masses) if masses else 0.0) / tot
    return dict(j=j, nsc=nsc, nsc_rel=nsc_rel, pil=pil,
                a1j=float(np.sum(vj)), tail=tail, scut=scut,
                scales=scales, masses=masses)


def mult_ward(mults):
    """the fold-multiplicity REFUSAL (mechanism clause (2), the
    proven multiplicity <= 2): returns (max multiplicity,
    admitted flag) -- any genealogy with a group of more than
    MULT_CAP fold ancestors at one position is REFUSED (the e2
    mutant presents a 3-fold toy and must be CAUGHT)."""
    mx = int(max(int(v) for v in mults)) if len(mults) else 0
    return mx, mx <= MULT_CAP


def origin_tree(leak, restate, go_all, decided, sub, s1_stat):
    """the sealed six-letter verdict tree (booleans only; total,
    exactly one fires; order sealed):
    TARGET_LEAK > FA_RESTATEMENT > QMAX_MULTISCALE_GO >
    M2_GO_QMAX_OPEN (exponent undecided) >
    PILEUP_GROWS_SUBCRITICAL > PILEUP_SUPERCRITICAL."""
    if leak:
        return "TARGET_LEAK"
    if restate:
        return "FA_RESTATEMENT"
    if go_all:
        return "QMAX_MULTISCALE_GO"
    if not decided:
        _ = s1_stat  # printed in the letter detail by the caller
        return "M2_GO_QMAX_OPEN"
    if sub:
        return "PILEUP_GROWS_SUBCRITICAL"
    return "PILEUP_SUPERCRITICAL"


def mutant_scale_drop(masses):
    """e1 MUST-FAIL MUTANT: an 'aggregation' that drops the
    deepest scale -- the recomposition ward must measure the
    exact break (LOUD)."""
    ms = tuple(float(v) for v in masses)
    return sum(ms[:-1]) if ms else 0.0


def mutant_mult3_toy():
    """e2 MUST-FAIL MUTANT: a toy genealogy with a THREE-fold
    group (three ancestors at one position) -- mult_ward must
    REFUSE it."""
    return (1, 2, 3)


def mutant_m3_readback(cmrec, nblk):
    """e3 MUST-FAIL MUTANT: a 'mechanism column' consuming the
    cubic-moment record (the target side) -- the PHI3_FORBIDDEN
    identifier scan must FLAG this."""
    cm = cmrec
    return cm["S3"] * float(nblk) * float(nblk)


def mutant_scale_posthoc(scut_col, rho, cbar):
    """e4 MUST-FAIL MUTANT: the relevant-scale cutoff re-picked
    AFTER SIGHT of the violators (consumes rho): widened until
    every seen violator is 'relevant-covered' -- the
    BOUND_FORBIDDEN scope audit must FLAG it AND on the toy it
    returns != the canonical SCUT_FAC rule's cutoff."""
    worst = max((s for s, r in zip(scut_col, rho) if r > cbar),
                default=0)
    return int(worst) + 1


def mutant_gift_bound(rc, P):
    """m5a MUST-FAIL MUTANT: a 'scale orientation' consuming 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.abs(P) ** 3))


def mutant_branch_peek(rc, P):
    """m5b MUST-FAIL MUTANT (world-blindness break simulated): a
    'pileup constant' consuming the branch label -- the scope
    audit must FLAG this."""
    c = 0.5 if rc["g_branch"] >= 0.0 else 2.0
    return c * float(np.sum(np.abs(P) ** 3))


# ---------------- exact Fractions section: the S0 interpolation
# ---------------- and the pileup chain decided as rationals
def fr_interp_toys():
    """S0 in exact Fractions: q = (1/6, 1/3, 1/2): M_3 = 1/6 <=
    qmax M_2 = 7/36 (slack 1/36), M_2 = 7/18 <= qmax = 1/2; flat
    (1/2, 1/2): DOUBLE EQUALITY M_3 = qmax M_2 = 1/4 and M_2 =
    qmax; one-block (1, 0): equality at 1.  Returns worst
    rational deviation (must be 0)."""
    def st(qs):
        q = [Fr(a, b) for a, b in qs]
        m3 = sum(v ** 3 for v in q)
        m2 = sum(v ** 2 for v in q)
        qm = max(q)
        return m3, m2, qm

    devs = []
    m3, m2, qm = st(((1, 6), (1, 3), (1, 2)))
    devs += [abs(m3 - Fr(1, 6)), abs(qm * m2 - Fr(7, 36)),
             abs((qm * m2 - m3) - Fr(1, 36)),
             abs(m2 - Fr(7, 18)),
             Fr(0) if m3 <= qm * m2 and m2 <= qm else Fr(1)]
    m3, m2, qm = st(((1, 2), (1, 2)))
    devs += [abs(m3 - Fr(1, 4)), abs(qm * m2 - Fr(1, 4)),
             abs(m2 - qm)]
    m3, m2, qm = st(((1, 1), (0, 1)))
    devs += [abs(m3 - 1), abs(qm * m2 - 1)]
    return max(devs)


def fr_pileup_toy():
    """the pileup chain in exact Fractions: block j* atoms
    (4, 2, 1) at scales (0, 1, 2), second block (1), all
    positive: x = (7, 1), L = 8, m qmax = 7/4; per-scale m x
    share = (1, 1/2, 1/4); pil = 1, nsc = 3; chain 7/4 <= 3
    (slack 5/4 EXACT); recomposition 4 + 2 + 1 == 7 EXACT; the
    drop-scale mutant breaks by exactly 1.  Returns (worst dev,
    chain slack, drop break)."""
    L = Fr(8)
    m = Fr(2)
    qmax = Fr(7) / L
    masses = (Fr(4), Fr(2), Fr(1))
    shares = tuple(m * mv / L for mv in masses)
    pil = max(shares)
    nsc = Fr(3)
    chain_slack = nsc * pil - m * qmax
    rec = sum(masses)
    drop = rec - Fr(mutant_scale_drop(masses))
    devs = [abs(m * qmax - Fr(7, 4)), abs(pil - 1),
            abs(shares[1] - Fr(1, 2)), abs(shares[2] - Fr(1, 4)),
            abs(chain_slack - Fr(5, 4)), abs(rec - 7),
            abs(drop - 1),
            Fr(0) if m * qmax <= nsc * pil else Fr(1)]
    return max(devs), chain_slack, drop


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("qmax_m2_origin_probe -- "
          "PRIME.L2.RENYI3.QMAX_M2_ORIGIN.01 (round 324, "
          "reviewer-sharpened)")
    print("SPEC_SHA %s   R324PRE_SHA %s   R321_SHA %s   R302_SHA "
          "%s" % (SPEC_SHA[:16], FAP.SPEC_SHA[:16],
                  CCP.SPEC_SHA[:16], UNIF.SPEC_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 + controls + toys + scope/"
                        "purity audits + interpolation/identity/"
                        "pileup wards + e1-e4; ladder, "
                        "extensions, anchors, export, "
                        "certification, exponent and "
                        "adjudication 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 QMAX x M2 ORIGIN ROUND (reviewer course "
          "correction, binding, disclosed: the F_A-boundedness "
          "hunt of the sealed pre-work probe is DEMOTED -- the "
          "cleaner decomposition is QMAX x M_2): S0 exact "
          "interpolation M_3 <= qmax M_2 (Fractions) + the "
          "identity F_A B log m == m qmax (F_A no black "
          "factor); S1 pointwise M_2 export m M_2 <= C_2 "
          "(mid-ladder frozen; banked pre-work expectation "
          "7/39 violations DISCLOSED); S2 the multiscale "
          "pileup bound m qmax <= C_inf (log m)^%d via the "
          "four mechanism measurements (scale decomposition / "
          "fold multiplicity <= %d / per-scale pileup C_PIL / "
          "active scales C_NSC x log m) with the exact chain "
          "m qmax <= nsc x pil; S3 full composition to N_2 >= "
          "m^%.3f with explicit m_0*; verdict tree TARGET_LEAK "
          "/ FA_RESTATEMENT / QMAX_MULTISCALE_GO / "
          "M2_GO_QMAX_OPEN / PILEUP_GROWS_SUBCRITICAL / "
          "PILEUP_SUPERCRITICAL sealed BEFORE evaluation "
          "(CRIT_EXP %.3f = 2 x (1 - %.3f), the reviewer's "
          "0.112 F_A-side equivalent disclosed)"
          % (A_SEAL, MULT_CAP, N2_EXP_NEED, CRIT_EXP,
             N2_EXP_NEED))
    frag = antigate_fragment_audit()
    sc_own = []
    for fn in ("scale_bins", "pileup_state", "mult_ward",
               "origin_tree"):
        sc_own += scope_audit(fn, BOUND_FORBIDDEN)
        sc_own += scope_audit(fn, PHI3_FORBIDDEN)
    sc_a = scope_audit("mutant_gift_bound", BOUND_FORBIDDEN)
    sc_b = scope_audit("mutant_branch_peek", BOUND_FORBIDDEN)
    check("G03-scope-audits", (not frag) and (not sc_own)
          and len(sc_a) >= 1 and len(sc_b) >= 1,
          "fragment audit clean (%d hits); the four module-own "
          "mechanism builders/trees clean vs BOUND_FORBIDDEN + "
          "PHI3_FORBIDDEN (%d hits) -- the proof side consumes "
          "ONLY source genealogy / fold multiplicity / local "
          "mass balance / active scales / canonical "
          "aggregation; m5a gift-bound FLAGGED (%s); m5b "
          "branch-peek FLAGGED (%s)"
          % (len(frag), len(sc_own),
             sc_a[0] if sc_a else "MISS",
             sc_b[0] if sc_b else "MISS"))

    # ---------------- S1: census + controls (r321 scaffold verbatim)
    section("S1  CENSUS + CONTROLS + EXTENSIONS")
    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 = []
        ext = []
        ext2 = []
        okL = True
    else:
        kzs = []
        ekz = []
        ekz2 = []
        for kz in core.frame_a_zones():
            h = PIK.build_rung(kz)["h"]
            if h <= H_CAP:
                kzs.append(kz)
            elif h <= EXT_H_MAX:
                ekz.append(kz)
            elif h <= EXT2_H_MAX:
                ekz2.append((h, kz))
        ladder = [BH.wpack(kz) for kz in kzs]
        ladder.sort(key=lambda p: (p["N"], p["kz"]))
        epool = [BH.wpack(kz) for kz in ekz]
        epool.sort(key=lambda p: (p["N"], p["kz"]))
        ext = epool[:K_EXT]
        ekz2.sort()
        pool2 = epool[K_EXT:] + [BH.wpack(kz)
                                 for _h, kz in ekz2[:EXT2_POOL_CAP]]
        pool2.sort(key=lambda p: (p["N"], p["kz"]))
        ext2 = [p for p in pool2 if p["nf"] is None][:K_EXT2]
        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 "-"))
    if smoke:
        check("G12-extension-census", True, "SMOKE: skipped")
        check("G13-ext2-census", True, "SMOKE: skipped")
    else:
        check("G12-extension-census",
              len(ext) == K_EXT
              and ext[0]["N"] == EXT_NW_EXPECT[0]
              and ext[-1]["N"] == EXT_NW_EXPECT[1]
              and all(p["nf"] is None for p in ext),
              "r286-aligned extension: %d anchors, N_w %d..%d "
              "(expected %d..%d), POSITIVE_PREFIX %d/%d"
              % (len(ext), ext[0]["N"] if ext else -1,
                 ext[-1]["N"] if ext else -1, EXT_NW_EXPECT[0],
                 EXT_NW_EXPECT[1],
                 sum(1 for p in ext if p["nf"] is None), len(ext)))
        check("G13-ext2-census",
              len(ext2) <= K_EXT2
              and all(p["nf"] is None for p in ext2),
              "EXT2 (r316 A5 rule verbatim, census-grade): pool "
              "%d leftover + %d windows with %d < h <= %d; "
              "selected %d POSITIVE_PREFIX anchors, N_w %s..%s"
              % (len(epool) - K_EXT, min(len(ekz2), EXT2_POOL_CAP),
                 EXT_H_MAX, EXT2_H_MAX, len(ext2),
                 ext2[0]["N"] if ext2 else "-",
                 ext2[-1]["N"] if ext2 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)
        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
        v2w = BR.eval_scaled(rows, xu, N - 2)
        cw = wu * xu * v2w * fac
        o = np.argsort(bx, kind="stable")
        return dict(kz=p["kz"], N=N, g_branch=g,
                    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, nf=p["nf"])

    recs = [rung_rec(p) for p in pool]
    erecs = [rung_rec(p) for p in ext] if not smoke else []
    e2recs = [rung_rec(p) for p in ext2] if not smoke else []
    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:
        e_cheap = sum(1 for rc in erecs + e2recs
                      if rc["g_branch"] >= 0.0)
        e_exc = [rc["kz"] for rc in erecs + e2recs
                 if rc["g_branch"] < 0.0]
        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; "
              "EXT+EXT2 census (no sealed expectation): %d cheap "
              "/ %d exception %s"
              % (len(cheap), str(exc_kz),
                 "; ".join("w%d g %+.3f CHEAP" % (rc["kz"],
                                                  rc["g_branch"])
                           for rc in mrecs),
                 e_cheap, len(e_exc), str(e_exc)))

    # ---------------- S2: decomposition wards + eval
    section("S2  EXACT DECOMPOSITION + ATOMIC PRESENTATION WARDS")
    tb_worst = 0.0
    tb_deep = 0.0
    tb_ext = 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 rc in erecs + e2recs:
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(float(np.sum(np.abs(rc["ct"]))), 1e-300)
        tb_ext = max(tb_ext, 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_ext <= TB_WARD_BAR_DEEP
          and tb_ctrl <= TB_WARD_BAR_CTRL,
          "sum_b ct_b == t_{N-2} on %d rungs + %d ext + %d ext2 "
          "+ %d mains + 3 controls: worst dev/absmass %.1e main "
          "N<=%d (bar %.0e) / %.1e deep / %.1e ext+ext2 (bar "
          "%.0e) / %.1e controls (bar %.0e)"
          % (len(recs), len(erecs), len(e2recs), len(mrecs),
             tb_worst, DEEP_N, TB_WARD_BAR, tb_deep, tb_ext,
             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)
        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)
        brk, m, jb = WBT.block_breaks(xb, runs)
        Pb = np.bincount(jb, weights=cb, minlength=m) \
            if m else np.zeros(0)
        Pw = WBT.aggregate_blocks(rc["xu"], rc["cw"], rc["lo"],
                                  rc["hi"], brk, m)
        Pd = Pb - Pw
        cm = RY3.cubic_moments(Pd)
        absm = float(np.sum(np.abs(rc["ct"]))) \
            + float(np.sum(np.abs(rc["cw"])))
        degenerate = (cm["L1"] <= DEG_FLOOR * absm)
        edw = PBB.mask_edge(rc["xu"], rc["lo"], rc["hi"], EDGE_F)
        xw = rc["xu"][~edw]
        vw = -rc["cw"][~edw]
        jw = np.searchsorted(brk, xw) if m else np.zeros(0, int)
        jb2 = np.searchsorted(brk, xb) if m else np.zeros(0, int)
        mism = int(np.sum(jb2 != jb))
        pos_all = np.concatenate([xb, xw])
        val_all = np.concatenate([cb, vw])
        blk_all = np.concatenate([jb, jw]).astype(int)
        if m and not degenerate:
            gen = SCF.fold_genealogy(pos_all, val_all, blk_all, m)
            sct = SCF.signed_cube_terms(gen["G1"], gen["gblk"], m)
            ft = SCF.flux_telescope(gen["G1"], gen["ptr"], m)
            x_dev = float(np.max(np.abs(sct["x"] - Pd))
                          / max(np.max(np.abs(Pd)), 1e-300))
            sig = sct["sig"]
            cube = sct["cube"]
            A1 = np.bincount(blk_all, weights=np.abs(val_all),
                             minlength=m)
            scale3 = float(np.sum(A1 ** 3))
            sc_j = np.maximum(A1 ** 3, 1e-300)
            C_far_flux = float(np.sum(sig * ft["F_end"]))
            C_bnd = float(np.sum(sig * ft["F_open"]))
            rec3 = abs(C_far_flux + sct["C_pair"] + sct["C_full"]
                       + C_bnd - cube) / max(scale3, 1e-300)
            tel_dev = float(np.max(np.abs(ft["F_end"]
                                          - sct["far"]) / sc_j))
            bnd_dev = float(np.max(np.abs(ft["F_open"]) / sc_j))
            mx_mult = int(np.max(gen["mult"])) if gen["ng"] else 0
            trs = TRB.two_regime_state(sct["x"], sct["Q2"],
                                       sct["Q3"], gen["G1"],
                                       gen["ptr"], ft["F_end"],
                                       ft["F_open"],
                                       ft["edge_abs"], m)
            rho2 = RY3.renyi3_ratio(cm["S3"], m, 2)
            mqs = FAP.m2_qmax_state(sct["x"])
            pst = pileup_state(sct["x"], val_all, blk_all)
        else:
            gen = sct = ft = None
            x_dev = 0.0
            cube = 0.0
            rec3 = tel_dev = bnd_dev = 0.0
            C_bnd = 0.0
            mx_mult = 0
            A1 = np.zeros(0)
            trs = dict(nrm=0.0, coll=0.0, dflux=0.0, bnd=0.0,
                       fe=0.0, fcix=0.0, qmax=0.0, cnt3=0.0,
                       phiL1=0.0, phiL2=0.0, phiH1=0.0,
                       phiH2=0.0, L=0.0)
            rho2 = 0.0
            mqs = dict(qm=0.0, m2=0.0, ymx=0.0, maj=0.0)
            pst = dict(j=0, nsc=0, nsc_rel=0, pil=0.0, a1j=0.0,
                       tail=0.0, scut=0, scales=(), masses=())
        return dict(alt_ok=alt_ok, R=R, P=P, m=m, Pd=Pd, cm=cm,
                    degenerate=degenerate, mism=mism, x_dev=x_dev,
                    cube=cube, rec3=rec3, tel_dev=tel_dev,
                    bnd_dev=bnd_dev, C_bnd=C_bnd,
                    mx_mult=mx_mult, gen=gen, sct=sct, ft=ft,
                    trs=trs, rho2=rho2, A1=A1, mqs=mqs, pst=pst,
                    pos_all=pos_all, val_all=val_all,
                    blk_all=blk_all, brk=brk)

    all_rc = recs + mrecs + erecs + e2recs
    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)))

    live = [rc for rc in pool_all if not rc["ev"]["degenerate"]]
    deg_note = [c for c in crecs if crecs[c]["ev"]["degenerate"]]
    x_w = max(rc["ev"]["x_dev"] for rc in live)
    mism_tot = sum(rc["ev"]["mism"] for rc in pool_all)
    check("G22-genealogy-completeness",
          x_w <= ATOM_BAR and mism_tot == 0,
          "the r314 fold genealogy covers every block value on %d "
          "live worlds (group-sum dev %.1e, bar %.0e); run "
          "assignment == breakpoint search (%d mismatches)%s"
          % (len(live), x_w, ATOM_BAR, mism_tot,
             "; DEGENERATE guard fired (pre-declared): "
             + ", ".join(deg_note) if deg_note else ""))

    # ---------------- S3: Leg 0 anchors (slim + banked pre-work)
    section("S3  LEG 0 -- ANCHOR REGRESSION (slim + the banked "
            "r324-pre record)")
    rec3_w = max(rc["ev"]["rec3"] for rc in live)
    tel_w = max(rc["ev"]["tel_dev"] for rc in live)
    bnd_w = max(rc["ev"]["bnd_dev"] for rc in live)
    check("G30-r314-identity-wards",
          rec3_w <= REC3_BAR and tel_w <= TEL_BAR
          and bnd_w <= BND_BAR,
          "the r314 identity live on %d live worlds: three-term "
          "recomposition dev %.1e (bar %.0e), telescope dev %.1e "
          "(bar %.0e), boundary %.1e (bar %.0e); DISCLOSED slim "
          "anchor set -- the full chain is re-warded by the "
          "coexisting r321/r322 + the sealed r324-pre probe"
          % (len(live), rec3_w, REC3_BAR, tel_w, TEL_BAR, bnd_w,
             BND_BAR))
    if smoke:
        ev9s = recs[0]["ev"]
        info("SMOKE: w9 qmax %.4f G %.3f mM2 %.4f nsc %d "
             "nsc_rel %d pil %.3f"
             % (ev9s["trs"]["qmax"],
                ev9s["m"] * ev9s["trs"]["qmax"],
                ev9s["mqs"]["m2"], ev9s["pst"]["nsc"],
                ev9s["pst"]["nsc_rel"], ev9s["pst"]["pil"]))
        check("G31-r306-bound-live", True, "SMOKE: skipped")
        check("G32-r316-anchors", True, "SMOKE: skipped")
        check("G33-r321-sliding-anchor", True, "SMOKE: skipped")
        check("G34-r324pre-anchors", True, "SMOKE: skipped")
        srt = []
        n324 = 0
    else:
        srt57 = sorted(recs + erecs,
                       key=lambda rc: (rc["N"], rc["kz"]))
        rhoT2 = [rc["ev"]["rho2"] for rc in srt57]
        C2r, _j, _d = RY3.calib_freeze(rhoT2, range(N_CAL))
        viol2 = sum(1 for v in rhoT2 if v > C2r)
        check("G31-r306-bound-live",
              abs(C2r - R306_C2) <= R306_C2_TOL and viol2 == 0,
              "r306 pointwise bound live at A = 2: C_2 %.3f (rec "
              "%.3f tol %.3f, first-%d freeze), violations %d/%d"
              % (C2r, R306_C2, R306_C2_TOL, N_CAL, viol2,
                 len(srt57)))
        srt_all = sorted(recs + erecs + e2recs,
                         key=lambda rc: (rc["N"], rc["kz"]))
        srt = [rc for rc in srt_all
               if rc["ev"]["mx_mult"] <= MULT_CAP]
        n324 = len(srt)
        rho_all = [rc["ev"]["rho2"] for rc in srt]
        m_all = [rc["ev"]["m"] for rc in srt]
        rho_kz = {rc["kz"]: rc["ev"]["rho2"] for rc in srt}
        sm_i, ca_i, te_i = TRB.split_midladder(n324)
        C_small = max(rho_all[i] for i in sm_i)
        j_cs = max(sm_i, key=lambda i: rho_all[i])
        check("G32-r316-anchors",
              n324 == N324_REF
              and all(abs(rho_kz.get(kz, -1.0) - R316_RHO[kz])
                      <= R316_RHO_TOL for kz in R316_RHO)
              and abs(C_small - R316_CSMALL) <= R316_CSMALL_TOL
              and srt[j_cs]["kz"] == R316_CSMALL_KZ,
              "r316 anchors reproduced: class ladder n = %d (rec "
              "%d); rho kz53/kz67/kz55/kz83 = %.4f/%.4f/%.4f/"
              "%.4f (rec tol %.3f); C_small %.4f @ kz%d"
              % (n324, N324_REF, rho_kz.get(53, -1.0),
                 rho_kz.get(67, -1.0), rho_kz.get(55, -1.0),
                 rho_kz.get(83, -1.0), R316_RHO_TOL, C_small,
                 srt[j_cs]["kz"]))
        qmax_col = [rc["ev"]["trs"]["qmax"] for rc in srt]
        FA_col = EFP.local_ratio(qmax_col)
        medloc = CCP.local_median(qmax_col)
        Bcol = [medloc[i] * float(m_all[i])
                / math.log(float(m_all[i])) for i in range(n324)]
        parSQ, dSQ = CCP.g_calibrate("SQ", FA_col, rho_all,
                                     Bcol, ca_i)
        gv_sq = [CCP.g_eval("SQ", parSQ, FA_col[i])
                 for i in range(n324)]
        viol_sq = [i for i in te_i if rho_all[i] > gv_sq[i]]
        named_rank = {}
        for kz in NAMED_KZ:
            for i in range(n324):
                if srt[i]["kz"] == kz:
                    named_rank[kz] = i
        named_sq = sum(1 for kz in NAMED_KZ
                       if rho_all[named_rank[kz]]
                       <= gv_sq[named_rank[kz]])
        check("G33-r321-sliding-anchor",
              abs(parSQ[0] - R321_B_SQ) <= R321_B_TOL
              and not viol_sq and named_sq == 4
              and dSQ == tuple(ca_i),
              "r321 sliding bound reproduced: G_SQ b = %.4f (rec "
              "%.4f tol %.3f), violations %d/%d, named %d/4"
              % (parSQ[0], R321_B_SQ, R321_B_TOL, len(viol_sq),
                 len(te_i), named_sq))
        # banked r324-pre anchors: stationarity + m2 column
        m2_col = [rc["ev"]["mqs"]["m2"] for rc in srt]
        y_lists = []
        for rc in srt:
            x_abs = np.abs(rc["ev"]["sct"]["x"])
            Lx = float(np.sum(x_abs))
            y_lists.append(x_abs * (float(rc["ev"]["m"]) / Lx))
        g1, g2, g3 = FAP.qq_groups(n324)
        ks13 = UNIF.ks_two(np.concatenate([y_lists[i]
                                           for i in g1]),
                           np.concatenate([y_lists[i]
                                           for i in g3]))
        ks23 = UNIF.ks_two(np.concatenate([y_lists[i]
                                           for i in g2]),
                           np.concatenate([y_lists[i]
                                           for i in g3]))
        C_M2 = max(m2_col[i] for i in ca_i)
        viol_m2 = tuple(sorted(srt[i]["kz"] for i in te_i
                               if m2_col[i] > C_M2))
        check("G34-r324pre-anchors",
              abs(ks13 - R324P_KS13) <= R324P_KS_TOL
              and abs(ks23 - R324P_KS23) <= R324P_KS_TOL
              and abs(float(np.median(m2_col)) - R324P_M2MED)
              <= R324P_M2MED_TOL
              and abs(max(m2_col) - R324P_M2MAX)
              <= R324P_M2MAX_TOL
              and abs(C_M2 - R324P_CM2) <= R324P_CM2_TOL
              and viol_m2 == tuple(sorted(R324P_M2VIOL)),
              "the BANKED r324-pre record reproduced bit-near: "
              "stationarity thirds KS(G1,G3) %.4f / KS(G2,G3) "
              "%.4f (rec %.4f/%.4f tol %.3f); m2 = m M_2 med "
              "%.3f max %.3f (rec %.3f/%.3f); mid-ladder freeze "
              "C_M2 %.4f (rec %.4f); the seven m2 test "
              "violators %s == the banked set EXACT"
              % (ks13, ks23, R324P_KS13, R324P_KS23,
                 R324P_KS_TOL, float(np.median(m2_col)),
                 max(m2_col), R324P_M2MED, R324P_M2MAX, C_M2,
                 R324P_CM2, str(viol_m2)))

    # ---------------- S4: Leg A -- seal + purity + toys + wards
    section("S4  LEG A -- SEAL + PURITY + TOYS + LIVE WARDS + "
            "SOURCE-PURE TABLE")
    pure_lits = []
    for fn in ("scale_bins", "pileup_state", "mult_ward",
               "origin_tree", "fr_interp_toys", "fr_pileup_toy"):
        pure_lits += literal_audit(fn)
    e3_hits = scope_audit("mutant_m3_readback", PHI3_FORBIDDEN)
    e4_hits = scope_audit("mutant_scale_posthoc", BOUND_FORBIDDEN)
    check("G40-purity-audits",
          (not sc_own) and (not pure_lits)
          and len(e3_hits) >= 1 and len(e4_hits) >= 1,
          "SOURCE PURITY: the mechanism builders clean vs the "
          "forbidden sets (%d id hits) and vs the sealed r314..."
          "r321 + r324-pre record-literal set (%d literal hits); "
          "consumed inputs: atom values / block assignments / "
          "block values / group multiplicities / rank order -- "
          "M_3 and rho_2 are TARGET-SIDE, computed outside the "
          "builders (disclosed); e3 M3-readback FLAGGED (%s); "
          "e4 scale-posthoc FLAGGED (%s)"
          % (len(sc_own), len(pure_lits),
             e3_hits[0] if e3_hits else "MISS",
             e4_hits[0] if e4_hits else "MISS"))
    fr_dev = fr_interp_toys()
    fr_pdev, fr_slack, fr_drop = fr_pileup_toy()
    toy_x = np.array([7.0, 1.0])
    toy_v = np.array([4.0, 2.0, 1.0, 1.0])
    toy_b = np.array([0, 0, 0, 1])
    pst_t = pileup_state(toy_x, toy_v, toy_b)
    ok_pst = (pst_t["j"] == 0 and pst_t["nsc"] == 3
              and abs(pst_t["pil"] - 1.0) <= FR_BAR
              and abs(pst_t["a1j"] - 7.0) <= FR_BAR
              and pst_t["scales"] == (0, 1, 2)
              and pst_t["masses"] == (4.0, 2.0, 1.0))
    sb_t = scale_bins([4.0, -2.0, 1.0, 0.0])
    ok_sb = (list(sb_t) == [0, 1, 2, -1])
    mx_t, adm_t = mult_ward(mutant_mult3_toy())
    mx_r, adm_r = mult_ward((1, 2, 2, 1))
    ok_mw = (mx_t == 3 and not adm_t and mx_r == 2 and adm_r)
    tr_br = (origin_tree(True, True, True, True, True, True),
             origin_tree(False, True, True, True, True, True),
             origin_tree(False, False, True, True, True, True),
             origin_tree(False, False, False, False, True, True),
             origin_tree(False, False, False, True, True, True),
             origin_tree(False, False, False, True, False, True))
    ok_tr = tr_br == ("TARGET_LEAK", "FA_RESTATEMENT",
                      "QMAX_MULTISCALE_GO", "M2_GO_QMAX_OPEN",
                      "PILEUP_GROWS_SUBCRITICAL",
                      "PILEUP_SUPERCRITICAL")
    check("G41-toy-exactness",
          fr_dev == 0 and fr_pdev == 0 and ok_pst and ok_sb
          and ok_mw and ok_tr,
          "S0 Fractions interpolation toys EXACT (worst dev %s): "
          "M_3 1/6 <= qmax M_2 7/36 slack 1/36, M_2 7/18 <= "
          "qmax 1/2; flat DOUBLE EQUALITY; one-block equality; "
          "pileup Fractions toy EXACT (chain slack %s, drop "
          "break %s LOUD); pileup_state float toy EXACT (j* 0, "
          "scales (0,1,2), masses (4,2,1), pil 1, nsc 3); "
          "scale_bins toy EXACT (zero atom -> -1); mult_ward "
          "REFUSES the 3-fold toy and admits the 2-fold; "
          "origin_tree all six branches EXACT %s"
          % (str(fr_dev), str(fr_slack), str(fr_drop),
             str(tr_br)))
    # live wards
    chain_w = 0.0
    xw_cube = 0.0
    interp_w = 0.0
    m2q_w = 0.0
    norm_id_w = 0.0
    pil_ch_w = 0.0
    rec_sc_w = 0.0
    mult_all_ok = True
    for rc in live:
        ev = rc["ev"]
        trs = ev["trs"]
        nc = trs["nrm"] * ev["cube"]
        xw_cube = max(xw_cube, abs(nc - ev["rho2"])
                      / max(ev["rho2"], 1e-300))
        for a, b in ((nc, trs["phiL1"]),
                     (trs["phiL1"], trs["phiL2"]),
                     (trs["phiL2"], trs["phiH2"]),
                     (nc, trs["phiH1"])):
            chain_w = max(chain_w,
                          max(0.0, a - b) / max(b, 1e-300))
        x_abs = np.abs(ev["sct"]["x"])
        Lx = float(np.sum(x_abs))
        qv = x_abs / max(Lx, 1e-300)
        M3 = float(np.sum(qv ** 3))
        M2 = float(np.sum(qv ** 2))
        qm = float(np.max(qv))
        mloc = ev["m"]
        # S0 interpolation M_3 <= qmax M_2 and M_2 <= qmax
        interp_w = max(interp_w,
                       max(0.0, M3 - qm * M2)
                       / max(qm * M2, 1e-300),
                       max(0.0, M2 - qm) / max(qm, 1e-300))
        # cross-ward vs the imported r324-pre state
        m2q_w = max(m2q_w,
                    abs(ev["mqs"]["m2"] - mloc * M2)
                    / max(mloc * M2, 1e-300),
                    abs(ev["mqs"]["qm"] - qm)
                    / max(qm, 1e-300))
        # r306 NORM identity rho_2 == m^2 M_3/(log m)^2
        rid = mloc ** 2 * M3 / (math.log(float(mloc)) ** 2)
        norm_id_w = max(norm_id_w, abs(rid - ev["rho2"])
                        / max(ev["rho2"], 1e-300))
        # pileup chain m qmax <= nsc x pil + recomposition
        pst = ev["pst"]
        G = mloc * qm
        pil_ch_w = max(pil_ch_w,
                       max(0.0, G - pst["nsc"] * pst["pil"])
                       / max(pst["nsc"] * pst["pil"], 1e-300))
        rec_sc_w = max(rec_sc_w,
                       abs(sum(pst["masses"]) - pst["a1j"])
                       / max(pst["a1j"], 1e-300))
        mult_all_ok = mult_all_ok \
            and mult_ward(rc["ev"]["gen"]["mult"])[1]
    if smoke:
        fa_id_w = 0.0
    else:
        fa_id_w = max(abs(FA_col[i] * Bcol[i]
                          * math.log(float(m_all[i]))
                          - m_all[i] * qmax_col[i])
                      / max(m_all[i] * qmax_col[i], 1e-300)
                      for i in range(n324))
    check("G42-live-wards",
          chain_w <= CHAIN_BAR and xw_cube <= XW_BAR
          and interp_w <= CHAIN_BAR and m2q_w <= CHAIN_BAR
          and norm_id_w <= CHAIN_BAR and pil_ch_w <= CHAIN_BAR
          and rec_sc_w <= SA_BAR and mult_all_ok
          and fa_id_w <= CHAIN_BAR,
          "the r316 chain live on %d live worlds (worst %.1e); "
          "NORM x cube == rho_2 (%.1e); S0 INTERPOLATION M_3 <= "
          "qmax M_2 AND M_2 <= qmax (worst rel slack %.1e -- "
          "exact algebra live); r324-pre state cross-ward "
          "(%.1e); rho_2 == m^2 M_3/(log m)^2 (%.1e); PILEUP "
          "CHAIN m qmax <= nsc x pil (worst slack %.1e); scale "
          "recomposition sum_s mass == A1_{j*} (worst %.1e, bar "
          "%.0e); fold multiplicity <= %d admitted on ALL live "
          "worlds%s"
          % (len(live), chain_w, xw_cube, interp_w, m2q_w,
             norm_id_w, pil_ch_w, rec_sc_w, SA_BAR, MULT_CAP,
             "; S0 IDENTITY F_A B log m == m qmax on the "
             "ladder (worst %.1e -- F_A is no black factor)"
             % fa_id_w if not smoke else
             " (ladder identity SMOKE-skipped)"))
    if smoke:
        check("G43-coordinate-table", True, "SMOKE: skipped")
    else:
        G_col = [m_all[i] * qmax_col[i] for i in range(n324)]
        GL_col = [G_col[i] / math.log(float(m_all[i]))
                  for i in range(n324)]
        nsc_col = [rc["ev"]["pst"]["nsc"] for rc in srt]
        nscr_col = [rc["ev"]["pst"]["nsc_rel"] for rc in srt]
        pil_col = [rc["ev"]["pst"]["pil"] for rc in srt]
        info("sealed SOURCE-PURE table (printed BEFORE any "
             "certification table): rank kz N m qmax G=m*qmax "
             "G/logm mM2 nsc nscR pil")
        for i, rc in enumerate(srt):
            info("%2d kz%-3d N %4d m %3d qmax %.4f G %6.3f GL "
                 "%.3f mM2 %.3f nsc %2d nscR %2d pil %.3f"
                 % (i, rc["kz"], rc["N"], m_all[i], qmax_col[i],
                    G_col[i], GL_col[i], m2_col[i], nsc_col[i],
                    nscr_col[i], pil_col[i]))
        tails = [rc["ev"]["pst"]["tail"] for rc in srt]
        check("G43-coordinate-table", True,
              "G = m qmax range %.2f/%.2f/%.2f min/med/max (max "
              "at kz%d); G/log m med %.3f max %.3f; m M_2 med "
              "%.3f max %.3f; nsc med %.0f max %d; nsc_rel med "
              "%.0f max %d (cutoff 2 log2 m; dyadic tail mass "
              "beyond cutoff max %.2e -- negligible by "
              "algebra); pil med %.3f max %.3f"
              % (min(G_col), float(np.median(G_col)),
                 max(G_col), srt[int(np.argmax(G_col))]["kz"],
                 float(np.median(GL_col)), max(GL_col),
                 float(np.median(m2_col)), max(m2_col),
                 float(np.median(nsc_col)), max(nsc_col),
                 float(np.median(nscr_col)), max(nscr_col),
                 max(tails), float(np.median(pil_col)),
                 max(pil_col)))

    # ---------------- S5: Leg B -- S1 pointwise M_2 export
    section("S5  LEG B -- S1 POINTWISE M_2 EXPORT")
    if smoke:
        check("G50-split-seal", True, "SMOKE: skipped")
        check("G51-m2-export", True, "SMOKE: skipped")
    else:
        ovl = (len(set(sm_i) & set(ca_i))
               + len(set(sm_i) & set(te_i))
               + len(set(ca_i) & set(te_i)))
        cover = (tuple(sorted(sm_i + ca_i + te_i))
                 == tuple(range(n324)))
        m0 = min(m_all[i] for i in ca_i + te_i)
        C2_small = max(m2_col[i] for i in sm_i)
        check("G50-split-seal",
              ovl == 0 and cover and len(ca_i) == N_CAL,
              "SEALED split (TRB verbatim): small ranks 0..%d "
              "(individually certified, C_2small = %.4f), cal "
              "%d..%d (kz %s), test %d rungs; overlaps 0, cover "
              "EXACT; m_0 = %d"
              % (sm_i[-1], C2_small, ca_i[0], ca_i[-1],
                 str([srt[i]["kz"] for i in ca_i]), len(te_i),
                 m0))
        viol_m2_i = [i for i in te_i if m2_col[i] > C_M2]
        rsv_m2 = [C_M2 / max(m2_col[i], 1e-300) for i in te_i]
        NsT = [srt[i]["N"] for i in te_i]
        msT = [m_all[i] for i in te_i]
        sl_m2 = L2D.halves_slope(msT, [max(m2_col[i], 1e-300)
                                       for i in te_i])
        s1_point = (not viol_m2_i)
        s1_stat = (ks13 <= KS_STAT and ks23 <= KS_STAT)
        check("G51-m2-export", True,
              "S1 POINTWISE EXPORT (census; adjudicated in S7): "
              "m M_2 <= C_2 = %.4f (mid-ladder frozen at kz%d, "
              "NO cubic target consumed): test violations %d/%d "
              "%s -> pointwise %s (the banked pre-work "
              "expectation, disclosed); reserve min/med "
              "%.2f/%.2f; trend of m M_2 over test %+.3f; "
              "DISTRIBUTIONAL export (r302 stationarity, "
              "banked): KS %.4f/%.4f <= %.3f -> %s; named: %s"
              % (C_M2, srt[max(ca_i, key=lambda i:
                               m2_col[i])]["kz"],
                 len(viol_m2_i), len(te_i),
                 str([(srt[i]["kz"], round(m2_col[i], 4))
                      for i in viol_m2_i]),
                 "GO" if s1_point else "FAILS", min(rsv_m2),
                 float(np.median(rsv_m2)), sl_m2, ks13, ks23,
                 KS_STAT, "GO" if s1_stat else "FAILS",
                 str({("kz%d" % kz): round(m2_col[named_rank[kz]],
                                           3)
                      for kz in NAMED_KZ})))

    # ---------------- S6: Leg C -- S2 multiscale pileup
    section("S6  LEG C -- S2 MULTISCALE PILEUP (mechanism + "
            "certification + hardness + exponent)")
    if smoke:
        check("G60-mechanism-1-2", True, "SMOKE: skipped")
        check("G61-mechanism-3-pil", True, "SMOKE: skipped")
        check("G62-mechanism-4-nsc", True, "SMOKE: skipped")
        check("G63-direct-certification", True, "SMOKE: skipped")
        check("G64-hardness-census", True, "SMOKE: skipped")
        check("G65-growth-exponent", True, "SMOKE: skipped")
    else:
        check("G60-mechanism-1-2",
              rec_sc_w <= SA_BAR and mult_all_ok,
              "mechanism (1) SCALE DECOMPOSITION recomposes "
              "exactly on every live world (worst %.1e, bar "
              "%.0e -- e1 mutant breaks LOUD in S8); mechanism "
              "(2) FOLD MULTIPLICITY <= %d admitted on all live "
              "worlds (the r314-proven pileup cap; the 3-fold "
              "toy is REFUSED in S8)"
              % (rec_sc_w, SA_BAR, MULT_CAP))
        C_PIL = max(pil_col[i] for i in ca_i)
        viol_pil = [i for i in te_i if pil_col[i] > C_PIL]
        check("G61-mechanism-3-pil", True,
              "mechanism (3) PER-SCALE PILEUP MASS (does each "
              "scale carry O(1/m) at one block?): pil = m x "
              "max_s mass(j*, s)/L, C_PIL = %.4f frozen at cal; "
              "test violations %d/%d %s; pil med %.3f max %.3f "
              "at kz%d"
              % (C_PIL, len(viol_pil), len(te_i),
                 str([(srt[i]["kz"], round(pil_col[i], 3))
                      for i in viol_pil]) if viol_pil else "[]",
                 float(np.median(pil_col)), max(pil_col),
                 srt[int(np.argmax(pil_col))]["kz"]))
        nsclog = [nscr_col[i] / math.log(float(m_all[i]))
                  for i in range(n324)]
        C_NSC = max(nsclog[i] for i in ca_i)
        viol_nsc = [i for i in te_i if nsclog[i] > C_NSC]
        check("G62-mechanism-4-nsc", True,
              "mechanism (4) ACTIVE SCALES (only O(log m) "
              "relevant scales?): nsc_rel/log m med %.3f max "
              "%.3f, C_NSC = %.4f frozen at cal; test "
              "violations %d/%d %s; composed mechanism bound "
              "m qmax <= C_PIL x C_NSC x log m = %.3f log m"
              % (float(np.median(nsclog)), max(nsclog), C_NSC,
                 len(viol_nsc), len(te_i),
                 str([(srt[i]["kz"], round(nsclog[i], 3))
                      for i in viol_nsc]) if viol_nsc else "[]",
                 C_PIL * C_NSC))
        C_INF = max(GL_col[i] for i in ca_i)
        viol_G = [i for i in te_i if GL_col[i] > C_INF]
        named_G = {kz: GL_col[named_rank[kz]] <= C_INF
                   for kz in NAMED_KZ}
        n_named_G = sum(1 for kz in NAMED_KZ if named_G[kz])
        s2_ok = (rec_sc_w <= SA_BAR and mult_all_ok
                 and not viol_pil and not viol_nsc
                 and not viol_G and n_named_G == len(NAMED_KZ))
        check("G63-direct-certification", True,
              "DIRECT pointwise certification m qmax <= C_INF x "
              "(log m)^%d: C_INF = %.4f frozen at cal; test "
              "violations %d/%d %s; named coverage %d/4 %s -> "
              "S2 %s"
              % (A_SEAL, C_INF, len(viol_G), len(te_i),
                 str([(srt[i]["kz"], round(GL_col[i], 3))
                      for i in viol_G]) if viol_G else "[]",
                 n_named_G,
                 str({("kz%d" % kz): round(GL_col[named_rank[kz]],
                                           3)
                      for kz in NAMED_KZ}),
                 "GO" if s2_ok else "NOT-GO"))
        info("HARDNESS CENSUS -- the scale profile of the "
             "argmax block at the named near-critical rungs "
             "(scale: m x share of L):")
        for kz in NAMED_FA_KZ:
            i = named_rank[kz]
            pst = srt[i]["ev"]["pst"]
            prof = "; ".join("s%d %.3f"
                             % (s, m_all[i] * mv
                                / max(srt[i]["ev"]["trs"]["L"],
                                      1e-300))
                             for s, mv in zip(pst["scales"],
                                              pst["masses"]))
            info("  kz%-3d G %.2f nsc %d nsc_rel %d pil %.3f "
                 "scut %d | %s"
                 % (kz, G_col[i], pst["nsc"], pst["nsc_rel"],
                    pst["pil"], pst["scut"], prof))
        check("G64-hardness-census", True,
              "named spikes vs ladder medians: G %s (med %.2f), "
              "nsc %s (med %.0f), pil %s (med %.3f) -- the "
              "reviewer hardness question (many admissible "
              "scales converging near-maximally = pileup tip, "
              "or a single heavy scale?) is answered by the "
              "profiles above"
              % (str([round(G_col[named_rank[kz]], 2)
                      for kz in NAMED_FA_KZ]),
                 float(np.median(G_col)),
                 str([nsc_col[named_rank[kz]]
                      for kz in NAMED_FA_KZ]),
                 float(np.median(nsc_col)),
                 str([round(pil_col[named_rank[kz]], 3)
                      for kz in NAMED_FA_KZ]),
                 float(np.median(pil_col))))
        e_G = L2D.halves_slope(msT, [max(GL_col[i], 1e-300)
                                     for i in te_i])
        e_M2 = sl_m2
        e_tot = e_G + e_M2
        h = len(te_i) // 2
        te_a = te_i[:h]
        te_b = te_i[h:]

        def etot_on(idx):
            ms = [m_all[i] for i in idx]
            ea = L2D.halves_slope(ms, [max(GL_col[i], 1e-300)
                                       for i in idx])
            eb = L2D.halves_slope(ms, [max(m2_col[i], 1e-300)
                                       for i in idx])
            return ea + eb

        e_a = etot_on(te_a)
        e_b = etot_on(te_b)
        decided = ((e_a < CRIT_EXP) == (e_b < CRIT_EXP)
                   and (e_a < CRIT_EXP) == (e_tot < CRIT_EXP))
        sub = e_tot < CRIT_EXP
        check("G65-growth-exponent", True,
              "GROWTH EXPONENTS (r272 dyadic halves-slope vs m "
              "over the %d test rungs, fit-free): e(G/log m) = "
              "%+.3f, e(m M_2) = %+.3f, e_tot = %+.3f vs CRIT "
              "%.3f (= 2 x (1 - %.3f); the reviewer's 0.112 is "
              "the F_A-side equivalent); stability halves "
              "%+.3f / %+.3f -> %s, %s"
              % (len(te_i), e_G, e_M2, e_tot, CRIT_EXP,
                 N2_EXP_NEED, e_a, e_b,
                 "DECIDED" if decided else "UNDECIDED",
                 ("SUBCRITICAL" if sub else "SUPERCRITICAL")
                 if decided else "open"))

    # ---------------- S7: Leg D -- adjudication + composition
    section("S7  LEG D -- SEALED ADJUDICATION + S3 COMPOSITION")
    if smoke:
        check("G70-adjudication", True, "SMOKE: skipped")
        check("G71-composition", True, "SMOKE: skipped")
        verdict_main = "SMOKE_NO_ADJUDICATION"
    else:
        leak = bool(sc_own) or bool(pure_lits)
        restate = (rec_sc_w > SA_BAR or pil_ch_w > CHAIN_BAR
                   or not mult_all_ok)
        go_all = s2_ok and s1_point and s1_stat
        vkey = origin_tree(leak, restate, go_all, decided, sub,
                           s1_stat)
        det_v = {
            "TARGET_LEAK": "purity/scope audit hit on a "
                           "mechanism builder",
            "FA_RESTATEMENT": "the mechanism decomposition "
                              "breaks structurally",
            "QMAX_MULTISCALE_GO":
                "S2 pointwise GO (C_INF %.4f, mech C_PIL %.4f x "
                "C_NSC %.4f) + S1 pointwise GO (C_2 %.4f) + "
                "stationarity GO" % (C_INF, C_PIL, C_NSC, C_M2),
            "M2_GO_QMAX_OPEN":
                "exponent UNDECIDED (halves %+.3f/%+.3f "
                "straddle %.3f); distributional M_2 export GO "
                "(KS %.4f/%.4f), pointwise M_2 export %s"
                % (e_a, e_b, CRIT_EXP, ks13, ks23,
                   "GO" if s1_point else
                   "FAILS (%d viol, banked)" % len(viol_m2_i)),
            "PILEUP_GROWS_SUBCRITICAL":
                "e_tot %+.3f < %.3f DECIDED (halves %+.3f/"
                "%+.3f) -- sufficient by the reviewer contract"
                % (e_tot, CRIT_EXP, e_a, e_b),
            "PILEUP_SUPERCRITICAL":
                "e_tot %+.3f >= %.3f DECIDED (halves %+.3f/"
                "%+.3f)" % (e_tot, CRIT_EXP, e_a, e_b)}
        verdict_main = "%s(%s)" % (vkey, det_v[vkey])
        check("G70-adjudication", True,
              "exactly one sealed letter fired: %s"
              % verdict_main)
        # S3 composition (printed ALWAYS, honestly typed)
        C_G_env = max(GL_col)
        C_M2_env = max(m2_col)
        if vkey == "QMAX_MULTISCALE_GO":
            C_use = C_INF * C_M2
            e_use = 0.0
            hyp = ("both factors mid-ladder CERTIFIED pointwise "
                   "(0 violations)")
        else:
            C_use = C_G_env * C_M2_env
            e_use = max(e_tot, 0.0)
            hyp = ("measured ladder envelopes + the measured "
                   "growth exponent e_tot %+.3f (letter %s) -- "
                   "hypothesis typed MEASURED, not certified"
                   % (e_tot, vkey))
        # log-space solve of m^{CRIT - e} >= C log m: t = ln m,
        # condition t (CRIT - e) >= ln C + ln t (deterministic
        # grid; a finite root exists iff CRIT - e > 0)
        m_star_l10 = None
        if CRIT_EXP - e_use > 0.0:
            t = math.log(73.0)
            while t < 1e7:
                if t * (CRIT_EXP - e_use) \
                        >= math.log(C_use) + math.log(t):
                    m_star_l10 = t / math.log(10.0)
                    break
                t *= 1.02
        info("S3 COMPOSITION (all constants explicit; %s):" % hyp)
        info("  S0 (EXACT, Fractions-proved + live-warded): M_3 "
             "<= qmax x M_2, hence sum q^3 <= (m qmax)(m M_2)/"
             "m^2 and rho_2 <= (m qmax)(m M_2)/(log m)^2;")
        info("  S1 + S2: m M_2 <= %.4f and m qmax <= %.4f x "
             "log m x m^{%.3f}  =>  sum q^3 <= %.3f x (log m)^"
             "%d x m^{%.3f} / m^2;"
             % (C_M2 if vkey == "QMAX_MULTISCALE_GO"
                else C_M2_env,
                C_INF if vkey == "QMAX_MULTISCALE_GO"
                else C_G_env, e_use, C_use, A_SEAL, e_use))
        info("  => N_3 = (sum q^3)^{-1/2} >= m^{%.3f}/sqrt(%.3f "
             "log m) and N_2 >= N_3 (r306 exact chain);"
             % (1.0 - e_use / 2.0, C_use))
        ms_txt = ("10^%.1f" % m_star_l10) \
            if m_star_l10 is not None else "NONE (supercritical)"
        info("  => N_2 >= m^%.3f for all m >= m_0* = %s (the "
             "smallest m with m^{%.3f} >= %.3f log m); "
             "MEASURED LADDER: m <= %d -- the gap (%d, m_0*) "
             "is the disclosed extrapolation hypothesis;"
             % (N2_EXP_NEED, ms_txt, CRIT_EXP - e_use, C_use,
                max(m_all), max(m_all)))
        info("  => slope(n_eff) >= NEED = %+.3f => sl_D <= "
             "sigma* => sigma <= sigma* = %.3f => the r297 "
             "target => the v964-S0 vdC theorem => delta' > "
             "%.2f on the generic half => the "
             "terminal_positive_main edge; exceptions: 6 via "
             "r287 F2 + kz15 via r270; all measured m <= %d "
             "closed by the finite certificates (r306 0/57 + "
             "this round's tables)."
             % (NEED_SLOPE, SIGMA_STAR, DELTA_NEED, max(m_all)))
        check("G71-composition",
              (m_star_l10 is not None)
              == (CRIT_EXP - e_use > 0.0),
              "composition printed with explicit constants "
              "(C = %.3f, e = %+.3f, m_0* = %s, m_0 = %d); "
              "the chain to terminal_positive_main is typed: "
              "S0 exact, S1/S2 %s, the ladder-to-m_0* step an "
              "extrapolation hypothesis -- NO cofinal claim"
              % (C_use, e_use, ms_txt, m0,
                 "certified" if vkey == "QMAX_MULTISCALE_GO"
                 else "measured"))

    # ---------------- S8: Leg E -- must-fails
    section("S8  LEG E -- WARDS / MUST-FAILS")
    drop = mutant_scale_drop((4.0, 2.0, 1.0))
    check("G80-e1-scale-drop",
          abs((7.0 - drop) - 1.0) <= FR_BAR
          and abs(drop - 6.0) <= FR_BAR,
          "e1 LOUD: the drop-scale 'aggregation' returns 6 != "
          "the exact recomposition 7 (break exactly 1 >= %.0e; "
          "Fractions-warded in G41) -- an incomplete scale "
          "decomposition cannot slip through the recomposition "
          "ward (live worst %.1e)" % (MUT_MIN, rec_sc_w))
    mx3, adm3 = mult_ward(mutant_mult3_toy())
    check("G81-e2-mult-uncapped",
          mx3 == 3 and not adm3 and mult_all_ok,
          "e2 CAUGHT: the 3-fold toy genealogy (three ancestors "
          "at one position) is REFUSED by mult_ward (max %d > "
          "%d) while every live world is admitted at exactly 2 "
          "-- a pileup count without the proven multiplicity "
          "bound is structurally refused" % (mx3, MULT_CAP))
    check("G82-e3-m3-readback",
          len(e3_hits) >= 1 and (not sc_own),
          "e3 AST-CAUGHT: the 'mechanism column' consuming the "
          "cubic-moment record (cm/S3) is FLAGGED (%s) while "
          "the four module-own mechanism builders are clean "
          "(%d hits) -- M_3 cannot enter the proof side"
          % (e3_hits[0] if e3_hits else "MISS", len(sc_own)))
    toy_scut = (4, 5, 6)
    toy_rho = (0.1, 0.9, 0.1)
    cut_mut = mutant_scale_posthoc(toy_scut, toy_rho, 0.5)
    cut_seal = int(math.ceil(SCUT_FAC * math.log2(4.0)))
    check("G83-e4-scale-posthoc",
          len(e4_hits) >= 1 and cut_mut == 6
          and cut_mut != cut_seal,
          "e4 CAUGHT twice: the after-sight cutoff re-pick "
          "consumes the evaluated bound column -- AST-FLAGGED "
          "(%s) -- and on the toy returns %d != the canonical "
          "SCUT_FAC rule's %d (a post-hoc class/cutoff choice "
          "is structurally refused)"
          % (e4_hits[0] if e4_hits else "MISS", cut_mut,
             cut_seal))

    # ---------------- S9: verdict
    section("S9  VERDICT")
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the exact S0 interpolation M_3 <= qmax M_2 "
          "with the F_A identity (no black factor), the "
          "pointwise M_2 export test, the multiscale pileup "
          "mechanism (scale decomposition + multiplicity cap + "
          "per-scale mass + active-scale count) with the exact "
          "chain m qmax <= nsc x pil, the growth-exponent "
          "criterion and the full S3 composition -- NO new "
          "certificate promoted, NO universal bound claimed "
          "beyond the measured rungs")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        parts = ["R324_ANCHORS(identity %.1e, r306 C2 %.3f viol "
                 "%d/57, r316 n %d rho4 bit-near, r321 b %.4f, "
                 "r324-pre KS %.4f/%.4f C_M2 %.4f viol7 EXACT)"
                 % (rec3_w, C2r, viol2, n324, parSQ[0], ks13,
                    ks23, C_M2)]
        parts.append("SEAL(interp %.1e, identity %.1e, pileup "
                     "chain %.1e, recomposition %.1e, purity "
                     "clean, toys exact)"
                     % (interp_w, fa_id_w, pil_ch_w, rec_sc_w))
        parts.append("S1_EXPORT(C_2 %.4f viol %d/%d, reserve "
                     "%.2f/%.2f, trend %+.3f, stationarity "
                     "%.4f/%.4f %s)"
                     % (C_M2, len(viol_m2_i), len(te_i),
                        min(rsv_m2), float(np.median(rsv_m2)),
                        sl_m2, ks13, ks23,
                        "GO" if s1_stat else "FAILS"))
        parts.append("S2_PILEUP(C_PIL %.4f viol %d, C_NSC %.4f "
                     "viol %d, C_INF %.4f viol %d named %d/4, "
                     "e_G %+.3f e_M2 %+.3f e_tot %+.3f %s)"
                     % (C_PIL, len(viol_pil), C_NSC,
                        len(viol_nsc), C_INF, len(viol_G),
                        n_named_G, e_G, e_M2, e_tot,
                        "DECIDED" if decided else "UNDECIDED"))
        parts.append(verdict_main)
        parts.append("S3_COMPOSITION(C %.3f, e %+.3f, m_0* %s, "
                     "typed)" % (C_use, e_use, ms_txt))
        parts.append("MUSTFAIL_LEDGER(e1-e4 + scopes)")
        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 S0 interpolation, "
          "the F_A identity, the pileup chain, the "
          "recomposition, the Fractions toys, the tree logic "
          "and the purity audits (exact / AST-decided); "
          "MEASURED: every constant, violation count, scale "
          "census and exponent (the finite class ladder + 2 "
          "mains + 2 live controls); OPEN: any bound beyond "
          "the measured rungs, the cofinal law, the "
          "ladder-to-m_0* extrapolation, 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"""extraction_order_probe -- PRIME.EXTRACTION.ORDER_REPAIR_FORK.01
(round 325): THE EXTRACTION-REPAIR FORK -- the measurable halves of
the three reviewer variants for repairing the RH connection seam
found by R319 (the rh/ cofinality runs in the ANCHOR direction;
the carrier hypothesis H_cof demands the MESH-refinement direction;
the window direction is MEASURED inadmissible there -- false floors
-2.114e-03 at D0 = 1/32 / -2.128e-04 at D0 = 1/128,
hcof_dodging_audit_probe S6.8).  This probe measures ONLY the
machine-checkable parts; the quantifier architecture itself is the
round's analytic deliverable (fork table, next.txt note).

THE THREE VARIANTS (reviewer, verbatim; measured halves per leg):
  A  ELEMENTWISE (per-test-function) STABILIZATION: for each f of a
     dense class a window sequence w_j(f) PREDEFINED FROM f with
     Q_{w_j(f)}(f) -> Q_Weil(f), ideally finite stabilization
     (exists j0(f): equality for all j >= j0(f)) -- the R310 form
     finite_forms_converge_to_weil generalized beyond the comb
     channel.  MEASURED HERE (S1): on the NATIVE dense class (dyadic
     step-function autocorrelations F = D0 * autocorr(x), the v749
     "Weil form of step functions" class, elements sealed by seed
     BEFORE any sign is read) the per-channel reads of the canonical
     tower windows (comb = atom tent lags, arch = Weil-kernel tent
     lags, pole) stabilize EXACTLY at the predicted finite onset
     alpha*(f) = (n_g + 1) D0 / 2 in the ANCHOR direction, and are
     CONSTANT under dyadic mesh refinement (no hidden mesh limit:
     the value at the element's native mesh IS the limit value).
  B  CANONICAL MESH REBUILD (no transport): the family
     w(a, h) = buildPrimeWindow(a, h) is built DIRECTLY at every
     mesh stage.  MEASURED HERE (S3): the v749 bridge reproduced --
     every deployed frame-A window IS a tower member at deviation
     0.0 (T1.4b class); the direct rebuild ladder at fixed anchor is
     PD at every dyadic stage (Levinson), with the honest falling
     relative margins; the dyadic lag-transport identity holds but
     is NOT consumed (variant B's point: no transport step).
  C  EXPLICIT QUADRATURE CORRECTION: Q_{a,h}(f) = Q_Weil(f) + E_h(f)
     with E controlled ON ITS OWN (hard rule: never divided through
     the shrinking wall margin -- no margin appears anywhere in this
     probe).  MEASURED HERE (S2): on a SEALED non-native test class
     (F1 tent with off-grid kink C^0, F2 quartic bump C^1, F3 Hann
     C^1; widths 1.7 / 2.3 / 2.9, fixed before any run) the
     per-channel defect E_ch(D, F) = L^D_ch(F) - R_ch(F) against
     mesh-independent references (comb: exact atom sum; arch/pole:
     Richardson-gated fine-mesh reads), its SIGN census, its dyadic
     decay ratios, and the RIGOROUS interpolation envelope
     |E_ch| <= (D^2/8) ||F''||_inf K_ch (K_comb = atom mass on the
     support, K_arch/pole = read-weighted absolute kernel mass) --
     an inequality gate consuming NO wall margin.  Plus the
     ANCHOR-ONLY FLOOR: at fixed mesh the anchor ladder stabilizes
     at a NONZERO E (the R319 false-floor mechanism on this probe's
     own elements).

THE OBJECT (v563/v716/v718/v749 machinery imported verbatim, zero
new constructors): U_ALL/MU_ALL (prime-power log nodes, von-Mangoldt
comb masses 2 Lambda(n)/sqrt(n)), atom_lags_at (T115 tent assembly),
arch_lags (exact Weil arch kernel vs tents, GL-48), pole_lags_closed
(v716), family_ext (v718 deployed frame-A family), the v749 tower
constructor c(D, X) = arch + atoms + pole at M = 2 alpha / D.  The
probe's single derived identity, used as the comb reference (proved
in-line by the tent algebra, gated at S1.3): the even lag read
L_cat(F) = F(0) c_0 + 2 sum_{d>=1} F(dD) c_d of the atom channel
equals -sum_n mu_n (I_D F)(u_n) EXACTLY, I_D = the piecewise-linear
interpolant on the D-grid -- so E_comb = -sum_n mu_n (I_D F - F)(u_n)
and E_comb == 0 identically on the native class (I_D F = F).

SEALED ADJUDICATION (frozen BEFORE the first full run; exactly one
primary letter; co-letters recorded independently):
  GATE_A: S1 all three channels stabilize exactly at the predicted
          onset on every sealed grid element (rel dev <= BAR_EXACT
          comb / BAR_GL arch+pole above onset, > ONSET_MIN below),
          AND mesh-constancy across two dyadic refinements
          (<= BAR_EXACT comb, <= BAR_GL arch/pole),
          AND the comb read identity vs the exact atom sum
          (<= BAR_EXACT).
  GATE_B: S3 deployed-window tower membership rel dev <= BAR_MEMBER
          on all three picked windows AND the direct rebuild ladder
          PD (Levinson, no breakdown, min E > 0) at every stage.
  GATE_C: S2 on every C^2 element (F2, F3), every mesh stage and
          every channel: |E_ch| <= envelope_ch + ABS_GL,
          AND every dyadic PER-CHANNEL defect ratio >= RATIO_DOWN
          (denominators below 1e-13 scale: stage skipped, disclosed;
          the TOTAL ratio is reported, not gated -- the smoke run
          measured comb/arch sign opposition that cancels in the
          total, an honest structural record).
          Subtype SIGN iff each channel's E carries ONE sign across
          all C^2 elements and stages, else subtype RATE.
  FLOOR:  at fixed D = 1/32 the anchor sweep stabilizes
          (|E(a_last) - E(a_prev)| <= 0.01 |E(a_last)|) at
          |E| > FLOOR_MIN on every smooth element.
  Primary: ELEMENTWISE_STABILIZATION_GO iff GATE_A; else
  CANONICAL_MESH_REBUILD_GO iff GATE_B; else
  SIGNED_DEFECT_CORRECTION_GO iff GATE_C; else
  ANCHOR_ONLY_INSUFFICIENT iff FLOOR; else
  NO_EXTRACTION_ARCHITECTURE.
  Co-letters: CANONICAL_MESH_REBUILD_GO iff GATE_B;
  SIGNED_DEFECT_CORRECTION_GO(SIGN|RATE) iff GATE_C;
  ANCHOR_ONLY_INSUFFICIENT iff FLOOR.
  The "comb exactly 0" reviewer parenthesis is adjudicated as a
  two-prong gate (S2.3): E_comb == 0 on the native class AND
  E_comb != 0 on the smooth class (the parenthesis holds exactly on
  the native class and FAILS off it -- whichever way it measures).

SEALED BARS: BAR_EXACT = 1e-12 (relative; float-exact identities),
BAR_GL = 5e-9 (the v749 BAR_REFINE GL-48 tolerance), BAR_MEMBER =
1e-13 (v749 T1.4b class), ONSET_MIN = 1e-6 (a truncated read must
differ), BAR_RICH = 1e-6 (Richardson reference gap), RATIO_DOWN = 1.8
(strict per-channel dyadic fall; the D^2 class value 4 is the
reported reference), FLOOR_MIN = 1e-9, ABS_GL = 1e-7 (additive GL
slack on the envelope gate).

MUST-FAILS (>= 3; all sealed with the tree):
  m1 ANCHOR-ONLY ADVERSARY: the claim "the fixed-mesh anchor ladder
     reaches Q_Weil" (|E_tot| <= 1e-9 scale at the deepest anchor,
     D = 1/32, on a smooth element) must FAIL -- the false-floor
     guard fires.
  m2 BROKEN TENT EXACTNESS: a nearest-neighbour read (instead of the
     linear-interpolation read) on a native grid element must
     violate the comb exactness bar.
  m3 CORRUPTED TRANSPORT: the dyadic lag identity with full (not
     half) neighbour weights must violate BAR_GL.
  m4 MEMBERSHIP CORRUPTION: a 1e-6 perturbation of one deployed lag
     must violate BAR_MEMBER.

PROTOCOL: deterministic (seeded elements, no data downloads);
run1/run2 identical up to WALL; --smoke = reduced config (one grid
element, F2 only, two meshes, coarser references), same gates.
Record tables are inserted AFTER the first full run (r316/r317
protocol; the insertion is the only post-freeze change).
SMOKE-HARNESS FIXES (disclosed, all BEFORE the first full run =
the freeze; r318 class): (1) the grid-element constructor omitted
the closing zero knot -- np.interp created a jump at the last knot
and the kernel-channel midpoint reads across that cell were wrong
by ~1e-6 (the dyadic lag identity itself measured machine-exact,
arch 1.1e-16 / pole 0.0); (2) the decay gate retyped from the
total defect to PER-CHANNEL ratios after the smoke run measured
comb/arch sign opposition cancelling in the total (recorded as a
finding, not gated away); (3) a smoke-config index bug in S2.3.

RECORD (2026-08-27, inserted after the first full run per the
r316/r317 protocol -- this insertion is the only post-freeze
change; freeze-run SPEC_SHA 57e50d366a62f2a6, all numbers below
byte-identical on run1/run2 after insertion):
  S1 anchor-onset (comb rel dev to the deep reference):
    g1 (seed 11, n_g 48, D0 1/32, a* 0.766):
       a=0.35: 2.65e-02 | 0.55: 6.10e-03 | 1.0/2.0/3.0: 3.3e-18
    g2 (seed 12, n_g 40, D0 1/32, a* 0.641):
       a=0.35: 5.34e-02 | 0.55: 4.92e-02 | 1.0/2.0/3.0: 0.0
    g3 (seed 13, n_g 96, D0 1/64, a* 0.758):
       a=0.35: 1.76e-02 | 0.55: 2.04e-02 | 1.0/2.0/3.0: 1.7e-18
    mesh constancy D0 -> D0/2 -> D0/4 (worst): comb 3.3e-18,
    arch 1.5e-15, pole 2.0e-17 -- the native mesh IS the limit
  S2 defect E_ch(D, F) at alpha 2.5 (sign carried):
    F1_tent (C^0, L=1.7; report only): comb +2.2e-16 EXACTLY 0 --
       the off-grid kink cells contain NO prime-power atom (honest
       fluke, recorded); arch -6.09e-05 -> -1.02e-05 -> -3.81e-06;
       pole +3.82e-04 -> +6.35e-05 -> +2.38e-05
    F2_quartic (C^2, L=2.3): comb -3.00e-04 -> -4.97e-05 ->
       -5.52e-06 (ratios 6.05, 9.01); arch +3.67e-04 -> +1.02e-04
       -> +2.82e-05 (3.58, 3.63); pole +1.11e-04 -> +2.71e-05 ->
       +6.82e-06 (4.10, 3.97); total ratios 2.22, 2.70 (reported)
    F3_hann (C^2, L=2.9): comb -2.69e-04 -> -6.67e-05 -> -1.15e-05
       (4.03, 5.81); arch +2.91e-04 -> +8.11e-05 -> +2.23e-05
       (3.59, 3.63); pole +1.36e-04 -> +3.39e-05 -> +8.42e-06
       (4.03, 4.02); total ratios 3.29, 2.51 (reported)
    sign census (C^2, all stages): comb NEGATIVE, arch POSITIVE,
       pole POSITIVE, total POSITIVE -> subtype SIGN; the comb/arch
       opposition cancels in the total (the reported-only ratios)
    anchor floor (D=1/32, a = 2.0/2.5/3.0/3.5): E_tot CONSTANT at
       +1.77e-04 (F2) / +1.59e-04 (F3) -- stable and nonzero
    comb two-prong: native 6.9e-18 (exactly 0) vs smooth 3.00e-04
  S3: membership rel dev 0.0 / 0.0 / 0.0 (deployed picks 0/mid/
    last); rebuild ladder alpha 2.5, D = 1/64 -> 1/128 -> 1/256:
    PD 3/3, lambda_min/c_0 = 1.33e-05 -> 3.34e-06 -> 6.92e-07
    (falling, reported not consumed); transport identity 8.0e-17
  VERDICT: primary ELEMENTWISE_STABILIZATION_GO; co-letters
    CANONICAL_MESH_REBUILD_GO + SIGNED_DEFECT_CORRECTION_GO(SIGN)
    + ANCHOR_ONLY_INSUFFICIENT; must-fails m1-m4 all CAUGHT
    (6.5e-02 / 1.5e-01 / 4.4e-07 against their bars).
    18/18 gates PASS, 0.4 s full / 0.2 s smoke.

EXPLORATION ONLY (2026-08-27).  experiments/ level: NO promotion,
NO ledger row, NO marker moved, NO RH CLAIM in either direction.
Coexistence: the wave-12 worker (v969) and R324 (QMAX x M_2) run in
parallel; this probe touches nothing outside its own file and the
strictly additive rh-sync.
"""

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

import numpy as np
import scipy.linalg as sla

_here = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _here)
sys.path.insert(0, os.path.abspath(os.path.join(_here, "..", "..",
                                                "verification")))

import v563_paper2_readouts as core            # noqa: E402
import v716_moonshot_arch_glue as stage2       # noqa: E402
import v718_moonshot_spectral as stage4        # noqa: E402
import v696_z1_jacobi as jac                   # noqa: E402

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

# ---------------------------------------------------------- sealed bars
BAR_EXACT = 1.0e-12     # float-exact identities (relative)
BAR_GL = 5.0e-9         # GL-48 arch tolerance (v749 BAR_REFINE)
BAR_MEMBER = 1.0e-13    # tower membership (v749 T1.4b class)
ONSET_MIN = 1.0e-6      # below-onset reads must genuinely differ
BAR_RICH = 1.0e-6       # Richardson reference gap (relative)
RATIO_DOWN = 1.8        # strict per-channel dyadic fall (4 = D^2 ref)
FLOOR_MIN = 1.0e-9      # anchor floor must be genuinely nonzero
ABS_GL = 1.0e-7         # additive GL slack on the envelope gate

# ------------------------------------------------------- sealed configs
# S1 native grid elements: (seed, n_g, D0); support n_g * D0,
# predicted onset alpha* = (n_g + 1) * D0 / 2.
GRID_ELEMENTS = ((11, 48, 1.0 / 32.0),
                 (12, 40, 1.0 / 32.0),
                 (13, 96, 1.0 / 64.0))
ALPHA_SWEEP = (0.35, 0.55, 1.0, 2.0, 3.0)
ALPHA_MESHCONST = 2.0

# S2 non-native sealed class: (name, kind, half-width L, ||F''||_inf
# or None for C^0).  Widths chosen off-grid on every dyadic mesh.
SMOOTH_ELEMENTS = (("F1_tent", "tent", 1.7, None),
                   ("F2_quartic", "quartic", 2.3, 8.0 / 2.3 ** 2),
                   ("F3_hann", "hann", 2.9, math.pi ** 2 / (2 * 2.9 ** 2)))
ALPHA_C = 2.5
MESHES_C = (1.0 / 32.0, 1.0 / 64.0, 1.0 / 128.0)
ALPHA_FLOOR = (2.0, 2.5, 3.0, 3.5)

# S3 rebuild ladder
ALPHA_B = 2.5
MESHES_B = (1.0 / 64.0, 1.0 / 128.0, 1.0 / 256.0)


def check(name, ok, detail=""):
    ok = bool(ok)
    CHECKS.append((name, ok, detail))
    print("  [%s] %-46s %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)


# ---------------------------------------------------------- constructors
def channel_lags(D, alpha):
    """The v749 tower member at (D, X = e^{2 alpha}), per channel:
    M = 2 alpha / D lags; comb = T115 tent assembly of the atoms
    n <= e^{2 al}; arch = exact Weil-kernel tent integrals (GL-48);
    pole = v716 closed form.  Verbatim constructor chain."""
    M = int(round(2.0 * alpha / D))
    al = 0.5 * M * D
    ka = core.atoms_in(al)
    cat, _dd = core.atom_lags_at(al, M, core.U_ALL[:ka], core.MU_ALL[:ka])
    car = core.arch_lags(M, D)
    cp = stage2.pole_lags_closed(M, D)
    return dict(M=M, al=al, ka=ka, cat=cat, car=car, cp=cp)


def read_lags(c, D, F, Lsup):
    """The even lag read L_c(F) = F(0) c_0 + 2 sum_{d>=1} F(dD) c_d,
    truncated at the support (F == 0 beyond Lsup)."""
    dmax = min(len(c), int(math.floor(Lsup / D)) + 3)
    dd = np.arange(dmax, dtype=float) * D
    vals = F(dd)
    return float(vals[0] * c[0] + 2.0 * float(vals[1:] @ c[1:dmax]))


def grid_element(seed, ng, D0):
    """A native element: F = D0 * autocorr(x) of a seeded step
    function on the D0-grid -- piecewise linear with knots on the
    grid, support [-(ng) D0, ng D0].  Sealed BEFORE any sign read."""
    rng = np.random.default_rng(seed)
    x = rng.standard_normal(ng)
    a = np.append(np.correlate(x, x, "full")[ng - 1:] * D0, 0.0)
    knots = np.arange(ng + 1, dtype=float) * D0   # closing zero knot

    def F(u):
        return np.interp(np.abs(np.asarray(u, dtype=float)), knots, a,
                         right=0.0)
    return F, float(ng * D0)


def smooth_element(kind, L):
    """The sealed non-native class: even, compactly supported on
    [-L, L], evaluated exactly (closed forms)."""
    if kind == "tent":
        def F(u):
            t = np.abs(np.asarray(u, dtype=float)) / L
            return np.maximum(0.0, 1.0 - t)
    elif kind == "quartic":
        def F(u):
            t = np.abs(np.asarray(u, dtype=float)) / L
            v = np.maximum(0.0, 1.0 - t * t)
            return v * v
    elif kind == "hann":
        def F(u):
            t = np.abs(np.asarray(u, dtype=float)) / L
            return np.where(t < 1.0,
                            0.5 * (1.0 + np.cos(math.pi
                                                * np.minimum(t, 1.0))), 0.0)
    else:
        raise ValueError(kind)
    return F


def comb_ref(F, alpha_eff):
    """The exact comb reference -sum_n mu_n F(u_n) over the window
    atom set n <= e^{2 al} (mesh-free; the derived tent identity
    makes L_cat(F) = -sum_n mu_n (I_D F)(u_n))."""
    ka = core.atoms_in(alpha_eff)
    return -float(core.MU_ALL[:ka] @ F(core.U_ALL[:ka]))


def kernel_ref_lags(D_ref, Lsup, builder):
    """Fine-mesh kernel lags over the support only (reference)."""
    M = int(math.floor(Lsup / D_ref)) + 4
    return builder(M, D_ref)


# ------------------------------------------------------------ G0 firewall
def g0_firewall():
    section("G0  FIREWALL")
    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", "prime" + "pi"}
    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))
    check("G0.1 zero/prime-oracle-free", not bad,
          "constructors = v563 sieve + v563/v716 kernels only"
          if not bad else "; ".join(bad))
    fitfrags = ("poly" + "fit", "curve_" + "fit", "lst" + "sq",
                "mini" + "mize")
    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
        if nm and any(f in nm for f in fitfrags):
            hits.append("%s@%d" % (nm, node.lineno))
    check("G0.2 no fitting anywhere", not hits,
          "decay ratios are raw quotients, envelopes closed-form"
          if not hits else "; ".join(hits))


# ================================================================== S1
def s1_elementwise(cfg):
    """VARIANT A measured half: per-channel finite stabilization on
    the native class, in the anchor direction, at the PREDICTED
    onset; plus mesh-constancy (no hidden refinement)."""
    section("S1  VARIANT A -- ELEMENTWISE STABILIZATION (native class)")
    ok_onset = True
    ok_below = True
    ok_exact = True
    rows = []
    for (seed, ng, D0) in cfg["grid_elements"]:
        F, Lsup = grid_element(seed, ng, D0)
        astar = (ng + 1) * D0 / 2.0
        # reference: exact atom sum at the deepest sweep anchor
        ch_deep = channel_lags(D0, cfg["alpha_sweep"][-1])
        ref_comb = comb_ref(F, ch_deep["al"])
        ref_arch = read_lags(ch_deep["car"], D0, F, Lsup)
        ref_pole = read_lags(ch_deep["cp"], D0, F, Lsup)
        sc = max(abs(ref_comb), abs(ref_arch), abs(ref_pole), 1.0e-6)
        # comb tent-exactness at the deep anchor (the derived identity)
        dev_id = abs(read_lags(ch_deep["cat"], D0, F, Lsup)
                     - ref_comb) / sc
        ok_exact &= dev_id <= BAR_EXACT
        devs = []
        for a in cfg["alpha_sweep"]:
            ch = channel_lags(D0, a)
            dc = abs(read_lags(ch["cat"], D0, F, Lsup) - ref_comb) / sc
            da = abs(read_lags(ch["car"], D0, F, Lsup) - ref_arch) / sc
            dp = abs(read_lags(ch["cp"], D0, F, Lsup) - ref_pole) / sc
            devs.append((a, dc, da, dp))
            if a >= astar + D0:
                ok_onset &= max(dc, da, dp) <= max(BAR_EXACT, BAR_GL)
            elif 2.0 * ch["al"] < Lsup - D0:
                ok_below &= max(dc, da, dp) > ONSET_MIN
        rows.append("g(seed %d, n_g %d, D0 1/%d, a* %.3f): comb %s "
                    "| tent-id %.1e"
                    % (seed, ng, int(round(1.0 / D0)),
                       astar,
                       ", ".join("a=%g: %.2e" % (a, dc)
                                 for (a, dc, _da, _dp) in devs), dev_id))
    for r in rows:
        info(r)
    check("S1.1 finite anchor stabilization EXACT", ok_onset,
          "all channels, every element, every anchor >= alpha* + D0: "
          "rel dev <= %.0e (comb) / %.0e (arch,pole) -- the R310 "
          "finite_forms_converge_to_weil shape holds for ALL channels "
          "on the native class" % (BAR_EXACT, BAR_GL))
    check("S1.2 below-onset reads genuinely differ", ok_below,
          "truncated windows (2 al < support) deviate > %.0e -- the "
          "onset is real, not vacuous" % ONSET_MIN)
    check("S1.3 comb tent-read identity", ok_exact,
          "L_cat(F) == -sum_n mu_n (I_D F)(u_n) == -sum_n mu_n F(u_n) "
          "on the native class (I_D F = F), rel dev <= %.0e" % BAR_EXACT)

    # mesh constancy: refining the mesh does not move the value
    ok_mc_comb = True
    ok_mc_kern = True
    worst = dict(comb=0.0, arch=0.0, pole=0.0)
    for (seed, ng, D0) in cfg["grid_elements"]:
        F, Lsup = grid_element(seed, ng, D0)
        base = channel_lags(D0, cfg["alpha_meshconst"])
        v0 = dict(comb=read_lags(base["cat"], D0, F, Lsup),
                  arch=read_lags(base["car"], D0, F, Lsup),
                  pole=read_lags(base["cp"], D0, F, Lsup))
        sc = max(*[abs(v) for v in v0.values()], 1.0e-6)
        for k in (2, 4):
            ch = channel_lags(D0 / k, cfg["alpha_meshconst"])
            dc = abs(read_lags(ch["cat"], D0 / k, F, Lsup)
                     - v0["comb"]) / sc
            da = abs(read_lags(ch["car"], D0 / k, F, Lsup)
                     - v0["arch"]) / sc
            dp = abs(read_lags(ch["cp"], D0 / k, F, Lsup)
                     - v0["pole"]) / sc
            worst["comb"] = max(worst["comb"], dc)
            worst["arch"] = max(worst["arch"], da)
            worst["pole"] = max(worst["pole"], dp)
            ok_mc_comb &= dc <= BAR_EXACT
            ok_mc_kern &= max(da, dp) <= BAR_GL
    check("S1.4 mesh constancy (no hidden refinement)", 
          ok_mc_comb and ok_mc_kern,
          "native value CONSTANT under D0 -> D0/2 -> D0/4: comb %.1e "
          "(exact), arch %.1e, pole %.1e (GL) -- the element's native "
          "mesh already carries the limit value"
          % (worst["comb"], worst["arch"], worst["pole"]))
    return dict(ok=(ok_onset and ok_below and ok_exact
                    and ok_mc_comb and ok_mc_kern))


# ================================================================== S2
def s2_defect(cfg):
    """VARIANT C measured half: the per-channel quadrature defect
    E_ch(D, F) on the sealed non-native class, its sign census, its
    dyadic decay, the rigorous interpolation envelope, and the
    anchor-only floor."""
    section("S2  VARIANT C -- QUADRATURE DEFECT (non-native class)")
    D_fine = min(cfg["meshes_c"])
    Lmax = max(t[2] for t in cfg["smooth_elements"])
    # Richardson-gated kernel references over the support
    dref1, dref2 = D_fine / cfg["ref_div"], D_fine / (2 * cfg["ref_div"])
    car1 = kernel_ref_lags(dref1, Lmax, core.arch_lags)
    car2 = kernel_ref_lags(dref2, Lmax, core.arch_lags)
    cp1 = kernel_ref_lags(dref1, Lmax, stage2.pole_lags_closed)
    cp2 = kernel_ref_lags(dref2, Lmax, stage2.pole_lags_closed)
    ok_rich = True
    for (_name, kind, L, _f2) in cfg["smooth_elements"]:
        F = smooth_element(kind, L)
        for (ca, cb, dpa, dpb) in ((car1, car2, dref1, dref2),
                                   (cp1, cp2, dref1, dref2)):
            r1 = read_lags(ca, dpa, F, L)
            r2 = read_lags(cb, dpb, F, L)
            ok_rich &= abs(r1 - r2) <= BAR_RICH * max(1.0, abs(r2))
    check("S2.0 Richardson reference gate", ok_rich,
          "arch/pole references at D_ref = %.1e vs %.1e agree to "
          "<= %.0e rel on every element" % (dref1, dref2, BAR_RICH))

    # read-weighted absolute kernel masses for the envelopes
    def abs_mass(c, D_ref, L):
        dmax = min(len(c), int(math.floor(L / D_ref)) + 3)
        return float(abs(c[0]) + 2.0 * np.sum(np.abs(c[1:dmax])))

    ok_env = True
    ok_ratio = True
    sign_tab = dict(comb=set(), arch=set(), pole=set(), tot=set())
    e_records = {}
    for (name, kind, L, f2max) in cfg["smooth_elements"]:
        F = smooth_element(kind, L)
        r_arch = read_lags(car2, dref2, F, L)
        r_pole = read_lags(cp2, dref2, F, L)
        e_by_mesh = []
        for D in cfg["meshes_c"]:
            ch = channel_lags(D, cfg["alpha_c"])
            r_comb = comb_ref(F, ch["al"])
            ec = read_lags(ch["cat"], D, F, L) - r_comb
            ea = read_lags(ch["car"], D, F, L) - r_arch
            ep = read_lags(ch["cp"], D, F, L) - r_pole
            e_by_mesh.append((D, ec, ea, ep, ec + ea + ep))
            if f2max is not None:
                ka = core.atoms_in(ch["al"])
                inside = core.U_ALL[:ka] <= L + D
                k_comb = float(np.sum(core.MU_ALL[:ka][inside]))
                env = (D * D / 8.0) * f2max
                ok_env &= abs(ec) <= env * k_comb + ABS_GL
                ok_env &= abs(ea) <= env * abs_mass(car2, dref2, L) + ABS_GL
                ok_env &= abs(ep) <= env * abs_mass(cp2, dref2, L) + ABS_GL
                for key, val in (("comb", ec), ("arch", ea),
                                 ("pole", ep), ("tot", ec + ea + ep)):
                    sign_tab[key].add(1 if val > 0 else -1)
        e_records[name] = e_by_mesh
        info("%s (L=%.1f): %s" % (name, L, " | ".join(
            "D=1/%d: comb %+.2e arch %+.2e pole %+.2e"
            % (int(round(1.0 / D)), ec, ea, ep)
            for (D, ec, ea, ep, _et) in e_by_mesh)))
        if f2max is not None:
            sc = max(abs(r_arch), abs(r_pole), 1.0e-6)
            for i in range(len(e_by_mesh) - 1):
                rr = []
                for j, chn in ((1, "comb"), (2, "arch"), (3, "pole")):
                    num = abs(e_by_mesh[i][j])
                    den = abs(e_by_mesh[i + 1][j])
                    if den > 1.0e-13 * sc:
                        ratio = num / den
                        ok_ratio &= ratio >= RATIO_DOWN
                        rr.append("%s %.2f" % (chn, ratio))
                    else:
                        rr.append("%s skipped" % chn)
                tot_r = (abs(e_by_mesh[i][4]) / abs(e_by_mesh[i + 1][4])
                         if abs(e_by_mesh[i + 1][4]) > 1.0e-13 * sc
                         else float("nan"))
                info("  %s dyadic ratios D=1/%d -> 1/%d: %s "
                     "(total %.2f, reported only)"
                     % (name, int(round(1.0 / e_by_mesh[i][0])),
                        int(round(1.0 / e_by_mesh[i + 1][0])),
                        ", ".join(rr), tot_r))
    check("S2.1 rigorous envelope holds (C^2 elements)", ok_env,
          "|E_ch| <= (D^2/8) ||F''|| K_ch + %.0e on every channel/"
          "stage -- the defect is controlled ON ITS OWN (closed-form "
          "interpolation bound; no wall margin anywhere)" % ABS_GL)
    check("S2.2 per-channel dyadic fall >= %.1f (C^2)" % RATIO_DOWN,
          ok_ratio, "every channel's defect falls strictly at every "
          "dyadic step (D^2 reference value 4; the TOTAL ratio is "
          "reported only -- comb/arch sign opposition cancels there)")
    one_signed = all(len(sign_tab[k]) == 1
                     for k in ("comb", "arch", "pole"))
    subtype = "SIGN" if one_signed else "RATE"
    info("sign census (C^2): comb %s arch %s pole %s tot %s -> "
         "subtype %s"
         % tuple([sorted(sign_tab[k]) for k in
                  ("comb", "arch", "pole", "tot")] + [subtype]))

    # the comb two-prong ("comb exactly 0" adjudication)
    (seed, ng, D0) = cfg["grid_elements"][0]
    Fg, Lg = grid_element(seed, ng, D0)
    chg = channel_lags(D0, cfg["alpha_c"])
    e_native = abs(read_lags(chg["cat"], D0, Fg, Lg)
                   - comb_ref(Fg, chg["al"]))
    name2, kind2, L2, _ = cfg["smooth_elements"][min(
        1, len(cfg["smooth_elements"]) - 1)]
    F2 = smooth_element(kind2, L2)
    ch2 = channel_lags(cfg["meshes_c"][0], cfg["alpha_c"])
    e_smooth = abs(read_lags(ch2["cat"], cfg["meshes_c"][0], F2, L2)
                   - comb_ref(F2, ch2["al"]))
    check("S2.3 comb two-prong", 
          e_native <= BAR_EXACT and e_smooth > 1.0e-6,
          "E_comb native %.1e (exactly 0) vs smooth %.2e (NOT 0) -- "
          "the reviewer parenthesis 'comb exactly 0' holds ONLY on "
          "the native class" % (e_native, e_smooth))

    # anchor-only floor
    ok_floor = True
    for (name, kind, L, f2max) in cfg["smooth_elements"]:
        if f2max is None:
            continue
        F = smooth_element(kind, L)
        r_arch = read_lags(car2, dref2, F, L)
        r_pole = read_lags(cp2, dref2, F, L)
        es = []
        for a in cfg["alpha_floor"]:
            ch = channel_lags(cfg["meshes_c"][0], a)
            et = (read_lags(ch["cat"], cfg["meshes_c"][0], F, L)
                  - comb_ref(F, ch["al"])
                  + read_lags(ch["car"], cfg["meshes_c"][0], F, L)
                  - r_arch
                  + read_lags(ch["cp"], cfg["meshes_c"][0], F, L)
                  - r_pole)
            es.append(et)
        stab = abs(es[-1] - es[-2]) <= 0.01 * abs(es[-1])
        ok_floor &= stab and abs(es[-1]) > FLOOR_MIN
        info("%s anchor sweep (D=1/%d): E_tot %s -> floor %s"
             % (name, int(round(1.0 / cfg["meshes_c"][0])),
                ", ".join("%+.2e" % e for e in es),
                "STABLE-NONZERO" if stab and abs(es[-1]) > FLOOR_MIN
                else "?"))
    check("S2.4 anchor-only floor reproduced", ok_floor,
          "at fixed mesh the anchor ladder stabilizes at a NONZERO "
          "defect (> %.0e) -- the R319 false-floor mechanism on this "
          "probe's own elements: the anchor direction cannot repair "
          "the mesh defect" % FLOOR_MIN)
    return dict(ok_env=ok_env, ok_ratio=ok_ratio, ok_rich=ok_rich,
                subtype=subtype, ok_floor=ok_floor,
                gate_c=(ok_rich and ok_env and ok_ratio),
                records=e_records)


# ================================================================== S3
def s3_rebuild(cfg):
    """VARIANT B measured half: tower membership of the deployed
    windows (v749 T1.4b class), direct-rebuild ladder PD, and the
    (unconsumed) dyadic transport identity."""
    section("S3  VARIANT B -- CANONICAL MESH REBUILD")
    wins = stage4.family_ext()
    picks = ([wins[0]] if cfg["smoke"]
             else [wins[0], wins[len(wins) // 2], wins[-1]])
    ok_mem = True
    devs = []
    for w in picks:
        ch = channel_lags(w["D"], w["alpha"])
        c_tw = ch["car"] + ch["cat"] + ch["cp"]
        sc = float(np.max(np.abs(w["p"])))
        dev = float(np.max(np.abs(c_tw[:w["M"]] - w["p"]))) / sc
        devs.append(dev)
        ok_mem &= dev <= BAR_MEMBER
    check("S3.1 deployed windows ARE rebuilt members", ok_mem,
          "lag vector == direct constructor at (D_w, alpha_w), rel "
          "dev %s (v749 T1.4b reproduced: NO transport is needed to "
          "reach any deployed window)"
          % ", ".join("%.1e" % d for d in devs))

    ok_pd = True
    margins = []
    for D in cfg["meshes_b"]:
        ch = channel_lags(D, cfg["alpha_b"])
        c = ch["car"] + ch["cat"] + ch["cp"]
        ks, Es, bd = jac.levinson(c, len(c) - 1)
        pd = (bd is None) and float(np.min(Es)) > 0.0
        ok_pd &= pd
        lam = float(np.min(np.linalg.eigvalsh(sla.toeplitz(c))))
        margins.append("D=1/%d: PD %s, lambda_min/c_0 %.2e"
                       % (int(round(1.0 / D)), pd, lam / c[0]))
    check("S3.2 direct rebuild ladder PD per stage", ok_pd,
          "%s -- every stage carries its own PSD certificate (the "
          "variant-B premise measured; the falling relative margin "
          "is the honest price, reported not consumed" 
          % "; ".join(margins))

    # transport identity: exists, measured, NOT consumed by B
    dev_lag = 0.0
    Dc, Df = cfg["meshes_b"][0], cfg["meshes_b"][1]
    cc = channel_lags(Dc, cfg["alpha_b"])
    cf = channel_lags(Df, cfg["alpha_b"])
    c = cc["car"] + cc["cat"] + cc["cp"]
    c2 = cf["car"] + cf["cat"] + cf["cp"]
    M = len(c)
    d = np.arange(1, M - 1)
    pred = c2[2 * d] + 0.5 * (c2[2 * d - 1] + c2[2 * d + 1])
    sc = float(np.max(np.abs(c)))
    dev_lag = float(np.max(np.abs(c[1:M - 1] - pred))) / sc
    check("S3.3 dyadic transport identity (unconsumed)", 
          dev_lag <= BAR_GL,
          "c^(D)_d == c^(D/2)_2d + (c'_2d-1 + c'_2d+1)/2, rel dev "
          "%.1e -- transport EXISTS (v749 T1.2a) but variant B never "
          "uses it: each stage is built from source" % dev_lag)
    return dict(ok=(ok_mem and ok_pd), ok_mem=ok_mem, ok_pd=ok_pd)


# ============================================================ must-fails
def s4_mustfails(cfg):
    section("S4  MUST-FAILS (sealed mutants)")
    # m1 anchor-only adversary
    name2, kind2, L2, _ = cfg["smooth_elements"][min(
        1, len(cfg["smooth_elements"]) - 1)]
    F2 = smooth_element(kind2, L2)
    D = cfg["meshes_c"][0]
    dref = min(cfg["meshes_c"]) / (2 * cfg["ref_div"])
    car = kernel_ref_lags(dref, L2, core.arch_lags)
    cp = kernel_ref_lags(dref, L2, stage2.pole_lags_closed)
    ch = channel_lags(D, cfg["alpha_floor"][-1])
    e_tot = (read_lags(ch["cat"], D, F2, L2) - comb_ref(F2, ch["al"])
             + read_lags(ch["car"], D, F2, L2)
             - read_lags(car, dref, F2, L2)
             + read_lags(ch["cp"], D, F2, L2)
             - read_lags(cp, dref, F2, L2))
    adversary_claim = abs(e_tot) <= 1.0e-9 * max(1.0, abs(e_tot))
    check("m1 anchor-only adversary CAUGHT", not adversary_claim,
          "'deepest anchor at fixed mesh reaches Q_Weil' is FALSE: "
          "|E_tot| = %.2e stays" % abs(e_tot))

    # m2 broken tent exactness: a nearest-neighbour ATOM PLACEMENT
    # in the reference (the sloppy assembly: each atom snapped to its
    # closest grid node instead of the exact tent split)
    (seed, ng, D0) = cfg["grid_elements"][0]
    Fg, Lg = grid_element(seed, ng, D0)
    chg = channel_lags(D0, cfg["alpha_meshconst"])
    ka = core.atoms_in(chg["al"])
    u_snap = np.round(core.U_ALL[:ka] / D0) * D0
    ref_nn = -float(core.MU_ALL[:ka] @ Fg(u_snap))
    dev_nn = abs(read_lags(chg["cat"], D0, Fg, Lg) - ref_nn)
    sc = max(abs(comb_ref(Fg, chg["al"])), 1.0e-6)
    check("m2 broken tent read CAUGHT", dev_nn / sc > BAR_EXACT,
          "nearest-neighbour atom placement violates the exactness "
          "bar: rel dev %.2e >> %.0e" % (dev_nn / sc, BAR_EXACT))

    # m3 corrupted transport weights
    Dc, Df = cfg["meshes_b"][0], cfg["meshes_b"][1]
    cc = channel_lags(Dc, cfg["alpha_b"])
    cf = channel_lags(Df, cfg["alpha_b"])
    c = cc["car"] + cc["cat"] + cc["cp"]
    c2 = cf["car"] + cf["cat"] + cf["cp"]
    M = len(c)
    d = np.arange(1, M - 1)
    pred_bad = c2[2 * d] + (c2[2 * d - 1] + c2[2 * d + 1])   # full weight
    dev_bad = float(np.max(np.abs(c[1:M - 1] - pred_bad))) \
        / float(np.max(np.abs(c)))
    check("m3 corrupted transport CAUGHT", dev_bad > BAR_GL,
          "full-weight neighbour rule violates the identity: rel dev "
          "%.2e >> %.0e" % (dev_bad, BAR_GL))

    # m4 membership corruption
    wins = stage4.family_ext()
    w = wins[0]
    ch = channel_lags(w["D"], w["alpha"])
    c_tw = ch["car"] + ch["cat"] + ch["cp"]
    p_bad = w["p"].copy()
    p_bad[len(p_bad) // 2] += 1.0e-6
    dev_mem = float(np.max(np.abs(c_tw[:w["M"]] - p_bad))) \
        / float(np.max(np.abs(p_bad)))
    check("m4 membership corruption CAUGHT", dev_mem > BAR_MEMBER,
          "a 1e-6 lag perturbation violates the membership bar: rel "
          "dev %.2e >> %.0e" % (dev_mem, BAR_MEMBER))


# ================================================================== S5
def s5_verdict(r1, r2, r3):
    section("S5  SEALED VERDICT")
    gate_a = r1["ok"]
    gate_b = r3["ok"]
    gate_c = r2["gate_c"]
    floor = r2["ok_floor"]
    if gate_a:
        primary = "ELEMENTWISE_STABILIZATION_GO"
    elif gate_b:
        primary = "CANONICAL_MESH_REBUILD_GO"
    elif gate_c:
        primary = "SIGNED_DEFECT_CORRECTION_GO"
    elif floor:
        primary = "ANCHOR_ONLY_INSUFFICIENT"
    else:
        primary = "NO_EXTRACTION_ARCHITECTURE"
    co = []
    if gate_b:
        co.append("CANONICAL_MESH_REBUILD_GO")
    if gate_c:
        co.append("SIGNED_DEFECT_CORRECTION_GO(%s)" % r2["subtype"])
    if floor:
        co.append("ANCHOR_ONLY_INSUFFICIENT")
    print("""
  THE MEASURED FORK (honest scope):
  A  the native class stabilizes FINITELY in the anchor direction,
     per channel, at the predicted onset, and its value is CONSTANT
     under mesh refinement -- the elementwise architecture consumes
     NO mesh-cofinal ladder and NO transport.  The mesh limit
     reappears ONLY off the native class, where it is a rate-
     controlled quadrature defect (leg C), i.e. the classical
     density/continuity step -- not a positivity ladder.
  B  every deployed window is a directly rebuilt canonical member
     (dev 0 class); the rebuild ladder carries per-stage PSD
     certificates with honestly falling margins; the transport
     identity exists but is never consumed.
  C  the defect is one-sided per channel on the C^2 class and sits
     inside the closed-form interpolation envelope -- controlled on
     its own, no wall margin; the anchor-only floor is real.
  NOTHING here proves any window positivity, any local lemma, or
  any statement about zeta zeros.  NO RH CLAIM.""")
    print("\n  PRIMARY: %s" % primary)
    if co:
        print("  CO-LETTERS: %s" % " + ".join(co))
    return primary


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

    cfg = dict(
        smoke=smoke,
        grid_elements=GRID_ELEMENTS[:1] if smoke else GRID_ELEMENTS,
        alpha_sweep=(0.55, 1.0, 2.0) if smoke else ALPHA_SWEEP,
        alpha_meshconst=ALPHA_MESHCONST,
        smooth_elements=(SMOOTH_ELEMENTS[1],) if smoke
        else SMOOTH_ELEMENTS,
        alpha_c=ALPHA_C,
        meshes_c=MESHES_C[:2] if smoke else MESHES_C,
        alpha_floor=ALPHA_FLOOR[-2:] if smoke else ALPHA_FLOOR,
        alpha_b=ALPHA_B,
        meshes_b=MESHES_B[:2] if smoke else MESHES_B,
        ref_div=8 if smoke else 16,
    )

    print("PRIME.EXTRACTION.ORDER_REPAIR_FORK.01 -- round 325%s"
          % ("  [SMOKE]" if smoke else ""))
    print("SPEC_SHA %s" % SPEC_SHA[:16])
    g0_firewall()
    r1 = s1_elementwise(cfg)
    r2 = s2_defect(cfg)
    r3 = s3_rebuild(cfg)
    s4_mustfails(cfg)
    primary = s5_verdict(r1, r2, r3)

    n_ok = sum(1 for _n, ok, _d in CHECKS if ok)
    print("\nRESULT: %d/%d gates PASS   VERDICT %s   SPEC_SHA %s"
          % (n_ok, len(CHECKS), primary, SPEC_SHA[:16]))
    print("wall %.1f s" % (time.time() - T0_WALL))
    return 0 if n_ok == len(CHECKS) else 1


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

_SRC_3 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""group_mass_cap_probe -- PRIME.L2.RENYI3.GROUP_MASS_CAP.01
(round 327): THE FOLD-GROUP MASS CAP -- the r324 follow-up question
on the terminal main lane.

CONTEXT (binding, from the sealed r324 record): the composition to
terminal_positive_main stands as MEASURED (PILEUP_GROWS_SUBCRITICAL,
e_tot +0.172 < CRIT 0.224, m_0* = 10^59.6 astronomical, the gap
(274, 10^59.6) the disclosed extrapolation hypothesis).  The
mechanism is HALF understood: the scale count O(log m) is pointwise
CERTIFIED (C_NSC 2.026, 0/39) but the per-scale mass O(1/m) is
REFUTED (11/39) -- the near-critical windows are a SINGLE heavy
source scale at the argmax block (kz53: s0 carries 13.78 of
G 13.02), not multiscale convergence.  The r324-named follow-up:
WHAT CAPS THE MASS OF THE DOMINANT FOLD GROUP?  The fold
multiplicity <= 2 holds uniformly (69/69, the r313/r314 banked
asset) -- the cap must come from the PER-GROUP MASS BALANCE.  A
theorem of the form  m x (mass of the heaviest group)/L <= C_G x
(log m)^A  would, via the certified scale-count bound and the exact
chain m q_max <= nsc x pil (slack 0.0, r324), deliver the direct
q_max bound and possibly push the +0.172 exponent to polylog -- or
explain its unavoidability.

THE THREE QUESTIONS (sealed):
Q1 -- ANATOMY OF THE HEAVY GROUP: what IS the dominant fold group
   at the spikes structurally?  Its two ancestors (mult 2: one
   bulk atom +ct and/or one window atom -cw at one position),
   their values and internal alignment |sum|/(sum| |), its
   position inside the block (the r322 mid/tail thirds), its gap
   to the second-heaviest group (census over the ladder), and the
   SOURCE-vs-AGGREGATION adjudication: is the r324 heavy SCALE
   carried by ONE group (source: two large source masses meet --
   then the cap is a statement about source-pair coincidences) or
   by MANY groups that the fold bundles (aggregation)?  Sealed
   rule: ANATOMY = SOURCE iff the med over the three named
   near-critical rungs of ratio = hga/(max scale mass of the
   argmax block) >= RATIO_BAR = 0.5, else AGGREGATION.
Q2 -- THE CAP CANDIDATES (source-pure, all mid-ladder frozen, TRB
   split verbatim, test pointwise, named coverage printed):
   (i) THE TWO-ANCESTOR / LAMBDA-PAIR ROUTE: per group EXACTLY
       gabs_g <= mult_g x gmax_g <= MULT_CAP x vmax (vmax = the
       maximal atom magnitude; block-local vmaxb and window-global
       vmaxw both gated) -- the von-Mangoldt size analogy: the
       maximal source-pair sum on one fold target is ~ 2 x (the
       largest atom).  The cap question reduces EXACTLY to: is
       lvb = MULT_CAP x m x vmaxb/L <= C_LV x log m pointwise?
       (the elegant exit: the cap is the source-size bound
       itself);
   (ii) THE DIRECT GROUP-MASS BALANCE: hgn = m x hga/L (hga = abs
       atom mass of the heaviest group of the argmax block) with
       the minimal-A protocol (A in {1, 2}, r313 convention): the
       L-normalization is the known difficulty (sl_L1 +0.196,
       r297) -- the balance identity sum_g gabs (block) == A1_j
       (exact partition, warded) plus the group recomposition
       sum_j |sum_g G1_g| == L1 (exact, warded) make a heavy
       group force light mass elsewhere;
   (iii) THE GROUP COUNT: ngl = n_groups(argmax block)/log m <=
       C_NG (the pigeonhole partner: the exact chain
       m q_max <= m A1_{j*}/L = sum_g m gabs_g/L <= ng x hgn
       is EXACT algebra, warded live -- with (ii) or (i) it
       composes to m q_max <= C_NG C_cap (log m)^{1+A}).
Q3 -- THE COMPOSITION: if a cap candidate certifies pointwise
   (mid-ladder freeze, ALL spikes inside): recompose -- does it
   replace the +0.172 exponent by polylog, and what becomes of
   m_0*?  (a non-astronomical m_0 would be the jump from MEASURED
   to a realistically checkable theorem candidate.)  If NO cap
   certifies: the growth exponents e_hg + e_ng + e_M2 vs CRIT =
   0.224 decide HEAVY_GROUP_UNBOUNDED vs CAP_PARTIAL -- then
   +0.172 is presumably unavoidable and the MEASURED composition
   is the honest end state of the route (sealed honestly).

SEALED VERDICTS (exactly one fires; total order):
   TARGET_LEAK              iff any purity/scope audit hit on the
       mechanism builders,
   RECOMP_BREAK             iff the group ledger breaks
       structurally (partition/recomposition/two-ancestor ward
       fails on a live world),
   LAMBDA_PAIR_CAP_GO(A=1)  iff the lambda-pair chain certifies
       pointwise: two-ancestor ward exact live AND lvb/log m 0
       test violations at the mid-ladder freeze AND named 4/4 AND
       the group count certifies (ngl 0 violations + named 4/4),
   BALANCE_CAP_GO(A)        iff not lambda-pair but the direct
       heavy-group cap certifies at minimal A in {1, 2} (0
       violations + named 4/4) AND the group count certifies,
   HEAVY_GROUP_UNBOUNDED    iff no GO and the decided route
       exponent e_route = e(hgn/log m) + e(ngl) + e(m M_2) >=
       CRIT = 0.224 (both test halves agree),
   CAP_PARTIAL(rest)        otherwise (named rest printed).

EXPLORATION ONLY (2026-08-27).  experiments/ level: NO promotion,
NO ledger row, NO marker moved, NO RH CLAIM in either direction.
Coexistence: the r326 Lean round runs in parallel; this probe
touches NOTHING outside its own file and the strictly additive
rh-sync (existing entries byte-identical).

THE OBJECT (r269/r287/r298/r302/r306/r314/r316/r324 machinery +
the r324 module 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); the
frozen positional block machinery (r298); the r306
RY3.cubic_moments + RY3.renyi3_ratio + RY3.calib_freeze; the r314
SCF.fold_genealogy + SCF.signed_cube_terms + SCF.flux_telescope;
the r316 TRB.two_regime_state + TRB.split_midladder; the r324
QMO.scale_bins + QMO.pileup_state + QMO.mult_ward; the r324-pre
FAP.m2_qmax_state; PDelta = Pbeta - Pomega; x_j = (PDelta)_j.
NEW in this round (module-own, source-pure): group_mass_ledger
(the per-group abs-mass/max-atom/source-flag ledger on the
identical fold segmentation), heavy_state (the argmax-block
heavy-group anatomy + the cap coordinates) and the sealed
cap_tree.

LEG 0 -- ANCHOR REGRESSION (slim set + the r324 record,
disclosed): the r314 identity wards live; r306 C_2 = 1.069 (tol
0.005) first-5 freeze, 0/57; r316 rho anchors kz53/kz67/kz55/
kz83 = 1.0490/1.0536/0.4821/0.7790 (tol 0.005) + C_small 1.0694
at kz18 + n = 65; r324 RECORD anchors reproduced bit-near:
C_NSC 2.0258 (tol 0.005) with 0/39 test violations, C_PIL 9.3583
(tol 0.005) with 11/39, C_INF 1.7481 (tol 0.005) with 5/39, the
named heavy-scale masses {kz53: 13.778, kz83: 12.707, kz67:
22.378} (tol 0.02, == pil at the named rungs), exponents
e(G/log m) +0.158 / e(m M_2) +0.014 / e_tot +0.172 (tol 0.005);
r324-pre C_M2 = 2.2557 (tol 0.005) with the seven-violator set
{53, 67, 83, 76, 61, 28, 109} EXACT.

LEG A -- SEAL + PURITY + TOYS + LIVE WARDS: (A1) sealed
definitions printed; the SOURCE-PURE table (rank, kz, N, m, G =
m qmax, ng, hgn, hgn/log m, lvb/log m, gap, align, ratio, third,
nwin) printed BEFORE any certification table.  (A2) SOURCE-PURITY
AUDITS: the AST identifier scan over group_mass_ledger +
heavy_state + cap_tree must be clean against BOUND_FORBIDDEN +
PHI3_FORBIDDEN + QMAX_FORBIDDEN (no M_3 read-back, no terminal
value, no q_max record read-back -- the cap builders consume atom
values / positions / block assignments / group order ONLY; the
block-value argmax is the same access class as the r324
pileup_state, disclosed); the literal scan over the builders must
be clean against the sealed record-literal set
R327_TABLE_LITERALS (the r314..r324-pre set UNION the r324 record
numbers); e3/e4 prove the audits bite.  (A3) TOY EXACTNESS
(Fractions): the group toy (block j*: group A = atoms (3, 2) at
one position (mult 2, G1 = 5 = gabs), group B = atom (1); block
1: atom (1)): x = (6, 1), L = 7, m = 2, m qmax = 12/7; hga = 5,
hgn = 10/7, ng = 2, chain m qmax = 12/7 <= ng x hgn = 20/7
(slack 8/7 EXACT); vmaxb = 3, two-ancestor 5 <= 2 x 3 (slack 1
EXACT); partition 5 + 1 == A1 = 6 EXACT; the aligned/cancelling
group toy (3, -2): G1 = 1, gabs = 5, align = 1/5 EXACT; the
drop-group mutant breaks the L1 recomposition by EXACTLY 1
(LOUD); the wrong-window-max mutant bound 2 x 2 = 4 < hga 5
breaks the two-ancestor ward by EXACTLY 1 (CAUGHT); the cap_tree
on all six branches EXACT.  (A4) LIVE WARDS on every live world:
the r316 chain + NORM x cube == rho_2 (r324 verbatim); the S0
interpolation M_3 <= qmax M_2 AND M_2 <= qmax; THE GROUP LEDGER
WARDS: ledger G1/mult/ng == the r314 genealogy EXACTLY; the
partition sum_g gabs == A1_j (bar SA_BAR); the L1 recomposition
sum_j |sum_g G1_g| == L (bar SA_BAR); the two-ancestor bound
gabs_g <= MULT_CAP x gmax_g on every group (exact, bar TOY_BAR
relative); THE CAP CHAIN m qmax <= ng x hgn AND hgn <= lvb
(exact algebra, bar CHAIN_BAR); the r324 pileup chain m qmax <=
nsc x pil re-warded.

LEG B -- Q1 ANATOMY (census + sealed adjudication): the heavy-
group profile at the three named near-critical rungs (ancestor
values, alignment, bulk/window composition, position third, gap
to the second group, ratio to the r324 heavy scale mass); ladder
censuses gap med/max, align med, third histogram, nwin histogram;
the sealed SOURCE/AGGREGATION letter (RATIO_BAR).

LEG C -- Q2 CAPS (mid-ladder freeze, TRB verbatim; small ranks
individually certified): (i) C_LV = max cal lvb/log m, test
violations, named coverage; the window-global lvw census printed
alongside (disclosed: the block-local vmaxb is the sharper exact
form; the window-global bound is gated as census); (ii) C_HG1 =
max cal hgn/log m and C_HG2 = max cal hgn/(log m)^2, minimal-A
protocol, violations, named; (iii) C_NG = max cal ngl, test
violations, named; growth exponents (r272 dyadic halves-slope
over the test rungs, fit-free): e_hg = e(hgn/log m), e_lv =
e(lvb/log m), e_ng = e(ngl), e_M2 = e(m M_2), e_route = e_hg +
e_ng + e_M2 vs CRIT = 0.224, stability = the two test halves
must agree on the criticality side (else undecided ->
CAP_PARTIAL).

LEG D -- Q3 COMPOSITION (printed ALWAYS, honestly typed): on a
GO branch: m qmax <= C_NG x C_cap x (log m)^{1+A} => sum q^3 <=
C_NG C_cap C_2env (log m)^{1+A}/m^2 (C_2env = the measured m M_2
envelope, typed MEASURED) => N_3 >= m/sqrt(C (log m)^{1+A}) and
N_2 >= N_3 (r306 exact chain) => N_2 >= m^0.888 for all m >=
m_0* = the smallest m with m^{0.224} >= C (log m)^{1+A}
(log-space solve, r324 verbatim) -- the NEW m_0* printed against
the r324 record 10^59.6; on the no-GO branch: the r324 MEASURED
composition restated unchanged (the cap route does not improve
it) with the measured cap-route envelopes printed.

LEG E -- WARDS / MUST-FAILS (>= 4 mutants + 2 scope mutants):
(e1) GROUP RECOMPOSITION != L1: mutant_group_drop drops the last
  group of the argmax block -- the L1 recomposition breaks by
  exactly the dropped |G1| (toy break == 1 EXACT; live rel dev >=
  MUT_MIN) -- LOUD.
(e2) LAMBDA-PAIR BOUND WITH THE WRONG WINDOW MAXIMUM:
  mutant_wrong_window_max computes the source maximum on a
  truncated atom set (the global maximal atom dropped) -- on the
  sealed toy the mutant cap 2 x 2 = 4 < hga = 5 breaks the
  two-ancestor ward by EXACTLY 1 while the true cap holds
  (slack 1) -- CAUGHT (exact).
(e3) CAP CONSTANT AFTER SIGHT OF THE SPIKES: mutant_cap_posthoc
  re-picks the cap constant to cover the seen violators (consumes
  rho) -- the BOUND_FORBIDDEN scope audit must FLAG it AND on the
  sealed toy it returns a constant != the mid-ladder rule's --
  CAUGHT twice.
(e4) QMAX READ-BACK: mutant_qmax_readback consumes the q_max
  record (trs/qmax) as a 'cap coordinate' -- the QMAX_FORBIDDEN
  scan must FLAG it (AST-CAUGHT) while the module-own builders
  stay clean.
(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.

INDEX FIREWALL (binding, r238-r324 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; the cubic target M_3 / rho_2 and the q_max RECORD enter
GATES / anchors / composition checks only, NEVER a cap builder
(AST-warded); no zero/prime oracles anywhere (AST firewall); no
fit primitives (fragment audit; the growth exponents are the
imported r272 dyadic halves-slope, fit-free).  MACHINERY IMPORTED
VERBATIM: r324 QMO.scale_bins + QMO.pileup_state + QMO.mult_ward,
r324-pre FAP.m2_qmax_state, r316 TRB.two_regime_state +
TRB.split_midladder, r314 SCF.fold_genealogy +
SCF.signed_cube_terms + SCF.flux_telescope, r306
RY3.cubic_moments + RY3.renyi3_ratio + RY3.calib_freeze, r298
WBT.block_breaks + WBT.aggregate_blocks, r269 PBB.mask_edge +
PBB.runs_split, r287 L2D.blocks_level2 + L2D.halves_slope +
L2D.autocorr_full, r244 BH.wpack, 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, r316/r324 verbatim): frame-A h <= 900, 42 rungs,
(N, kz)-sorted; exception set {kz15, 20, 22, 36, 38, 39, 52};
EXTENSION: 900 < h <= 1300, first 15 by (N, kz); EXT2: the r316
A5 rule (leftover pool + first 12 windows 1300 < h <= 1650,
first 8 POSITIVE_PREFIX by (N, kz)).

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);
EXT_H_MAX 1300; K_EXT 15; EXT_NW_EXPECT (942, 1218); EXT2_H_MAX
1650; EXT2_POOL_CAP 12; K_EXT2 8; ATOM_BAR 1e-9; REC3_BAR 1e-13;
TEL_BAR 1e-13; BND_BAR 1e-13; CHAIN_BAR 1e-9; SA_BAR 1e-12;
DEG_FLOOR 1e-6; MULT_CAP 2; N_CAL 5 (via TRB, verbatim);
RATIO_BAR 0.5; A_FAM (1, 2); CRIT_EXP 0.224; N2_EXP_NEED 0.888;
NEED_SLOPE 0.908; SIGMA_STAR -0.516; DELTA_NEED 0.21; NAMED_KZ
(53, 83, 67, 55); NAMED_HV_KZ (53, 83, 67); MUT_MIN 1e-6;
TOY_BAR 1e-12; FR_BAR 1e-14; TB_WARD bars 1e-9 main N <= 400 /
3e-6 deep + ext + ext2 / 1e-6 controls; ID_BAR 1e-12; AC_BAR
1e-9; R306 anchor C_2 1.069 tol 0.005; N327_REF 65; R316 RHO
{53: 1.0490, 67: 1.0536, 55: 0.4821, 83: 0.7790} tol 0.005,
C_SMALL 1.0694 tol 0.005 at kz18; R324 anchors C_NSC 2.0258 /
C_PIL 9.3583 / C_INF 1.7481 (tol 0.005) with violation counts
0/11/5 EXACT, named heavy-scale masses {53: 13.778, 83: 12.707,
67: 22.378} tol 0.02, exponents +0.158/+0.014/+0.172 tol 0.005;
R324P C_M2 2.2557 tol 0.005, violator set {53, 67, 83, 76, 61,
28, 109} EXACT; R327_TABLE_LITERALS = the sealed r314..r324-pre
forbidden set (r324 verbatim) UNION the r324 record set {2.0258,
9.3583, 1.7481, 0.158, 0.014, 0.172, 0.141, -0.16, 13.778,
22.378, 12.707, 25.309, 14.15, 2.724, 2.8, 1.971, 2.103, 2.567,
8.941, 59.6, 6.661, 1.165, 2.026, 1.137, 3.1938, 2.613, 0.71,
1.1, 5.32};
runtime <= 1800 s; smoke = w9 + controls + toys + scope/purity
audits + the ledger/chain/two-ancestor wards on w9 + controls +
e1-e4 mutants; ladder, extensions, anchors, anatomy census, cap
certification, exponents and adjudication skipped.
DISCLOSED PRE-SPEC INPUT (no scratch run of THIS probe): every
anchor band is an r306/r316/r324/r324-pre RECORD number adopted
as-is (incl. the known r324 heavy-scale anatomy at the named
rungs -- that the heavy SCALE is near the block total is known;
whether ONE GROUP carries it is genuinely open); the two-ancestor
bound gabs <= mult x gmax <= MULT_CAP x vmax, the partition
identity, the L1 recomposition and the cap chain m qmax <= ng x
hgn are derived algebra, disclosed above; GENUINELY OPEN
quantities of this round: every heavy-group column (hga, hgn,
gap, align, third, nwin, ratio), all cap constants C_LV/C_HG/
C_NG, all violation counts, all four growth exponents, the
anatomy letter and the recomposed m_0* -- NONE was computed
before this spec was frozen; RATIO_BAR = 0.5, A_FAM = (1, 2) and
CRIT_EXP = 0.224 are a-priori (the criticality budget is the
r324 budget verbatim); the six sealed letters are symmetric and
total -- the tree maps every outcome to exactly one letter by
CONTRACT.

RECORD TABLES (inserted AFTER the record run -- the only
amendment after freeze; freeze SPEC_SHA 71f8b7b423a3f847;
protocol: smoke pass 1 = 34/34 (0.4 s), NO amendment;
calibration pass 1 = first full evaluation, 34/34, wall 36.4 s,
NO amendment; record run1/run2 after this insertion, identical
up to the runtime line):
MAIN VERDICT: CAP_PARTIAL(lambda-pair 19 viol; direct cap fails
at A <= 2 (8/39); exponent halves straddle +0.411/-1.183;
e_route +0.106 < CRIT 0.224 UNDECIDED) -- no cap candidate
certifies pointwise at the mid-ladder freeze; the r324 MEASURED
composition (m_0* = 10^59.6) stays the honest state of the
route.
Q1 ANATOMY: SOURCE (sealed rule, med named ratio 1.057 >=
RATIO_BAR 0.5; kz53 1.081 / kz83 1.057 / kz67 0.460) -- the
r324 single heavy scale IS a single fold group at the two
sharpest spikes; the STRUCTURAL FINDING of the round: on ALL 65
rungs the heaviest group of the argmax block is EXACTLY ONE
beta/omega fold pair (window-atom histogram [0, 65, 0]: one
bulk atom + one window atom at one position) with median
alignment 1.000 (min 0.099 -- NO internal cancellation at the
median: the two ancestors REINFORCE); kz53: the single pair
carries bshare 0.888 of the argmax block's atom mass at gap
0.076 (the second group is 13x lighter) -- the spike is
literally ONE bulk/window coincidence; kz67 is the exception
shape (6 groups, bshare 0.416, ratio 0.460); position thirds
[21, 29, 15] (mid-heavy, the r322 mid/tail echo); ladder gap
med 0.807 (generic rungs have near-tied top groups; the spikes
have dominant ones).
Q2 CAPS (mid-ladder freeze, TRB verbatim, 39 test rungs):
(i) lambda-pair C_LV = 1.1838: FAILS 19/39 (worst kz55 6.853,
kz53 5.766, kz83 4.609, kz67 4.132 -- named coverage 0/4): the
two-ancestor bound hga <= 2 vmaxb is EXACT (live slack 0.0) but
the SOURCE-SIZE coordinate m x vmaxb/L itself spikes -- the
von-Mangoldt size analogy does NOT close as a mid-ladder
polylog cap; (ii) direct cap A = 1 C 0.9143 FAILS 18/39, A = 2
C 0.2047 FAILS 8/39 (kz53 0.652 3.2x), minimal A = None;
(iii) THE GROUP COUNT CERTIFIES: ngl <= C_NG = 2.6351 with
0/39 violations and named 4/4 (ng med 5 max 13) -- the third
certified O(log m) count of the lane (after the r324 scale
count C_NSC 2.0258).
EXPONENTS (fit-free dyadic halves-slope over test): e(hgn/
log m) = -0.200 FALLING, e(lvb/log m) = -0.261 FALLING, e(ngl)
= +0.293, e(m M_2) = +0.014 -> e_route = +0.106 < CRIT 0.224
but halves +0.411/-1.183 STRADDLE -- UNDECIDED by the sealed
stability rule (the deep half falls steeply: the heavy-group
coordinate DECAYS with depth; the spike set is a shallow/mid
phenomenon, not growth) -- HEAVY_GROUP_UNBOUNDED does NOT fire.
Q3 COMPOSITION: no certifying cap -> the r324 chain restated
unchanged (sum q^3 <= 8.941 (log m) m^{+0.172}/m^2, N_2 >=
m^0.888 for m >= 10^59.6); measured cap-route envelope
max(ngl x hgL) = 2.616 with e_route +0.106 -- the cap route is
SUBCRITICAL in the median but pointwise-blocked by the same
named spike family as every mid-ladder constant since r316.
ANCHORS bit-near: r306 C_2 1.069 (0/57), r316 n 65 + rho
quartet + C_small 1.0694@kz18, r324 C_NSC 2.0258 (0/39) /
C_PIL 9.3583 (11/39) / C_INF 1.7481 (5/39) + named scale
masses 3/3 + e_tot +0.172, r324-pre C_M2 2.2557 + the seven-
violator set EXACT; r314 identity 4.5e-17.
SEAL: partition 3.4e-16, L1 recomposition 0.0, two-ancestor
slack 0.0, cap chain m qmax <= ng x hgn slack 0.0, ledger ==
genealogy 0.0; must-fails e1 LOUD (toy break 1 EXACT, live rel
1.3e-1) / e2 CAUGHT (toy break 1 EXACT) / e3 CAUGHT twice
(AST rho + toy 3.0 != 1.0) / e4 AST-CAUGHT (trs) + m5a/m5b
FLAGGED.

SEALED VERDICT FORM (frozen BEFORE evaluation, joined with '+'):
  R327_ANCHORS(identity wards, r306 C_2, r316 rho + C_small + n,
    r324 C_NSC/C_PIL/C_INF + viols + named scale masses +
    exponents, r324-pre C_M2 + violator set)
+ SEAL(ledger wards + partition + L1 recomposition +
    two-ancestor + cap chain + purity audits + toys)
+ ANATOMY(the heavy-group census + the sealed SOURCE/AGGREGATION
    letter + gap/align/third/nwin statistics)
+ CAPS(C_LV/C_HG/C_NG, violations, named coverage, minimal A,
    exponents e_hg/e_lv/e_ng/e_route, stability)
+ [exactly one of] LAMBDA_PAIR_CAP_GO / BALANCE_CAP_GO /
    CAP_PARTIAL / HEAVY_GROUP_UNBOUNDED / RECOMP_BREAK /
    TARGET_LEAK
+ COMPOSITION(the recomposed chain with explicit constants +
    the new m_0* vs the r324 record; printed ALWAYS, typed)
+ MUSTFAIL_LEDGER(e1-e4 + scopes).
Honesty before beauty: the partition, the recomposition, the
two-ancestor bound and the cap chain are EXACT algebra; every
constant, violation count, census and exponent is MEASURED on
the finite ladder only; a certifying cap fixes a proof TARGET
and recomposes the r324 chain, it proves NO cofinal law; a
non-certifying outcome seals the honest end state of the route;
the r324 record numbers are disclosed pre-spec inputs; r243-r325
stand.

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 window_border_transfer_probe as WBT     # noqa: E402 r298
import renyi3_probe as RY3                     # noqa: E402 r306
import signed_cubic_flux_probe as SCF          # noqa: E402 r314
import two_regime_bound_probe as TRB           # noqa: E402 r316
import fa_provenance_probe as FAP              # noqa: E402 r324-pre
import qmax_m2_origin_probe as QMO             # noqa: E402 r324
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
EXT_H_MAX = 1300
K_EXT = 15
EXT_NW_EXPECT = (942, 1218)
EXT2_H_MAX = 1650
EXT2_POOL_CAP = 12
K_EXT2 = 8
ATOM_BAR = 1e-9
REC3_BAR = 1e-13
TEL_BAR = 1e-13
BND_BAR = 1e-13
CHAIN_BAR = 1e-9
SA_BAR = 1e-12
DEG_FLOOR = 1e-6
MULT_CAP = 2
N_CAL = 5
RATIO_BAR = 0.5
A_FAM = (1, 2)
CRIT_EXP = 0.224
N2_EXP_NEED = 0.888
NEED_SLOPE = 0.908
SIGMA_STAR = -0.516
DELTA_NEED = 0.21
NAMED_KZ = (53, 83, 67, 55)
NAMED_HV_KZ = (53, 83, 67)
MUT_MIN = 1e-6
TOY_BAR = 1e-12
FR_BAR = 1e-14
EDGE_F = 0.20
PAIR_OFFSET = 0
R306_C2 = 1.069
R306_C2_TOL = 0.005
N327_REF = 65
R316_RHO = {53: 1.0490, 67: 1.0536, 55: 0.4821, 83: 0.7790}
R316_RHO_TOL = 0.005
R316_CSMALL = 1.0694
R316_CSMALL_TOL = 0.005
R316_CSMALL_KZ = 18
R324_CNSC = 2.0258
R324_CPIL = 9.3583
R324_CINF = 1.7481
R324_C_TOL = 0.005
R324_VNSC = 0
R324_VPIL = 11
R324_VINF = 5
R324_S0 = {53: 13.778, 83: 12.707, 67: 22.378}
R324_S0_TOL = 0.02
R324_EG = 0.158
R324_EM2 = 0.014
R324_ETOT = 0.172
R324_E_TOL = 0.005
R324P_CM2 = 2.2557
R324P_CM2_TOL = 0.005
R324P_M2VIOL = (53, 67, 83, 76, 61, 28, 109)
R327_TABLE_LITERALS = frozenset(QMO.R324B_TABLE_LITERALS | {
    2.0258, 9.3583, 1.7481, 0.158, 0.014, 0.172, 0.141, -0.16,
    13.778, 22.378, 12.707, 25.309, 14.15, 2.724, 2.8, 1.971,
    2.103, 2.567, 8.941, 59.6, 6.661, 1.165, 2.026, 1.137,
    3.1938, 2.613, 0.71, 1.1, 5.32})

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"}
PHI3_FORBIDDEN = {"cube", "S" + "3", "cm",
                  "renyi3" + "_ratio", "cubic" + "_moments"}
QMAX_FORBIDDEN = {"q" + "max", "q" + "m", "tr" + "s", "mq" + "s",
                  "G" + "L_col", "G" + "_col"}


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


def literal_audit(funcname):
    """the RECORD-LITERAL audit: walk ONLY the named function's
    subtree and flag any numeric constant whose 4-decimal rounding
    lies in the sealed r314..r324 + r324 record 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):
                if isinstance(sub, ast.Constant) \
                        and isinstance(sub.value, (int, float)) \
                        and not isinstance(sub.value, bool):
                    if round(float(sub.value), 4) \
                            in R327_TABLE_LITERALS:
                        hits.append("%s@%d" % (repr(sub.value),
                                               sub.lineno))
    return hits


# ---------------- module-own builders.  Source-pure: the cap
# ---------------- builders consume atom values / positions / block
# ---------------- assignments / source flags / group order only;
# ---------------- the withheld terminal drive key, the branch
# ---------------- label, the cubic target M_3 and the q_max RECORD
# ---------------- are forbidden (AST identifier scan + literal
# ---------------- scan).
def group_mass_ledger(pos, val, blk, src, m):
    """the per-group MASS LEDGER on the identical fold segmentation
    as the r314 genealogy (same lexsort key (block, position)):
    per fold group g returns the signed value G1_g, the abs atom
    mass gabs_g = sum |v|, the maximal atom magnitude gmax_g, the
    multiplicity mult_g, the window-atom count gwin_g (source
    flag), the block index gblk and the block slice pointers ptr;
    plus the rung-global maximal atom magnitude vmaxw.  Consumes
    atom positions + values + block assignments + source flags
    only."""
    pos = np.asarray(pos, dtype=float)
    val = np.asarray(val, dtype=float)
    blk = np.asarray(blk, dtype=int)
    src = np.asarray(src, dtype=float)
    o = np.lexsort((pos, blk))
    pb = blk[o]
    pp = pos[o]
    vv = val[o]
    ss = src[o]
    av = np.abs(vv)
    if len(pb):
        new = np.concatenate([[True], (pb[1:] != pb[:-1])
                              | (pp[1:] != pp[:-1])])
    else:
        new = np.zeros(0, dtype=bool)
    gid = np.cumsum(new) - 1
    ng = int(gid[-1]) + 1 if len(gid) else 0
    G1 = np.bincount(gid, weights=vv, minlength=ng)
    gabs = np.bincount(gid, weights=av, minlength=ng)
    gwin = np.bincount(gid, weights=ss, minlength=ng)
    mult = np.bincount(gid, minlength=ng)
    gblk = pb[new] if ng else np.zeros(0, dtype=int)
    if ng:
        starts = np.nonzero(new)[0]
        gmax = np.maximum.reduceat(av, starts)
    else:
        gmax = np.zeros(0)
    ptr = np.searchsorted(gblk, np.arange(m + 1))
    vmaxw = float(np.max(av)) if len(av) else 0.0
    return dict(G1=G1, gabs=gabs, gmax=gmax, gwin=gwin, mult=mult,
                ng=ng, gblk=gblk, ptr=ptr, vmaxw=vmaxw)


def heavy_state(x, led):
    """the ARGMAX-BLOCK heavy-group anatomy + the cap coordinates:
    on block values x (length m) and a group_mass_ledger led:
    j* = argmax |x|, L = sum |x|; over the groups of j* (position
    ordered): hga = max gabs (the heaviest group's abs atom mass),
    hgv = the same group's |G1|, hga2 = the second-heaviest gabs,
    gap = hga2/hga, align = hgv/hga, third = the position third of
    the heavy group inside the block, nwin = its window-atom
    count, npair = its multiplicity; vmaxb = max atom magnitude
    inside j*; the cap coordinates hgn = m x hga/L, lvb = MULT_CAP
    x m x vmaxb/L, lvw = MULT_CAP x m x vmaxw/L, ngj = the group
    count of j*, bshare = hga/A1_{j*}.  Consumes block values +
    the ledger only (the argmax access is the same class as the
    r324 pileup_state, disclosed)."""
    ax = np.abs(np.asarray(x, dtype=float))
    m = int(len(ax))
    tot = float(np.sum(ax))
    if m < 2 or tot <= 0.0 or led["ng"] == 0:
        return dict(j=0, ngj=0, hga=0.0, hgv=0.0, hga2=0.0,
                    gap=0.0, align=0.0, third=0, nwin=0, npair=0,
                    vmaxb=0.0, hgn=0.0, lvb=0.0, lvw=0.0,
                    bshare=0.0, a1j=0.0)
    j = int(np.argmax(ax))
    a, b = int(led["ptr"][j]), int(led["ptr"][j + 1])
    ga = led["gabs"][a:b]
    gv = np.abs(led["G1"][a:b])
    gm = led["gmax"][a:b]
    gw = led["gwin"][a:b]
    mu = led["mult"][a:b]
    ngj = b - a
    if ngj == 0:
        return dict(j=j, ngj=0, hga=0.0, hgv=0.0, hga2=0.0,
                    gap=0.0, align=0.0, third=0, nwin=0, npair=0,
                    vmaxb=0.0, hgn=0.0, lvb=0.0, lvw=0.0,
                    bshare=0.0, a1j=0.0)
    i1 = int(np.argmax(ga))
    hga = float(ga[i1])
    hgv = float(gv[i1])
    hga2 = float(np.max(np.delete(ga, i1))) if ngj > 1 else 0.0
    a1j = float(np.sum(ga))
    vmaxb = float(np.max(gm))
    third = min(2, (3 * i1) // ngj)
    return dict(j=j, ngj=ngj, hga=hga, hgv=hgv, hga2=hga2,
                gap=hga2 / max(hga, 1e-300),
                align=hgv / max(hga, 1e-300), third=third,
                nwin=int(round(float(gw[i1]))),
                npair=int(mu[i1]), vmaxb=vmaxb,
                hgn=float(m) * hga / tot,
                lvb=float(MULT_CAP) * float(m) * vmaxb / tot,
                lvw=float(MULT_CAP) * float(m) * led["vmaxw"] / tot,
                bshare=hga / max(a1j, 1e-300), a1j=a1j)


def cap_tree(leak, brk, lam_go, bal_go, unbounded):
    """the sealed six-letter verdict tree (booleans only; total,
    exactly one fires; order sealed):
    TARGET_LEAK > RECOMP_BREAK > LAMBDA_PAIR_CAP_GO >
    BALANCE_CAP_GO > HEAVY_GROUP_UNBOUNDED > CAP_PARTIAL."""
    if leak:
        return "TARGET_LEAK"
    if brk:
        return "RECOMP_BREAK"
    if lam_go:
        return "LAMBDA_PAIR_CAP_GO"
    if bal_go:
        return "BALANCE_CAP_GO"
    if unbounded:
        return "HEAVY_GROUP_UNBOUNDED"
    return "CAP_PARTIAL"


def mutant_group_drop(gvals):
    """e1 MUST-FAIL MUTANT: an L1 'recomposition' that drops the
    last group of the block -- the recomposition ward must measure
    the exact break (LOUD)."""
    gs = tuple(float(v) for v in gvals)
    return sum(gs[:-1]) if gs else 0.0


def mutant_wrong_window_max(vals):
    """e2 MUST-FAIL MUTANT: the 'window maximum' computed on a
    TRUNCATED atom set (the global maximal atom dropped) -- the
    two-ancestor ward must break EXACTLY on the sealed toy."""
    av = sorted(abs(float(v)) for v in vals)
    return av[-2] if len(av) >= 2 else 0.0


def mutant_cap_posthoc(cap_col, rho, cbar):
    """e3 MUST-FAIL MUTANT: the cap constant re-picked AFTER SIGHT
    of the violators (consumes rho): raised until every seen
    violator is covered -- the BOUND_FORBIDDEN scope audit must
    FLAG it AND on the toy it returns != the mid-ladder rule's."""
    return max((float(c) for c, r in zip(cap_col, rho)
                if r > cbar), default=0.0)


def mutant_qmax_readback(state):
    """e4 MUST-FAIL MUTANT: a 'cap coordinate' consuming the q_max
    RECORD (the target-side concentration coordinate) -- the
    QMAX_FORBIDDEN identifier scan must FLAG this."""
    tr = state["trs"]
    return float(tr["qmax"]) * float(state["m"])


def mutant_gift_bound(rc, P):
    """m5a MUST-FAIL MUTANT: a 'cap orientation' consuming 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.abs(P) ** 3))


def mutant_branch_peek(rc, P):
    """m5b MUST-FAIL MUTANT (world-blindness break simulated): a
    'cap constant' consuming the branch label -- the scope audit
    must FLAG this."""
    c = 0.5 if rc["g_branch"] >= 0.0 else 2.0
    return c * float(np.sum(np.abs(P) ** 3))


# ---------------- exact Fractions section: the group toy, the cap
# ---------------- chain and the e1/e2 breaks decided as rationals
def fr_group_toy():
    """the sealed group toy in exact Fractions: block j* holds
    group A = atoms (3, 2) at one position (G1 = gabs = 5) and
    group B = atom (1); block 1 holds atom (1).  x = (6, 1),
    L = 7, m = 2: m qmax = 12/7; hga = 5, hgn = 10/7, ng = 2;
    chain slack ng x hgn - m qmax = 8/7 EXACT; vmaxb = 3,
    two-ancestor slack 2 x 3 - 5 = 1 EXACT; partition 5 + 1 == 6
    EXACT; L1 recomposition 6 + 1 == 7 EXACT; the drop-group
    mutant breaks the L1 recomposition by EXACTLY 1; the
    wrong-window-max mutant cap 2 x 2 = 4 breaks the two-ancestor
    ward by EXACTLY 1.  Returns (worst dev, chain slack, pair
    slack, drop break, wrongmax break)."""
    atoms = (Fr(3), Fr(2), Fr(1))          # block 0
    x0 = sum(atoms)
    x1 = Fr(1)
    L = abs(x0) + abs(x1)
    m = Fr(2)
    qmx = x0 / L
    hga = Fr(3) + Fr(2)
    hgn = m * hga / L
    ng = Fr(2)
    chain_slack = ng * hgn - m * qmx
    vmaxb = Fr(3)
    pair_slack = Fr(MULT_CAP) * vmaxb - hga
    part = hga + Fr(1)
    rec = abs(x0) + abs(x1)
    drop = rec - (abs(Fr(mutant_group_drop((5.0, 1.0)))) + abs(x1))
    wmx = Fr(mutant_wrong_window_max((3.0, 2.0, 1.0, 1.0)))
    wbrk = hga - Fr(MULT_CAP) * wmx
    devs = [abs(m * qmx - Fr(12, 7)), abs(hgn - Fr(10, 7)),
            abs(chain_slack - Fr(8, 7)), abs(pair_slack - 1),
            abs(part - 6), abs(rec - 7), abs(drop - 1),
            abs(wbrk - 1),
            Fr(0) if m * qmx <= ng * hgn else Fr(1),
            Fr(0) if hga <= Fr(MULT_CAP) * vmaxb else Fr(1)]
    return max(devs), chain_slack, pair_slack, drop, wbrk


def fr_align_toy():
    """the aligned/cancelling group toy: atoms (3, -2) at one
    position: G1 = 1, gabs = 5, align = 1/5 EXACT; atoms (3, 2):
    align = 1 EXACT.  Returns worst dev."""
    g1c = Fr(3) + Fr(-2)
    gac = Fr(3) + Fr(2)
    al_c = abs(g1c) / gac
    g1a = Fr(3) + Fr(2)
    al_a = abs(g1a) / gac
    return max(abs(al_c - Fr(1, 5)), abs(al_a - 1))


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("group_mass_cap_probe -- "
          "PRIME.L2.RENYI3.GROUP_MASS_CAP.01 (round 327, the "
          "r324 follow-up)")
    print("SPEC_SHA %s   R324_SHA %s   R314_SHA %s   R316_SHA %s"
          % (SPEC_SHA[:16], QMO.SPEC_SHA[:16], SCF.SPEC_SHA[:16],
             TRB.SPEC_SHA[:16]))
    print("mode: %s" % ("SMOKE (w9 + controls + toys + scope/"
                        "purity audits + ledger/chain/two-"
                        "ancestor wards + e1-e4; ladder, "
                        "extensions, anchors, anatomy, caps, "
                        "exponents and adjudication 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 FOLD-GROUP MASS CAP ROUND (the r324 follow-up): "
          "Q1 anatomy of the dominant fold group at the spikes "
          "(ancestors, alignment, mid/tail third, gap, the "
          "sealed SOURCE/AGGREGATION letter at RATIO_BAR %.1f); "
          "Q2 the three cap candidates source-pure -- (i) the "
          "two-ancestor/lambda-pair route hga <= %d x vmax with "
          "lvb <= C_LV log m, (ii) the direct balance cap hgn <= "
          "C_HG (log m)^A (A in %s minimal), (iii) the group "
          "count ngl <= C_NG -- with the EXACT chain m qmax <= "
          "ng x hgn; Q3 recomposition to N_2 >= m^%.3f with the "
          "new m_0* vs the r324 record 10^59.6; verdict tree "
          "TARGET_LEAK / RECOMP_BREAK / LAMBDA_PAIR_CAP_GO / "
          "BALANCE_CAP_GO / HEAVY_GROUP_UNBOUNDED / CAP_PARTIAL "
          "sealed BEFORE evaluation (CRIT_EXP %.3f the r324 "
          "budget verbatim)"
          % (RATIO_BAR, MULT_CAP, str(A_FAM), N2_EXP_NEED,
             CRIT_EXP))
    frag = antigate_fragment_audit()
    sc_own = []
    for fn in ("group_mass_ledger", "heavy_state", "cap_tree"):
        sc_own += scope_audit(fn, BOUND_FORBIDDEN)
        sc_own += scope_audit(fn, PHI3_FORBIDDEN)
        sc_own += scope_audit(fn, QMAX_FORBIDDEN)
    sc_a = scope_audit("mutant_gift_bound", BOUND_FORBIDDEN)
    sc_b = scope_audit("mutant_branch_peek", BOUND_FORBIDDEN)
    check("G03-scope-audits", (not frag) and (not sc_own)
          and len(sc_a) >= 1 and len(sc_b) >= 1,
          "fragment audit clean (%d hits); the three module-own "
          "cap builders/trees clean vs BOUND_FORBIDDEN + "
          "PHI3_FORBIDDEN + QMAX_FORBIDDEN (%d hits) -- the cap "
          "side consumes ONLY atom values / positions / block "
          "assignments / source flags / group order; m5a "
          "gift-bound FLAGGED (%s); m5b branch-peek FLAGGED (%s)"
          % (len(frag), len(sc_own),
             sc_a[0] if sc_a else "MISS",
             sc_b[0] if sc_b else "MISS"))

    # ---------------- S1: census + controls (r324 scaffold verbatim)
    section("S1  CENSUS + CONTROLS + EXTENSIONS")
    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 = []
        ext = []
        ext2 = []
        okL = True
    else:
        kzs = []
        ekz = []
        ekz2 = []
        for kz in core.frame_a_zones():
            h = PIK.build_rung(kz)["h"]
            if h <= H_CAP:
                kzs.append(kz)
            elif h <= EXT_H_MAX:
                ekz.append(kz)
            elif h <= EXT2_H_MAX:
                ekz2.append((h, kz))
        ladder = [BH.wpack(kz) for kz in kzs]
        ladder.sort(key=lambda p: (p["N"], p["kz"]))
        epool = [BH.wpack(kz) for kz in ekz]
        epool.sort(key=lambda p: (p["N"], p["kz"]))
        ext = epool[:K_EXT]
        ekz2.sort()
        pool2 = epool[K_EXT:] + [BH.wpack(kz)
                                 for _h, kz in ekz2[:EXT2_POOL_CAP]]
        pool2.sort(key=lambda p: (p["N"], p["kz"]))
        ext2 = [p for p in pool2 if p["nf"] is None][:K_EXT2]
        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 "-"))
    if smoke:
        check("G12-extension-census", True, "SMOKE: skipped")
        check("G13-ext2-census", True, "SMOKE: skipped")
    else:
        check("G12-extension-census",
              len(ext) == K_EXT
              and ext[0]["N"] == EXT_NW_EXPECT[0]
              and ext[-1]["N"] == EXT_NW_EXPECT[1]
              and all(p["nf"] is None for p in ext),
              "r286-aligned extension: %d anchors, N_w %d..%d "
              "(expected %d..%d), POSITIVE_PREFIX %d/%d"
              % (len(ext), ext[0]["N"] if ext else -1,
                 ext[-1]["N"] if ext else -1, EXT_NW_EXPECT[0],
                 EXT_NW_EXPECT[1],
                 sum(1 for p in ext if p["nf"] is None), len(ext)))
        check("G13-ext2-census",
              len(ext2) <= K_EXT2
              and all(p["nf"] is None for p in ext2),
              "EXT2 (r316 A5 rule verbatim, census-grade): pool "
              "%d leftover + %d windows with %d < h <= %d; "
              "selected %d POSITIVE_PREFIX anchors, N_w %s..%s"
              % (len(epool) - K_EXT, min(len(ekz2), EXT2_POOL_CAP),
                 EXT_H_MAX, EXT2_H_MAX, len(ext2),
                 ext2[0]["N"] if ext2 else "-",
                 ext2[-1]["N"] if ext2 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)
        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
        v2w = BR.eval_scaled(rows, xu, N - 2)
        cw = wu * xu * v2w * fac
        o = np.argsort(bx, kind="stable")
        return dict(kz=p["kz"], N=N, g_branch=g,
                    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, nf=p["nf"])

    recs = [rung_rec(p) for p in pool]
    erecs = [rung_rec(p) for p in ext] if not smoke else []
    e2recs = [rung_rec(p) for p in ext2] if not smoke else []
    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:
        e_cheap = sum(1 for rc in erecs + e2recs
                      if rc["g_branch"] >= 0.0)
        e_exc = [rc["kz"] for rc in erecs + e2recs
                 if rc["g_branch"] < 0.0]
        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; "
              "EXT+EXT2 census (no sealed expectation): %d cheap "
              "/ %d exception %s"
              % (len(cheap), str(exc_kz),
                 "; ".join("w%d g %+.3f CHEAP" % (rc["kz"],
                                                  rc["g_branch"])
                           for rc in mrecs),
                 e_cheap, len(e_exc), str(e_exc)))

    # ---------------- S2: decomposition wards + eval
    section("S2  EXACT DECOMPOSITION + GROUP-LEDGER WARDS")
    tb_worst = 0.0
    tb_deep = 0.0
    tb_ext = 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 rc in erecs + e2recs:
        dev = abs(float(np.sum(rc["ct"])) - rc["t_term"]) \
            / max(float(np.sum(np.abs(rc["ct"]))), 1e-300)
        tb_ext = max(tb_ext, 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_ext <= TB_WARD_BAR_DEEP
          and tb_ctrl <= TB_WARD_BAR_CTRL,
          "sum_b ct_b == t_{N-2} on %d rungs + %d ext + %d ext2 "
          "+ %d mains + 3 controls: worst dev/absmass %.1e main "
          "N<=%d (bar %.0e) / %.1e deep / %.1e ext+ext2 (bar "
          "%.0e) / %.1e controls (bar %.0e)"
          % (len(recs), len(erecs), len(e2recs), len(mrecs),
             tb_worst, DEEP_N, TB_WARD_BAR, tb_deep, tb_ext,
             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)
        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)
        brk, m, jb = WBT.block_breaks(xb, runs)
        Pb = np.bincount(jb, weights=cb, minlength=m) \
            if m else np.zeros(0)
        Pw = WBT.aggregate_blocks(rc["xu"], rc["cw"], rc["lo"],
                                  rc["hi"], brk, m)
        Pd = Pb - Pw
        cm = RY3.cubic_moments(Pd)
        absm = float(np.sum(np.abs(rc["ct"]))) \
            + float(np.sum(np.abs(rc["cw"])))
        degenerate = (cm["L1"] <= DEG_FLOOR * absm)
        edw = PBB.mask_edge(rc["xu"], rc["lo"], rc["hi"], EDGE_F)
        xw = rc["xu"][~edw]
        vw = -rc["cw"][~edw]
        jw = np.searchsorted(brk, xw) if m else np.zeros(0, int)
        jb2 = np.searchsorted(brk, xb) if m else np.zeros(0, int)
        mism = int(np.sum(jb2 != jb))
        pos_all = np.concatenate([xb, xw])
        val_all = np.concatenate([cb, vw])
        blk_all = np.concatenate([jb, jw]).astype(int)
        src_all = np.concatenate([np.zeros(len(xb)),
                                  np.ones(len(xw))])
        if m and not degenerate:
            gen = SCF.fold_genealogy(pos_all, val_all, blk_all, m)
            sct = SCF.signed_cube_terms(gen["G1"], gen["gblk"], m)
            ft = SCF.flux_telescope(gen["G1"], gen["ptr"], m)
            x_dev = float(np.max(np.abs(sct["x"] - Pd))
                          / max(np.max(np.abs(Pd)), 1e-300))
            sig = sct["sig"]
            cube = sct["cube"]
            A1 = np.bincount(blk_all, weights=np.abs(val_all),
                             minlength=m)
            scale3 = float(np.sum(A1 ** 3))
            sc_j = np.maximum(A1 ** 3, 1e-300)
            C_far_flux = float(np.sum(sig * ft["F_end"]))
            C_bnd = float(np.sum(sig * ft["F_open"]))
            rec3 = abs(C_far_flux + sct["C_pair"] + sct["C_full"]
                       + C_bnd - cube) / max(scale3, 1e-300)
            tel_dev = float(np.max(np.abs(ft["F_end"]
                                          - sct["far"]) / sc_j))
            bnd_dev = float(np.max(np.abs(ft["F_open"]) / sc_j))
            mx_mult = int(np.max(gen["mult"])) if gen["ng"] else 0
            trs = TRB.two_regime_state(sct["x"], sct["Q2"],
                                       sct["Q3"], gen["G1"],
                                       gen["ptr"], ft["F_end"],
                                       ft["F_open"],
                                       ft["edge_abs"], m)
            rho2 = RY3.renyi3_ratio(cm["S3"], m, 2)
            mqs = FAP.m2_qmax_state(sct["x"])
            pst = QMO.pileup_state(sct["x"], val_all, blk_all)
            led = group_mass_ledger(pos_all, val_all, blk_all,
                                    src_all, m)
            hst = heavy_state(sct["x"], led)
        else:
            gen = sct = ft = None
            x_dev = 0.0
            cube = 0.0
            rec3 = tel_dev = bnd_dev = 0.0
            C_bnd = 0.0
            mx_mult = 0
            A1 = np.zeros(0)
            trs = dict(nrm=0.0, coll=0.0, dflux=0.0, bnd=0.0,
                       fe=0.0, fcix=0.0, qmax=0.0, cnt3=0.0,
                       phiL1=0.0, phiL2=0.0, phiH1=0.0,
                       phiH2=0.0, L=0.0)
            rho2 = 0.0
            mqs = dict(qm=0.0, m2=0.0, ymx=0.0, maj=0.0)
            pst = dict(j=0, nsc=0, nsc_rel=0, pil=0.0, a1j=0.0,
                       tail=0.0, scut=0, scales=(), masses=())
            led = dict(G1=np.zeros(0), gabs=np.zeros(0),
                       gmax=np.zeros(0), gwin=np.zeros(0),
                       mult=np.zeros(0, int), ng=0,
                       gblk=np.zeros(0, int),
                       ptr=np.zeros(1, int), vmaxw=0.0)
            hst = heavy_state(np.zeros(0), led)
        return dict(alt_ok=alt_ok, R=R, P=P, m=m, Pd=Pd, cm=cm,
                    degenerate=degenerate, mism=mism, x_dev=x_dev,
                    cube=cube, rec3=rec3, tel_dev=tel_dev,
                    bnd_dev=bnd_dev, C_bnd=C_bnd,
                    mx_mult=mx_mult, gen=gen, sct=sct, ft=ft,
                    trs=trs, rho2=rho2, A1=A1, mqs=mqs, pst=pst,
                    led=led, hst=hst,
                    pos_all=pos_all, val_all=val_all,
                    blk_all=blk_all, brk=brk)

    all_rc = recs + mrecs + erecs + e2recs
    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)))

    live = [rc for rc in pool_all if not rc["ev"]["degenerate"]]
    deg_note = [c for c in crecs if crecs[c]["ev"]["degenerate"]]
    x_w = max(rc["ev"]["x_dev"] for rc in live)
    mism_tot = sum(rc["ev"]["mism"] for rc in pool_all)
    led_dev = 0.0
    for rc in live:
        ev = rc["ev"]
        gen = ev["gen"]
        led = ev["led"]
        if gen["ng"] != led["ng"]:
            led_dev = max(led_dev, 1.0)
            continue
        if gen["ng"]:
            sc = max(float(np.max(np.abs(gen["G1"]))), 1e-300)
            led_dev = max(
                led_dev,
                float(np.max(np.abs(led["G1"] - gen["G1"]))) / sc,
                float(np.max(np.abs(led["mult"] - gen["mult"]))),
                float(np.max(np.abs(led["gblk"] - gen["gblk"]))))
    check("G22-genealogy-ledger-identity",
          x_w <= ATOM_BAR and mism_tot == 0 and led_dev <= SA_BAR,
          "the r314 fold genealogy covers every block value on %d "
          "live worlds (group-sum dev %.1e, bar %.0e); run "
          "assignment == breakpoint search (%d mismatches); the "
          "module-own group ledger segments IDENTICALLY to the "
          "genealogy (G1/mult/gblk worst dev %.1e, bar %.0e)%s"
          % (len(live), x_w, ATOM_BAR, mism_tot, led_dev, SA_BAR,
             "; DEGENERATE guard fired (pre-declared): "
             + ", ".join(deg_note) if deg_note else ""))

    # ---------------- S3: Leg 0 anchors (slim + r324 record)
    section("S3  LEG 0 -- ANCHOR REGRESSION (slim + the r324 "
            "record)")
    rec3_w = max(rc["ev"]["rec3"] for rc in live)
    tel_w = max(rc["ev"]["tel_dev"] for rc in live)
    bnd_w = max(rc["ev"]["bnd_dev"] for rc in live)
    check("G30-r314-identity-wards",
          rec3_w <= REC3_BAR and tel_w <= TEL_BAR
          and bnd_w <= BND_BAR,
          "the r314 identity live on %d live worlds: three-term "
          "recomposition dev %.1e (bar %.0e), telescope dev %.1e "
          "(bar %.0e), boundary %.1e (bar %.0e); DISCLOSED slim "
          "anchor set -- the full chain is re-warded by the "
          "sealed r321/r324 probes"
          % (len(live), rec3_w, REC3_BAR, tel_w, TEL_BAR, bnd_w,
             BND_BAR))
    if smoke:
        ev9s = recs[0]["ev"]
        hs = ev9s["hst"]
        info("SMOKE: w9 G %.3f ng %d hgn %.4f lvb %.4f gap %.3f "
             "align %.3f third %d nwin %d"
             % (ev9s["m"] * ev9s["trs"]["qmax"], hs["ngj"],
                hs["hgn"], hs["lvb"], hs["gap"], hs["align"],
                hs["third"], hs["nwin"]))
        check("G31-r306-bound-live", True, "SMOKE: skipped")
        check("G32-r316-anchors", True, "SMOKE: skipped")
        check("G33-r324-pileup-anchors", True, "SMOKE: skipped")
        check("G34-r324pre-m2-anchor", True, "SMOKE: skipped")
        srt = []
        n327 = 0
    else:
        srt57 = sorted(recs + erecs,
                       key=lambda rc: (rc["N"], rc["kz"]))
        rhoT2 = [rc["ev"]["rho2"] for rc in srt57]
        C2r, _j, _d = RY3.calib_freeze(rhoT2, range(N_CAL))
        viol2 = sum(1 for v in rhoT2 if v > C2r)
        check("G31-r306-bound-live",
              abs(C2r - R306_C2) <= R306_C2_TOL and viol2 == 0,
              "r306 pointwise bound live at A = 2: C_2 %.3f (rec "
              "%.3f tol %.3f, first-%d freeze), violations %d/%d"
              % (C2r, R306_C2, R306_C2_TOL, N_CAL, viol2,
                 len(srt57)))
        srt_all = sorted(recs + erecs + e2recs,
                         key=lambda rc: (rc["N"], rc["kz"]))
        srt = [rc for rc in srt_all
               if rc["ev"]["mx_mult"] <= MULT_CAP]
        n327 = len(srt)
        rho_all = [rc["ev"]["rho2"] for rc in srt]
        m_all = [rc["ev"]["m"] for rc in srt]
        rho_kz = {rc["kz"]: rc["ev"]["rho2"] for rc in srt}
        sm_i, ca_i, te_i = TRB.split_midladder(n327)
        C_small = max(rho_all[i] for i in sm_i)
        j_cs = max(sm_i, key=lambda i: rho_all[i])
        check("G32-r316-anchors",
              n327 == N327_REF
              and all(abs(rho_kz.get(kz, -1.0) - R316_RHO[kz])
                      <= R316_RHO_TOL for kz in R316_RHO)
              and abs(C_small - R316_CSMALL) <= R316_CSMALL_TOL
              and srt[j_cs]["kz"] == R316_CSMALL_KZ,
              "r316 anchors reproduced: class ladder n = %d (rec "
              "%d); rho kz53/kz67/kz55/kz83 = %.4f/%.4f/%.4f/"
              "%.4f (rec tol %.3f); C_small %.4f @ kz%d"
              % (n327, N327_REF, rho_kz.get(53, -1.0),
                 rho_kz.get(67, -1.0), rho_kz.get(55, -1.0),
                 rho_kz.get(83, -1.0), R316_RHO_TOL, C_small,
                 srt[j_cs]["kz"]))
        named_rank = {}
        for kz in NAMED_KZ:
            for i in range(n327):
                if srt[i]["kz"] == kz:
                    named_rank[kz] = i
        # r324 record anchors: pileup columns re-derived
        qmax_col = [rc["ev"]["trs"]["qmax"] for rc in srt]
        G_col = [m_all[i] * qmax_col[i] for i in range(n327)]
        GL_col = [G_col[i] / math.log(float(m_all[i]))
                  for i in range(n327)]
        nscr_col = [rc["ev"]["pst"]["nsc_rel"] for rc in srt]
        pil_col = [rc["ev"]["pst"]["pil"] for rc in srt]
        nsclog = [nscr_col[i] / math.log(float(m_all[i]))
                  for i in range(n327)]
        C_NSC = max(nsclog[i] for i in ca_i)
        viol_nsc = [i for i in te_i if nsclog[i] > C_NSC]
        C_PIL = max(pil_col[i] for i in ca_i)
        viol_pil = [i for i in te_i if pil_col[i] > C_PIL]
        C_INF = max(GL_col[i] for i in ca_i)
        viol_G = [i for i in te_i if GL_col[i] > C_INF]
        msT = [m_all[i] for i in te_i]
        e_G = L2D.halves_slope(msT, [max(GL_col[i], 1e-300)
                                     for i in te_i])
        m2_col = [rc["ev"]["mqs"]["m2"] for rc in srt]
        e_M2 = L2D.halves_slope(msT, [max(m2_col[i], 1e-300)
                                      for i in te_i])
        e_tot = e_G + e_M2
        s0_ok = all(abs(pil_col[named_rank[kz]] - R324_S0[kz])
                    <= R324_S0_TOL for kz in R324_S0)
        check("G33-r324-pileup-anchors",
              abs(C_NSC - R324_CNSC) <= R324_C_TOL
              and abs(C_PIL - R324_CPIL) <= R324_C_TOL
              and abs(C_INF - R324_CINF) <= R324_C_TOL
              and len(viol_nsc) == R324_VNSC
              and len(viol_pil) == R324_VPIL
              and len(viol_G) == R324_VINF
              and s0_ok
              and abs(e_G - R324_EG) <= R324_E_TOL
              and abs(e_M2 - R324_EM2) <= R324_E_TOL
              and abs(e_tot - R324_ETOT) <= R324_E_TOL,
              "the r324 RECORD reproduced bit-near: C_NSC %.4f "
              "(rec %.4f) viol %d/%d (rec %d), C_PIL %.4f (rec "
              "%.4f) viol %d (rec %d), C_INF %.4f (rec %.4f) "
              "viol %d (rec %d); named heavy-scale masses "
              "kz53/kz83/kz67 = %.3f/%.3f/%.3f (rec 13.778/"
              "12.707/22.378 tol %.2f); exponents e(G/log m) "
              "%+.3f / e(m M_2) %+.3f / e_tot %+.3f (rec "
              "%+.3f/%+.3f/%+.3f tol %.3f)"
              % (C_NSC, R324_CNSC, len(viol_nsc), len(te_i),
                 R324_VNSC, C_PIL, R324_CPIL, len(viol_pil),
                 R324_VPIL, C_INF, R324_CINF, len(viol_G),
                 R324_VINF, pil_col[named_rank[53]],
                 pil_col[named_rank[83]], pil_col[named_rank[67]],
                 R324_S0_TOL, e_G, e_M2, e_tot, R324_EG,
                 R324_EM2, R324_ETOT, R324_E_TOL))
        C_M2 = max(m2_col[i] for i in ca_i)
        viol_m2 = tuple(sorted(srt[i]["kz"] for i in te_i
                               if m2_col[i] > C_M2))
        C_M2env = max(m2_col)
        check("G34-r324pre-m2-anchor",
              abs(C_M2 - R324P_CM2) <= R324P_CM2_TOL
              and viol_m2 == tuple(sorted(R324P_M2VIOL)),
              "the r324-pre m2 record reproduced: mid-ladder "
              "freeze C_M2 %.4f (rec %.4f tol %.3f); the seven "
              "test violators %s == the banked set EXACT; ladder "
              "envelope C_2env = %.4f (the composition's M_2 "
              "side)" % (C_M2, R324P_CM2, R324P_CM2_TOL,
                         str(viol_m2), C_M2env))

    # ---------------- S4: Leg A -- seal + purity + toys + wards
    section("S4  LEG A -- SEAL + PURITY + TOYS + LIVE WARDS + "
            "SOURCE-PURE TABLE")
    pure_lits = []
    for fn in ("group_mass_ledger", "heavy_state", "cap_tree",
               "fr_group_toy", "fr_align_toy"):
        pure_lits += literal_audit(fn)
    e3_hits = scope_audit("mutant_cap_posthoc", BOUND_FORBIDDEN)
    e4_hits = scope_audit("mutant_qmax_readback", QMAX_FORBIDDEN)
    check("G40-purity-audits",
          (not sc_own) and (not pure_lits)
          and len(e3_hits) >= 1 and len(e4_hits) >= 1,
          "SOURCE PURITY: the cap builders clean vs the forbidden "
          "sets (%d id hits) and vs the sealed r314..r324 record-"
          "literal set (%d literal hits); consumed inputs: atom "
          "values / positions / block assignments / source flags "
          "/ group order -- M_3, rho_2 and the q_max RECORD are "
          "TARGET-SIDE, computed outside the builders "
          "(disclosed); e3 cap-posthoc FLAGGED (%s); e4 "
          "qmax-readback FLAGGED (%s)"
          % (len(sc_own), len(pure_lits),
             e3_hits[0] if e3_hits else "MISS",
             e4_hits[0] if e4_hits else "MISS"))
    fr_dev, fr_chain, fr_pair, fr_drop, fr_wmx = fr_group_toy()
    fr_al = fr_align_toy()
    toy_pos = np.array([0.1, 0.1, 0.2, 0.3])
    toy_val = np.array([3.0, 2.0, 1.0, 1.0])
    toy_blk = np.array([0, 0, 0, 1])
    toy_src = np.array([0.0, 1.0, 0.0, 0.0])
    led_t = group_mass_ledger(toy_pos, toy_val, toy_blk, toy_src, 2)
    hst_t = heavy_state(np.array([6.0, 1.0]), led_t)
    ok_led = (led_t["ng"] == 3
              and abs(led_t["gabs"][0] - 5.0) <= FR_BAR
              and abs(led_t["gmax"][0] - 3.0) <= FR_BAR
              and int(led_t["mult"][0]) == 2
              and abs(led_t["vmaxw"] - 3.0) <= FR_BAR)
    ok_hst = (hst_t["j"] == 0 and hst_t["ngj"] == 2
              and abs(hst_t["hga"] - 5.0) <= FR_BAR
              and abs(hst_t["hgn"] - 10.0 / 7.0) <= FR_BAR
              and abs(hst_t["lvb"] - 12.0 / 7.0) <= FR_BAR
              and abs(hst_t["gap"] - 0.2) <= FR_BAR
              and abs(hst_t["align"] - 1.0) <= FR_BAR
              and hst_t["nwin"] == 1 and hst_t["npair"] == 2)
    tr_br = (cap_tree(True, True, True, True, True),
             cap_tree(False, True, True, True, True),
             cap_tree(False, False, True, True, True),
             cap_tree(False, False, False, True, True),
             cap_tree(False, False, False, False, True),
             cap_tree(False, False, False, False, False))
    ok_tr = tr_br == ("TARGET_LEAK", "RECOMP_BREAK",
                      "LAMBDA_PAIR_CAP_GO", "BALANCE_CAP_GO",
                      "HEAVY_GROUP_UNBOUNDED", "CAP_PARTIAL")
    check("G41-toy-exactness",
          fr_dev == 0 and fr_al == 0 and ok_led and ok_hst
          and ok_tr,
          "the Fractions group toy EXACT (worst dev %s): chain "
          "slack %s, two-ancestor slack %s, drop break %s LOUD, "
          "wrong-window-max break %s CAUGHT; align toy EXACT "
          "(worst %s); the float ledger/heavy_state match the "
          "toy (ng 3, gabs (5,1,1), hga 5, hgn 10/7, lvb 12/7, "
          "gap 1/5, align 1, nwin 1, npair 2); cap_tree all six "
          "branches EXACT %s"
          % (str(fr_dev), str(fr_chain), str(fr_pair),
             str(fr_drop), str(fr_wmx), str(fr_al), str(tr_br)))
    # live wards
    chain_w = 0.0
    xw_cube = 0.0
    interp_w = 0.0
    part_w = 0.0
    l1rec_w = 0.0
    panc_w = 0.0
    capch_w = 0.0
    lvch_w = 0.0
    pilch_w = 0.0
    mult_all_ok = True
    for rc in live:
        ev = rc["ev"]
        trs = ev["trs"]
        nc = trs["nrm"] * ev["cube"]
        xw_cube = max(xw_cube, abs(nc - ev["rho2"])
                      / max(ev["rho2"], 1e-300))
        for a, b in ((nc, trs["phiL1"]),
                     (trs["phiL1"], trs["phiL2"]),
                     (trs["phiL2"], trs["phiH2"]),
                     (nc, trs["phiH1"])):
            chain_w = max(chain_w,
                          max(0.0, a - b) / max(b, 1e-300))
        x_abs = np.abs(ev["sct"]["x"])
        Lx = float(np.sum(x_abs))
        qv = x_abs / max(Lx, 1e-300)
        M3 = float(np.sum(qv ** 3))
        M2 = float(np.sum(qv ** 2))
        qmx = float(np.max(qv))
        mloc = ev["m"]
        interp_w = max(interp_w,
                       max(0.0, M3 - qmx * M2)
                       / max(qmx * M2, 1e-300),
                       max(0.0, M2 - qmx) / max(qmx, 1e-300))
        led = ev["led"]
        # partition: per-block sum of gabs == A1_j
        A1led = np.bincount(led["gblk"], weights=led["gabs"],
                            minlength=mloc)
        part_w = max(part_w,
                     float(np.max(np.abs(A1led - ev["A1"])))
                     / max(float(np.max(ev["A1"])), 1e-300))
        # L1 recomposition: sum_j |sum_g G1_g| == L
        xled = np.bincount(led["gblk"], weights=led["G1"],
                           minlength=mloc)
        l1rec_w = max(l1rec_w,
                      abs(float(np.sum(np.abs(xled))) - Lx)
                      / max(Lx, 1e-300))
        # two-ancestor bound per group: gabs <= mult x gmax
        if led["ng"]:
            panc_w = max(panc_w,
                         float(np.max(led["gabs"]
                                      - led["mult"] * led["gmax"]))
                         / max(float(np.max(led["gabs"])), 1e-300))
        # the cap chain: m qmax <= ng x hgn  AND  hgn <= lvb
        hs = ev["hst"]
        G = mloc * qmx
        capch_w = max(capch_w,
                      max(0.0, G - hs["ngj"] * hs["hgn"])
                      / max(hs["ngj"] * hs["hgn"], 1e-300))
        lvch_w = max(lvch_w,
                     max(0.0, hs["hgn"] - hs["lvb"])
                     / max(hs["lvb"], 1e-300))
        # the r324 pileup chain re-warded
        pst = ev["pst"]
        pilch_w = max(pilch_w,
                      max(0.0, G - pst["nsc"] * pst["pil"])
                      / max(pst["nsc"] * pst["pil"], 1e-300))
        mult_all_ok = mult_all_ok \
            and QMO.mult_ward(rc["ev"]["gen"]["mult"])[1]
    check("G42-live-wards",
          chain_w <= CHAIN_BAR and xw_cube <= CHAIN_BAR
          and interp_w <= CHAIN_BAR and part_w <= SA_BAR
          and l1rec_w <= SA_BAR and panc_w <= TOY_BAR
          and capch_w <= CHAIN_BAR and lvch_w <= CHAIN_BAR
          and pilch_w <= CHAIN_BAR and mult_all_ok,
          "the r316 chain live on %d live worlds (worst %.1e); "
          "NORM x cube == rho_2 (%.1e); S0 interpolation (worst "
          "%.1e); GROUP PARTITION sum_g gabs == A1_j (worst "
          "%.1e, bar %.0e); L1 RECOMPOSITION sum_j |sum_g G1| == "
          "L (worst %.1e); TWO-ANCESTOR gabs <= mult x gmax on "
          "every group (worst slack %.1e); THE CAP CHAIN m qmax "
          "<= ng x hgn (worst %.1e) AND hgn <= lvb (worst %.1e); "
          "the r324 pileup chain re-warded (%.1e); fold "
          "multiplicity <= %d admitted on ALL live worlds"
          % (len(live), chain_w, xw_cube, interp_w, part_w,
             SA_BAR, l1rec_w, panc_w, capch_w, lvch_w, pilch_w,
             MULT_CAP))
    if smoke:
        check("G43-coordinate-table", True, "SMOKE: skipped")
    else:
        ng_col = [rc["ev"]["hst"]["ngj"] for rc in srt]
        hgn_col = [rc["ev"]["hst"]["hgn"] for rc in srt]
        lvb_col = [rc["ev"]["hst"]["lvb"] for rc in srt]
        lvw_col = [rc["ev"]["hst"]["lvw"] for rc in srt]
        gap_col = [rc["ev"]["hst"]["gap"] for rc in srt]
        al_col = [rc["ev"]["hst"]["align"] for rc in srt]
        th_col = [rc["ev"]["hst"]["third"] for rc in srt]
        nw_col = [rc["ev"]["hst"]["nwin"] for rc in srt]
        bs_col = [rc["ev"]["hst"]["bshare"] for rc in srt]
        rat_col = []
        for rc in srt:
            pmx = max(rc["ev"]["pst"]["masses"]) \
                if rc["ev"]["pst"]["masses"] else 0.0
            rat_col.append(rc["ev"]["hst"]["hga"]
                           / max(pmx, 1e-300))
        hgl_col = [hgn_col[i] / math.log(float(m_all[i]))
                   for i in range(n327)]
        lvl_col = [lvb_col[i] / math.log(float(m_all[i]))
                   for i in range(n327)]
        ngl_col = [ng_col[i] / math.log(float(m_all[i]))
                   for i in range(n327)]
        info("sealed SOURCE-PURE table (printed BEFORE any "
             "certification table): rank kz N m G ng hgn "
             "hgn/logm lvb/logm gap align ratio third nwin")
        for i, rc in enumerate(srt):
            info("%2d kz%-3d N %4d m %3d G %6.3f ng %2d hgn "
                 "%6.3f hgL %.3f lvL %.3f gap %.3f al %.3f rat "
                 "%.3f t%d w%d"
                 % (i, rc["kz"], rc["N"], m_all[i], G_col[i],
                    ng_col[i], hgn_col[i], hgl_col[i],
                    lvl_col[i], gap_col[i], al_col[i],
                    rat_col[i], th_col[i], nw_col[i]))
        check("G43-coordinate-table", True,
              "hgn range %.2f/%.2f/%.2f min/med/max (max at "
              "kz%d); hgn/log m med %.3f max %.3f; lvb/log m "
              "med %.3f max %.3f (window-global lvw med %.3f "
              "max %.3f census); ng med %.0f max %d; gap med "
              "%.3f max %.3f; align med %.3f; bshare med %.3f; "
              "ratio med %.3f"
              % (min(hgn_col), float(np.median(hgn_col)),
                 max(hgn_col),
                 srt[int(np.argmax(hgn_col))]["kz"],
                 float(np.median(hgl_col)), max(hgl_col),
                 float(np.median(lvl_col)), max(lvl_col),
                 float(np.median([lvw_col[i]
                                  / math.log(float(m_all[i]))
                                  for i in range(n327)])),
                 max(lvw_col[i] / math.log(float(m_all[i]))
                     for i in range(n327)),
                 float(np.median(ng_col)), max(ng_col),
                 float(np.median(gap_col)), max(gap_col),
                 float(np.median(al_col)),
                 float(np.median(bs_col)),
                 float(np.median(rat_col))))

    # ---------------- S5: Leg B -- Q1 anatomy
    section("S5  LEG B -- Q1 HEAVY-GROUP ANATOMY (census + "
            "sealed adjudication)")
    if smoke:
        check("G50-heavy-census", True, "SMOKE: skipped")
        check("G51-source-vs-aggregation", True, "SMOKE: skipped")
        anatomy = "SMOKE"
    else:
        info("the heavy group at the named near-critical rungs "
             "(the r324 spikes):")
        for kz in NAMED_HV_KZ:
            i = named_rank[kz]
            hs = srt[i]["ev"]["hst"]
            pmx = max(srt[i]["ev"]["pst"]["masses"]) \
                if srt[i]["ev"]["pst"]["masses"] else 0.0
            info("  kz%-3d G %.2f | hga %.4f (m hga/L %.3f) vs "
                 "heavy scale mass %.4f -> ratio %.3f | ng %d "
                 "gap %.3f align %.3f third %d nwin %d npair %d "
                 "bshare %.3f"
                 % (kz, G_col[i], hs["hga"], hs["hgn"],
                    pmx * 1.0, rat_col[i], hs["ngj"], hs["gap"],
                    hs["align"], hs["third"], hs["nwin"],
                    hs["npair"], hs["bshare"]))
        th_hist = [sum(1 for t in th_col if t == k)
                   for k in (0, 1, 2)]
        nw_hist = [sum(1 for w in nw_col if w == k)
                   for k in (0, 1, 2)]
        check("G50-heavy-census", True,
              "ladder census: gap med %.3f max %.3f (second/"
              "first heaviest group); align med %.3f min %.3f "
              "(1 = no internal cancellation); position thirds "
              "%s (the r322 mid/tail question); heavy-group "
              "window-atom count histogram %s (0 = pure bulk, "
              "1 = beta/omega fold, 2 = pure window); bshare "
              "med %.3f max %.3f (in-block share of the heavy "
              "group)"
              % (float(np.median(gap_col)), max(gap_col),
                 float(np.median(al_col)), min(al_col),
                 str(th_hist), str(nw_hist),
                 float(np.median(bs_col)), max(bs_col)))
        named_ratio = [rat_col[named_rank[kz]]
                       for kz in NAMED_HV_KZ]
        med_ratio = float(np.median(named_ratio))
        anatomy = "SOURCE" if med_ratio >= RATIO_BAR \
            else "AGGREGATION"
        check("G51-source-vs-aggregation", True,
              "SEALED ADJUDICATION (RATIO_BAR %.1f): med named "
              "ratio hga/(heavy scale mass) = %.3f %s -> "
              "ANATOMY = %s (%s); ladder ratio med %.3f -- the "
              "heavy SCALE of the r324 spikes is %s"
              % (RATIO_BAR, med_ratio,
                 str([round(v, 3) for v in named_ratio]),
                 anatomy,
                 "one group carries the scale: the heaviness is "
                 "a SOURCE property (two source masses meet at "
                 "one fold target)" if anatomy == "SOURCE" else
                 "no single group carries the scale: the "
                 "heaviness is AGGREGATION (the fold bundles "
                 "many groups inside one scale)",
                 float(np.median(rat_col)),
                 "single-group-carried" if anatomy == "SOURCE"
                 else "many-group aggregated"))

    # ---------------- S6: Leg C -- Q2 cap certification
    section("S6  LEG C -- Q2 CAP CANDIDATES (mid-ladder freeze + "
            "exponents)")
    if smoke:
        check("G60-lambda-pair-cap", True, "SMOKE: skipped")
        check("G61-balance-cap", True, "SMOKE: skipped")
        check("G62-group-count-cap", True, "SMOKE: skipped")
        check("G63-growth-exponents", True, "SMOKE: skipped")
    else:
        C_LV = max(lvl_col[i] for i in ca_i)
        viol_lv = [i for i in te_i if lvl_col[i] > C_LV]
        named_lv = sum(1 for kz in NAMED_KZ
                       if lvl_col[named_rank[kz]] <= C_LV)
        C_LVs = max(lvl_col[i] for i in sm_i)
        check("G60-lambda-pair-cap", True,
              "(i) THE LAMBDA-PAIR CAP lvb = %d x m x vmaxb/L <= "
              "C_LV x log m: C_LV = %.4f (mid-ladder frozen at "
              "kz%d; small-m C %.4f); test violations %d/%d %s; "
              "named coverage %d/4 %s"
              % (MULT_CAP, C_LV,
                 srt[max(ca_i, key=lambda i: lvl_col[i])]["kz"],
                 C_LVs, len(viol_lv), len(te_i),
                 str([(srt[i]["kz"], round(lvl_col[i], 3))
                      for i in viol_lv]) if viol_lv else "[]",
                 named_lv,
                 str({("kz%d" % kz): round(lvl_col[named_rank[kz]],
                                           3)
                      for kz in NAMED_KZ})))
        hg_caps = {}
        for A in A_FAM:
            col = [hgn_col[i] / (math.log(float(m_all[i])) ** A)
                   for i in range(n327)]
            C_A = max(col[i] for i in ca_i)
            viol_A = [i for i in te_i if col[i] > C_A]
            named_A = sum(1 for kz in NAMED_KZ
                          if col[named_rank[kz]] <= C_A)
            hg_caps[A] = (C_A, viol_A, named_A, col)
        minA = None
        for A in A_FAM:
            if not hg_caps[A][1] and hg_caps[A][2] == len(NAMED_KZ):
                minA = A
                break
        check("G61-balance-cap", True,
              "(ii) THE DIRECT GROUP-MASS CAP hgn <= C_HG x "
              "(log m)^A: A=1 C %.4f viol %d/%d named %d/4 %s; "
              "A=2 C %.4f viol %d/%d named %d/4 %s; minimal "
              "certifying A = %s"
              % (hg_caps[1][0], len(hg_caps[1][1]), len(te_i),
                 hg_caps[1][2],
                 str([(srt[i]["kz"],
                       round(hg_caps[1][3][i], 3))
                      for i in hg_caps[1][1]])
                 if hg_caps[1][1] else "[]",
                 hg_caps[2][0], len(hg_caps[2][1]), len(te_i),
                 hg_caps[2][2],
                 str([(srt[i]["kz"],
                       round(hg_caps[2][3][i], 3))
                      for i in hg_caps[2][1]])
                 if hg_caps[2][1] else "[]",
                 str(minA)))
        C_NG = max(ngl_col[i] for i in ca_i)
        viol_ng = [i for i in te_i if ngl_col[i] > C_NG]
        named_ng = sum(1 for kz in NAMED_KZ
                       if ngl_col[named_rank[kz]] <= C_NG)
        check("G62-group-count-cap", True,
              "(iii) THE GROUP COUNT ngl = ng(argmax block)/"
              "log m <= C_NG: C_NG = %.4f; test violations "
              "%d/%d %s; named %d/4; ng med %.0f max %d "
              "(compare the r324 certified scale count C_NSC "
              "%.4f)"
              % (C_NG, len(viol_ng), len(te_i),
                 str([(srt[i]["kz"], round(ngl_col[i], 3))
                      for i in viol_ng]) if viol_ng else "[]",
                 named_ng, float(np.median(ng_col)), max(ng_col),
                 C_NSC))
        e_hg = L2D.halves_slope(msT, [max(hgl_col[i], 1e-300)
                                      for i in te_i])
        e_lv = L2D.halves_slope(msT, [max(lvl_col[i], 1e-300)
                                      for i in te_i])
        e_ng = L2D.halves_slope(msT, [max(ngl_col[i], 1e-300)
                                      for i in te_i])
        e_route = e_hg + e_ng + e_M2
        h = len(te_i) // 2
        te_a = te_i[:h]
        te_b = te_i[h:]

        def eroute_on(idx):
            ms = [m_all[i] for i in idx]
            ea = L2D.halves_slope(ms, [max(hgl_col[i], 1e-300)
                                       for i in idx])
            eb = L2D.halves_slope(ms, [max(ngl_col[i], 1e-300)
                                       for i in idx])
            ec = L2D.halves_slope(ms, [max(m2_col[i], 1e-300)
                                       for i in idx])
            return ea + eb + ec

        e_a = eroute_on(te_a)
        e_b = eroute_on(te_b)
        decided = ((e_a >= CRIT_EXP) == (e_b >= CRIT_EXP)
                   and (e_a >= CRIT_EXP) == (e_route >= CRIT_EXP))
        check("G63-growth-exponents", True,
              "GROWTH EXPONENTS (r272 dyadic halves-slope vs m "
              "over the %d test rungs, fit-free): e(hgn/log m) "
              "= %+.3f, e(lvb/log m) = %+.3f, e(ngl) = %+.3f, "
              "e(m M_2) = %+.3f -> e_route = %+.3f vs CRIT %.3f "
              "(the r324 budget; r324 e_tot %+.3f for "
              "comparison); stability halves %+.3f / %+.3f -> "
              "%s, %s"
              % (len(te_i), e_hg, e_lv, e_ng, e_M2, e_route,
                 CRIT_EXP, e_tot, e_a, e_b,
                 "DECIDED" if decided else "UNDECIDED",
                 ("UNBOUNDED-SIDE" if e_route >= CRIT_EXP
                  else "SUBCRITICAL-SIDE") if decided else "open"))

    # ---------------- S7: Leg D -- adjudication + composition
    section("S7  LEG D -- SEALED ADJUDICATION + Q3 COMPOSITION")
    if smoke:
        check("G70-adjudication", True, "SMOKE: skipped")
        check("G71-composition", True, "SMOKE: skipped")
        verdict_main = "SMOKE_NO_ADJUDICATION"
    else:
        leak = bool(sc_own) or bool(pure_lits)
        brk_struct = (part_w > SA_BAR or l1rec_w > SA_BAR
                      or panc_w > TOY_BAR or capch_w > CHAIN_BAR
                      or led_dev > SA_BAR or not mult_all_ok)
        ng_ok = (not viol_ng) and named_ng == len(NAMED_KZ)
        lam_go = ((not viol_lv) and named_lv == len(NAMED_KZ)
                  and ng_ok and panc_w <= TOY_BAR)
        bal_go = (not lam_go) and (minA is not None) and ng_ok
        unbounded = ((not lam_go) and (not bal_go)
                     and decided and e_route >= CRIT_EXP)
        vkey = cap_tree(leak, brk_struct, lam_go, bal_go,
                        unbounded)
        rest = []
        if viol_lv:
            rest.append("lambda-pair %d viol" % len(viol_lv))
        elif named_lv < len(NAMED_KZ):
            rest.append("lambda-pair named %d/4" % named_lv)
        if minA is None:
            rest.append("direct cap fails at A<=2 (%d/%d viol)"
                        % (len(hg_caps[2][1]), len(te_i)))
        if not ng_ok:
            rest.append("group count %d viol named %d/4"
                        % (len(viol_ng), named_ng))
        if not decided:
            rest.append("exponent halves straddle %+.3f/%+.3f"
                        % (e_a, e_b))
        det_v = {
            "TARGET_LEAK": "purity/scope audit hit on a cap "
                           "builder",
            "RECOMP_BREAK": "the group ledger breaks "
                            "structurally",
            "LAMBDA_PAIR_CAP_GO":
                "A = 1: hga <= %d vmaxb exact + lvb/log m 0 "
                "viol (C_LV %.4f) + group count 0 viol (C_NG "
                "%.4f)" % (MULT_CAP, C_LV, C_NG),
            "BALANCE_CAP_GO":
                "A = %s: hgn/(log m)^A 0 viol (C %.4f) + group "
                "count 0 viol (C_NG %.4f)"
                % (str(minA),
                   hg_caps[minA][0] if minA else 0.0, C_NG),
            "HEAVY_GROUP_UNBOUNDED":
                "e_route %+.3f >= %.3f DECIDED (halves "
                "%+.3f/%+.3f) -- the +0.172 exponent is "
                "presumably unavoidable on this route"
                % (e_route, CRIT_EXP, e_a, e_b),
            "CAP_PARTIAL":
                "rest: %s; e_route %+.3f %s CRIT %.3f (halves "
                "%+.3f/%+.3f)"
                % ("; ".join(rest) if rest else "none",
                   e_route, ">=" if e_route >= CRIT_EXP
                   else "<", CRIT_EXP, e_a, e_b)}
        verdict_main = "%s(%s)" % (vkey, det_v[vkey])
        check("G70-adjudication", True,
              "exactly one sealed letter fired: %s"
              % verdict_main)
        # Q3 composition (printed ALWAYS, honestly typed)
        if vkey == "LAMBDA_PAIR_CAP_GO":
            A_use = 1
            C_qmx = C_NG * C_LV
            hyp = ("lambda-pair + group count mid-ladder "
                   "CERTIFIED pointwise (0 violations)")
        elif vkey == "BALANCE_CAP_GO":
            A_use = minA
            C_qmx = C_NG * hg_caps[minA][0]
            hyp = ("direct cap (A = %d) + group count "
                   "mid-ladder CERTIFIED pointwise" % minA)
        else:
            A_use = None
            C_qmx = max(ngl_col[i] * hgl_col[i]
                        for i in range(n327))
            hyp = ("NO certifying cap -- the r324 MEASURED "
                   "composition stands unchanged; the cap-route "
                   "envelope is printed as census")
        info("Q3 COMPOSITION (%s):" % hyp)
        if A_use is not None:
            Atot = 1 + A_use
            C_full = C_qmx * C_M2env
            m_star_l10 = None
            t = math.log(73.0)
            while t < 1e7:
                if t * CRIT_EXP >= math.log(C_full) \
                        + Atot * math.log(t):
                    m_star_l10 = t / math.log(10.0)
                    break
                t *= 1.02
            ms_txt = ("10^%.1f" % m_star_l10) \
                if m_star_l10 is not None else "NONE"
            info("  m qmax <= ng x hgn <= C_NG C_cap (log m)^%d "
                 "= %.3f (log m)^%d  =>  sum q^3 <= %.3f x "
                 "(log m)^%d / m^2 (C_2env %.4f measured "
                 "envelope, typed MEASURED);"
                 % (Atot, C_qmx, Atot, C_full, Atot, C_M2env))
            info("  => N_3 >= m/sqrt(%.3f (log m)^%d), N_2 >= "
                 "N_3 (r306 exact chain) => N_2 >= m^%.3f for "
                 "all m >= m_0* = %s (m^{%.3f} >= %.3f "
                 "(log m)^%d) -- vs the r324 record m_0* = "
                 "10^59.6: the exponent m^{+0.172} is REPLACED "
                 "by polylog;"
                 % (C_full, Atot, N2_EXP_NEED, ms_txt, CRIT_EXP,
                    C_full, Atot))
            info("  => slope(n_eff) >= %+.3f => sigma <= sigma* "
                 "= %.3f => the r297 target => the v964-S0 vdC "
                 "theorem => delta' > %.2f => the "
                 "terminal_positive_main edge; all measured m "
                 "<= %d closed by the finite certificates; the "
                 "gap (%d, m_0*) stays the disclosed "
                 "extrapolation hypothesis."
                 % (NEED_SLOPE, SIGMA_STAR, DELTA_NEED,
                    max(m_all), max(m_all)))
            comp_ok = (m_star_l10 is not None)
            comp_txt = "m_0* %s (A_tot %d, C %.3f)" \
                % (ms_txt, Atot, C_full)
        else:
            info("  the r324 MEASURED composition restated "
                 "(anchor-gated in G33): sum q^3 <= 8.941 x "
                 "(log m) x m^{%+.3f}/m^2 => N_2 >= m^%.3f for "
                 "all m >= m_0* = 10^59.6 -- the fold-group cap "
                 "route does NOT improve it; measured cap-route "
                 "envelope max(ngl x hgL) = %.3f, e_route "
                 "%+.3f."
                 % (e_tot, N2_EXP_NEED, C_qmx, e_route))
            comp_ok = True
            comp_txt = "r324 restated (m_0* 10^59.6, e_tot " \
                "%+.3f); cap envelope %.3f" % (e_tot, C_qmx)
        check("G71-composition", comp_ok,
              "composition printed with explicit constants "
              "(%s); the chain to terminal_positive_main is "
              "typed: partition/recomposition/two-ancestor/cap "
              "chain exact, every constant MEASURED on the "
              "finite ladder, the ladder-to-m_0* step an "
              "extrapolation hypothesis -- NO cofinal claim"
              % comp_txt)

    # ---------------- S8: Leg E -- must-fails
    section("S8  LEG E -- WARDS / MUST-FAILS")
    ev9m = (recs[0] if smoke else mrecs[0])["ev"]
    led9 = ev9m["led"]
    hs9 = ev9m["hst"]
    j9 = hs9["j"]
    a9, b9 = int(led9["ptr"][j9]), int(led9["ptr"][j9 + 1])
    g9 = led9["G1"][a9:b9]
    x9j = float(np.sum(g9))
    drop9 = mutant_group_drop(tuple(float(v) for v in g9))
    dev1 = abs(drop9 - x9j) / max(abs(x9j), 1e-300) \
        if b9 - a9 > 1 else 1.0
    check("G80-e1-group-drop",
          fr_drop == 1 and dev1 >= MUT_MIN,
          "e1 LOUD: the drop-group 'recomposition' breaks the "
          "toy L1 by EXACTLY %s (Fractions-warded in G41) and "
          "the real argmax block value by rel %.1e >= %.0e -- "
          "an incomplete group ledger cannot slip through the "
          "recomposition ward (live worst %.1e)"
          % (str(fr_drop), dev1, MUT_MIN, l1rec_w
             if not smoke else 0.0))
    wmx9 = mutant_wrong_window_max(tuple(
        float(v) for v in ev9m["val_all"]))
    true9 = float(np.max(np.abs(ev9m["val_all"])))
    check("G81-e2-wrong-window-max",
          fr_wmx == 1 and wmx9 <= true9,
          "e2 CAUGHT (exact): the truncated-window 'maximum' "
          "breaks the two-ancestor ward on the sealed toy by "
          "EXACTLY %s (mutant cap 4 < hga 5, true slack 1) "
          "while the true window maximum holds it exactly "
          "(live worst slack %.1e); real w9 mutant max %.3e <= "
          "true %.3e -- a lambda-pair bound with the wrong "
          "window maximum is structurally refused"
          % (str(fr_wmx), panc_w, wmx9, true9))
    toy_capcol = (1.0, 3.0, 2.0)
    toy_rho = (0.1, 0.9, 0.1)
    cap_mut = mutant_cap_posthoc(toy_capcol, toy_rho, 0.5)
    cap_seal = max(toy_capcol[:1])
    check("G82-e3-cap-posthoc",
          len(e3_hits) >= 1 and cap_mut == 3.0
          and cap_mut != cap_seal,
          "e3 CAUGHT twice: the after-sight cap re-pick "
          "consumes the evaluated bound column -- AST-FLAGGED "
          "(%s) -- and on the toy returns %.1f != the sealed "
          "mid-ladder freeze rule's %.1f (a cap constant chosen "
          "after sight of the spikes is structurally refused)"
          % (e3_hits[0] if e3_hits else "MISS", cap_mut,
             cap_seal))
    rb9 = mutant_qmax_readback(dict(trs=ev9m["trs"],
                                    m=ev9m["m"]))
    check("G83-e4-qmax-readback",
          len(e4_hits) >= 1 and (not sc_own) and rb9 >= 0.0,
          "e4 AST-CAUGHT: the 'cap coordinate' consuming the "
          "q_max RECORD is FLAGGED (%s) while the three "
          "module-own cap builders are clean (%d hits) -- the "
          "target-side concentration coordinate cannot enter "
          "the cap side (the mutant value %.3f is computed only "
          "to prove the mutant runs)"
          % (e4_hits[0] if e4_hits else "MISS", len(sc_own),
             rb9))

    # ---------------- S9: verdict
    section("S9  VERDICT")
    check("G95-mincut-unchanged", True,
          "mincut base 4 / refined 5 UNCHANGED; what the round "
          "adds: the exact per-group mass ledger on the r314 "
          "fold segmentation (partition + L1 recomposition + "
          "two-ancestor bound), the heavy-group anatomy with "
          "the sealed SOURCE/AGGREGATION adjudication, the "
          "three cap candidates with mid-ladder certification "
          "and the exact cap chain m qmax <= ng x hgn, the "
          "route growth exponent and the Q3 recomposition -- "
          "NO new certificate promoted, NO universal bound "
          "claimed beyond the measured rungs")
    if smoke:
        verd = "SMOKE_NO_ADJUDICATION"
    else:
        parts = ["R327_ANCHORS(identity %.1e, r306 C2 %.3f viol "
                 "%d/57, r316 n %d rho4 bit-near, r324 C_NSC "
                 "%.4f/C_PIL %.4f/C_INF %.4f viols %d/%d/%d, s0 "
                 "named 3/3, e_tot %+.3f, r324-pre C_M2 %.4f "
                 "viol7 EXACT)"
                 % (rec3_w, C2r, viol2, n327, C_NSC, C_PIL,
                    C_INF, len(viol_nsc), len(viol_pil),
                    len(viol_G), e_tot, C_M2)]
        parts.append("SEAL(partition %.1e, L1 recomposition "
                     "%.1e, two-ancestor %.1e, cap chain %.1e, "
                     "ledger %.1e, purity clean, toys exact)"
                     % (part_w, l1rec_w, panc_w, capch_w,
                        led_dev))
        parts.append("ANATOMY(%s: named ratio %.3f, gap med "
                     "%.3f, align med %.3f, thirds %s, nwin "
                     "%s)"
                     % (anatomy, med_ratio,
                        float(np.median(gap_col)),
                        float(np.median(al_col)), str(th_hist),
                        str(nw_hist)))
        parts.append("CAPS(C_LV %.4f viol %d named %d/4, C_HG1 "
                     "%.4f viol %d, C_HG2 %.4f viol %d, minA "
                     "%s, C_NG %.4f viol %d, e_hg %+.3f e_lv "
                     "%+.3f e_ng %+.3f e_route %+.3f %s)"
                     % (C_LV, len(viol_lv), named_lv,
                        hg_caps[1][0], len(hg_caps[1][1]),
                        hg_caps[2][0], len(hg_caps[2][1]),
                        str(minA), C_NG, len(viol_ng), e_hg,
                        e_lv, e_ng, e_route,
                        "DECIDED" if decided else "UNDECIDED"))
        parts.append(verdict_main)
        parts.append("COMPOSITION(%s)" % comp_txt)
        parts.append("MUSTFAIL_LEDGER(e1-e4 + scopes)")
        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 partition, the L1 "
          "recomposition, the two-ancestor bound, the cap "
          "chain, the Fractions toys, the tree logic and the "
          "purity audits (exact / AST-decided); MEASURED: every "
          "constant, violation count, census and exponent (the "
          "finite class ladder + 2 mains + 2 live controls); "
          "OPEN: any bound beyond the measured rungs, the "
          "cofinal law, the ladder-to-m_0* extrapolation, 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(?:\s+\(SMOKE\))?"
    r"(?:\s+VERDICT\s+(\S+))?\s+SPEC_SHA\s+([0-9a-f]+)")


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


def _exec_probe(name, src):
    """Execute one embedded frozen probe source BYTE-EXACT in its own
    module namespace 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, exp_verdict, 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(4) == exp_sha
              and (exp_verdict is None or m.group(3) == exp_verdict))
    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%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,
             (" VERDICT " + exp_verdict) if exp_verdict else "",
             code, prov), flush=True)
    return ok


_PLAN = (
    ('fa_provenance_probe', _SRC_0, 36, '9a6696f875718322', None),
    ('qmax_m2_origin_probe', _SRC_1, 36, 'dc36cacbebdaf53b', None),
    ('extraction_order_probe', _SRC_2, 18, '31277f917dd04a7e',
     'ELEMENTWISE_STABILIZATION_GO'),
    ('group_mass_cap_probe', _SRC_3, 34, '11e4fd401ff77583', None),
)


def run():
    t0 = time.time()
    print("=" * 74)
    print('v970 -- PRIME.EXTRACTION.ELEMENTWISE.01 [E] +')
    print('PRIME.L2.RENYI3.MEASURED_COMPOSITION.01 [O] (rounds 323-327):')
    print('THE EXTRACTION REPAIR AND THE TERMINAL COMPOSITION -- (1) r323')
    print('aborted CLEANLY (L* paused by the reviewer, before any write')
    print('access -- nothing counts as a round).  (2) r324 (after the')
    print('course correction; the pre-work banked as r324-pre):')
    print('PILEUP_GROWS_SUBCRITICAL(+0.172 < 0.224) -- S0 exact (M_3 <=')
    print('q_max M_2, F_A de-black-boxed via F_A B log m == m q_max),')
    print('the M_2 export pointwise refuted / distributionally GO, the')
    print('O(log m) scale count CERTIFIED (C_NSC), the per-scale mass')
    print('refuted: the near-critical windows are ONE heavy source')
    print('scale; the composition MEASURED to m_0* = 10^59.6 at the')
    print('record bar (r328B chain audit: the chain-honest need is')
    print('block-level 454/501, bar 0.188, m_0* 10^238 -- the verdict')
    print('survives, 0.172 < 0.188; the record stays sealed).  (3) r325:')
    print('ELEMENTWISE_STABILIZATION_GO -- the extraction repair is a')
    print('QUANTIFIER statement: all three channels stabilize exactly at')
    print('the finite anchor onset, constant under mesh refinement;')
    print('H_cof is not needed; B = construction substrate, C =')
    print('quantified density step.  (4) r326 (Lean): the Level-C')
    print('architecture implemented -- sourceExact_buildPrimeWindow')
    print('PROVED, comb stabilization PROVED, weil_nonneg_of_windowlocal')
    print('PROVED (extraction without the ladder); census 5 -> 8 with')
    print('three typed Level-C statements.  (5) r327: CAP_PARTIAL with')
    print('SOURCE anatomy -- the heaviest group is EXACTLY ONE beta/')
    print('omega fold pair on all 65 rungs (kz53 = one coincidence at')
    print('88.8 percent); the Lambda-pair cap refuted, the group count')
    print('certified (the third O(log m) count); the r324 MEASURED')
    print('composition stays the end state; direction: WHERE can the')
    print('coincidence sit (source geometry).')
    print("(frozen probes embedded byte-exact, sealed --smoke stage; "
          "NO RH claim)")
    print("=" * 74, flush=True)
    gates = []
    _extraction_and_composition(gates)
    for name, src, exp_n, exp_sha, exp_verdict 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, exp_verdict, gates)
    ok = all(gates)
    print("\n" + "=" * 74)
    print("v970: %d/%d gates passed (23 module-own checks + 4 "
          "pattern gates) | runtime %.1f s"
          % (sum(gates), len(gates), time.time() - t0))
    print('the extraction repair and the terminal composition stand')
    print('frozen: the elementwise architecture is BANKED (R325 GO +')
    print('R326 Lean implementation -- sourceExact_buildPrimeWindow,')
    print('the comb stabilization and the ladder-free extraction')
    print('PROVED; census 5 -> 8 with three typed Level-C statements;')
    print('the honest new connection: two window-local lemmata + the')
    print('elementwise architecture + cited classics => RH, open links')
    print('arch/pole transcription + compression bridge + source')
    print('completion); the terminal lane ends in the MEASURED')
    print('composition (subcritical +0.172 < 0.188 chain-honest per the')
    print('r328B audit, m_0* record 10^59.6 / chain-honest 10^238, the')
    print('gap an explicit extrapolation hypothesis; the spike anatomy')
    print('is ONE bulk/window coincidence -- the coincidence-geometry')
    print('question is the named direction).  HONEST: nothing is proved')
    print('cofinally; the window-local positivity premise is proved')
    print('nowhere; the two true Lean holes are unchanged')
    print('(lstar_subordination + terminal_positive_main); L* stays')
    print('paused.  Mincut base 4 / refined 5 unchanged; NO RH claim.')
    print("[%s] v970 VERDICT GATE" % ("PASS" if ok else "FAIL"))
    return 0 if ok else 1


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