#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""v906 -- PRIME.PORT.TAILSIGN.01 + PRIME.PORT.TAILSIGN.02 + PRIME.PORT.PG.SCHUR.01 + PRIME.PORT.TAIL.ABEL.01 + PRIME.PORT.TAIL.SEGSPLIT.01 + PRIME.PORT.TAIL.OSCPAIR.01: THE TAIL MECHANISM MAP -- five dead routes with named seats and two structural positives on the n > q half of the wall end-form, TYPED EXPLICITLY AS MECHANISM/NEGATIVE CARTOGRAPHY, NOT PROGRESS, one module from six probes (14/14 + 10/10 + 20/20 + 22/22 + 24/24 + 22/22 checks, zero fails, verdicts TAILSIGN-MEASURED (NET-A(67/67) + NET-B(67/67@cB|12/67@9) / POINTWISE-FAIL-V(0/67) / MECH-NET-ONLY / HEADFLOOR-O1(slope=+0.113) / UNIF-TERMINAL-POS) + TAILREPAIR-MEASURED (FAILGEO(int med 2) / SET-DIFFUSE(k90 med 646) / REPAIR-GROWING(X^0.89) / HEADFLOOR2-AMBIG(slope=-0.395)) + PGSCHUR-MEASURED (LOEWNER-WARDED(39/39 exact) / DFAIL(0) / OUTCOME-C(med qbar/q=91.310, max=408.182) / KSTAR-SKIPPED) + TAILABEL-MEASURED (DUALSIGN-OPEN(best r=1: 0/67) / ABEL-EXACT(8.9e-16) + ARITH-ID / ENV-INSUFFICIENT(gap law +1.744) / CHAT(>=1/2 on 64/67) / SCREENS-AMBIG) + SEGSPLIT-MEASURED (BP-CENSUS(med 4, neg-dom 67/67) / SEG-ID-EXACT(3.5e-16) / SEGENV-INSUFFICIENT(residual law +1.824) / GAIN(med 0.69 < 1 on 67/67) / SCREENS) + OSCPAIR-MEASURED (RECON-WARDED(5.5e-03) / OSC-FEW(n90 med 3) / GAMMA(CARRIER-FAR, med d 13.17) / REDUCED-ACHIEVED(K=12, med share 1.01) / SCREENS-PASS); discovery probes rounds 62-63, 2026-08-10/11, re-run identically at promotion, embedded BYTE-EXACT and executed verbatim, ~105 s).  THE TWO STRUCTURAL POSITIVES: (P1) HEADFLOOR-O1 (tail_sign_mechanism, 14/14): the ENTIRE h-decay of the wall margin lives in the sign-measured atom tail -- head_B at the first B-cover cut is O(1) (tau-screen slope +0.113 +- 0.164, R^2 0.02, med 0.388) and tail_B <= 0 net at the B-cut on 67/67: the open arithmetic statement collapses to the ONE-SIDED bound tail_B > -head_B between two O(1) objects whose gap is the margin m_h itself; (P2) the 12-BIN REDUCED STATEMENT (tail_oscillation_pairing, 22/22): the missing oscillation bookkeeping is explicit and SMALL -- the tail pairing P_h = <dF, q_v>_deep decomposes over the orthonormal half-range cosine frame (reconstruction >= 99.45 percent on every rung) with a TINY carrier census (n90 med 3, low-frequency, window-harmonic locked j* in {1,2,3} on 67/67), and 12 frozen global bins carry share min/med/max +0.846/+1.006/+1.049 on 67/67 -- the tail bound is now a statement about ~12 windowed psi-fluctuation Fourier coefficients Fhat(omega), omega <~ 5; honestly typed: the reduced margin carries the FULL decay (screen -1.042, R^2 0.80) -- the reduction changes the DIMENSION of the open statement, not its difficulty; and the carriers are measurably NOT gamma-concentrated (CARRIER-FAR: med d_gamma 13.17 vs uniform null ~1.0, near 0/67, all carriers BELOW gamma_1 = 14.13 at these window depths -- a result, not a celebration).  THE FIVE DEAD ROUTES, EACH WITH A NAMED SEAT: (D1) POINTWISE SIGN (tail_sign_mechanism): the net negativity is an arithmetic CANCELLATION fact, not a weight-sign fact -- sup q_v beyond EVERY cut is positive on 67/67 (med 0.67 max|q|, positive node share med 0.65) and the terminal lobe is POSITIVE on 67/67 (onset u/(2 alpha) = 0.752, scale-stable): MECH-NET-ONLY, no pointwise fix exists; (D2) THE POINTWISE REPAIR (tail_sign_repair, 10/10): the minimal atomwise enlargement exists but its price is the window itself -- no small named exception set (SET-DIFFUSE, k90 med 646, union 10649; the largest carriers are simply the primes right behind the cut), the repair support grows as N+ ~ X^0.890 (R^2 1.00, med 89 percent of ALL deep atoms), and the enlarged head is ANTI-tau (slope -0.395, HEADFLOOR2-AMBIG): the pointwise form relocates the one-sided bound onto a window-growing support; (D3) THE DIRECTIONAL LOEWNER ROUTE (pgram_directional_schur, 20/20): with D = (1/2)P_G + c_dom I (the v905 chain) the whole construction is exact-rationally certified and the Loewner step holds EXACTLY (q <= qbar, Fraction comparison, 39/39, no D-FAIL) -- but the sufficient form n > qbar dies on 38/39 (delta med -5.28) and the loss is NO O(1): qbar/q med 91.3, max 408 -- TWO orders of magnitude; THE MECHANISM: D is an excellent FLOOR model of B (c_B/lam_min(B) med 0.979) but a catastrophic INVERSE model along b -- the Schur load q reads the FULL spectral geometry of B (directions of scale 10..1e4) which D caps at its O(1) floor: D^{-1} inflates exactly the b-components that B^{-1} suppresses; any future dominance route needs the MIDDLE geometry of B along b, not the floor; (D4) THE CUMULATIVE/ABEL ROUTE (tail_abel_transport, 22/22): the Abel transport of the B-cover tail to the integer lattice is EXACT (chain order 1..3 at 8.9e-16, lattice tie 9.7e-15) and the arithmetic identity of the cumulants is NAMED and warded (A^(1) = windowed psi partial sum at 1.5e-15; A^(2)/A^(3) = Riesz/Cesaro means at 3.3e-15) -- but NO order r <= 3 fixes the sign of the prime-free dual kernel (one-signed 0/67; the r = 2 curvature hypothesis is DEAD), the honest all-integer envelope (KAPPA_INT = 0.059547, amendment A1 disclosed fail-first: the deployed jump-point kappa = 0.038821 does NOT majorize the integer psi deviations) closes NOTHING (slack min/med -3.32e+06/-1.51e+05 mu1, positive 0/67) with the envelope GAP LAW e^{+1.744 alpha} (2SE 0.202, R^2 0.77); THE OSCILLATION DIAGNOSIS: the envelope overshoot vs the true oscillating remainder is only med 20x -- the real hole is that the true remainder itself is ~1e4 mu1 units; and chat = (H + Ttilde)/mu1 is NOT O(1) (negative on 3 deep rungs): the halfgap-1/2 does NOT live at the (H + Ttilde) split but in the near-cancellation chat + rhat = shat; (D5) THE SEGMENT SPLIT (tail_segment_split, 24/24): the telescoped segment identity T = Sum_j [m_j w(b_{j+1}) - Sum_seg B_j(k) Dw(k)] stands EXACT on 67/67 (3.5e-16; the r = 1 kernel splits into med 4 one-signed segments at CLASSICAL breakpoint positions), the per-segment demand is NAMED (a one-sided windowed psi statement AT DEEP ANCHORS: 135 segments need the lower psi window side, 110 the upper) -- but the segment envelope closes nothing (slack med -2.17e+05 mu1, residual law +1.824 = the global law UNCHANGED) and the GAIN is < 1 on 67/67 (med 0.694): THE SEGMENT ROUTE IS COSTLIER THAN THE GLOBAL ONE; THE MECHANISM is the ANCHOR PRICE -- every Chebyshev-class envelope |psi(x) - x| <= kappa x pays the deep anchor at EVERY point of the segment, one-sidedness saves numerically nothing under a symmetric envelope, and the deficit carrier is the INTERIOR segment (onset x med 0.572), not the terminal lobe (0/67); THE NAMED MISSING OBJECT: a DIFFERENCE envelope for psi(y) - psi(x) - (y - x) on short deep windows (Brun-Titchmarsh/Selberg class instead of Chebyshev class; window lengths = the measured segment spans x in [0.31, 0.83] x 2 alpha).  CONTROLS FIRE IN ALL SIX PROBES (smooth/Epstein/scramble batteries per frozen spec, each honest limit typed in-probe -- incl. the disclosed smooth-segment 2.93 > 1 read and the vacuous delta-screen); all round-59/60/62 reproduction wards green; AST firewalls clean; RNG only in controls.  NO RH claim; no marker moves; nothing here bounds tau or the two scalars n, q -- this module is the map of where the tail statement lives and which certificate languages cannot reach it.

PROVENANCE: discovery probes tail_sign_mechanism_probe.py (14/14,
TAILSIGN-MEASURED, round 62 note CXLVII, Spec-SHA a9bdf536...,
2026-08-10), tail_sign_repair_probe.py (10/10, TAILREPAIR-MEASURED,
round 62 note CXLVIII, Spec-SHA e383864f..., 2026-08-10),
pgram_directional_schur_probe.py (20/20, PGSCHUR-MEASURED, round 63
note CL, Spec-SHA 85b78941..., 2026-08-11),
tail_abel_transport_probe.py (22/22, TAILABEL-MEASURED, round 63
note CLII, Spec-SHA 02f7d485..., 2026-08-11),
tail_segment_split_probe.py (24/24, SEGSPLIT-MEASURED, round 63
note CLVI, Spec-SHA 8c5b4324..., 2026-08-11),
tail_oscillation_pairing_probe.py (22/22, OSCPAIR-MEASURED, round
63 note CLV, Spec-SHA d125f293..., 2026-08-11), all re-run
identically at promotion.  ROUND-31 EMBEDDING CONVENTION: frozen
sources embedded BYTE-EXACT, executed verbatim in isolated
namespaces; printed spec SHAs reproduce; byte-equality ward vs
experiments/tfpt-discovery/ inside the pattern gates.  All probes
consume the READ-ONLY deployed core v563_paper2_readouts.py; all
spec amendments are disclosed fail-first inside the probes.

FIREWALL: no zeros, no prime-table oracles (AST firewalls inside
the probes; the gamma comparison in the oscillation probe uses
hardcoded literature constants for DISTANCE MEASUREMENT only,
never construction -- the wall_margin S2 pattern); every negative
is a first-class registered result; NO route here is claimed to
work; NO RH claim.  Python-only per GATE.WOLFRAM.02.
"""

import contextlib
import io
import os
import re
import sys
import time
import types

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

# ------------- frozen probe source tail_sign_mechanism_probe (embedded BYTE-EXACT, raw string)
_SRC_0 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""tail_sign_mechanism_probe -- PRIME.PORT.TAILSIGN.01
(EXPLORATION ONLY, experiments/; round 62, theorem-engineering on
the RH-side wall: the CRACK attempt on the n > q half's only
visible seam -- the SIGN MECHANISM of the covering-cut tail.
Predecessor wall_cut_schedule_probe (round 60) measured FULL
COVERAGE 67/67 with minimal cuts n_min in [3, 9], ONE shared cut
n = 9, and tail <= 0 at the first covering cut on 67/67 (the head
OVERSHOOTS).  THE QUESTION HIERARCHY, each level strictly
stronger: (a) NET tail <= 0 (regression), (b) POINTWISE weight
negativity beyond the cut (then the tail sign is DETERMINISTIC
for any nonnegative comb), (c) CLASSICAL reduction of the weight
sign to the prime-free direction v_sm, (d) the HEAD FLOOR
tau-screen (O(1) or relocation -- the headline), (e) the
uniformity boundary named.  2026-08-10.)

THE TWO EXACT BOOKKEEPINGS (frozen; both warded to head + tail =
m EXACTLY).  On the lift-race surface m_h = lam_min(K) = lift -
demand exactly, with lift = E_at(v) - E_sm(v), demand =
-(E_ar(v) + E_sm(v)); hence ALSO m = E_ar(v) + E_at(v) -- the
smooth-comb parts CANCEL IDENTICALLY between lift and demand.
Cut at u_c = log c:
  A (round-59/60 verbatim; smooth counterpart INSIDE the tail):
      G(c)      = sum_{u_n <= u_c} mu_n q_v(u_n)
                  - int_{u <= u_c} 2 e^{u/2} q_v(u) du - demand,
      tail_A(c) = sum_{u_n > u_c} mu_n q_v(u_n)
                  - int_{u > u_c} 2 e^{u/2} q_v(u) du,
      m = G(c) + tail_A(c).  Pointwise weight negativity does NOT
      fix sign(tail_A): the smooth counterpart enters with the
      OPPOSITE sign.
  B (atom-only tail; the mechanism bookkeeping, NEW):
      head_B(c) = E_ar(v) + sum_{u_n <= u_c} mu_n q_v(u_n),
      tail_B(c) = sum_{u_n > u_c} mu_n q_v(u_n),
      m = head_B(c) + tail_B(c).  head_B is a FINITE EXPLICIT
      object (the archimedean read + finitely many atom reads);
      tail_B is a nonnegative-weighted sum of DEEP atom weights,
      so  q_v(u) <= 0 for all u > u_c  ==>  tail_B(c) <= 0  for
      ANY nonnegative comb -- no arithmetic input.
  Relation (warded): G(c) = head_B(c) + smoothtail(c) with
  smoothtail(c) = int_{u > u_c} 2 e^{u/2} q_v(u) du.
  SAID PLAINLY (frozen): tail_B <= 0 alone does NOT lower-bound
  m (m = head_B + tail_B <= head_B).  What the sign mechanism
  buys: the round-59 TWO-SIDED tail-accuracy demand collapses to
  the ONE-SIDED lower bound tail_B > -head_B, with the tail's
  sign known for free; the certificate shape is head_B > |tail_B|
  and at any cut where tail_B <= 0, cert_B := head_B - |tail_B|
  = m EXACTLY (same algebra as round 60).  Whether the remaining
  one-sided statement is between two O(1) quantities or is
  itself tau-small is measured in (d) -- that is the headline.

WHAT IS MEASURED (frozen; typed, never kills):
 (a) NET: sign census of tail_A at the per-rung first A-covering
     cut c(h) (cert_A > 0, round-60 verbatim) and at the shared
     cut n = 9; sign census of tail_B at the per-rung first
     B-COVERING cut cB(h) (cert_B = head_B - |tail_B| > 0 --
     bookkeeping B has its OWN schedule) and at the shared cut
     n = 9.  Typed NET-A(k/N@cmin | k9/N@9),
     NET-B(kB/N@cB | k9/N@9), plus the B-schedule ladder n_minB.
 (b) POINTWISE: q_v is PIECEWISE LINEAR on the lag knots i*D, so
     sup_{u > u_c} q_v is EXACT from the knot values (+ the cut
     point).  Census beyond log 9, beyond the per-rung u_min (A),
     and beyond the per-rung u_minB (B): positive-knot count, sup
     q_deep / max|q| (exact), number of sign changes beyond the
     cut, the LAST sign change u_last (whole window, exact
     interpolation on knots) in the scaled variable u_last/alpha
     vs the node law 0.3727 - 0.0116 alpha and vs log 9 / alpha,
     the terminal sign.  Atom-level census: deep atoms with
     q_v(u_n) > 0, their count, and positive contribution P =
     sum mu_n q^+ vs |tail_B(9)|.  Typed POINTWISE-V(n/N) iff
     sup q_deep <= 0 beyond log 9 on n rungs.
 (c) CLASSICAL: the same census for q_{v_sm} with v_sm the
     PRIME-FREE smooth-model bottom mode (arch + PNT-continuum
     comb only; branch crossings disclosed per the lift-race
     probe: at most MAX_CROSS rungs with |<v, v_sm>| < OV_MIN,
     each carrying the direction on one of the 4 lowest smooth
     branches).  Agreement of the deep-sign property and of
     u_last between v and v_sm (corr, med |Delta|); jackknife law
     u_last/alpha vs alpha.  Typed CLASSICAL-NEG(n/N) etc.
 (d) THE HEAD FLOOR (tau-screen, decisive): the TYPED screen
     lives at the per-rung first B-COVERING cut cB(h) (the
     mechanism's own schedule; the smoke showed head_B(9) < 0 on
     most rungs -- the shared cut 9 belongs to bookkeeping A's
     schedule): jackknife slope of log head_B(cB) vs log m_h.
     Bands PASS |s| <= 0.30 (HEADFLOOR-O1: the ENTIRE h-decay of
     the wall margin lives in the sign-measured tail; the open
     arithmetic statement tail_B > -head_B is an inequality
     between two O(1) quantities whose gap is m_h) / RELOC s >=
     0.70 (the hardness moved into the finite head -- an honest
     relocation) / else AMBIG.  Context screens (printed, never
     typed): head_B(9), G(9).  Plus the SHARED B-CUT search: the
     single cut value n covering the most rungs in the B sense
     (candidates = all deployed atom values <= CAP_SHARED),
     printed as SCHED-B(n*, count).
 (e) UNIFORMITY BOUNDARY (named): every certificate piece depends
     on h -- the weight through the direction (v arithmetic, v_sm
     prime-free) and through the window (2 alpha(h), lag pitch
     D(h)); the head through e_ar(h) and the h-dependent atom
     weights.  If pointwise negativity HOLDS at the shared cut:
     report the sign margin -sup q_deep / max|q| (med/min, typed
     UNIF-STABLE iff min >= MARGIN_MIN, else UNIF-MARGINAL) and
     its jackknife trend vs alpha.  If it FAILS: report the
     minimal pointwise-valid cut u_pw = last sign change (only
     meaningful when the terminal sign is negative), its scaled
     position and the atom count of the enlarged head <= e^{u_pw}
     -- i.e. whether the pointwise mechanism is restorable at a
     UNIFORMLY FINITE head or only at a head growing with X.

FROZEN PROTOCOL (machinery verbatim from wall_cut_schedule_probe
= round-59/60 chain; v_sm construction verbatim from
arithmetic_lift_race_probe S0):

 W   LADDER + WARDS (kill -> PIPELINE-BROKEN / WARD-BROKEN): W1
     faithful ladder >= MIN_RUNGS = 40 (kz 2..KZMAX, H_MIN <= h
     <= HCAP, X <= ATOM_MAX); W2 WARD m_h > 0 everywhere; W3 WARD
     both exact bookkeepings |lift - demand - m| <= ID_WARD AND
     |e_ar + e_t - m| <= ID_WARD; W4 WARD atom identities (atom
     sum = E_at, PNT grid sum = E_sm, rel <= ID_WARD); W5 WARD
     split exactness on the full scans: max rel dev of
     (head_B + tail_B) - m, (G + tail_A) - m, and G - head_B -
     smoothtail, all <= SCAN_WARD; W6 REPRODUCTION of round
     59/60: G > 0 counts at cuts (50, 100, 200) == (52, 26, 25);
     n_min(h) in [NMIN_LO, NMIN_HI] on every rung; the shared cut
     n = 9 covers N/N (cert > 0); tail_A <= 0 at the first
     covering cut on N/N; W7 WARD the v_sm branch: |<v, v_sm>| >=
     OV_MIN on all but <= MAX_CROSS rungs, each crossing rung
     carrying the direction on one of the 4 lowest smooth
     branches with overlap >= OV_MIN.

 H   THE HIERARCHY (typed as frozen above): Ha NET; Hb POINTWISE
     (v); Hc CLASSICAL (v_sm); Hd HEAD FLOOR + tau-screens; He
     UNIFORMITY BOUNDARY.

 C   CONTROLS (kill -> WARD-BROKEN if silent): scramble (seed 1)
     and Epstein x^2+5y^2 comb at kz 9, smooth comb (lattice
     masses 2 e^{u/2} du): each must show m < 0 AND cert_B =
     head_B - |tail_B| < 0 at EVERY cut AND A-sense cert coverage
     == 0 (the mechanism cannot manufacture a certificate without
     the wall); the smooth comb's DIFFERENT failure (lift
     collapse) recorded.

KILLS: K1 ladder (W1) -> PIPELINE-BROKEN; K2 wards (W2-W7, C) ->
WARD-BROKEN.  All H-typed outcomes are measurements, never kills.

VERDICT (frozen enum): TAILSIGN-MEASURED with typed sublabels
NET-A(k/N|k9/N) + NET-B(kB/N@cB|k9/N@9),
MECH-CLASSICAL-POINTWISE / MECH-POINTWISE-V / MECH-NET-ONLY /
MECH-MIXED(counts) [precedence in that order, decided at the
per-rung first B-covering cut cB(h) -- the mechanism's own
schedule],
HEADFLOOR-O1(slope) / HEADFLOOR-RELOC(slope) /
HEADFLOOR-AMBIG(slope),
UNIF-STABLE(min margin) / UNIF-MARGINAL(min margin) /
UNIF-CUTGROWTH(x_pw med, head atoms med) / UNIF-TERMINAL-POS;
else PIPELINE-BROKEN / WARD-BROKEN.

FROZEN BARS: KZMAX = 150; MIN_RUNGS = 40; REF_CUTS = (50, 100,
200); REF_COUNTS = (52, 26, 25); NMIN_LO, NMIN_HI = 3, 9;
NC_SHARED = 9; CAP_SHARED = 10000; ID_WARD = 1e-10; SCAN_WARD =
1e-9; NG_SMOOTH = 6000; OV_MIN = 0.8; MAX_CROSS = 2; SLOPE_PASS =
0.30; SLOPE_RELOC = 0.70; MARGIN_MIN = 0.01; NODE_C = 0.3727,
NODE_S = -0.0116 (declared input); CTRL_KZ = 9; scramble seed 1;
jackknife = full leave-one-out, CI = +- 2SE; sign decisions on
exact knot values (float sign, no tolerance -- the sup over a
piecewise-linear function is attained at a knot or at the cut
point).

SMOKE-RUN DISCLOSURE (2026-08-10, before freezing): ONE smoke run
(14/14, 17.6 s) on SPEC v0.  All wards green at 1.9e-13 or better
and the full round-59/60 reproduction exact.  Smoke facts frozen
as the context the frozen run must confirm: (i) NET-A holds
everywhere (tail_A <= 0 on 67/67 at c(h) AND at the shared cut
9), but the ATOM-ONLY tail flips: tail_B(9) <= 0 on only 12/67 --
on 55 rungs head_B(9) < 0 and tail_B(9) > 0 (the atom-only deep
sum CARRIES the positive lift there); (ii) bookkeeping B has its
OWN covering schedule: cert_B > 0 cuts exist on 67/67 with n_minB
med 17, and head_B at that cut is O(1) vs m (slope +0.113 +- 2SE
0.164, R^2 0.02); (iii) POINTWISE FAILS 0/67 (sup q_deep med 0.67
max|q|, positive knot share med 0.65, terminal lobe POSITIVE on
67/67); the same census is CLASSICAL (q_{v_sm}: 0/67, agreement
67/67, corr(u_last) +0.97, law u_last/alpha = +0.0163 alpha + c,
R^2 0.98, kz 97 on its carrier branch); (iv) G(9) screen slope
+0.292 (R^2 0.30); head_B(9) > 0 on only 12/67 -- the v0 typed
head-floor rule (keyed to head_B(9)) was nearly vacuous.
AMENDMENTS (disclosed, no bar/band/tolerance moved): A1 the typed
head-floor screen re-keyed from head_B(9) to head_B(cB) at the
per-rung first B-covering cut (head_B(9), G(9) stay printed as
context); A2 the MECH enum decided at cB(h) instead of the shared
cut 9 (bookkeeping B's own schedule; the shared-cut censuses stay
reported); A3 Ha additionally reports n_minB and the tail_B sign
census at cB; A4 Hb additionally reports the pointwise census
beyond u_minB (both directions, mech input); A5 the shared-B-cut
search added (info print).  Fail-first preserved: pointwise
negativity still fails at EVERY cut on the smoke (terminal lobe
positive), so the amendments cannot upgrade the mechanism verdict
beyond NET-ONLY; they relocate the screens to the bookkeeping the
mechanism actually lives on.

SPEC v1 (2026-08-10, frozen + SHA-hashed before the frozen run):
everything above.  Mechanical concretizations frozen with v1: (i)
cuts INCLUSIVE at atom positions (u_n <= u_c), the shared-cut
read at the largest atom position <= log 9 + 1e-12; (ii) knots
i*D for i = 0..M with the i = 0 value read at u = 1e-12 (q(0+) =
-||g||^2); (iii) u_last by linear interpolation between adjacent
knots with strict sign product < 0; (iv) the crossing-rung
carrier branch chosen as argmax_j |<v, v_sm^{(j)}>| over the 4
lowest smooth branches (disclosed per rung); (v) smoothtail via
the NG_SMOOTH midpoint grid (same grid as E_sm, so the W5
relation ward is exact).

NO-GO COMPLIANCE (frozen): no certified-bound retry, no rank-1
approximation, no Herglotz; no fit where an identity is claimed
(both bookkeepings are exact wards; the u_last law and the
head-floor screens are typed trends with jackknife error bars).

NO RH claim: a deterministic tail sign plus an O(1) explicit head
is a MEASURED SURFACE STRUCTURE -- the one-sided lower bound
tail_B > -head_B remains an unproved arithmetic statement at
every depth, and nothing here bounds it.  No marker moves.

FIREWALL: no zeros, no prime oracles (AST scan; banned ids
zetazero / nzeros / primerange / isprime / primepi / nextprime /
prevprime; the heads read the DEPLOYED window atoms); v563
READ-ONLY; RNG only inside the declared scramble control; stdout
only.

Sources (read-only): v563_paper2_readouts; cut/scan machinery
verbatim from wall_cut_schedule_probe.py (round 60); q_read +
v_sm construction verbatim from arithmetic_lift_race_probe.py;
node drift law from node_origin_arch_probe.py (declared input);
round-59/60 censuses (declared reproduction targets).

Run:
    experiments/tfpt-discovery/.venv/bin/python \
        experiments/tfpt-discovery/tail_sign_mechanism_probe.py
"""

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

import numpy as np

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

import v563_paper2_readouts as core        # noqa: E402  (READ-ONLY)

KZMAX = 150
MIN_RUNGS = 40
REF_CUTS = (50, 100, 200)
REF_COUNTS = (52, 26, 25)
NMIN_LO, NMIN_HI = 3, 9
NC_SHARED = 9
CAP_SHARED = 10000
ID_WARD = 1e-10
SCAN_WARD = 1e-9
NG_SMOOTH = 6000
OV_MIN = 0.8
MAX_CROSS = 2
SLOPE_PASS = 0.30
SLOPE_RELOC = 0.70
MARGIN_MIN = 0.01
NODE_C = 0.3727
NODE_S = -0.0116
CTRL_KZ = 9
BANNED_IDS = ("zetazero", "nzeros", "primerange", "isprime",
              "primepi", "nextprime", "prevprime")

CHECKS = []
KILLS = []
T0 = time.time()


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


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


def ast_scan(banned):
    src = open(os.path.abspath(__file__), encoding="utf-8").read()
    bad = []
    for node in ast.walk(ast.parse(src)):
        name = None
        if isinstance(node, ast.Name):
            name = node.id
        elif isinstance(node, ast.Attribute):
            name = node.attr
        if name and name.lower() in banned:
            bad.append(name)
    return bad


def ols_line(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    vx = float(np.var(x))
    if vx == 0.0:
        return float(np.mean(y)), 0.0, float("nan")
    b = float(np.cov(x, y, bias=True)[0, 1] / vx)
    a = float(np.mean(y) - b * np.mean(x))
    ss = float(np.sum((y - a - b * x) ** 2))
    st = float(np.sum((y - np.mean(y)) ** 2))
    return a, b, (1.0 - ss / st if st > 0 else float("nan"))


def jack_slope(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    _a, b, r2 = ols_line(x, y)
    n = len(x)
    bb = []
    for i in range(n):
        m = np.ones(n, bool)
        m[i] = False
        bb.append(ols_line(x[m], y[m])[1])
    bb = np.array(bb)
    se = math.sqrt((n - 1) / n * float(np.sum((bb - bb.mean())
                                              ** 2)))
    return b, se, r2


def corr(x, y):
    return float(np.corrcoef(np.asarray(x, float),
                             np.asarray(y, float))[0, 1])


def q_read(W, u, D, M):
    u = np.asarray(u, float)
    i0 = np.floor(u / D).astype(int)
    f = u / D - i0
    val = np.zeros_like(u)
    ok0 = (i0 >= 0) & (i0 < M)
    val[ok0] += (1.0 - f[ok0]) * W[i0[ok0]]
    ok1 = (i0 + 1 >= 0) & (i0 + 1 < M)
    val[ok1] += f[ok1] * W[i0[ok1] + 1]
    refl = u < D
    val[refl] += (1.0 - u[refl] / D) * W[0]
    return -0.5 * val


def smooth_comb(alpha, ng=NG_SMOOTH):
    ug = (np.arange(ng) + 0.5) * (2.0 * alpha / ng)
    mg = 2.0 * np.exp(ug / 2.0) * (2.0 * alpha / ng)
    return ug, mg


def lambda_eps(N):
    """Epstein x^2+5y^2 comb (port_schur_reduction verbatim)."""
    r = np.zeros(N + 1)
    s = int(math.isqrt(N)) + 1
    for x in range(-s, s + 1):
        for y in range(-s, s + 1):
            v = x * x + 5 * y * y
            if 1 <= v <= N:
                r[v] += 1.0
    a = r / 2.0
    lam = np.zeros(N + 1)
    for n in range(2, N + 1):
        acc = a[n] * math.log(n)
        for dd in range(2, n):
            if n % dd == 0:
                acc -= lam[dd] * a[n // dd]
        lam[n] = acc
    return lam


def knot_census(W, D, M, alpha, u_cut):
    """Exact deep-sign census of the piecewise-linear weight
    q(u) = q_read(W, u): knot values (i*D, i = 0..M, i = 0 read at
    u = 1e-12), sup over u > u_cut (exact: knots above the cut +
    the cut point), sign changes, last sign change (interpolated),
    terminal sign.  A non-finite cut is read as u_cut = 0+ (the
    whole window; the harshest census)."""
    if not math.isfinite(float(u_cut)):
        u_cut = 1e-12
    uk = np.arange(M + 1) * D
    ue = uk.copy()
    ue[0] = 1e-12
    qk = q_read(W, ue, D, M)
    qmax = float(np.max(np.abs(qk)))
    q_cut = float(q_read(W, np.array([u_cut]), D, M)[0])
    deep = uk > u_cut
    q_deep = np.concatenate([[q_cut], qk[deep]])
    sup_deep = float(np.max(q_deep))
    pos_frac = float(np.mean(q_deep > 0.0))
    prod = qk[:-1] * qk[1:]
    idx = np.nonzero(prod < 0.0)[0]
    ucross = np.array([uk[i] + D * qk[i] / (qk[i] - qk[i + 1])
                       for i in idx])
    n_deep_cross = int(np.sum(ucross > u_cut))
    u_last = float(ucross[-1]) if len(ucross) else float("nan")
    end_sign = float(np.sign(qk[np.max(np.nonzero(
        np.abs(qk) > 1e-15 * max(qmax, 1e-30))[0])]))
    return dict(qmax=qmax, sup_deep=sup_deep,
                sup_rel=sup_deep / max(qmax, 1e-30),
                pos_frac=pos_frac, n_deep_cross=n_deep_cross,
                u_last=u_last, end_sign=end_sign,
                n_cross=len(ucross))


def build_rung(kz, comb=None, scramble_seed=None,
               smooth_world=False, need_sm=True):
    """One rung of the lift-race surface with both bookkeepings,
    the full atom-cut scans, and (optionally) the smooth-model
    bottom direction (lift-race S0 verbatim)."""
    try:
        rr = core.build_window(kz, scramble_seed=scramble_seed)
    except Exception:
        return None
    if not (core.H_MIN <= rr["h"] <= core.HCAP):
        return None
    if rr["X"] > core.ATOM_MAX:
        return None
    alpha, M, D, h = rr["alpha"], rr["M"], rr["D"], rr["h"]
    uu = np.asarray(rr["uu"], float)
    mu = 2.0 * np.asarray(rr["lam"], float)
    if smooth_world:
        du = np.zeros(len(uu))
        du[1:-1] = 0.5 * (uu[2:] - uu[:-2])
        du[0] = uu[1] - uu[0]
        du[-1] = uu[-1] - uu[-2]
        mu = 2.0 * np.exp(uu / 2.0) * du
    if comb is not None:
        uu, mu = comb
    c_at = core.atom_lags_at(alpha, M, uu, mu)[0]
    c_ar = np.asarray(core.arch_lags(M, D), float)
    w, V = np.linalg.eigh(core.odd_toeplitz(c_ar + c_at, M))
    v = V[:, 0]
    ug, mg = smooth_comb(alpha)
    c_sm = core.atom_lags_at(alpha, M, ug, mg)[0]
    row = dict(kz=kz, alpha=float(alpha), h=h, M=M, D=D,
               m=float(w[0]), uu=uu)
    Wv = core.lag_weights_from_v(v, h)
    e_ar = float(c_ar @ Wv)
    e_t = float(c_at @ Wv)
    e_s = float(c_sm @ Wv)
    qa = mu * q_read(Wv, uu, D, M)
    qg = mg * q_read(Wv, ug, D, M)
    row.update(e_ar=e_ar, e_t=e_t, e_s=e_s, lift=e_t - e_s,
               demand=-(e_ar + e_s),
               dev_at=max(abs(float(qa.sum()) - e_t)
                          / max(abs(e_t), 1e-30),
                          abs(float(qg.sum()) - e_s)
                          / max(abs(e_s), 1e-30)))
    # ---- the atom-cut scans (cumsum routes; A verbatim round 60)
    cq = np.cumsum(qa)
    idxg = np.searchsorted(ug, uu, side="right")
    cg_all = np.concatenate([[0.0], np.cumsum(qg)])
    head_err = cq - cg_all[idxg]
    G = head_err - row["demand"]
    tail_A = row["lift"] - head_err
    cert_A = G - np.abs(tail_A)
    head_B = e_ar + cq
    tail_B = float(qa.sum()) - cq
    cert_B = head_B - np.abs(tail_B)
    smoothtail = float(qg.sum()) - cg_all[idxg]
    row.update(G=G, tail_A=tail_A, cert_A=cert_A, head_B=head_B,
               tail_B=tail_B, cert_B=cert_B, smoothtail=smoothtail,
               qa=qa)
    # reference-cut split (round-59 census reproduction)
    row["Gref"] = {}
    for nc in REF_CUTS:
        ucut = math.log(nc)
        he = (float(qa[uu <= ucut].sum())
              - float(qg[ug <= ucut].sum()))
        row["Gref"][nc] = he - row["demand"]
    if need_sm:
        ws, Vs = np.linalg.eigh(core.odd_toeplitz(c_ar + c_sm, M))
        vsm = Vs[:, 0]
        if float(v @ vsm) < 0:
            vsm = -vsm
        ov4 = [abs(float(v @ Vs[:, j])) for j in range(4)]
        jcar = int(np.argmax(ov4))
        vcar = Vs[:, jcar] * (1.0 if float(v @ Vs[:, jcar]) >= 0
                              else -1.0)
        row.update(ov=float(abs(v @ vsm)), ov4=ov4, jcar=jcar)
        row["Wsm"] = core.lag_weights_from_v(vsm, h)
        row["Wcar"] = core.lag_weights_from_v(vcar, h)
    row["Wv"] = Wv
    return row


def main():
    section("PRIME.PORT.TAILSIGN.01 -- the sign mechanism of the "
            "covering-cut tail (EXPLORATION ONLY)")
    print("    FROZEN_SPEC SHA-256 = %s"
          % hashlib.sha256(__doc__.encode("utf-8")).hexdigest())
    print("    NO RH claim; no marker moves.")
    print("\nS0 -- firewall")
    check("S0.1 AST firewall clean", not ast_scan(BANNED_IDS))

    # ------------------------------------------------------------ W
    section("W -- the faithful ladder + wards")
    rungs = []
    for kz in range(2, KZMAX + 1):
        row = build_rung(kz)
        if row is not None:
            rungs.append(row)
    rungs.sort(key=lambda r: (r["h"], r["kz"]))
    check("W1 faithful ladder >= %d rungs" % MIN_RUNGS,
          len(rungs) >= MIN_RUNGS,
          "%d rungs, h %d..%d  [%.1f s]"
          % (len(rungs), rungs[0]["h"], rungs[-1]["h"],
             time.time() - T0), kill="K1")
    if KILLS:
        return finish({})
    N = len(rungs)
    check("W2 WARD truth margin m_h > 0 on every rung (min %.3e)"
          % min(r["m"] for r in rungs),
          all(r["m"] > 0 for r in rungs), kill="K2")
    dev_bk = max(max(abs((r["lift"] - r["demand"]) - r["m"]),
                     abs((r["e_ar"] + r["e_t"]) - r["m"]))
                 / max(1.0, abs(r["m"])) for r in rungs)
    check("W3 WARD both exact bookkeepings (lift - demand = m AND "
          "e_ar + E_at = m -- the smooth parts cancel "
          "identically): max dev %.2e <= %.0e" % (dev_bk, ID_WARD),
          dev_bk <= ID_WARD, kill="K2")
    dev_at = max(r["dev_at"] for r in rungs)
    check("W4 WARD atom identities (atom sum = E_at, PNT grid = "
          "E_sm): max rel dev %.2e <= %.0e" % (dev_at, ID_WARD),
          dev_at <= ID_WARD, kill="K2")
    dev_sc = 0.0
    for r in rungs:
        sc = max(float(np.max(np.abs((r["head_B"] + r["tail_B"])
                                     - r["m"]))),
                 float(np.max(np.abs((r["G"] + r["tail_A"])
                                     - r["m"]))),
                 float(np.max(np.abs(r["G"] - r["head_B"]
                                     - r["smoothtail"]))))
        dev_sc = max(dev_sc, sc / max(1.0, abs(r["e_t"])))
    check("W5 WARD split exactness on the full scans (head_B + "
          "tail_B = m, G + tail_A = m, G = head_B + smoothtail): "
          "max rel dev %.2e <= %.0e" % (dev_sc, SCAN_WARD),
          dev_sc <= SCAN_WARD, kill="K2")
    cnts = tuple(int(np.sum(np.array(
        [r["Gref"][nc] for r in rungs]) > 0)) for nc in REF_CUTS)
    n_min, u_min, i9s = [], [], []
    for r in rungs:
        nn = np.round(np.exp(r["uu"])).astype(int)
        covC = r["cert_A"] > 0.0
        i0 = int(np.argmax(covC)) if bool(np.any(covC)) else -1
        n_min.append(int(nn[i0]) if i0 >= 0 else -1)
        u_min.append(float(r["uu"][i0]) if i0 >= 0
                     else float("nan"))
        i9 = int(np.searchsorted(r["uu"],
                                 math.log(NC_SHARED) + 1e-12,
                                 side="right")) - 1
        i9s.append(i9)
    cov9 = sum(1 for r, i9 in zip(rungs, i9s)
               if i9 >= 0 and r["cert_A"][i9] > 0)
    tneg_cut = sum(1 for r, nm in zip(rungs, n_min) if nm > 0
                   and r["tail_A"][int(np.argmax(
                       r["cert_A"] > 0))] <= 0.0)
    ok_rep = (cnts == REF_COUNTS
              and all(NMIN_LO <= nm <= NMIN_HI for nm in n_min)
              and cov9 == N and tneg_cut == N)
    check("W6 REPRODUCTION round 59/60: G > 0 at %s = %s == %s; "
          "n_min in [%d, %d] on %d/%d; shared cut n = %d covers "
          "%d/%d; tail_A <= 0 at first covering cut %d/%d"
          % (REF_CUTS, cnts, REF_COUNTS, NMIN_LO, NMIN_HI,
             sum(1 for nm in n_min
                 if NMIN_LO <= nm <= NMIN_HI), N, NC_SHARED,
             cov9, N, tneg_cut, N), ok_rep, kill="K2")
    n_cross = sum(1 for r in rungs if r["ov"] < OV_MIN)
    cross_ok = all(max(r["ov4"]) >= OV_MIN for r in rungs
                   if r["ov"] < OV_MIN)
    check("W7 WARD v_sm branch: %d rung(s) with |<v, v_sm>| < "
          "%.1f (%s; ward <= %d), each carried on smooth branch "
          "j = %s with overlap >= %.1f"
          % (n_cross,
             OV_MIN, ", ".join("kz%d ov %.4f" % (r["kz"], r["ov"])
                               for r in rungs
                               if r["ov"] < OV_MIN) or "none",
             MAX_CROSS,
             "/".join(str(r["jcar"]) for r in rungs
                      if r["ov"] < OV_MIN) or "-", OV_MIN),
          n_cross <= MAX_CROSS and cross_ok, kill="K2")
    if KILLS:
        return finish({})

    # ------------------------------------------------------------ Ha
    section("Ha -- NET: the tail sign at c(h) and at the shared "
            "cut n = %d (both bookkeepings)" % NC_SHARED)
    print("    bookkeeping A: tail_A = deep atoms - deep smooth "
          "counterpart (round-59/60 verbatim); m = G + tail_A")
    print("    bookkeeping B: tail_B = deep atoms ONLY (smooth "
          "parts cancel in m = e_ar + E_at); m = head_B + tail_B")
    print("    kz   h    m_h        n_min  tailA@cmin  tailA@9   "
          " tailB@9    headB@9   n_minB  tailB@cB")
    kA_c = kA_9 = kB_cB = kB_9 = 0
    nB_min, uB_min, hB_cut = [], [], []
    for r, nm, i9 in zip(rungs, n_min, i9s):
        ic = int(np.argmax(r["cert_A"] > 0))
        tAc = float(r["tail_A"][ic])
        tA9 = float(r["tail_A"][i9])
        tB9 = float(r["tail_B"][i9])
        hB9 = float(r["head_B"][i9])
        nn = np.round(np.exp(r["uu"])).astype(int)
        covB = r["cert_B"] > 0.0
        if bool(np.any(covB)):
            icB = int(np.argmax(covB))
            nB_min.append(int(nn[icB]))
            uB_min.append(float(r["uu"][icB]))
            hB_cut.append(float(r["head_B"][icB]))
            tBc = float(r["tail_B"][icB])
        else:
            nB_min.append(-1)
            uB_min.append(float("nan"))
            hB_cut.append(float("nan"))
            tBc = float("nan")
        kA_c += tAc <= 0
        kA_9 += tA9 <= 0
        kB_cB += (tBc <= 0) if np.isfinite(tBc) else 0
        kB_9 += tB9 <= 0
        print("    %-4d %-4d %.3e  %-6d %+.3e  %+.3e  %+.3e  "
              "%+.3f    %-7d %+.3e"
              % (r["kz"], r["h"], r["m"], nm, tAc, tA9, tB9,
                 hB9, nB_min[-1], tBc), flush=True)
    n_covB = sum(1 for n in nB_min if n > 0)
    ha = ("NET-A(%d/%d@cmin|%d/%d@9) + NET-B(%d/%d@cB|%d/%d@9)"
          % (kA_c, N, kA_9, N, kB_cB, N, kB_9, N))
    print("\n    B-covering schedule: cert_B > 0 cuts exist on "
          "%d/%d; n_minB med %d (%d..%d)"
          % (n_covB, N,
             int(np.median([n for n in nB_min if n > 0])),
             min(n for n in nB_min if n > 0),
             max(n for n in nB_min if n > 0)))
    check("Ha.1 typed (a): %s (definitions pinned above; both "
          "splits warded to m exactly; the atom-only bookkeeping "
          "has its OWN schedule)" % ha, True)

    # ------------------------------------------------------------ Hb
    section("Hb -- POINTWISE: exact knot census of q_v beyond the "
            "cut")
    u9 = math.log(NC_SHARED)
    cen_v, cen_v_cmin, cen_v_cB = [], [], []
    at_pos = []
    for r, um, umB, i9 in zip(rungs, u_min, uB_min, i9s):
        c9 = knot_census(r["Wv"], r["D"], r["M"], r["alpha"], u9)
        cm = knot_census(r["Wv"], r["D"], r["M"], r["alpha"], um)
        cB = knot_census(r["Wv"], r["D"], r["M"], r["alpha"],
                         umB)
        cen_v.append(c9)
        cen_v_cmin.append(cm)
        cen_v_cB.append(cB)
        qan = q_read(r["Wv"], r["uu"], r["D"], r["M"])
        deep = r["uu"] > u9
        pos = deep & (qan > 0.0)
        Ppos = float(np.sum((r["qa"])[pos]))
        at_pos.append((int(np.sum(pos)), Ppos,
                       abs(float(r["tail_B"][i9]))))
    n_pw9 = sum(1 for c in cen_v if c["sup_deep"] <= 0.0)
    n_pwc = sum(1 for c in cen_v_cmin if c["sup_deep"] <= 0.0)
    n_pwB = sum(1 for c in cen_v_cB if c["sup_deep"] <= 0.0)
    sup_rel = np.array([c["sup_rel"] for c in cen_v])
    posf = np.array([c["pos_frac"] for c in cen_v])
    ndc = np.array([c["n_deep_cross"] for c in cen_v])
    print("    beyond log %d: sup q_deep <= 0 on %d/%d rungs; "
          "sup rel to max|q| med %.3f (%.3f..%.3f); positive "
          "knot share med %.3f; deep sign changes %d..%d"
          % (NC_SHARED, n_pw9, N, float(np.median(sup_rel)),
             float(np.min(sup_rel)), float(np.max(sup_rel)),
             float(np.median(posf)), int(ndc.min()),
             int(ndc.max())))
    print("    beyond the per-rung u_min (A): sup q_deep <= 0 on "
          "%d/%d rungs; beyond the per-rung u_minB (B): %d/%d"
          % (n_pwc, N, n_pwB, N))
    npos_at = np.array([a[0] for a in at_pos])
    ratP = np.array([a[1] / max(a[2], 1e-30) for a in at_pos])
    print("    atom census beyond n = %d: positive-weight atoms "
          "med %d (%d..%d); positive contribution P = sum mu q^+ "
          "= %.3f..%.3f of |tail_B(9)| (med %.3f)"
          % (NC_SHARED, int(np.median(npos_at)),
             int(npos_at.min()), int(npos_at.max()),
             float(np.min(ratP)), float(np.max(ratP)),
             float(np.median(ratP))))
    if n_pw9 == N:
        hb = "POINTWISE-V(%d/%d)" % (n_pw9, N)
    else:
        hb = ("POINTWISE-FAIL-V(%d/%d, sup med %.2f max|q|, "
              "pos share med %.2f)"
              % (n_pw9, N, float(np.median(sup_rel)),
                 float(np.median(posf))))
    check("Hb.1 typed (b): %s (exact: sup over a piecewise-linear "
          "weight is attained at a knot or the cut point)" % hb,
          True)

    # ------------------------------------------------------------ Hc
    section("Hc -- CLASSICAL: the same census for the prime-free "
            "q_{v_sm}")
    cen_s, cen_s_cB, cen_car = [], [], []
    for r, umB in zip(rungs, uB_min):
        cs = knot_census(r["Wsm"], r["D"], r["M"], r["alpha"], u9)
        cen_s.append(cs)
        cen_s_cB.append(knot_census(r["Wsm"], r["D"], r["M"],
                                    r["alpha"], umB))
        if r["ov"] < OV_MIN:
            cen_car.append((r["kz"], knot_census(
                r["Wcar"], r["D"], r["M"], r["alpha"], u9)))
    n_sm9 = sum(1 for c in cen_s if c["sup_deep"] <= 0.0)
    n_smB = sum(1 for c in cen_s_cB if c["sup_deep"] <= 0.0)
    sup_s = np.array([c["sup_rel"] for c in cen_s])
    print("    beyond log %d: sup q_sm <= 0 on %d/%d rungs; sup "
          "rel med %.3f (%.3f..%.3f); beyond u_minB: %d/%d"
          % (NC_SHARED, n_sm9, N, float(np.median(sup_s)),
             float(np.min(sup_s)), float(np.max(sup_s)), n_smB,
             N))
    for kzc, cc in cen_car:
        print("    crossing rung kz %d read on its carrier "
              "branch: sup rel %.3f, u_last %.3f, end sign %+d"
              % (kzc, cc["sup_rel"], cc["u_last"],
                 int(cc["end_sign"])))
    # u_last agreement + law (crossing rungs read on the carrier)
    ul_v = np.array([c["u_last"] for c in cen_v])
    ul_s = np.array([c["u_last"] for c in cen_s])
    for i, r in enumerate(rungs):
        if r["ov"] < OV_MIN:
            cc = dict(cen_car)[r["kz"]]
            ul_s[i] = cc["u_last"]
    okl = np.isfinite(ul_v) & np.isfinite(ul_s)
    co_ul = corr(ul_v[okl], ul_s[okl])
    dmed = float(np.median(np.abs(ul_v[okl] - ul_s[okl])))
    aa = np.array([r["alpha"] for r in rungs])
    sl_l, se_l, r2_l = jack_slope(aa[okl], (ul_s / aa)[okl])
    ustar = (NODE_C + NODE_S * aa) * aa
    co_node = corr(ul_s[okl], ustar[okl])
    x_last = ul_s[okl] / aa[okl]
    print("    u_last agreement v vs v_sm: corr %+.3f, med "
          "|Delta| %.1e; law u_last/alpha = %+.4f alpha + c "
          "(2SE %.4f, R^2 %.2f); med u_last/alpha %.3f vs node "
          "law med %.3f vs log%d/alpha med %.3f; corr(u_last, "
          "u*) = %+.3f; terminal sign negative on %d/%d (v) / "
          "%d/%d (v_sm)"
          % (co_ul, dmed, sl_l, 2 * se_l, r2_l,
             float(np.median(x_last)),
             float(np.median(NODE_C + NODE_S * aa)),
             NC_SHARED, float(np.median(u9 / aa)), co_node,
             sum(1 for c in cen_v if c["end_sign"] < 0), N,
             sum(1 for c in cen_s if c["end_sign"] < 0), N))
    agree = sum(1 for cv, cs in zip(cen_v, cen_s)
                if (cv["sup_deep"] <= 0) == (cs["sup_deep"] <= 0))
    if n_sm9 == N:
        hc = "CLASSICAL-NEG(%d/%d)" % (n_sm9, N)
    else:
        hc = ("CLASSICAL-CENSUS(%d/%d neg, sign-agreement with v "
              "%d/%d, corr(u_last) %+.2f)"
              % (n_sm9, N, agree, N, co_ul))
    check("Hc.1 typed (c): %s -- the weight geometry (deep sign "
          "pattern + last sign change) is a property of the "
          "PRIME-FREE smooth model" % hc, True)

    # ------------------------------------------------------------ Hd
    section("Hd -- THE HEAD FLOOR (tau-screen, decisive; typed "
            "at the per-rung first B-covering cut)")
    mm = np.array([r["m"] for r in rungs])
    hB9 = np.array([float(r["head_B"][i9])
                    for r, i9 in zip(rungs, i9s)])
    G9 = np.array([float(r["G"][i9])
                   for r, i9 in zip(rungs, i9s)])
    n_hpos = int(np.sum(hB9 > 0))
    slG, seG, r2G = jack_slope(np.log(mm[G9 > 0]),
                               np.log(G9[G9 > 0]))
    okB = np.array([n > 0 for n in nB_min])
    hBc = np.array(hB_cut)
    slC, seC, r2C = jack_slope(np.log(mm[okB]), np.log(hBc[okB]))
    print("    head_B(cB) = e_ar + sum_{n <= cB} mu_n q_v(u_n) "
          "at the first B-covering cut (covers %d/%d, n_minB med "
          "%d): med %.3f, min %.3f, max %.3f; head_B(cB)/m med "
          "%.1f; |tail_B(cB)| = head_B - m, med %.3f"
          % (int(np.sum(okB)), N,
             int(np.median(np.array(nB_min)[okB])),
             float(np.median(hBc[okB])), float(np.min(hBc[okB])),
             float(np.max(hBc[okB])),
             float(np.median(hBc[okB] / mm[okB])),
             float(np.median(hBc[okB] - mm[okB]))))
    print("    TYPED tau-screen log head_B(cB) vs log m: slope "
          "%+.3f +- 2SE %.3f (R^2 %.2f)"
          % (slC, 2 * seC, r2C))
    print("    context screens: G(9) slope %+.3f +- %.3f (R^2 "
          "%.2f, > 0 on %d/%d); head_B(9) med %.3f, > 0 on only "
          "%d/%d (the shared cut 9 belongs to bookkeeping A's "
          "schedule)"
          % (slG, 2 * seG, r2G, int(np.sum(G9 > 0)), N,
             float(np.median(hB9)), n_hpos, N))
    # shared single B-cut search (info)
    grid_n = np.unique(np.concatenate(
        [np.round(np.exp(r["uu"])).astype(int) for r in rungs]))
    grid_n = grid_n[grid_n <= CAP_SHARED]
    covmat = np.zeros((N, len(grid_n)), int)
    for i, r in enumerate(rungs):
        pos = np.searchsorted(r["uu"],
                              np.log(grid_n.astype(float))
                              + 1e-12, side="right") - 1
        okp = pos >= 0
        covmat[i, okp] = (r["cert_B"][pos[okp]] > 0.0)
    cov_cnt = covmat.sum(axis=0)
    jb = int(np.argmax(cov_cnt))
    print("    shared single B-cut search (candidates <= %d): "
          "best n = %d covers %d/%d"
          % (CAP_SHARED, int(grid_n[jb]), int(cov_cnt[jb]), N))
    if abs(slC) <= SLOPE_PASS:
        hd = "HEADFLOOR-O1(slope=%+.3f)" % slC
        print("    ==> O(1): the ENTIRE h-decay of the wall "
              "margin lives in the (sign-measured) atom tail "
              "tail_B(cB) = m - head_B(cB); the open arithmetic "
              "statement tail_B > -head_B is an inequality "
              "between two O(1) quantities whose gap IS m_h")
    elif slC >= SLOPE_RELOC:
        hd = "HEADFLOOR-RELOC(slope=%+.3f)" % slC
        print("    ==> RELOCATION: the head margin tracks tau -- "
              "the hardness moved into the finite head; recorded "
              "honestly")
    else:
        hd = "HEADFLOOR-AMBIG(slope=%+.3f)" % slC
    check("Hd.1 typed (d): %s + SCHED-B(n=%d, %d/%d) (bands PASS "
          "|s| <= %.2f, RELOC s >= %.2f)"
          % (hd, int(grid_n[jb]), int(cov_cnt[jb]), N,
             SLOPE_PASS, SLOPE_RELOC), True)

    # ------------------------------------------------------------ He
    section("He -- THE UNIFORMITY BOUNDARY (named)")
    print("    h-dependence of the certificate pieces: the weight "
          "q depends on h through the DIRECTION (v arithmetic; "
          "v_sm prime-free) and the WINDOW (2 alpha(h), lag pitch "
          "D(h)); the head through e_ar(h) and the h-dependent "
          "weights of the 7 fixed atoms.")
    if n_pw9 == N:
        marg = -sup_rel
        slM, seM, r2M = jack_slope(aa, marg)
        he = ("UNIF-STABLE(min=%.3f)" % float(np.min(marg))
              if float(np.min(marg)) >= MARGIN_MIN else
              "UNIF-MARGINAL(min=%.3f)" % float(np.min(marg)))
        print("    deep-sign margin -sup q_deep / max|q|: med "
              "%.3f, min %.3f; trend vs alpha %+.4f +- %.4f "
              "(R^2 %.2f)"
              % (float(np.median(marg)), float(np.min(marg)),
                 slM, 2 * seM, r2M))
    else:
        n_endneg = sum(1 for c in cen_v if c["end_sign"] < 0)
        if n_endneg == N:
            x_pw = np.array([c["u_last"] for c in cen_v]) \
                / (2.0 * aa)
            n_head = np.array([int(np.sum(
                r["uu"] <= c["u_last"] + 1e-12))
                for r, c in zip(rungs, cen_v)])
            slP, seP, r2P = jack_slope(
                np.log(np.exp(2.0 * aa)),
                np.log(np.maximum(n_head, 1)))
            he = ("UNIF-CUTGROWTH(x_pw med %.3f, head atoms med "
                  "%d ~ X^%.2f)"
                  % (float(np.median(x_pw)),
                     int(np.median(n_head)), slP))
            print("    pointwise negativity fails at n = %d but "
                  "the TERMINAL lobe is negative on %d/%d: a "
                  "per-rung pointwise-valid cut exists at u_pw = "
                  "u_last, scaled x_pw = u_pw/(2 alpha) med %.3f "
                  "(%.3f..%.3f); enlarged head atom count med %d "
                  "(%d..%d), growth ~ X^%.2f +- %.2f (R^2 %.2f) "
                  "-- the pointwise mechanism is restorable ONLY "
                  "at a head growing with X, not uniformly finite"
                  % (NC_SHARED, n_endneg, N,
                     float(np.median(x_pw)), float(np.min(x_pw)),
                     float(np.max(x_pw)), int(np.median(n_head)),
                     int(np.min(n_head)), int(np.max(n_head)),
                     slP, 2 * seP, r2P))
        else:
            he = ("UNIF-TERMINAL-POS(%d/%d end positive)"
                  % (N - n_endneg, N))
            xon = np.array([c["u_last"] for c in cen_v]) \
                / (2.0 * aa)
            xon = xon[np.isfinite(xon)]
            print("    the terminal weight lobe is POSITIVE on "
                  "%d/%d rungs -- NO enlarged cut restores "
                  "pointwise negativity; the mechanism is "
                  "NET-only there.  Terminal-lobe onset u_last/"
                  "(2 alpha) med %.3f (%.3f..%.3f): the positive "
                  "lobe occupies the deepest ~%.0f%% of the "
                  "window at every h -- the u-region repair "
                  "(probe 2 object) must name it"
                  % (N - n_endneg, N, float(np.median(xon)),
                     float(np.min(xon)), float(np.max(xon)),
                     100.0 * (1.0 - float(np.median(xon)))))
    check("He.1 typed (e): %s" % he, True)

    # ------------------------------------------------------------ C
    section("C -- controls on this surface at kz %d" % CTRL_KZ)
    rr9 = core.build_window(CTRL_KZ)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE_ = lambda_eps(N_E)
    nnE = np.nonzero(np.abs(lamE_) > 1e-12)[0]
    ctl = {}
    ctl["Epstein"] = build_rung(CTRL_KZ, comb=(
        np.log(nnE.astype(float)),
        2.0 * lamE_[nnE] / np.sqrt(nnE.astype(float))),
        need_sm=False)
    ctl["scramble"] = build_rung(CTRL_KZ, scramble_seed=1,
                                 need_sm=False)
    ctl["smooth"] = build_rung(CTRL_KZ, smooth_world=True,
                               need_sm=False)
    fired = True
    for name, r in ctl.items():
        if r is None:
            print("    %-9s: rung dies -> fires" % name)
            continue
        ncovA = int(np.sum(r["cert_A"] > 0))
        ncovB = int(np.sum(r["cert_B"] > 0))
        f = (r["m"] < 0) and ncovA == 0 and ncovB == 0
        fired &= f
        print("    %-9s: m %+.3e  lift %+.3e  covering cuts "
              "A/B %d/%d -> %s"
              % (name, r["m"], r["lift"], ncovA, ncovB,
                 "FIRES" if f else "SILENT"), flush=True)
    print("    truth |lift| med %.3f (smooth failure = lift "
          "collapse, a DIFFERENT anatomy, recorded)"
          % float(np.median([abs(r["lift"]) for r in rungs])))
    check("C1 WARD all three controls fire (m < 0 and zero "
          "coverage in BOTH senses)", fired, kill="K2")

    # mechanism verdict (frozen precedence, decided at the
    # per-rung first B-covering cut cB(h))
    if n_pwB == N and n_smB == N:
        mech = "MECH-CLASSICAL-POINTWISE"
    elif n_pwB == N:
        mech = "MECH-POINTWISE-V"
    elif kB_cB == N:
        mech = ("MECH-NET-ONLY(B-net %d/%d@cB, pointwise %d/%d"
                "@cB)" % (kB_cB, N, n_pwB, N))
    else:
        mech = ("MECH-MIXED(B-net %d/%d@cB, pointwise %d/%d@cB)"
                % (kB_cB, N, n_pwB, N))

    return finish(dict(ha=ha, hb=hb, hc=hc, hd=hd, he=he,
                       mech=mech))


def finish(labels):
    section("V -- FROZEN VERDICT")
    n_pass = sum(1 for _n, okk in CHECKS if okk)
    n_tot = len(CHECKS)
    if KILLS:
        VERDICT = {"K1": "PIPELINE-BROKEN",
                   "K2": "WARD-BROKEN"}[KILLS[0]]
        print("\n  VERDICT: %s" % VERDICT)
    else:
        VERDICT = ("TAILSIGN-MEASURED / %(ha)s / %(hb)s / %(hc)s "
                   "/ %(mech)s / %(hd)s / %(he)s" % labels)
        print("\n  VERDICT: %s" % VERDICT)
    print("""
  HONEST FRAME (as frozen): the tail sign and the head floor are
  MEASURED SURFACE STRUCTURE.  A deterministic tail sign (where it
  holds) converts the round-59 two-sided tail-accuracy demand into
  the one-sided lower bound tail_B > -head_B -- it does NOT prove
  it; the one-sided statement remains the open arithmetic content
  at every depth.  A NET-only sign is an arithmetic cancellation
  fact, not a weight-sign fact.  NO RH claim.  No marker moves.""")
    print("\n[TIME] %.1f s   [CHECKS] %d run, %d failed"
          % (time.time() - T0, n_tot, n_tot - n_pass))
    return 0 if n_pass == n_tot else 1


if __name__ == "__main__":
    raise SystemExit(main())
'''

# ------------- frozen probe source tail_sign_repair_probe (embedded BYTE-EXACT, raw string)
_SRC_1 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""tail_sign_repair_probe -- PRIME.PORT.TAILSIGN.02
(EXPLORATION ONLY, experiments/; round 62, theorem-engineering on
the RH-side wall; TRIGGERED successor of tail_sign_mechanism_probe
(PRIME.PORT.TAILSIGN.01), whose levels (b) POINTWISE and (c)
CLASSICAL-POINTWISE both FAILED: sup_{u > cut} q > 0 on 67/67 at
every cut (shared 9, per-rung A-cut, per-rung B-cut), positive
knot share med 0.65, terminal lobe POSITIVE on 67/67 with onset
u_last/(2 alpha) med 0.752.  THE QUESTION: where EXACTLY does
pointwise negativity fail (u-region geography, atom census,
magnitude), does a SMALL EXPLICIT set of exceptional atoms carry
all deep positivity (then the head can be enlarged by finitely
many NAMED atoms), what is the MINIMAL enlargement that restores
the deterministic-sign mechanism, and what do the head-floor
tau-screen (d) and the uniformity boundary (e) look like for the
enlarged head.  2026-08-10.)

THE ENLARGED BOOKKEEPING (frozen; exact, warded).  Probe-1
bookkeeping B at the per-rung first B-covering cut cB(h):
m = head_B(cB) + tail_B(cB), tail_B = sum of DEEP atom reads
mu_n q_v(u_n).  The deep positive REGION R+ = {u > u_cB : q_v(u)
> 0} is a finite union of intervals (q_v is piecewise linear on
the lag knots; interval endpoints exact).  Enlarged head:
    head2 = head_B(cB) + sum_{u_n in R+} mu_n q_v(u_n),
    tail2 = sum_{u_n > u_cB, u_n not in R+} mu_n q_v(u_n),
    m = head2 + tail2 EXACTLY (warded), and tail2 <= 0 holds
    DETERMINISTICALLY for ANY nonnegative comb (every remaining
    tail atom sits where the weight is <= 0) -- R+ is WEIGHT
    geometry (classical per probe 1's (c)), not comb data.
cert2 = head2 - |tail2| = m exactly when tail2 <= 0 (same algebra
as rounds 60/62).  The REPAIR PRICE is head2's atom support: the
atoms inside R+.  If R+ reaches the window edge (probe-1 terminal
lobe), that support contains every atom with u_n > u_term -- a
POSITIVE SHARE of all atoms by count -- and the repair is NOT
uniformly finite; measured, not assumed.

WHAT IS MEASURED (frozen; typed, never kills):
 (1) FAILURE GEOGRAPHY: per rung, the positive intervals of q_v
     beyond u_cB: count, endpoints in the scaled variable
     u/(2 alpha), the terminal-lobe onset law (jackknife vs
     alpha), and the mass anatomy: atom count N+, von-Mangoldt
     mass share, positive contribution P+ = sum_{R+} mu_n q^+,
     split terminal lobe vs interior lobes.  CLASSICAL cross-
     check: same intervals from q_{v_sm} (prime-free): interval-
     count agreement share, terminal-onset |Delta| med (kz 97 on
     its carrier branch, disclosed).  Typed FAILGEO(int med,
     terminal share of P+).
 (2) THE EXCEPTIONAL-SET CENSUS: concentration of P+ across
     atoms: per rung the minimal k for 50/90/99% of P+ (sorted
     contributions), the top-N_TOP named atoms (deployed values,
     integer-root prime-power labels), and the STABILITY of the
     named set across the ladder (share of rungs whose top-1
     atom value repeats; union size of the top-k90 sets).  Typed
     SET-SMALL(k90max) iff k90 <= K_SMALL on every rung AND the
     union of top-k90 atom VALUES across rungs has size <=
     K_UNION (a finite NAMED set carries the positivity), else
     SET-DIFFUSE(k90 med, union size).
 (3) THE MINIMAL ENLARGEMENT + (d)/(e) RE-RUN: the atomwise
     repair must absorb ALL of R+ (every positive-weight deep
     atom individually breaks tail2 <= 0 for some nonnegative
     comb); its price N+ vs X: jackknife slope of log N+ vs
     log X (typed REPAIR-FINITE iff slope <= GROW_BAR, else
     REPAIR-GROWING(X^s)); the share N+ / N_deep.  (d) re-run:
     head2 med/min/max, jackknife slope of log head2 vs log m --
     bands PASS |s| <= 0.30 (HEADFLOOR2-O1) / RELOC s >= 0.70 /
     else AMBIG; |tail2| = head2 - m likewise.  (e) named: the
     enlarged head is explicit but its support grows with the
     window; the deterministic-sign statement it buys (tail2 <=
     0) holds for any nonnegative comb, while head2 > |tail2|
     (equivalently head2 > -tail2, gap m) remains the open
     arithmetic content -- now carried by an O(?) head measured
     here.

FROZEN PROTOCOL (pipeline verbatim from
tail_sign_mechanism_probe; ladder, wards and cut conventions
identical):

 W   LADDER + WARDS (kill -> PIPELINE-BROKEN / WARD-BROKEN): W1
     faithful ladder >= MIN_RUNGS = 40; W2 WARD m_h > 0; W3 WARD
     exact bookkeepings (lift - demand = m, e_ar + E_at = m, rel
     <= ID_WARD); W4 REPRODUCTION of probe-1 headline facts:
     B-covering cuts exist on N/N with n_minB med in [NB_LO,
     NB_HI]; pointwise fails beyond u_cB on 0/N; terminal sign
     positive on N/N; W5 WARD enlarged split exactness: |head2 +
     tail2 - m| rel <= ID_WARD on every rung AND tail2 <= 0 on
     every rung (construction: only q <= 0 atoms remain) AND
     cert2 = m to ID_WARD (the tail2 <= 0 algebra).

 H   H1 FAILURE GEOGRAPHY; H2 EXCEPTIONAL-SET CENSUS; H3 MINIMAL
     ENLARGEMENT + (d)/(e) RE-RUN (typed as frozen above).

 C   CONTROLS (kill -> WARD-BROKEN if silent): scramble (seed 1)
     and smooth comb at kz 9: m < 0 AND cert2 < 0 at every cut
     (tail2 <= 0 still holds by construction -- the repair
     cannot manufacture a certificate without the wall, cert2 =
     m exactly); Epstein x^2+5y^2 at kz 9: m < 0 AND cert2 < 0
     at every cut, with the DECLARED different anatomy recorded:
     the Epstein comb has NEGATIVE masses, so the nonnegative-
     comb premise of the deterministic tail sign does not even
     apply there (tail2 <= 0 is checked as measured fact, not
     construction).

KILLS: K1 ladder (W1) -> PIPELINE-BROKEN; K2 wards (W2-W5, C) ->
WARD-BROKEN.  All H-typed outcomes are measurements, never kills.

VERDICT (frozen enum): TAILREPAIR-MEASURED with typed sublabels
FAILGEO(int med, term share), SET-SMALL(kmax)/SET-DIFFUSE(k90,
union), REPAIR-FINITE(slope)/REPAIR-GROWING(X^slope),
HEADFLOOR2-O1/RELOC/AMBIG(slope); else PIPELINE-BROKEN /
WARD-BROKEN.

FROZEN BARS: KZMAX = 150; MIN_RUNGS = 40; NB_LO, NB_HI = 5, 47
(probe-1 measured n_minB band, med-ward: med in band); ID_WARD =
1e-10; NG_SMOOTH = 6000; OV_MIN = 0.8; MAX_CROSS = 2; K_SMALL =
16; K_UNION = 32; N_TOP = 8; GROW_BAR = 0.10; SLOPE_PASS = 0.30;
SLOPE_RELOC = 0.70; CTRL_KZ = 9; scramble seed 1; jackknife =
full leave-one-out, CI = +- 2SE; interval endpoints from exact
knot crossings (piecewise-linear interpolation, no tolerance).

SMOKE-RUN DISCLOSURE (2026-08-10, before freezing): ONE smoke run
(10/10, 17.6 s) on SPEC v0; NO code, bar, band, count, enum or
typed rule was changed after the smoke (the freeze adds only this
disclosure).  Smoke facts frozen as the context the frozen run
must confirm: (1) FAILGEO: 2 positive intervals med (2..3);
terminal-lobe onset u/(2 alpha) med 0.752 and FLAT vs alpha
(slope +0.0026 +- 0.0151, R^2 0.00) -- a stable scaled position;
terminal lobe carries med 0.46 of P+; classical cross-check:
interval-count agreement 66/67, terminal-onset |Delta| med 0.335;
(2) SET-DIFFUSE: k90 med 646 (max 7711), top-k90 union 10649 --
NO small named set; the largest individual positive atoms are the
primes just beyond the cut (mid-ladder: 19, 23, 29, 31, 37, 41,
43, 47); (3) REPAIR-GROWING: N+ med 1969 ~ X^0.890 +- 0.007 (R^2
1.00), med 0.89 of ALL deep atoms; head2 med 17.3 (2.8..65.1) and
ANTI-tau (slope of log head2 vs log m = -0.395 +- 0.072, R^2
0.62 = HEADFLOOR2-AMBIG: the enlarged head GROWS as the margin
shrinks); controls all fire (cert2 = m < 0 at every cut; Epstein
negative-mass anatomy disclosed, tail2 <= 0 there measured, not
construction).

SPEC v1 (2026-08-10, frozen + SHA-hashed before the frozen run):
everything above.  Mechanical concretizations: (i) R+ intervals built from the knot
sign pattern beyond u_cB, clipped at u_cB and at the window edge
2 alpha; an interval is TERMINAL iff its right endpoint is the
window edge; (ii) atom membership u_n in R+ decided by q_v(u_n)
> 0 (equivalent for atoms, exact); (iii) concentration ranks by
the atom contribution mu_n q_v(u_n) descending; (iv) the v_sm
cross-check reads the crossing rung (|<v, v_sm>| < OV_MIN) on
its carrier branch among the 4 lowest smooth branches
(disclosed); (v) X = e^{2 alpha}.

NO-GO COMPLIANCE (frozen): no certified-bound retry, no rank-1
approximation, no Herglotz; identities are exact wards, laws are
typed trends with jackknife error bars.

NO RH claim: the enlarged head restores a deterministic tail
sign at a measured price; the one-sided bound head2 > |tail2|
remains the open arithmetic content at every depth, and nothing
here bounds it.  No marker moves.

FIREWALL: no zeros, no prime oracles (AST scan; banned ids
zetazero / nzeros / primerange / isprime / primepi / nextprime /
prevprime); v563 READ-ONLY; RNG only inside the declared
scramble control; stdout only.

Sources (read-only): v563_paper2_readouts; machinery verbatim
from tail_sign_mechanism_probe.py (round 62, PRIME.PORT.
TAILSIGN.01) and wall_cut_schedule_probe.py (round 60); probe-1
headline facts as declared reproduction targets.

Run:
    experiments/tfpt-discovery/.venv/bin/python \
        experiments/tfpt-discovery/tail_sign_repair_probe.py
"""

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

import numpy as np

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

import v563_paper2_readouts as core        # noqa: E402  (READ-ONLY)

KZMAX = 150
MIN_RUNGS = 40
NB_LO, NB_HI = 5, 47
ID_WARD = 1e-10
NG_SMOOTH = 6000
OV_MIN = 0.8
MAX_CROSS = 2
K_SMALL = 16
K_UNION = 32
N_TOP = 8
GROW_BAR = 0.10
SLOPE_PASS = 0.30
SLOPE_RELOC = 0.70
CTRL_KZ = 9
BANNED_IDS = ("zetazero", "nzeros", "primerange", "isprime",
              "primepi", "nextprime", "prevprime")

CHECKS = []
KILLS = []
T0 = time.time()


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


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


def ast_scan(banned):
    src = open(os.path.abspath(__file__), encoding="utf-8").read()
    bad = []
    for node in ast.walk(ast.parse(src)):
        name = None
        if isinstance(node, ast.Name):
            name = node.id
        elif isinstance(node, ast.Attribute):
            name = node.attr
        if name and name.lower() in banned:
            bad.append(name)
    return bad


def ols_line(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    vx = float(np.var(x))
    if vx == 0.0:
        return float(np.mean(y)), 0.0, float("nan")
    b = float(np.cov(x, y, bias=True)[0, 1] / vx)
    a = float(np.mean(y) - b * np.mean(x))
    ss = float(np.sum((y - a - b * x) ** 2))
    st = float(np.sum((y - np.mean(y)) ** 2))
    return a, b, (1.0 - ss / st if st > 0 else float("nan"))


def jack_slope(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    _a, b, r2 = ols_line(x, y)
    n = len(x)
    bb = []
    for i in range(n):
        m = np.ones(n, bool)
        m[i] = False
        bb.append(ols_line(x[m], y[m])[1])
    bb = np.array(bb)
    se = math.sqrt((n - 1) / n * float(np.sum((bb - bb.mean())
                                              ** 2)))
    return b, se, r2


def q_read(W, u, D, M):
    u = np.asarray(u, float)
    i0 = np.floor(u / D).astype(int)
    f = u / D - i0
    val = np.zeros_like(u)
    ok0 = (i0 >= 0) & (i0 < M)
    val[ok0] += (1.0 - f[ok0]) * W[i0[ok0]]
    ok1 = (i0 + 1 >= 0) & (i0 + 1 < M)
    val[ok1] += f[ok1] * W[i0[ok1] + 1]
    refl = u < D
    val[refl] += (1.0 - u[refl] / D) * W[0]
    return -0.5 * val


def smooth_comb(alpha, ng=NG_SMOOTH):
    ug = (np.arange(ng) + 0.5) * (2.0 * alpha / ng)
    mg = 2.0 * np.exp(ug / 2.0) * (2.0 * alpha / ng)
    return ug, mg


def lambda_eps(N):
    r = np.zeros(N + 1)
    s = int(math.isqrt(N)) + 1
    for x in range(-s, s + 1):
        for y in range(-s, s + 1):
            v = x * x + 5 * y * y
            if 1 <= v <= N:
                r[v] += 1.0
    a = r / 2.0
    lam = np.zeros(N + 1)
    for n in range(2, N + 1):
        acc = a[n] * math.log(n)
        for dd in range(2, n):
            if n % dd == 0:
                acc -= lam[dd] * a[n // dd]
        lam[n] = acc
    return lam


def pp_label(n):
    """Prime-power structure of a deployed atom value by integer
    roots (no primality oracle; the table IS the comb)."""
    for k in range(int(math.log2(max(n, 2))), 1, -1):
        b = int(round(n ** (1.0 / k)))
        for bb in (b - 1, b, b + 1):
            if bb >= 2 and bb ** k == n:
                return "%d^%d" % (bb, k)
    return "%d" % n


def pos_intervals(W, D, M, u_cut):
    """Positive intervals of the piecewise-linear weight beyond
    u_cut, from the exact knot sign pattern (crossings by linear
    interpolation), clipped at u_cut and the window edge M*D."""
    uk = np.arange(M + 1) * D
    ue = uk.copy()
    ue[0] = 1e-12
    qk = q_read(W, ue, D, M)
    # boundary points: crossings + cut + edge
    pts = [u_cut]
    for i in np.nonzero(qk[:-1] * qk[1:] < 0.0)[0]:
        uc = uk[i] + D * qk[i] / (qk[i] - qk[i + 1])
        if uc > u_cut:
            pts.append(float(uc))
    pts.append(float(M * D))
    pts = sorted(set(pts))
    out = []
    for a, b in zip(pts[:-1], pts[1:]):
        if b <= a:
            continue
        um = 0.5 * (a + b)
        if float(q_read(W, np.array([um]), D, M)[0]) > 0.0:
            out.append((a, b, b >= M * D - 1e-12))
    return out


def build_rung(kz, comb=None, scramble_seed=None,
               smooth_world=False, need_sm=True):
    """One rung: lift-race surface, both bookkeepings, first
    B-covering cut, enlarged split (verbatim probe-1 machinery +
    the R+ enlargement)."""
    try:
        rr = core.build_window(kz, scramble_seed=scramble_seed)
    except Exception:
        return None
    if not (core.H_MIN <= rr["h"] <= core.HCAP):
        return None
    if rr["X"] > core.ATOM_MAX:
        return None
    alpha, M, D, h = rr["alpha"], rr["M"], rr["D"], rr["h"]
    uu = np.asarray(rr["uu"], float)
    mu = 2.0 * np.asarray(rr["lam"], float)
    if smooth_world:
        du = np.zeros(len(uu))
        du[1:-1] = 0.5 * (uu[2:] - uu[:-2])
        du[0] = uu[1] - uu[0]
        du[-1] = uu[-1] - uu[-2]
        mu = 2.0 * np.exp(uu / 2.0) * du
    if comb is not None:
        uu, mu = comb
    c_at = core.atom_lags_at(alpha, M, uu, mu)[0]
    c_ar = np.asarray(core.arch_lags(M, D), float)
    w, V = np.linalg.eigh(core.odd_toeplitz(c_ar + c_at, M))
    v = V[:, 0]
    ug, mg = smooth_comb(alpha)
    c_sm = core.atom_lags_at(alpha, M, ug, mg)[0]
    Wv = core.lag_weights_from_v(v, h)
    e_ar = float(c_ar @ Wv)
    e_t = float(c_at @ Wv)
    e_s = float(c_sm @ Wv)
    qan = q_read(Wv, uu, D, M)
    qa = mu * qan
    row = dict(kz=kz, alpha=float(alpha), h=h, M=M, D=D,
               m=float(w[0]), uu=uu, mu=mu, e_ar=e_ar, e_t=e_t,
               lift=e_t - e_s, demand=-(e_ar + e_s), qa=qa,
               qan=qan, Wv=Wv)
    cq = np.cumsum(qa)
    head_B = e_ar + cq
    tail_B = float(qa.sum()) - cq
    cert_B = head_B - np.abs(tail_B)
    row.update(head_B=head_B, tail_B=tail_B, cert_B=cert_B)
    covB = cert_B > 0.0
    if bool(np.any(covB)):
        icB = int(np.argmax(covB))
        row["icB"] = icB
        row["n_minB"] = int(round(math.exp(uu[icB])))
        row["u_cB"] = float(uu[icB])
    else:
        row["icB"] = -1
        row["n_minB"] = -1
        row["u_cB"] = 0.0
    if need_sm:
        ws, Vs = np.linalg.eigh(core.odd_toeplitz(c_ar + c_sm, M))
        vsm = Vs[:, 0]
        if float(v @ vsm) < 0:
            vsm = -vsm
        ov4 = [abs(float(v @ Vs[:, j])) for j in range(4)]
        jcar = int(np.argmax(ov4))
        vcar = Vs[:, jcar] * (1.0 if float(v @ Vs[:, jcar]) >= 0
                              else -1.0)
        row.update(ov=float(abs(v @ vsm)), ov4=ov4, jcar=jcar,
                   Wsm=core.lag_weights_from_v(vsm, h),
                   Wcar=core.lag_weights_from_v(vcar, h))
    return row


def enlarged_split(row):
    """head2/tail2 at the first B-covering cut: absorb all
    positive-weight deep atoms into the head (atom membership by
    q_v(u_n) > 0, exact for atoms)."""
    icB = row["icB"]
    deep = np.arange(len(row["uu"])) > icB
    pos = deep & (row["qan"] > 0.0)
    neg = deep & ~ (row["qan"] > 0.0)
    P = float(np.sum(row["qa"][pos]))
    head2 = float(row["head_B"][icB]) + P
    tail2 = float(np.sum(row["qa"][neg]))
    return dict(pos=pos, neg=neg, P=P, head2=head2, tail2=tail2,
                Npos=int(np.sum(pos)), Ndeep=int(np.sum(deep)))


def main():
    section("PRIME.PORT.TAILSIGN.02 -- the repair of the "
            "pointwise tail-sign mechanism (EXPLORATION ONLY)")
    print("    FROZEN_SPEC SHA-256 = %s"
          % hashlib.sha256(__doc__.encode("utf-8")).hexdigest())
    print("    NO RH claim; no marker moves.")
    print("\nS0 -- firewall")
    check("S0.1 AST firewall clean", not ast_scan(BANNED_IDS))

    # ------------------------------------------------------------ W
    section("W -- the faithful ladder + wards")
    rungs = []
    for kz in range(2, KZMAX + 1):
        row = build_rung(kz)
        if row is not None:
            rungs.append(row)
    rungs.sort(key=lambda r: (r["h"], r["kz"]))
    check("W1 faithful ladder >= %d rungs" % MIN_RUNGS,
          len(rungs) >= MIN_RUNGS,
          "%d rungs, h %d..%d  [%.1f s]"
          % (len(rungs), rungs[0]["h"], rungs[-1]["h"],
             time.time() - T0), kill="K1")
    if KILLS:
        return finish({})
    N = len(rungs)
    check("W2 WARD truth margin m_h > 0 on every rung (min %.3e)"
          % min(r["m"] for r in rungs),
          all(r["m"] > 0 for r in rungs), kill="K2")
    dev_bk = max(max(abs((r["lift"] - r["demand"]) - r["m"]),
                     abs((r["e_ar"] + r["e_t"]) - r["m"]))
                 / max(1.0, abs(r["m"])) for r in rungs)
    check("W3 WARD exact bookkeepings (lift - demand = m, "
          "e_ar + E_at = m): max dev %.2e <= %.0e"
          % (dev_bk, ID_WARD), dev_bk <= ID_WARD, kill="K2")
    n_covB = sum(1 for r in rungs if r["icB"] >= 0)
    nB = [r["n_minB"] for r in rungs if r["icB"] >= 0]
    # probe-1 headline reproduction: pointwise fail + terminal +
    u9 = None
    n_pwB = 0
    n_endpos = 0
    IV = []
    for r in rungs:
        iv = pos_intervals(r["Wv"], r["D"], r["M"], r["u_cB"])
        IV.append(iv)
        if len(iv) == 0:
            n_pwB += 1
        if any(t for _a, _b, t in iv):
            n_endpos += 1
    ok_rep = (n_covB == N and NB_LO <= int(np.median(nB)) <= NB_HI
              and n_pwB == 0 and n_endpos == N)
    check("W4 REPRODUCTION probe-1 headline: B-covering cuts on "
          "%d/%d (n_minB med %d in [%d, %d]); pointwise holds "
          "beyond u_cB on %d/%d (must be 0); terminal lobe "
          "positive on %d/%d"
          % (n_covB, N, int(np.median(nB)), NB_LO, NB_HI,
             n_pwB, N, n_endpos, N), ok_rep, kill="K2")
    ES = [enlarged_split(r) for r in rungs]
    dev_e = max(abs((e["head2"] + e["tail2"]) - r["m"])
                / max(1.0, abs(r["e_t"]))
                for e, r in zip(ES, rungs))
    t2max = max(e["tail2"] for e in ES)
    dev_c = max(abs((e["head2"] - abs(e["tail2"])) - r["m"])
                / max(1.0, abs(r["e_t"]))
                for e, r in zip(ES, rungs))
    check("W5 WARD enlarged split: head2 + tail2 = m (max rel "
          "dev %.2e), tail2 <= 0 on %d/%d (max %+.3e), cert2 = m "
          "(max rel dev %.2e); all <= %.0e"
          % (dev_e, sum(1 for e in ES if e["tail2"] <= 0), N,
             t2max, dev_c, ID_WARD),
          dev_e <= ID_WARD and t2max <= 0 and dev_c <= ID_WARD,
          kill="K2")
    n_cross = sum(1 for r in rungs if r["ov"] < OV_MIN)
    if KILLS:
        return finish({})

    # ------------------------------------------------------------ H1
    section("H1 -- FAILURE GEOGRAPHY: the positive intervals of "
            "q_v beyond u_cB")
    aa = np.array([r["alpha"] for r in rungs])
    n_int = np.array([len(iv) for iv in IV])
    term_on = np.array([[a for a, _b, t in iv if t][0]
                        for iv in IV])
    x_on = term_on / (2.0 * aa)
    sl_on, se_on, r2_on = jack_slope(aa, x_on)
    # mass anatomy
    term_share, int_share = [], []
    for r, iv, e in zip(rungs, IV, ES):
        uT = [a for a, _b, t in iv if t][0]
        posm = e["pos"]
        Pt = float(np.sum(r["qa"][posm & (r["uu"] >= uT)]))
        term_share.append(Pt / max(e["P"], 1e-30))
    term_share = np.array(term_share)
    print("    interval count beyond u_cB: med %d (%d..%d); "
          "terminal-lobe onset u/(2 alpha): med %.3f "
          "(%.3f..%.3f), trend vs alpha %+.4f +- %.4f (R^2 %.2f)"
          % (int(np.median(n_int)), int(n_int.min()),
             int(n_int.max()), float(np.median(x_on)),
             float(np.min(x_on)), float(np.max(x_on)),
             sl_on, 2 * se_on, r2_on))
    print("    P+ split: terminal lobe carries med %.2f "
          "(%.2f..%.2f) of P+; interior lobes the rest"
          % (float(np.median(term_share)),
             float(np.min(term_share)),
             float(np.max(term_share))))
    # classical cross-check
    agree_int, d_on = 0, []
    for r, iv in zip(rungs, IV):
        Wq = r["Wcar"] if r["ov"] < OV_MIN else r["Wsm"]
        ivs = pos_intervals(Wq, r["D"], r["M"], r["u_cB"])
        agree_int += (len(ivs) == len(iv))
        tS = [a for a, _b, t in ivs if t]
        tV = [a for a, _b, t in iv if t]
        if tS and tV:
            d_on.append(abs(tS[0] - tV[0]))
    print("    CLASSICAL cross-check (v_sm, %d crossing rung(s) "
          "on carrier branch): interval-count agreement %d/%d; "
          "terminal-onset |Delta| med %.3f (%.1e..%.3f)"
          % (n_cross, agree_int, N, float(np.median(d_on)),
             float(np.min(d_on)), float(np.max(d_on))))
    h1 = ("FAILGEO(int med %d, term share med %.2f)"
          % (int(np.median(n_int)), float(np.median(term_share))))
    check("H1.1 typed (1): %s -- the failure region is weight "
          "geometry (classical), a terminal lobe + interior "
          "lobes, not an atom accident" % h1, True)

    # ------------------------------------------------------------ H2
    section("H2 -- THE EXCEPTIONAL-SET CENSUS: concentration of "
            "P+")
    k50s, k90s, k99s = [], [], []
    top1_vals, u90 = [], set()
    for r, e in zip(rungs, ES):
        contrib = r["qa"][e["pos"]]
        vals = np.round(np.exp(r["uu"][e["pos"]])).astype(int)
        o = np.argsort(contrib)[::-1]
        cs = np.cumsum(contrib[o]) / max(e["P"], 1e-30)
        k50 = int(np.searchsorted(cs, 0.50) + 1)
        k90 = int(np.searchsorted(cs, 0.90) + 1)
        k99 = int(np.searchsorted(cs, 0.99) + 1)
        k50s.append(k50)
        k90s.append(k90)
        k99s.append(k99)
        top1_vals.append(int(vals[o[0]]))
        u90.update(int(x) for x in vals[o[:k90]])
    k50s, k90s, k99s = map(np.array, (k50s, k90s, k99s))
    vals_c, cnt_c = np.unique(top1_vals, return_counts=True)
    jtop = int(np.argmax(cnt_c))
    print("    minimal k for 50/90/99%% of P+: med %d / %d / %d "
          "(max %d / %d / %d); top-1 atom value repeats: n = %d "
          "(%s) on %d/%d rungs; union of top-k90 atom values "
          "across the ladder: %d"
          % (int(np.median(k50s)), int(np.median(k90s)),
             int(np.median(k99s)), int(k50s.max()),
             int(k90s.max()), int(k99s.max()),
             int(vals_c[jtop]), pp_label(int(vals_c[jtop])),
             int(cnt_c[jtop]), N, len(u90)))
    r_mid = rungs[N // 2]
    e_mid = ES[N // 2]
    contrib = r_mid["qa"][e_mid["pos"]]
    vals = np.round(np.exp(r_mid["uu"][e_mid["pos"]])).astype(int)
    o = np.argsort(contrib)[::-1][:N_TOP]
    print("    mid-ladder rung kz %d top-%d positive atoms: %s"
          % (r_mid["kz"], N_TOP,
             ", ".join("n=%d (%s) %+0.3f" % (vals[i],
                                             pp_label(int(
                                                 vals[i])),
                                             contrib[i])
                       for i in o)))
    small = (int(k90s.max()) <= K_SMALL and len(u90) <= K_UNION)
    h2 = ("SET-SMALL(k90max=%d, union=%d)" % (int(k90s.max()),
                                              len(u90))
          if small else
          "SET-DIFFUSE(k90 med %d, union %d)"
          % (int(np.median(k90s)), len(u90)))
    check("H2.1 typed (2): %s (bars K_SMALL = %d, K_UNION = %d)"
          % (h2, K_SMALL, K_UNION), True)

    # ------------------------------------------------------------ H3
    section("H3 -- THE MINIMAL ENLARGEMENT + (d)/(e) RE-RUN")
    mm = np.array([r["m"] for r in rungs])
    XX = np.exp(2.0 * aa)
    Npos = np.array([e["Npos"] for e in ES], float)
    Ndeep = np.array([e["Ndeep"] for e in ES], float)
    h2v = np.array([e["head2"] for e in ES])
    sl_N, se_N, r2_N = jack_slope(np.log(XX), np.log(Npos))
    sl_H, se_H, r2_H = jack_slope(np.log(mm), np.log(h2v))
    print("    minimal atomwise enlargement = ALL positive-"
          "weight deep atoms: N+ med %d (%d..%d), share of deep "
          "atoms med %.2f; growth log N+ vs log X: slope %+.3f "
          "+- %.3f (R^2 %.2f)"
          % (int(np.median(Npos)), int(Npos.min()),
             int(Npos.max()),
             float(np.median(Npos / Ndeep)), sl_N, 2 * se_N,
             r2_N))
    print("    enlarged head head2 = head_B(cB) + P+: med %.3f "
          "(%.3f..%.3f); |tail2| = head2 - m med %.3f; "
          "P+ med %.3f"
          % (float(np.median(h2v)), float(np.min(h2v)),
             float(np.max(h2v)),
             float(np.median(h2v - mm)),
             float(np.median([e["P"] for e in ES]))))
    print("    (d) re-run TYPED tau-screen log head2 vs log m: "
          "slope %+.3f +- 2SE %.3f (R^2 %.2f)"
          % (sl_H, 2 * se_H, r2_H))
    rep = ("REPAIR-FINITE(slope=%+.3f)" % sl_N
           if sl_N <= GROW_BAR else
           "REPAIR-GROWING(X^%.2f)" % sl_N)
    if abs(sl_H) <= SLOPE_PASS:
        hf = "HEADFLOOR2-O1(slope=%+.3f)" % sl_H
    elif sl_H >= SLOPE_RELOC:
        hf = "HEADFLOOR2-RELOC(slope=%+.3f)" % sl_H
    else:
        hf = "HEADFLOOR2-AMBIG(slope=%+.3f)" % sl_H
    print("    (e) named: tail2 <= 0 is deterministic for ANY "
          "nonnegative comb, but the head that buys it carries "
          "med %d atoms and grows ~ X^%.2f -- the enlarged head "
          "is explicit yet NOT uniformly finite; the open "
          "arithmetic content head2 > |tail2| (gap m_h) now "
          "lives on that growing support"
          % (int(np.median(Npos)), sl_N))
    check("H3.1 typed (3): %s + %s (bands PASS |s| <= %.2f, "
          "RELOC s >= %.2f; GROW_BAR %.2f)"
          % (rep, hf, SLOPE_PASS, SLOPE_RELOC, GROW_BAR), True)

    # ------------------------------------------------------------ C
    section("C -- controls on this surface at kz %d" % CTRL_KZ)
    rr9 = core.build_window(CTRL_KZ)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE_ = lambda_eps(N_E)
    nnE = np.nonzero(np.abs(lamE_) > 1e-12)[0]
    ctl = {}
    ctl["Epstein"] = build_rung(CTRL_KZ, comb=(
        np.log(nnE.astype(float)),
        2.0 * lamE_[nnE] / np.sqrt(nnE.astype(float))),
        need_sm=False)
    ctl["scramble"] = build_rung(CTRL_KZ, scramble_seed=1,
                                 need_sm=False)
    ctl["smooth"] = build_rung(CTRL_KZ, smooth_world=True,
                               need_sm=False)
    fired = True
    for name, r in ctl.items():
        if r is None:
            print("    %-9s: rung dies -> fires" % name)
            continue
        # cert2 at every cut: head2(c) - |tail2(c)| with the same
        # R+ absorption applied at each cut
        pos_all = r["qan"] > 0.0
        cqp = np.cumsum(np.where(pos_all, r["qa"], 0.0))
        Pdeep = float(np.sum(np.where(pos_all, r["qa"], 0.0))) \
            - cqp
        h2c = r["head_B"] + Pdeep
        t2c = r["tail_B"] - Pdeep
        cert2 = h2c - np.abs(t2c)
        nc2 = int(np.sum(cert2 > 0))
        f = (r["m"] < 0) and nc2 == 0
        fired &= f
        extra = ""
        if name == "Epstein":
            extra = ("  [negative masses: tail2 <= 0 measured "
                     "%s, premise n/a]"
                     % ("yes" if float(np.max(t2c)) <= 0
                        else "NO (max %+.2e)"
                        % float(np.max(t2c))))
        print("    %-9s: m %+.3e  cert2 > 0 cuts %d -> %s%s"
              % (name, r["m"], nc2,
                 "FIRES" if f else "SILENT", extra), flush=True)
    check("C1 WARD all three controls fire (m < 0 and cert2 < 0 "
          "at every cut -- the repair cannot manufacture a "
          "certificate without the wall)", fired, kill="K2")

    return finish(dict(h1=h1, h2=h2, rep=rep, hf=hf))


def finish(labels):
    section("V -- FROZEN VERDICT")
    n_pass = sum(1 for _n, okk in CHECKS if okk)
    n_tot = len(CHECKS)
    if KILLS:
        VERDICT = {"K1": "PIPELINE-BROKEN",
                   "K2": "WARD-BROKEN"}[KILLS[0]]
        print("\n  VERDICT: %s" % VERDICT)
    else:
        VERDICT = ("TAILREPAIR-MEASURED / %(h1)s / %(h2)s / "
                   "%(rep)s / %(hf)s" % labels)
        print("\n  VERDICT: %s" % VERDICT)
    print("""
  HONEST FRAME (as frozen): the repair is MEASURED SURFACE
  STRUCTURE.  Absorbing the positive-weight region restores a
  deterministic tail sign for any nonnegative comb, at the
  measured price of a head support that grows with the window;
  the one-sided bound head2 > |tail2| (gap m_h) remains the open
  arithmetic content at every depth.  NO RH claim.  No marker
  moves.""")
    print("\n[TIME] %.1f s   [CHECKS] %d run, %d failed"
          % (time.time() - T0, n_tot, n_tot - n_pass))
    return 0 if n_pass == n_tot else 1


if __name__ == "__main__":
    raise SystemExit(main())
'''

# ------------- frozen probe source pgram_directional_schur_probe (embedded BYTE-EXACT, raw string)
_SRC_2 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""pgram_directional_schur_probe -- PRIME.PORT.PG.SCHUR.01
(EXPLORATION ONLY, experiments/; round 63, theorem-engineering on
the RH-side wall: the ONE-THEOREM question on the n > q half.
2026-08-11.)

THE QUESTION (frozen).  P2/P3 split the wall update into (B_h PD)
AND (n_h > q_h) with q_h = b* B^{-1} b in the frozen Householder
frame (gap n - q min/med 0.052/0.888 on 39/39).  CXLIV certified
the B-half via the source-only chain B >= 1/2 P_G + c_dom I =: D
with P_G the CD-Gram co-block of the rung's OWN positive chain and
c_dom the exact-rational LDL-certified dominance shift (assembled
floor min c_B = 0.5914 > 0, so D is PD).  Loewner antitonicity of
the matrix inverse gives, from  B >= D > 0,
    B^{-1} <= D^{-1}  ==>  q = b* B^{-1} b <= b* D^{-1} b =: qbar,
so the STRONGER statement  n > qbar  SUFFICES for the wall.  Its
value: qbar is built from the P_G-dominated block D whose
DIRECTION content is source-only (positive-chain CD Gram plus the
identity) -- if n > qbar holds with an O(1) ladder, the open
problem reduces to controlling the P_G-dominated Schur block
uniformly in h instead of B itself.  This probe measures exactly:
  (a) delta_h = n_h - qbar_h on all reachable steps, and
      deltahat_h = delta_h / mu1(h), mu1(h) = 4 sin^2(pi/(2h+1))
      (the deployed KMS/Dirichlet parity gap, source-only);
  (b) THE VERDICT (frozen enums, below);
  (c) if OUTCOME-B: the monotone Woodbury hierarchy
      D_{k+1} = D_k + w_k w_k* with source-only components w_k;
  (d) controls + the exact Loewner ward q <= qbar everywhere.

EXACTNESS MODEL (frozen).  All decisions and the delta ladder are
computed in EXACT Fraction arithmetic on the float64-computed step
matrices (whose entries are exact rationals -- the v897/CXLIV
certificate class): Bfr = fr(B), Pfr = fr(0.5 * P_G) (halving a
float is exact), Kfr = Bfr - Pfr formed in Fractions, c_dom by
exact dyadic LDL bisection on Kfr, Dfr = Pfr + c_dom I, q and qbar
by exact Gaussian solves on Bfr and Dfr, delta = fr(n) - qbar
exact.  Float eigensolves appear ONLY as bisection hints and
printed context (a hint cannot affect a certificate: the final PD
decision is re-run exactly).  What is NOT enclosed: the float
pipeline that produces the entries (FFT density, Lanczos, eigh
frame, Schur solves) -- the interval rollout of that pipeline is a
CONCURRENT, separate work item and is deliberately NOT duplicated
here; this probe consumes the float-level chain only.  NO RH
claim.

FROZEN PROTOCOL (pipeline verbatim from
bfloor_pg_dominance_probe.py = CXLIV = v900 chain; ONE Gram per
rung; window memoization):

 W   PIPELINE + REPRODUCTION (kill -> PIPELINE-BROKEN /
     WARD-BROKEN): W1 42 rungs, chains complete, tau finite; W2 >=
     30 full-core rungs; W3a truth all-PSD (A, R, S); W3b >= 20
     consecutive full-core steps; W4 REPRODUCTION P2/P3 ledger:
     min lam_min(B) == 0.679 (rtol 2e-2), gap min/med ==
     0.052/0.888 (rtol 5e-2), raw-B certified disaster (best bound
     < 0 on every step); W5 REPRODUCTION of CXLIV V4: P_G PD on
     every step (float, PG_TOL) and float dominance
     negidx(B - 1/2 P_G) = 0 on >= DOMHALF_MIN steps (CXLIV
     measured 39/39, min lam_min +0.179); W6 MACHINE WARDS: the
     exact LDL accepts PD / refuses indefinite; the exact solver
     reproduces a known rational solution exactly.

 E1  THE EXACT LADDER (per step): c_dom = largest certified c
     with Kfr - c I PD (dyadic bisection, BIS_ITERS; lo = 0 if PD
     at 0, else lo = float hint minus LO_PAD relative padding --
     if PD fails at lo the step is typed D-FAIL); Dfr = Pfr +
     c_dom I; wards (kill -> WARD-BROKEN): E1.w1 exact Loewner
     q <= qbar on EVERY step (Fraction comparison, no tolerance);
     E1.w2 exact re-certification B - D PD on every step; E1.w3
     D PD (exact; expected everywhere since c_B > 0 in CXLIV --
     typed count, a failing step is D-FAIL, measured not killed).
     Printed ladder: kz, h, alpha, n, q, qbar, delta = n - qbar,
     deltahat = delta/mu1(h), qbar/q.

 E2  THE VERDICT (frozen a priori):
       OUTCOME-A  iff delta_h > 0 EXACTLY on all steps -- a
                  genuine new sufficient route; report the margin
                  ladder min/med and its tau-screen (OLS slope of
                  log delta vs log tau on the positive subset,
                  bands PASS |s| <= 0.30 / RELOC >= 0.70 / AMBIG);
       OUTCOME-B  iff delta_h <= 0 somewhere AND median(qbar/q)
                  <= QLOSS_BAR = 2.0 -- near miss; report the
                  deficit per failing step in units of n and of
                  mu1, then run E3;
       OUTCOME-C  iff median(qbar/q) > QLOSS_BAR -- the bound
                  loses O(1), route honestly dead; report median
                  and max qbar/q.
     The qbar/q ladder is printed for every outcome (bound
     quality is reported even when the route wins).

 E3  THE HIERARCHY (only if OUTCOME-B; per failing step): the
     monotone updates D_{k+1} = D_k + w_k w_k* with the
     source-only components the positive chain itself offers:
     w_k = sqrt(1/2) u_k, u_k = co-block of Q^T (sqrt(v_core)
     p_k(y_core)) -- the rank-1 CD-Gram summands of the REMAINING
     half of P_G, taken in ASCENDING chain degree k (frozen
     order; NEVER an eigenvector of B, never b, n or any target
     data in the selection).  Acceptance: exact LDL PD of
     B - D_{k+1} (a certificate decision, not a construction);
     rejected components are skipped, at most K_HIER candidates
     tried.  Each accepted update lowers qbar via
     Sherman-Morrison: qbar_{k+1} = qbar_k - z^2/(1 + w* D_k^{-1}
     w), z = w* D_k^{-1} b, VERIFIED against the direct solve to
     WOODBURY_TOL relative (machine-precision ward, kill ->
     WARD-BROKEN).  k*(h) = number of ACCEPTED components until
     delta > 0; typed KSTAR-ALL-REACHED(max k*, OLS slope of k*
     vs log h) / KSTAR-NOT-REACHED(count) -- bounded k* = a
     finite proof architecture for the tail; growing k* = honest
     relocation.

 C   CONTROLS (kill -> WARD-BROKEN if silent): C0 truth neg(A) =
     0 everywhere; C1 smooth world neg(A) > 0 on >= 1 rung; C2
     Epstein x^2+5y^2 comb + scramble (seed 1) at kz 9 fire
     (neg(A) > 0 or frame death); C3 THE DECLARED BREAK MODE of
     this route in the smooth world: B0 (smooth co-block, same
     truth frame) NOT PD by exact LDL on >= REFUSE_MIN usable
     steps -- the Loewner premise B >= D > 0 is unavailable, the
     route cannot even be stated there; C4 the scramble core,
     where it exists, must break the floor (disclosed skip if the
     scramble core dies; C3 carries the cannot-fake content).

KILLS: K1 pipeline (W1-W3) -> PIPELINE-BROKEN; K2 reproduction /
ward / control failures (W4-W6, E1.w1, E1.w2, E3 Woodbury ward,
C0-C4) -> WARD-BROKEN.  All E-typed outcomes are measurements,
never kills.

VERDICT (frozen enum): PGSCHUR-MEASURED with typed sublabels
LOEWNER-WARDED(N/N exact), DFAIL(count), and exactly one of
OUTCOME-A(min delta, min deltahat, screen) /
OUTCOME-B(worst deficit/n, worst deficit/mu1, KSTAR-...) /
OUTCOME-C(med qbar/q, max qbar/q); else PIPELINE-BROKEN /
WARD-BROKEN.

FROZEN BARS: CORE_J = (2,...,16); H_LADDER_MAX = 900; N_RUNGS_EXP
= 42; MIN_CORE_RUNGS = 30; MIN_STEPS = 20; MINB_REF = 0.679 (rtol
2e-2); GAPMIN_REF = 0.052, GAPMED_REF = 0.888 (rtol 5e-2); PG_TOL
= 1e-12; S_HALF = 1/2 EXACT (the CXLIV canonical V4, frozen as
declared input -- no variant scan here); DOMHALF_MIN = 37
(expected 39); BIS_ITERS = 40; LO_PAD = 2^-10 relative; QLOSS_BAR
= 2.0; K_HIER = 64; WOODBURY_TOL = 1e-9; REFUSE_MIN = 30;
SLOPE_PASS = 0.30; SLOPE_RELOC = 0.70; CTRL_KZ = 9; scramble seed
1; mu1(h) = 4 sin^2(pi/(2h+1)) on r2's h.  Runtime cap declared:
8 min.

ANTI-CIRCULARITY (frozen): no sigma_h, no defect eigenvector, no
pivot sign, no spectral data of the TARGET B in any CONSTRUCTION
-- P_G and the hierarchy components are source-only (positive
chain at the core nodes, frozen constants); c_dom is a CERTIFIED
scalar obtained by the declared v897/CXLIV exact-LDL certificate
class on B - 1/2 P_G (a decision procedure, not a fit; the
direction content of D stays source-only: P_G plus the identity);
float eigensolves are hints/context only.  The hierarchy selects
components by frozen chain order, never by target data.

NO-GO COMPLIANCE (frozen): no rank-1 approximation of the core
update; no plain Herglotz certificate; no fit where an identity
is claimed; exact-rational LDL is allowed as a CERTIFICATE per
the CXLIV mandate -- declared, not silent.

SMOKE-RUN DISCLOSURE (2026-08-11, before freezing): one smoke run
of this script (20/20 with the identical bars; NO bar, band,
count, rule or enum was moved after it) measured: pipeline +
P2/P3 + CXLIV reproduction green (min lam_min(B) 0.6790, gap
0.0520/0.8875, raw disaster best -88.2, P_G PD 39/39, float
half-dominance 39/39, min +0.179 reproduced).  E1: c_dom
certified with lo = 0 on 39/39 (no D-FAIL), D PD exact 39/39,
B - D PD re-certified 39/39, the exact Loewner ward q <= qbar
holds 39/39.  THE ANSWER IS OUTCOME-C, AND IT IS NOT CLOSE:
delta = n - qbar > 0 on only 1/39 steps (kz 60 h 388, +0.0926);
delta min/med -4071.4/-5.28; deltahat min/med -7.8e+07/-1.0e+05;
qbar/q min/med/max 4.39/91.3/408.2 -- the Loewner bound loses
TWO ORDERS OF MAGNITUDE, not O(1): D = 1/2 P_G + c_dom I is an
excellent FLOOR model of B (CXLIV: c_B/lam_min(B) med 0.979) but
a terrible INVERSE model along b, because q = b* B^{-1} b reads
B's full spectral geometry (B has O(10..1e4)-scale directions
that D truncates at its O(1) floor, so D^{-1} inflates exactly
the b-components that B^{-1} suppresses).  The delta tau-screen
is vacuous (pos = 1, disclosed).  E3 does not run (frozen:
hierarchy only on OUTCOME-B).  Controls: smooth neg(A) > 0 on
42/42, C3 refusal 35/35, Epstein neg(A) 55 fires, scramble
neg(A) 37 fires, scramble core dead -> C4 disclosed skip.
Runtime 4.3 s (cap holds).  Fail-first preserved: nothing was
weakened; the verdict rule, bars and enums are exactly as frozen
above.

SPEC v1 (2026-08-11, frozen + SHA-hashed before the frozen run):
everything above.  Mechanical concretizations frozen with v1: (i)
window memoization per (kz, seed); (ii) Householder frame as
P2/CXLIV; (iii) P_G via eval_chain on r2's own chain at r2's core
nodes, degree < h (CXLIV V0 direction, s = 1/2 by V4); (iv) exact
LDL = full symmetric Gaussian elimination in Fraction arithmetic,
PD iff all pivots > 0 (Sylvester); exact solver = Gaussian
elimination with partial pivoting in Fractions; (v) bisection lo
certified by a final exact re-decision; (vi) negidx = count of
float eigenvalues < 0; (vii) OLS population statistics as v900;
screens read positive subsets.

NO RH claim: delta > 0 (had it held) would be a SURFACE statement
about the computed step matrices of the deployed ladder; it does
not prove n > q uniformity in h, the pipeline enclosure, or any
tail statement.  OUTCOME-C is a route-mortality measurement.  No
marker moves.

FIREWALL: no zeros, no prime oracles (AST scan; banned ids
zetazero / nzeros / primerange / isprime / primepi / nextprime /
prevprime); v563 READ-ONLY; RNG only inside the declared scramble
control; stdout only.

Sources (read-only): v563_paper2_readouts; wall + fixed-core +
P_G machinery verbatim from bfloor_pg_dominance_probe.py (CXLIV);
P2/P3 split from port_tangent_schur_probe (declared input); mu1
parity geometry as moving_node_second_order_probe (CXLIII,
declared input).

Run:
    experiments/tfpt-discovery/.venv/bin/python \
        experiments/tfpt-discovery/pgram_directional_schur_probe.py
"""

import ast
import hashlib
import math
import os
import sys
import time
from fractions import Fraction

import numpy as np

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

import v563_paper2_readouts as core        # noqa: E402  (READ-ONLY)

CORE_J = (2, 4, 6, 8, 10, 12, 14, 16)
H_LADDER_MAX = 900
N_RUNGS_EXP = 42
MIN_CORE_RUNGS = 30
MIN_STEPS = 20
MINB_REF = 0.679
MINB_RTOL = 2e-2
GAPMIN_REF = 0.052
GAPMED_REF = 0.888
GAP_RTOL = 5e-2
PG_TOL = 1e-12
S_HALF = Fraction(1, 2)
DOMHALF_MIN = 37
BIS_ITERS = 40
LO_PAD = Fraction(1, 1024)
QLOSS_BAR = 2.0
K_HIER = 64
WOODBURY_TOL = 1e-9
REFUSE_MIN = 30
SLOPE_PASS = 0.30
SLOPE_RELOC = 0.70
CTRL_KZ = 9
BANNED_IDS = ("zetazero", "nzeros", "primerange", "isprime",
              "primepi", "nextprime", "prevprime")

CHECKS = []
KILLS = []
T0 = time.time()


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


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


def ast_scan(banned):
    src = open(os.path.abspath(__file__), encoding="utf-8").read()
    bad = []
    for node in ast.walk(ast.parse(src)):
        name = None
        if isinstance(node, ast.Name):
            name = node.id
        elif isinstance(node, ast.Attribute):
            name = node.attr
        if name and name.lower() in banned:
            bad.append(name)
    return bad


# --------------- pipeline, verbatim (bfloor_pg_dominance_probe)
def grid_density(c):
    c = np.asarray(c, float)
    a = np.concatenate([c, c[-2:0:-1]])
    d = np.fft.fft(a)
    assert float(np.max(np.abs(d.imag))) <= 1e-9 * max(
        1.0, float(np.max(np.abs(d.real))))
    return d.real


def cell_widths(uu):
    du = np.zeros(len(uu))
    du[1:-1] = 0.5 * (uu[2:] - uu[:-2])
    du[0] = uu[1] - uu[0]
    du[-1] = uu[-1] - uu[-2]
    return du


def folded_measure(d_arm, L, sign=+1.0):
    jj = np.arange(L)
    keep = (sign * d_arm) > 0.0
    jj = jj[keep]
    th = 2.0 * math.pi * jj / L
    wt = (np.abs(d_arm[keep]) / (2.0 * L)) * 4.0 * np.sin(
        th / 2.0) ** 2
    fold = np.minimum(jj, L - jj)
    uf, inv = np.unique(fold, return_inverse=True)
    wagg = np.zeros(len(uf))
    np.add.at(wagg, inv, wt)
    xs = np.cos(2.0 * math.pi * uf / L)
    m = wagg > 1e-300
    return xs[m], wagg[m], uf[m]


def lanczos_chain(x, w, n):
    m0 = float(np.sum(w))
    m = len(x)
    Q = np.zeros((m, n))
    Q[:, 0] = np.sqrt(w) / math.sqrt(m0)
    al = np.zeros(n)
    be = np.zeros(max(n - 1, 0))
    steps = n
    for k in range(n):
        z = x * Q[:, k]
        al[k] = float(Q[:, k] @ z)
        z = z - al[k] * Q[:, k]
        if k > 0:
            z = z - be[k - 1] * Q[:, k - 1]
        for _ in range(2):
            z = z - Q[:, :k + 1] @ (Q[:, :k + 1].T @ z)
        if k == n - 1:
            break
        bnorm = float(np.linalg.norm(z))
        if bnorm <= 1e-14:
            steps = k + 1
            break
        be[k] = bnorm
        Q[:, k + 1] = z / bnorm
    return al[:steps], be[:max(steps - 1, 0)], m0, steps


def eval_chain(al, be, m0, y, n):
    P = np.zeros((len(y), n))
    P[:, 0] = 1.0 / math.sqrt(m0)
    if n > 1:
        P[:, 1] = (y - al[0]) * P[:, 0] / be[0]
    for k in range(1, n - 1):
        P[:, k + 1] = ((y - al[k]) * P[:, k]
                       - be[k - 1] * P[:, k - 1]) / be[k]
    return P


def lambda_eps(N):
    """Epstein x^2+5y^2 comb (port_schur_reduction verbatim)."""
    r = np.zeros(N + 1)
    s = int(math.isqrt(N)) + 1
    for x in range(-s, s + 1):
        for y in range(-s, s + 1):
            v = x * x + 5 * y * y
            if 1 <= v <= N:
                r[v] += 1.0
    a = r / 2.0
    lam = np.zeros(N + 1)
    for n in range(2, N + 1):
        acc = a[n] * math.log(n)
        for dd in range(2, n):
            if n % dd == 0:
                acc -= lam[dd] * a[n // dd]
        lam[n] = acc
    return lam


_WIN_CACHE = {}


def window_of(kz, scramble_seed=None):
    key = (kz, scramble_seed)
    if key not in _WIN_CACHE:
        rr = core.build_window(kz, scramble_seed=scramble_seed)
        _WIN_CACHE[key] = dict(
            h=rr["h"], M=rr["M"], D=rr["D"], alpha=rr["alpha"],
            n_atom=rr["n_atom"],
            uu=np.asarray(rr["uu"], float).copy(),
            lam=np.asarray(rr["lam"], float).copy(),
            c_ar=np.asarray(core.arch_lags(rr["M"], rr["D"]),
                            float))
    return _WIN_CACHE[key]


def ladder_zones():
    out = []
    for kz in core.frame_a_zones():
        D_k = 0.5 * float(core.G_ALL[kz]) / float(core.NU_MAIN)
        M_k = int(math.ceil(float(core.U_ALL[kz]) / D_k - 1.0e-9)) + 1
        if M_k % 2:
            M_k += 1
        if M_k // 2 <= H_LADDER_MAX:
            out.append(kz)
    return out


def smooth_masses(uu):
    return 2.0 * np.exp(uu / 2.0) * cell_widths(uu)


def world_smooth(uu, mm, rr):
    return uu, smooth_masses(uu)


def gram_anatomy(kz, world_fn=None, scramble_seed=None, comb=None,
                 keep_chain=False):
    """v900 verbatim wall + fixed-core split."""
    rr = window_of(kz, scramble_seed=scramble_seed)
    M, D, alpha, h = rr["M"], rr["D"], rr["alpha"], rr["h"]
    uu = rr["uu"]
    mm = 2.0 * rr["lam"]
    if world_fn is not None:
        uu, mm = world_fn(uu, mm, rr)
    if comb is not None:
        uu, mm = comb
    c_at, _ = core.atom_lags_at(alpha, M, uu, mm)
    d = grid_density(rr["c_ar"] + np.asarray(c_at, float))
    L = 2 * M - 2
    xs, ws, _ = folded_measure(d, L, +1.0)
    ys, vs, uf_n = folded_measure(d, L, -1.0)
    al, be, m0, steps = lanczos_chain(xs, ws, h + 1)
    if steps < h + 1 or np.any(be <= 0):
        return None
    Pn = eval_chain(al, be, m0, ys, h)
    G = np.sqrt(vs)[:, None] * (Pn @ Pn.T) * np.sqrt(vs)[None, :]
    G = 0.5 * (G + G.T)
    n = G.shape[0]
    A = np.eye(n) - G
    evA = np.linalg.eigvalsh(A)
    out = dict(kz=kz, h=h, n=n, alpha=float(alpha), M=M, D=D, L=L)
    out["tau"] = float(evA[0])
    out["negA"] = int(np.sum(evA < 0.0))
    if keep_chain:
        out["chain"] = (al, be, m0)
    idx = {int(j): k for k, j in enumerate(uf_n)}
    out["core_ok"] = all(j in idx for j in CORE_J)
    if not out["core_ok"]:
        return out
    ic = np.array([idx[j] for j in CORE_J], dtype=int)
    icset = set(ic.tolist())
    ib = np.array([k for k in range(n) if k not in icset],
                  dtype=int)
    B = A[np.ix_(ic, ic)]
    Xc = A[np.ix_(ic, ib)]
    R = A[np.ix_(ib, ib)]
    evR = np.linalg.eigvalsh(R)
    out["lamR"] = float(evR[0])
    out["negR"] = int(np.sum(evR < 0.0))
    Z = np.linalg.solve(R, Xc.T)
    Y = Xc @ Z
    Y = 0.5 * (Y + Y.T)
    S = B - Y
    S = 0.5 * (S + S.T)
    evS = np.linalg.eigvalsh(S)
    out["S"] = S
    out["lamS"] = float(evS[0])
    out["negS"] = int(np.sum(evS < 0.0))
    if keep_chain:
        out["y_core"] = np.array([ys[idx[j]] for j in CORE_J])
        out["v_core"] = np.array([vs[idx[j]] for j in CORE_J])
    return out


def householder_frame(v):
    n = len(v)
    v = v / float(np.linalg.norm(v))
    e1 = np.zeros(n)
    e1[0] = 1.0
    u = e1 - v
    nu = float(np.linalg.norm(u))
    if nu < 1e-14:
        return np.eye(n)
    u = u / nu
    Q = np.eye(n) - 2.0 * np.outer(u, u)
    if float(Q[:, 0] @ v) < 0:
        Q = -Q
    return Q


def ols_line(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    vx = float(np.var(x))
    if vx == 0.0:
        return float(np.mean(y)), 0.0, float("nan")
    b = float(np.cov(x, y, bias=True)[0, 1] / vx)
    a = float(np.mean(y) - b * np.mean(x))
    ss = float(np.sum((y - a - b * x) ** 2))
    st = float(np.sum((y - np.mean(y)) ** 2))
    return a, b, (1.0 - ss / st if st > 0 else float("nan"))


# ------------------------------ certified bounds (P3 verbatim)
def gersh_min(B):
    d = np.diag(B)
    r = np.sum(np.abs(B), axis=1) - np.abs(d)
    return float(np.min(d - r))


def gersh_scaled(B):
    d = np.diag(B)
    if float(np.min(d)) <= 0.0:
        return float("-inf")
    s = 1.0 / np.sqrt(d)
    C = B * np.outer(s, s)
    r = np.sum(np.abs(C), axis=1) - np.abs(np.diag(C))
    lamg = float(np.min(1.0 - r))
    return lamg * (float(np.min(d)) if lamg >= 0.0
                   else float(np.max(d)))


def cassini_scaled(B):
    d = np.diag(B)
    if float(np.min(d)) <= 0.0:
        return float("-inf")
    s = 1.0 / np.sqrt(d)
    C = B * np.outer(s, s)
    r = np.sum(np.abs(C), axis=1) - np.abs(np.diag(C))
    rr = np.sort(r)[::-1]
    lamc = 1.0 - math.sqrt(float(rr[0]) * float(rr[1]))
    return lamc * (float(np.min(d)) if lamc >= 0.0
                   else float(np.max(d)))


def best_cert(B):
    return max(gersh_min(B), gersh_scaled(B), cassini_scaled(B))


def screen(vals, taus):
    vals = np.asarray(vals, float)
    taus = np.asarray(taus, float)
    pos = vals > 0
    if int(np.sum(pos)) >= 3:
        _a, sl, r2 = ols_line(np.log(taus[pos]), np.log(vals[pos]))
    else:
        return "vacuous(pos=%d)" % int(np.sum(pos)), float("nan")
    lab = ("PASS" if abs(sl) <= SLOPE_PASS
           else "RELOC" if sl >= SLOPE_RELOC else "AMBIG")
    return "%s(slope=%+.3f, R2=%.3f)" % (lab, sl, r2), sl


# ------------------------- the exact-rational certificate class
def mat_fr(M):
    """float64 matrix -> exact-rational (Fraction) list of lists."""
    n = M.shape[0]
    return [[Fraction(float(M[i, j])) for j in range(n)]
            for i in range(n)]


def pd_exact(Afr, shift=Fraction(0)):
    """Exact Sylvester/LDL decision: is A - shift I PD?"""
    n = len(Afr)
    A = [[Afr[i][j] - (shift if i == j else 0) for j in range(n)]
         for i in range(n)]
    for k in range(n):
        p = A[k][k]
        if p <= 0:
            return False, k
        for i in range(k + 1, n):
            f = A[i][k] / p
            for j in range(k + 1, n):
                A[i][j] = A[i][j] - f * A[k][j]
    return True, -1


def cert_floor_exact(Afr, lo, hi, iters=BIS_ITERS):
    """Largest certified c in [lo, hi] with A - c I PD (dyadic
    bisection; final PD decision re-run exactly at the returned
    lo).  None if PD fails at lo."""
    lo = Fraction(lo)
    hi = Fraction(hi)
    ok, _ = pd_exact(Afr, lo)
    if not ok:
        return None
    for _ in range(iters):
        mid = (lo + hi) / 2
        ok, _ = pd_exact(Afr, mid)
        if ok:
            lo = mid
        else:
            hi = mid
    ok, _ = pd_exact(Afr, lo)
    assert ok
    return lo


def solve_fr(Afr, bfr):
    """Exact Gaussian elimination with partial pivoting.
    Returns x with A x = b in Fractions, or None if singular."""
    n = len(Afr)
    A = [list(Afr[i]) + [bfr[i]] for i in range(n)]
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(A[i][k]))
        if A[p][k] == 0:
            return None
        if p != k:
            A[k], A[p] = A[p], A[k]
        for i in range(k + 1, n):
            f = A[i][k] / A[k][k]
            for j in range(k, n + 1):
                A[i][j] = A[i][j] - f * A[k][j]
    x = [Fraction(0)] * n
    for i in range(n - 1, -1, -1):
        s = A[i][n]
        for j in range(i + 1, n):
            s = s - A[i][j] * x[j]
        x[i] = s / A[i][i]
    return x


def quad_fr(Afr, bfr):
    """Exact b* A^{-1} b in Fractions (None if singular)."""
    x = solve_fr(Afr, bfr)
    if x is None:
        return None
    s = Fraction(0)
    for bi, xi in zip(bfr, x):
        s = s + bi * xi
    return s


def build_pg(w):
    """The source-only P_G co-block (CXLIV V0 direction)."""
    r2 = w["r2"]
    ch = r2.get("chain")
    if ch is None:
        return None
    al, be, m0 = ch
    Pc = eval_chain(al, be, m0, r2["y_core"], r2["h"])
    Gc = (np.sqrt(r2["v_core"])[:, None] * (Pc @ Pc.T)
          * np.sqrt(r2["v_core"])[None, :])
    Gc = 0.5 * (Gc + Gc.T)
    PG = (w["Q"].T @ Gc @ w["Q"])[1:, 1:]
    return 0.5 * (PG + PG.T)


def pg_components(w):
    """The rank-1 CD-Gram summands u_k of P_G (co-block frame),
    ascending chain degree k (frozen hierarchy order)."""
    r2 = w["r2"]
    al, be, m0 = r2["chain"]
    Pc = eval_chain(al, be, m0, r2["y_core"], r2["h"])
    sq = np.sqrt(r2["v_core"])
    out = []
    for k in range(Pc.shape[1]):
        g = sq * Pc[:, k]
        out.append((w["Q"].T @ g)[1:])
    return out


def mu1_of(h):
    return 4.0 * math.sin(math.pi / (2.0 * h + 1.0)) ** 2


def main():
    section("PRIME.PORT.PG.SCHUR.01 -- n > qbar = b* D^{-1} b with "
            "D = 1/2 P_G + c_dom I: the directional Loewner route "
            "on the n > q half (EXPLORATION ONLY)")
    print("    FROZEN_SPEC SHA-256 = %s"
          % hashlib.sha256(__doc__.encode("utf-8")).hexdigest())
    print("    NO RH claim; no marker moves.  Exact statements are "
          "about the float64-computed step matrices (caveat block "
          "in spec); the pipeline interval rollout is a concurrent "
          "separate work item, NOT duplicated here.")
    print("\nS0 -- firewall")
    check("S0.1 AST firewall clean", not ast_scan(BANNED_IDS))

    # ------------------------------------------------------------ W
    section("W -- the truth ladder + P2/P3 + CXLIV reproduction")
    zones = ladder_zones()
    check("W1 frozen rung count %d" % N_RUNGS_EXP,
          len(zones) == N_RUNGS_EXP, "found %d" % len(zones),
          kill="K1")
    truth = []
    sm_map = {}
    for kz in zones:
        r = gram_anatomy(kz, keep_chain=True)
        if r is None:
            print("    kz %-3d: CHAIN SHORT" % kz, flush=True)
            truth.append(None)
            continue
        truth.append(r)
        rs = gram_anatomy(kz, world_fn=world_smooth,
                          keep_chain=True)
        if isinstance(rs, dict):
            sm_map[kz] = rs
    ok_chain = all(r is not None for r in truth)
    check("W1b all chains complete", ok_chain, kill="K1")
    if not ok_chain:
        return finish({})
    truth.sort(key=lambda r: (r["h"], r["kz"]))
    check("W1c all tau finite",
          all(np.isfinite(r["tau"]) for r in truth), kill="K1")
    full = [r for r in truth if r["core_ok"]]
    check("W2 >= %d full-core rungs" % MIN_CORE_RUNGS,
          len(full) >= MIN_CORE_RUNGS,
          "%d full-core rungs" % len(full), kill="K1")
    ok_psd = all(r["negA"] == 0 and r["negR"] == 0
                 and r["negS"] == 0 for r in full)
    check("W3a WARD truth all-PSD (A, R, S)", ok_psd, kill="K1")
    steps = []
    for r1, r2 in zip(truth, truth[1:]):
        if not (r1.get("core_ok") and r2.get("core_ok")):
            continue
        if r1["lamS"] <= 0.0 or r1["negA"] > 0:
            continue
        steps.append((r1, r2))
    check("W3b >= %d consecutive full-core steps" % MIN_STEPS,
          len(steps) >= MIN_STEPS, "%d steps" % len(steps),
          kill="K1")
    print("    h range %d..%d  [%.1f s]"
          % (truth[0]["h"], truth[-1]["h"], time.time() - T0))
    if KILLS:
        return finish({})
    rows = []
    for r1, r2 in steps:
        wS, VS = np.linalg.eigh(r1["S"])
        Q = householder_frame(VS[:, 0])
        Mt = Q.T @ (r2["S"] / r1["tau"]) @ Q
        Mt = 0.5 * (Mt + Mt.T)
        nsc = float(Mt[0, 0])
        b = Mt[1:, 0]
        B = Mt[1:, 1:]
        minB = float(np.linalg.eigvalsh(B)[0])
        gap = (nsc - float(b @ np.linalg.solve(B, b))
               if minB > 0 else float("nan"))
        rs2 = sm_map.get(r2["kz"])
        B0 = None
        if isinstance(rs2, dict) and "S" in rs2:
            M0 = Q.T @ (rs2["S"] / r1["tau"]) @ Q
            M0 = 0.5 * (M0 + M0.T)
            B0 = M0[1:, 1:]
        rows.append(dict(r1=r1, r2=r2, Q=Q, B=B, b=b, nsc=nsc,
                         B0=B0, minB=minB, gap=gap, tau=r1["tau"],
                         bestg=best_cert(B)))
    minB_all = float(np.min([w["minB"] for w in rows]))
    gaps = np.array([w["gap"] for w in rows])
    bests = np.array([w["bestg"] for w in rows])
    gmin, gmed = float(np.min(gaps)), float(np.median(gaps))
    ok_repro = (abs(minB_all / MINB_REF - 1.0) <= MINB_RTOL
                and abs(gmin / GAPMIN_REF - 1.0) <= GAP_RTOL
                and abs(gmed / GAPMED_REF - 1.0) <= GAP_RTOL
                and float(np.max(bests)) < 0.0)
    check("W4 REPRODUCTION P2/P3 ledger: min lam_min(B) %.4f == "
          "%.3f; gap min/med %.4f/%.4f == %.3f/%.3f; raw-B "
          "certified disaster (best max %+.1f < 0 on %d steps)"
          % (minB_all, MINB_REF, gmin, gmed, GAPMIN_REF,
             GAPMED_REF, float(np.max(bests)), len(rows)),
          ok_repro, kill="K2")
    pg_ok = True
    n_dom = 0
    for w in rows:
        PG = build_pg(w)
        if PG is None:
            pg_ok = False
            continue
        if float(np.linalg.eigvalsh(PG)[0]) <= PG_TOL:
            pg_ok = False
        w["PG"] = PG
        Dm = w["B"] - 0.5 * PG
        Dm = 0.5 * (Dm + Dm.T)
        w["lamK_hint"] = float(np.linalg.eigvalsh(Dm)[0])
        if int(np.sum(np.linalg.eigvalsh(Dm) < 0.0)) == 0:
            n_dom += 1
    check("W5 REPRODUCTION CXLIV V4: P_G PD on every step; float "
          "dominance negidx(B - 1/2 P_G) = 0 on %d/%d (>= %d; "
          "CXLIV: 39/39, min +0.179)"
          % (n_dom, len(rows), DOMHALF_MIN),
          pg_ok and n_dom >= DOMHALF_MIN, kill="K2")
    ok_pd, _ = pd_exact(mat_fr(np.array([[2.0, 1.0], [1.0, 2.0]])))
    ok_ind, _ = pd_exact(mat_fr(np.array([[1.0, 2.0], [2.0, 1.0]])))
    xs = solve_fr([[Fraction(2), Fraction(1)],
                   [Fraction(1), Fraction(2)]],
                  [Fraction(1), Fraction(0)])
    ok_sol = (xs is not None and xs[0] == Fraction(2, 3)
              and xs[1] == Fraction(-1, 3))
    check("W6 MACHINE WARDS: exact LDL accepts PD / refuses "
          "indefinite; exact solver hits the known rational "
          "solution", ok_pd and not ok_ind and ok_sol, kill="K2")
    if KILLS:
        return finish({})

    # ----------------------------------------------------------- E1
    section("E1 -- the exact ladder: c_dom, D, q, qbar, delta")
    n_loew, n_recert, n_dpd, n_dfail = 0, 0, 0, 0
    ladder = []
    print("      kz    h    alpha    n_h       q         qbar      "
          "delta      deltahat    qbar/q")
    for w in rows:
        n7 = 7
        Bfr = mat_fr(w["B"])
        Pfr = mat_fr(0.5 * w["PG"])
        Kfr = [[Bfr[i][j] - Pfr[i][j] for j in range(n7)]
               for i in range(n7)]
        hi = min(Kfr[k][k] for k in range(n7))
        ok0, _ = pd_exact(Kfr)
        if ok0:
            lo = Fraction(0)
        else:
            hint = Fraction(w["lamK_hint"])
            lo = hint - LO_PAD * max(Fraction(1), abs(hint))
            okl, _ = pd_exact(Kfr, lo)
            if not okl:
                n_dfail += 1
                print("    D-FAIL kz %d h %d: PD fails at padded "
                      "lo" % (w["r2"]["kz"], w["r2"]["h"]),
                      flush=True)
                continue
        cdom = cert_floor_exact(Kfr, lo, hi)
        if cdom is None:
            n_dfail += 1
            print("    D-FAIL kz %d h %d: bisection refused"
                  % (w["r2"]["kz"], w["r2"]["h"]), flush=True)
            continue
        Dfr = [[Pfr[i][j] + (cdom if i == j else 0)
                for j in range(n7)] for i in range(n7)]
        okD, _ = pd_exact(Dfr)
        if okD:
            n_dpd += 1
        else:
            n_dfail += 1
            print("    D-FAIL kz %d h %d: D not PD"
                  % (w["r2"]["kz"], w["r2"]["h"]), flush=True)
            continue
        okBD, _ = pd_exact(Kfr, cdom)
        if okBD:
            n_recert += 1
        bfr = [Fraction(float(x)) for x in w["b"]]
        nfr = Fraction(w["nsc"])
        q = quad_fr(Bfr, bfr)
        qbar = quad_fr(Dfr, bfr)
        if q is None or qbar is None:
            n_dfail += 1
            print("    D-FAIL kz %d h %d: singular solve"
                  % (w["r2"]["kz"], w["r2"]["h"]), flush=True)
            continue
        if q <= qbar:
            n_loew += 1
        delta = nfr - qbar
        mu1 = mu1_of(w["r2"]["h"])
        row = dict(w=w, cdom=cdom, q=q, qbar=qbar, delta=delta,
                   nfr=nfr, mu1=mu1, Dflt=0.5 * w["PG"]
                   + float(cdom) * np.eye(n7))
        ladder.append(row)
        print("    %4d %5d  %6.2f  %8.4f  %8.4f  %8.4f  %+9.4f  "
              "%+.3e  %6.3f"
              % (w["r2"]["kz"], w["r2"]["h"], w["r2"]["alpha"],
                 float(nfr), float(q), float(qbar), float(delta),
                 float(delta) / mu1, float(qbar / q)), flush=True)
    N = len(rows)
    check("E1.w1 WARD exact Loewner q <= qbar on %d/%d usable "
          "steps (Fraction comparison, no tolerance)"
          % (n_loew, len(ladder)), n_loew == len(ladder),
          kill="K2")
    check("E1.w2 WARD exact re-certification B - D PD on %d/%d"
          % (n_recert, len(ladder)), n_recert == len(ladder),
          kill="K2")
    check("E1.w3 typed: D PD exact on %d/%d, D-FAIL on %d "
          "(measured)" % (n_dpd, N, n_dfail), True)
    if KILLS or not ladder:
        return finish({})

    # ----------------------------------------------------------- E2
    section("E2 -- the frozen verdict rule")
    deltas = np.array([float(r["delta"]) for r in ladder])
    dhat = np.array([float(r["delta"]) / r["mu1"] for r in ladder])
    qr = np.array([float(r["qbar"] / r["q"]) for r in ladder])
    n_pos = sum(1 for r in ladder if r["delta"] > 0)
    med_qr = float(np.median(qr))
    print("    delta > 0 (exact) on %d/%d steps; delta min/med "
          "%+.4f/%+.4f; deltahat min/med %+.3e/%+.3e; qbar/q "
          "min/med/max %.3f/%.3f/%.3f"
          % (n_pos, len(ladder), float(deltas.min()),
             float(np.median(deltas)), float(dhat.min()),
             float(np.median(dhat)), float(qr.min()), med_qr,
             float(qr.max())), flush=True)
    scr_lab, _sl = screen(deltas, [r["w"]["tau"] for r in ladder])
    print("    tau-screen of delta (positive subset): %s"
          % scr_lab)
    if n_pos == len(ladder) and n_dfail == 0:
        outcome = ("OUTCOME-A(min delta=%+.4f, min deltahat="
                   "%+.3e, screen %s)"
                   % (float(deltas.min()), float(dhat.min()),
                      scr_lab))
        print("    READING: a genuine new sufficient route -- the "
              "open problem reduces to controlling the "
              "P_G-dominated block D uniformly in h.")
    elif med_qr <= QLOSS_BAR:
        outcome = "OUTCOME-B"
        for r in ladder:
            if r["delta"] <= 0:
                print("    DEFICIT kz %d h %d: |delta|/n %.3f, "
                      "|delta|/mu1 %.3e"
                      % (r["w"]["r2"]["kz"], r["w"]["r2"]["h"],
                         float(-r["delta"] / r["nfr"]),
                         float(-r["delta"]) / r["mu1"]),
                      flush=True)
    else:
        outcome = ("OUTCOME-C(med qbar/q=%.3f, max=%.3f)"
                   % (med_qr, float(qr.max())))
        print("    READING: the Loewner bound loses O(1) -- the "
              "route is honestly dead in this direction; D is a "
              "floor model of B, not an inverse model along b.")
    check("E2 typed: %s" % outcome, True)

    # ----------------------------------------------------------- E3
    section("E3 -- the Woodbury hierarchy (only on OUTCOME-B)")
    kstar_lab = "KSTAR-SKIPPED(frozen: hierarchy runs only on " \
                "OUTCOME-B)"
    if outcome == "OUTCOME-B":
        kstars, hs_k, n_nr = [], [], 0
        wood_ok = True
        for r in ladder:
            if r["delta"] > 0:
                continue
            w = r["w"]
            comps = pg_components(w)
            Dc = r["Dflt"].copy()
            qbar_c = float(r["qbar"])
            n_acc, tried = 0, 0
            reached = False
            for u in comps:
                if tried >= K_HIER:
                    break
                tried += 1
                wv = math.sqrt(0.5) * u
                Dn = Dc + np.outer(wv, wv)
                okd, _ = pd_exact(mat_fr(0.5 * (w["B"] - Dn
                                                + (w["B"]
                                                   - Dn).T)))
                if not okd:
                    continue
                x = np.linalg.solve(Dc, w["b"])
                y = np.linalg.solve(Dc, wv)
                z = float(wv @ x)
                den = 1.0 + float(wv @ y)
                qbar_w = qbar_c - z * z / den
                qbar_d = float(w["b"] @ np.linalg.solve(Dn,
                                                        w["b"]))
                rel = abs(qbar_w - qbar_d) / max(abs(qbar_d),
                                                 1e-30)
                if rel > WOODBURY_TOL:
                    wood_ok = False
                Dc, qbar_c = Dn, qbar_d
                n_acc += 1
                if w["nsc"] - qbar_c > 0:
                    reached = True
                    break
            if reached:
                kstars.append(n_acc)
                hs_k.append(w["r2"]["h"])
                print("    k* kz %d h %d: %d accepted components"
                      % (w["r2"]["kz"], w["r2"]["h"], n_acc),
                      flush=True)
            else:
                n_nr += 1
                print("    k* NOT-REACHED kz %d h %d (tried %d)"
                      % (w["r2"]["kz"], w["r2"]["h"], tried),
                      flush=True)
        check("E3.w WARD Sherman-Morrison identity <= %.0e "
              "relative on every accepted update" % WOODBURY_TOL,
              wood_ok, kill="K2")
        if kstars and n_nr == 0:
            _a, slk, r2k = ols_line(np.log(np.array(hs_k, float)),
                                    np.array(kstars, float))
            kstar_lab = ("KSTAR-ALL-REACHED(max=%d, med=%.1f, "
                         "slope vs log h %+.2f R2 %.2f)"
                         % (max(kstars),
                            float(np.median(kstars)), slk, r2k))
        else:
            kstar_lab = ("KSTAR-NOT-REACHED(%d of %d failing "
                         "steps)" % (n_nr, n_nr + len(kstars)))
    check("E3 typed: %s" % kstar_lab, True)

    # ------------------------------------------------------------ C
    section("C -- controls")
    check("C0.1 WARD truth wall holds (neg(A) = 0 on all rungs)",
          all(r["negA"] == 0 for r in truth), kill="K2")
    n_viol = sum(1 for kz in zones
                 if isinstance(sm_map.get(kz), dict)
                 and sm_map[kz]["negA"] > 0)
    check("C1 WARD smooth world violates (neg(A) > 0 on %d rungs)"
          % n_viol, n_viol > 0, kill="K2")
    rr9 = window_of(CTRL_KZ)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE_ = lambda_eps(N_E)
    nn = np.nonzero(np.abs(lamE_) > 1e-12)[0]
    ctl = {"Epstein": gram_anatomy(
               CTRL_KZ, comb=(np.log(nn.astype(float)),
                              2.0 * lamE_[nn]
                              / np.sqrt(nn.astype(float)))),
           "scramble": gram_anatomy(CTRL_KZ, scramble_seed=1,
                                    keep_chain=True)}
    fired_all = True
    for name, r in ctl.items():
        if not isinstance(r, dict):
            print("    %-9s: chain dies -> fires" % name)
            continue
        f = r["negA"] > 0
        fired_all &= f
        print("    %-9s: tau %+.3e  neg(A) %d -> %s"
              % (name, r["tau"], r["negA"],
                 "FIRES" if f else "SILENT"), flush=True)
    check("C2.1 WARD both controls fire", fired_all, kill="K2")
    n_ref, n_use = 0, 0
    for w in rows:
        if w["B0"] is None:
            continue
        n_use += 1
        ok0, _ = pd_exact(mat_fr(0.5 * (w["B0"] + w["B0"].T)))
        if not ok0:
            n_ref += 1
    check("C3 WARD DECLARED BREAK MODE: exact LDL refuses the "
          "smooth co-block B0 on %d/%d usable steps (>= %d) -- "
          "the Loewner premise B >= D > 0 dies in the smooth "
          "world" % (n_ref, n_use, REFUSE_MIN),
          n_ref >= REFUSE_MIN, kill="K2")
    rsc = ctl["scramble"]
    c4_ok = True
    c4_msg = "scramble core dead -> skipped (disclosed; C3 " \
             "carries the content)"
    if isinstance(rsc, dict) and rsc.get("core_ok") \
            and "S" in rsc and rsc["lamS"] < 0.0:
        c4_ok = rsc["lamS"] < 0.0
        c4_msg = ("lam_min(S_scr) %.3e < 0 -> the scramble core "
                  "breaks the floor" % rsc["lamS"])
    check("C4 WARD scramble breaks the floor: %s" % c4_msg,
          c4_ok, kill="K2")

    labels = dict(loew="LOEWNER-WARDED(%d/%d exact)"
                  % (n_loew, len(ladder)),
                  dfail="DFAIL(%d)" % n_dfail,
                  outcome=outcome, kstar=kstar_lab)
    return finish(labels)


def finish(labels):
    section("V -- FROZEN VERDICT")
    n_pass = sum(1 for _n, okk in CHECKS if okk)
    n_tot = len(CHECKS)
    if KILLS:
        VERDICT = {"K1": "PIPELINE-BROKEN",
                   "K2": "WARD-BROKEN"}[KILLS[0]]
        print("\n  VERDICT: %s" % VERDICT)
    else:
        VERDICT = ("PGSCHUR-MEASURED / %s / %s / %s / %s"
                   % (labels.get("loew", "-"),
                      labels.get("dfail", "-"),
                      labels.get("outcome", "-"),
                      labels.get("kstar", "-")))
        print("\n  VERDICT: %s" % VERDICT)
    print("""
  HONEST FRAME (as frozen): every exact statement above is about
  the float64-computed step matrices (whose entries are exact
  rationals); the D-direction is source-only (P_G plus identity),
  c_dom is a certified scalar of the declared certificate class.
  What this does NOT prove: the interval enclosure of the
  pipeline (concurrent separate work item), n > q uniformity in
  h beyond the reachable surface, or any tail statement.  NO RH
  claim.  No marker moves.""")
    print("\n[TIME] %.1f s   [CHECKS] %d run, %d failed"
          % (time.time() - T0, n_tot, n_tot - n_pass))
    return 0 if n_pass == n_tot else 1


if __name__ == "__main__":
    raise SystemExit(main())
'''

# ------------- frozen probe source tail_abel_transport_probe (embedded BYTE-EXACT, raw string)
_SRC_3 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""tail_abel_transport_probe -- PRIME.PORT.TAIL.ABEL.01
(EXPLORATION ONLY, experiments/; round 63, theorem-engineering on
the RH-side wall, probe 3 -- the CUMULATIVE attack on the tail.
Predecessors (round 62, PRIME.PORT.TAILSIGN.01/.02) closed the
ATOMWISE route: the net tail sign is an arithmetic CANCELLATION
fact over ~2000 deep atoms (tail_B <= 0 at the per-rung first
B-covering cut on 67/67, n_minB med 17, range 5..47), POINTWISE
weight negativity is impossible (terminal lobe positive 67/67,
onset u/(2 alpha) ~ 0.752), the head margin at those cuts is O(1)
(med 0.388, slope +0.113 vs m) -- the ENTIRE h-decay of the wall
margin lives in the net-negative tail -- and the deep weight
GEOMETRY is prime-free (q_{v_sm} reproduces the sign census
67/67).  THE FROZEN IDEA: the right object is the CUMULATIVE
distribution of the prime comb against the DISCRETE DERIVATIVES
of the weight.  2026-08-11.)

THE TRANSPORT (frozen).  Beyond the per-rung first B-covering cut
n_c = n_minB(h), put the tail on the INTEGER grid k = n_c+1 ..
N_g = floor(X), X = e^{2 alpha}: masses a_k = mu_k = 2 Lambda(k)/
sqrt(k) (zero off prime powers; identical floats to the deployed
window atoms, warded), weights w_k = q_v(log k) with q_v the
deployed piecewise-linear per-atom weight functional (lift-race
S0 verbatim; exact identity sum mu_n q_v(u_n) = E_at warded).
Then T_h = sum_k a_k w_k = tail_B(cB) EXACTLY (tie warded), and
the Abel/partial-summation chain (all sums over [J, N], J =
n_c + 1, A1(k) = sum_{n<=k} a_n, A2 = cumsum A1, A3 = cumsum A2):
  order 1:  T = A1(N) w_N - sum_{k<N} A1(k) Dw(k)
  order 2:  T = A1(N) w_N - A2(N-1) Dw(N-1)
                + sum_{k<N-1} A2(k) D2w(k)
  order 3:  T = A1(N) w_N - A2(N-1) Dw(N-1) + A3(N-2) D2w(N-2)
                - sum_{k<N-2} A3(k) D3w(k)
with Dw(k) = w_{k+1} - w_k etc.  Each summation-by-parts moves a
discrete derivative onto the weight (the DUAL KERNEL D^r w --
prime-free for w = q_{v_sm}: an all-integer grid read of a
prime-free function) and a further cumulation onto the primes.

WHAT IS MEASURED (frozen; typed, never kills unless marked WARD):
 (a) SIGN OF THE DUAL KERNEL: exact sign census of D^r w on the
     deep integer grid for r = 1, 2, 3 and BOTH weights (v
     arithmetic; v_sm prime-free, crossing rungs read on their
     carrier branch as in round 62): number of strict sign
     changes (entries below SIGN_EPS * max|D^r w| treated as
     zero, declared), dominant-sign mass share, last-change
     position u/(2 alpha), dominant sign.  Typed
     DUALSIGN-FIXED(r*, N/N, sign) iff some r <= 3 has ZERO sign
     changes on ALL rungs for q_{v_sm}; else DUALSIGN-OPEN with
     the residual census as the named obstruction.
 (b) WHICH CUMULATIVE PRIME QUANTITY (exact identities, WARD):
     A1(k) = 2 sum_{J<=n<=k} Lambda(n)/sqrt(n) is a windowed
     psi-type partial sum: the exact psi-Abel identity
       A1(k) = 2 [ psi_w(k)/sqrt(k)
                   + sum_{m=J}^{k-1} psi_w(m) delta_m ],
       psi_w(m) = sum_{J<=n<=m} Lambda(n),
       delta_m = m^{-1/2} - (m+1)^{-1/2},
     is warded at EVERY k to PSI_ID_WARD.  A^{(r)}(k) =
     2 sum_n binom(k-n+r-1, r-1) Lambda(n)/sqrt(n) is the
     (r-1)-th Riesz/Cesaro mean of the sqrt-smoothed prime comb
     (r = 2: integrated psi-type / Riesz mean; r = 3: twice
     integrated); warded exactly at two frozen spot indices per
     rung (mid, end) to RIESZ_WARD.  The Abel chain itself is
     warded at all three orders to ABEL_WARD relative to the
     declared term scale sc_r = |boundary| + sum |A_r| |D^r w|
     (float bookkeeping; the identity is exact arithmetic).
 (c) ENVELOPES (decisive): the ONLY deployed unconditional
     envelope in the corpus is the Chebyshev table constant
     kappa = 0.038821: |psi(x) - x| <= kappa x at the JUMP POINTS
     of psi(x)/x on [100, 400000] (v563 S0.KAPPA, reproduced here
     as a WARD; B_PSI = 1.03883 noted, not needed).  The
     transport reads psi at ALL integers, where the deficit side
     just before a jump is larger -- AMENDMENT A1 (disclosed
     below): the bound uses the ALL-INTEGER table constant
     KAPPA_INT = max_{100 <= n <= 400000} |psi(n) - n|/n,
     computed in-run from the same deployed table (same finite-
     verification class, strictly weaker = conservative); below
     100 the table-verified exact deviations |psi(n) - n|.  With
     D(m) = (psi(m) - m) - (psi(J-1) - (J-1)) the exact Abel form
     of E1(k) = A1(k) - At1(k), At1(k) = 2 sum 1/sqrt(n) (the
     integer smooth counterpart), gives the PROVABLE pointwise
     bound
       |E1(k)| <= BE1(k) = 2 [ beta(k)/sqrt(k)
                    + sum_{m=J}^{k-1} beta(m) delta_m ],
       beta(m) = bnd(m) + bnd(J-1),
       bnd(x) = KAPPA_INT x (x >= 100) else |psi(x) - x|_table,
     warded in-window (|E1| <= BE1 everywhere, float slack), and
     BE_{r+1} = cumsum BE_r bounds the higher cumulants.  The
     envelope-certified lower bound at order r:
       T >= Ttilde - ERR_r,  Ttilde = sum_k (2/sqrt(k)) w_k,
       ERR_1 = BE1(N)|w_N| + sum BE1|Dw|,
       ERR_2 = BE1(N)|w_N| + BE2(N-1)|Dw(N-1)| + sum BE2|D2w|,
       ERR_3 = ... + BE3(N-2)|D2w(N-2)| + sum BE3|D3w|.
     THE DECISIVE MEASUREMENT: with H = head_B(cB) and the frozen
     halfgap constant C0 = 1/2 (CLI registration, NO-ADJUST --
     recorded comparison only, no constant move), the per-rung
     per-order slack in mu1 units
       slack_r = (H + Ttilde - ERR_r)/mu1 - C0,
       mu1 = 4 sin^2(pi/(2h+1)) = core.parity_mu(h)[0] (warded),
     slack_best = max_r slack_r.  Typed ENV-SUFFICIENT(min
     slack_best) iff slack_best > 0 on ALL rungs (then the tail
     statement closes classically on the surface -- said
     prominently, with constants); else ENV-INSUFFICIENT(min/med
     slack_best, gap law): jackknife slope of log(ERR_best/mu1)
     vs alpha (the gap law) and vs log m (screen).  Context
     diagnostics (printed): the MEASURED arithmetic remainder
     (T - Ttilde)/mu1 and the envelope OVERSHOOT ERR_best /
     |T - Ttilde| -- how much the absolute envelope loses against
     the actual oscillating sum; Ttilde vs the round-60 continuum
     smoothtail(cB) (Euler-Maclaurin tie, info).
 (d) NORMALIZED CONSTANT (recorded, NO adjustment): chat =
     (H + Ttilde)/mu1 -- the smooth-certified part of the halfgap
     statement.  Census: min/med/max, count chat > 0, count
     chat >= C0; the arithmetic remainder share rhat =
     (T - Ttilde)/mu1 min/med/max.  Connection to the frozen
     HALFGAP 1/2 recorded as a comparison only.
 (e) TAU-SCREENS (typed, jackknife, bands PASS |s| <= 0.30 /
     RELOC s >= 0.70 / else AMBIG): log chat vs log m (on the
     chat > 0 subset, disclosed if not all); log(ERR_best/mu1)
     vs log m.

FROZEN PROTOCOL (ladder machinery verbatim from
tail_sign_mechanism_probe.py = round-59/60/62 chain; v_sm
construction verbatim from arithmetic_lift_race_probe S0):

 W   LADDER + WARDS (kill -> PIPELINE-BROKEN / WARD-BROKEN): W1
     faithful ladder >= MIN_RUNGS = 40 (kz 2..KZMAX, H_MIN <= h
     <= HCAP, X <= ATOM_MAX); W2 WARD m_h > 0 everywhere; W3 WARD
     both exact bookkeepings (lift - demand = m AND e_ar + E_at =
     m) <= ID_WARD; W4 WARD atom identities (atom sum = E_at, PNT
     grid = E_sm) <= ID_WARD; W5 WARD split exactness on the full
     scans <= SCAN_WARD; W6 REPRODUCTION round 59/60/62: G > 0
     counts at (50, 100, 200) == (52, 26, 25); n_min in [3, 9];
     shared cut 9 covers N/N; tail_A <= 0 at first covering cut
     N/N; B-covering cuts exist N/N with n_minB med == 17 in
     [5, 47]; tail_B <= 0 at cB N/N; head_B(cB) med within
     HEADB_TOL of 0.388; W7 WARD v_sm branch (<= MAX_CROSS
     crossing rungs, carrier branch overlap >= OV_MIN); W8 WARD
     kappa: core.chebyshev_kappa() within 1e-6 of 0.038821; W9
     WARD mu1 closed form == core.parity_mu(h)[0] exactly and the
     CXLIII shat band: shat = m/mu1 min/med/max within SHAT_TOL
     of (0.502, 1.027, 2.185); W10 WARD grid tie: the integer-
     grid tail equals tail_B(cB) <= TIE_WARD; W11 WARD envelope
     in-window: |E1| <= BE1 everywhere on every rung (float
     slack ENV_SLACK).

 A/B/E/N/T  as (a)/(b)/(c)/(d)/(e) above.

 C   CONTROLS at kz 9 (kill -> WARD-BROKEN if silent): C1
     scramble (seed 1), Epstein x^2+5y^2, smooth comb: each must
     show m < 0 AND zero covering cuts in BOTH senses (round-62
     criterion).  C2 envelope battery from the FIXED declared cut
     CTRL_CUT = 17: the scramble comb (true masses at uniform
     positions, read at integer points against the SAME integer
     smooth counterpart, declared) must VIOLATE the classical
     envelope by a factor >= CTRL_VIOL = 5 (the cumulative
     structure is destroyed -- structurally certain, kill if
     silent); the Epstein and smooth-world envelope factors are
     REPORTED as typed measurements (smooth expected <= 1 --
     quadrature only; Epstein's psi-deviation is a measurement,
     honestly typed either way, no kill).

KILLS: K1 ladder (W1) -> PIPELINE-BROKEN; K2 wards (W2-W11, B
wards, C1/C2-scramble) -> WARD-BROKEN.  All typed A/E/N/T
outcomes are measurements, never kills.

VERDICT (frozen enum): TAILABEL-MEASURED with typed sublabels
DUALSIGN-FIXED(r*, N/N, sign) / DUALSIGN-OPEN(best r, count/N,
med changes, med dominant share),
ABEL-EXACT(max dev) + ARITH-ID(psi dev, riesz dev),
ENV-SUFFICIENT(min slack) / ENV-INSUFFICIENT(min/med slack, gap
slope vs alpha),
CHAT(min/med/max, n >= 1/2),
SCREENS(chat, gap);  else PIPELINE-BROKEN / WARD-BROKEN.

FROZEN BARS: KZMAX = 150; MIN_RUNGS = 40; REF_CUTS = (50, 100,
200); REF_COUNTS = (52, 26, 25); NMIN_LO, NMIN_HI = 3, 9;
NC_SHARED = 9; NB_MED = 17; NB_LO, NB_HI = 5, 47; HEADB_MED =
0.388, HEADB_TOL = 0.01; SHAT_REF = (0.502, 1.027, 2.185),
SHAT_TOL = 1.5e-3; ID_WARD = 1e-10; SCAN_WARD = 1e-9; TIE_WARD =
1e-10; ABEL_WARD = 1e-12 (relative to the declared term scale);
PSI_ID_WARD = 1e-12; RIESZ_WARD = 1e-12; ENV_SLACK = 1e-9;
KAPPA_TOL = 1e-6; KAPPA_INT = in-run all-integer table constant
(amendment A1, reported in W8); MU_WARD = 1e-12; NG_SMOOTH =
6000; OV_MIN =
0.8; MAX_CROSS = 2; SIGN_EPS = 1e-15 (relative); C0 = 1/2
(frozen, NO-ADJUST, recorded comparison only); SLOPE_PASS = 0.30;
SLOPE_RELOC = 0.70; CTRL_KZ = 9; CTRL_CUT = 17; CTRL_VIOL = 5.0;
scramble seed 1; jackknife = full leave-one-out, CI = +- 2SE;
sign decisions on exact grid values (float sign with the declared
relative zero threshold); blocked cumulative sums (block 1024,
deterministic error bound) wherever a cumsum feeds a ward.

SMOKE-RUN DISCLOSURE (2026-08-11, before freezing): TWO smoke
runs disclosed.  SMOKE 1 (SPEC v0, W11 FAILED at min slack
-0.386): the deployed jump-point kappa does NOT majorize the
all-integer psi deviations -- measured all-integer table constant
0.059547 (worst at n = 100, deficit side) vs jump-point 0.038821.
AMENDMENT A1 (disclosed, conservative -- the envelope gets
WEAKER, fail-first preserved): the bound switches to the
ALL-INTEGER table constant KAPPA_INT as frozen in (c) above; the
jump-point kappa stays as the W8 reproduction ward.  SMOKE 2
(22/22, 18.3 s) facts frozen as the context the frozen run must
confirm: (i) DUALSIGN-OPEN at EVERY order: single-signed 0/67 for
r = 1, 2, 3 (q_{v_sm}); med sign changes 3/363/1113 -- r = 1 is
NEARLY fixed (2..3 changes per rung, negative-dominant on 67/67,
dominant mass share med 0.757: the first difference inherits the
2..4 deep slope-sign changes of the weight itself) and each
further difference EXPLODES the census (the lag-knot jumps of the
piecewise-linear weight dominate D^2 w, D^3 w) -- the r = 2
curvature hypothesis is DEAD; (ii) all identity wards at the
1e-15 class (Abel 8.9e-16, psi 1.5e-15, Riesz 3.3e-15, tie
9.7e-15, envelope in-window slack -8.9e-16 = float zero); (iii)
ENV-INSUFFICIENT on 67/67 with best order r = 1 on 67/67 (the
cumulated bounds BE2/BE3 grow faster than the extra difference
decays): slack min/med -3.32e+06/-1.51e+05, ERR_best/mu1 med
1.59e+05, gap law slope vs alpha +1.744 (2SE 0.202, R^2 0.77);
(iv) the MEASURED remainder (T - Ttilde)/mu1 is itself LARGE (med
-9847) and chat = (H + Ttilde)/mu1 correspondingly large (med
+9850, >= 1/2 on 64/67, NEGATIVE on 3 deep rungs) -- the integer
smooth counterpart and the atom comb differ at the cB cut by
O(0.1) absolute ~ 1e4 mu1 units: the halfgap does NOT live at the
(H + Ttilde) split, it lives in the near-cancellation chat + rhat
= shat; envelope overshoot vs the actual oscillating remainder
med 2.0e+01; (v) both screens anti-correlated (chat -1.068 R^2
0.81, gap -1.208 R^2 0.93 -> AMBIG per the frozen bands: budget
and mismatch explode exactly where the margin shrinks); (vi)
controls: C1 3/3, scramble envelope factor 5.99 >= 5 FIRES,
smooth 0.837 <= 1 as declared, Epstein 7.51 OUTSIDE the classical
envelope (measured, typed).  AMENDMENTS beyond A1: NONE -- no
bar, band, tolerance, enum or rule moved after the smoke.

SPEC v1 (2026-08-11, frozen + SHA-hashed before the frozen run):
everything above.  Mechanical concretizations frozen with v1:
(i) the cut is INCLUSIVE at the covering atom (grid starts at
n_c + 1); (ii) N_g = max(floor(X), largest window atom); (iii)
Lambda on the grid read from the deployed core.LAM_TAB (the same
sieve that builds the window atoms; equality of masses warded via
the grid tie W10); (iv) Riesz spot indices per rung: i = (L-1)//2
and i = L-1; (v) the smooth-world control snaps its prime-power
positions to integers by round(exp(u)) (exact); the scramble
control reads its cumulative mass at integer points by
searchsorted (declared above); (vi) runtime ~ 20 s (67 eigh
pairs dominate).

NO-GO COMPLIANCE (frozen): no certified-bound retry, no rank-1
approximation, no Herglotz; no fit where an identity is claimed
(the Abel chain, the psi-Abel identity, the Riesz identity and
the envelope bound are exact wards; all trends are typed
jackknife screens).

NO RH claim: everything here is float-level MEASURED SURFACE
STRUCTURE on the 67-rung ladder; the direction v is computed
per-rung data (the round-62 uniformity boundary applies
verbatim); an ENV-SUFFICIENT outcome would still be a per-rung
surface certificate, not a theorem, and an ENV-INSUFFICIENT
outcome is a measured gap law, not a proof of impossibility.  The
halfgap constant 1/2 is the CLI registration and is NEVER
adjusted here.  No marker moves.

FIREWALL: no zeros, no prime oracles (AST scan; banned ids
zetazero / nzeros / primerange / isprime / primepi / nextprime /
prevprime; Lambda is read from the DEPLOYED window table only);
v563 READ-ONLY; RNG only inside the declared scramble control;
stdout only.

Sources (read-only): v563_paper2_readouts (core; kappa envelope
S0.KAPPA, B_PSI noted); ladder + cut/scan machinery verbatim from
tail_sign_mechanism_probe.py (round 62); q_read + v_sm
construction verbatim from arithmetic_lift_race_probe.py; mu1
normalization from moving_node_second_order_probe.py (CXLIII);
halfgap constant C0 = 1/2 from halfgap_registration_probe.py
(CLI, NO-ADJUST); round-62 censuses (declared reproduction
targets).

Run:
    experiments/tfpt-discovery/.venv/bin/python \
        experiments/tfpt-discovery/tail_abel_transport_probe.py
"""

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

import numpy as np

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

import v563_paper2_readouts as core        # noqa: E402  (READ-ONLY)

KZMAX = 150
MIN_RUNGS = 40
REF_CUTS = (50, 100, 200)
REF_COUNTS = (52, 26, 25)
NMIN_LO, NMIN_HI = 3, 9
NC_SHARED = 9
NB_MED = 17
NB_LO, NB_HI = 5, 47
HEADB_MED = 0.388
HEADB_TOL = 0.01
SHAT_REF = (0.502, 1.027, 2.185)
SHAT_TOL = 1.5e-3
ID_WARD = 1e-10
SCAN_WARD = 1e-9
TIE_WARD = 1e-10
ABEL_WARD = 1e-12
PSI_ID_WARD = 1e-12
RIESZ_WARD = 1e-12
ENV_SLACK = 1e-9
KAPPA_TOL = 1e-6
MU_WARD = 1e-12
NG_SMOOTH = 6000
OV_MIN = 0.8
MAX_CROSS = 2
SIGN_EPS = 1e-15
C0 = 0.5
SLOPE_PASS = 0.30
SLOPE_RELOC = 0.70
CTRL_KZ = 9
CTRL_CUT = 17
CTRL_VIOL = 5.0
KAPPA_LOW_X = 100
BLOCK = 1024
BANNED_IDS = ("zetazero", "nzeros", "primerange", "isprime",
              "primepi", "nextprime", "prevprime")

CHECKS = []
KILLS = []
T0 = time.time()


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


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


def ast_scan(banned):
    src = open(os.path.abspath(__file__), encoding="utf-8").read()
    bad = []
    for node in ast.walk(ast.parse(src)):
        name = None
        if isinstance(node, ast.Name):
            name = node.id
        elif isinstance(node, ast.Attribute):
            name = node.attr
        if name and name.lower() in banned:
            bad.append(name)
    return bad


def ols_line(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    vx = float(np.var(x))
    if vx == 0.0:
        return float(np.mean(y)), 0.0, float("nan")
    b = float(np.cov(x, y, bias=True)[0, 1] / vx)
    a = float(np.mean(y) - b * np.mean(x))
    ss = float(np.sum((y - a - b * x) ** 2))
    st = float(np.sum((y - np.mean(y)) ** 2))
    return a, b, (1.0 - ss / st if st > 0 else float("nan"))


def jack_slope(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    _a, b, r2 = ols_line(x, y)
    n = len(x)
    bb = []
    for i in range(n):
        m = np.ones(n, bool)
        m[i] = False
        bb.append(ols_line(x[m], y[m])[1])
    bb = np.array(bb)
    se = math.sqrt((n - 1) / n * float(np.sum((bb - bb.mean())
                                              ** 2)))
    return b, se, r2


def q_read(W, u, D, M):
    u = np.asarray(u, float)
    i0 = np.floor(u / D).astype(int)
    f = u / D - i0
    val = np.zeros_like(u)
    ok0 = (i0 >= 0) & (i0 < M)
    val[ok0] += (1.0 - f[ok0]) * W[i0[ok0]]
    ok1 = (i0 + 1 >= 0) & (i0 + 1 < M)
    val[ok1] += f[ok1] * W[i0[ok1] + 1]
    refl = u < D
    val[refl] += (1.0 - u[refl] / D) * W[0]
    return -0.5 * val


def smooth_comb(alpha, ng=NG_SMOOTH):
    ug = (np.arange(ng) + 0.5) * (2.0 * alpha / ng)
    mg = 2.0 * np.exp(ug / 2.0) * (2.0 * alpha / ng)
    return ug, mg


def lambda_eps(N):
    """Epstein x^2+5y^2 comb (port_schur_reduction verbatim)."""
    r = np.zeros(N + 1)
    s = int(math.isqrt(N)) + 1
    for x in range(-s, s + 1):
        for y in range(-s, s + 1):
            v = x * x + 5 * y * y
            if 1 <= v <= N:
                r[v] += 1.0
    a = r / 2.0
    lam = np.zeros(N + 1)
    for n in range(2, N + 1):
        acc = a[n] * math.log(n)
        for dd in range(2, n):
            if n % dd == 0:
                acc -= lam[dd] * a[n // dd]
        lam[n] = acc
    return lam


def blocked_cumsum(x):
    """Deterministic error-bounded cumulative sum: within-block
    cumsum (<= BLOCK adds) + block-prefix offsets (<= L/BLOCK
    adds) -- feeds every warded identity."""
    x = np.asarray(x, float)
    n = len(x)
    if n <= BLOCK:
        return np.cumsum(x)
    pad = (-n) % BLOCK
    xb = np.concatenate([x, np.zeros(pad)]).reshape(-1, BLOCK)
    cs = np.cumsum(xb, axis=1)
    off = np.concatenate([[0.0], np.cumsum(cs[:-1, -1])])
    return (cs + off[:, None]).reshape(-1)[:n]


def sign_census(z, uu, alpha):
    """Exact sign census of a dual-kernel array z on the deep
    grid: strict sign changes among entries with |z| >
    SIGN_EPS max|z| (declared zero threshold), dominant-sign
    mass share, last-change scaled position, dominant sign."""
    z = np.asarray(z, float)
    az = np.abs(z)
    mx = float(az.max()) if len(z) else 0.0
    if mx == 0.0:
        return dict(n_changes=0, single=True, dom=1.0,
                    x_last=float("nan"), sign=0)
    mask = az > SIGN_EPS * mx
    s = np.sign(z[mask])
    um = uu[mask]
    ch = np.nonzero(s[1:] * s[:-1] < 0.0)[0]
    pos = float(z[z > 0.0].sum())
    neg = float(-z[z < 0.0].sum())
    dom = max(pos, neg) / max(pos + neg, 1e-300)
    x_last = (float(um[ch[-1] + 1]) / (2.0 * alpha)
              if len(ch) else float("nan"))
    return dict(n_changes=int(len(ch)), single=(len(ch) == 0),
                dom=dom, x_last=x_last,
                sign=(1 if pos >= neg else -1))


def build_rung(kz, comb=None, scramble_seed=None,
               smooth_world=False, need_sm=True):
    """One rung of the lift-race surface with both bookkeepings
    and the full atom-cut scans (tail_sign_mechanism_probe
    verbatim; additionally stores the raw mass vector mu)."""
    try:
        rr = core.build_window(kz, scramble_seed=scramble_seed)
    except Exception:
        return None
    if not (core.H_MIN <= rr["h"] <= core.HCAP):
        return None
    if rr["X"] > core.ATOM_MAX:
        return None
    alpha, M, D, h = rr["alpha"], rr["M"], rr["D"], rr["h"]
    uu = np.asarray(rr["uu"], float)
    mu = 2.0 * np.asarray(rr["lam"], float)
    if smooth_world:
        du = np.zeros(len(uu))
        du[1:-1] = 0.5 * (uu[2:] - uu[:-2])
        du[0] = uu[1] - uu[0]
        du[-1] = uu[-1] - uu[-2]
        mu = 2.0 * np.exp(uu / 2.0) * du
    if comb is not None:
        uu, mu = comb
    c_at = core.atom_lags_at(alpha, M, uu, mu)[0]
    c_ar = np.asarray(core.arch_lags(M, D), float)
    w, V = np.linalg.eigh(core.odd_toeplitz(c_ar + c_at, M))
    v = V[:, 0]
    ug, mg = smooth_comb(alpha)
    c_sm = core.atom_lags_at(alpha, M, ug, mg)[0]
    row = dict(kz=kz, alpha=float(alpha), h=h, M=M, D=D,
               m=float(w[0]), uu=uu, mu=mu, X=float(rr["X"]))
    Wv = core.lag_weights_from_v(v, h)
    e_ar = float(c_ar @ Wv)
    e_t = float(c_at @ Wv)
    e_s = float(c_sm @ Wv)
    qa = mu * q_read(Wv, uu, D, M)
    qg = mg * q_read(Wv, ug, D, M)
    row.update(e_ar=e_ar, e_t=e_t, e_s=e_s, lift=e_t - e_s,
               demand=-(e_ar + e_s),
               dev_at=max(abs(float(qa.sum()) - e_t)
                          / max(abs(e_t), 1e-30),
                          abs(float(qg.sum()) - e_s)
                          / max(abs(e_s), 1e-30)))
    cq = np.cumsum(qa)
    idxg = np.searchsorted(ug, uu, side="right")
    cg_all = np.concatenate([[0.0], np.cumsum(qg)])
    head_err = cq - cg_all[idxg]
    G = head_err - row["demand"]
    tail_A = row["lift"] - head_err
    cert_A = G - np.abs(tail_A)
    head_B = e_ar + cq
    tail_B = float(qa.sum()) - cq
    cert_B = head_B - np.abs(tail_B)
    smoothtail = float(qg.sum()) - cg_all[idxg]
    row.update(G=G, tail_A=tail_A, cert_A=cert_A, head_B=head_B,
               tail_B=tail_B, cert_B=cert_B, smoothtail=smoothtail,
               qa=qa)
    row["Gref"] = {}
    for nc in REF_CUTS:
        ucut = math.log(nc)
        he = (float(qa[uu <= ucut].sum())
              - float(qg[ug <= ucut].sum()))
        row["Gref"][nc] = he - row["demand"]
    if need_sm:
        ws, Vs = np.linalg.eigh(core.odd_toeplitz(c_ar + c_sm, M))
        vsm = Vs[:, 0]
        if float(v @ vsm) < 0:
            vsm = -vsm
        ov4 = [abs(float(v @ Vs[:, j])) for j in range(4)]
        jcar = int(np.argmax(ov4))
        vcar = Vs[:, jcar] * (1.0 if float(v @ Vs[:, jcar]) >= 0
                              else -1.0)
        row.update(ov=float(abs(v @ vsm)), ov4=ov4, jcar=jcar)
        row["Wsm"] = core.lag_weights_from_v(vsm, h)
        row["Wcar"] = core.lag_weights_from_v(vcar, h)
    row["Wv"] = Wv
    return row


# --------------------------------------------------------------- Abel
PSI_FULL = np.cumsum(core.LAM_TAB)                # psi(n) at index n
DEVPSI = np.abs(PSI_FULL - np.arange(len(PSI_FULL), dtype=float))
KAP = core.chebyshev_kappa()
# AMENDMENT A1 (disclosed): the deployed kappa is verified at the
# JUMP POINTS of psi(x)/x; the transport reads psi at ALL integers
# (the deficit side just before a jump is larger).  The envelope
# used is the ALL-INTEGER table constant on [100, ATOM_MAX] --
# same table, same finite verification class, strictly weaker
# (conservative) than the jump-point kappa.
KAPPA_INT = float(np.max(np.where(
    np.arange(len(PSI_FULL)) >= KAPPA_LOW_X,
    DEVPSI / np.maximum(np.arange(len(PSI_FULL), dtype=float),
                        1.0), 0.0)))


def bnd_psi(x):
    """The classical table envelope for |psi(x) - x| at integer
    x: KAPPA_INT x on [100, ATOM_MAX] (all-integer table
    verification, amendment A1), the table-verified exact
    deviation below 100."""
    x = np.asarray(x)
    return np.where(x >= KAPPA_LOW_X, KAPPA_INT * x.astype(float),
                    DEVPSI[np.minimum(x, KAPPA_LOW_X)])


def make_grid(row, nc):
    """The integer transport grid beyond the cut nc, with the
    cumulants A1..A3, the smooth counterpart, the exact psi/Riesz
    identity deviations, and the envelope bound ladder BE1..BE3."""
    alpha = row["alpha"]
    Ng = max(int(math.floor(row["X"])),
             int(np.round(math.exp(float(row["uu"][-1])))))
    kk = np.arange(nc + 1, Ng + 1, dtype=np.int64)
    kf = kk.astype(float)
    ug = np.log(kf)
    lamg = core.LAM_TAB[nc + 1:Ng + 1]
    inv_sq = 1.0 / np.sqrt(kf)
    a = 2.0 * lamg * inv_sq
    L = len(kk)
    A1 = blocked_cumsum(a)
    A2 = blocked_cumsum(A1)
    A3 = blocked_cumsum(A2)
    At1 = blocked_cumsum(2.0 * inv_sq)
    E1 = A1 - At1
    # (b) exact psi-Abel identity for A1, warded at every k
    delta = inv_sq[:-1] - inv_sq[1:]
    psiw = blocked_cumsum(lamg)
    Cpsi = np.concatenate([[0.0],
                           blocked_cumsum(psiw[:-1] * delta)])
    rhs = 2.0 * (psiw * inv_sq + Cpsi)
    dev_psi = float(np.max(np.abs(A1 - rhs))
                    / max(float(np.max(np.abs(A1))), 1.0))
    # (b) Riesz/Cesaro spot-wards for A2, A3 (frozen indices)
    dev_riesz = 0.0
    for i in ((L - 1) // 2, L - 1):
        c = kf[i] - kf[:i + 1] + 1.0
        d2 = float(np.dot(a[:i + 1], c))
        d3 = float(np.dot(a[:i + 1], c * (c + 1.0) / 2.0))
        dev_riesz = max(
            dev_riesz,
            abs(A2[i] - d2) / max(abs(A2[i]), 1.0),
            abs(A3[i] - d3) / max(abs(A3[i]), 1.0))
    # (c) the envelope bound ladder
    beta = bnd_psi(kk) + float(bnd_psi(np.array([nc]))[0])
    Cb = np.concatenate([[0.0],
                         blocked_cumsum(beta[:-1] * delta)])
    BE1 = 2.0 * (beta * inv_sq + Cb)
    BE2 = blocked_cumsum(BE1)
    BE3 = blocked_cumsum(BE2)
    env_min_slack = float(np.min(BE1 - np.abs(E1)))
    return dict(kk=kk, kf=kf, ug=ug, a=a, inv_sq=inv_sq, L=L,
                A1=A1, A2=A2, A3=A3, At1=At1, E1=E1,
                BE1=BE1, BE2=BE2, BE3=BE3,
                dev_psi=dev_psi, dev_riesz=dev_riesz,
                env_min_slack=env_min_slack, alpha=alpha)


def transport(grid, row, W):
    """Per-weight transport: w on the grid, the dual kernels
    D^r w, the exact Abel chain at orders 1..3 (warded), the
    smooth tail Ttilde and the envelope budgets ERR_1..3."""
    L = grid["L"]
    w = q_read(W, grid["ug"], row["D"], row["M"])
    dw1 = w[1:] - w[:-1]
    dw2 = dw1[1:] - dw1[:-1]
    dw3 = dw2[1:] - dw2[:-1]
    a = grid["a"]
    A1, A2, A3 = grid["A1"], grid["A2"], grid["A3"]
    T = float(np.dot(a, w))
    bdry = A1[L - 1] * w[L - 1]
    T1 = bdry - float(np.dot(A1[:L - 1], dw1))
    T2 = (bdry - A2[L - 2] * dw1[L - 2]
          + float(np.dot(A2[:L - 2], dw2)))
    T3 = (bdry - A2[L - 2] * dw1[L - 2]
          + A3[L - 3] * dw2[L - 3]
          - float(np.dot(A3[:L - 3], dw3)))
    sc1 = abs(bdry) + float(np.dot(np.abs(A1[:L - 1]),
                                   np.abs(dw1)))
    sc2 = (abs(bdry) + abs(A2[L - 2] * dw1[L - 2])
           + float(np.dot(np.abs(A2[:L - 2]), np.abs(dw2))))
    sc3 = (abs(bdry) + abs(A2[L - 2] * dw1[L - 2])
           + abs(A3[L - 3] * dw2[L - 3])
           + float(np.dot(np.abs(A3[:L - 3]), np.abs(dw3))))
    dev_abel = max(abs(T1 - T) / max(sc1, 1.0),
                   abs(T2 - T) / max(sc2, 1.0),
                   abs(T3 - T) / max(sc3, 1.0))
    Tt = float(np.dot(2.0 * grid["inv_sq"], w))
    BE1, BE2, BE3 = grid["BE1"], grid["BE2"], grid["BE3"]
    e_bdry = BE1[L - 1] * abs(w[L - 1])
    ERR1 = e_bdry + float(np.dot(BE1[:L - 1], np.abs(dw1)))
    ERR2 = (e_bdry + BE2[L - 2] * abs(dw1[L - 2])
            + float(np.dot(BE2[:L - 2], np.abs(dw2))))
    ERR3 = (e_bdry + BE2[L - 2] * abs(dw1[L - 2])
            + BE3[L - 3] * abs(dw2[L - 3])
            + float(np.dot(BE3[:L - 3], np.abs(dw3))))
    cens = [sign_census(dz, grid["ug"][:len(dz)], grid["alpha"])
            for dz in (dw1, dw2, dw3)]
    return dict(w=None, T=T, Tt=Tt, dev_abel=dev_abel,
                ERR=(ERR1, ERR2, ERR3), cens=cens)


def main():
    section("PRIME.PORT.TAIL.ABEL.01 -- the cumulative (Abel-"
            "transport) attack on the tail (EXPLORATION ONLY)")
    print("    FROZEN_SPEC SHA-256 = %s"
          % hashlib.sha256(__doc__.encode("utf-8")).hexdigest())
    print("    NO RH claim; no marker moves; C0 = 1/2 is the CLI "
          "registration, NO-ADJUST.")
    print("\nS0 -- firewall")
    check("S0.1 AST firewall clean", not ast_scan(BANNED_IDS))

    # ------------------------------------------------------------ W
    section("W -- the faithful ladder + wards")
    rungs = []
    for kz in range(2, KZMAX + 1):
        row = build_rung(kz)
        if row is not None:
            rungs.append(row)
    rungs.sort(key=lambda r: (r["h"], r["kz"]))
    check("W1 faithful ladder >= %d rungs" % MIN_RUNGS,
          len(rungs) >= MIN_RUNGS,
          "%d rungs, h %d..%d  [%.1f s]"
          % (len(rungs), rungs[0]["h"], rungs[-1]["h"],
             time.time() - T0), kill="K1")
    if KILLS:
        return finish({})
    N = len(rungs)
    check("W2 WARD truth margin m_h > 0 on every rung (min %.3e)"
          % min(r["m"] for r in rungs),
          all(r["m"] > 0 for r in rungs), kill="K2")
    dev_bk = max(max(abs((r["lift"] - r["demand"]) - r["m"]),
                     abs((r["e_ar"] + r["e_t"]) - r["m"]))
                 / max(1.0, abs(r["m"])) for r in rungs)
    check("W3 WARD both exact bookkeepings: max dev %.2e <= %.0e"
          % (dev_bk, ID_WARD), dev_bk <= ID_WARD, kill="K2")
    dev_at = max(r["dev_at"] for r in rungs)
    check("W4 WARD atom identities (atom sum = E_at, PNT grid = "
          "E_sm): max rel dev %.2e <= %.0e" % (dev_at, ID_WARD),
          dev_at <= ID_WARD, kill="K2")
    dev_sc = 0.0
    for r in rungs:
        sc = max(float(np.max(np.abs((r["head_B"] + r["tail_B"])
                                     - r["m"]))),
                 float(np.max(np.abs((r["G"] + r["tail_A"])
                                     - r["m"]))),
                 float(np.max(np.abs(r["G"] - r["head_B"]
                                     - r["smoothtail"]))))
        dev_sc = max(dev_sc, sc / max(1.0, abs(r["e_t"])))
    check("W5 WARD split exactness on the full scans: max rel "
          "dev %.2e <= %.0e" % (dev_sc, SCAN_WARD),
          dev_sc <= SCAN_WARD, kill="K2")
    # round-59/60/62 reproduction
    cnts = tuple(int(np.sum(np.array(
        [r["Gref"][nc] for r in rungs]) > 0)) for nc in REF_CUTS)
    n_min, nB_min, icBs, tB_neg = [], [], [], 0
    for r in rungs:
        nn = np.round(np.exp(r["uu"])).astype(int)
        covA = r["cert_A"] > 0.0
        i0 = int(np.argmax(covA)) if bool(np.any(covA)) else -1
        n_min.append(int(nn[i0]) if i0 >= 0 else -1)
        covB = r["cert_B"] > 0.0
        icB = int(np.argmax(covB)) if bool(np.any(covB)) else -1
        icBs.append(icB)
        nB_min.append(int(nn[icB]) if icB >= 0 else -1)
        if icB >= 0 and float(r["tail_B"][icB]) <= 0.0:
            tB_neg += 1
    i9s = [int(np.searchsorted(r["uu"],
                               math.log(NC_SHARED) + 1e-12,
                               side="right")) - 1 for r in rungs]
    cov9 = sum(1 for r, i9 in zip(rungs, i9s)
               if i9 >= 0 and r["cert_A"][i9] > 0)
    tA_neg = sum(1 for r in rungs if bool(np.any(r["cert_A"] > 0))
                 and r["tail_A"][int(np.argmax(
                     r["cert_A"] > 0))] <= 0.0)
    covB_n = sum(1 for i in icBs if i >= 0)
    hBc = np.array([float(r["head_B"][i])
                    for r, i in zip(rungs, icBs)])
    medB = float(np.median([n for n in nB_min if n > 0]))
    ok_rep = (cnts == REF_COUNTS
              and all(NMIN_LO <= nm <= NMIN_HI for nm in n_min)
              and cov9 == N and tA_neg == N and covB_n == N
              and medB == NB_MED
              and min(nB_min) >= NB_LO and max(nB_min) <= NB_HI
              and tB_neg == N
              and abs(float(np.median(hBc)) - HEADB_MED)
              <= HEADB_TOL)
    check("W6 REPRODUCTION 59/60/62: G > 0 at %s = %s == %s; "
          "n_min in [%d, %d]; cut 9 covers %d/%d; tail_A <= 0 "
          "%d/%d; B-cuts exist %d/%d, n_minB med %d in [%d, %d]; "
          "tail_B <= 0 at cB %d/%d; head_B(cB) med %.3f ~ %.3f"
          % (REF_CUTS, cnts, REF_COUNTS, NMIN_LO, NMIN_HI, cov9,
             N, tA_neg, N, covB_n, N, int(medB), min(nB_min),
             max(nB_min), tB_neg, N, float(np.median(hBc)),
             HEADB_MED), ok_rep, kill="K2")
    n_cross = sum(1 for r in rungs if r["ov"] < OV_MIN)
    cross_ok = all(max(r["ov4"]) >= OV_MIN for r in rungs
                   if r["ov"] < OV_MIN)
    check("W7 WARD v_sm branch: %d crossing rung(s) (%s; ward <= "
          "%d), carrier ok"
          % (n_cross,
             ", ".join("kz%d ov %.4f" % (r["kz"], r["ov"])
                       for r in rungs if r["ov"] < OV_MIN)
             or "none", MAX_CROSS),
          n_cross <= MAX_CROSS and cross_ok, kill="K2")
    check("W8 WARD kappa: chebyshev_kappa() = %.6f within %.0e "
          "of %.6f (v563 S0.KAPPA, jump points; ALL-INTEGER "
          "table envelope KAPPA_INT = %.6f used for the bound, "
          "amendment A1; B_PSI = %.5f noted)"
          % (KAP, KAPPA_TOL, core.KAPPA_REF, KAPPA_INT,
             core.B_PSI),
          abs(KAP - core.KAPPA_REF) <= KAPPA_TOL, kill="K2")
    mu1 = np.array([float(core.parity_mu(r["h"])[0])
                    for r in rungs])
    mu1_cf = np.array([4.0 * math.sin(math.pi
                                      / (2 * r["h"] + 1)) ** 2
                       for r in rungs])
    dev_mu = float(np.max(np.abs(mu1 - mu1_cf)
                          / np.maximum(mu1, 1e-300)))
    mm = np.array([r["m"] for r in rungs])
    shat = mm / mu1
    s3 = (float(np.min(shat)), float(np.median(shat)),
          float(np.max(shat)))
    ok_shat = all(abs(s3[i] - SHAT_REF[i]) <= SHAT_TOL
                  for i in range(3))
    check("W9 WARD mu1 closed form (dev %.1e) + CXLIII shat band "
          "min/med/max %.4f/%.4f/%.4f ~ %s"
          % (dev_mu, s3[0], s3[1], s3[2], SHAT_REF),
          dev_mu <= MU_WARD and ok_shat, kill="K2")
    if KILLS:
        return finish({})

    # ---------------------------------------------- the transports
    grids, trv, trs = [], [], []
    for r, icB, nc in zip(rungs, icBs, nB_min):
        g = make_grid(r, nc)
        grids.append(g)
        trv.append(transport(g, r, r["Wv"]))
        Ws = r["Wcar"] if r["ov"] < OV_MIN else r["Wsm"]
        trs.append(transport(g, r, Ws))
    tie = max(abs(t["T"] - float(r["tail_B"][i]))
              / max(1.0, abs(float(r["tail_B"][i])))
              for t, r, i in zip(trv, rungs, icBs))
    check("W10 WARD grid tie: integer-grid tail == tail_B(cB) "
          "max rel dev %.2e <= %.0e  [%.1f s]"
          % (tie, TIE_WARD, time.time() - T0),
          tie <= TIE_WARD, kill="K2")
    env_slk = min(g["env_min_slack"] for g in grids)
    check("W11 WARD envelope in-window: |E1| <= BE1 everywhere "
          "on every rung (min slack %+.3e >= %.0e)"
          % (env_slk, -ENV_SLACK), env_slk >= -ENV_SLACK,
          kill="K2")
    if KILLS:
        return finish({})

    # ------------------------------------------------------------ A
    section("A -- (a) THE DUAL KERNEL SIGN LADDER: D^r w on the "
            "deep integer grid, r = 1, 2, 3")
    print("    q_{v_sm} is PRIME-FREE; its integer-grid "
          "differences are a purely classical object.  Zero "
          "threshold %.0e * max|D^r w| (declared)." % SIGN_EPS)
    lab_a = None
    fix_r = 0
    for name, trl in (("v (arithmetic)", trv),
                      ("v_sm (prime-free)", trs)):
        for ri in range(3):
            cc = [t["cens"][ri] for t in trl]
            n_single = sum(1 for c in cc if c["single"])
            chg = np.array([c["n_changes"] for c in cc])
            dom = np.array([c["dom"] for c in cc])
            xl = np.array([c["x_last"] for c in cc])
            xl = xl[np.isfinite(xl)]
            sgn = np.array([c["sign"] for c in cc])
            print("    %-18s r=%d: single-signed %2d/%d; sign "
                  "changes med %4d (%d..%d); dominant share med "
                  "%.3f (sign - on %d/%d); last change x = u/"
                  "(2a) med %.3f"
                  % (name, ri + 1, n_single, N,
                     int(np.median(chg)), int(chg.min()),
                     int(chg.max()), float(np.median(dom)),
                     int(np.sum(sgn < 0)), N,
                     float(np.median(xl)) if len(xl)
                     else float("nan")), flush=True)
            if (name.startswith("v_sm") and n_single == N
                    and fix_r == 0):
                fix_r = ri + 1
                lab_a = ("DUALSIGN-FIXED(r=%d, %d/%d, sign %+d)"
                         % (fix_r, n_single, N,
                            int(np.sign(np.sum(sgn)))))
    if lab_a is None:
        best = max(range(3), key=lambda ri: sum(
            1 for t in trs if t["cens"][ri]["single"]))
        nb = sum(1 for t in trs if t["cens"][best]["single"])
        lab_a = ("DUALSIGN-OPEN(best r=%d: %d/%d single; med "
                 "changes r1/r2/r3 = %d/%d/%d)"
                 % (best + 1, nb, N,
                    int(np.median([t["cens"][0]["n_changes"]
                                   for t in trs])),
                    int(np.median([t["cens"][1]["n_changes"]
                                   for t in trs])),
                    int(np.median([t["cens"][2]["n_changes"]
                                   for t in trs]))))
        print("    ==> NO order r <= 3 fixes the dual kernel's "
              "sign: the residual sign-change census above IS "
              "the named obstruction of the cumulative route")
    check("A.1 typed (a): %s" % lab_a, True)

    # ------------------------------------------------------------ B
    section("B -- (b) THE ABEL IDENTITY CHAIN + the arithmetic "
            "identity of A^{(r)} (WARDS)")
    dev_ab = max(t["dev_abel"] for t in trv + trs)
    check("B.1 WARD Abel chain exact at orders 1..3, both "
          "weights, all rungs: max rel dev %.2e <= %.0e"
          % (dev_ab, ABEL_WARD), dev_ab <= ABEL_WARD, kill="K2")
    dev_ps = max(g["dev_psi"] for g in grids)
    check("B.2 WARD psi-Abel identity (A1 = windowed psi-type "
          "partial sum, exact at every k): max rel dev %.2e <= "
          "%.0e" % (dev_ps, PSI_ID_WARD),
          dev_ps <= PSI_ID_WARD, kill="K2")
    dev_rz = max(g["dev_riesz"] for g in grids)
    check("B.3 WARD Riesz/Cesaro identity (A^{(r)}(k) = 2 sum "
          "binom(k-n+r-1, r-1) Lambda(n)/sqrt(n), r = 2, 3, "
          "frozen spot indices): max rel dev %.2e <= %.0e"
          % (dev_rz, RIESZ_WARD), dev_rz <= RIESZ_WARD,
          kill="K2")
    print("    ==> A^{(1)} = smoothed (1/sqrt) prime counting "
          "in the window; A^{(2)} = its Riesz mean (integrated "
          "psi-type); A^{(3)} = twice integrated -- verified as "
          "EXACT identities, not asymptotics")
    lab_b = ("ABEL-EXACT(%.1e) + ARITH-ID(psi %.1e, riesz %.1e)"
             % (dev_ab, dev_ps, dev_rz))
    if KILLS:
        return finish({})

    # ------------------------------------------------------------ E
    section("E -- (c) THE ENVELOPE CERTIFICATE (decisive): does "
            "the classical table envelope (KAPPA_INT = %.6f) "
            "close the tail on the surface?" % KAPPA_INT)
    H = hBc
    Tarr = np.array([t["T"] for t in trv])
    Tt = np.array([t["Tt"] for t in trv])
    ERR = np.array([t["ERR"] for t in trv])       # (N, 3)
    slack = ((H + Tt - ERR.T) / mu1 - C0).T       # (N, 3)
    slack_best = slack.max(axis=1)
    best_r = slack.argmax(axis=1) + 1
    chat = (H + Tt) / mu1
    rhat = (Tarr - Tt) / mu1
    ovsh = ERR.min(axis=1) / np.maximum(np.abs(Tarr - Tt), 1e-300)
    st_cB = np.array([float(r["smoothtail"][i])
                      for r, i in zip(rungs, icBs)])
    print("    kz   h    m_h       mu1       nc  H+Tt/mu1   "
          "(T-Tt)/mu1  ERR1/mu1   ERR2/mu1   ERR3/mu1   slack")
    for i, r in enumerate(rungs):
        print("    %-4d %-4d %.3e %.3e %-3d %+.3e %+.3e %.3e "
              "%.3e %.3e %+.3e"
              % (r["kz"], r["h"], r["m"], mu1[i], nB_min[i],
                 chat[i], rhat[i], ERR[i, 0] / mu1[i],
                 ERR[i, 1] / mu1[i], ERR[i, 2] / mu1[i],
                 slack_best[i]), flush=True)
    n_pos = int(np.sum(slack_best > 0.0))
    cnt_r = [int(np.sum(best_r == ri)) for ri in (1, 2, 3)]
    print("\n    best order census r=1/2/3: %d/%d/%d; envelope "
          "budget ERR_best/mu1 min/med/max %.2e/%.2e/%.2e"
          % (cnt_r[0], cnt_r[1], cnt_r[2],
             float(np.min(ERR.min(axis=1) / mu1)),
             float(np.median(ERR.min(axis=1) / mu1)),
             float(np.max(ERR.min(axis=1) / mu1))))
    print("    MEASURED arithmetic remainder (T - Ttilde)/mu1 "
          "min/med/max %+.2f/%+.2f/%+.2f; envelope OVERSHOOT "
          "ERR_best/|T - Ttilde| med %.2e -- the budget vs the "
          "actual oscillating sum"
          % (float(np.min(rhat)), float(np.median(rhat)),
             float(np.max(rhat)), float(np.median(ovsh))))
    print("    integer smooth tail vs round-60 continuum "
          "smoothtail(cB): med |Ttilde - st| = %.2e (Euler-"
          "Maclaurin tie, info)"
          % float(np.median(np.abs(Tt - st_cB))))
    aa = np.array([r["alpha"] for r in rungs])
    if n_pos == N:
        slE, seE, r2E = jack_slope(aa, np.log(slack_best))
        lab_e = "ENV-SUFFICIENT(min slack %+.3e)" % float(
            np.min(slack_best))
        print("    ==> THE TAIL STATEMENT CLOSES CLASSICALLY ON "
              "THE SURFACE: H + Ttilde - ERR >= %.1f mu1 on "
              "%d/%d rungs (min slack %+.3e; KAPPA_INT = %.6f, "
              "C0 = %.1f frozen)" % (C0, n_pos, N,
                                     float(np.min(slack_best)),
                                     KAPPA_INT, C0))
    else:
        gap = ERR.min(axis=1) / mu1
        slE, seE, r2E = jack_slope(aa, np.log(gap))
        lab_e = ("ENV-INSUFFICIENT(slack min/med %+.2e/%+.2e, "
                 "gap law %+.3f)"
                 % (float(np.min(slack_best)),
                    float(np.median(slack_best)), slE))
        print("    ==> ENVELOPES INSUFFICIENT on %d/%d rungs: "
              "GAP LAW log(ERR_best/mu1) = %+.3f alpha + c "
              "(2SE %.3f, R^2 %.2f) -- the classical budget "
              "grows ~ e^{%.2f alpha} while the need chat - %.1f "
              "is O(1)"
              % (N - n_pos, N, slE, 2 * seE, r2E, slE, C0))
    check("E.1 typed (c): %s (per-order slacks valid "
          "certificates each; slack_best = max_r)" % lab_e, True)

    # ------------------------------------------------------------ N
    section("N -- (d) THE NORMALIZED CONSTANT vs the frozen "
            "1/2 (recorded, NO adjustment)")
    n_ch = int(np.sum(chat >= C0))
    print("    chat = (H + Ttilde)/mu1: min/med/max %.3f/%.3f/"
          "%.3f; chat > 0 on %d/%d; chat >= %.1f on %d/%d"
          % (float(np.min(chat)), float(np.median(chat)),
             float(np.max(chat)), int(np.sum(chat > 0)), N, C0,
             n_ch, N))
    print("    rhat = (T - Ttilde)/mu1: min/med/max %+.3f/%+.3f/"
          "%+.3f  (the arithmetic remainder the envelope must "
          "control; shat = chat + rhat, warded band above)"
          % (float(np.min(rhat)), float(np.median(rhat)),
             float(np.max(rhat))))
    print("    recorded comparison to the CLI halfgap: shat - "
          "1/2 min %+.2e (registration margin); the smooth-"
          "certified part chat clears 1/2 on %d/%d -- NO "
          "constant is moved" % (float(np.min(shat - C0)), n_ch,
                                 N))
    lab_n = ("CHAT(%.2f/%.2f/%.2f, >=1/2 on %d/%d)"
             % (float(np.min(chat)), float(np.median(chat)),
                float(np.max(chat)), n_ch, N))
    check("N.1 typed (d): %s" % lab_n, True)

    # ------------------------------------------------------------ T
    section("T -- (e) TAU-SCREENS (jackknife, typed)")
    okc = chat > 0
    slC, seC, r2C = jack_slope(np.log(mm[okc]),
                               np.log(chat[okc]))
    scr_c = ("PASS" if abs(slC) <= SLOPE_PASS else
             "RELOC" if slC >= SLOPE_RELOC else "AMBIG")
    print("    screen log chat vs log m (on %d/%d with chat > 0"
          "%s): slope %+.3f +- 2SE %.3f (R^2 %.2f) -> %s"
          % (int(np.sum(okc)), N,
             "" if bool(np.all(okc)) else " -- subset disclosed",
             slC, 2 * seC, r2C, scr_c))
    gap = ERR.min(axis=1) / mu1
    slG, seG, r2G = jack_slope(np.log(mm), np.log(gap))
    scr_g = ("PASS" if abs(slG) <= SLOPE_PASS else
             "RELOC" if slG >= SLOPE_RELOC else "AMBIG")
    print("    screen log(ERR_best/mu1) vs log m: slope %+.3f "
          "+- 2SE %.3f (R^2 %.2f) -> %s"
          % (slG, 2 * seG, r2G, scr_g))
    lab_t = ("SCREENS(chat %+.2f %s, gap %+.2f %s)"
             % (slC, scr_c, slG, scr_g))
    check("T.1 typed (e): %s" % lab_t, True)

    # ------------------------------------------------------------ C
    section("C -- controls on this surface at kz %d" % CTRL_KZ)
    rr9 = core.build_window(CTRL_KZ)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE_ = lambda_eps(N_E)
    nnE = np.nonzero(np.abs(lamE_) > 1e-12)[0]
    ctl = {}
    ctl["Epstein"] = build_rung(CTRL_KZ, comb=(
        np.log(nnE.astype(float)),
        2.0 * lamE_[nnE] / np.sqrt(nnE.astype(float))),
        need_sm=False)
    ctl["scramble"] = build_rung(CTRL_KZ, scramble_seed=1,
                                 need_sm=False)
    ctl["smooth"] = build_rung(CTRL_KZ, smooth_world=True,
                               need_sm=False)
    fired = True
    for name, r in ctl.items():
        if r is None:
            print("    %-9s: rung dies -> fires" % name)
            continue
        ncovA = int(np.sum(r["cert_A"] > 0))
        ncovB = int(np.sum(r["cert_B"] > 0))
        f = (r["m"] < 0) and ncovA == 0 and ncovB == 0
        fired &= f
        print("    %-9s: m %+.3e  covering cuts A/B %d/%d -> %s"
              % (name, r["m"], ncovA, ncovB,
                 "FIRES" if f else "SILENT"), flush=True)
    check("C1 WARD all three controls fire (m < 0 and zero "
          "coverage in BOTH senses)", fired, kill="K2")
    # C2 -- the envelope battery from the fixed cut CTRL_CUT
    facs = {}
    for name in ("Epstein", "smooth", "scramble"):
        r = ctl[name]
        Ng = int(math.floor(r["X"]))
        kk = np.arange(CTRL_CUT + 1, Ng + 1, dtype=np.int64)
        kf = kk.astype(float)
        inv_sq = 1.0 / np.sqrt(kf)
        delta = inv_sq[:-1] - inv_sq[1:]
        beta = (bnd_psi(kk)
                + float(bnd_psi(np.array([CTRL_CUT]))[0]))
        Cb = np.concatenate(
            [[0.0], blocked_cumsum(beta[:-1] * delta)])
        BE1 = 2.0 * (beta * inv_sq + Cb)
        At1 = blocked_cumsum(2.0 * inv_sq)
        if name == "scramble":
            cmass = np.concatenate([[0.0],
                                    blocked_cumsum(r["mu"])])
            idx = np.searchsorted(r["uu"], np.log(kf),
                                  side="right")
            i0 = int(np.searchsorted(
                r["uu"], math.log(CTRL_CUT) + 1e-12,
                side="right"))
            A1c = cmass[idx] - cmass[i0]
        else:
            nn = np.round(np.exp(r["uu"])).astype(int)
            ag = np.zeros(Ng + 1)
            keep = nn <= Ng
            np.add.at(ag, nn[keep], r["mu"][keep])
            A1c = blocked_cumsum(ag[CTRL_CUT + 1:Ng + 1])
        facs[name] = float(np.max(np.abs(A1c - At1) / BE1))
        print("    %-9s envelope factor max |E1|/BE1 = %.3g"
              % (name, facs[name]), flush=True)
    check("C2 WARD scramble violates the classical envelope: "
          "factor %.3g >= %.1f (cumulative structure destroyed)"
          % (facs["scramble"], CTRL_VIOL),
          facs["scramble"] >= CTRL_VIOL, kill="K2")
    lab_c = ("CTRL-ENV(scramble %.2g FIRES, smooth %.2g%s, "
             "Epstein %.2g %s -- measured, typed)"
             % (facs["scramble"], facs["smooth"],
                " <= 1 as declared" if facs["smooth"] <= 1.0
                else " > 1 (recorded)", facs["Epstein"],
                "inside" if facs["Epstein"] <= 1.0 else
                "OUTSIDE"))
    check("C3 typed control battery: %s" % lab_c, True)

    return finish(dict(a=lab_a, b=lab_b, e=lab_e, n=lab_n,
                       t=lab_t, c=lab_c))


def finish(labels):
    section("V -- FROZEN VERDICT")
    n_pass = sum(1 for _n, okk in CHECKS if okk)
    n_tot = len(CHECKS)
    if KILLS:
        VERDICT = {"K1": "PIPELINE-BROKEN",
                   "K2": "WARD-BROKEN"}[KILLS[0]]
        print("\n  VERDICT: %s" % VERDICT)
    else:
        VERDICT = ("TAILABEL-MEASURED / %(a)s / %(b)s / %(e)s / "
                   "%(n)s / %(t)s / %(c)s" % labels)
        print("\n  VERDICT: %s" % VERDICT)
    print("""
  HONEST FRAME (as frozen): the Abel chain and the arithmetic
  identity of the cumulants are EXACT bookkeeping; the dual-kernel
  sign census, the envelope slack ladder and the normalized
  constant are MEASURED SURFACE STRUCTURE at float level.  An
  insufficient envelope is a measured gap law, not an
  impossibility proof; a sufficient one would still be a per-rung
  surface certificate, not a theorem.  The halfgap constant 1/2
  (CLI) is never adjusted here.  NO RH claim.  No marker moves.""")
    print("\n[TIME] %.1f s   [CHECKS] %d run, %d failed"
          % (time.time() - T0, n_tot, n_tot - n_pass))
    return 0 if n_pass == n_tot else 1


if __name__ == "__main__":
    raise SystemExit(main())
'''

# ------------- frozen probe source tail_segment_split_probe (embedded BYTE-EXACT, raw string)
_SRC_4 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""tail_segment_split_probe -- PRIME.PORT.TAIL.SEGSPLIT.01
(EXPLORATION ONLY, experiments/; round 63, theorem-engineering on
the RH-side wall, probe 4 -- the SEGMENT-SPLIT attack on the
tail, direct successor of PRIME.PORT.TAIL.ABEL.01 (note CLII).
What the predecessor left: the Abel transport of the B-cover tail
onto the integer grid is EXACT (1e-15 class) and the cumulants
are named psi/Riesz objects; NO order r <= 3 fixes the dual
kernel sign globally (census med 3/363/1113 for r = 1/2/3); the
honest all-integer classical envelope (KAPPA_INT = 0.059547,
amendment A1 there) is insufficient GLOBALLY on 67/67 with gap
law e^{+1.744 alpha} (slack med -1.5e5 mu1) -- the missing
ingredient is oscillation bookkeeping, not constants; BUT the
r = 1 dual kernel is NEARLY single-signed: 2..3 deep sign
changes per rung, negative-dominant on 67/67, and the change
positions are CLASSICAL (prime-free -- q_{v_sm} reproduces the
census).  THE FROZEN IDEA: split the deep window at the r = 1
dual kernel's finitely many breakpoints into segments of fixed
kernel sign.  On each segment the transported tail pairs a
SEGMENT-LOCAL cumulative prime mass B_j(k) >= 0 against a
single-signed kernel, so the needed windowed-psi control per
segment is ONE-SIDED -- and on negative-kernel segments the
pairing is NONNEGATIVE EXACTLY (a free floor).  The global
oscillation bookkeeping decomposes into (i) per-segment
one-sided windowed psi statements plus (ii) boundary terms
reading the cumulative mass at the 2..3 classical breakpoints.
2026-08-11.)

THE SEGMENT IDENTITY (frozen).  Grid, masses, cumulants A1/At1/
E1, envelope table machinery, ladder and wards verbatim from the
predecessor (cut nc = n_minB(h); grid k = nc+1 .. N_g; masses
a_k = 2 Lambda(k)/sqrt(k); weight w = q_v on the grid; dual
kernel Dw(k) = w_{k+1} - w_k).  SEGMENTS: maximal runs of fixed
strict sign of Dw among entries with |Dw| > SIGN_EPS max|Dw|
(sub-threshold entries join the current segment -- the identical
threshold semantics as the predecessor's census; segments are
taken from the TRUE kernel q_v so the fixed sign is exact by
construction, and their CLASSICALITY is verified against
q_{v_sm} in (a)).  With segments j = 1..p, [s_j, e_j]
partitioning the Dw-index range, right breakpoints b_{j+1} =
s_{j+1} (b_{p+1} = the last grid point) and segment masses
m_j = A1(e_j) - A1(s_j - 1) (A1(-1) = 0):
  T = sum_j [ m_j w(b_{j+1}) - sum_{k in seg j} B_j(k) Dw(k) ],
  B_j(k) = A1(k) - A1(s_j - 1) >= 0
-- the telescoped regrouping of the order-1 Abel form: each
segment contributes ONE boundary read (its cumulative mass at
its right breakpoint) plus an in-segment pairing of the
segment-local cumulant against the single-signed kernel.  The
raw per-segment boundary terms bt_j = -A1(s_j - 1)(w(e_j + 1) -
w(s_j)) are measured separately for the telescoping census (d).

WHAT IS MEASURED (frozen; typed, never kills unless marked WARD):
 (a) BREAKPOINT CENSUS: per rung, the segment count and the
     breakpoint positions x = u/(2 alpha) from BOTH kernels
     (q_v true; q_{v_sm} prime-free, crossing rungs on their
     carrier branch as in round 62): count histogram, per-rung
     count agreement v vs v_sm, max matched-position deviation
     |dx| where counts agree, first/last position medians, drift
     law: jackknife slope of the LAST breakpoint position vs
     alpha (and the first; CXLVIII expectation: flat), dominant
     sign share (negative-dominant expectation 67/67).  Typed
     BP-CENSUS(...) + CLASSICAL-BP(match n/N, med/max |dx|).
 (b) EXACT SEGMENT IDENTITY (WARD): the telescoped identity
     above vs T = sum a_k w_k on every rung, relative to the
     declared term scale sum_j (|m_j w_b| + sum |B_j Dw|), ward
     <= SEG_ID_WARD; the same identity on the SMOOTH masses
     (At1/Bt_j) vs Ttilde = sum (2/sqrt(k)) w_k, ward <=
     SEG_ID_WARD; the regrouping ward: sum_j bt_j + A1(N) w_N ==
     sum_j m_j w(b_{j+1}) exactly (same scale).
 (c) ONE-SIDED DEMAND + SEGMENT-WISE ENVELOPE (decisive): on
     segment j with sign sigma_j the error term is -sum E_j Dw,
     E_j(k) = E1(k) - E1(s_j - 1) the SEGMENT-ANCHORED windowed
     psi deviation (the windowed psi sum starts at the segment,
     not at the cut): sigma_j = -1 needs ONLY the lower side
     E_j >= -BE_j (the windowed psi mass may not UNDERSHOOT),
     sigma_j = +1 needs ONLY the upper side E_j <= +BE_j.  The
     provable segment envelope (same argument as the
     predecessor's, anchored at the segment start):
       |E_j(k)| <= BE_j(k) = 2 [ beta_j(k)/sqrt(k)
                    + sum_{m=s_j}^{k-1} beta_j(m) delta_m ],
       beta_j(m) = bnd(m) + bnd(n(s_j) - 1),
     bnd = the all-integer table bound (KAPPA_INT x above 100,
     exact table deviations below; predecessor amendment A1
     adopted as deployed here), warded in-window on every
     segment of every rung (WARD).  Segment certificates:
       env_j  = sum BE_j |Dw|,   ts_j = -sum Bt_j Dw,
       cert_j = ts_j - env_j;
     on sigma_j = -1 additionally the EXACT floor: the pairing
     t_j = -sum B_j Dw >= floor_j = -sum_{off} (Bt_j + BE_j) Dw
     over the sub-threshold off-sign entries (tiny, disclosed),
     cert_j = max(ts_j - env_j, floor_j).  Boundary reads:
     m_j = mt_j + (E1(e_j) - E1(s_j-1)), |.| <= BE_j(e_j):
       b_cert_j = mt_j w(b) - BE_j(e_j) |w(b)|.
     Tabulated per rung: per-segment sign, required direction,
     measured one-sided margin min(BE_j -+ E_j), t_j/ts_j/env_j/
     cert_j in mu1 units (full table on the three frozen sample
     rungs, first/mid/deepest; compact per-rung line for all).
 (d) BOUNDARY TERMS: sizes |m_j w_b|/mu1, signs, the raw-form
     telescoping ratio |sum bt_j| / sum |bt_j|, the boundary
     envelope cost sum BE_j(e_j)|w_b|/mu1 (are the 2..3
     classical reads cheap against the in-segment budgets?).
 (e) ASSEMBLY (decisive): T_cert = sum_j (b_cert_j + cert_j),
     ERRseg_eff = Ttilde - T_cert >= 0 (the effective segment-
     route budget), slack_seg = (H + T_cert)/mu1 - C0 with H =
     head_B(cB), mu1 = 4 sin^2(pi/(2h+1)), C0 = 1/2 (CLI
     registration, NO-ADJUST, recorded comparison only).  Typed
     SEGENV-SUFFICIENT(min slack) iff slack_seg > 0 on ALL rungs
     (then the surface theorem shape T >= -H + c0 mu1 is stated
     with explicit constants and c0 = min (H + T_cert)/mu1
     recorded vs the frozen 1/2); else SEGENV-INSUFFICIENT
     (min/med slack, residual gap law: jackknife slope of
     log(ERRseg_eff/mu1) vs alpha, compared to the predecessor's
     global +1.744 -- recorded), plus the CARRIER census: per
     rung the segment with the largest certified deficit share
     cost_j = BE_j(e_j)|w_b| + (ts_j - cert_j) (index, sign,
     terminal?, position), and the GAIN ledger ERR_best(global,
     predecessor form) / ERRseg_eff min/med/max.  Floor usage
     census (how often the exact nonnegativity floor beats the
     envelope certificate).
 (f) TAU-SCREENS (typed, jackknife, bands PASS |s| <= 0.30 /
     RELOC s >= 0.70 / else AMBIG): log(ERRseg_eff/mu1) vs
     log m; log(sum_j |m_j w_b|/mu1) vs log m; log(gain) vs
     log m.

FROZEN PROTOCOL (ladder machinery verbatim from
tail_abel_transport_probe.py = round-59/60/62/63 chain):

 W   LADDER + WARDS W1-W11 verbatim from the predecessor
     (faithful ladder, both exact bookkeepings, atom identities,
     scan splits, round-59/60/62 reproduction incl. n_minB med
     17 and head_B(cB) med 0.388, v_sm carrier branch, kappa
     reproduction + KAPPA_INT, mu1 closed form + CXLIII shat
     band, grid tie T == tail_B(cB), global envelope in-window
     |E1| <= BE1).  Kills -> PIPELINE-BROKEN / WARD-BROKEN.

 A/B/D/E/T  as (a)/(b)/(d)/(c)+(e)/(f) above.  New WARDS: B.1
     segment identity, B.2 smooth segment identity, B.3
     regrouping, B.4 segment envelope in-window (all segments,
     all rungs), B.5 certificate order T_cert <= T (float slack).

 C   CONTROLS at kz 9 (kill -> WARD-BROKEN if silent): C1
     scramble (seed 1), Epstein x^2+5y^2, smooth comb: m < 0 AND
     zero covering cuts in BOTH senses (predecessor verbatim).
     C2 GLOBAL envelope battery from the fixed cut CTRL_CUT = 17
     (predecessor verbatim): scramble must violate the classical
     envelope by >= CTRL_VIOL = 5 (kill if silent); smooth /
     Epstein factors typed.  C3 SEGMENT battery (typed, no
     kill): each control's own integer-grid kernel is segmented
     by the same rule and the SEGMENT-ANCHORED envelope factor
     max |E_j|/BE_j is measured per control -- expectation
     declared: scramble largest (structure destroyed), smooth
     <= 1 (quadrature only), Epstein typed either way; if the
     scramble sits INSIDE all segment envelopes that is a
     first-class finding against the segment route's
     discriminating power, said prominently.

KILLS: K1 ladder (W1) -> PIPELINE-BROKEN; K2 wards (W2-W11,
B.1-B.5, C1, C2-scramble) -> WARD-BROKEN.  All typed A/D/E/T/C3
outcomes are measurements, never kills.

VERDICT (frozen enum): SEGSPLIT-MEASURED with typed sublabels
BP-CENSUS(...) + CLASSICAL-BP(...), SEG-ID-EXACT(...),
BDRY(...), SEGENV-SUFFICIENT(...)/SEGENV-INSUFFICIENT(...) +
GAIN(...), SCREENS(...), CTRL-SEG(...); else PIPELINE-BROKEN /
WARD-BROKEN.

FROZEN BARS (predecessor values verbatim unless new): KZMAX =
150; MIN_RUNGS = 40; REF_CUTS = (50, 100, 200); REF_COUNTS =
(52, 26, 25); NMIN_LO, NMIN_HI = 3, 9; NC_SHARED = 9; NB_MED =
17; NB_LO, NB_HI = 5, 47; HEADB_MED = 0.388, HEADB_TOL = 0.01;
SHAT_REF = (0.502, 1.027, 2.185), SHAT_TOL = 1.5e-3; ID_WARD =
1e-10; SCAN_WARD = 1e-9; TIE_WARD = 1e-10; ENV_SLACK = 1e-9;
KAPPA_TOL = 1e-6; MU_WARD = 1e-12; NG_SMOOTH = 6000; OV_MIN =
0.8; MAX_CROSS = 2; SIGN_EPS = 1e-15 (relative); C0 = 1/2
(frozen, NO-ADJUST, recorded comparison only); SLOPE_PASS =
0.30; SLOPE_RELOC = 0.70; CTRL_KZ = 9; CTRL_CUT = 17; CTRL_VIOL
= 5.0; KAPPA_LOW_X = 100; BLOCK = 1024; scramble seed 1;
jackknife = full leave-one-out, CI = +- 2SE.  NEW: SEG_ID_WARD =
1e-12 (relative to the declared term scale); SEG_ENV_SLACK =
1e-9; CERT_ORD_WARD = 1e-9 (relative); SAMPLE = (first, mid,
deepest) rung indices (0, N//2, N-1); breakpoint position x =
u(s_j)/(2 alpha) read at the segment-start grid index;
GAIN_EPS = 1e-300 guards on ratios/logs (declared).

SMOKE-RUN DISCLOSURE (2026-08-11, before freezing): ONE smoke
run (SPEC v0), 23/24 checks green, 18.9 s; the single failure
was a MECHANICAL format-string bug in the C3 control label
(missing Epstein argument -- fixed for v1, disclosed here; no
measurement, bar, band, enum or rule was touched, all
measurements had already completed and printed).  The smoke
facts are frozen here as the context the frozen run must
confirm.  (i) BREAKPOINTS: the true kernel splits into med 4
segments (histogram {3: 24, 4: 42, 5: 1}, pattern med +-+-),
negative-dominant 67/67 (mass share med 0.766); x_first med
0.313 with drift -0.1103/alpha (R^2 0.58, migrates inward),
x_last med 0.827 FLAT (+0.0004, R^2 0.00); classicality: count
agreement v vs v_sm on 49/67 only (the true kernel carries
extra arithmetic micro-crossings the prime-free kernel lacks),
matched-position |dx| med 0.0397 max 0.1146 -- the DEEP
breakpoints are classical positions, the count itself is not
fully prime-free.  (ii) IDENTITIES: segment identity 3.5e-16,
smooth twin 6.1e-16, regrouping 5.8e-17, segment envelopes
in-window everywhere (min slack -1.0e-15), T_cert <= T
everywhere.  (iii) THE DECISIVE MEASUREMENT -- the segment
split is a clean NEGATIVE with a sharp mechanism: slack min/med
-4.69e+06/-2.17e+05, positive on 0/67, residual law +1.824
alpha (2SE 0.194, R^2 0.80) ~ the predecessor's global +1.744;
GAIN med 0.694 (min 0.555, max 0.957) -- the segment-wise
budget is WORSE than the global one on 67/67, because the
segment anchor adds bnd(n_anchor) ~ KAPPA_INT n_anchor to
beta_j at EVERY point of the segment and the classical
breakpoints sit deep (the anchor penalty dominates the
one-sided saving, which is numerically ZERO for a symmetric
envelope); the free nonnegativity floor fires on only 1/135
negative segments (their envelope certificates are already
positive -- the floor is redundant where it holds); one-sided
demand census 135 lower / 110 upper, measured one-sided margin
min -0.000 (one saturated read at a segment start, within
float slack of the ward) med 0.318.  (iv) CARRIER: NOT the
terminal lobe (0/67) -- the deficit carrier is the INTERIOR
segment (onset x med 0.572, positive-sign on 43/67; the
mid-window +segment or the long -segment before it), i.e. the
budget lives where |Dw| mass meets deep anchors, not at the
last lobe.  (v) BOUNDARY: reads med -2.29e+05 mu1 (large and
NEGATIVE -- w < 0 at the deep breakpoints), envelope cost of
the reads med 6.45e+04 mu1 = a subdominant but non-negligible
fraction of ERRseg med 2.29e+05 mu1; raw telescoping ratio med
0.214 (adjacent raw boundary terms DO cancel ~5x).  (vi)
SCREENS: budget -1.242 AMBIG, boundary -1.194 AMBIG (both
anti-correlated exactly as the predecessor's), gain +0.034 PASS
(R^2 0.13) -- the split's cost factor is tau-FLAT: it neither
helps nor hurts where the margin shrinks.  (vii) CONTROLS: C1
3/3, C2 scramble 5.99 >= 5 FIRES, smooth 0.837, Epstein 7.51
(predecessor-verbatim); C3 segment battery: scramble 4.15
DISCRIMINATES (15 segments), Epstein 34.6, smooth 2.93 -- the
declared smooth <= 1 expectation is VIOLATED (recorded, typed,
no kill as frozen): the segment-anchored read is a single-
integer-point object near the segment start where the round-
snap quadrature error of the smooth comb exceeds the local
envelope -- an honest limit of the anchored form, not a
scramble-class violation.  AMENDMENT LEDGER: the C3 label
format fix above is the ONLY change after the smoke; no bar,
band, tolerance, enum or rule moved.

SPEC v1 (2026-08-11, frozen + SHA-hashed before the frozen
run): everything above.  Mechanical concretizations frozen:
(i) segment splitting is index-exact on the Dw array (length
L-1); (ii) the first segment's anchor is the cut itself
(A1(-1) = 0, beta_1 = predecessor's global beta -- BE_1 == BE1
restricted, a consistency tie); (iii) sigma_j = 0 (all-
sub-threshold segment) is handled as two-sided (no floor),
disclosed if it ever occurs; (iv) controls C3 read their
integer-grid masses exactly as the predecessor's C2 (round-snap
for smooth/Epstein, searchsorted cumulative for scramble) and
segment their OWN kernel from the fixed cut; (v) runtime ~ 45 s
(67 eigh pairs + full-grid segment envelopes dominate).

NO-GO COMPLIANCE (frozen): no certified-bound retry, no rank-1
approximation, no Herglotz; no fit where an identity is claimed
(the segment identity, its smooth twin, the regrouping and the
segment envelope bound are exact wards; all trends are typed
jackknife screens).

NO RH claim: everything here is float-level MEASURED SURFACE
STRUCTURE on the 67-rung ladder; the direction v is computed
per-rung data (the round-62 uniformity boundary applies
verbatim); a SEGENV-SUFFICIENT outcome would still be a per-rung
surface certificate, not a theorem, and a SEGENV-INSUFFICIENT
outcome is a measured residual demand, not a proof of
impossibility.  The halfgap constant 1/2 is the CLI registration
and is NEVER adjusted here.  No marker moves.

FIREWALL: no zeros, no prime oracles (AST scan; banned ids
zetazero / nzeros / primerange / isprime / primepi / nextprime /
prevprime; Lambda is read from the DEPLOYED window table only);
v563 READ-ONLY; RNG only inside the declared scramble control;
stdout only.

Sources (read-only): v563_paper2_readouts (core); ladder + cut/
scan machinery, grid/cumulant/envelope machinery and controls
verbatim from tail_abel_transport_probe.py (CLII, incl. its
amendment A1 = the all-integer KAPPA_INT, adopted as deployed);
q_read + v_sm construction verbatim from
arithmetic_lift_race_probe.py; mu1 normalization from
moving_node_second_order_probe.py (CXLIII); halfgap constant
C0 = 1/2 from halfgap_registration_probe.py (CLI, NO-ADJUST);
round-62 censuses (declared reproduction targets).

Run:
    experiments/tfpt-discovery/.venv/bin/python \
        experiments/tfpt-discovery/tail_segment_split_probe.py
"""

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

import numpy as np

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

import v563_paper2_readouts as core        # noqa: E402  (READ-ONLY)

KZMAX = 150
MIN_RUNGS = 40
REF_CUTS = (50, 100, 200)
REF_COUNTS = (52, 26, 25)
NMIN_LO, NMIN_HI = 3, 9
NC_SHARED = 9
NB_MED = 17
NB_LO, NB_HI = 5, 47
HEADB_MED = 0.388
HEADB_TOL = 0.01
SHAT_REF = (0.502, 1.027, 2.185)
SHAT_TOL = 1.5e-3
ID_WARD = 1e-10
SCAN_WARD = 1e-9
TIE_WARD = 1e-10
ENV_SLACK = 1e-9
KAPPA_TOL = 1e-6
MU_WARD = 1e-12
NG_SMOOTH = 6000
OV_MIN = 0.8
MAX_CROSS = 2
SIGN_EPS = 1e-15
C0 = 0.5
SLOPE_PASS = 0.30
SLOPE_RELOC = 0.70
CTRL_KZ = 9
CTRL_CUT = 17
CTRL_VIOL = 5.0
KAPPA_LOW_X = 100
BLOCK = 1024
SEG_ID_WARD = 1e-12
SEG_ENV_SLACK = 1e-9
CERT_ORD_WARD = 1e-9
GAIN_EPS = 1e-300
BANNED_IDS = ("zetazero", "nzeros", "primerange", "isprime",
              "primepi", "nextprime", "prevprime")

CHECKS = []
KILLS = []
T0 = time.time()


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


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


def ast_scan(banned):
    src = open(os.path.abspath(__file__), encoding="utf-8").read()
    bad = []
    for node in ast.walk(ast.parse(src)):
        name = None
        if isinstance(node, ast.Name):
            name = node.id
        elif isinstance(node, ast.Attribute):
            name = node.attr
        if name and name.lower() in banned:
            bad.append(name)
    return bad


def ols_line(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    vx = float(np.var(x))
    if vx == 0.0:
        return float(np.mean(y)), 0.0, float("nan")
    b = float(np.cov(x, y, bias=True)[0, 1] / vx)
    a = float(np.mean(y) - b * np.mean(x))
    ss = float(np.sum((y - a - b * x) ** 2))
    st = float(np.sum((y - np.mean(y)) ** 2))
    return a, b, (1.0 - ss / st if st > 0 else float("nan"))


def jack_slope(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    _a, b, r2 = ols_line(x, y)
    n = len(x)
    bb = []
    for i in range(n):
        m = np.ones(n, bool)
        m[i] = False
        bb.append(ols_line(x[m], y[m])[1])
    bb = np.array(bb)
    se = math.sqrt((n - 1) / n * float(np.sum((bb - bb.mean())
                                              ** 2)))
    return b, se, r2


def q_read(W, u, D, M):
    u = np.asarray(u, float)
    i0 = np.floor(u / D).astype(int)
    f = u / D - i0
    val = np.zeros_like(u)
    ok0 = (i0 >= 0) & (i0 < M)
    val[ok0] += (1.0 - f[ok0]) * W[i0[ok0]]
    ok1 = (i0 + 1 >= 0) & (i0 + 1 < M)
    val[ok1] += f[ok1] * W[i0[ok1] + 1]
    refl = u < D
    val[refl] += (1.0 - u[refl] / D) * W[0]
    return -0.5 * val


def smooth_comb(alpha, ng=NG_SMOOTH):
    ug = (np.arange(ng) + 0.5) * (2.0 * alpha / ng)
    mg = 2.0 * np.exp(ug / 2.0) * (2.0 * alpha / ng)
    return ug, mg


def lambda_eps(N):
    """Epstein x^2+5y^2 comb (port_schur_reduction verbatim)."""
    r = np.zeros(N + 1)
    s = int(math.isqrt(N)) + 1
    for x in range(-s, s + 1):
        for y in range(-s, s + 1):
            v = x * x + 5 * y * y
            if 1 <= v <= N:
                r[v] += 1.0
    a = r / 2.0
    lam = np.zeros(N + 1)
    for n in range(2, N + 1):
        acc = a[n] * math.log(n)
        for dd in range(2, n):
            if n % dd == 0:
                acc -= lam[dd] * a[n // dd]
        lam[n] = acc
    return lam


def blocked_cumsum(x):
    x = np.asarray(x, float)
    n = len(x)
    if n <= BLOCK:
        return np.cumsum(x)
    pad = (-n) % BLOCK
    xb = np.concatenate([x, np.zeros(pad)]).reshape(-1, BLOCK)
    cs = np.cumsum(xb, axis=1)
    off = np.concatenate([[0.0], np.cumsum(cs[:-1, -1])])
    return (cs + off[:, None]).reshape(-1)[:n]


def sign_census(z, uu, alpha):
    z = np.asarray(z, float)
    az = np.abs(z)
    mx = float(az.max()) if len(z) else 0.0
    if mx == 0.0:
        return dict(n_changes=0, single=True, dom=1.0,
                    x_last=float("nan"), sign=0)
    mask = az > SIGN_EPS * mx
    s = np.sign(z[mask])
    um = uu[mask]
    ch = np.nonzero(s[1:] * s[:-1] < 0.0)[0]
    pos = float(z[z > 0.0].sum())
    neg = float(-z[z < 0.0].sum())
    dom = max(pos, neg) / max(pos + neg, GAIN_EPS)
    x_last = (float(um[ch[-1] + 1]) / (2.0 * alpha)
              if len(ch) else float("nan"))
    return dict(n_changes=int(len(ch)), single=(len(ch) == 0),
                dom=dom, x_last=x_last,
                sign=(1 if pos >= neg else -1))


def segment_split(dw):
    """Maximal fixed-strict-sign runs of dw among entries with
    |dw| > SIGN_EPS max|dw| (sub-threshold entries join the
    current segment) -- the predecessor's census semantics.
    Returns list of (start, end, sign) over dw indices."""
    dw = np.asarray(dw, float)
    n = len(dw)
    az = np.abs(dw)
    mx = float(az.max()) if n else 0.0
    if mx == 0.0:
        return [(0, n - 1, 0)]
    idx = np.nonzero(az > SIGN_EPS * mx)[0]
    ss = np.sign(dw[idx])
    ch = np.nonzero(ss[1:] * ss[:-1] < 0.0)[0]
    starts = [0] + [int(idx[c + 1]) for c in ch]
    signs = [int(ss[0])] + [int(ss[c + 1]) for c in ch]
    segs = []
    for j, s in enumerate(starts):
        e = (starts[j + 1] - 1) if j + 1 < len(starts) else n - 1
        segs.append((s, e, signs[j]))
    return segs


def build_rung(kz, comb=None, scramble_seed=None,
               smooth_world=False, need_sm=True):
    """One rung of the lift-race surface (predecessor verbatim)."""
    try:
        rr = core.build_window(kz, scramble_seed=scramble_seed)
    except Exception:
        return None
    if not (core.H_MIN <= rr["h"] <= core.HCAP):
        return None
    if rr["X"] > core.ATOM_MAX:
        return None
    alpha, M, D, h = rr["alpha"], rr["M"], rr["D"], rr["h"]
    uu = np.asarray(rr["uu"], float)
    mu = 2.0 * np.asarray(rr["lam"], float)
    if smooth_world:
        du = np.zeros(len(uu))
        du[1:-1] = 0.5 * (uu[2:] - uu[:-2])
        du[0] = uu[1] - uu[0]
        du[-1] = uu[-1] - uu[-2]
        mu = 2.0 * np.exp(uu / 2.0) * du
    if comb is not None:
        uu, mu = comb
    c_at = core.atom_lags_at(alpha, M, uu, mu)[0]
    c_ar = np.asarray(core.arch_lags(M, D), float)
    w, V = np.linalg.eigh(core.odd_toeplitz(c_ar + c_at, M))
    v = V[:, 0]
    ug, mg = smooth_comb(alpha)
    c_sm = core.atom_lags_at(alpha, M, ug, mg)[0]
    row = dict(kz=kz, alpha=float(alpha), h=h, M=M, D=D,
               m=float(w[0]), uu=uu, mu=mu, X=float(rr["X"]))
    Wv = core.lag_weights_from_v(v, h)
    e_ar = float(c_ar @ Wv)
    e_t = float(c_at @ Wv)
    e_s = float(c_sm @ Wv)
    qa = mu * q_read(Wv, uu, D, M)
    qg = mg * q_read(Wv, ug, D, M)
    row.update(e_ar=e_ar, e_t=e_t, e_s=e_s, lift=e_t - e_s,
               demand=-(e_ar + e_s),
               dev_at=max(abs(float(qa.sum()) - e_t)
                          / max(abs(e_t), 1e-30),
                          abs(float(qg.sum()) - e_s)
                          / max(abs(e_s), 1e-30)))
    cq = np.cumsum(qa)
    idxg = np.searchsorted(ug, uu, side="right")
    cg_all = np.concatenate([[0.0], np.cumsum(qg)])
    head_err = cq - cg_all[idxg]
    G = head_err - row["demand"]
    tail_A = row["lift"] - head_err
    cert_A = G - np.abs(tail_A)
    head_B = e_ar + cq
    tail_B = float(qa.sum()) - cq
    cert_B = head_B - np.abs(tail_B)
    smoothtail = float(qg.sum()) - cg_all[idxg]
    row.update(G=G, tail_A=tail_A, cert_A=cert_A, head_B=head_B,
               tail_B=tail_B, cert_B=cert_B, smoothtail=smoothtail,
               qa=qa)
    row["Gref"] = {}
    for nc in REF_CUTS:
        ucut = math.log(nc)
        he = (float(qa[uu <= ucut].sum())
              - float(qg[ug <= ucut].sum()))
        row["Gref"][nc] = he - row["demand"]
    if need_sm:
        ws, Vs = np.linalg.eigh(core.odd_toeplitz(c_ar + c_sm, M))
        vsm = Vs[:, 0]
        if float(v @ vsm) < 0:
            vsm = -vsm
        ov4 = [abs(float(v @ Vs[:, j])) for j in range(4)]
        jcar = int(np.argmax(ov4))
        vcar = Vs[:, jcar] * (1.0 if float(v @ Vs[:, jcar]) >= 0
                              else -1.0)
        row.update(ov=float(abs(v @ vsm)), ov4=ov4, jcar=jcar)
        row["Wsm"] = core.lag_weights_from_v(vsm, h)
        row["Wcar"] = core.lag_weights_from_v(vcar, h)
    row["Wv"] = Wv
    return row


# --------------------------------------------------------------- Abel
PSI_FULL = np.cumsum(core.LAM_TAB)
DEVPSI = np.abs(PSI_FULL - np.arange(len(PSI_FULL), dtype=float))
KAP = core.chebyshev_kappa()
# Predecessor amendment A1 adopted as deployed: the bound is the
# ALL-INTEGER table constant on [100, ATOM_MAX] (the jump-point
# kappa does not majorize integer psi reads).
KAPPA_INT = float(np.max(np.where(
    np.arange(len(PSI_FULL)) >= KAPPA_LOW_X,
    DEVPSI / np.maximum(np.arange(len(PSI_FULL), dtype=float),
                        1.0), 0.0)))


def bnd_psi(x):
    x = np.asarray(x)
    return np.where(x >= KAPPA_LOW_X, KAPPA_INT * x.astype(float),
                    DEVPSI[np.minimum(x, KAPPA_LOW_X)])


def make_grid(row, nc):
    """Integer transport grid beyond the cut nc (predecessor
    verbatim + stored delta)."""
    alpha = row["alpha"]
    Ng = max(int(math.floor(row["X"])),
             int(np.round(math.exp(float(row["uu"][-1])))))
    kk = np.arange(nc + 1, Ng + 1, dtype=np.int64)
    kf = kk.astype(float)
    ug = np.log(kf)
    lamg = core.LAM_TAB[nc + 1:Ng + 1]
    inv_sq = 1.0 / np.sqrt(kf)
    a = 2.0 * lamg * inv_sq
    L = len(kk)
    A1 = blocked_cumsum(a)
    At1 = blocked_cumsum(2.0 * inv_sq)
    E1 = A1 - At1
    delta = inv_sq[:-1] - inv_sq[1:]
    beta = bnd_psi(kk) + float(bnd_psi(np.array([nc]))[0])
    Cb = np.concatenate([[0.0],
                         blocked_cumsum(beta[:-1] * delta)])
    BE1 = 2.0 * (beta * inv_sq + Cb)
    BE2 = blocked_cumsum(BE1)
    BE3 = blocked_cumsum(BE2)
    env_min_slack = float(np.min(BE1 - np.abs(E1)))
    return dict(kk=kk, kf=kf, ug=ug, a=a, inv_sq=inv_sq, L=L,
                A1=A1, At1=At1, E1=E1, delta=delta,
                BE1=BE1, BE2=BE2, BE3=BE3,
                env_min_slack=env_min_slack, alpha=alpha, nc=nc)


def transport(grid, row, W):
    """Global order-1..3 transport (predecessor verbatim; gives
    the reference ERR budgets and the r=1 census)."""
    L = grid["L"]
    w = q_read(W, grid["ug"], row["D"], row["M"])
    dw1 = w[1:] - w[:-1]
    dw2 = dw1[1:] - dw1[:-1]
    dw3 = dw2[1:] - dw2[:-1]
    a = grid["a"]
    A1 = grid["A1"]
    A2 = blocked_cumsum(A1)
    A3 = blocked_cumsum(A2)
    T = float(np.dot(a, w))
    bdry = A1[L - 1] * w[L - 1]
    T1 = bdry - float(np.dot(A1[:L - 1], dw1))
    sc1 = abs(bdry) + float(np.dot(np.abs(A1[:L - 1]),
                                   np.abs(dw1)))
    dev_abel = abs(T1 - T) / max(sc1, 1.0)
    Tt = float(np.dot(2.0 * grid["inv_sq"], w))
    BE1, BE2, BE3 = grid["BE1"], grid["BE2"], grid["BE3"]
    e_bdry = BE1[L - 1] * abs(w[L - 1])
    ERR1 = e_bdry + float(np.dot(BE1[:L - 1], np.abs(dw1)))
    ERR2 = (e_bdry + BE2[L - 2] * abs(dw1[L - 2])
            + float(np.dot(BE2[:L - 2], np.abs(dw2))))
    ERR3 = (e_bdry + BE2[L - 2] * abs(dw1[L - 2])
            + BE3[L - 3] * abs(dw2[L - 3])
            + float(np.dot(BE3[:L - 3], np.abs(dw3))))
    cen1 = sign_census(dw1, grid["ug"][:len(dw1)], grid["alpha"])
    return dict(w=w, dw1=dw1, T=T, Tt=Tt, dev_abel=dev_abel,
                ERR=(ERR1, ERR2, ERR3), cen1=cen1)


def seg_analyze(grid, row, W):
    """The segment-split bookkeeping: exact telescoped identity,
    per-segment one-sided envelopes, boundary reads, floors and
    the assembled certificate."""
    L = grid["L"]
    ug = grid["ug"]
    alpha = grid["alpha"]
    w = q_read(W, ug, row["D"], row["M"])
    dw = w[1:] - w[:-1]
    segs = segment_split(dw)
    A1, At1, E1 = grid["A1"], grid["At1"], grid["E1"]
    kk, inv, delta = grid["kk"], grid["inv_sq"], grid["delta"]
    a = grid["a"]
    T = float(np.dot(a, w))
    Tt = float(np.dot(2.0 * inv, w))
    out = []
    scale = 0.0
    for (s, e, sg) in segs:
        A1p = float(A1[s - 1]) if s > 0 else 0.0
        At1p = float(At1[s - 1]) if s > 0 else 0.0
        E1p = float(E1[s - 1]) if s > 0 else 0.0
        Bj = A1[s:e + 1] - A1p
        Btj = At1[s:e + 1] - At1p
        Ej = E1[s:e + 1] - E1p
        beta = (bnd_psi(kk[s:e + 1])
                + float(bnd_psi(np.array([int(kk[s]) - 1]))[0]))
        Cb = np.concatenate(
            [[0.0], blocked_cumsum(beta[:-1] * delta[s:e])])
        BE = 2.0 * (beta * inv[s:e + 1] + Cb)
        dws = dw[s:e + 1]
        adws = np.abs(dws)
        env = float(np.dot(BE, adws))
        t_m = -float(np.dot(Bj, dws))
        ts = -float(np.dot(Btj, dws))
        wb = float(w[e + 1])
        m_i = float(A1[e] - A1p)
        mt_i = float(At1[e] - At1p)
        BEe = float(BE[-1])
        b_meas = m_i * wb
        b_cert = mt_i * wb - BEe * abs(wb)
        bt_raw = -A1p * (float(w[e + 1]) - float(w[s]))
        slack2 = float(np.min(BE - np.abs(Ej)))
        if sg < 0:
            m1 = float(np.min(BE + Ej))
            off = dws > 0.0
        elif sg > 0:
            m1 = float(np.min(BE - Ej))
            off = dws < 0.0
        else:
            m1 = slack2
            off = np.zeros(len(dws), bool)
        floored = False
        cert = ts - env
        if sg < 0:
            floor = -float(np.dot((Btj + BE)[off], dws[off]))
            if floor > cert:
                cert = floor
                floored = True
        scale += abs(b_meas) + float(np.dot(np.abs(Bj), adws))
        out.append(dict(
            s=s, e=e, sg=sg, x0=float(ug[s]) / (2.0 * alpha),
            x1=float(ug[min(e + 1, L - 1)]) / (2.0 * alpha),
            m=m_i, mt=mt_i, t=t_m, ts=ts, env=env, cert=cert,
            b_meas=b_meas, b_cert=b_cert, bt_raw=bt_raw, BEe=BEe,
            wb=wb, slack2=slack2, m1=m1, floored=floored,
            n_off=int(np.sum(off)),
            m1rel=m1 / max(float(np.max(BE)), GAIN_EPS)))
    T_seg = sum(o["b_meas"] + o["t"] for o in out)
    Tt_seg = sum(o["mt"] * o["wb"] + o["ts"] for o in out)
    T_cert = sum(o["b_cert"] + o["cert"] for o in out)
    bdry_glob = float(A1[L - 1] * w[L - 1])
    regroup = abs(sum(o["bt_raw"] for o in out) + bdry_glob
                  - sum(o["b_meas"] for o in out))
    dev_seg = abs(T_seg - T) / max(scale, 1.0)
    dev_sm = abs(Tt_seg - Tt) / max(scale, 1.0)
    dev_rg = regroup / max(scale, 1.0)
    env_ward = min(o["slack2"] for o in out)
    bts = [o["bt_raw"] for o in out]
    tel = (abs(sum(bts)) / max(sum(abs(b) for b in bts),
                               GAIN_EPS))
    return dict(segs=out, T=T, Tt=Tt, T_cert=T_cert,
                dev_seg=dev_seg, dev_sm=dev_sm, dev_rg=dev_rg,
                env_ward=env_ward, tel=tel, scale=scale,
                nseg=len(out),
                xbp=[o["x0"] for o in out[1:]],
                pattern="".join("+" if o["sg"] > 0 else
                                "-" if o["sg"] < 0 else "0"
                                for o in out))


def ctrl_seg_battery(r, cut):
    """C3: segment-anchored envelope factor for a control rung
    from the fixed cut (integer reads exactly as the
    predecessor's C2; segments from the control's OWN kernel)."""
    Ng = int(math.floor(r["X"]))
    kk = np.arange(cut + 1, Ng + 1, dtype=np.int64)
    kf = kk.astype(float)
    inv = 1.0 / np.sqrt(kf)
    delta = inv[:-1] - inv[1:]
    At1 = blocked_cumsum(2.0 * inv)
    if "scr" in r and r["scr"]:
        cmass = np.concatenate([[0.0], blocked_cumsum(r["mu"])])
        idx = np.searchsorted(r["uu"], np.log(kf), side="right")
        i0 = int(np.searchsorted(r["uu"], math.log(cut) + 1e-12,
                                 side="right"))
        A1c = cmass[idx] - cmass[i0]
    else:
        nn = np.round(np.exp(r["uu"])).astype(int)
        ag = np.zeros(Ng + 1)
        keep = nn <= Ng
        np.add.at(ag, nn[keep], r["mu"][keep])
        A1c = blocked_cumsum(ag[cut + 1:Ng + 1])
    E1c = A1c - At1
    wc = q_read(r["Wv"], np.log(kf), r["D"], r["M"])
    dwc = wc[1:] - wc[:-1]
    segs = segment_split(dwc)
    fac = 0.0
    for (s, e, _sg) in segs:
        E1p = float(E1c[s - 1]) if s > 0 else 0.0
        Ej = E1c[s:e + 1] - E1p
        beta = (bnd_psi(kk[s:e + 1])
                + float(bnd_psi(np.array([int(kk[s]) - 1]))[0]))
        Cb = np.concatenate(
            [[0.0], blocked_cumsum(beta[:-1] * delta[s:e])])
        BE = 2.0 * (beta * inv[s:e + 1] + Cb)
        fac = max(fac, float(np.max(np.abs(Ej) / BE)))
    return fac, len(segs)


def main():
    section("PRIME.PORT.TAIL.SEGSPLIT.01 -- the segment-split "
            "attack on the tail (EXPLORATION ONLY)")
    print("    FROZEN_SPEC SHA-256 = %s"
          % hashlib.sha256(__doc__.encode("utf-8")).hexdigest())
    print("    NO RH claim; no marker moves; C0 = 1/2 is the CLI "
          "registration, NO-ADJUST.")
    print("\nS0 -- firewall")
    check("S0.1 AST firewall clean", not ast_scan(BANNED_IDS))

    # ------------------------------------------------------------ W
    section("W -- the faithful ladder + wards (predecessor "
            "verbatim)")
    rungs = []
    for kz in range(2, KZMAX + 1):
        row = build_rung(kz)
        if row is not None:
            rungs.append(row)
    rungs.sort(key=lambda r: (r["h"], r["kz"]))
    check("W1 faithful ladder >= %d rungs" % MIN_RUNGS,
          len(rungs) >= MIN_RUNGS,
          "%d rungs, h %d..%d  [%.1f s]"
          % (len(rungs), rungs[0]["h"], rungs[-1]["h"],
             time.time() - T0), kill="K1")
    if KILLS:
        return finish({})
    N = len(rungs)
    check("W2 WARD truth margin m_h > 0 on every rung (min %.3e)"
          % min(r["m"] for r in rungs),
          all(r["m"] > 0 for r in rungs), kill="K2")
    dev_bk = max(max(abs((r["lift"] - r["demand"]) - r["m"]),
                     abs((r["e_ar"] + r["e_t"]) - r["m"]))
                 / max(1.0, abs(r["m"])) for r in rungs)
    check("W3 WARD both exact bookkeepings: max dev %.2e <= %.0e"
          % (dev_bk, ID_WARD), dev_bk <= ID_WARD, kill="K2")
    dev_at = max(r["dev_at"] for r in rungs)
    check("W4 WARD atom identities (atom sum = E_at, PNT grid = "
          "E_sm): max rel dev %.2e <= %.0e" % (dev_at, ID_WARD),
          dev_at <= ID_WARD, kill="K2")
    dev_sc = 0.0
    for r in rungs:
        sc = max(float(np.max(np.abs((r["head_B"] + r["tail_B"])
                                     - r["m"]))),
                 float(np.max(np.abs((r["G"] + r["tail_A"])
                                     - r["m"]))),
                 float(np.max(np.abs(r["G"] - r["head_B"]
                                     - r["smoothtail"]))))
        dev_sc = max(dev_sc, sc / max(1.0, abs(r["e_t"])))
    check("W5 WARD split exactness on the full scans: max rel "
          "dev %.2e <= %.0e" % (dev_sc, SCAN_WARD),
          dev_sc <= SCAN_WARD, kill="K2")
    cnts = tuple(int(np.sum(np.array(
        [r["Gref"][nc] for r in rungs]) > 0)) for nc in REF_CUTS)
    n_min, nB_min, icBs, tB_neg = [], [], [], 0
    for r in rungs:
        nn = np.round(np.exp(r["uu"])).astype(int)
        covA = r["cert_A"] > 0.0
        i0 = int(np.argmax(covA)) if bool(np.any(covA)) else -1
        n_min.append(int(nn[i0]) if i0 >= 0 else -1)
        covB = r["cert_B"] > 0.0
        icB = int(np.argmax(covB)) if bool(np.any(covB)) else -1
        icBs.append(icB)
        nB_min.append(int(nn[icB]) if icB >= 0 else -1)
        if icB >= 0 and float(r["tail_B"][icB]) <= 0.0:
            tB_neg += 1
    i9s = [int(np.searchsorted(r["uu"],
                               math.log(NC_SHARED) + 1e-12,
                               side="right")) - 1 for r in rungs]
    cov9 = sum(1 for r, i9 in zip(rungs, i9s)
               if i9 >= 0 and r["cert_A"][i9] > 0)
    tA_neg = sum(1 for r in rungs if bool(np.any(r["cert_A"] > 0))
                 and r["tail_A"][int(np.argmax(
                     r["cert_A"] > 0))] <= 0.0)
    covB_n = sum(1 for i in icBs if i >= 0)
    hBc = np.array([float(r["head_B"][i])
                    for r, i in zip(rungs, icBs)])
    medB = float(np.median([n for n in nB_min if n > 0]))
    ok_rep = (cnts == REF_COUNTS
              and all(NMIN_LO <= nm <= NMIN_HI for nm in n_min)
              and cov9 == N and tA_neg == N and covB_n == N
              and medB == NB_MED
              and min(nB_min) >= NB_LO and max(nB_min) <= NB_HI
              and tB_neg == N
              and abs(float(np.median(hBc)) - HEADB_MED)
              <= HEADB_TOL)
    check("W6 REPRODUCTION 59/60/62: G > 0 at %s = %s == %s; "
          "n_min in [%d, %d]; cut 9 covers %d/%d; tail_A <= 0 "
          "%d/%d; B-cuts exist %d/%d, n_minB med %d in [%d, %d]; "
          "tail_B <= 0 at cB %d/%d; head_B(cB) med %.3f ~ %.3f"
          % (REF_CUTS, cnts, REF_COUNTS, NMIN_LO, NMIN_HI, cov9,
             N, tA_neg, N, covB_n, N, int(medB), min(nB_min),
             max(nB_min), tB_neg, N, float(np.median(hBc)),
             HEADB_MED), ok_rep, kill="K2")
    n_cross = sum(1 for r in rungs if r["ov"] < OV_MIN)
    cross_ok = all(max(r["ov4"]) >= OV_MIN for r in rungs
                   if r["ov"] < OV_MIN)
    check("W7 WARD v_sm branch: %d crossing rung(s) (%s; ward <= "
          "%d), carrier ok"
          % (n_cross,
             ", ".join("kz%d ov %.4f" % (r["kz"], r["ov"])
                       for r in rungs if r["ov"] < OV_MIN)
             or "none", MAX_CROSS),
          n_cross <= MAX_CROSS and cross_ok, kill="K2")
    check("W8 WARD kappa: chebyshev_kappa() = %.6f within %.0e "
          "of %.6f (jump points; ALL-INTEGER table envelope "
          "KAPPA_INT = %.6f deployed, predecessor amendment A1)"
          % (KAP, KAPPA_TOL, core.KAPPA_REF, KAPPA_INT),
          abs(KAP - core.KAPPA_REF) <= KAPPA_TOL, kill="K2")
    mu1 = np.array([float(core.parity_mu(r["h"])[0])
                    for r in rungs])
    mu1_cf = np.array([4.0 * math.sin(math.pi
                                      / (2 * r["h"] + 1)) ** 2
                       for r in rungs])
    dev_mu = float(np.max(np.abs(mu1 - mu1_cf)
                          / np.maximum(mu1, GAIN_EPS)))
    mm = np.array([r["m"] for r in rungs])
    shat = mm / mu1
    s3 = (float(np.min(shat)), float(np.median(shat)),
          float(np.max(shat)))
    ok_shat = all(abs(s3[i] - SHAT_REF[i]) <= SHAT_TOL
                  for i in range(3))
    check("W9 WARD mu1 closed form (dev %.1e) + CXLIII shat band "
          "min/med/max %.4f/%.4f/%.4f ~ %s"
          % (dev_mu, s3[0], s3[1], s3[2], SHAT_REF),
          dev_mu <= MU_WARD and ok_shat, kill="K2")
    if KILLS:
        return finish({})

    grids, trv, sgv, sgs = [], [], [], []
    for r, nc in zip(rungs, nB_min):
        g = make_grid(r, nc)
        grids.append(g)
        trv.append(transport(g, r, r["Wv"]))
        sgv.append(seg_analyze(g, r, r["Wv"]))
        Ws = r["Wcar"] if r["ov"] < OV_MIN else r["Wsm"]
        sgs.append(seg_analyze(g, r, Ws))
    tie = max(abs(t["T"] - float(r["tail_B"][i]))
              / max(1.0, abs(float(r["tail_B"][i])))
              for t, r, i in zip(trv, rungs, icBs))
    check("W10 WARD grid tie: integer-grid tail == tail_B(cB) "
          "max rel dev %.2e <= %.0e  [%.1f s]"
          % (tie, TIE_WARD, time.time() - T0),
          tie <= TIE_WARD, kill="K2")
    env_slk = min(g["env_min_slack"] for g in grids)
    check("W11 WARD global envelope in-window: |E1| <= BE1 "
          "everywhere on every rung (min slack %+.3e >= %.0e)"
          % (env_slk, -ENV_SLACK), env_slk >= -ENV_SLACK,
          kill="K2")
    if KILLS:
        return finish({})

    # ------------------------------------------------------------ A
    section("A -- (a) BREAKPOINT CENSUS: the r = 1 dual kernel's "
            "sign-change points, both kernels")
    print("    segments from the TRUE kernel q_v (exact fixed "
          "sign); classicality vs the prime-free q_{v_sm} "
          "(carrier branch).  Zero threshold %.0e * max|Dw| "
          "(declared)." % SIGN_EPS)
    aa = np.array([r["alpha"] for r in rungs])
    nsegv = np.array([s["nseg"] for s in sgv])
    nsegs = np.array([s["nseg"] for s in sgs])
    match = nsegv == nsegs
    dxs = []
    for sv, ss_, mt in zip(sgv, sgs, match):
        if mt and sv["nseg"] > 1:
            dxs.append(max(abs(a - b) for a, b in
                           zip(sv["xbp"], ss_["xbp"])))
    dxs = np.array(dxs) if dxs else np.array([float("nan")])
    hist = {}
    for n in nsegv:
        hist[int(n)] = hist.get(int(n), 0) + 1
    dom_neg = sum(1 for t in trv if t["cen1"]["sign"] < 0)
    dom_med = float(np.median([t["cen1"]["dom"] for t in trv]))
    xf = np.array([s["xbp"][0] for s in sgv if s["nseg"] > 1])
    xl = np.array([s["xbp"][-1] for s in sgv if s["nseg"] > 1])
    af = np.array([r["alpha"] for r, s in zip(rungs, sgv)
                   if s["nseg"] > 1])
    slF, seF, r2F = jack_slope(af, xf)
    slL, seL, r2L = jack_slope(af, xl)
    print("    segment count histogram (true kernel): %s; "
          "pattern med %s"
          % (dict(sorted(hist.items())),
             sorted((s["pattern"] for s in sgv),
                    key=len)[len(sgv) // 2]))
    print("    dominant sign negative on %d/%d (mass share med "
          "%.3f)" % (dom_neg, N, dom_med))
    print("    breakpoint positions x = u/(2a): first med %.3f "
          "(drift %+.4f/alpha +- 2SE %.4f, R^2 %.2f); last med "
          "%.3f (drift %+.4f/alpha +- 2SE %.4f, R^2 %.2f)"
          % (float(np.median(xf)), slF, 2 * seF, r2F,
             float(np.median(xl)), slL, 2 * seL, r2L))
    print("    classicality: count agreement v vs v_sm on %d/%d; "
          "matched-position |dx| med %.4f max %.4f"
          % (int(np.sum(match)), N, float(np.nanmedian(dxs)),
             float(np.nanmax(dxs))))
    lab_a = ("BP-CENSUS(nseg med %d (%d..%d), neg-dom %d/%d, "
             "x_last %.3f drift %+.4f) + CLASSICAL-BP(match "
             "%d/%d, med|dx| %.4f)"
             % (int(np.median(nsegv)), int(nsegv.min()),
                int(nsegv.max()), dom_neg, N,
                float(np.median(xl)), slL, int(np.sum(match)),
                N, float(np.nanmedian(dxs))))
    check("A.1 typed (a): %s" % lab_a, True)

    # ------------------------------------------------------------ B
    section("B -- (b) THE EXACT SEGMENT IDENTITY (WARDS)")
    dev_seg = max(s["dev_seg"] for s in sgv)
    check("B.1 WARD segment identity T = sum_j [m_j w(b) - sum "
          "B_j Dw] on every rung: max rel dev %.2e <= %.0e"
          % (dev_seg, SEG_ID_WARD), dev_seg <= SEG_ID_WARD,
          kill="K2")
    dev_sm = max(s["dev_sm"] for s in sgv)
    check("B.2 WARD smooth twin identity (At1/Bt vs Ttilde): "
          "max rel dev %.2e <= %.0e" % (dev_sm, SEG_ID_WARD),
          dev_sm <= SEG_ID_WARD, kill="K2")
    dev_rg = max(s["dev_rg"] for s in sgv)
    check("B.3 WARD regrouping sum bt_j + A1(N)w_N == sum m_j "
          "w(b): max rel dev %.2e <= %.0e"
          % (dev_rg, SEG_ID_WARD), dev_rg <= SEG_ID_WARD,
          kill="K2")
    env_w = min(s["env_ward"] for s in sgv)
    check("B.4 WARD segment envelope in-window |E_j| <= BE_j on "
          "every segment of every rung (min slack %+.3e >= %.0e)"
          % (env_w, -SEG_ENV_SLACK), env_w >= -SEG_ENV_SLACK,
          kill="K2")
    dev_ord = max((s["T_cert"] - s["T"]) / max(s["scale"], 1.0)
                  for s in sgv)
    check("B.5 WARD certificate order T_cert <= T on every rung "
          "(max rel excess %+.2e <= %.0e)"
          % (dev_ord, CERT_ORD_WARD), dev_ord <= CERT_ORD_WARD,
          kill="K2")
    lab_b = ("SEG-ID-EXACT(%.1e, smooth %.1e, regroup %.1e)"
             % (dev_seg, dev_sm, dev_rg))
    if KILLS:
        return finish({})

    # ------------------------------------------------------------ D
    section("D -- (d) BOUNDARY TERMS at the classical "
            "breakpoints")
    bdry_tot = np.array([sum(o["b_meas"] for o in s["segs"])
                         for s in sgv]) / mu1
    bdry_env = np.array([sum(o["BEe"] * abs(o["wb"])
                             for o in s["segs"])
                         for s in sgv]) / mu1
    tels = np.array([s["tel"] for s in sgv])
    print("    boundary content sum m_j w(b)/mu1: min/med/max "
          "%+.3e/%+.3e/%+.3e; envelope cost of the reads "
          "min/med/max %.3e/%.3e/%.3e mu1"
          % (float(np.min(bdry_tot)), float(np.median(bdry_tot)),
             float(np.max(bdry_tot)), float(np.min(bdry_env)),
             float(np.median(bdry_env)),
             float(np.max(bdry_env))))
    print("    raw-form telescoping |sum bt_j|/sum|bt_j|: "
          "min/med/max %.3f/%.3f/%.3f (1 = no cancellation)"
          % (float(np.min(tels)), float(np.median(tels)),
             float(np.max(tels))))
    lab_d = ("BDRY(reads med %.2e mu1, env med %.2e mu1, tel "
             "med %.2f)"
             % (float(np.median(np.abs(bdry_tot))),
                float(np.median(bdry_env)),
                float(np.median(tels))))
    check("D.1 typed (d): %s" % lab_d, True)

    # ------------------------------------------------------------ E
    section("E -- (c)+(e) THE SEGMENT-WISE ENVELOPE + ASSEMBLY "
            "(decisive): KAPPA_INT = %.6f segment-anchored"
            % KAPPA_INT)
    H = hBc
    Tcert = np.array([s["T_cert"] for s in sgv])
    Ttv = np.array([s["Tt"] for s in sgv])
    ERRg = np.array([min(t["ERR"]) for t in trv])
    ERRseg = Ttv - Tcert
    slack_seg = (H + Tcert) / mu1 - C0
    slack_glb = (H + Ttv - ERRg) / mu1 - C0
    gain = ERRg / np.maximum(ERRseg, GAIN_EPS)
    car_idx, car_term, car_sign, car_x = [], [], [], []
    n_floor, n_negseg, n_needlow, n_needup = 0, 0, 0, 0
    m1_all = []
    for s in sgv:
        costs = [o["BEe"] * abs(o["wb"]) + (o["ts"] - o["cert"])
                 for o in s["segs"]]
        ci = int(np.argmax(costs))
        car_idx.append(ci)
        car_term.append(ci == s["nseg"] - 1)
        car_sign.append(s["segs"][ci]["sg"])
        car_x.append(s["segs"][ci]["x0"])
        for o in s["segs"]:
            if o["sg"] < 0:
                n_negseg += 1
                n_needlow += 1
                if o["floored"]:
                    n_floor += 1
            elif o["sg"] > 0:
                n_needup += 1
            m1_all.append(o["m1rel"])
    m1_all = np.array(m1_all)
    print("    per-rung ledger (certificates in mu1 units):")
    print("    kz   h    nseg pat    slack_seg   ERRseg/mu1  "
          "ERR_glb/mu1 gain  carrier")
    for i, (r, s) in enumerate(zip(rungs, sgv)):
        print("    %-4d %-4d %-4d %-6s %+.3e %.3e %.3e %5.2f "
              "seg%d(%s%s)"
              % (r["kz"], r["h"], s["nseg"], s["pattern"],
                 slack_seg[i], ERRseg[i] / mu1[i],
                 ERRg[i] / mu1[i], gain[i], car_idx[i] + 1,
                 "+" if car_sign[i] > 0 else "-",
                 ",term" if car_term[i] else ""), flush=True)
    for si, tag in ((0, "first"), (N // 2, "mid"),
                    (N - 1, "deepest")):
        r, s = rungs[si], sgv[si]
        print("\n    SAMPLE rung (%s) kz %d h %d (nc %d, mu1 "
              "%.3e): per-segment ladder"
              % (tag, r["kz"], r["h"], grids[si]["nc"], mu1[si]))
        print("      j sgn x-range        need     m1/maxBE  "
              "t/mu1       ts/mu1      env/mu1     cert/mu1")
        for j, o in enumerate(s["segs"]):
            need = ("E >= -BE" if o["sg"] < 0 else
                    "E <= +BE" if o["sg"] > 0 else "two-sided")
            print("      %d  %s  [%.3f,%.3f] %-9s %.3f     "
                  "%+.3e %+.3e %.3e %+.3e%s"
                  % (j + 1, "+" if o["sg"] > 0 else "-",
                     o["x0"], o["x1"], need, o["m1rel"],
                     o["t"] / mu1[si], o["ts"] / mu1[si],
                     o["env"] / mu1[si], o["cert"] / mu1[si],
                     "  FLOOR" if o["floored"] else ""))
    n_pos = int(np.sum(slack_seg > 0.0))
    print("\n    one-sided demand census: %d segments need the "
          "LOWER side (sigma = -1), %d the UPPER (sigma = +1); "
          "measured one-sided margin min(BE -+ E)/max BE "
          "min/med %.3f/%.3f"
          % (n_needlow, n_needup, float(np.min(m1_all)),
             float(np.median(m1_all))))
    print("    nonnegativity floor fires on %d/%d negative "
          "segments (replaces a worse envelope certificate)"
          % (n_floor, n_negseg))
    print("    GAIN ledger ERR_best(global)/ERRseg_eff: "
          "min/med/max %.3f/%.3f/%.3f; global slack min/med "
          "%+.2e/%+.2e (predecessor form, reference)"
          % (float(np.min(gain)), float(np.median(gain)),
             float(np.max(gain)), float(np.min(slack_glb)),
             float(np.median(slack_glb))))
    nt = int(np.sum(car_term))
    print("    CARRIER census: terminal segment on %d/%d; "
          "carrier sign + on %d/%d; carrier onset x med %.3f"
          % (nt, N, int(np.sum(np.array(car_sign) > 0)), N,
             float(np.median(car_x))))
    if n_pos == N:
        c0_rec = float(np.min((H + Tcert) / mu1))
        lab_e = "SEGENV-SUFFICIENT(min slack %+.3e)" % float(
            np.min(slack_seg))
        print("    ==> THE TAIL STATEMENT CLOSES SEGMENT-WISE "
              "ON THE SURFACE: T >= -H + c0 mu1 with c0 = %.4f "
              "(recorded vs frozen 1/2, NO adjustment; "
              "KAPPA_INT = %.6f, cuts n_minB, breakpoints "
              "classical)" % (c0_rec, KAPPA_INT))
    else:
        slG, seG, r2G = jack_slope(aa, np.log(ERRseg / mu1))
        lab_e = ("SEGENV-INSUFFICIENT(slack min/med %+.2e/%+.2e, "
                 "residual law %+.3f, carrier term %d/%d)"
                 % (float(np.min(slack_seg)),
                    float(np.median(slack_seg)), slG, nt, N))
        print("    ==> SEGMENT-WISE ENVELOPES INSUFFICIENT on "
              "%d/%d: residual demand law log(ERRseg_eff/mu1) = "
              "%+.3f alpha + c (2SE %.3f, R^2 %.2f) vs global "
              "+1.744 (CLII, recorded); the residual object is "
              "the carrier segment's one-sided windowed-psi "
              "demand at scale med %.2e mu1"
              % (N - n_pos, N, slG, 2 * seG, r2G,
                 float(np.median(ERRseg / mu1))))
    lab_g = "GAIN(med %.2f, max %.2f)" % (
        float(np.median(gain)), float(np.max(gain)))
    check("E.1 typed (c)+(e): %s / %s" % (lab_e, lab_g), True)

    # ------------------------------------------------------------ T
    section("T -- (f) TAU-SCREENS (jackknife, typed)")
    scr = []
    for nm, yv in (("ERRseg/mu1", ERRseg / mu1),
                   ("bdry reads/mu1", np.abs(bdry_tot) + 1e-30),
                   ("gain", gain)):
        sl, se, r2 = jack_slope(np.log(mm), np.log(yv))
        ty = ("PASS" if abs(sl) <= SLOPE_PASS else
              "RELOC" if sl >= SLOPE_RELOC else "AMBIG")
        scr.append((nm, sl, ty))
        print("    screen log %s vs log m: slope %+.3f +- 2SE "
              "%.3f (R^2 %.2f) -> %s" % (nm, sl, 2 * se, r2, ty))
    lab_t = "SCREENS(%s)" % ", ".join(
        "%s %+.2f %s" % s for s in scr)
    check("T.1 typed (f): %s" % lab_t, True)

    # ------------------------------------------------------------ C
    section("C -- controls on this surface at kz %d" % CTRL_KZ)
    rr9 = core.build_window(CTRL_KZ)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE_ = lambda_eps(N_E)
    nnE = np.nonzero(np.abs(lamE_) > 1e-12)[0]
    ctl = {}
    ctl["Epstein"] = build_rung(CTRL_KZ, comb=(
        np.log(nnE.astype(float)),
        2.0 * lamE_[nnE] / np.sqrt(nnE.astype(float))),
        need_sm=False)
    ctl["scramble"] = build_rung(CTRL_KZ, scramble_seed=1,
                                 need_sm=False)
    ctl["smooth"] = build_rung(CTRL_KZ, smooth_world=True,
                               need_sm=False)
    ctl["scramble"]["scr"] = True
    fired = True
    for name, r in ctl.items():
        if r is None:
            print("    %-9s: rung dies -> fires" % name)
            continue
        ncovA = int(np.sum(r["cert_A"] > 0))
        ncovB = int(np.sum(r["cert_B"] > 0))
        f = (r["m"] < 0) and ncovA == 0 and ncovB == 0
        fired &= f
        print("    %-9s: m %+.3e  covering cuts A/B %d/%d -> %s"
              % (name, r["m"], ncovA, ncovB,
                 "FIRES" if f else "SILENT"), flush=True)
    check("C1 WARD all three controls fire (m < 0 and zero "
          "coverage in BOTH senses)", fired, kill="K2")
    facs = {}
    for name in ("Epstein", "smooth", "scramble"):
        r = ctl[name]
        Ng = int(math.floor(r["X"]))
        kk = np.arange(CTRL_CUT + 1, Ng + 1, dtype=np.int64)
        kf = kk.astype(float)
        inv_sq = 1.0 / np.sqrt(kf)
        delta = inv_sq[:-1] - inv_sq[1:]
        beta = (bnd_psi(kk)
                + float(bnd_psi(np.array([CTRL_CUT]))[0]))
        Cb = np.concatenate(
            [[0.0], blocked_cumsum(beta[:-1] * delta)])
        BE1 = 2.0 * (beta * inv_sq + Cb)
        At1 = blocked_cumsum(2.0 * inv_sq)
        if name == "scramble":
            cmass = np.concatenate([[0.0],
                                    blocked_cumsum(r["mu"])])
            idx = np.searchsorted(r["uu"], np.log(kf),
                                  side="right")
            i0 = int(np.searchsorted(
                r["uu"], math.log(CTRL_CUT) + 1e-12,
                side="right"))
            A1c = cmass[idx] - cmass[i0]
        else:
            nn = np.round(np.exp(r["uu"])).astype(int)
            ag = np.zeros(Ng + 1)
            keep = nn <= Ng
            np.add.at(ag, nn[keep], r["mu"][keep])
            A1c = blocked_cumsum(ag[CTRL_CUT + 1:Ng + 1])
        facs[name] = float(np.max(np.abs(A1c - At1) / BE1))
        print("    %-9s GLOBAL envelope factor max |E1|/BE1 = "
              "%.3g" % (name, facs[name]), flush=True)
    check("C2 WARD scramble violates the classical envelope: "
          "factor %.3g >= %.1f (cumulative structure destroyed)"
          % (facs["scramble"], CTRL_VIOL),
          facs["scramble"] >= CTRL_VIOL, kill="K2")
    segf = {}
    for name in ("Epstein", "smooth", "scramble"):
        segf[name], nsg = ctrl_seg_battery(ctl[name], CTRL_CUT)
        print("    %-9s SEGMENT-anchored factor max |E_j|/BE_j "
              "= %.3g (%d segments of its own kernel)"
              % (name, segf[name], nsg), flush=True)
    if segf["scramble"] <= 1.0:
        print("    ==> WARNING (first-class): the scramble sits "
              "INSIDE all segment envelopes -- the segment "
              "route would NOT discriminate")
    lab_c = ("CTRL-SEG(scramble %.3g%s, smooth %.3g%s, Epstein "
             "%.3g -- measured, typed)"
             % (segf["scramble"],
                " DISCRIMINATES" if segf["scramble"] > 1.0
                else " NON-DISCRIMINATING",
                segf["smooth"],
                " <= 1 as declared" if segf["smooth"] <= 1.0
                else " > 1 (recorded)",
                segf["Epstein"]))
    check("C3 typed segment battery: %s" % lab_c, True)

    return finish(dict(a=lab_a, b=lab_b, d=lab_d, e=lab_e,
                       g=lab_g, t=lab_t, c=lab_c))


def finish(labels):
    section("V -- FROZEN VERDICT")
    n_pass = sum(1 for _n, okk in CHECKS if okk)
    n_tot = len(CHECKS)
    if KILLS:
        VERDICT = {"K1": "PIPELINE-BROKEN",
                   "K2": "WARD-BROKEN"}[KILLS[0]]
        print("\n  VERDICT: %s" % VERDICT)
    else:
        VERDICT = ("SEGSPLIT-MEASURED / %(a)s / %(b)s / %(d)s / "
                   "%(e)s / %(g)s / %(t)s / %(c)s" % labels)
        print("\n  VERDICT: %s" % VERDICT)
    print("""
  HONEST FRAME (as frozen): the segment identity, its smooth
  twin, the regrouping and the segment-anchored envelope bound
  are EXACT bookkeeping; the breakpoint census, the per-segment
  slack ladders, the floors, the carrier census and the gain
  ledger are MEASURED SURFACE STRUCTURE at float level.  An
  insufficient segment-wise envelope is a measured residual
  demand, not an impossibility proof; a sufficient one would
  still be a per-rung surface certificate, not a theorem.  The
  halfgap constant 1/2 (CLI) is never adjusted here.  NO RH
  claim.  No marker moves.""")
    print("\n[TIME] %.1f s   [CHECKS] %d run, %d failed"
          % (time.time() - T0, n_tot, n_tot - n_pass))
    return 0 if n_pass == n_tot else 1


if __name__ == "__main__":
    raise SystemExit(main())
'''

# ------------- frozen probe source tail_oscillation_pairing_probe (embedded BYTE-EXACT, raw string)
_SRC_5 = r'''
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
r"""tail_oscillation_pairing_probe -- PRIME.PORT.TAIL.OSCPAIR.01
(EXPLORATION ONLY, experiments/; round 63, theorem-engineering on
the RH-side wall -- the FREQUENCY-SPACE bookkeeping of the tail
pairing.  Predecessor CLII (PRIME.PORT.TAIL.ABEL.01) measured that
every classical absolute envelope on the deep tail fails by a
budget growing like e^{+1.744 alpha} against an O(1) need, and
typed the missing ingredient as "oscillation bookkeeping in the
psi-fluctuation pairing": the true arithmetic remainder is itself
~1e4 mu1 units and net-negative -- the tail sign is carried by
PHASE, which absolute envelopes discard.  THE FROZEN IDEA: measure
the phase structure directly.  The tail beyond the per-rung first
B-covering cut is the pairing
    P_h = <dF, q_g>_deep = sum_k f_k w_k,
    f_k = 2 (Lambda(k) - 1)/sqrt(k)   (k = n_c+1 .. N_g, ALL
          integers: the prime comb MINUS the PNT continuum on the
          integer grid -- exactly the increments of CLII's E1),
    w_k = q_v(log k)                  (the deployed piecewise-
          linear per-atom weight functional, lift-race S0
          verbatim),
so that P_h = tail_B(cB) - Ttilde EXACTLY (both ties warded).
Expand the WEIGHT over a declared frequency frame and pair each
frame function against the fluctuation:
    P_h = sum_j c_g(omega_j) Fhat(omega_j) + residual,
    c_g  = the weight's spectrum   (closed-form piecewise-linear
           integrals, exact),
    Fhat = the fluctuation's spectrum, Fhat(omega_j) =
           sum_k f_k psi_j(u_k),
and measure WHERE the net negativity lives on the omega axis.
2026-08-11.)

THE FRAME (frozen).  On the deep window [u0, uL], u0 = log(n_c+1),
uL = log(N_g), Lu = uL - u0, the orthonormal half-range cosine
frame
    psi_0(u) = 1/sqrt(Lu),
    psi_j(u) = sqrt(2/Lu) cos(omega_j (u - u0)),
    omega_j  = pi j / Lu,   j = 0 .. J-1,
    J = min(J_CAP, ceil(OMEGA_MAX Lu / pi) + 1)
(boxcar-windowed cosines at the harmonics of the deep window --
the natural frame the lag structure suggests: the weight is
piecewise linear on the lag grid, its even extension is continuous,
so its cosine coefficients decay ~ 1/omega^2 and a finite frame
carries the pairing; the frame is complete in L^2 as J -> inf and
orthonormal, so c_g(omega_j) = int w psi_j is basis-unambiguous).
OMEGA_MAX = 60 covers the first ten zeta ordinates (largest
49.774) with margin; frame resolution pi/Lu per rung is printed
with every carrier statement (honest: peaks narrower than the
resolution cannot be localized better than that, boxcar sidelobes
disclosed).  The weight coefficients c_g are computed in CLOSED
FORM piece by piece (the weight is exactly linear between lag
knots i*D; each piece contributes analytic sin/cos integrals);
Fhat and the atom-level reconstruction R(u_k) = sum_j c_j
psi_j(u_k) are accumulated in ONE pass over j via the Chebyshev
cosine recurrence cos((j+1)x) = 2 cos(x) cos(jx) - cos((j-1)x)
(spot-warded against direct cos evaluation).

WHAT IS MEASURED (frozen; typed, never kills unless marked WARD):
 (a) RECONSTRUCTION WARD (the >= 99% requirement): per rung the
     residual share |P - sum_j c_j Fhat_j| / |P| <= RES_WARD =
     0.01 for the arithmetic weight q_v (WARD, kill K2 -- the
     frame must account for >= 99% of the pairing before any
     census is read); Fubini ward: sum_k f_k R(u_k) ==
     sum_j c_j Fhat_j (pure order swap, <= FUB_WARD); frame-
     coefficient ward: closed-form c_j vs per-piece 5-point
     Gauss-Legendre at frozen spot indices (<= QUAD_WARD rel to
     max |c|); recurrence spot-ward vs direct cos (<= REC_WARD).
     Sup-norm reconstruction quality max|w - R|/max|w| printed
     (diagnostic, not a ward -- the pairing ward is the claim).
 (b) FREQUENCY CENSUS OF THE NET NEGATIVITY: per rung the signed
     contributions t_j = c_j Fhat_j toward P (sorted toward
     sign(P)); n50/n90 = minimal number of frequency bins whose
     partial sum reaches 50% / 90% of |P|; participation ratio
     PR = (sum|t|)^2 / sum t^2 (effective number of contributing
     bins); top carrier omega* = argmax |t_j|.  FEW-OR-MANY
     (decisive, typed): OSC-FEW iff med n90 <= FEW_N90 = 12 AND
     the top carrier is stable across rungs IN THE FRAME'S OWN
     COORDINATE (harmonic index j* = round(omega* Lu / pi):
     fraction of rungs with |j* - med j*| <= J_STAB_TOL = 1 is
     >= STAB_FRAC = 0.8; AMENDMENT A2, disclosed below -- the
     v0 absolute-omega stability read |omega* - med omega*| <=
     STAB_TOL = 0.5 is KEPT and printed, its smoke value 0.70
     stays on record as a FAIL of that coordinate); else
     OSC-BROAD.  Carrier drift law: jackknife slope of omega*
     vs alpha (recorded either way).
     The prime-free cross-check: the same census with q_{v_sm}
     (crossing rungs on their carrier branch as in round 62);
     agreement census |omega*_v - omega*_vsm| <= STAB_TOL
     (typed, recorded).
 (c) WHERE ARE THE CARRIERS (distances, not celebrations): per
     rung d_gamma = min_i |omega* - gamma_i| against the first
     ten LITERATURE zeta ordinates (hardcoded comparison
     constants, NEVER construction -- wall_margin S2 pattern);
     typed CARRIER-NEAR-GAMMA iff med d_gamma <= GAMMA_NEAR =
     0.5 (about half the uniform-null median ~ local gamma
     spacing/4 ~ 1.0, printed alongside), else CARRIER-FAR --
     an honest open measurement, either answer is a result.
     Classical scales: distance to the full-window harmonic comb
     pi k/(2 alpha) NORMALIZED by its half-spacing (comb spacing
     pi/(2 alpha) ~ 0.24 is DENSER than the frame resolution, so
     only the normalized distance is meaningful -- uniform null
     0.5, disclosed); the lag-knot fundamental 2 pi / D recorded
     as omega* D/(2 pi) (carriers vs the breakpoint scale).
 (d) THE PAIRING INEQUALITY SHAPE: if OSC-FEW, the reduced
     object: pool all per-rung n90 carriers weighted by |t_j|
     into a histogram on the absolute omega axis (bin RED_BIN =
     0.5), take the top K_RED = 12 centers, and re-read every
     rung through ONLY those frequencies: share_red = (sum of
     t_j with |omega_j - center| <= RED_HALF = 0.5) / P.
     REDUCED-ACHIEVED iff med share_red >= RED_MED = 0.90 and
     min share_red >= RED_MIN = 0.75: then the tail bound is a
     statement about K_RED fluctuation coefficients against
     classical weights -- written out explicitly with the
     measured coefficients at the median rung, and tau-screened.
     If OSC-BROAD: the effective dimension is the honest
     obstruction -- jackknife law log PR vs alpha and screen
     log PR vs log m.
 (e) TAU-SCREENS (typed, jackknife, bands PASS |s| <= 0.30 /
     RELOC s >= 0.70 / else AMBIG): log n90 vs log m; log PR vs
     log m; if reduced: log |P_red/mu1| vs log m (recorded).

FROZEN PROTOCOL (ladder machinery verbatim from
tail_abel_transport_probe.py = round-59/60/62/63 chain; v_sm
construction verbatim from arithmetic_lift_race_probe S0):

 W   LADDER + WARDS (kill -> PIPELINE-BROKEN / WARD-BROKEN): W1
     faithful ladder >= MIN_RUNGS = 40 (kz 2..KZMAX, H_MIN <= h
     <= HCAP, X <= ATOM_MAX); W2 WARD m_h > 0 everywhere; W3 WARD
     both exact bookkeepings (lift - demand = m AND e_ar + E_at =
     m) <= ID_WARD; W4 WARD atom identities <= ID_WARD; W5 WARD
     split exactness on the full scans <= SCAN_WARD; W6
     REPRODUCTION round 59/60/62: G > 0 counts at (50, 100, 200)
     == (52, 26, 25); n_min in [3, 9]; shared cut 9 covers N/N;
     tail_A <= 0 at first covering cut N/N; B-covering cuts exist
     N/N with n_minB med == 17 in [5, 47]; tail_B <= 0 at cB N/N;
     head_B(cB) med within HEADB_TOL of 0.388; W7 WARD v_sm
     branch (<= MAX_CROSS crossing rungs, carrier branch overlap
     >= OV_MIN); W8 WARD mu1 closed form == core.parity_mu(h)[0]
     exactly and the CXLIII shat band within SHAT_TOL of (0.502,
     1.027, 2.185); W9 WARD grid tie: the integer-grid tail
     T = sum a_k w_k equals tail_B(cB) <= TIE_WARD; W10 WARD
     pairing tie: (T - Ttilde) - P <= PAIR_WARD relative to
     sum |f||w| (distributivity bookkeeping); W11 frame wards:
     closed-form c_j vs GL5 (frozen spots: rung indices (0, N//2),
     j in (1, J//2, J-1), both weights) and cosine recurrence
     spot-ward at j = J-1 on the same rungs; W12 WARD
     reconstruction (a): Fubini <= FUB_WARD everywhere AND
     residual share <= RES_WARD on EVERY rung for q_v.

 A/B/G/R/T  as (b)/(b-few)/(c)/(d)/(e) above.

 C   CONTROLS at kz 9 (kill -> WARD-BROKEN if silent): C1
     scramble (seed 1), Epstein x^2+5y^2, smooth comb: each must
     show m < 0 AND zero covering cuts in BOTH senses (round-62
     criterion).  C2 SPECTRAL battery from the FIXED declared cut
     CTRL_CUT = 17 (controls have no covering cuts; the true kz-9
     rung is re-read at the SAME cut for apples-to-apples), each
     world paired through its OWN weight q_v, combs snapped to
     the integer grid by n = round(exp(u)) and aggregated
     (masses outside the deep grid dropped -- the deep-window
     restriction, declared):
       smooth world (AMENDMENT A3, disclosed below): the
         BY-CONSTRUCTION integer-continuum world Lambda == 1 on
         the whole deep grid has f == 0 IDENTICALLY, so Fhat == 0
         and the pairing dies EXACTLY -- verified as an identity
         (max|f| == 0 and P == 0, WARD); the DISCRETIZED smooth
         world (build_rung smooth comb snapped to integers) is
         RECORDED as a typed measurement -- its pairing is a
         quadrature-error object and does NOT die (the honest v0
         FAIL, on record);
       scramble: the CUMULATIVE structure is destroyed -- the
         PNT cancellation that keeps the true low-frequency
         spectrum small dies, the DC bin blows up:
         |Fhat_scr(0)| / |Fhat_true(0)| >= SCR_BLOWUP (WARD);
         the whiteness census (peakiness max|Fhat|^2 /
         mean|Fhat|^2, PR of spectral energy) is RECORDED;
       Epstein: different carrier signature RECORDED (its comb is
         measured against the SAME PNT continuum, declared -- the
         continuum-density mismatch appears as a low-frequency
         drift; omega*, d_gamma, drift factor typed as
         measurements, no kill).

KILLS: K1 ladder (W1) -> PIPELINE-BROKEN; K2 wards (W2-W12,
C1/C2-smooth/C2-scramble) -> WARD-BROKEN.  All typed A/B/G/R/T
outcomes are measurements, never kills.

VERDICT (frozen enum): OSCPAIR-MEASURED with typed sublabels
RECON-WARDED(max residual share),
OSC-FEW(med n50/n90, harmonic-index stability frac) /
OSC-BROAD(med n50/n90, med PR),
CARRIERS(med omega*, med j*, abs-omega stab, j-stab, drift slope
vs alpha),
GAMMA(med d_gamma vs null, count near, verdict NEAR/FAR) +
CLASSICAL(normalized window-comb distance, knot-scale ratio),
REDUCED-ACHIEVED(K, med share) / REDUCED-FAILED(med share) /
EFFDIM(med PR, law slope vs alpha),
SCREENS(n90, PR),
CTRL(...);  else PIPELINE-BROKEN / WARD-BROKEN.

FROZEN BARS: KZMAX = 150; MIN_RUNGS = 40; REF_CUTS = (50, 100,
200); REF_COUNTS = (52, 26, 25); NMIN_LO, NMIN_HI = 3, 9;
NC_SHARED = 9; NB_MED = 17; NB_LO, NB_HI = 5, 47; HEADB_MED =
0.388, HEADB_TOL = 0.01; SHAT_REF = (0.502, 1.027, 2.185),
SHAT_TOL = 1.5e-3; ID_WARD = 1e-10; SCAN_WARD = 1e-9; TIE_WARD =
1e-10; PAIR_WARD = 1e-12; FUB_WARD = 1e-9; QUAD_WARD = 1e-9 (rel
to max|c|); REC_WARD = 1e-9; RES_WARD = 0.01; MU_WARD = 1e-12;
NG_SMOOTH = 6000; OV_MIN = 0.8; MAX_CROSS = 2; OMEGA_MAX = 240.0
(amendment A1); J_CAP = 4096; GL5_SEG = 0.5 (amendment A1b);
FEW_N90 = 12; STAB_TOL = 0.5 (absolute omega, recorded);
J_STAB_TOL = 1 (harmonic index, gate -- amendment A2);
STAB_FRAC = 0.8; GAMMA_NEAR = 0.5; GAMMA_BAND_LO = 10.0;
RED_BIN = 0.5; RED_HALF = 0.5; K_RED = 12; RED_MED = 0.90;
RED_MIN = 0.75; SLOPE_PASS = 0.30; SLOPE_RELOC = 0.70; CTRL_KZ =
9; CTRL_CUT = 17; SMOOTH_ZERO = 0.0 exactly (amendment A3);
SCR_BLOWUP = 5.0; scramble seed 1; jackknife = full
leave-one-out, CI = +-2SE; blocked cumulative sums (block 1024)
wherever a cumsum feeds a ward.

SMOKE-RUN DISCLOSURE (2026-08-11, before freezing): THREE smoke
runs, full fail-first history.  SMOKE 1 (SPEC v0, OMEGA_MAX =
60, W12 FAILED at max residual share 2.38e-02 > 0.01): the
omega <= 60 frame carries only 97.6% of the pairing on the worst
rung -- the 1/omega^2 coefficient decay needs a larger budget.
AMENDMENT A1: OMEGA_MAX = 240 (frame budget only; ward, bars and
census rules untouched).  SMOKE 2 (W11 FAILED at GL5 dev 4.09e-06
> 1e-9): at omega ~ 240 a single 5-point Gauss rule per lag-knot
piece is no longer machine-exact (theta * width ~ 2).  AMENDMENT
A1b: the WARD ROUTE subdivides every piece until theta * segment
<= GL5_SEG = 0.5 (composite GL5; the closed form under test is
unchanged).  SMOKE 3 (22/22 checks except the declared C2a FAIL,
22.4 s) -- facts frozen as the context the frozen run must
confirm: (i) reconstruction warded: max residual share 5.50e-03,
Fubini 1.3e-15, GL5 (composite) and recurrence at the 1e-11
class; (ii) THE CARRYING SET IS TINY: n50 med 1 (1..2), n90 med
3 (1..8), PR med 3.5 (1.8..14.5) -- but the top carrier omega*
med 0.965 (0.383..2.249) FAILS the v0 absolute-omega stability
read (0.70 < 0.8) because it is LOCKED TO THE WINDOW HARMONICS:
omega* = j* pi/Lu with j* in {1, 2, 3} on 67/67 (drift law
omega* = -0.384 alpha + c, R^2 0.60 = the 1/Lu shrinkage of the
harmonics themselves).  AMENDMENT A2 (disclosed re-key): the
FEW gate reads stability in the frame's own coordinate j* =
round(omega* Lu/pi) (|j* - med j*| <= 1); the absolute-omega
read STAYS PRINTED with its 0.70 fail on record.  (iii) GAMMA
COMPARISON (honest, decisive): med d_gamma(omega*) = 13.17 vs
uniform null ~ 1.0, near on 0/67 -- the carriers are FAR from
the zeta ordinates (they sit BELOW gamma_1 = 14.13); the
gamma-band (omega >= 10) |t|-mass share is med 0.036: at these
window depths the pairing is NOT gamma-concentrated -- the
measured answer to the open question in (c).  (iv) Classical
scales: normalized window-comb distance med 0.42 ~ null 0.5
(uninformative, as declared); knot-scale ratio med 1.1e-03.
(v) v_sm agreement 50/67 within 0.5.  (vi) REDUCED read-through:
the top-12 pooled bins (all centers <= 5.25 except two trace
bins at 13.25/14.25) carry share_red min/med/max
+0.846/+1.006/+1.049 -- the whole pairing is ~12 low-frequency
coefficients.  (vii) Screens: n90 +0.034 PASS, PR +0.065 PASS
(tau-decorrelated); effective-dimension law (recorded) log PR =
-0.073 alpha (R^2 0.05, flat).  (viii) Controls: C1 3/3; the v0
C2a smooth ward FAILED as a DISCRETIZATION fact: the SNAPPED
smooth comb's quadrature-error pairing is 11.7x the (anomalously
small, +8.9e-02) true kz-9/cut-17 pairing -- the snapped world
does not die, only the by-construction integer continuum does.
AMENDMENT A3: C2a re-keyed to the by-construction world (f == 0
identically, exact-zero ward); the snapped world stays as a
recorded typed measurement.  Scramble DC blowup 3.26e+01 >= 5
FIRES; Epstein drift 1.57 with omega* 142.2 (d_gamma 92.4)
recorded.  AMENDMENTS beyond A1/A1b/A2/A3: NONE -- no other bar,
band, tolerance, enum or rule moved after the smokes; FEW_N90,
RED_MED/RED_MIN, GAMMA_NEAR, SCR_BLOWUP, all ladder wards and
both tau-screen bands are v0-verbatim.

SPEC v1 (2026-08-11, frozen + SHA-hashed before the frozen run):
everything above.  Mechanical concretizations frozen with v1:
(i) the cut is INCLUSIVE at the covering atom (grid starts at
n_c + 1); (ii) N_g = max(floor(X), largest window atom); (iii)
Lambda on the grid read from the deployed core.LAM_TAB (equality
of masses warded via the grid tie W9); (iv) the DC bin j = 0 is
a frame bin like any other (census includes it); (v) piece
endpoints evaluated by the deployed q_read (piecewise linearity
makes endpoint evaluation exact); (vi) runtime ~ 25 s (67 eigh
pairs + the J-recurrence over the deep grids dominate).

NO-GO COMPLIANCE (frozen): no certified-bound retry, no rank-1
approximation, no Herglotz; no fit where an identity is claimed
(the reconstruction, Fubini, quadrature and tie wards are exact
bookkeeping; all trends are typed jackknife screens).

NO RH claim: everything here is float-level MEASURED SURFACE
STRUCTURE on the 67-rung ladder; the direction v is computed
per-rung data (the round-62 uniformity boundary applies
verbatim); an OSC-FEW outcome would be a finite-dimensional
SURFACE statement, not a theorem, and an OSC-BROAD outcome is a
measured effective-dimension law, not a proof of impossibility.
The zeta ordinates appear ONLY as recorded comparison constants
in (c) -- never in any comb, frame, weight or window
construction.  No marker moves.

FIREWALL: no zeros in construction, no prime oracles (AST scan;
banned ids zetazero / nzeros / primerange / isprime / primepi /
nextprime / prevprime; Lambda is read from the DEPLOYED window
table only; GAMMAS is a hardcoded literature tuple used only in
distance REPORTS, wall_margin_mechanism_probe S2 pattern);
v563 READ-ONLY; RNG only inside the declared scramble control;
stdout only.

Sources (read-only): v563_paper2_readouts (core); ladder +
cut/scan machinery verbatim from tail_abel_transport_probe.py /
tail_sign_mechanism_probe.py (rounds 62/63); q_read + v_sm
construction verbatim from arithmetic_lift_race_probe.py; mu1
normalization from moving_node_second_order_probe.py (CXLIII);
gamma comparison pattern from wall_margin_mechanism_probe.py
(S2); round-62 censuses (declared reproduction targets).

Run:
    experiments/tfpt-discovery/.venv/bin/python \
        experiments/tfpt-discovery/tail_oscillation_pairing_probe.py
"""

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

import numpy as np

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

import v563_paper2_readouts as core        # noqa: E402  (READ-ONLY)

KZMAX = 150
MIN_RUNGS = 40
REF_CUTS = (50, 100, 200)
REF_COUNTS = (52, 26, 25)
NMIN_LO, NMIN_HI = 3, 9
NC_SHARED = 9
NB_MED = 17
NB_LO, NB_HI = 5, 47
HEADB_MED = 0.388
HEADB_TOL = 0.01
SHAT_REF = (0.502, 1.027, 2.185)
SHAT_TOL = 1.5e-3
ID_WARD = 1e-10
SCAN_WARD = 1e-9
TIE_WARD = 1e-10
PAIR_WARD = 1e-12
FUB_WARD = 1e-9
QUAD_WARD = 1e-9
REC_WARD = 1e-9
RES_WARD = 0.01
MU_WARD = 1e-12
NG_SMOOTH = 6000
OV_MIN = 0.8
MAX_CROSS = 2
OMEGA_MAX = 240.0
J_CAP = 4096
FEW_N90 = 12
STAB_TOL = 0.5
J_STAB_TOL = 1
STAB_FRAC = 0.8
GAMMA_NEAR = 0.5
RED_BIN = 0.5
RED_HALF = 0.5
K_RED = 12
RED_MED = 0.90
RED_MIN = 0.75
SLOPE_PASS = 0.30
SLOPE_RELOC = 0.70
CTRL_KZ = 9
CTRL_CUT = 17
SCR_BLOWUP = 5.0
GAMMA_BAND_LO = 10.0
BLOCK = 1024
# first ten zeta ordinates -- literature constants, used ONLY in
# the (c) distance reports (comparison, never construction); they
# are never fed to any comb, frame, weight, window or Toeplitz
# object (wall_margin_mechanism_probe S2 pattern)
GAMMAS = (14.134725141734693, 21.022039638771555,
          25.010857580145688, 30.424876125859513,
          32.935061587739190, 37.586178158825671,
          40.918719012147495, 43.327073280914999,
          48.005150881167159, 49.773832477672302)
BANNED_IDS = ("zetazero", "nzeros", "primerange", "isprime",
              "primepi", "nextprime", "prevprime")
GL5_SEG = 0.5
GL5_X = (-0.9061798459386640, -0.5384693101056831, 0.0,
         0.5384693101056831, 0.9061798459386640)
GL5_W = (0.2369268850561891, 0.4786286704993665,
         0.5688888888888889, 0.4786286704993665,
         0.2369268850561891)

CHECKS = []
KILLS = []
T0 = time.time()


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


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


def ast_scan(banned):
    src = open(os.path.abspath(__file__), encoding="utf-8").read()
    bad = []
    for node in ast.walk(ast.parse(src)):
        name = None
        if isinstance(node, ast.Name):
            name = node.id
        elif isinstance(node, ast.Attribute):
            name = node.attr
        if name and name.lower() in banned:
            bad.append(name)
    return bad


def ols_line(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    vx = float(np.var(x))
    if vx == 0.0:
        return float(np.mean(y)), 0.0, float("nan")
    b = float(np.cov(x, y, bias=True)[0, 1] / vx)
    a = float(np.mean(y) - b * np.mean(x))
    ss = float(np.sum((y - a - b * x) ** 2))
    st = float(np.sum((y - np.mean(y)) ** 2))
    return a, b, (1.0 - ss / st if st > 0 else float("nan"))


def jack_slope(x, y):
    x = np.asarray(x, float)
    y = np.asarray(y, float)
    _a, b, r2 = ols_line(x, y)
    n = len(x)
    bb = []
    for i in range(n):
        m = np.ones(n, bool)
        m[i] = False
        bb.append(ols_line(x[m], y[m])[1])
    bb = np.array(bb)
    se = math.sqrt((n - 1) / n * float(np.sum((bb - bb.mean())
                                              ** 2)))
    return b, se, r2


def q_read(W, u, D, M):
    u = np.asarray(u, float)
    i0 = np.floor(u / D).astype(int)
    f = u / D - i0
    val = np.zeros_like(u)
    ok0 = (i0 >= 0) & (i0 < M)
    val[ok0] += (1.0 - f[ok0]) * W[i0[ok0]]
    ok1 = (i0 + 1 >= 0) & (i0 + 1 < M)
    val[ok1] += f[ok1] * W[i0[ok1] + 1]
    refl = u < D
    val[refl] += (1.0 - u[refl] / D) * W[0]
    return -0.5 * val


def smooth_comb(alpha, ng=NG_SMOOTH):
    ug = (np.arange(ng) + 0.5) * (2.0 * alpha / ng)
    mg = 2.0 * np.exp(ug / 2.0) * (2.0 * alpha / ng)
    return ug, mg


def lambda_eps(N):
    """Epstein x^2+5y^2 comb (port_schur_reduction verbatim)."""
    r = np.zeros(N + 1)
    s = int(math.isqrt(N)) + 1
    for x in range(-s, s + 1):
        for y in range(-s, s + 1):
            v = x * x + 5 * y * y
            if 1 <= v <= N:
                r[v] += 1.0
    a = r / 2.0
    lam = np.zeros(N + 1)
    for n in range(2, N + 1):
        acc = a[n] * math.log(n)
        for dd in range(2, n):
            if n % dd == 0:
                acc -= lam[dd] * a[n // dd]
        lam[n] = acc
    return lam


def blocked_cumsum(x):
    x = np.asarray(x, float)
    n = len(x)
    if n <= BLOCK:
        return np.cumsum(x)
    pad = (-n) % BLOCK
    xb = np.concatenate([x, np.zeros(pad)]).reshape(-1, BLOCK)
    cs = np.cumsum(xb, axis=1)
    off = np.concatenate([[0.0], np.cumsum(cs[:-1, -1])])
    return (cs + off[:, None]).reshape(-1)[:n]


def build_rung(kz, comb=None, scramble_seed=None,
               smooth_world=False, need_sm=True):
    """One rung of the lift-race surface with both bookkeepings
    and the full atom-cut scans (tail_abel_transport_probe
    verbatim)."""
    try:
        rr = core.build_window(kz, scramble_seed=scramble_seed)
    except Exception:
        return None
    if not (core.H_MIN <= rr["h"] <= core.HCAP):
        return None
    if rr["X"] > core.ATOM_MAX:
        return None
    alpha, M, D, h = rr["alpha"], rr["M"], rr["D"], rr["h"]
    uu = np.asarray(rr["uu"], float)
    mu = 2.0 * np.asarray(rr["lam"], float)
    if smooth_world:
        du = np.zeros(len(uu))
        du[1:-1] = 0.5 * (uu[2:] - uu[:-2])
        du[0] = uu[1] - uu[0]
        du[-1] = uu[-1] - uu[-2]
        mu = 2.0 * np.exp(uu / 2.0) * du
    if comb is not None:
        uu, mu = comb
    c_at = core.atom_lags_at(alpha, M, uu, mu)[0]
    c_ar = np.asarray(core.arch_lags(M, D), float)
    w, V = np.linalg.eigh(core.odd_toeplitz(c_ar + c_at, M))
    v = V[:, 0]
    ug, mg = smooth_comb(alpha)
    c_sm = core.atom_lags_at(alpha, M, ug, mg)[0]
    row = dict(kz=kz, alpha=float(alpha), h=h, M=M, D=D,
               m=float(w[0]), uu=uu, mu=mu, X=float(rr["X"]))
    Wv = core.lag_weights_from_v(v, h)
    e_ar = float(c_ar @ Wv)
    e_t = float(c_at @ Wv)
    e_s = float(c_sm @ Wv)
    qa = mu * q_read(Wv, uu, D, M)
    qg = mg * q_read(Wv, ug, D, M)
    row.update(e_ar=e_ar, e_t=e_t, e_s=e_s, lift=e_t - e_s,
               demand=-(e_ar + e_s),
               dev_at=max(abs(float(qa.sum()) - e_t)
                          / max(abs(e_t), 1e-30),
                          abs(float(qg.sum()) - e_s)
                          / max(abs(e_s), 1e-30)))
    cq = np.cumsum(qa)
    idxg = np.searchsorted(ug, uu, side="right")
    cg_all = np.concatenate([[0.0], np.cumsum(qg)])
    head_err = cq - cg_all[idxg]
    G = head_err - row["demand"]
    tail_A = row["lift"] - head_err
    cert_A = G - np.abs(tail_A)
    head_B = e_ar + cq
    tail_B = float(qa.sum()) - cq
    cert_B = head_B - np.abs(tail_B)
    smoothtail = float(qg.sum()) - cg_all[idxg]
    row.update(G=G, tail_A=tail_A, cert_A=cert_A, head_B=head_B,
               tail_B=tail_B, cert_B=cert_B, smoothtail=smoothtail,
               qa=qa)
    row["Gref"] = {}
    for nc in REF_CUTS:
        ucut = math.log(nc)
        he = (float(qa[uu <= ucut].sum())
              - float(qg[ug <= ucut].sum()))
        row["Gref"][nc] = he - row["demand"]
    if need_sm:
        ws, Vs = np.linalg.eigh(core.odd_toeplitz(c_ar + c_sm, M))
        vsm = Vs[:, 0]
        if float(v @ vsm) < 0:
            vsm = -vsm
        ov4 = [abs(float(v @ Vs[:, j])) for j in range(4)]
        jcar = int(np.argmax(ov4))
        vcar = Vs[:, jcar] * (1.0 if float(v @ Vs[:, jcar]) >= 0
                              else -1.0)
        row.update(ov=float(abs(v @ vsm)), ov4=ov4, jcar=jcar)
        row["Wsm"] = core.lag_weights_from_v(vsm, h)
        row["Wcar"] = core.lag_weights_from_v(vcar, h)
    row["Wv"] = Wv
    return row


# ----------------------------------------------------- the frame
def frame_freqs(Lu):
    J = min(J_CAP, int(math.ceil(OMEGA_MAX * Lu / math.pi)) + 1)
    return np.pi * np.arange(J) / Lu, J


def weight_pieces(row, u0, uL, W):
    """Breakpoints of the piecewise-linear weight on [u0, uL]:
    the lag knots i*D strictly inside, plus the endpoints.
    Returns piece starts a, ends b, left values wa, slopes s
    (endpoint evaluation is exact for a piecewise-linear
    function)."""
    D, M = row["D"], row["M"]
    i_lo = int(math.floor(u0 / D)) + 1
    i_hi = int(math.ceil(uL / D)) - 1
    knots = D * np.arange(i_lo, i_hi + 1, dtype=float)
    knots = knots[(knots > u0 + 1e-12) & (knots < uL - 1e-12)]
    edges = np.concatenate([[u0], knots, [uL]])
    a_p, b_p = edges[:-1], edges[1:]
    wa = q_read(W, a_p, D, M)
    wb = q_read(W, b_p, D, M)
    s_p = (wb - wa) / (b_p - a_p)
    return a_p, b_p, wa, s_p


def cosine_coeffs(om, Lu, u0, a_p, b_p, wa, s_p):
    """Closed-form orthonormal half-range cosine coefficients of
    the piecewise-linear weight: per piece
    int (wa + s (u - a)) cos(theta (u - u0)) du analytic."""
    J = len(om)
    ga = a_p - u0
    gb = b_p - u0
    ln = b_p - a_p
    craw = np.empty(J)
    craw[0] = float(np.sum(wa * ln + 0.5 * s_p * ln * ln))
    th = om[1:][:, None]                       # (J-1, 1)
    sin_a = np.sin(th * ga[None, :])
    sin_b = np.sin(th * gb[None, :])
    cos_a = np.cos(th * ga[None, :])
    cos_b = np.cos(th * gb[None, :])
    I0 = (sin_b - sin_a) / th
    I1 = ln[None, :] * sin_b / th + (cos_b - cos_a) / (th * th)
    craw[1:] = I0 @ wa + I1 @ s_p
    c = craw.copy()
    c[0] /= math.sqrt(Lu)
    c[1:] *= math.sqrt(2.0 / Lu)
    return c


def gl5_coeff(om_j, Lu, u0, a_p, b_p, wa, s_p, j):
    """The same coefficient by composite 5-point Gauss-Legendre
    (independent exact-class route for the W11 ward): every
    piece is subdivided until theta * segment <= GL5_SEG, so the
    rule is machine-exact on each segment."""
    width = b_p - a_p
    ns = max(1, int(math.ceil(float(np.max(width))
                              * max(om_j, 1.0) / GL5_SEG)))
    tt = np.arange(ns, dtype=float) / ns
    A = (a_p[:, None] + width[:, None] * tt[None, :]).ravel()
    Wd = np.repeat(width / ns, ns)
    WA = (wa[:, None]
          + s_p[:, None] * (width[:, None] * tt[None, :])).ravel()
    S = np.repeat(s_p, ns)
    mid = A + 0.5 * Wd
    half = 0.5 * Wd
    acc = 0.0
    for xg, wg in zip(GL5_X, GL5_W):
        u = mid + half * xg
        wval = WA + S * (u - A)
        acc += wg * float(np.sum(half * wval
                                 * np.cos(om_j * (u - u0))))
    return acc * (1.0 / math.sqrt(Lu) if j == 0
                  else math.sqrt(2.0 / Lu))


def spectral_pair(ug, f, cv, cs, om, Lu, u0, rec_spot=False):
    """One pass over the frame: the fluctuation spectrum Fhat_j =
    sum_k f_k psi_j(u_k) and the atom-level reconstructions
    R = sum_j c_j psi_j(u_k) for both weights, via the Chebyshev
    cosine recurrence."""
    J = len(om)
    x = ug - u0
    n0 = 1.0 / math.sqrt(Lu)
    n1 = math.sqrt(2.0 / Lu)
    c1v = np.cos((math.pi / Lu) * x)
    Fh = np.empty(J)
    Rv = np.zeros(len(ug))
    Rs = np.zeros(len(ug))
    prev = np.ones(len(ug))
    cur = c1v.copy()
    rec_dev = 0.0
    for j in range(J):
        if j == 0:
            cj, nj = prev, n0
        elif j == 1:
            cj, nj = cur, n1
        else:
            nxt = 2.0 * c1v * cur - prev
            prev, cur = cur, nxt
            cj, nj = cur, n1
        Fh[j] = nj * float(f @ cj)
        Rv += (cv[j] * nj) * cj
        Rs += (cs[j] * nj) * cj
        if rec_spot and j == J - 1:
            direct = np.cos(om[j] * x)
            rec_dev = float(np.max(np.abs(cj - direct)))
    return Fh, Rv, Rs, rec_dev


def pairing_census(t, om):
    """Signed census of the contributions t_j toward the total:
    n50/n90 bins, participation ratio, top carrier."""
    tot = float(np.sum(t))
    sgn = 1.0 if tot >= 0.0 else -1.0
    order = np.argsort(-(t * sgn), kind="stable")
    pref = np.cumsum(t[order] * sgn)
    tgt = abs(tot)
    n50 = int(np.argmax(pref >= 0.5 * tgt)) + 1
    n90 = int(np.argmax(pref >= 0.9 * tgt)) + 1
    at = np.abs(t)
    pr = float(at.sum() ** 2 / max(float((at * at).sum()),
                                   1e-300))
    jstar = int(np.argmax(at))
    return dict(tot=tot, n50=n50, n90=n90, pr=pr,
                jstar=jstar, om_star=float(om[jstar]),
                S90=order[:n90])


def build_spectral(row, nc, spot=False):
    """The full frequency-space object of one rung: grid,
    fluctuation, both weights, frame, coefficients, spectrum,
    reconstruction wards, census."""
    Ng = max(int(math.floor(row["X"])),
             int(np.round(math.exp(float(row["uu"][-1])))))
    kk = np.arange(nc + 1, Ng + 1, dtype=np.int64)
    kf = kk.astype(float)
    ug = np.log(kf)
    lamg = core.LAM_TAB[nc + 1:Ng + 1]
    inv_sq = 1.0 / np.sqrt(kf)
    a = 2.0 * lamg * inv_sq
    f = a - 2.0 * inv_sq
    wv = q_read(row["Wv"], ug, row["D"], row["M"])
    Ws = row["Wcar"] if row["ov"] < OV_MIN else row["Wsm"]
    ws = q_read(Ws, ug, row["D"], row["M"])
    T = float(a @ wv)
    Tt = float((2.0 * inv_sq) @ wv)
    P_v = float(f @ wv)
    P_s = float(f @ ws)
    pair_scale = max(float(np.abs(f) @ np.abs(wv)), 1e-300)
    dev_pair = abs((T - Tt) - P_v) / pair_scale
    u0, uL = float(ug[0]), float(ug[-1])
    Lu = uL - u0
    om, J = frame_freqs(Lu)
    pv = weight_pieces(row, u0, uL, row["Wv"])
    ps = weight_pieces(row, u0, uL, Ws)
    cv = cosine_coeffs(om, Lu, u0, *pv)
    cs = cosine_coeffs(om, Lu, u0, *ps)
    Fh, Rv, Rs, rec_dev = spectral_pair(ug, f, cv, cs, om, Lu,
                                        u0, rec_spot=spot)
    P_rec_v = float(cv @ Fh)
    P_rec_s = float(cs @ Fh)
    res_v = abs(P_v - P_rec_v) / max(abs(P_v), 1e-300)
    res_s = abs(P_s - P_rec_s) / max(abs(P_s), 1e-300)
    dev_fub = max(abs(float(f @ Rv) - P_rec_v),
                  abs(float(f @ Rs) - P_rec_s)) / pair_scale
    sup_v = float(np.max(np.abs(wv - Rv))
                  / max(float(np.max(np.abs(wv))), 1e-300))
    quad_dev = 0.0
    if spot:
        for (pc, cc) in ((pv, cv), (ps, cs)):
            mxc = max(float(np.max(np.abs(cc))), 1e-300)
            for j in (1, J // 2, J - 1):
                g5 = gl5_coeff(float(om[j]), Lu, u0, *pc, j)
                quad_dev = max(quad_dev,
                               abs(cc[j] - g5) / mxc)
    t_v = cv * Fh
    t_s = cs * Fh
    cen_v = pairing_census(t_v, om)
    cen_s = pairing_census(t_s, om)
    return dict(T=T, Tt=Tt, P_v=P_v, P_s=P_s, dev_pair=dev_pair,
                res_v=res_v, res_s=res_s, dev_fub=dev_fub,
                sup_v=sup_v, quad_dev=quad_dev, rec_dev=rec_dev,
                om=om, J=J, Lu=Lu, Fh=Fh, cv=cv, cs=cs,
                t_v=t_v, cen_v=cen_v, cen_s=cen_s)


def ctrl_spectral(r, cut):
    """C2 control read: comb snapped to the integer grid by
    n = round(exp(u)), aggregated, paired through the world's
    OWN weight from the fixed cut."""
    Ng = int(math.floor(r["X"]))
    nn = np.round(np.exp(np.asarray(r["uu"], float))
                  ).astype(np.int64)
    ag = np.zeros(Ng + 2)
    keep = (nn >= cut + 1) & (nn <= Ng)
    np.add.at(ag, nn[keep], np.asarray(r["mu"], float)[keep])
    kk = np.arange(cut + 1, Ng + 1, dtype=np.int64)
    kf = kk.astype(float)
    ug = np.log(kf)
    inv_sq = 1.0 / np.sqrt(kf)
    f = ag[kk] - 2.0 * inv_sq
    wv = q_read(r["Wv"], ug, r["D"], r["M"])
    P = float(f @ wv)
    u0, uL = float(ug[0]), float(ug[-1])
    Lu = uL - u0
    om, J = frame_freqs(Lu)
    x = ug - u0
    c1v = np.cos((math.pi / Lu) * x)
    Fh = np.empty(J)
    prev = np.ones(len(ug))
    cur = c1v.copy()
    for j in range(J):
        if j == 0:
            cj, nj = prev, 1.0 / math.sqrt(Lu)
        elif j == 1:
            cj, nj = cur, math.sqrt(2.0 / Lu)
        else:
            nxt = 2.0 * c1v * cur - prev
            prev, cur = cur, nxt
            cj, nj = cur, math.sqrt(2.0 / Lu)
        Fh[j] = nj * float(f @ cj)
    e2 = Fh * Fh
    pk = float(np.max(e2) / max(float(np.mean(e2)), 1e-300))
    prF = float(e2.sum() ** 2 / max(float((e2 * e2).sum()),
                                    1e-300))
    jstar = int(np.argmax(np.abs(Fh)))
    return dict(P=P, F0=float(Fh[0]), pk=pk, prF=prF,
                om_star=float(om[jstar]), om=om, Fh=Fh)


def dist_to_comb(w, spacing):
    rem = math.fmod(w, spacing)
    return min(rem, spacing - rem)


def main():
    section("PRIME.PORT.TAIL.OSCPAIR.01 -- the frequency-space "
            "bookkeeping of the tail pairing (EXPLORATION ONLY)")
    print("    FROZEN_SPEC SHA-256 = %s"
          % hashlib.sha256(__doc__.encode("utf-8")).hexdigest())
    print("    NO RH claim; no marker moves; the zeta ordinates "
          "are literature comparison constants only.")
    print("\nS0 -- firewall")
    check("S0.1 AST firewall clean", not ast_scan(BANNED_IDS))

    # ------------------------------------------------------------ W
    section("W -- the faithful ladder + wards")
    rungs = []
    for kz in range(2, KZMAX + 1):
        row = build_rung(kz)
        if row is not None:
            rungs.append(row)
    rungs.sort(key=lambda r: (r["h"], r["kz"]))
    check("W1 faithful ladder >= %d rungs" % MIN_RUNGS,
          len(rungs) >= MIN_RUNGS,
          "%d rungs, h %d..%d  [%.1f s]"
          % (len(rungs), rungs[0]["h"], rungs[-1]["h"],
             time.time() - T0), kill="K1")
    if KILLS:
        return finish({})
    N = len(rungs)
    check("W2 WARD truth margin m_h > 0 on every rung (min %.3e)"
          % min(r["m"] for r in rungs),
          all(r["m"] > 0 for r in rungs), kill="K2")
    dev_bk = max(max(abs((r["lift"] - r["demand"]) - r["m"]),
                     abs((r["e_ar"] + r["e_t"]) - r["m"]))
                 / max(1.0, abs(r["m"])) for r in rungs)
    check("W3 WARD both exact bookkeepings: max dev %.2e <= %.0e"
          % (dev_bk, ID_WARD), dev_bk <= ID_WARD, kill="K2")
    dev_at = max(r["dev_at"] for r in rungs)
    check("W4 WARD atom identities (atom sum = E_at, PNT grid = "
          "E_sm): max rel dev %.2e <= %.0e" % (dev_at, ID_WARD),
          dev_at <= ID_WARD, kill="K2")
    dev_sc = 0.0
    for r in rungs:
        sc = max(float(np.max(np.abs((r["head_B"] + r["tail_B"])
                                     - r["m"]))),
                 float(np.max(np.abs((r["G"] + r["tail_A"])
                                     - r["m"]))),
                 float(np.max(np.abs(r["G"] - r["head_B"]
                                     - r["smoothtail"]))))
        dev_sc = max(dev_sc, sc / max(1.0, abs(r["e_t"])))
    check("W5 WARD split exactness on the full scans: max rel "
          "dev %.2e <= %.0e" % (dev_sc, SCAN_WARD),
          dev_sc <= SCAN_WARD, kill="K2")
    cnts = tuple(int(np.sum(np.array(
        [r["Gref"][nc] for r in rungs]) > 0)) for nc in REF_CUTS)
    n_min, nB_min, icBs, tB_neg = [], [], [], 0
    for r in rungs:
        nn = np.round(np.exp(r["uu"])).astype(int)
        covA = r["cert_A"] > 0.0
        i0 = int(np.argmax(covA)) if bool(np.any(covA)) else -1
        n_min.append(int(nn[i0]) if i0 >= 0 else -1)
        covB = r["cert_B"] > 0.0
        icB = int(np.argmax(covB)) if bool(np.any(covB)) else -1
        icBs.append(icB)
        nB_min.append(int(nn[icB]) if icB >= 0 else -1)
        if icB >= 0 and float(r["tail_B"][icB]) <= 0.0:
            tB_neg += 1
    i9s = [int(np.searchsorted(r["uu"],
                               math.log(NC_SHARED) + 1e-12,
                               side="right")) - 1 for r in rungs]
    cov9 = sum(1 for r, i9 in zip(rungs, i9s)
               if i9 >= 0 and r["cert_A"][i9] > 0)
    tA_neg = sum(1 for r in rungs if bool(np.any(r["cert_A"] > 0))
                 and r["tail_A"][int(np.argmax(
                     r["cert_A"] > 0))] <= 0.0)
    covB_n = sum(1 for i in icBs if i >= 0)
    hBc = np.array([float(r["head_B"][i])
                    for r, i in zip(rungs, icBs)])
    medB = float(np.median([n for n in nB_min if n > 0]))
    ok_rep = (cnts == REF_COUNTS
              and all(NMIN_LO <= nm <= NMIN_HI for nm in n_min)
              and cov9 == N and tA_neg == N and covB_n == N
              and medB == NB_MED
              and min(nB_min) >= NB_LO and max(nB_min) <= NB_HI
              and tB_neg == N
              and abs(float(np.median(hBc)) - HEADB_MED)
              <= HEADB_TOL)
    check("W6 REPRODUCTION 59/60/62: G > 0 at %s = %s == %s; "
          "n_min in [%d, %d]; cut 9 covers %d/%d; tail_A <= 0 "
          "%d/%d; B-cuts exist %d/%d, n_minB med %d in [%d, %d]; "
          "tail_B <= 0 at cB %d/%d; head_B(cB) med %.3f ~ %.3f"
          % (REF_CUTS, cnts, REF_COUNTS, NMIN_LO, NMIN_HI, cov9,
             N, tA_neg, N, covB_n, N, int(medB), min(nB_min),
             max(nB_min), tB_neg, N, float(np.median(hBc)),
             HEADB_MED), ok_rep, kill="K2")
    n_cross = sum(1 for r in rungs if r["ov"] < OV_MIN)
    cross_ok = all(max(r["ov4"]) >= OV_MIN for r in rungs
                   if r["ov"] < OV_MIN)
    check("W7 WARD v_sm branch: %d crossing rung(s) (%s; ward <= "
          "%d), carrier ok"
          % (n_cross,
             ", ".join("kz%d ov %.4f" % (r["kz"], r["ov"])
                       for r in rungs if r["ov"] < OV_MIN)
             or "none", MAX_CROSS),
          n_cross <= MAX_CROSS and cross_ok, kill="K2")
    mu1 = np.array([float(core.parity_mu(r["h"])[0])
                    for r in rungs])
    mu1_cf = np.array([4.0 * math.sin(math.pi
                                      / (2 * r["h"] + 1)) ** 2
                       for r in rungs])
    dev_mu = float(np.max(np.abs(mu1 - mu1_cf)
                          / np.maximum(mu1, 1e-300)))
    mm = np.array([r["m"] for r in rungs])
    shat = mm / mu1
    s3 = (float(np.min(shat)), float(np.median(shat)),
          float(np.max(shat)))
    ok_shat = all(abs(s3[i] - SHAT_REF[i]) <= SHAT_TOL
                  for i in range(3))
    check("W8 WARD mu1 closed form (dev %.1e) + CXLIII shat band "
          "min/med/max %.4f/%.4f/%.4f ~ %s"
          % (dev_mu, s3[0], s3[1], s3[2], SHAT_REF),
          dev_mu <= MU_WARD and ok_shat, kill="K2")
    if KILLS:
        return finish({})

    # ------------------------------------- the spectral objects
    spec = []
    spot_at = (0, N // 2)
    for i, (r, icB, nc) in enumerate(zip(rungs, icBs, nB_min)):
        spec.append(build_spectral(r, nc, spot=(i in spot_at)))
    tie = max(abs(s["T"] - float(r["tail_B"][i]))
              / max(1.0, abs(float(r["tail_B"][i])))
              for s, r, i in zip(spec, rungs, icBs))
    check("W9 WARD grid tie: integer-grid tail == tail_B(cB) "
          "max rel dev %.2e <= %.0e  [%.1f s]"
          % (tie, TIE_WARD, time.time() - T0),
          tie <= TIE_WARD, kill="K2")
    dev_pr = max(s["dev_pair"] for s in spec)
    check("W10 WARD pairing tie: (T - Ttilde) - P == 0 max rel "
          "dev %.2e <= %.0e" % (dev_pr, PAIR_WARD),
          dev_pr <= PAIR_WARD, kill="K2")
    qd = max(s["quad_dev"] for s in spec)
    rd = max(s["rec_dev"] for s in spec)
    check("W11 WARD frame: closed-form c_j vs GL5 at frozen "
          "spots %.2e <= %.0e; cosine recurrence vs direct "
          "%.2e <= %.0e" % (qd, QUAD_WARD, rd, REC_WARD),
          qd <= QUAD_WARD and rd <= REC_WARD, kill="K2")
    fub = max(s["dev_fub"] for s in spec)
    res_mx = max(s["res_v"] for s in spec)
    check("W12 WARD reconstruction: Fubini max %.2e <= %.0e; "
          "residual share max %.2e <= %.2f on all %d rungs "
          "(the >= 99%% requirement; sup-norm weight recon med "
          "%.1e, diagnostic)"
          % (fub, FUB_WARD, res_mx, RES_WARD, N,
             float(np.median([s["sup_v"] for s in spec]))),
          fub <= FUB_WARD and res_mx <= RES_WARD, kill="K2")
    if KILLS:
        return finish({})
    lab_w = "RECON-WARDED(max res share %.1e)" % res_mx

    # ------------------------------------------------------------ A
    section("A -- (a)+(b) THE FREQUENCY CENSUS OF THE NET "
            "NEGATIVITY (arithmetic weight q_v)")
    aa = np.array([r["alpha"] for r in rungs])
    Pv = np.array([s["P_v"] for s in spec])
    n50 = np.array([s["cen_v"]["n50"] for s in spec])
    n90 = np.array([s["cen_v"]["n90"] for s in spec])
    prs = np.array([s["cen_v"]["pr"] for s in spec])
    oms = np.array([s["cen_v"]["om_star"] for s in spec])
    Js = np.array([s["J"] for s in spec])
    resl = np.array([math.pi / s["Lu"] for s in spec])
    dg = np.array([min(abs(w - g) for g in GAMMAS) for w in oms])
    print("    kz   h    nc  P/mu1       res_share  J    n50  "
          "n90  PR      omega*  d_gamma  resol")
    for i, r in enumerate(rungs):
        print("    %-4d %-4d %-3d %+.3e %.2e %-4d %-4d %-4d "
              "%-7.1f %-7.3f %-8.3f %.3f"
              % (r["kz"], r["h"], nB_min[i], Pv[i] / mu1[i],
                 spec[i]["res_v"], Js[i], n50[i], n90[i],
                 prs[i], oms[i], dg[i], resl[i]), flush=True)
    print("\n    P/mu1 min/med/max %+.3e/%+.3e/%+.3e (the CLII "
          "arithmetic remainder rhat, reproduced by tie); "
          "P < 0 on %d/%d"
          % (float(np.min(Pv / mu1)), float(np.median(Pv / mu1)),
             float(np.max(Pv / mu1)), int(np.sum(Pv < 0)), N))
    print("    carrying-set ladder: n50 med %d (%d..%d), n90 med "
          "%d (%d..%d), PR med %.1f (%.1f..%.1f); frame size J "
          "med %d"
          % (int(np.median(n50)), int(n50.min()), int(n50.max()),
             int(np.median(n90)), int(n90.min()), int(n90.max()),
             float(np.median(prs)), float(prs.min()),
             float(prs.max()), int(np.median(Js))))
    lab_a = ("CENSUS(n50 med %d, n90 med %d, PR med %.1f)"
             % (int(np.median(n50)), int(np.median(n90)),
                float(np.median(prs))))
    check("A.1 typed (b) census: %s" % lab_a, True)

    # ------------------------------------------------------------ B
    section("B -- (b) FEW-OR-MANY + carrier stability across "
            "rungs")
    om_med = float(np.median(oms))
    stab = float(np.mean(np.abs(oms - om_med) <= STAB_TOL))
    jstars = np.array([int(round(w * s["Lu"] / math.pi))
                       for w, s in zip(oms, spec)])
    j_med = int(np.median(jstars))
    stab_j = float(np.mean(np.abs(jstars - j_med) <= J_STAB_TOL))
    slD, seD, r2D = jack_slope(aa, oms)
    few = (float(np.median(n90)) <= FEW_N90
           and stab_j >= STAB_FRAC)
    oms_s = np.array([s["cen_s"]["om_star"] for s in spec])
    agree = int(np.sum(np.abs(oms - oms_s) <= STAB_TOL))
    print("    top carrier omega*: med %.3f (min/max %.3f/%.3f); "
          "ABSOLUTE-omega stability frac |omega* - med| <= %.1f: "
          "%.2f (recorded; smoke FAIL of this coordinate on "
          "record); drift law omega* = %+.3f alpha + c (2SE "
          "%.3f, R^2 %.2f)"
          % (om_med, float(oms.min()), float(oms.max()),
             STAB_TOL, stab, slD, 2 * seD, r2D))
    print("    HARMONIC-INDEX read (amendment A2, the gate): "
          "j* = round(omega* Lu/pi) med %d (min/max %d/%d); "
          "stability frac |j* - med| <= %d: %.2f (bar %.2f) -- "
          "the carrier in the frame's own coordinate"
          % (j_med, int(jstars.min()), int(jstars.max()),
             J_STAB_TOL, stab_j, STAB_FRAC))
    print("    v_sm cross-check (prime-free weight): omega* "
          "agreement within %.1f on %d/%d; n90(v_sm) med %d"
          % (STAB_TOL, agree, N,
             int(np.median([s["cen_s"]["n90"] for s in spec]))))
    if few:
        lab_b = ("OSC-FEW(n90 med %d <= %d, j-stab %.2f, "
                 "abs-stab %.2f recorded)"
                 % (int(np.median(n90)), FEW_N90, stab_j, stab))
        print("    ==> the carrying set is SMALL and STABLE: a "
              "finite-dimensional pairing statement is on the "
              "table (section R)")
    else:
        lab_b = ("OSC-BROAD(n90 med %d, PR med %.1f, j-stab "
                 "%.2f)" % (int(np.median(n90)),
                            float(np.median(prs)), stab_j))
        print("    ==> the carrying set is BROAD and/or "
              "unstable: genuinely diffuse cancellation -- the "
              "effective dimension is the honest obstruction "
              "(section R)")
    check("B.1 typed (b) few-or-many: %s" % lab_b, True)

    # ------------------------------------------------------------ G
    section("G -- (c) WHERE ARE THE CARRIERS: classical scales "
            "vs the first ten zeta ordinates (COMPARISON ONLY)")
    null_g = float(np.median(np.diff(np.array(GAMMAS)))) / 4.0
    dwin = np.array([dist_to_comb(w, math.pi / (2.0 * al))
                     / (math.pi / (4.0 * al))
                     for w, al in zip(oms, aa)])
    dknot = np.array([w * r["D"] / (2.0 * math.pi)
                      for w, r in zip(oms, rungs)])
    gband = np.array([
        float(np.abs(s["t_v"])[s["om"] >= GAMMA_BAND_LO].sum()
              / max(float(np.abs(s["t_v"]).sum()), 1e-300))
        for s in spec])
    n_near = int(np.sum(dg <= GAMMA_NEAR))
    print("    d_gamma(omega*): med %.3f (min/max %.3f/%.3f); "
          "uniform-null scale ~ %.2f (local gamma spacing/4); "
          "near (<= %.1f) on %d/%d"
          % (float(np.median(dg)), float(dg.min()),
             float(dg.max()), null_g, GAMMA_NEAR, n_near, N))
    print("    gamma-BAND share (|t| mass at omega >= %.0f, "
          "where the ordinates live): med %.3f (min/max "
          "%.3f/%.3f) -- energy census, not a peak claim"
          % (GAMMA_BAND_LO, float(np.median(gband)),
             float(gband.min()), float(gband.max())))
    print("    window-harmonic comb pi k/(2 alpha): NORMALIZED "
          "distance med %.3f (uniform null 0.5 -- the comb "
          "spacing %.3f..%.3f is denser than the frame "
          "resolution, disclosed)"
          % (float(np.median(dwin)),
             math.pi / (2.0 * float(aa.max())),
             math.pi / (2.0 * float(aa.min()))))
    print("    lag-knot fundamental 2 pi / D: omega* D/(2 pi) "
          "med %.2e -- carriers vs the breakpoint scale"
          % float(np.median(dknot)))
    ver_g = ("CARRIER-NEAR-GAMMA" if float(np.median(dg))
             <= GAMMA_NEAR else "CARRIER-FAR")
    lab_g = ("GAMMA(med d %.2f vs null %.2f, near %d/%d, %s) + "
             "CLASSICAL(win-comb %.2f, knot %.1e)"
             % (float(np.median(dg)), null_g, n_near, N, ver_g,
                float(np.median(dwin)),
                float(np.median(dknot))))
    check("G.1 typed (c): %s -- distances, not celebrations"
          % lab_g, True)

    # ------------------------------------------------------------ R
    section("R -- (d) THE PAIRING INEQUALITY SHAPE")
    # pooled carrier histogram on the absolute omega axis
    hist = {}
    for s in spec:
        S90 = s["cen_v"]["S90"]
        for j in S90:
            b = int(s["om"][j] / RED_BIN)
            hist[b] = hist.get(b, 0.0) + abs(s["t_v"][j])
    top = sorted(hist.items(), key=lambda kvv: -kvv[1])[:K_RED]
    centers = np.array(sorted((b + 0.5) * RED_BIN
                              for b, _w in top))
    shares = []
    Pred = []
    for s in spec:
        d = np.min(np.abs(s["om"][:, None] - centers[None, :]),
                   axis=1)
        pin = float(s["t_v"][d <= RED_HALF].sum())
        Pred.append(pin)
        shares.append(pin / s["P_v"] if s["P_v"] != 0 else 0.0)
    shares = np.array(shares)
    Pred = np.array(Pred)
    print("    pooled top-%d carrier bins (centers, weight "
          "share of pooled |t| mass):" % K_RED)
    wtot = sum(hist.values())
    for b, wgt in top:
        print("      omega ~ %6.2f   pooled share %.3f"
              % ((b + 0.5) * RED_BIN, wgt / wtot))
    print("    reduced read-through (only |omega - center| <= "
          "%.1f): share_red min/med/max %+.3f/%+.3f/%+.3f"
          % (RED_HALF, float(shares.min()),
             float(np.median(shares)), float(shares.max())))
    reduced = (few and float(np.median(shares)) >= RED_MED
               and float(shares.min()) >= RED_MIN)
    if reduced:
        imed = int(np.argsort(Pv)[len(Pv) // 2])
        s = spec[imed]
        print("    ==> REDUCED PAIRING STATEMENT (median rung "
              "kz %d): P = sum over the %d frozen carriers of "
              "c_g(omega_i) Fhat(omega_i) + res"
              % (rungs[imed]["kz"], K_RED))
        d = np.min(np.abs(s["om"][:, None] - centers[None, :]),
                   axis=1)
        for j in np.nonzero(d <= RED_HALF)[0]:
            print("      omega %6.2f: c_g %+.3e  Fhat %+.3e  "
                  "t %+.3e" % (s["om"][j], s["cv"][j],
                               s["Fh"][j], s["t_v"][j]))
        lab_r = ("REDUCED-ACHIEVED(K=%d, med share %.2f)"
                 % (K_RED, float(np.median(shares))))
    elif few:
        lab_r = ("REDUCED-FAILED(med share %.2f < %.2f)"
                 % (float(np.median(shares)), RED_MED))
        print("    ==> carrying set small per rung but NOT "
              "poolable into %d global frequencies" % K_RED)
    else:
        slP, seP, r2P = jack_slope(aa, np.log(prs))
        lab_r = ("EFFDIM(PR med %.1f, law %+.3f alpha, 2SE "
                 "%.3f, R^2 %.2f)"
                 % (float(np.median(prs)), slP, 2 * seP, r2P))
        print("    ==> THE EFFECTIVE-DIMENSION LAW (the honest "
              "obstruction): log PR = %+.3f alpha + c (2SE "
              "%.3f, R^2 %.2f) -- the number of frequency bins "
              "the cancellation genuinely uses grows ~ "
              "e^{%.2f alpha}" % (slP, 2 * seP, r2P, slP))
    check("R.1 typed (d): %s" % lab_r, True)

    # ------------------------------------------------------------ T
    section("T -- (e) TAU-SCREENS (jackknife, typed)")
    sl1, se1, r21 = jack_slope(np.log(mm), np.log(n90))
    scr1 = ("PASS" if abs(sl1) <= SLOPE_PASS else
            "RELOC" if sl1 >= SLOPE_RELOC else "AMBIG")
    print("    screen log n90 vs log m: slope %+.3f +- 2SE %.3f "
          "(R^2 %.2f) -> %s" % (sl1, 2 * se1, r21, scr1))
    sl2, se2, r22 = jack_slope(np.log(mm), np.log(prs))
    scr2 = ("PASS" if abs(sl2) <= SLOPE_PASS else
            "RELOC" if sl2 >= SLOPE_RELOC else "AMBIG")
    print("    screen log PR vs log m: slope %+.3f +- 2SE %.3f "
          "(R^2 %.2f) -> %s" % (sl2, 2 * se2, r22, scr2))
    ex = ""
    if reduced:
        okp = np.abs(Pred) > 0
        sl3, se3, r23 = jack_slope(
            np.log(mm[okp]), np.log(np.abs(Pred[okp] / mu1[okp])))
        ex = ("; reduced-margin screen log|P_red/mu1| vs log m "
              "%+.3f (2SE %.3f, R^2 %.2f, recorded)"
              % (sl3, 2 * se3, r23))
        print("    " + ex[2:])
    lab_t = ("SCREENS(n90 %+.2f %s, PR %+.2f %s%s)"
             % (sl1, scr1, sl2, scr2, ex))
    check("T.1 typed (e): %s" % lab_t, True)

    # ------------------------------------------------------------ C
    section("C -- controls on this surface at kz %d" % CTRL_KZ)
    rr9 = core.build_window(CTRL_KZ)
    N_E = int(math.floor(math.exp(2.0 * rr9["alpha"]))) + 1
    lamE_ = lambda_eps(N_E)
    nnE = np.nonzero(np.abs(lamE_) > 1e-12)[0]
    ctl = {}
    ctl["Epstein"] = build_rung(CTRL_KZ, comb=(
        np.log(nnE.astype(float)),
        2.0 * lamE_[nnE] / np.sqrt(nnE.astype(float))),
        need_sm=False)
    ctl["scramble"] = build_rung(CTRL_KZ, scramble_seed=1,
                                 need_sm=False)
    ctl["smooth"] = build_rung(CTRL_KZ, smooth_world=True,
                               need_sm=False)
    fired = True
    for name, r in ctl.items():
        if r is None:
            print("    %-9s: rung dies -> fires" % name)
            continue
        ncovA = int(np.sum(r["cert_A"] > 0))
        ncovB = int(np.sum(r["cert_B"] > 0))
        f = (r["m"] < 0) and ncovA == 0 and ncovB == 0
        fired &= f
        print("    %-9s: m %+.3e  covering cuts A/B %d/%d -> %s"
              % (name, r["m"], ncovA, ncovB,
                 "FIRES" if f else "SILENT"), flush=True)
    check("C1 WARD all three controls fire (m < 0 and zero "
          "coverage in BOTH senses)", fired, kill="K2")
    # C2 -- the spectral battery from the fixed cut CTRL_CUT
    rtrue = build_rung(CTRL_KZ, need_sm=False)
    st = ctrl_spectral(rtrue, CTRL_CUT)
    print("    true kz-%d at cut %d: P %+.3e  |Fhat(0)| %.3e  "
          "peakiness %.1f  PR_F %.1f  omega* %.3f"
          % (CTRL_KZ, CTRL_CUT, st["P"], abs(st["F0"]),
             st["pk"], st["prF"], st["om_star"]))
    sc2 = {}
    for name in ("smooth", "scramble", "Epstein"):
        sc2[name] = ctrl_spectral(ctl[name], CTRL_CUT)
        dgc = min(abs(sc2[name]["om_star"] - g) for g in GAMMAS)
        print("    %-9s: P %+.3e (ratio %.3e)  |Fhat(0)|-blowup "
              "%.3e  peakiness %.1f  PR_F %.1f  omega* %.3f "
              "(d_gamma %.1f)"
              % (name, sc2[name]["P"],
                 abs(sc2[name]["P"]) / max(abs(st["P"]), 1e-300),
                 abs(sc2[name]["F0"]) / max(abs(st["F0"]),
                                            1e-300),
                 sc2[name]["pk"], sc2[name]["prF"],
                 sc2[name]["om_star"], dgc), flush=True)
    # C2a -- the by-construction integer-continuum world
    # (amendment A3): Lambda == 1 on the whole deep grid, so
    # f = 2(1 - 1)/sqrt(k) == 0 identically and the pairing dies
    # exactly; read through the true rung's weight (any weight
    # gives zero -- that is the point).
    Ng0 = int(math.floor(rtrue["X"]))
    kk0 = np.arange(CTRL_CUT + 1, Ng0 + 1, dtype=np.int64)
    inv0 = 1.0 / np.sqrt(kk0.astype(float))
    f0 = 2.0 * np.ones(len(kk0)) * inv0 - 2.0 * inv0
    w0 = q_read(rtrue["Wv"], np.log(kk0.astype(float)),
                rtrue["D"], rtrue["M"])
    P0 = float(f0 @ w0)
    rat_sm = abs(sc2["smooth"]["P"]) / max(abs(st["P"]), 1e-300)
    check("C2a WARD by-construction smooth world dies exactly: "
          "max|f| = %.1e, P = %.1e (both == 0; Fhat == 0 "
          "identically).  The DISCRETIZED (snapped) smooth "
          "world is a quadrature-error object and does NOT die: "
          "|P_sm|/|P_true| = %.3e (recorded, the honest v0 "
          "fail)" % (float(np.max(np.abs(f0))), P0, rat_sm),
          float(np.max(np.abs(f0))) == 0.0 and P0 == 0.0,
          kill="K2")
    blow = (abs(sc2["scramble"]["F0"])
            / max(abs(st["F0"]), 1e-300))
    check("C2b WARD scramble DC blowup: |Fhat_scr(0)|/"
          "|Fhat_true(0)| = %.3e >= %.1f (the PNT cancellation "
          "is destroyed)" % (blow, SCR_BLOWUP),
          blow >= SCR_BLOWUP, kill="K2")
    lab_c = ("CTRL(smooth exact-zero dies + snapped %.1e "
             "recorded, scramble blowup %.1e FIRES, Epstein "
             "drift %.1e omega* %.2f recorded)"
             % (rat_sm, blow,
                abs(sc2["Epstein"]["F0"]) / max(abs(st["F0"]),
                                                1e-300),
                sc2["Epstein"]["om_star"]))
    check("C3 typed control battery: %s" % lab_c, True)

    return finish(dict(w=lab_w, b=lab_b, g=lab_g, r=lab_r,
                       t=lab_t, c=lab_c))


def finish(labels):
    section("V -- FROZEN VERDICT")
    n_pass = sum(1 for _n, okk in CHECKS if okk)
    n_tot = len(CHECKS)
    if KILLS:
        VERDICT = {"K1": "PIPELINE-BROKEN",
                   "K2": "WARD-BROKEN"}[KILLS[0]]
        print("\n  VERDICT: %s" % VERDICT)
    else:
        VERDICT = ("OSCPAIR-MEASURED / %(w)s / %(b)s / %(g)s / "
                   "%(r)s / %(t)s / %(c)s" % labels)
        print("\n  VERDICT: %s" % VERDICT)
    print("""
  HONEST FRAME (as frozen): the frame expansion, the Fubini swap,
  the closed-form coefficients and the ties are EXACT bookkeeping;
  the census, carrier locations and all laws are MEASURED SURFACE
  STRUCTURE at float level.  The zeta ordinates enter ONLY as
  recorded comparison constants -- a near or far answer is a
  measurement either way, never a construction input.  An OSC-FEW
  outcome would be a per-rung surface statement, not a theorem; an
  OSC-BROAD outcome is a measured effective-dimension law, not an
  impossibility proof.  NO RH claim.  No marker moves.""")
    print("\n[TIME] %.1f s   [CHECKS] %d run, %d failed"
          % (time.time() - T0, n_tot, n_tot - n_pass))
    return 0 if n_pass == n_tot else 1


if __name__ == "__main__":
    raise SystemExit(main())
'''

# --------------------------------------------------------------- harness
_PF_RE = re.compile(r"^\s*\[(PASS|FAIL)\]\s+(\S+)", re.M)
_VD_RE = re.compile(r"VERDICT[:\]]")


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 _census(out):
    marks = _PF_RE.findall(out)
    fails = sorted({tok for st, tok in marks if st == "FAIL"})
    verdict = ""
    for line in out.splitlines():
        if _VD_RE.search(line):
            verdict = line.strip()
    return len(marks), fails, verdict


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


def _gate(name, out, code, same, exp_n, exp_fails, exp_verdict,
          exp_code, gates):
    n, fails, verdict = _census(out)
    ok = (n == exp_n and fails == list(exp_fails)
          and exp_verdict in verdict and code == exp_code
          and same is not False)
    gates.append(ok)
    prov = ("byte-exact vs experiments source" if same is True else
            "embedded copy (source file not present)" if same is None
            else "SOURCE MISMATCH")
    print("\n[%s] PATTERN GATE %s: %d checks (exp %d) | FAILs %s "
          "(exp %s) | exit %d (exp %d) | %s\n      verdict line: %s"
          % ("PASS" if ok else "FAIL", name, n, exp_n,
             ",".join(fails) if fails else "none",
             ",".join(exp_fails) if exp_fails else "none",
             code, exp_code, prov, verdict), flush=True)
    return ok


_PLAN = (
    ('tail_sign_mechanism_probe', _SRC_0, 14, (), 'TAILSIGN-MEASURED', 0),
    ('tail_sign_repair_probe', _SRC_1, 10, (), 'TAILREPAIR-MEASURED', 0),
    ('pgram_directional_schur_probe', _SRC_2, 20, (), 'PGSCHUR-MEASURED', 0),
    ('tail_abel_transport_probe', _SRC_3, 22, (), 'TAILABEL-MEASURED', 0),
    ('tail_segment_split_probe', _SRC_4, 24, (), 'SEGSPLIT-MEASURED', 0),
    ('tail_oscillation_pairing_probe', _SRC_5, 22, (), 'OSCPAIR-MEASURED', 0),
)


def run():
    t0 = time.time()
    print("=" * 74)
    print('v906 -- PRIME.PORT.TAILSIGN.01/.02 + PRIME.PORT.PG.SCHUR.01 + PRIME.PORT.TAIL.ABEL.01 + PRIME.PORT.TAIL.SEGSPLIT.01 + PRIME.PORT.TAIL.OSCPAIR.01: the tail mechanism map -- five dead routes with named seats (pointwise sign, pointwise repair, directional Loewner, cumulative/Abel, segment split) and two structural positives (HEADFLOOR-O1; the 12-bin reduced oscillation statement), typed explicitly as mechanism/negative cartography, NOT progress')
    print("(frozen probes embedded byte-exact and executed verbatim; NO RH claim)")
    print("=" * 74, flush=True)
    gates = []
    for name, src, exp_n, exp_fails, exp_verdict, exp_code 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_fails,
              exp_verdict, exp_code, gates)
    ok = all(gates)
    print("\n" + "=" * 74)
    print("v906: %d/%d pattern gates passed | runtime %.1f s"
          % (sum(gates), len(gates), time.time() - t0))
    print('the tail statement is a one-sided bound between two O(1) objects, reducible to ~12 low-frequency psi-fluctuation coefficients; every tested certificate language (pointwise, Loewner-floor, Chebyshev-envelope, segment-anchored) fails with a named mechanism; nothing here bounds n, q or tau')
    print("[%s] v906 VERDICT GATE" % ("PASS" if ok else "FAIL"))
    return 0 if ok else 1


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