"""RUN-029 - Round 26: the full necessity-atlas B7 wave and the production arithmetic contract.

Round 26 runs B7, in common-depth waves 22 -> 36, over all 77 of Round 19's necessity-marked
depth-40 cells: 51 close by depth 36, 26 remain, all still contracting (largest ratio 0.576). It
classifies the residual by open volume (5 dust, 7 thin, 14 broad), rejects a larger global pad
(the least audited leaf slack is 2.90e-9), audits the tightest leaf of the certificate cell against
uniform contact polygons and a coarse radial core, measures the 77 markers' margins, and writes an
arithmetic contract for a directed-interval replay. Here all 77 trees are rebuilt to depth 36 with
exact cores under this tree's pad (a box closes once its exact hull less 1e-9 reaches T), and the
residual cells and every cell whose ledger row that pad changes are lifted again under the package's
(less 1e-10); the curve, the residual and its statistics are recomputed, and the audits are redone.

Checks
  A0 anchors      the numbers and formulas below occur in Round 26 as written
  W1 cells        sec. 1: the 77 cells are Round 19's depth-40 cells with outer markers below T;
                  their margins
  W2 curve        sec. 5-6: the common-budget closure curve 22-36, the 51 closed and 26 open
  W3 residual     sec. 7-9: the residual volumes, classes and contraction ratios
  W4 ledger       the ledger's per-cell nodes, open boxes and volumes at depth 36, under both pads
  W5 slack        sec. 14: the least leaf slack over the complete trees, and what a larger pad does
  W6 tight leaf   sec. 20, 22: the certificate cell's tightest leaf against contact polygons, and
                  the radial core
  W7 code         what the package ships, read after the rebuild and never run
  P1 package      the ledger, the specs, the audits, the crystal and the text agree
  P2 package      VALIDATION against the archive; its checks from the data
  R1 registry     Round 26's judgments reviewed, first-used statuses defined

Usage: python code/run029_round26_full_atlas.py [--drill] [--blind CID]
"""
import argparse
import copy
import hashlib
import inspect
import json
import math
from multiprocessing import Pool

import numpy as np
from scipy.spatial import ConvexHull

import gate
import registry
import run008_round05_saturation_gate as r8
import run009_round06_witness_exchange as r9
import run011_round08_conditional_lift as r11
import run012_round09_adaptive_atlas as r12
import run013_round10_reference_dry_run as r13
import run019_round16_global_pilot as r19
import run020_round17_d3_cpg as r20
import run022_round19_necessity_lift as r22
import run023_round20_mixed_escalation as r23
import run025_round22_fourier_pareto as r25
import run026_round23_portfolio_closure as r26
import run027_round24_residual_joint as r27
import run028_round25_closure_wave as r28
from corpus import SOURCES, TREE, source_bytes, walk_sources
from run009_round06_witness_exchange import placed_disc
from run010_round07_minimizer_atlas import d_star, t_text
from run011_round08_conditional_lift import placed_vertices
from run012_round09_adaptive_atlas import core_pieces
from run013_round10_reference_dry_run import contact_points

PKG = "main.zip!/AMRAL_LUC_FC_Round_26_Package_v0.1.zip!/"
DOC = PKG + "AMRAL_Lebesgue_Finite_Closure_Round_26_Full_Atlas_Arithmetic_v0.1.md"
CRYSTAL = PKG + "AMRAL_LUC_FC_State_Crystal_Round_26_v0.1.md"
LEDGER = PKG + "AMRAL_LUC_FC_Round_26_FULL_ATLAS_LEDGER.json"
SCHEDULER = PKG + "AMRAL_LUC_FC_Round_26_WAVE_SCHEDULER_SPEC.json"
AUDIT = PKG + "AMRAL_LUC_FC_Round_26_ARITHMETIC_AUDIT.json"
SUPPLEMENT = PKG + "AMRAL_LUC_FC_Round_26_ARITHMETIC_AUDIT_SUPPLEMENT.json"
CONTRACT = PKG + "AMRAL_LUC_FC_Round_26_ARITHMETIC_CONTRACT.json"
MIGRATION = PKG + "AMRAL_LUC_FC_Round_26_ARITHMETIC_MIGRATION_SPEC.json"
VALIDATION = PKG + "AMRAL_LUC_FC_Round_26_VALIDATION.json"
REF = PKG + "AMRAL_LUC_FC_Round_26_reference/"
LOG = TREE / "data" / "gate-logs" / "run029-round26-full-atlas.json"
CACHE = TREE / "data" / "cache" / "run029-atlas.json"
MANIFEST = TREE / "data" / "SOURCE_MANIFEST.v1.json"

T, TM = 0.835, 0.8365
BUDGET, PKG_PAD = 36, 1e-10
WAVES = (22, 24, 26, 28, 30, 32, 34, 36)
ROOT7 = 2 * math.pi / 7 * (2 * t_text(7, d_star(TM))) ** 2

# ---------------------------------------------------------------- the certificate cell's leaves

def _leaf(args):
    """the exact area of a box's bound, and the pieces behind it"""
    c, h, wc, wh = args
    area = r27._exact(args)
    return area


def leaves(pool, c, h, max_depth):
    """RUN-027's exact lift, keeping every CERT leaf: (centre, half-widths, exact area)"""
    tn = t_text(7, d_star(TM))
    level = [((math.pi / 7, 0.0, 0.0), (math.pi / 7, tn, tn))]
    out = []
    for d in range(max_depth + 1):
        areas = pool.map(_leaf, [(list(c), list(h), wc, wh) for wc, wh in level], chunksize=8)
        nxt = []
        for (wc, wh), area in zip(level, areas):
            lb = math.pi / 4 if area is None else area - r19.PAD
            if lb >= T:
                out.append([list(wc), list(wh), area])
                continue
            if d == max_depth:
                continue
            trial = []
            for a in range(3):
                hh = list(wh)
                hh[a] /= 2
                trial.append(r23.delta_n(7, hh))
            a = int(np.argmin(trial))
            hh = list(wh)
            hh[a] /= 2
            lo, hi = list(wc), list(wc)
            lo[a] -= hh[a]
            hi[a] += hh[a]
            nxt += [(tuple(lo), tuple(hh)), (tuple(hi), tuple(hh))]
        level = nxt
        if not level:
            break
    return out


def polygon_bound(c, h, wc, wh, N):
    """the uniform contact polygon at N directions of the same bodies: the disc, the cell's two
    cores and B7's core"""
    th = 2 * np.pi * np.arange(N) / N
    k3, k5 = r19.cores(np.asarray(c, dtype=float), np.asarray(h, dtype=float))
    kn = core_pieces(placed_vertices(7, wc[0], wc[1:3]), 1 - r23.delta_n(7, wh))[0]
    return float(ConvexHull(np.vstack([contact_points(p, th) for p in (placed_disc(), k3, k5, kn)])).volume)


def compute():
    out = {}
    with Pool(14) as pool:
        seg, twelve = r26.twelve(pool)
        atlas = sorted((s for s in seg if s["outer"] < T), key=lambda s: s["path"])
        out["segment"] = [{k: s[k] for k in ("path", "exact", "outer")} for s in seg]
        out["atlas"] = [{k: s[k] for k in ("path", "outer", "center", "half")} for s in atlas]
        out["trees"] = [r28.exact_lift(pool, s["center"], s["half"], BUDGET) for s in atlas]
        cert = twelve[0]
        leaf = leaves(pool, cert["center"], cert["half"], 30)
        worst = min(leaf, key=lambda x: x[2])
        out["certificate"] = {"path": cert["path"], "leaves": len(leaf), "worst": worst,
                              "polygon": {str(N): polygon_bound(cert["center"], cert["half"], worst[0], worst[1], N) for N in (4096, 8192)}}
    return out


def _code_key(files):
    digest = hashlib.sha256()
    for fn in (_leaf, leaves, polygon_bound, compute):
        digest.update(inspect.getsource(fn).encode())
    for mod in (r8, r9, r11, r12, r13, r19, r20, r22, r23, r25, r26, r27, r28):
        digest.update(open(mod.__file__, "rb").read())
    digest.update(files)
    digest.update(repr((BUDGET,)).encode())
    return digest.hexdigest()


_COMPUTED = {}


def computed(key_bytes):
    key = _code_key(key_bytes)
    if key not in _COMPUTED:
        if CACHE.exists():
            cached = json.loads(CACHE.read_text(encoding="utf-8"))
            if cached.get("key") == key:
                _COMPUTED[key] = cached["results"]
        if key not in _COMPUTED:
            _COMPUTED[key] = json.loads(json.dumps(compute()))
            CACHE.parent.mkdir(parents=True, exist_ok=True)
            CACHE.write_text(json.dumps({"key": key, "results": _COMPUTED[key]}) + "\n", encoding="utf-8")
    return _COMPUTED[key]


# ---------------------------------------------------------------- sec. 20's radial core (a second cache)

RADIAL_CACHE = TREE / "data" / "cache" / "run029-radial.json"
RADIAL_N = (24, 32, 48, 64)


def rays(n, phi, centre, delta, psi):
    """the eroded Reuleaux core's boundary along rays from its centre at the angles psi"""
    rho = 1 - delta
    v = placed_vertices(n, phi, centre) - np.asarray(centre, dtype=float)
    u = np.stack([np.cos(psi), np.sin(psi)], axis=1)
    proj = u @ v.T
    disc = proj ** 2 + rho * rho - (v * v).sum(axis=1)[None, :]
    return np.asarray(centre, dtype=float) + (proj + np.sqrt(np.maximum(disc, 0.0))).min(axis=1)[:, None] * u


def _radial(args):
    """a CERT leaf under the two radial fallbacks at N rays: every body radial (the disc and all
    three cores, as sec. 20's audit builds it), or only B7's core, the rest exact"""
    c, h, wc, wh, N = args
    psi = 2 * np.pi * np.arange(N) / N
    d3 = math.hypot(h[0], h[1])
    d5 = math.hypot(h[3], h[4]) + 2 * r12.R5 * math.sin(h[2] / 2)
    b7 = rays(7, wc[0], wc[1:3], r23.delta_n(7, wh), psi)
    every = np.vstack([0.5 * np.stack([np.cos(psi), np.sin(psi)], axis=1), rays(3, 0.0, c[:2], d3, psi), rays(5, c[2], c[3:5], d5, psi), b7])
    k3, k5 = r19.cores(np.asarray(c, dtype=float), np.asarray(h, dtype=float))
    only = r19.exact_area(placed_disc() + k3 + k5 + [(p, 0.0, None) for p in b7]) - PKG_PAD
    return [bool(float(ConvexHull(every).volume) >= T), bool(only >= T)]


def radial_compute(cert):
    with Pool(14) as pool:
        leaf = leaves(pool, cert["center"], cert["half"], 30)
        out = {}
        for N in RADIAL_N:
            res = pool.map(_radial, [(cert["center"], cert["half"], x[0], x[1], N) for x in leaf], chunksize=64)
            out[str(N)] = [sum(r[0] for r in res), sum(r[1] for r in res), len(res)]
    return out


def radial_computed(cert):
    digest = hashlib.sha256()
    for fn in (rays, _radial, radial_compute, leaves, _leaf):
        digest.update(inspect.getsource(fn).encode())
    for mod in (r12, r19, r23, r27):
        digest.update(open(mod.__file__, "rb").read())
    digest.update(json.dumps(cert, sort_keys=True).encode())
    key = digest.hexdigest()
    if RADIAL_CACHE.exists():
        cached = json.loads(RADIAL_CACHE.read_text(encoding="utf-8"))
        if cached.get("key") == key:
            return cached["results"]
    results = json.loads(json.dumps(radial_compute(cert)))
    RADIAL_CACHE.write_text(json.dumps({"key": key, "results": results}) + "\n", encoding="utf-8")
    return results


# ---------------------------------------------------------------- the package's pad (a third cache)

PAD_CACHE = TREE / "data" / "cache" / "run029-package-pad.json"


def lift_pad(pool, c, h, max_depth, pad):
    """RUN-028's exact lift with the pad a parameter - the package bounds a box by its exact hull less
    1e-10, this tree by less 1e-9, so a box clearing T by more than 1e-10 but not by 1e-9 closes there
    and splits here - which also keeps the boxes open at max_depth, as their paths (a leading 1, then
    0 for the lower child) in hexadecimal, for Round 27 to resume from"""
    tn = t_text(7, d_star(TM))
    level = [(1, (math.pi / 7, 0.0, 0.0), (math.pi / 7, tn, tn))]
    per, nodes, closed, frontier = {}, 0, 0, []
    for d in range(max_depth + 1):
        areas = pool.map(r27._exact, [(list(c), list(h), wc, wh) for _, wc, wh in level], chunksize=8)
        nodes += len(level)
        nxt, opened, slack = [], 0, None
        for (p, wc, wh), area in zip(level, areas):
            lb = math.pi / 4 if area is None else area - pad
            if lb >= T:
                closed += 1
                slack = lb - T if slack is None else min(slack, lb - T)
                continue
            opened += 1
            if d == max_depth:
                frontier.append(format(p, "x"))
                continue
            trial = []
            for a in range(3):
                hh = list(wh)
                hh[a] /= 2
                trial.append(r23.delta_n(7, hh))
            a = int(np.argmin(trial))
            hh = list(wh)
            hh[a] /= 2
            lo, hi = list(wc), list(wc)
            lo[a] -= hh[a]
            hi[a] += hh[a]
            nxt += [(2 * p, tuple(lo), tuple(hh)), (2 * p + 1, tuple(hi), tuple(hh))]
        per[d] = [nodes, closed, opened, slack]
        level = nxt
        if not level:
            break
    return {"per": per, "frontier": frontier}


def pad_compute(cells):
    with Pool(14) as pool:
        return {c["path"]: lift_pad(pool, c["center"], c["half"], BUDGET, PKG_PAD) for c in cells}


def pad_computed(cells):
    """the residual cells, and every cell whose depth-36 row differs from the ledger under this tree's
    pad, lifted again under the package's"""
    digest = hashlib.sha256()
    for fn in (lift_pad, pad_compute):
        digest.update(inspect.getsource(fn).encode())
    for mod in (r8, r9, r11, r12, r13, r19, r20, r22, r23, r25, r26, r27, r28):
        digest.update(open(mod.__file__, "rb").read())
    digest.update(json.dumps(cells, sort_keys=True).encode())
    key = digest.hexdigest()
    if PAD_CACHE.exists():
        cached = json.loads(PAD_CACHE.read_text(encoding="utf-8"))
        if cached.get("key") == key:
            return cached["results"]
    results = json.loads(json.dumps(pad_compute(cells)))
    PAD_CACHE.write_text(json.dumps({"key": key, "results": results}) + "\n", encoding="utf-8")
    return results


def relift_cells(atlas, ledger):
    """the cells to lift again: open at depth 36, or whose depth-36 row differs from the ledger"""
    row = {c["path"]: c for c in ledger["cells"]}
    return [{k: a[k] for k in ("path", "center", "half")} for a, per in zip(atlas["atlas"], atlas["trees"])
            if at(per, BUDGET)[2] > 0 or (at(per, BUDGET)[0], at(per, BUDGET)[2]) != (row[a["path"]]["nodes_at_depth36"], row[a["path"]]["pending_at_depth36"])]


def load_inputs():
    blobs = {n: source_bytes(n) for n in SOURCES}
    got = {leaf.id: d for leaf, d in walk_sources(blobs, keep=lambda l: l.id.startswith(PKG)) if d is not None}
    return {"text": got[DOC].decode("utf-8"), "crystal": got[CRYSTAL].decode("utf-8"), "ledger": json.loads(got[LEDGER]),
            "scheduler": json.loads(got[SCHEDULER]), "audit": json.loads(got[AUDIT]), "supplement": json.loads(got[SUPPLEMENT]),
            "contract": json.loads(got[CONTRACT]), "migration": json.loads(got[MIGRATION]), "validation": json.loads(got[VALIDATION]),
            "residual": json.loads(got[REF + "residual_depth36.json"]),
            "code": {k[len(REF):]: v.decode("utf-8") for k, v in got.items() if k.startswith(REF) and k.endswith(".py")},
            "key_bytes": got[LEDGER], "manifest": json.loads(MANIFEST.read_text(encoding="utf-8"))}


ANCHORS = {
    "W1": [r"$$\boxed{77}$$", r"U_{\rmbase}(q_j)<0.835.", r"\boxed{2.885\times10^{-7}},", r"\approx6.806\times10^{-5}.", r"U_{\rminterval}^{\rmhi}<T"],
    "W2": [r"\boxed{d=36}.", r"$$\boxed{51/77}$$", r"$$\boxed{26/77}$$", r"\boxed{66.23\%}.", r"22\to24\to26\to28\to30\to32\to34\to36.",
           r"\boxed{I_{jK}^{(d)}\leI_{jK}^{(d')}}.", r"\Gamma_{B_7}(22)=0,", r"\Gamma_{B_7}(28)=0,", r"\boxed{\Gamma_{B_7}(30)=7},",
           r"\boxed{\Gamma_{B_7}(32)=19},", r"\boxed{\Gamma_{B_7}(34)=38},", r"\boxed{\Gamma_{B_7}(36)=51}.", r"\boxed{\frac{51}{77}\approx66.23\%.}",
           r"\boxed{|\mathcalR_{36}|=26}.", r"\text{FULL77-CELLCHECKPOINTTHROUGH}d=36:\\text{COMPLETED}", r"B_7\text{STRICTREFERENCECLOSUREAT}d=36:\51/77"],
    "W3": [r"V_{\min}\approx6.36\times10^{-12},", r"Q_{25}\approx2.31\times10^{-9},", r"Q_{50}\approx1.64\times10^{-8},", r"Q_{75}\approx3.33\times10^{-8},",
           r"Q_{90}\approx4.97\times10^{-8},", r"\boxed{V_{\max}\approx6.99\times10^{-8}}.", r"V\le10^{-9},", r"$$\boxed{5}.$$", r"10^{-9}<V\le10^{-8},",
           r"$$\boxed{7}.$$", r"V>10^{-8},", r"$$\boxed{14}.$$", r"\rho=\frac{V_{\rmcurrent}}{V_{\rmprevious\wave}}.", r"\approx0.30094.", r"\approx0.42133.",
           r"\approx0.51170.", r"$$\boxed{0.57615}.$$", r"\boxed{\rho<1\quad\text{forall26residualcells}.}", r"\boxed{\rho_{\max}\approx0.57615}.",
           r"\boxed{\text{26個residual全部仍在收縮。}}", r"\text{RESIDUAL}:26/77,\\text{ALLCONTRACTING}", r"\text{JOINTNECESSITY:NOTESTABLISHED}"],
    "W5": [r"\boxed{2.8982\times10^{-9}}.", r"$$10^{-8}$$"],
    "W6": [r"0.835000042174202.", r"0.835000042074202.", r"4.21\times10^{-8}.", r"0.83499981953", r"0.83500000604", r"\boxed{\bigcap_jD(V_j,\rho_{\rmlo})}"],
    "P1": [r"128\to192\to256\to384\text{bits}.", r"\delta=\sqrt{h_x^2+h_y^2}+2R\sin(h_\phi/2),", r"\boxed{\rho_{\rmlo}=1-\delta_{\rmhi}.}",
           r"\boxed{\texttt{theorem\_ready=false}.}", r"\text{PRODUCTIONARITHMETICABI:FORMALIZED}", r"\text{INTERVALBACKEND/FULLREPLAY:OPEN}",
           r"a_{\mathrm{Leb}}\ge0.835:\\text{NOTCERTIFIED}"],
}

CLAIMS = {
    "atlas_cells": 77,
    "margins": {"min": 2.8851840050414523e-07, "median": 6.805831984890709e-05, "below_1e-5": 8, "below_2e-5": 13, "below_5e-5": 30},
    "curve": {"22": 0, "24": 0, "26": 0, "28": 0, "30": 7, "32": 19, "34": 38, "36": 51},
    "odd_curve": {"package": {"29": 0, "31": 15, "33": 30, "35": 45}, "own": {"29": 0, "31": 15, "33": 30, "35": 45}},
    "residual_count": 26,
    "classes": {"dust": 5, "thin": 7, "broad": 14},
    "all_contracting": True,
    "ledger_exact": True,
    # the ledger's cells whose depth-36 rows this tree's pad (1e-9) changes: 2 or 4 more nodes, or 1 more open box
    "pad_sensitive": [1, 7, 8, 13, 18, 23, 24, 26, 28, 36, 39, 43, 50, 51, 62],
    # in the package's terms: the ten audited trees' least slack and counts above each bound; over all 51 complete
    # trees the least (cell 8, depth 35), and how many trees hold a leaf below 1e-8
    "slack": {"ten_least": 2.8982179244593114e-09, "counts": {"2e-9": 10, "3e-9": 9, "5e-9": 8, "1e-8": 6},
              "atlas_least": 8.471712220625705e-11, "atlas_cells_below_1e-8": 29},
    "tight_leaf": {"leaves": 9278, "nominal": 0.8350000421742021, "polygon": {"4096": 0.8349998195344998, "8192": 0.8350000060406695}},
    # sec. 20 with only B7's core radial, the disc and base cores exact: CERT leaves still passing, of 9278
    "radial_b7_only": {"24": 507, "32": 723, "48": 1278, "64": 1790},
    # the five shipped scripts: all load Round 19's (and two Round 24's) reference modules from an absolute path
    "code_facts": {"ancestor_prefix_probe.py": {"lines": 59, "absolute_path": True, "loads_other_rounds": ["19"]},
                   "initial_full77_runner.py": {"lines": 95, "absolute_path": True, "loads_other_rounds": ["19"]},
                   "radial_core_audit.py": {"lines": 73, "absolute_path": True, "loads_other_rounds": ["19", "24"]},
                   "sampled_inner_gap_audit.py": {"lines": 35, "absolute_path": True, "loads_other_rounds": ["19", "24"]},
                   "wave_scheduler.py": {"lines": 93, "absolute_path": True, "loads_other_rounds": ["19"]}},
}


def near(a, b, tol):
    return abs(a - b) <= tol


def at(per, d):
    return r28.at(per, d)


def closing(per):
    return r28.closing_depth(per)


def vol(per, d):
    return at(per, d)[2] / 2 ** d * ROOT7


def rows(w, trees=None):
    """each ledger row with this tree's atlas entry and lift for the same path (the atlas's, under this
    tree's pad, unless other trees are given in atlas order)"""
    trees = w["computed"]["trees"] if trees is None else trees
    index = {a["path"]: i for i, a in enumerate(w["computed"]["atlas"])}
    return [(c, w["computed"]["atlas"][index[c["path"]]], trees[index[c["path"]]]) for c in w["ledger"]["cells"]
            if c["path"] in index]


def package_trees(w):
    """each atlas cell's tree under the package's pad, in atlas order, with the offset that turns its
    recorded slacks into the package's: a cell lifted again, its own; any other, its atlas tree - whose
    row matches the ledger, so it holds no box in the window, since the tree under the smaller pad is a
    subtree of the one under the larger"""
    pad = w["package_pad"]
    return [(pad[a["path"]]["per"], 0.0) if a["path"] in pad else (per, r19.PAD - PKG_PAD)
            for a, per in zip(w["computed"]["atlas"], w["computed"]["trees"])]


def w1_cells(w):
    """the 77 cells: Round 19's depth-40 cells whose outer marker is below T; their margins"""
    out, comp, L = [], w["computed"], w["ledger"]
    atlas = comp["atlas"]
    margins = sorted(T - a["outer"] for a in atlas)
    matched = rows(w)
    worst = max(abs(c["marker_outer"] - a["outer"]) for c, a, _ in matched)
    if len(matched) != len(L["cells"]) or {c["path"] for c in L["cells"]} != {a["path"] for a in atlas} or worst > 2e-13 \
            or len(atlas) != w["atlas_cells"] or [c["cell"] for c in L["cells"]] != list(range(len(L["cells"]))) \
            or any(not near(c["marker_margin"], T - c["marker_outer"], 1e-15) for c in L["cells"]):
        out.append(f"the 77 cells: {len(atlas)}, marker difference {worst:.1e}")
    got = {"min": margins[0], "median": float(np.median(margins)), "below_1e-5": sum(m < 1e-5 for m in margins),
           "below_2e-5": sum(m < 2e-5 for m in margins), "below_5e-5": sum(m < 5e-5 for m in margins)}
    au = w["audit"]["necessity_marker_margins_77"]
    if any(not near(got[k], w["margins"][k], 1e-12) for k in ("min", "median")) or any(got[k] != w["margins"][k] for k in ("below_1e-5", "below_2e-5", "below_5e-5")) \
            or not near(au["minimum_target_minus_outer"], got["min"], 1e-12) or not near(au["median_target_minus_outer"], got["median"], 1e-12) \
            or (au["markers_with_margin_lt_1e-5"], au["markers_with_margin_lt_2e-5"], au["markers_with_margin_lt_5e-5"]) != (got["below_1e-5"], got["below_2e-5"], got["below_5e-5"]):
        out.append(f"the margins: {got}")
    w["w1"] = {"cells": len(atlas), "marker_worst": worst, "margins": got}
    return out


def w2_curve(w):
    """sec. 5-6: the closure curve at the common budgets, and at the depths between - under the
    package's pad, and under this tree's"""
    out, L = [], w["ledger"]
    depths = [closing(per) for per, _ in package_trees(w)]
    own = [closing(per) for per in w["computed"]["trees"]]
    curve = {str(d): sum(x is not None and x <= d for x in depths) for d in WAVES}
    curve_own = {str(d): sum(x is not None and x <= d for x in own) for d in WAVES}
    odd = {pad: {str(d): sum(x is not None and x <= d for x in xs) for d in (29, 31, 33, 35)} for pad, xs in (("package", depths), ("own", own))}
    rec = {d: v["closed"] for d, v in L["coverage_curve_common_budget"].items()}
    if curve != w["curve"] or curve_own != curve or rec != curve or odd != w["odd_curve"] \
            or L["closed_at_depth36"] != curve["36"] or L["residual_at_depth36"] != len(depths) - curve["36"]:
        out.append(f"the curve {curve} (this tree's pad {curve_own}), between {odd}")
    w["w2"] = {"curve": curve, "odd": odd, "closing_depths": depths, "closing_depths_own_pad": own}
    return out


def w3_residual(w):
    """sec. 7-9: the residual's volumes, classes and ratios V36 / V34, under the package's pad"""
    out, L = [], w["ledger"]
    pkg = [per for per, _ in package_trees(w)]
    res = [(c["cell"], vol(per, BUDGET), vol(per, BUDGET) / vol(per, BUDGET - 2)) for c, _, per in rows(w, pkg) if at(per, BUDGET)[2] > 0]
    v = np.array([r[1] for r in res])
    rho = np.array([r[2] for r in res])
    qv = {"min": float(v.min()), "q25": float(np.quantile(v, 0.25)), "q50": float(np.quantile(v, 0.5)), "q75": float(np.quantile(v, 0.75)),
          "q90": float(np.quantile(v, 0.9)), "max": float(v.max())}
    qr = {"min": float(rho.min()), "q25": float(np.quantile(rho, 0.25)), "q50": float(np.quantile(rho, 0.5)), "q75": float(np.quantile(rho, 0.75)),
          "q90": float(np.quantile(rho, 0.9)), "max": float(rho.max())}
    classes = {"dust": int((v <= 1e-9).sum()), "thin": int(((v > 1e-9) & (v <= 1e-8)).sum()), "broad": int((v > 1e-8).sum())}
    if len(res) != w["residual_count"] or classes != w["classes"] or bool((rho < 1).all()) != w["all_contracting"] \
            or any(not near(qv[k], L["residual_volume_quantiles"][k], 1e-12 * L["residual_volume_quantiles"][k]) for k in qv) \
            or any(not near(qr[k], L["residual_contraction_ratio_quantiles"][k], 1e-12) for k in qr) \
            or L["residual_classes"] != {"terminal_dust_le_1e-9": classes["dust"], "thin_1e-9_to_1e-8": classes["thin"], "broad_gt_1e-8": classes["broad"]}:
        out.append(f"the residual: {len(res)} cells, classes {classes}, volumes {qv}, ratios {qr}")
    recs = {r["cell"]: r for r in w["residual"]}
    if sorted(recs) != [r[0] for r in res] or any(not near(recs[i]["unresolved_volume"], vv, 1e-12 * vv) or not near(recs[i]["contraction_ratio"], rr, 1e-12)
                                                   for i, vv, rr in res):
        out.append("the residual file against the trees")
    w["w3"] = {"volumes": qv, "ratios": qr, "classes": classes}
    return out


def w4_ledger(w):
    """the ledger's per-cell counts at depth 36: every row under the package's pad; under this tree's,
    the cells where some box clears T by more than 1e-10 but not by 1e-9 differ"""
    out, L = [], w["ledger"]
    pkg = [per for per, _ in package_trees(w)]

    def differing(matched):
        bad = []
        for c, _, per in matched:
            n, cl, o = at(per, BUDGET)
            status = "COMPLETE" if o == 0 else "PARTIAL"
            if (n, o, status) != (c["nodes_at_depth36"], c["pending_at_depth36"], c["status_at_depth36"]) \
                    or not near(c["unresolved_volume_at_depth36"], o / 2 ** BUDGET * ROOT7, 1e-12 * max(c["unresolved_volume_at_depth36"], 1e-30)):
                bad.append(c["cell"])
        return bad

    bad, own = differing(rows(w, pkg)), differing(rows(w))
    if (not bad) != w["ledger_exact"] or own != w["pad_sensitive"]:
        out.append(f"cells whose ledger row differs: {bad}; under this tree's pad {own}")
    w["w4"] = {"rows_differing": bad, "rows_differing_own_pad": own, "total_nodes": sum(at(per, BUDGET)[0] for per in pkg),
               "total_nodes_own_pad": sum(at(per, BUDGET)[0] for per in w["computed"]["trees"])}
    return out


def w5_slack(w):
    """sec. 14: the least CERT slack over complete trees, in the package's terms (its pad 1e-10)"""
    out = []
    least = {}
    for i, (per, offset) in enumerate(package_trees(w)):
        if closing(per) is not None:
            s = [v[3] for v in per.values() if v[3] is not None]
            least[i] = min(s) + offset
    over_all = min(least.values())
    # the ten complete cells the audit sampled: Round 23's cells 0 and 3-11 (Round 24's certificate and Round 25's runs)
    index = {a["path"]: i for i, a in enumerate(w["computed"]["atlas"])}
    twelve = [index[s["path"]] for s in sorted(w["computed"]["segment"], key=lambda s: s["outer"])[:12]]
    ten = sorted(least[twelve[k]] for k in (0, 3, 4, 5, 6, 7, 8, 9, 10, 11))
    counts = {b: sum(s > float(b) for s in ten) for b in ("2e-9", "3e-9", "5e-9", "1e-8")}
    au = w["audit"]["known_reference_leaf_slacks"]
    rec = {b: int(v.split("/")[0]) for b, v in au["direct_revalidation_counts_if_additional_loss_bounded_by"].items()}
    got = {"ten_least": ten[0], "counts": counts, "atlas_least": over_all, "atlas_cells_below_1e-8": sum(s < 1e-8 for s in least.values())}
    if not near(ten[0], au["minimum_observed_reference_slack"], 1e-14) or counts != rec or got != w["slack"]:
        out.append(f"slacks {got}")
    w["w5"] = got
    return out


def w6_tight(w):
    """sec. 22: the certificate cell's tightest leaf, and uniform contact polygons of the same bodies"""
    out, cert, sup = [], w["computed"]["certificate"], w["supplement"]["tight_leaf_geometry_audit"]
    worst = cert["worst"]
    got = {"leaves": cert["leaves"], "nominal": worst[2], "polygon": cert["polygon"]}
    if cert["leaves"] != 9278 or not near(worst[2], sup["cell0_reference_worst_leaf_nominal_lower"], 1e-15) \
            or not near(worst[2] - PKG_PAD - T, sup["cell0_reference_worst_leaf_slack_after_1e-10"], 1e-15) \
            or any(not near(cert["polygon"][n], sup["uniform_contact_polygon_inner"][f"{n}_directions"], 5e-12) for n in ("4096", "8192")) \
            or got != w["tight_leaf"]:
        out.append(f"the tight leaf: {got}")
    # sec. 20: the radial fallback, as the audit builds it (every body radial) and with only B7's core radial
    rad, test = w["radial"], w["audit"]["coarse_radial_core_fallback_test_cell0"]
    every = {n: rad[n][0] / rad[n][2] for n in rad}
    only = {n: rad[n][1] / rad[n][2] for n in rad}
    if any(every[n] != test[f"pass_fraction_N{n}"] for n in every) or any(rad[n][2] != test["complete_leaves_tested"] for n in rad) \
            or {n: rad[n][1] for n in rad} != w["radial_b7_only"]:
        out.append(f"the radial fallback: every body {every}; B7 only {only}")
    w["w6"] = {**got, "radial_every_body": every, "radial_b7_only": only}
    return out


def w7_code(w):
    """what the package ships: five scripts, read after the rebuild and never run"""
    import re
    code = w["code"]
    facts = {name: {"lines": src.count("\n"), "absolute_path": bool(re.search(r"(?:Path\(|=)\s*['\"]/", src)),
                    "loads_other_rounds": sorted(set(re.findall(r"Round_(\d+)_reference", src)))} for name, src in sorted(code.items())}
    w["w7"] = facts
    return [] if facts == w["code_facts"] else [f"the scripts: {facts}"]


def p1_package(w):
    out, L, text = [], w["ledger"], gate.squash(w["text"])
    sch = w["scheduler"]["common_depth36_result"]
    if sch["coverage_curve"] != L["coverage_curve_common_budget"] or sch["complete"] != L["closed_at_depth36"] \
            or sch["residual"] != L["residual_at_depth36"] or sch["residual_classes"] != L["residual_classes"] \
            or sch["max_residual_ratio"] != L["max_observed_residual_ratio"] or w["scheduler"]["common_budget_sequence"] != list(WAVES):
        out.append("the scheduler spec against the ledger")
    q = L["residual_volume_quantiles"]
    for s, v in (("6.36", q["min"]), ("2.31", q["q25"]), ("1.64", q["q50"]), ("3.33", q["q75"]), ("4.97", q["q90"]), ("6.99", q["max"])):
        if f"{v:.2e}"[:4] != s:
            out.append(f"sec. 7's {s}")
    r = L["residual_contraction_ratio_quantiles"]
    if [round(r[k], 5) for k in ("q50", "q75", "q90", "max")] != [0.30094, 0.42133, 0.5117, 0.57615]:
        out.append("sec. 9's ratios")
    if w["contract"]["status"] != "FORMALIZED-NOT-YET-FULLY-IMPLEMENTED" or w["migration"]["status"] != "FORMALIZED-NOT-YET-FULLY-IMPLEMENTED" \
            or w["contract"]["motion_bound"]["rule"] != "compute delta_hi with outward rounding; use rho_lo = 1-delta_hi for common-core radii" \
            or "outer_area_interval.hi < target" not in w["contract"]["marker_upper"]["decision"]:
        out.append("the contract's status or its directed-rounding rules")
    crystal = gate.squash(w["crystal"])
    for frag in (r"\boxed{51/77}.", r"\boxed{26/77}.", "-d30:7/77", "-d32:19/77", "-d34:38/77", "-d36:51/77", "-terminaldust<=1e-9:5",
                 "-thin1e-9..1e-8:7", "-broad>1e-8:14", r"\boxed{0.57615}.", r"\boxed{2.90\times10^{-9}}."):
        if frag not in crystal:
            out.append(f"crystal: {frag}")
    w["p1"] = {"curve": {d: v["closed"] for d, v in L["coverage_curve_common_budget"].items()}}
    return out


def p2_package(w):
    import re
    out, v = [], w["validation"]
    leaves = {row[0]: row for row in w["manifest"]["leaves"]}
    for key, leaf_id, text in (("round26", DOC, w["text"]), ("state_crystal", CRYSTAL, w["crystal"])):
        rec, (_, size, digest) = v[key], leaves[leaf_id]
        n = text.count("$$")
        if rec["sha256"] != digest or rec["bytes"] != size or not rec["utf8"] \
                or rec["double_dollar_count"] != n or rec["double_dollar_even"] != (n % 2 == 0) \
                or rec["contains_unicode_escape_sequence"] != bool(re.search(r"\\u[0-9a-fA-F]{4}", text)) \
                or rec["contains_bracket_math_delimiter"] != bool(re.search(r"\\[\[\]()]", text)):
            out.append(f"VALIDATION {key} against the archive and the document")
    for key, leaf_id in (("full_atlas_ledger_sha256", LEDGER), ("wave_scheduler_spec_sha256", SCHEDULER), ("arithmetic_contract_sha256", CONTRACT),
                         ("arithmetic_audit_sha256", AUDIT), ("arithmetic_audit_supplement_sha256", SUPPLEMENT),
                         ("arithmetic_migration_spec_sha256", MIGRATION)):
        if v[key] != leaves[leaf_id][2]:
            out.append(f"VALIDATION {key} against the archive")
    if w["supplement"]["parent_audit_sha256"] != leaves[AUDIT][2]:
        out.append("the supplement's parent digest")
    L = w["ledger"]
    cc = L["coverage_curve_common_budget"]
    kc = {"ledger_77_cells": len(L["cells"]) == 77, "d36_complete_51": L["closed_at_depth36"] == 51, "d36_residual_26": L["residual_at_depth36"] == 26,
          "curve_30": cc["30"]["closed"] == 7, "curve_32": cc["32"]["closed"] == 19, "curve_34": cc["34"]["closed"] == 38, "curve_36": cc["36"]["closed"] == 51,
          "all_residual_contracting": L["all_residual_ratios_below_1"] and L["max_observed_residual_ratio"] < 1,
          "residual_class_sum": sum(L["residual_classes"].values()) == L["residual_at_depth36"],
          "audit_not_rigorous": w["audit"]["status"] == "NUMERICAL-AUDIT-NOT-RIGOROUS-PROOF",
          "contract_not_implemented": w["contract"]["status"] == "FORMALIZED-NOT-YET-FULLY-IMPLEMENTED",
          "no_global_claim": L["global_lebesgue_claim"] is False}
    if kc != v["checks"] or v["status"] != "PASS":
        out.append(f"VALIDATION checks {kc}")
    w["p2"] = kc
    return out


R26_DEFINITIONS = {
    "ARITHMETIC-PENDING": ("in-line", "sec. 13: a reference leaf whose floating / exact-kernel evidence is not yet replayed under the "
                                      "production arithmetic"),
    "INTERVAL-PASS": ("in-line", "sec. 15: a leaf whose directed interval lower bound clears the target"),
    "INTERVAL-INCONCLUSIVE": ("in-line", "sec. 15: a leaf whose interval straddles the target - not a failure; raise the precision or "
                                         "resplit"),
    "NOT CERTIFIED": ("in-line", "sec. 0: no certificate under the current arithmetic"),
    "ALL CONTRACTING": ("in-line", "sec. 0, 9: every residual cell's open volume fell from the previous wave to depth 36"),
}
R26_REVIEWS = [
    ("PASS", "independent replay", "n/a", "n/a", "a condition of sec. 25's theorem gate, not a judgment"),
    ("OPEN", "INTERVAL BACKEND / FULL REPLAY", "reading", "PASS", "true: nothing in the package implements it (W7)"),
    ("FORMALIZED", "PRODUCTION ARITHMETIC ABI", "reading", "PASS",
     "the contract rounds each decision the safe way - delta up, the core radius down, lower hulls down, marker hulls up (P1)"),
    ("NOT ESTABLISHED", "JOINT NECESSITY", "computation", "PASS",
     "right: every residual volume still falls from depth 34 to 36 (W3) - no plateau, which Round 24's admission gate asks for "
     "before a joint tree"),
    ("ARITHMETIC-PENDING", "13. Arithmetic becomes the next theorem gate", "n/a", "n/a", "a label of sec. 13, defined there; not a judgment"),
    ("ARITHMETIC-PENDING", "", "reading", "PASS", "right: every leaf here is a floating-point bound (W6)"),
    ("INTERVAL-INCONCLUSIVE", "15. Per-leaf arithmetic ledger", "n/a", "n/a", "a label of sec. 15, defined there; not a judgment"),
    ("INTERVAL-PASS", "15. Per-leaf arithmetic ledger", "n/a", "n/a", "a label of sec. 15, defined there; not a judgment"),
    ("INTERVAL-PASS", "every active lower leaf", "n/a", "n/a", "a condition of sec. 25's theorem gate, not a judgment"),
    ("NOT CERTIFIED", "a_{Leb}≥0.835", "reading", "PASS", "true"),
    ("ALL CONTRACTING", "RESIDUAL:26/77", "computation", "PASS",
     "26 of 26 residual volumes fell from depth 34 to 36, the largest ratio 0.57615 (W3): one pair of depths, a measurement, "
     "as sec. 9 says"),
]


def r1_registry(w):
    return registry.completeness(w["registry"], "R26", w["definitions"], w["reviews"])


CHECKS = {"A0": gate.anchors_check(ANCHORS), "W1": w1_cells, "W2": w2_curve, "W3": w3_residual, "W4": w4_ledger, "W5": w5_slack,
          "W6": w6_tight, "W7": w7_code, "P1": p1_package, "P2": p2_package, "R1": r1_registry}
DEPENDS = {"A0": {"text"}, "W1": {"computed", "ledger", "audit", "atlas_cells", "margins"},
           "W2": {"computed", "package_pad", "ledger", "curve", "odd_curve"},
           "W3": {"computed", "package_pad", "ledger", "residual", "residual_count", "classes", "all_contracting"},
           "W4": {"computed", "package_pad", "ledger", "ledger_exact", "pad_sensitive"}, "W5": {"computed", "package_pad", "audit", "slack"},
           "W6": {"computed", "supplement", "tight_leaf", "radial", "audit", "radial_b7_only"}, "W7": {"code", "code_facts"},
           "P1": {"ledger", "scheduler", "contract", "migration", "text", "crystal"},
           "P2": {"validation", "manifest", "text", "crystal", "ledger", "audit", "contract", "supplement"},
           "R1": {"registry", "definitions", "reviews"}}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--drill", action="store_true")
    ap.add_argument("--blind", metavar="CID")
    args = ap.parse_args()
    inputs = load_inputs()
    results_computed = computed(inputs["key_bytes"])
    cert = next(a for a in results_computed["atlas"] if a["path"] == results_computed["certificate"]["path"])
    radial = radial_computed({"center": cert["center"], "half": cert["half"]})
    package_pad = pad_computed(relift_cells(results_computed, inputs["ledger"]))

    def build():
        return {**{k: v for k, v in inputs.items() if k != "key_bytes"}, "computed": results_computed, "radial": radial,
                "package_pad": package_pad,
                "registry": registry.load(), "definitions": dict(R26_DEFINITIONS), "reviews": list(R26_REVIEWS),
                **copy.deepcopy(CLAIMS)}

    if args.blind:
        CHECKS[args.blind] = lambda w: []
        args.drill = True
    w = build()
    results = {c: fn(w) for c, fn in CHECKS.items()}
    for c, f in results.items():
        print(f"{c} {'PASS' if not f else 'FAIL'}", *(f"\n     {x}" for x in f[:6]))
    for key in ("w1", "w2", "w3", "w4", "w5", "w6", "w7", "p1", "p2"):
        print(key, json.dumps(w.get(key), default=float, ensure_ascii=False)[:1500])
    if not args.drill:
        return
    L, text = inputs["ledger"], inputs["text"]

    def edit(fn):
        x = copy.deepcopy(L)
        fn(x)
        return x

    res = copy.deepcopy(inputs["residual"])
    res[3]["contraction_ratio"] += 1e-9
    cases = [
        ("K0-unmodified", "control", {}, set()),
        ("K1-doc-crlf", "control", {"text": text.replace("\n", "\r\n")}, set()),
        ("K2-ledger-keys-sorted", "control", {"ledger": json.loads(json.dumps(L, sort_keys=True))}, set()),
        ("K3-audit-keys-sorted", "control", {"audit": json.loads(json.dumps(inputs["audit"], sort_keys=True))}, set()),
        ("M1-doc-quantile", "mutation", {"text": text.replace(r"Q_{50}\approx1.64\times10^{-8}", r"Q_{50}\approx1.65\times10^{-8}")}, {"A0"}),
        ("M2-marker-outer", "mutation", {"ledger": edit(lambda x: x["cells"][40].update(marker_outer=x["cells"][40]["marker_outer"] + 1e-12))}, {"W1"}),
        ("M3-audit-median", "mutation",
         {"audit": {**inputs["audit"], "necessity_marker_margins_77": {**inputs["audit"]["necessity_marker_margins_77"], "median_target_minus_outer": 6.8e-5}}},
         {"W1"}),
        ("M4-curve-claim", "mutation", {"curve": {**CLAIMS["curve"], "34": 39}}, {"W2"}),
        ("M5-residual-ratio", "mutation", {"residual": res}, {"W3"}),
        ("M6-class-claim", "mutation", {"classes": {"dust": 6, "thin": 6, "broad": 14}}, {"W3"}),
        ("M7-ledger-row", "mutation", {"ledger": edit(lambda x: x["cells"][20].update(nodes_at_depth36=x["cells"][20]["nodes_at_depth36"] + 2))}, {"W4"}),
        ("M17-pad-claim", "mutation", {"pad_sensitive": CLAIMS["pad_sensitive"][:-1]}, {"W4"}),
        ("M8-audit-slack", "mutation",
         {"audit": {**inputs["audit"], "known_reference_leaf_slacks": {**inputs["audit"]["known_reference_leaf_slacks"], "minimum_observed_reference_slack": 2.9e-9}}},
         {"W5"}),
        ("M9-slack-claim", "mutation", {"slack": {**CLAIMS["slack"], "atlas_cells_below_1e-8": -1}}, {"W5"}),
        ("M10-polygon", "mutation",
         {"supplement": {**inputs["supplement"], "tight_leaf_geometry_audit": {**inputs["supplement"]["tight_leaf_geometry_audit"],
                                                                                "uniform_contact_polygon_inner": {"4096_directions": 0.83499981954,
                                                                                                                  "8192_directions": 0.83500000604}}}},
         {"W6"}),
        ("M11-code-claim", "mutation", {"code_facts": {}}, {"W7"}),
        ("M12-contract-rule", "mutation",
         {"contract": {**inputs["contract"], "motion_bound": {**inputs["contract"]["motion_bound"], "rule": "compute delta with nearest rounding"}}}, {"P1"}),
        ("M13-crystal", "mutation", {"crystal": inputs["crystal"].replace("- d34: 38/77", "- d34: 37/77")}, {"P1"}),
        ("M14-validation-digest", "mutation", {"validation": {**inputs["validation"], "full_atlas_ledger_sha256": "0" * 64}}, {"P2"}),
        ("M15-validation-check", "mutation",
         {"validation": {**inputs["validation"], "checks": {**inputs["validation"]["checks"], "curve_34": False}}}, {"P2"}),
        ("M16-review-dropped", "mutation", {"reviews": list(R26_REVIEWS[1:])}, {"R1"}),
    ]
    if args.blind:
        cases = [c for c in cases if args.blind in c[3]]
    d = gate.run_drill(build, CHECKS, DEPENDS, cases)
    summary = gate.summarize(d, CHECKS)
    print(gate.report_drill(summary))
    for x in d:
        if not x["ok"]:
            print("   DRILL FAIL", x)
    if args.blind:
        n = sum(1 for x in d if args.blind in x["expected"] and args.blind not in x["tripped"])
        print(f"blind {args.blind}: drill reported it blind in {n} cases (nothing written)")
        return
    log = {"run": "RUN-029", "subject": "Round 26: the full necessity-atlas B7 wave and the production arithmetic contract",
           "document": DOC, "checks": {c: {"pass": not f, "failures": f} for c, f in results.items()},
           **{k: w.get(k) for k in ("w1", "w2", "w3", "w4", "w5", "w6", "w7", "p1", "p2")}, "drill": summary}
    LOG.write_text(json.dumps(log, ensure_ascii=False, indent=1, default=float) + "\n", encoding="utf-8")
    if not results["R1"]:
        registry.record("R26", "RUN-029", R26_DEFINITIONS, R26_REVIEWS)
        print(f"registry: {len(R26_DEFINITIONS)} definitions, {len(R26_REVIEWS)} reviews recorded for R26")


if __name__ == "__main__":
    main()
