"""p21_gravity — the ledger file of 21-gravity (ledger migration; 10 October 2026).

"Gravitation as Phase Synchronisation" (Akhtman, 2026; preprint pp202606.1018.v2). The paper's predicate ledger is
docs/21-gravity/21-gravity-ledger.json. This file binds its predicates to the framework: the table of keys (generated from
the ledger by ci/make_ledgers.py), and the checks of seven blocks. Each check names the predicate(s) it witnesses
(LEDGER) under a `# 21:XN (<key>)` marker on the check that decides it (PREDICATES). The checks compute what the paper's
validation package computes (src/21-gravity, twenty-one scripts of 13 July 2026), rewritten onto the themes: the exact
blocks A to D in integers, fractions and residues (frc/drift.py, frc/lattice.py, frc/gravity.py, frc/extension.py), the
chart blocks E to G in floats with every numeral anchored to the ledger's scale import (frc/chart.py: ln Ω = 283.5,
Ω = 1.3 × 10¹²³, the entailed H₀ = 67.4; frc/chart_gravity.py). The package stays the paper's published witness until
the milestone's release pin retires it.

The exact checks call the gravity theme and stay exact (gate G09); the chart checks carry their tolerances in the
verdict and every comparison with measured data is [data]. The Lean side is lean/FrcCore/Theme/Drift.lean,
Theme/Lattice.lean, the register section of Theme/Gravity.lean and Theme/Shift.lean (core, no
axioms), and lean/FrcLedger/Theme/Strong.lean (the reals) with FrcLedger/Theme/Gravity.lean (the exact Mathlib
variants); the certificates are lean/FrcCore/Ledgers/P21Gravity.lean and lean/FrcLedger/Ledgers/P21Gravity.lean.

    python3 -m frc.ledgers.p21_gravity        every block, the census; exit 1 if a check fails (≈ 40 s)
    python3 -m frc.ledgers.p21_gravity E      one block (A to G)
    from frc.ledgers.p21_gravity import R; R.predicate("21:C21")    one predicate: its blocks run once per session

Blocks:  A  the register on a frame                     EXACT   (21:A1, A9, C2, C5, C13, C16, X1, X8)
         B  the lattice                                 EXACT   (21:C1, C2, C4, C9, C15, C20)
         C  the drift and the defect                    EXACT   (21:C1, C3, C6, C7, C11, C12, C19, C21, C22, C23, C25, P7, X3)
         D  the post-Newtonian series                   EXACT   (21:C7, C8, C12, C18, C23, P6)
         E  the strong field                            CHART   (21:C2, C4, C7, C10, C11, C12, C13, C15, C17, P1, P2, P7, X3)
         F  the floor and the crossover                 CHART   (21:C18, C19, P3, P4, P5, P8, X1, X2)
         G  the simulation                              CHART   (21:C19: the flux-conservation lemma, seeded)

The notebook frc/ledgers/p21_gravity.ipynb runs one predicate per cell, the cell's id its key (gate G13).
"""
import random
import sys
from fractions import Fraction
from math import gcd, isqrt

from frc import arith
from frc import chart as C
from frc import chart_gravity as CG
from frc import drift as D
from frc import gravity as G
from frc import lattice as LT
from frc.registry import Registry

# ---- generated by ci/make_ledgers.py from docs/21-gravity/21-gravity-ledger.json; edit the ledger, not this table ----
PAPER = "21-gravity"
KEYS = {"A1": "p21001", "A2": "p21002", "A3": "p21003", "A4": "p21004", "A5": "p21005", "A6": "p21006", "A7": "p21007", "A8": "p21008", "A9": "p21009", "B1": "p21010", "B2": "p21011", "B3": "p21012", "B4": "p21013", "B5": "p21014", "B6": "p21015", "B7": "p21065", "B8": "p32014", "B9": "p32015", "C1": "p21016", "C2": "p21017", "C3": "p21018", "C4": "p21019", "C5": "p21020", "C6": "p21021", "C7": "p21022", "C8": "p21023", "C9": "p21024", "C10": "p21025", "C11": "p21026", "C12": "p21027", "C13": "p21062", "C14": "p21063", "C15": "p21030", "C16": "p21031", "C17": "p21032", "C18": "p21033", "C19": "p21064", "C20": "p21035", "C21": "p21036", "C22": "p21037", "C23": "p21038", "C25": "p21040", "X1": "p21041", "X2": "p21042", "X3": "p21043", "X4": "p21044", "X5": "p21045", "X6": "p21046", "X7": "p21047", "X8": "p21048", "P1": "p21049", "P7": "p21050", "P8": "p21060", "P2": "p21051", "P3": "p21052", "P4": "p21053", "P5": "p21054", "P6": "p21055", "Z1": "p21059"}       # every row of the ledger: its label and its accession key
LEAN = {"A1": "core, ml", "A9": "core, ml", "C1": "core, ml", "C2": "core, ml", "C3": "core", "C4": "ml", "C5": "core, ml", "C6": "core", "C7": "core, ml", "C8": "core, ml", "C9": "core, ml", "C11": "core, ml", "C12": "ml", "C13": "core, ml", "C15": "core, ml", "C16": "core, ml", "C18": "ml", "C19": "core, ml", "C20": "core, ml", "C21": "core", "C25": "core, ml", "X1": "core", "X2": "ml", "X3": "core", "X8": "ml", "P1": "ml", "P7": "ml", "P8": "ml", "P2": "ml", "P3": "ml", "P4": "ml", "P5": "ml", "P6": "core, ml"}       # the rows with a Lean declaration: the libraries whose key files prove them
# ---- end of the generated table ----

LEAN_ONLY = ()                  # the predicates with a Lean declaration and no python check (gate G12): none

SHELLS = [13, 17, 37, 1373]                  # the shells p = 4κ + 1 of the paper's register (21:C2, C16)
LAB = 2408561                                # the laboratory Carrier Ω = 4S + 1, S = 602 140 (21:C16; FRC.Gravity.lab_register)
MERGER = (27811, 1596)                       # the merger instance on the count face (21:C13; FRC.Gravity.merger_instance)

# The paper's predicate ledger (Appendix A, predicates cited as 21:XN): the predicate(s) each check witnesses.
LEDGER = {
    "A1": "21:C16, 21:A1", "A2": "21:C2, 21:C16", "A3": "21:C5", "A4": "21:A9", "A5": "21:C13", "A6": "21:X8, 21:C5",
    "A7": "21:X1, 21:C14",
    "B1": "21:C9", "B2": "21:C9", "B3": "21:C9", "B4": "21:C20", "B5": "21:C4, 21:C20", "B6": "21:C1", "B7": "21:C15",
    "B8": "21:C2",
    "C1": "21:C21", "C2": "21:C22, 21:C21", "C3": "21:C21, 21:C1", "C4": "21:C11", "C5": "21:C25, 21:C7", "C6": "21:C6",
    "C7": "21:C19", "C8": "21:C19, 21:C21", "C9": "21:C23, 21:C21", "C10": "21:P7, 21:C12", "C11": "21:C19, 21:C21",
    "C12": "21:C3", "C13": "21:X3, 21:C21",
    "D1": "21:C8, 21:C7", "D2": "21:C23", "D3": "21:P6, 21:C8", "D4": "21:C12", "D5": "21:C18",
    "E1": "21:C2", "E2": "21:C7", "E3": "21:C12", "E4": "21:P1", "E5": "21:P7, 21:C12, 21:C13", "E6": "21:C4",
    "E7": "21:P2, 21:C10", "E8": "21:C17", "E9": "21:C11", "E10": "21:C11", "E11": "21:C15", "E12": "21:P6", "E13": "21:X3, 21:C12",
    "F1": "21:P3", "F2": "21:X2, 21:C19", "F3": "21:P4", "F4": "21:P4", "F5": "21:P8, 21:C18", "F6": "21:P5",
    "F7": "21:X1, 21:C14",
    "G1": "21:C19",
}

BLOCK = {"A": "the register on a frame",                     # check-id prefix -> the block (the function block_<letter> below)
         "B": "the lattice",
         "C": "the drift and the defect",
         "D": "the post-Newtonian series",
         "E": "the strong field",
         "F": "the floor and the crossover",
         "G": "the simulation"}

# the deciding check of each witnessed predicate
PREDICATES = {
    "21:A1": "A1", "21:A9": "A4", "21:C16": "A1", "21:C2": "A2", "21:C5": "A3", "21:C13": "A5", "21:X8": "A6", "21:X1": "A7",
    "21:C9": "B1", "21:C20": "B4", "21:C4": "B5", "21:C1": "B6", "21:C15": "B7",
    "21:C21": "C1", "21:C22": "C2", "21:C11": "C4", "21:C25": "C5", "21:C6": "C6", "21:C19": "C7", "21:C23": "D2", "21:C3": "C12", "21:X3": "C13",
    "21:C8": "D1", "21:C7": "D1", "21:P6": "D3", "21:C12": "D4", "21:C18": "D5",
    "21:P1": "E4", "21:P7": "E5", "21:P2": "E7", "21:C10": "E7", "21:C17": "E8",
    "21:P3": "F1", "21:X2": "F2", "21:P4": "F3", "21:P8": "F5", "21:P5": "F6",
}

R = Registry("21", "gravity", LEDGER, PREDICATES, sources=[__file__])
Fr = Fraction


def near(x, y, rel=None, abs_=None):
    """|x − y| within the stated tolerance, the chart's float x read as a Fraction against rational bounds."""
    d = abs(Fr(x) - Fr(y))
    return (rel is not None and d <= Fr(rel) * abs(Fr(y))) or (abs_ is not None and d <= Fr(abs_))


def between(lo, x, hi):
    return Fr(lo) < Fr(x) < Fr(hi)


def num(x):
    """A Fraction as a quotient of integers for the record's text (Python 3.10 formats no Fraction); a float as it is."""
    return x.numerator / x.denominator if isinstance(x, Fraction) else x


# ---- block A: the register on a frame (21:A1, A9, C2, C5, C13, C16, X1, X8) ---------------------------------------------------
@R.block("A", BLOCK["A"])
def block_A():
    shells = SHELLS + [LAB]
    ok = all(D.calibration(p) for p in shells)
    ok &= 4 * 602140 + 1 == LAB and (4 * 602140) % LAB == LAB - 1 and (4 * 602140) ** 2 % LAB == 1
    # 21:C16 (p21031), 21:A1 (p21001)
    R.check("A1", "the calibration congruence on p = 4κ + 1: 4κ ≡ −1 and (4κ)² ≡ 1 on the four shells and the laboratory Carrier Ω = 2 408 561 (4S = 2 408 560)", ok,
            f"p ∈ {SHELLS} and Ω = {LAB}")
    ok, det = True, []
    for p in shells:
        rel = D.newton_register(p)
        ok &= all(rel)
        k = (p - 1) // 4
        det.append(f"p={p}: G={2 * k}, c²={2 * k + 1}")
    # 21:C2 (p21017)
    R.check("A2", "the register value G = 2κ on every shell: 2G ≡ −1, (−2)G ≡ 1, the Gauss count (2·4κ)G ≡ 1, 2c² ≡ 1 with c² = 2κ + 1, and G ≡ −c²", ok, "; ".join(det))
    ok, det = True, []
    for p in shells:
        g = arith.primitive_root(p)
        rel = D.hbar_root(p, g)
        ok &= all(rel)
        det.append(f"p={p}: g={g}, ħ=g^κ={pow(g, (p - 1) // 4, p)}")
    # 21:C5 (p21020)
    R.check("A3", "the action quantum ħ = g^κ on every shell: ħ² ≡ −1 (the quarter turn), the root r = ħc² has r² ≡ κ and 2r ≡ ħ", ok, "; ".join(det))
    ps = [p for p in range(5, 200) if p % 4 == 1 and all(p % d for d in range(2, isqrt(p) + 1))]
    ok = all(D.channel_q4(p) for p in ps)
    ok &= all(k * (2 * S) == 2 * (k * S) and (4 * k) * (4 * S) == 4 * (4 * (k * S)) for k in range(1, 30) for S in (3, 7, 602140))
    # 21:A9 (p21009)
    R.check("A4", "the mass–energy channel: the residues of 𝔽_p^× in both C_{p−1} and C_{2(p+1)} are exactly the quarter-turn core Q₄ = {x : x⁴ = 1}, on every p ≡ 1 (mod 4) below 200; the two-face count κ·2S = 2κS and (p−1)(Ω−1) = 16κS", ok,
            f"{len(ps)} shells")
    ok, det = True, []
    for p in SHELLS:
        k = (p - 1) // 4
        S, A = G.record(p), G.area(p)
        ok &= S == k * (p + 1) and A == p * (p + 1) and Fraction(S, A) == Fraction(k, p) and 4 * k + 1 == p
        ok &= Fraction(k, p) == Fraction(1, 4) - Fraction(1, 4 * p)
        det.append(f"p={p}: S/A = {k}/{p}")
    ok &= all(G.sphere_points(p, a) == G.sphere_brute(p, a) for p in (13, 17) for a in (1, 2))
    m1, m2 = MERGER
    ok &= G.merger_area(m1, m2) == 2 * m1 * m2 == 88772712 and m1 + m2 == 29407
    ok &= all(G.merger_area(a, b) == 2 * a * b for a in range(1, 40) for b in range(1, 40))
    # 21:C13 (p21062)
    R.check("A5", "the count face: the record S = κ(p+1) and the area A = p(p+1) with S/A = κ/p = ¼ − 1/4p exactly (the Q₄ quotient's quarter), the sphere count two ways on 𝔽₁₃ and 𝔽₁₇, and the merger law ΔA = 2M₁M₂ on the count face (the instance 27 811 + 1 596 = 29 407)", ok,
            "; ".join(det) + f"; ΔA({m1}, {m2}) = {2 * m1 * m2}")
    ok = all(D.dilution(m, s) for m in (1, 3, 1000) for s in (5, 1552, 10 ** 61))
    # 21:X8 (p21048)
    R.check("A6", "cardinality dilution: with the Planck mass √Ω the coupling of two masses m is (m/√Ω)² = m²/Ω exactly on Ω = s²", ok, "m ∈ {1, 3, 1000}, s ∈ {5, 1552, 10⁶¹}")
    gens = {p: arith.primitive_root(p) for p in SHELLS + [29, 41]}
    ok = all(D.closed_chart(p, g) for p, g in gens.items())
    data = [D.curvature_datum(S) for S in (3, 4, 7, 10, 602140)]
    ok &= all(d[0] for d in data) and all(d[1] == Fraction(3, S) and d[2] == Fraction(1, 4 * S) for d, S in zip(data, (3, 4, 7, 10, 602140)))
    # 21:X1 (p21041)
    R.check("A7", "the closed chart and its curvature: on the frames of 𝔽₁₃, 𝔽₁₇, 𝔽₂₉, 𝔽₃₇, 𝔽₄₁ every nonzero residue returns after the full cycle 4κ chronons, the generator after no shorter run, the half cycle is −1, and the cycle's register is 4κ ≡ −1 (the horizon circumference in light time, 2π r_H/c, is the full cycle); over ℚ with π a symbol, the de Sitter entropy S = π r_H² and Ω = 4S + 1 give the curvature Λ = 3/r_H² = (3/S)π with Λ(Ω − 1) = 12π exactly (Λ ∼ 1/Ω in Planck units, the two readings of the one datum Ω), the chronon τ² = (π/4S) t_P² and the horizon 2S/π chronons (the chart's π kept a symbol: no residue stands in for it)", ok,
            "; ".join(f"p={p}: g={g}" for p, g in gens.items()) + "; S ∈ {3, 4, 7, 10, 602140}")


# ---- block B: the lattice (21:C1, C2, C4, C9, C15, C20) --------------------------------------------------------------------
@R.block("B", BLOCK["B"])
def block_B():
    ok = LT.fp_gauge_invariant(3, 4, seed=7) and LT.fp_gauge_invariant(3, 4, seed=11) and LT.fp_gauge_invariant(4, 4, seed=7)
    control = LT.fp_gauge_invariant(3, 4, seed=7, kind="forward")
    ok &= not control
    # 21:C9 (p21024)
    R.check("B1", "the discrete Fierz–Pauli functional on ℤ_N⁴ (N = 3, 4; Minkowski signature) with random integer fields: E[h + Dξ + (Dξ)ᵀ] = E[h] an exact integer identity for central differences, failing for one-sided differences (the control)", ok,
            f"central invariant on ℤ₃⁴ (two seeds) and ℤ₄⁴; one-sided invariant: {control}")
    ok1, ok2, ns1, ns2 = LT.fierz_pauli_line(samples=12)
    ok = ok1 and ok2
    R.check("B2", "uniqueness by the symbol method over ℚ: the gauge-invariant quadratic forms at a symbol are one line for spin 1 (Maxwell, a₁ + a₂ = 0) and one line for spin 2, the Fierz–Pauli line (−1, 2, −2, 1)", ok,
            f"spin-2 nullspace {[str(x) for x in ns2[0]]}" if ns2 else "no line")
    rng = random.Random(21)
    ok = True
    for n in range(3, 61):
        f = [rng.randint(-9, 9) for _ in range(n)]; g = [rng.randint(-9, 9) for _ in range(n)]
        ok &= LT.adjoint_identity(f, g, n) and LT.forward_adjoint_identity(f, g, n)
    R.check("B3", "the central difference is anti-self-adjoint on every cycle of 3 to 60 sites, Σ (Δf) g = −Σ f (Δg) on random integer fields; the forward difference's adjoint is the negative backward difference", ok, "58 cycles")
    ok, det = True, []
    for p in (13, 17, 37):
        g = arith.primitive_root(p)
        ns = [n for n in range(2, p) if (p - 1) % n == 0]
        for n in ns:
            for _ in range(3):
                v = [rng.randrange(p) for _ in range(n)]
                ok &= all(LT.shift_theorem(p, n, g, v, a) for a in range(n))
        det.append(f"p={p}: n ∈ {ns}")
    # 21:C20 (p21035)
    R.check("B4", "the finite Fourier shift theorem on every cycle of 𝔽₁₃, 𝔽₁₇ and 𝔽₃₇: the kick ζ^{ax}v shifts the transform by a, the shift of v by a multiplies its transform by ζ^{ak}, every a, random v (seed 21)", ok, "; ".join(det))
    ok = all(LT.two_shift_law(m, gu, T) for m in (1, 4, 9) for gu in (1, 2, 5) for T in (20, 40))
    # 21:C4 (p21019)
    R.check("B5", "the two-shift update law on an integer grid: Δ²q = −∇u at every interior chronon, and the registered trajectory is bitwise independent of m (the equivalence principle as an identity)", ok, "m ∈ {1, 4, 9}, ∇u ∈ {1, 2, 5}")
    ok, det = True, []
    for n, m in ((3, 3), (4, 3), (5, 3), (3, 5), (4, 4), (6, 3), (7, 3)):
        locked, mean = D.locked_sum(n, m)
        ok &= locked == m * m and mean == m
        det.append(f"n={n}, m={m}: |Σ|²={locked}, mean {mean}")
    # 21:C1 (p21016)
    R.check("B6", "the locked ensemble couples as m (|Σ_m z|² = m² on the locked word, computed as its residue multiset in ℤ[ζ_n]) while over all n^m phase words the mean of |Σ ζ^k|² is exactly m (the incoherent √m), an integer identity in ℤ[ζ_n]", ok, "; ".join(det))
    ok = all(LT.tt_rank(k) == 2 for k in ((1, 0, 0), (1, 1, 0), (1, 2, 2), (3, -1, 5)))
    det = []
    for p in (13, 17, 29):
        even, zeros = LT.laplacian_symbol_even(p, arith.primitive_root(p))
        ok &= even and zeros == [0]
        det.append(f"p={p}: even, zero at k=0 only")
    # 21:C15 (p21030)
    R.check("B7", "the radiative sector: the transverse-traceless projector has rank 2 at rational directions (two polarisations), and the cycle Laplacian's symbol 2 − g^k − g^{−k} is even in k with its zero at k = 0 alone on 𝔽₁₃, 𝔽₁₇, 𝔽₂₉", ok, "; ".join(det))
    ok = all(LT.tree_count(n) == n for n in (5, 8, 12, 20))
    R.check("B8", "spanning-tree admissibility: det of the reduced Laplacian of C_n is τ(C_n) = n exactly (n = 5, 8, 12, 20), the finite solvability predicate of the lattice potential", ok, "")


# ---- block C: the drift and the defect (21:C1, C3, C6, C7, C11, C12, C19, C21, C22, C23, C25, P7, X3) -----------------------
@R.block("C", BLOCK["C"])
def block_C():
    L, q, a, T = D.defect(60, 28, 1, 1)
    ok = (L, q, a, T) == (420, 4, 8, 105) and D.first_return(L // q, a) == 105 and D.first_return(L, a) == 105
    rng = random.Random(2128)
    for _ in range(200):
        nA, nB = rng.randint(2, 60), rng.randint(2, 60)
        wA, wB = rng.randint(0, nA - 1), rng.randint(0, nB - 1)
        L, q, a, T = D.defect(nA, nB, wA, wB)
        ok &= D.first_return(L // q, a) == T and (T * a) % (L // q) == 0 and all((t * a) % (L // q) for t in range(1, T))
    # 21:C21 (p21036)
    R.check("C1", "the relative-cycle defect recurs exactly: on the C₆₀–C₂₈ pair L = 420, q = 4, the defect a = 8 and the period T = 105 (the least t with t·a ≡ 0), and on 200 random pairs the least return equals (L/q)/gcd(L/q, a)", ok,
            "C₆₀–C₂₈: (420, 4, 8, 105); 200 random pairs")
    ok = all(D.compression_identity(n, sec) for n, sec in ((6, {0, 1, 2}), (8, {0, 1, 2, 3, 5}), (12, {1, 2, 3, 4, 5, 6, 7})))
    # 21:C22 (p21037)
    R.check("C2", "the compression identity: on the cyclic shift U with a sector projector P, K = PUP and C = (1 − P)UP satisfy P − KᵀK = CᵀC exactly (relaxation is unresolved leakage, the recurrence retained), on ℤ₆, ℤ₈, ℤ₁₂", ok, "")
    ok = all(D.pair_tally_identity(p, z) for p in (13, 17, 37) for z in range(1, p))
    dims = [D.antisymmetric_dimension(d) for d in (1, 2, 3, 5)]
    ok &= dims == [1, 2, 3, 5]
    R.check("C3", "the pair tally on the norm-one pair (z, w = z⁻¹): E + W = 4 and (z − w)² = −E·W for every z ∈ 𝔽_p^×, p = 13, 17, 37; the antisymmetric currents J(z⁻¹) = −J(z) of degree ≤ d form a d-dimensional space (exact rank over ℚ), so the sine mode (z − z⁻¹)/2i is the unique minimal-degree current up to scale and higher odd harmonics exist", ok,
            f"dimensions {dims} at d = 1, 2, 3, 5")
    ok = True
    for trial in range(20):
        n = rng.randint(4, 12)
        J = [[0] * n for _ in range(n)]
        for x in range(n):
            for y in range(x + 1, n):
                v = rng.randint(-5, 5); J[x][y], J[y][x] = v, -v
        region = {x for x in range(n) if rng.randrange(2) == 0}
        ok &= D.gauss_law(J, region)
    # 21:C11 (p21026)
    R.check("C4", "the cut-flux law from transfer antisymmetry: on 20 random graphs with antisymmetric integer link currents, the divergence summed over a random region equals the flux through its boundary (the interior links cancel in pairs)", ok, "")
    ok = D.cover_triangle(Fraction(1), Fraction(1))
    ok &= all((2 * g - b == 1 and g == 1) <= (b == 1) for g in (Fraction(1), Fraction(3, 2), Fraction(1, 2)) for b in (Fraction(1), Fraction(2), Fraction(0)))
    ok &= not D.cover_triangle(Fraction(1), Fraction(2))
    # 21:C25 (p21040)
    R.check("C5", "the PPN triangle: channel unity's γ = 1 with the instance cover's 2γ − β = 1 force β = 1, the deviation ⅔(2γ − β − 1) vanishing; a second β fails the triangle", ok, "")
    ok, det = True, []
    for p in (13, 17, 37):
        nu = next(v for v in range(2, p) if pow(v, (p - 1) // 2, p) == p - 1)
        for _ in range(30):
            ok &= D.frobenius_trace(p, nu, rng.randrange(1, p), rng.randrange(p), rng.randrange(p))
        det.append(f"p={p}: ν={nu}")
    # 21:C6 (p21021)
    R.check("C6", "the dust tensor's source: the Frobenius pairing of m(w ⊗ w) on 𝔽_p[η]/(η² − ν) equals m·N(w), the trace of the Frobenius-symmetric square is the mass times the norm", ok, "; ".join(det))
    ok, det = True, []
    for w, s in ((Fraction(3, 5), Fraction(4, 5)), (Fraction(5, 13), Fraction(12, 13)), (Fraction(8, 17), Fraction(15, 17)), (Fraction(20, 29), Fraction(21, 29))):
        r, eta = D.registration_root(w, s)
        ok &= r and 0 < eta < 1
        det.append(f"w={w}: η={eta}")
    ok &= all(D.chebyshev_weight(L, d, w) for L, d, w in ((6, 2, Fraction(3, 5)), (9, 4, Fraction(7, 10)), (12, 5, Fraction(2, 3))))
    # 21:C19 (p21064)
    R.check("C7", "the registration crossover's exact root: on w² + s² = 1 the root η = (1 − s)/w of wη² − 2η + w = 0 lies in (0, 1); the two-boundary masking weight q_{L,d} = (U_{d−1} + U_{L−d−1})/U_{L−1} at 1/w equals the tridiagonal solve of the killed walk on three (L, d, w)", ok,
            "; ".join(det))
    ok = all(D.christoffel(a, b) for a, b in ((3, 7), (5, 12), (7, 10), (114, 641)))
    prov, within = D.largest_remainder([Fraction(23, 54), Fraction(23, 54), Fraction(2, 27), Fraction(2, 27)], 81)
    ok &= within and prov == [35, 34, 6, 6] and sum(prov) == 81
    ok &= all(D.ledger_identity(m, g, N, T) for m in (1, 3) for g in (Fraction(2), Fraction(-7, 3)) for N, T in ((3, 7), (10, 4)))
    orbit = [D.event_orbit(a, b, g) for a, b, g in ((23, 54, Fraction(11, 9)), (5, 12, Fraction(3)), (7, 9, Fraction(-2, 5)))]
    ok &= all(o[0] and o[1] == a for o, a in zip(orbit, (23, 5, 7)))
    R.check("C8", "the registration words and the readout: the Christoffel pattern at rate a/b (a marks per recurrence b, gaps ⌊b/a⌋, ⌈b/a⌉), the largest-remainder allocation 35 + 34 + 6 + 6 = 81 at weights (23/54, 23/54, 2/27, 2/27), the registered-inertia identity mgT = (fm)(g/f)T over framed rationals; the event-based orbit: the a registered events of the word, each carrying g_N/f, sum to the window total b·g_N exactly (rates 23/54, 5/12, 7/9)", ok,
            f"allocation {prov}")
    sup, cut, bil, clock = D.binding(N=5, m1=3, m2=5)
    ok = sup and cut and bil and clock
    R.check("C9", "binding bookkeeping on the torus ℤ₅³ over the prime field 𝔽_{2⁶¹−1}: superposition exact, the far cut flux around the bound pair equals m₁ + m₂, the interaction energy exactly bilinear, the binding defect m₁(1 − u₂(a)) a registered-clock identity (η_Nordtvedt = 0)", ok,
            f"superposition {sup}, cut {cut}, bilinear {bil}, clock {clock}")
    ok = D.fold_return(17, 8, 4)
    R.check("C10", "the fold-return toy over 𝔽₁₇: on the chain C₈ with the interior block folded by its exact DFT (i = 4), the period-averaged exterior return P_E F Uⁿ F⁻¹ P_E is the uniform floor operator, fold-independent (no echo carries the fold)", ok, "")
    first = D.kesten_control(641, 3, Fraction(23, 54), 200)
    split = [D.stratum_split(B) for B in (2, 3)]
    ok = first is not None and all(s[0] for s in split) and [s[1] for s in split] == [128, 512]
    R.check("C11", "the counting theorem's controls on the readout's worked instance (Ω = 641, g = 3): the negative control — prefix counts along the raw drive orbit against the threshold 23/54 break unit discrepancy (Kesten), so the attribution is stated over complete recurrences; the per-stratum split at B = 2, 3 — the dial of eight primitive eighth roots is ±√2 summing to zero, the string tallies in ℤ[√2] are 8 × the Galois-symmetric coefficients, total 4^B · 8, agreeing mod 641", ok,
            f"first discrepancy ≥ 2 at B = {first}; totals {[s[1] for s in split]}")
    arrows = [D.single_arrow(p, nu) for p, nu in ((13, 2), (17, 3), (37, 2))]
    signs = [D.pair_energy_sign(n) for n in (3, 4)]
    ok = all(a[0] for a in arrows) and all(a[1] == p + 1 for a, (p, _) in zip(arrows, ((13, 2), (17, 3), (37, 2)))) and all(s[0] for s in signs)
    # 21:C3 (p21018)
    R.check("C12", "the single arrow: on 𝔽_{p²} (p = 13, 17, 37) the Frobenius z ↦ z^p is the conjugation on every element, on the norm-one circle the conjugate is the inverse and the drive generator's conjugate orbit is its orbit reversed, and the conjugation fixes ±1 alone (no translation of the circle does): a time-reversed clock is the Frobenius branch, not a step of the drive; over ℚ the Dirichlet Green's function of the 3³ and 4³ grids is entrywise positive, so the cross term of two sources lowers the energy exactly when their signs agree — like-signed sources attract", ok,
            "; ".join(f"p={p}: circle of order {a[1]}, fixed {a[2]}" for a, (p, _) in zip(arrows, ((13, 2), (17, 3), (37, 2)))) + f"; G_ab = {signs[0][1]} (3³), {signs[1][1]} (4³)")
    returns = [D.offset_return(n, sec) for n, sec in ((8, {1, 2, 3}), (12, {0, 5, 6, 7, 11}), (9, {4}))]
    ok = all(r[0] and r[1] == n for r, (n, _) in zip(returns, ((8, 0), (12, 0), (9, 0)))) and all(D.compression_identity(n, sec) for n, sec in ((8, {1, 2, 3}), (9, {4})))
    # 21:X3 (p21043)
    R.check("C13", "the offset sector confines what the drive moves, exactly: on the cycles ℤ₈, ℤ₁₂, ℤ₉ with a sector P, for random rational ψ the sector's weight is what the step keeps plus what it moves out, ‖Pψ‖² = ‖PUPψ‖² + ‖(1 − P)UPψ‖² (the compression identity P − KᵀK = CᵀC), the step conserves the whole weight, and the drive is a permutation of order n, so the leaked data return after n steps (the interior data of the horizonless body live in that sector; nothing is lost — the theorem citation is 22:C15)", ok,
            f"orders {[r[1] for r in returns]}")


# ---- block D: the post-Newtonian series (21:C7, C8, C12, C18, C23, P6) ------------------------------------------------------
@R.block("D", BLOCK["D"])
def block_D():
    pn = D.pn_coefficients(6)
    ok = pn["ok"] and Fraction(2 + 2 * pn["gamma"] - pn["beta"], 3) == 1
    # 21:C8 (p21023), 21:C7 (p21022)
    R.check("D1", "the exponential isotropic metric: β = γ = 1 read off e^{−2U} and e^{2U}, the perihelion factor (2 + 2γ − β)/3 = 1; against the isotropic Schwarzschild form the deviations are δA = U³/6 and δB = U²/2 exactly, nothing lower", ok,
            f"dA = {[str(x) for x in pn['dA'][:5]]}, dB = {[str(x) for x in pn['dB'][:4]]}")
    ok = D.two_body_1pn(3)
    # 21:C23 (p21038)
    R.check("D2", "the 1PN equivalence lemma: on the superposed potential U = U₁ + U₂ the two-body coefficients A to O(U²) and B to O(U) coincide with the isotropic form, the cross term 4U₁U₂ included (the Einstein–Infeld–Hoffmann sector shared exactly)", ok, "U₂/U₁ ∈ {1, 3/7, −2/5}")
    inp = D.pn_orbit_inputs(5)
    ok = inp["ok"]
    # 21:P6 (p21055)
    R.check("D3", "the 2PN orbit-equation inputs, exact in x = Mw: B/A − (B/A)_S = x²/2 + 5x³/3 and B − B_S = x²/2 + 5x³/6, so δc₂'s leading term is ε M²/L² and δc₃ = (5/6) M³/L²; the apsidal sum 5/2 − (1 − e²)/2 = 2 + e²/2", ok,
            f"c2 at E=1: {inp['c2_const']}, ε-coefficient {inp['c2_eps']}, c3 = {inp['c3']}")
    co = D.static_profile_coefficients(3)
    ok = co == [Fraction(1), Fraction(1, 30), Fraction(1, 120)]
    # 21:C12 (p21027)
    R.check("D4", "the exact saturating profile u(r) = ∫_r^∞ arcsin(Gm/s²) ds as an exact series: Gm/r (1 + (Gm/r²)²/30 + (Gm/r²)⁴/120 + …), the arcsin saturating at the slip core r_* = √(Gm)", ok, f"coefficients {[str(c) for c in co]}")
    fixed, ratios = D.scale_invariant_exponent(-6, 3)
    ok = fixed == [-3] and all(ratios[n][(lam, k)] == lam ** (n + 3) for n in ratios for lam, k in ratios[n])
    ok &= ratios[-2][(Fraction(2), 5)] == 2 and ratios[-4][(Fraction(2), 5)] == Fraction(1, 2) and ratios[0][(Fraction(3, 2), 1)] == Fraction(27, 8)
    # 21:C18 (p21033)
    R.check("D5", "the primordial spectrum's fixed point: Δ² ∝ k^{n+3} under the drive k ↦ λk is multiplied by (λk)^{n+3}/k^{n+3} = λ^{n+3}, evaluated exactly over ℚ for n ∈ [−6, 3), λ ∈ {2, 3/2, 1/3}, k ∈ {1, 2, 5}: the ratio is 1 at every (λ, k) for n = −3 alone, n_s = 1 (Harrison–Zel'dovich) the unique scale-dilation fixed point", ok,
            f"fixed points {fixed}; at n = −2 the ratio is λ, at n = −4 it is 1/λ")


# ---- block E: the strong field (21:C2, C4, C7, C10, C11, C12, C13, C15, C17, P1, P2, P6, P7, X3) [chart] ----------------------
# The chart's floats are read as Fractions and judged against rational tolerances: this file carries no float (gate G09).
@R.block("E", BLOCK["E"])
def block_E():
    ratios = CG.green_ratios((3, 5, 8, 12), M=300)
    slope = CG.green_slope((5, 8, 12), M=300)
    ok = all(abs(Fr(ratios[r]) - 1) <= Fr(3, 2) / r ** 2 + Fr(5, 1000) for r in ratios) and abs(Fr(slope) + 1) < Fr(2, 100)
    ok &= near(CG.lattice_green(0, 300), Fr("0.2527310098"), rel=Fr(1, 10 ** 5))
    R.check("E1", "the Newtonian layer: the exact lattice Green's function of ℤ³ (the Montroll kernel, the k₁ integral in closed form) has 4πr G(r) = 1 + O(r⁻²) at r = 3, 5, 8, 12 and the potential slope −1; G(0) = 0.252731 (Watson)", ok,
            ", ".join(f"4π·{r}·G = {ratios[r]:.4f}" for r in ratios) + f"; slope {slope:.4f}", kind="CHART")
    alpha, target = CG.deflection()
    ok = near(alpha, target, rel=Fr(1, 10 ** 6))
    R.check("E2", "the Fermat deflection in the index n = 1 + 2Gm/c²r integrates over the line to 4Gm/c²b (the full light deflection, γ = 1)", ok, f"α = {alpha:.9f} against {target}", kind="CHART")
    ok = all(near(*CG.profile_series(r), rel=Fr(1, 10 ** 5)) for r in (3, 5, 10))
    rph, bc = CG.photon_sphere()
    ok &= near(rph, 2, abs_=Fr(5, 100)) and near(bc, CG.TWO_E, abs_=Fr(2, 100))     # the package's tolerances: the exact profile shifts the exponential minimum by 1 %
    R.check("E3", "the exact profile's quadrature against its series (r = 3, 5, 10) and the photon sphere: the minimum of r e^{2u} taken on the exact profile (grid 0.01) lies within 1 % of the exponential zone's r_ph = 2Gm, its critical impact parameter within 0.2 % of b_c = 2e·Gm (tolerances 0.05, 0.02)", ok,
            f"r_ph = {rph:.2f}, b_c = {bc:.4f} (2e = {CG.TWO_E:.4f})", kind="CHART")
    sh, rd = CG.shadow_ringdown(); ang = CG.angular_shadows(); isc = CG.isco()
    ok = near(sh, Fr("0.0463"), abs_=Fr(5, 10 ** 4)) and near(rd, Fr("-0.0442"), abs_=Fr(5, 10 ** 4))
    ok &= near(isc["eff"], Fr("0.0548"), abs_=Fr(2, 10 ** 4)) and near(isc["eff_schw"], Fr("0.0572"), abs_=Fr(2, 10 ** 4))
    ok &= abs(Fr(isc["Wrr"])) < Fr(1, 10 ** 6) and near(isc["ratio"], Fr("0.931"), abs_=Fr(2, 1000))
    ok &= near(ang["Sgr A*"][0], Fr("53.3"), abs_=Fr(2, 10)) and near(ang["Sgr A*"][1], Fr("55.7"), abs_=Fr(2, 10))
    ok &= near(ang["M87*"][0], Fr("39.7"), abs_=Fr(2, 10)) and near(ang["M87*"][1], Fr("41.5"), abs_=Fr(2, 10))
    # 21:P1 (p21049)
    R.check("E4", "the strong-field signatures: shadow +4.63 % and ringdown −4.42 % (2e against 3√3), the ISCO at r = (3 + √5)Gm with accretion efficiency 5.48 % against Schwarzschild's 5.72 % and the ISCO frequency at 0.931 (−6.9 %); Sgr A* 53.3 → 55.7 μas and M87* 39.7 → 41.5 μas [data]", ok,
            f"shadow {sh:+.4f}, ringdown {rd:+.4f}, efficiency {isc['eff']:.4f}, frequency ratio {isc['ratio']:.4f}", kind="CHART")
    cut = CG.operational_cut(10 ** 6); low = CG.operational_cut(100)
    ok = cut["ordered"] and not low["ordered"] and near(cut["threshold"], Fr("20093.06"), rel=Fr(1, 10 ** 5))
    ok &= near(cut["round_trip"], CG.OMEGA, rel=Fr(1, 10 ** 9)) and near(cut["capacity_ratio"], Fr("1.244e-5"), rel=Fr(1, 1000))
    ok &= near(cut["echo"], CG.OMEGA / CG.LN_OMEGA ** 2, rel=Fr(1, 10 ** 12)) and near(cut["r_f"], Fr(2 * 10 ** 6) / C.LN_OMEGA, rel=Fr(1, 10 ** 12))
    # 21:P7 (p21050)
    R.check("E5", "the operational cut at ln Ω = 283.5: r_* < r_f = r_s/ln Ω < M for M > (ln Ω/2)² = 20 093 Planck masses (ordered at 10⁶, not at 10²); the round-trip factor e^{2u(r_f)} = Ω = 1.3 × 10¹²³ (no prompt echo); the capacity ratio S/S_BH = 1/ln²Ω = 1.24 × 10⁻⁵; the echo factor Ω/ln²Ω", ok,
            f"r_f = r_s/{CG.LN_OMEGA}, threshold {cut['threshold']:.1f}, capacity ratio {cut['capacity_ratio']:.3e}", kind="CHART")
    ok = all(CG.redshift_linear(Fr(1, 10 ** k)) for k in (1, 2, 3, 4, 6))
    ta = CG.turnaround()
    ok &= between(1, ta, Fr(5, 2))
    R.check("E6", "the redshift as clock rate: 1 − e^{−u} = u + O(u²), |1 − e^{−u} − u| ≤ u² on 10⁻⁶ ≤ u ≤ 10⁻¹; the Local-Group turnaround radius (Gm/H²)^{1/3} ≈ 1.6 Mpc against the observed ~1 Mpc [data]", ok, f"turnaround {ta:.2f} Mpc", kind="CHART")
    pf = CG.preferred_frame_scale()
    ok = between(Fr(2, 10 ** 62), pf, Fr(4, 10 ** 62)) and near(pf, Fr("2.75e-62"), rel=Fr(1, 100))
    drag = CG.dragging_field(J=Fr(3, 10), r=10)
    ok &= near(drag["axis"], CG.lense_thirring(Fr(3, 10), 10), rel=Fr(1, 10 ** 6)) and near(drag["equator"], -Fr(3, 10 ** 4), rel=Fr(1, 10 ** 6))
    ok &= Fr(drag["laplacian"]) < Fr(1, 10 ** 5) and Fr(drag["divergence"]) < Fr(1, 10 ** 5) and Fr(drag["transverse"]) < Fr(1, 10 ** 12)
    # 21:P2 (p21051), 21:C10 (p21025)
    R.check("E7", "no preferred-frame leakage: the drive's signature at 1/√Ω = 3 × 10⁻⁶² on the chart (α₁, α₂ = O(1/√Ω), far below the 10⁻⁵ bounds [data]); the dragging of the spin J: the gravitomagnetic dipole A = J × r/r³ (C17's quarter-turn dual) is harmonic and divergence-free off the source, and its curl is 2J/r³ on the axis — the Lense–Thirring rate 2GJ/c²r³ in its observed form — and −J/r³ on the equator (central differences, J = 0.3, r = 10)", ok,
            f"1/√Ω = {pf:.3e}; curl on the axis {drag['axis']:.6e} against 2J/r³ = {num(CG.lense_thirring(Fr(3, 10), 10)):.6e}", kind="CHART")
    spins = (Fr(1, 10), Fr(3, 10), Fr(1, 2), Fr(9, 10))
    erg = [CG.ergosurface(a) for a in spins]
    ok = all(Fr(erg[i]) < Fr(erg[i + 1]) for i in range(3)) and all(between(1, e, 3) for e in erg)
    # 21:C17 (p21032)
    R.check("E8", "the rotating solution: the O(a²) ergosurface of the horizonless body, the outer root of e^{−4/r} = 4a²/r⁴, exists and grows with the spin a (the frame-dragging dual, no horizon)", ok, ", ".join(f"a={a}: r={e:.3f}" for a, e in zip(spins, erg)), kind="CHART")
    ok = all(Fr(CG.schwarzschild_as_exponential(U)) < Fr(1, 10 ** 12) for U in (Fr(1, 10), Fr(3, 10), Fr(1, 2), Fr(9, 10)))
    ce, cs = CG.composition_violation(Fr(1, 5), Fr(3, 10))
    ok &= Fr(ce) < Fr(1, 10 ** 15) and Fr(cs) > Fr(1, 1000) and abs(Fr(CG.laplacian_psi(3))) > Fr(1, 10 ** 4)
    R.check("E9", "the nonlinear completion's two readings: isotropic Schwarzschild is the exponential reading e^{−2ψ} of ψ = 2 artanh(U/2), ψ non-harmonic (Δψ ≠ 0), and the Schwarzschild reading violates the composition law R(a + b) = R(a)R(b) that the exponential satisfies", ok,
            f"composition defect: exponential {num(ce):.1e}, Schwarzschild {num(cs):.4f}; Δψ(3) = {num(CG.laplacian_psi(3)):.2e}", kind="CHART")
    fluxes, power, two = CG.sine_model_flux(N=9, iters=1500)
    ok = all(near(f, 4, abs_=Fr(1, 1000)) for f in fluxes) and near(power, 3, abs_=Fr(2, 10)) and near(two, 6, abs_=Fr(1, 1000))
    R.check("E10", "the cut-flux law of the full sine model: the flux through every box about the source equals the demand to solver precision, the deviation from the linear model scales as the cube of the source (no m² self-sourcing), and with two sources (4 and 2, two sites apart) the flux through the box enclosing both is 6", ok,
            f"fluxes {[round(f, 5) for f in fluxes]} against 4; power {power:.3f}; two sources {two:.5f} against 6", kind="CHART")
    vg = CG.group_velocity(Fr(1, 1000))
    ok = near(vg, 1, abs_=Fr(1, 10 ** 5)) and near(CG.dispersion((CG.PI, 0, 0)), 4, abs_=Fr(1, 10 ** 12))
    ok &= all(near(CG.helicity_angle(d), 2 * d, abs_=Fr(1, 10 ** 9)) for d in (15, 30, 45))
    R.check("E11", "the radiative sector on the chart: ω² = Σ 4 sin²(k_i/2), the long-wave group velocity c = 1 (channel unity), the Nyquist edge at ω² = 4; rotating the field about k by ψ rotates (h₊, h×) by 2ψ — helicity ±2", ok,
            f"v_g(10⁻³) = {vg:.6f}", kind="CHART")
    up, excess = CG.periastron_excess()
    ok = near(up, Fr("4.38e-6"), rel=Fr(1, 100)) and near(excess, Fr("1.46e-6"), rel=Fr(1, 100)) and near(excess, up * (2 + Fr("0.0878") ** 2 / 2) / 6, rel=Fr(1, 10 ** 9))
    R.check("E12", "the 2PN periastron excess of PSR J0737−3039 [data]: on the semi-latus rectum U_p = GM/c²p = 4.38 × 10⁻⁶ (M = 2.5871 M_⊙, P_b = 8834.5 s, e = 0.0878) and δω̇/ω̇ = U_p (2 + e²/2)/6 = 1.46 × 10⁻⁶, the row's 1.5 × 10⁻⁶", ok,
            f"U_p = {up:.4e}, excess {excess:.4e}", kind="CHART")
    u0, floor_rate, bound, low = CG.horizonless()
    ok = Fr(u0) < Fr(bound) and Fr(floor_rate) > 0 and near(low, floor_rate, rel=Fr(1, 10 ** 9)) and near(u0, Fr("2.622"), abs_=Fr(1, 1000))
    R.check("E13", "no horizon, no singularity: below the slip core r_* = √(Gm) the profile's integrand saturates at π/2, so u(0) = u(r_*) + (π/2) r_* = 2.622 Gm is finite and below the bound π r_* (arcsin x ≤ (π/2) x); the clock-rate factor e^{−2u} attains its minimum e^{−2u(0)} = 0.0053 > 0 at the centre and is positive everywhere", ok,
            f"u(0) = {u0:.4f}, e^(−2u(0)) = {floor_rate:.4e}, bound π r_* = {bound:.4f}", kind="CHART")


# ---- block F: the floor and the crossover (21:C18, C19, P3, P4, P5, P8, X1, X2) [chart] -------------------------------------------
@R.block("F", BLOCK["F"])
def block_F():
    a0 = CG.floor()
    ok = near(a0, Fr("1.042e-10"), rel=Fr(2, 1000))
    fit, syst = C.A0_FIT
    ok &= all(abs(Fr(CG.floor(h)) - fit) <= syst for h in (C.H0_ENTAILED, 70, 73))
    # 21:P3 (p21052)
    R.check("F1", "the weak-acceleration floor a₀ = cH₀/2π = 1.04 × 10⁻¹⁰ m s⁻² at the entailed H₀ = 67.4, and for H₀ ∈ {67.4, 70, 73} within one systematic σ of the fitted 1.20 ± 0.24 × 10⁻¹⁰ [data]", ok,
            f"a₀(67.4) = {a0:.4e}", kind="CHART")
    pairs = [CG.eta_reach(s, a) for s, a in ((Fr(1, 50), 3), (Fr(1, 800), 12), (Fr(1, 12800), 48))]
    gaps = [abs(Fr(x) - Fr(y)) / Fr(y) for x, y in pairs]
    ok = gaps[0] > gaps[1] > gaps[2] and gaps[2] < Fr(1, 10 ** 4)
    deep, newton = CG.loglog_slope(Fr(1, 10 ** 6)), CG.loglog_slope(10 ** 6)
    ok &= near(deep, Fr(1, 2), abs_=Fr(1, 1000)) and near(newton, 1, abs_=Fr(1, 10 ** 6))
    # 21:X2 (p21042)
    R.check("F2", "the crossover: the exact root η^a converges to the e^{−√x} reading as the window refines; the deep limit's log–log slope ½ (g_obs → √(g_N a₀), no dark-matter particle) and the Newtonian limit's slope 1", ok,
            f"slopes {deep:.4f}, {newton:.6f}; root–reading gaps {[f'{num(g):.1e}' for g in gaps]}", kind="CHART")
    r5, nu, disc = CG.interpolant_discriminant(5)
    ok = near(disc, Fr("0.0511"), abs_=Fr(3, 10 ** 4)) and between(Fr("1.11966"), r5, Fr("1.11967")) and between(Fr("1.17082"), nu, Fr("1.17083"))
    ok &= all(Fr(CG.ratio(x)) > 1 for x in (Fr(1, 10 ** 4), Fr(1, 100), 1, 100)) and Fr(CG.ratio(100)) < Fr("1.0001") and Fr(CG.ratio(10 ** 4)) == 1
    # 21:P4 (p21053)
    R.check("F3", "the radial acceleration relation g_obs = g_N/(1 − e^{−√(g_N/a₀)}) across four decades, above Newton everywhere, within 10⁻⁴ of it at g_N = 100a₀ and at it on the chart by 10⁴a₀; its discriminant 0.051 at g_N = 5a₀ against the simple interpolant ½ + √(¼ + a₀/g_N)", ok,
            f"ratio(5) = {r5:.5f}, ν(5) = {nu:.5f}, difference {disc:.4f}", kind="CHART")
    v, curve = CG.tully_fisher(10 ** 10)
    ok = near(v, Fr("112.3e3"), rel=Fr(1, 1000)) and all(1 < Fr(curve[i][2]) and Fr(curve[i + 1][2]) < Fr(curve[i][2]) for i in range(2)) and near(curve[2][2], 1, abs_=Fr(2, 100))
    R.check("F4", "the baryonic Tully–Fisher asymptote: the rotation curve v(r) = √(g_obs r) of 10¹⁰ M_⊙ on the radial acceleration relation flattens from above to the deep limit's (GMa₀)^{1/4} = 112 km s⁻¹ with the fitted a₀ (v⁴/GMa₀ = 1.12, 1.03, 1.01 at 30, 100, 300 kpc); the identity v⁴ = GMa₀ itself is the deep limit's theorem (P4's key)", ok,
            f"v∞ = {v / 1000:.1f} km s⁻¹; " + ", ".join(f"{r:.0f} kpc: {num(q):.3f}" for r, _, q in curve), kind="CHART")
    t = CG.tilt()
    sig = C.sigma(t, C.TILT_FIT); half = C.sigma(-CG.PI ** 2 / (CG.LN_OMEGA / 2), C.TILT_FIT)
    ok = near(t, Fr("-0.0348"), abs_=Fr(1, 10 ** 4)) and abs(Fr(sig)) < Fr(1, 10) and abs(Fr(half)) > 8
    probe = [Fr(CG.scale_path_probe(K)) / Fr(CG.PI ** 2) for K in (6, 15, 50, 283, 1000)]
    ok &= all(probe[i] < probe[i + 1] < 1 for i in range(4)) and probe[3] > Fr(99, 100)
    sens = CG.tilt_sensitivity()
    ok &= near(sens, Fr("0.00244"), rel=Fr(1, 100))
    # 21:P8 (p21060)
    R.check("F5", "the primordial tilt n_s − 1 = −π²/ln Ω = −0.0348 at ln Ω = 283.5 [approx], at +0.07σ from Planck 2018's −0.0351 ± 0.0042 [data]; ½ ln Ω excluded at 8.2σ; the tilt moves by ln 2/ln Ω = 0.24 % per factor two in S; the scale-path probe K²λ₁ → π² monotonically, 99.3 % at K = 283", ok,
            f"tilt {t:.4f}, {sig:+.2f}σ; ½ ln Ω at {half:+.1f}σ; sensitivity {num(sens):.4%} per factor two; probe {num(probe[3]):.4f}", kind="CHART")
    om = C.OMEGA_L_FIT[0]
    zs = (0, Fr(1, 2), 1, 2)
    shifts = [CG.running_shift(z, om) for z in zs]
    ok = Fr(shifts[0]) == 1 and all(Fr(shifts[i]) < Fr(shifts[i + 1]) for i in range(3))
    ok &= near(shifts[1], Fr("1.072"), abs_=Fr(1, 1000)) and near(shifts[2], Fr("1.157"), abs_=Fr(1, 1000)) and near(shifts[3], Fr("1.320"), abs_=Fr(1, 1000))
    # 21:P5 (p21054)
    R.check("F6", "the running floor a₀(z) ∝ H(z): the Tully–Fisher zero-point E(z)^{1/4} on the rival chart's E(z) (Ω_Λ = 0.685) rises monotonically with redshift, 1.072, 1.157, 1.320 at z = ½, 1, 2 (that a₀ ∝ H gives the zero-point ∝ E(z)^{1/4} is P5's key)", ok,
            ", ".join(f"z={z}: {s:.3f}" for z, s in zip(zs, shifts)), kind="CHART")
    ci = CG.curvature_import()
    ok = near(ci["ln_omega"], C.LN_OMEGA, rel=Fr(1, 1000)) and near(ci["log10_lambda_omega"], ci["log10_12pi"], abs_=Fr(1, 10 ** 6))
    ok &= Fr(1) < Fr(ci["log10_lambda_omega"]) < Fr(2) and Fr(121) < Fr(ci["orders_lambda"]) < Fr(123) and Fr(122) < Fr(ci["orders_S"]) < Fr(123)
    ok &= near(ci["chronon"], Fr("4.87e-62"), rel=Fr(1, 100)) and near(ci["horizon_ratio"], 1, rel=Fr(1, 10 ** 9))
    R.check("F7", "the curvature of the closed chart on the scale import [data]: the measured Λ = 1.088 × 10⁻⁵² m⁻² in Planck units is Λ ℓ_P² = 2.84 × 10⁻¹²²; the de Sitter entropy S = 3π/(Λ ℓ_P²) = 3.32 × 10¹²² and Ω = 4S + 1 give ln Ω = 283.50, the ledger's numeral; Λ ℓ_P² · Ω = 12π to the sixth digit (log₁₀ 1.58: Λ ∼ 1/Ω within two decades, the constant the chart's 4π and 3); the vacuum-energy gap of the row is the count, log₁₀ S = 122.5 (−log₁₀ Λ ℓ_P² = 121.5); the Carrier chronon (√π/2) t_P/√S = 4.87 × 10⁻⁶² t_P and the horizon r_H = √Ω ℓ_P/(2√π) = 1.03 × 10⁶¹ ℓ_P, the coherence horizon", ok,
            f"ln Ω = {ci['ln_omega']:.4f}, log₁₀(Λ ℓ_P² Ω) = {ci['log10_lambda_omega']:.4f}, log₁₀ S = {ci['orders_S']:.2f}, τ/t_P = {ci['chronon']:.3e}", kind="CHART")


# ---- block G: the simulation (21:C19's flux-conservation lemma) [chart, seeded] ----------------------------------------------------
@R.block("G", BLOCK["G"])
def block_G():
    quiet = CG.kuramoto_chain(0, T=60000, burn=20000)
    noisy = CG.kuramoto_chain(Fr(3, 10), T=60000, burn=20000)
    ok = near(quiet[0], Fr(3, 10), rel=Fr(1, 100)) and Fr(quiet[1]) < Fr(1, 1000) and near(noisy[0], Fr(3, 10), rel=Fr(3, 100)) and Fr(noisy[1]) < Fr(5, 100)
    R.check("G1", "flux conservation under noise: a driven, pinned Kuramoto chain of 20 links in its stationary regime carries the time-averaged transport b = 0.3 through every link, with and without the ambient noise (seed 3, 60 000 steps)", ok,
            f"quiet: mean {quiet[0]:.4f}, max deviation {quiet[1]:.1e}; noisy: mean {noisy[0]:.4f}, max deviation {noisy[1]:.3f}", kind="CHART")


if __name__ == "__main__":
    want = [a.upper() for a in sys.argv[1:]] or sorted(BLOCK)
    bad = [b for b in want if b not in BLOCK]
    if bad: sys.exit(f"no block {', '.join(bad)}: the blocks are {', '.join(sorted(BLOCK))}")
    for b in want: R.run_block(b)
    sys.exit(0 if R.summary(write=False, expect=list(LEDGER) if want == sorted(BLOCK) else None) else 1)
