"""RUN-044 - UESFCM Cycles 01-03: the B7 separator gate, the minimizer atlas and exact exchange, orbit localization.

The first three Lebesgue cycles of UESFCM (2026-09-19) start from Mishra's certified seed D, B3, B5
(Lambda >= 0.8344) and its exhibited ceiling A3+ = 0.834781191. Cycle 01 measures how far B7 fails to fit the
seed's near-minimal hull U0 (a support-direction LP on a grid of directions and orientations) and ranks the
regular Reuleaux odd-gons. Cycle 02 proves a hull Hausdorff radius for a placement box, a minimizer-atlas
theorem and the exact witness-exchange equivalence (Lambda grows iff the batch separates every minimizer).
Cycle 03 shrinks the translation domain by the farthest corner, reduces the gate to one margin s7 and one
orbit radius, measures s7 continuously, reports that the minimum is sharp and that coarse angle grids give
false minima, and rejects the replacement family D, B3, B7. Here every number is rebuilt with this tree's
exact hull (RUN-009, with RUN-031's verified segments), the LP and the domain from their definitions, and
what the cycles attribute to Mishra is read in his full text.

Checks
  A0 anchors      the numbers and formulas below occur in the three documents as written
  X1 paper        Mishra's full text (v2): the gauge, the confining box, the forest of the emitting run, the
                  erosion lemma, the fourth body, the eight-dimensional cost; Remarks 20 and 34
  W1 separator    Cycle 01: U0 is the repository's placement; the grid LP at M = 2048, P = 256 and its
                  orientation loss; the ranking of B7 ... B41; the headroom
  W2 atlas        Cycle 02: R5; the hull Hausdorff radius on random boxes; the confining box covers the
                  A3+-sublevel; the quoted optima
  W3 domain       Cycle 03 sec. 2-4: d*, T3, T5 and the volume factor at A3+ and at 0.8344; the exclusion
  W4 margin       Cycle 03 sec. 6: M_U0(B7) minimized continuously over translation and orientation (a numerical
                  minimum: a 2048-turn scan, every local minimum refined)
  W5 sharpness    Cycle 03 sec. 13-16: the one-sided slopes at the seed; the grid trap of sec. 14
  W6 replacement  Cycle 03 sec. 17: the family D, B3, B7 and its outer polygons
  W7 crystals     the three state crystals against the numbers rebuilt here
  W8 code         the three scripts, read after the rebuild and never run
  P1 package      the three VALIDATION records against the archive

Usage: python code/run044_uesfcm_cycles_01_03.py [--refresh] [--drill] [--blind CID]
"""
import argparse
import copy
import datetime
import hashlib
import inspect
import json
import math
import re

import numpy as np
from scipy.optimize import brentq, differential_evolution, linprog, minimize

import gate
from corpus import SOURCES, TREE, source_bytes, walk_sources
from run008_round05_saturation_gate import envelope, phi_text, reuleaux_support, segments, verify_segments, wrap
from run009_round06_witness_exchange import hull_pieces, placed_disc, placed_reuleaux

FOLDER = "main.zip!/UESFCM/"
PKG = {i: FOLDER + f"UESFCM_Lebesgue_Cycle_{i:02d}_Package_v0.1.zip!/" for i in (1, 2, 3)}
DOCS = {1: PKG[1] + "UESFCM_Lebesgue_Cycle_01_B7_Separator_Gate_v0.1.md",
        2: PKG[2] + "UESFCM_Lebesgue_Cycle_02_Minimizer_Atlas_and_Exact_Exchange_v0.1.md",
        3: PKG[3] + "UESFCM_Lebesgue_Cycle_03_Orbit_Localization_and_Scalar_Closure_v0.1.md"}
CODE = {1: PKG[1] + "UESFCM_Lebesgue_Cycle_01_B7_Separator_Search.py", 2: PKG[2] + "UESFCM_Lebesgue_Cycle_02_Atlas_Compiler_Scaffold.py",
        3: PKG[3] + "UESFCM_Lebesgue_Cycle_03_Scalar_Gate_Utilities.py"}
CRYSTALS = {i: PKG[i] + f"UESFCM_Lebesgue_State_Crystal_Cycle_{i:02d}_v0.1.json" for i in (1, 2, 3)}
VALIDATIONS = {i: PKG[i] + f"UESFCM_Lebesgue_Cycle_{i:02d}_VALIDATION.json" for i in (1, 2, 3)}
SNAPSHOT = TREE / "data" / "external" / "uesfcm-c01-c03-mishra.json"
ROUND07 = TREE / "data" / "external" / "round07-citations.json"
ROUND11 = TREE / "data" / "external" / "round11-repository.json"
RUN010 = TREE / "data" / "gate-logs" / "run010-round07-minimizer-atlas.json"
LOG = TREE / "data" / "gate-logs" / "run044-uesfcm-cycles-01-03.json"
MANIFEST = TREE / "data" / "SOURCE_MANIFEST.v1.json"
CACHE = TREE / "data" / "cache" / "run044-searches.json"     # data/cache is not committed

A3 = 0.834781191                 # Mishra's exhibited ceiling (sec. 2 of Cycle 02)
MISHRA = ("2608.30538", 2)
# short phrases only, matched in the full text of v2 (the page itself is never kept)
MISHRA_FACTS = {
    "gauge": r"ρ ∈ \[ 0 , 2 π / 5 \)",
    "lemma18": r"f \( d \) = 1 4 \( π − arccos 1 2 d \) \+ 1 2 d 2 − 1 4",
    "corollary19": r"If A \( t 3 , ρ , t 5 \) < 0\.8344 .{0,40}then \| t 3 \| ≤ 0\.70 .{0,30}and \| t 5 \| ≤ 0\.70",
    "f070": r"A ≥ f \( \| t 3 \| \) > f \( 0\.70 \) > 0\.836548794 > 0\.8344",
    "search_box": r"The search therefore runs over the compact box \[ − 0\.70 , 0\.70 \] 2 × \[ 0 , 2 π / 5 \] × \[ − 0\.70 , 0\.70 \] 2",
    "remark20": r"Applying Lemma 18 to the farthest corner of a body rather than to its centre .{0,600}?the resulting domain is \| t 3 \| ≤ 0\.192366 "
                r".{0,40}and \| t 5 \| ≤ 0\.195891 .{0,40}, smaller by a factor of 169 in four-dimensional volume",
    "remark34": r"The sharper domain of Remark 20 does not reduce this cost\. Run at τ = 0\.833 .{0,40}with every other parameter fixed, "
                r"the subdivision examines 25,425,568 boxes over the domain of Corollary 19 and 27,350,260 over the smaller one",
    "radii": r"R 3 = 0\.577350269190 .{0,40}and R 5 = 0\.525731112119",
    "erosion": r"A corner of B 5 B_\{5\} moves by at most δ 5 = h x 2 \+ h y 2 \+ 2 R 5 sin \( h ρ / 2 \)",
    "forest": r"a forest of s s such trees with L L leaves in total has exactly 2 L − s 2L-s nodes",
    "emitting_run": r"For τ = 0\.8344 \\tau=0\.8344 the emitting run produced 486,799,600 nodes and 245,496,952 leaves",
    "located_optima": r"numerically located optimum, 0\.834780947 in the first family and 0\.836494901 in the second",
    "fourth_body": r"Adding the Reuleaux heptagon raises the attainable value to 0\.836494901",
    "cost_8d": r"calls for about 8\.6 × 10 11 .{0,30}boxes, near 880 days at the measured throughput",
    "commit": r"frozen at commit da956b117a",
}
RANKED = (7, 9, 11, 13, 15, 17, 19, 21, 25, 31, 41)


def load_inputs():
    blobs = {n: source_bytes(n) for n in SOURCES}
    want = set(DOCS.values()) | set(CODE.values()) | set(CRYSTALS.values()) | set(VALIDATIONS.values())
    got = {leaf.id: d for leaf, d in walk_sources(blobs, keep=lambda l: l.id in want) if d is not None}
    rows = {row[0]: row for row in json.loads(MANIFEST.read_text(encoding="utf-8"))["leaves"]}
    seed = json.loads(ROUND11.read_text(encoding="utf-8"))["facts"]["src/certemitB.py"]["seed_depth"]
    return {"texts": {i: got[DOCS[i]].decode("utf-8") for i in DOCS}, "code": {i: got[CODE[i]].decode("utf-8") for i in CODE},
            "crystals": {i: json.loads(got[CRYSTALS[i]]) for i in CRYSTALS},
            "validations": {i: json.loads(got[VALIDATIONS[i]]) for i in VALIDATIONS},
            "files": {k.split("!/")[-1]: got[k] for k in want}, "manifest_rows": {k.split("!/")[-1]: rows[k] for k in want},
            "repository": json.loads(ROUND07.read_text(encoding="utf-8"))["repository"],
            "seed_depth": int(re.search(r"else (\d+)", seed).group(1)),
            "four_body_search": json.loads(RUN010.read_text(encoding="utf-8"))["w4"]["four_body_search"]}


# ---------------------------------------------------------------- the hull, its support, the margin

def support(pieces):
    """the hull's support function: the largest c.u + rho over the pieces, an arc counting only on its range"""
    C = np.array([p[0] for p in pieces], dtype=float)
    rho = np.array([p[1] for p in pieces], dtype=float)
    ranged = [(k, p[2]) for k, p in enumerate(pieces) if p[2] is not None]

    def h(th):
        th = np.atleast_1d(np.asarray(th, dtype=float))
        V = C @ np.stack([np.cos(th), np.sin(th)]) + rho[:, None]
        for k, (mid, half) in ranged:
            V[k, np.abs(wrap(th - mid)) > half] = -np.inf
        return V.max(axis=0)
    return h


def base_pieces(v, n=5):
    """D at the origin, B3 at t3 in the gauge's orientation, B_n turned by rho at t_n"""
    return placed_disc() + placed_reuleaux(3, 0.0, v[:2]) + placed_reuleaux(n, v[2], v[3:5])


def family_area(v, n=5, N=16384, verify=True):
    return hull_pieces(base_pieces(v, n), N, verify)[0]


def lp_margin(F, th):
    """min over t of max_j [F_j + t.u_j]: a linear program in (t_x, t_y, s)"""
    A = np.stack([np.cos(th), np.sin(th), -np.ones_like(th)], axis=1)
    res = linprog(c=[0, 0, 1], A_ub=A, b_ub=-F, bounds=[(None, None)] * 3, method="highs")
    return res.fun, res.x[:2]


def grid_margins(v, n, M=2048, P=256):
    """Cycle 01 sec. 7-9: the margin of B_n in U(v) on M support directions, at P orientations over one period"""
    hU, hK = support(base_pieces(v)), reuleaux_support(n)
    th = 2 * np.pi * np.arange(M) / M
    hv = hU(th)
    return [lp_margin(hK(th - 2 * np.pi / n * l / P) - hv, th)[0] for l in range(P)]


def golden_max(g, a, b, iters=80):
    r = (math.sqrt(5) - 1) / 2
    c, d = b - r * (b - a), a + r * (b - a)
    gc, gd = g(c), g(d)
    for _ in range(iters):
        if gc > gd:
            b, d, gd = d, c, gc
            c = b - r * (b - a)
            gc = g(c)
        else:
            a, c, gc = c, d, gd
            d = a + r * (b - a)
            gd = g(d)
    return (c, gc) if gc > gd else (d, gd)


def golden_min(g, a, b, iters=90):
    """the least value of g on [a, b] by golden-section search: no smoothness assumed (the margin has a kink
    at its minimum), and the bracket shrinks to the float spacing"""
    x, v = golden_max(lambda t: -g(t), a, b, iters)
    return x, -v


def continuous_margin(hU, hK, phi, M0=4096, M1=1 << 16, rounds=8):
    """min over t of max over every direction of h_K(R_phi^T u) + t.u - h_U(u): the LP on a direction set, the
    true maximum at its t found from a fine grid and golden-section refinement of every peak, the refined
    directions added, until the two agree. Returns (the LP value, a lower bound; the true maximum at the LP's t,
    an upper bound)"""
    th = list(2 * np.pi * np.arange(M0) / M0)
    fine = 2 * np.pi * np.arange(M1) / M1
    Ffine = hK(fine - phi) - hU(fine)
    low = up = None
    for _ in range(rounds):
        arr = np.array(th)
        low, t = lp_margin(hK(arr - phi) - hU(arr), arr)
        g = Ffine + t[0] * np.cos(fine) + t[1] * np.sin(fine)
        top = np.nonzero(g >= g.max() - 1e-6)[0]
        peaks = [i for i in top if g[i] >= g[(i - 1) % M1] and g[i] >= g[(i + 1) % M1]]
        gc = lambda x: float(hK(np.array([x - phi]))[0] - hU(np.array([x]))[0] + t[0] * math.cos(x) + t[1] * math.sin(x))
        refined = [golden_max(gc, fine[i] - 2 * np.pi / M1, fine[i] + 2 * np.pi / M1) for i in peaks]
        up = max(v for _, v in refined)
        th += [x for x, _ in refined]
        if up - low < 1e-15:
            break
    return low, up


def rn(n):
    """the circumradius of the regular n-gon whose diagonal is 1: the corners' distance from the centre"""
    return 1 / (2 * math.cos(math.pi / (2 * n)))


def d_star(T):
    """Phi_{1/2}^{-1}(T): the distance at which one point and the disc already span area T"""
    return brentq(lambda d: phi_text(0.5, d) - T, 0.5 + 1e-12, 2.0, xtol=1e-16)


def t_bound(n, T):
    """Cycle 03 sec. 3: the translation at which the nearest corner reaches d*(T)"""
    R, c, d = rn(n), math.cos(math.pi / n), d_star(T)
    return -R * c + math.sqrt(R * R * c * c - R * R + d * d)


def outer_area(pieces, N):
    """the polygon cut out by the N supporting half-planes at uniform directions"""
    th = 2 * np.pi * np.arange(N) / N
    h, d = support(pieces)(th), 2 * np.pi / N
    ell = (np.roll(h, 1) - h * math.cos(d)) / math.sin(d) + (np.roll(h, -1) - h * math.cos(d)) / math.sin(d)
    return 0.5 * float(np.sum(h * ell))


def outer_stable(pieces, th):
    """the polygon of the supporting lines at any set of directions, each edge length written without the
    cancellation of h' - h cos d (= h' - h + 2 h sin^2(d/2)), the sum taken exactly rounded"""
    th = np.unique(np.mod(np.asarray(th, dtype=float), 2 * np.pi))
    hv = support(pieces)(th)
    dn = np.roll(th, -1) - th
    dn[-1] += 2 * np.pi
    dp = th - np.roll(th, 1)
    dp[0] += 2 * np.pi
    ell = (np.roll(hv, -1) - hv + 2 * hv * np.sin(dn / 2) ** 2) / np.sin(dn) + (np.roll(hv, 1) - hv + 2 * hv * np.sin(dp / 2) ** 2) / np.sin(dp)
    return 0.5 * math.fsum((hv * ell).tolist())


def handovers(pieces):
    """the angles where the hull's support passes from one piece to another: the normals of its bridging edges
    (the verified segments of RUN-031)"""
    C = np.array([p[0] for p in pieces], dtype=float)
    rho = np.array([p[1] for p in pieces], dtype=float)
    ranged = [(k, p[2]) for k, p in enumerate(pieces) if p[2] is not None]

    def owner(t):
        V = C @ np.stack([np.cos(t), np.sin(t)]) + rho[:, None]
        for k, (mid, half) in ranged:
            V[k, np.abs(wrap(t - mid)) > half] = -np.inf
        return np.argmax(V, axis=0)
    cuts, own = envelope(owner, 2048, len(pieces))
    return sorted({a % (2 * math.pi) for a, b, k in verify_segments(C, rho, [p[2] for p in pieces], list(segments(cuts, own)))})


def ceiling_excess(v0):
    """Cycle 02 sec. 2: A3+ is the area of the outer polygon of 10^6 uniform supporting lines at the seed. Its
    excess over the seed's exact hull, recomputed without cancellation; the repository's own; and the excess once
    the hull's hand-over directions join 10^4 uniform ones"""
    P, A = base_pieces(v0), family_area(v0)
    h = handovers(P)
    return {"uniform_1e6": outer_stable(P, 2 * np.pi * np.arange(10 ** 6) / 10 ** 6) - A, "handovers": len(h),
            "uniform_1e4": outer_stable(P, 2 * np.pi * np.arange(10 ** 4) / 10 ** 4) - A,
            "with_handovers_1e4": outer_stable(P, np.concatenate([2 * np.pi * np.arange(10 ** 4) / 10 ** 4, h])) - A}


# ---------------------------------------------------------------- the searches (cached)

HELPERS = ("support", "base_pieces", "family_area", "lp_margin", "golden_max", "golden_min", "continuous_margin", "rn", "d_star", "t_bound",
           "outer_area")


def _key(fn):
    """a search's cache key: its own code, the helpers above, and run008/run009's hull kernel"""
    import run008_round05_saturation_gate as r8
    import run009_round06_witness_exchange as r9
    digest = hashlib.sha256(inspect.getsource(fn).encode())
    for name in HELPERS:
        digest.update(inspect.getsource(globals()[name]).encode())
    for path in (r8.__file__, r9.__file__):
        digest.update(open(path, "rb").read())
    return digest.hexdigest()


def landscape(v, n=7, P=2048):
    """Cycle 03 sec. 6: the continuous margin over one period of orientations - a continuous scan at P turns, then
    every local minimum of the scan refined by golden-section search over the two steps around it. A numerical
    minimum, not a certified one: between two scanned turns the margin can fall by up to R_n pi / (n P) (it is
    R_n-Lipschitz in the turn), and the scan points within that of the best are counted"""
    hU, hK, per = support(base_pieces(v)), reuleaux_support(n), 2 * math.pi / n
    phis = per * np.arange(P) / P
    vals = np.array([continuous_margin(hU, hK, f, M0=2048, M1=1 << 14, rounds=3)[1] for f in phis])
    local = [i for i in range(P) if vals[i] <= vals[i - 1] and vals[i] <= vals[(i + 1) % P]]
    minima = []
    for i in local:
        x, _ = golden_min(lambda f: continuous_margin(hU, hK, f)[1], phis[i] - per / P, phis[i] + per / P, iters=70)
        lo, up = continuous_margin(hU, hK, x)
        minima.append({"grid": i, "phi": float(x), "low": float(lo), "up": float(up)})
    best = min(m["up"] for m in minima)
    slack = rn(n) * per / P / 2
    return {"scan_min": float(vals.min()), "minima": minima, "slack": slack,
            "within_slack": [int(i) for i in np.nonzero(vals - slack < best)[0]]}


def sharpness(v0, m=200, seed=44):
    """Cycle 03 sec. 13: one-sided slopes of the exact hull area at the seed, along the ten coordinate
    directions and m random ones, at two step lengths; the least slope then minimized over the sphere"""
    def area_at(v):
        """the verified hull area; where the hand-over chain breaks on one grid (the kernel raises rather than
        guess), the next grid - the segments are checked in closed form either way"""
        for n in (16384, 16381, 12289, 8191):
            try:
                return family_area(v, 5, n)
            except RuntimeError:
                continue
        raise RuntimeError(f"no grid for {list(v)}")

    A0 = area_at(v0)
    rng = np.random.default_rng(seed)
    dirs = rng.normal(size=(m, 5))
    dirs = np.vstack([np.eye(5), -np.eye(5), dirs / np.linalg.norm(dirs, axis=1)[:, None]])
    slope = lambda d, h: (area_at(np.asarray(v0) + h * np.asarray(d) / np.linalg.norm(d)) - A0) / h
    out = {"A0": float(A0)}
    for h in (1e-5, 1e-6):
        s = np.array([slope(d, h) for d in dirs])
        out[str(h)] = {"least": float(s.min()), "median": float(np.median(s)), "negative": int((s < 0).sum())}
        if h == 1e-6:
            starts = dirs[np.argsort(s)[:5]]
    best = None
    for start in starts:
        res = minimize(lambda d: slope(d, 1e-6), start, method="Nelder-Mead", options={"xatol": 1e-6, "fatol": 1e-9, "maxfev": 2000})
        val = float(slope(res.x, 1e-6))
        if best is None or val < best[0]:
            best = (val, res.x / np.linalg.norm(res.x))
    out["least_minimized"], d = best[0], best[1]
    out["direction"] = [float(x) for x in d]
    rise = lambda t: area_at(np.asarray(v0) + t * d) - A0
    out["profile"] = {f"{t:+.0e}": rise(t) for t in (1e-6, -1e-6, 1e-5, -1e-5, 1e-4, -1e-4, 1e-3, -1e-3)}
    # how far the sublevel A <= A3+ reaches along the valley, each way (bisection on the rise)
    head, reach = A3 - A0, {}
    for sgn in (1, -1):
        lo, hi = 0.0, 4e-3
        for _ in range(40):
            mid = (lo + hi) / 2
            lo, hi = (mid, hi) if rise(sgn * mid) <= head else (lo, mid)
        reach[str(sgn)] = lo
    out["reach"] = reach
    return out


def grid_trap(v0, counts=(32, 64, 128)):
    """Cycle 03 sec. 14: minimize the hull area from angles on a coarse grid alone (no segment verified), then
    read the exact area where that minimum lies"""
    out = {}
    for N in counts:
        simplex = np.asarray(v0) + np.vstack([np.zeros(5), 1e-3 * np.eye(5)])
        res = minimize(lambda y: family_area(y, 5, N, verify=False), v0, method="Nelder-Mead",
                       options={"xatol": 1e-12, "fatol": 1e-16, "maxfev": 8000, "initial_simplex": simplex})
        out[str(N)] = {"grid_min": float(res.fun), "exact_there": float(family_area(res.x))}
    return out


def replacement():
    """Cycle 03 sec. 17: the family D, B3, B7 searched (differential evolution, then Nelder-Mead); its exact hull
    and the outer polygons of 1,000 and 10^6 supporting half-planes at the placement found"""
    box = [(-0.1, 0.1), (-0.1, 0.1), (0.0, 2 * math.pi / 7), (-0.1, 0.1), (-0.1, 0.1)]
    de = differential_evolution(lambda x: family_area(x, 7, 512), box, seed=20260927, popsize=20, maxiter=200, tol=1e-12, polish=False)
    res = minimize(lambda x: family_area(x, 7, 2048), de.x, method="Nelder-Mead", options={"xatol": 1e-11, "fatol": 1e-15, "maxfev": 6000})
    x = [float(a) for a in res.x]
    return {"placement": x, "area": family_area(x, 7), "outer_1000": outer_area(base_pieces(x, 7), 1000),
            "outer_1e6": outer_area(base_pieces(x, 7), 10 ** 6)}


def hausdorff_sample(v0, boxes=300, seed=44):
    """Cycle 02 sec. 4: the hull of a placement in a box against the hull at the box's centre, over random boxes
    around the seed - d_H over 2^16 directions, as a fraction of max(delta3, delta5)"""
    rng = np.random.default_rng(seed)
    th = 2 * np.pi * np.arange(1 << 16) / (1 << 16)
    worst = 0.0
    for _ in range(boxes):
        c = np.asarray(v0) + rng.normal(0, [0.02, 0.02, 0.05, 0.02, 0.02])
        hw = rng.uniform(0, [0.01, 0.01, 0.05, 0.01, 0.01]) * 10 ** rng.uniform(-3, 0)
        v = c + rng.uniform(-1, 1, 5) * hw
        tau = max(math.hypot(hw[0], hw[1]), math.hypot(hw[3], hw[4]) + 2 * rn(5) * math.sin(hw[2] / 2))
        worst = max(worst, float(np.max(np.abs(support(base_pieces(v))(th) - support(base_pieces(c))(th)))) / tau)
    return worst


def exclusion_sample(T, trials=60, seed=3):
    """Cycle 03 sec. 3-4: B_n placed just beyond T_n(T), at any turn, already spans more than T with the disc"""
    rng, least = np.random.default_rng(seed), {}
    for n in (3, 5):
        tb, worst = t_bound(n, T), math.inf
        for _ in range(trials):
            r, a, phi = tb + rng.uniform(1e-9, 0.05), rng.uniform(0, 2 * np.pi), rng.uniform(0, 2 * np.pi)
            worst = min(worst, hull_pieces(placed_disc() + placed_reuleaux(n, phi, (r * math.cos(a), r * math.sin(a))), 16384)[0] - T)
        least[str(n)] = worst
    return least


SEARCHES = {"landscape": (landscape, lambda v0: landscape(v0)), "sharpness": (sharpness, lambda v0: sharpness(v0)),
            "trap": (grid_trap, lambda v0: grid_trap(v0)), "replacement": (replacement, lambda v0: replacement()),
            "hausdorff": (hausdorff_sample, lambda v0: hausdorff_sample(v0)), "exclusion": (exclusion_sample, lambda v0: exclusion_sample(A3))}


def searches(v0):
    """each search cached under its own key, so a change to one leaves the others"""
    cached = json.loads(CACHE.read_text(encoding="utf-8")) if CACHE.exists() else {}
    out = {}
    for name, (fn, call) in SEARCHES.items():
        key = _key(fn)
        if cached.get(name, {}).get("key") != key:
            cached[name] = {"key": key, "value": call(v0)}
            CACHE.parent.mkdir(parents=True, exist_ok=True)
            CACHE.write_text(json.dumps(cached, indent=1) + "\n", encoding="utf-8")     # after each, so a later failure keeps it
        out[name] = cached[name]["value"]
    return out


def world(inputs):
    v0 = inputs["repository"]["reuleaux"]["placement"]
    paper = [-0.012158832, -0.000000037, 1.256661190, 0.022996607, -0.000003897]
    grids = {str(n): grid_margins(v0, n) for n in RANKED}
    return {**inputs, "v0": v0, "grids": grids, "grid_paper": min(grid_margins(paper, 7)),
            "areas": {"repository": family_area(v0), "paper": family_area(paper)}, "ceiling": ceiling_excess(v0), "search": searches(v0)}


# ---------------------------------------------------------------- checks

ANCHORS = {
    1: {"W1": [r"\boxed{(-0.0121588321,-3.71\times10^{-8},1.2566611904,0.0229966069,-3.90\times10^{-6}).}", "0.834780946.",
               r"M_U(K)=\min_{Q\inO(2)}\min_{t\in\mathbbR^2}\max_{u\inS^1}[h_K(Q^Tu)+t\cdotu-h_U(u)].", "$$M=2048$$supportdirections，",
               r"\min_\ellm_M(\phi_\ell)\approx0.00938298365.", r"\frac{\pi}{7\cdot256}\approx0.00175312090.", r"M_{U_0}(B_7)\gtrsim0.00762986275>0.",
               r"R_K\le1.", r"0.834781191-0.8344=0.000381191", "|$B_7$|$0.00938$|", "|$B_{41}$|$0.00037$|"],
        "X1": [r"\boxed{0.836494901.}"]},
    2: {"X1": [r"\mathcalD=[-0.70,0.70]^2\times[0,2\pi/5]\times[-0.70,0.70]^2.", "$$486{,}799{,}600$$nodes，", "$$245{,}496{,}952$$leaves。",
               r"(t_3,\rho,t_5)\in\mathbbR^2\times[0,2\pi/5)\times\mathbbR^2.", r"\delta_5(\mathcalB)=\sqrt{h_{5x}^2+h_{5y}^2}+2R_5\sin\frac{h_\rho}{2},",
               "R_5=0.525731112119.", "commit`da956b117a`"],
        "W2": [r"\tau(\mathcalB)=\max\{\delta_3(\mathcalB),\delta_5(\mathcalB)\}.", r"d_H(\operatorname{conv}A,\operatorname{conv}B)\led_H(A,B).",
               r"\Lambda(\mathcalF_3)\leA_3^+:=0.834781191.", r"S_{\mathcalF}(\mathcalB)=\min_{U\in\mathfrakM(\mathcalF)}\max_{K\in\mathcalB}M_U(K).",
               "0.836494901.", "0.834780947.", r"\boxed{0.001713954.}"]},
    3: {"W3": [r"\Phi_r(d)=\pir^2+r\sqrt{d^2-r^2}-r^2\arccos\fracrd.", r"d_\star\approx0.694929333199893.", r"R_n=\frac1{2\sin(\pi(n-1)/(2n))}.",
               r"g_n(s)=\sqrt{R_n^2+s^2+2R_ns\cos(\pi/n)}.", r"|t_3|\leT_3\approx0.193949748872303.", r"|t_5|\leT_5\approx0.197117585445617.",
               r"\boxed{164.272\times.}", "`DOMAIN-STRENGTHENING`"],
        "W4": [r"s_7\approx0.00938484.", "`NUMERICAL-EVIDENCE``CERTIFICATE-SCHEMA-READY`尚未升格`PROVED`"],
        "W5": [r"2.45\times10^{-7}.", "`hull_area_exact`", "`IMPLEMENTATION-TRAP/REJECTED-ROUTE`", r"\|v-v_0\|\le\frac{2(A_3^+-A(v_0))}{c}."],
        "W6": [r"\minA(D,B_3,B_7)\approx0.830638626.", r"A_{\mathrm{outer},1000}\approx0.830957521.", "`STRONGSEARCHREJECTION`"],
        "X1": [r"8.6\times10^{11}", "$$880$$days。"]},
}

CLAIMS = {
    "paper_claim": {"missing": [], "forest_roots": 4194304, "seed_roots": 4194304, "remark20": [True, True], "remark20_factor": 169,
                    "remark34_boxes": [25425568, 27350260], "f070": True},
    "separator_claim": {"placement_as_shown": True, "areas": {"repository": 0.834780945912, "paper": 0.83478094594},
                        "grid": {"min": 0.009382983648263432, "at": 193, "loss": 0.0017531209004407328, "lower": 0.007629862747822699,
                                 "paper_placement": 0.00938298364328},
                        "ranking": {7: 0.009383, 9: 0.00517, 11: 0.004727, 13: 0.003512, 15: 0.002646, 17: 0.002138, 19: 0.001713, 21: 0.001402,
                                    25: 0.0009883, 31: 0.0006423, 41: 0.0003669},
                        "table_within_one_unit": {n: True for n in RANKED}, "decreasing": True, "loss_with_R7": 0.0008991},
    "atlas_claim": {"R5": "0.525731112119", "hausdorff_worst": 0.92, "box_holds_the_sublevel": True, "difference": "0.001713954",
                    "four_body_search": 0.8364914416,
                    "ceiling": {"uniform_1e6": 2.45e-07, "repository_1e6": 2.45e-07, "handovers": 17, "uniform_1e4": 3.42e-06, "with_handovers_1e4": 1.2e-08}},
    "margin_claim": {"minima": [[6.2e-05, 0.01208567841], [0.220843, 0.009385623167], [0.449237, 0.01267971752], [0.676813, 0.009384687909]],
                     "converged": True, "deep_basins": 2, "slack": 0.000112, "within_slack": [63, 16], "s7": 0.009384687909, "cycle03_minus_s7": 1.52e-07,
                     "cycle01_grid_below": True},
    "sharpness_claim": {"headroom": 2.451e-07, "negative": [0, 0], "least": [0.00841, 0.00839, 1.12e-05], "radius": 0.044,
                        "valley": {"turn_share": 0.987, "slopes": [1.1e-05, 6.9e-05], "reach": [0.00099, 0.00078], "reach_along_axes_at_most": 2.9e-05},
                        "trap": {N: {"grid_min": 0.8347809459, "exact_there": 0.8347809459, "false_low": False} for N in ("32", "64", "128")}},
    "domain_claim": {"at_A3": [0.694929333199893, 0.193949748872303, 0.197117585445617], "text_agrees": [True, True, True], "factor": 164.271784679,
                     "at_08344": [True, True, True], "exclusion_least_excess": {"3": 0.0905, "5": 0.134}},
    "replacement_claim": {"area": 0.8305410847, "outer_1000": 0.8309188653, "outer_1e6": 0.8305414988, "vs_text": -9.8e-05, "below_seed": True},
    "crystal_claim": {"C01": [True, True, True, True], "C02": [True, True], "C03_domain_ulps": [1, 0, 4], "C03_factor": 164.271784679,
                      "C03_replacement": [9.8e-05, 3.9e-05]},
    "code_facts": {"lines": {1: 141, 2: 175, 3: 66},
                   "cycle01": {"repository_placement": True, "directions": True, "loss": True, "prints": ["B7"]},
                   "cycle02": {"split_weights": True, "inflate": True, "injected": True, "root": True},
                   "cycle03": {"bisection": True, "imports": [("math", "")], "says_it_imports_geom": True}},
}


def sig(x, n=4):
    return float(f"{x:.{n - 1}e}")


def a0_anchors(w):
    out = []
    for i, groups in ANCHORS.items():
        text = gate.squash(w["texts"][i])
        out += [f"Cycle {i:02d} {cid}: anchor not found: {a[:50]}" for cid, frags in groups.items() for a in frags if a not in text]
    return out


def x1_paper(w):
    """what the cycles take from Mishra, in his full text (v2): the gauge, the confining box and f(0.70), the
    emitting run's forest (its roots are the repository's 2^22 seeds), the erosion lemma and R5, the fourth
    body and the eight-dimensional cost - and Remarks 20 and 34, where the farthest-corner domain of Cycle 03
    already stands, with its volume factor and the remark that it saves no boxes"""
    f = w["snapshot"]["facts"]
    num = lambda k: [int(x.replace(",", "")) for x in re.findall(r"\d{1,3}(?:,\d{3})+", f.get(k) or "")]
    run, cost = num("emitting_run"), num("remark34")
    t20 = [float(x) for x in re.findall(r"≤ (0\.\d+)", f.get("remark20") or "")]
    got = {"missing": sorted(k for k in MISHRA_FACTS if not f.get(k)),
           "forest_roots": 2 * run[1] - run[0] if len(run) == 2 else None, "seed_roots": 2 ** w["seed_depth"],
           "remark20": [abs(t20[0] - t_bound(3, 0.8344)) < 5e-7, abs(t20[1] - t_bound(5, 0.8344)) < 5e-7] if len(t20) == 2 else None,
           "remark20_factor": round(1.4 ** 4 / (16 * t_bound(3, 0.8344) ** 2 * t_bound(5, 0.8344) ** 2)),
           "remark34_boxes": cost, "f070": phi_text(0.5, 0.70) > 0.836548794 > A3}
    w["x1"] = got
    return [] if not got["missing"] and got["forest_roots"] == got["seed_roots"] and got == w["paper_claim"] else [f"Mishra's text: {got}"]


def w1_separator(w):
    """Cycle 01: U0 is the repository's placement (its exact hull 0.834780946); the LP over 2048 directions at 256
    orientations per period gives the recorded minimum to the last digit, with the loss pi/(7 P) from R_K <= 1;
    the ranking table against the same LP for every n; the headroom 0.000381191"""
    t1, v0 = gate.squash(w["texts"][1]), w["v0"]
    shown = [-0.0121588321, -3.71e-8, 1.2566611904, 0.0229966069, -3.90e-6]
    table = {int(n): float(x) for n, x in re.findall(r"\|\$B_\{?(\d+)\}?\$\|\$([0-9.]+)\$\|", t1)}
    g7 = w["grids"]["7"]
    got = {"placement_as_shown": all(abs(a - b) <= tol for a, b, tol in zip(v0, shown, (5e-11, 5e-11, 5e-11, 5e-11, 5e-9))),
           "areas": {k: sig(a, 12) for k, a in w["areas"].items()},
           "grid": {"min": min(g7), "at": int(np.argmin(g7)), "loss": math.pi / (7 * 256), "lower": min(g7) - math.pi / (7 * 256),
                    "paper_placement": sig(w["grid_paper"], 12)},
           "ranking": {n: sig(min(w["grids"][str(n)]), 4) for n in RANKED},
           "table_within_one_unit": {n: abs(min(w["grids"][str(n)]) - x) <= 1.01e-5 for n, x in table.items()},
           "decreasing": all(min(w["grids"][str(a)]) > min(w["grids"][str(b)]) for a, b in zip(RANKED, RANKED[1:])),
           "loss_with_R7": sig(rn(7) * math.pi / (7 * 256), 4)}
    w["w1"] = got
    return [] if got["placement_as_shown"] and all(got["table_within_one_unit"].values()) and got == w["separator_claim"] else [f"Cycle 01: {got}"]


def w2_atlas(w):
    """Cycle 02: R5 from the pentagon; the hull Hausdorff radius tau(B) holds on random boxes around the seed;
    Mishra's box confines the whole A3+-sublevel, since f(0.70) > A3+; the two optima it subtracts, and this
    tree's four-body search (RUN-010), which goes below the second"""
    c = w["ceiling"]
    got = {"R5": f"{rn(5):.12f}", "hausdorff_worst": round(w["search"]["hausdorff"], 3), "box_holds_the_sublevel": phi_text(0.5, 0.70) > A3,
           "difference": str(round(0.836494901 - 0.834780947, 9)), "four_body_search": sig(w["four_body_search"], 10),
           "ceiling": {"uniform_1e6": sig(c["uniform_1e6"], 4), "repository_1e6": sig(w["repository"]["reuleaux"]["outer_1e6"] - w["areas"]["repository"], 4),
                       "handovers": c["handovers"], "uniform_1e4": sig(c["uniform_1e4"], 3), "with_handovers_1e4": sig(c["with_handovers_1e4"], 2)}}
    w["w2"] = got
    return [] if got["hausdorff_worst"] <= 1 and got == w["atlas_claim"] else [f"Cycle 02: {got}"]


def w3_domain(w):
    """Cycle 03 sec. 2-4: d*, T3, T5 and the volume factor at A3+, against the text; the same at 0.8344 are
    Remark 20's and the repository's domain log; B3, B5 just beyond T_n already span more than A3+"""
    t3 = gate.squash(w["texts"][3])
    rep = w["repository"]
    num = lambda pat: float(re.search(pat, t3).group(1))
    text = [num(r"d_\\star\\approx([0-9.]+[0-9])"), num(r"T_3\\approx([0-9.]+[0-9])"), num(r"T_5\\approx([0-9.]+[0-9])")]
    mine = [d_star(A3), t_bound(3, A3), t_bound(5, A3)]
    got = {"at_A3": [sig(x, 15) for x in mine], "text_agrees": [abs(a - b) < 2e-15 for a, b in zip(mine, text)],
           "factor": sig(1.4 ** 4 / (16 * mine[1] ** 2 * mine[2] ** 2), 12),
           "at_08344": [abs(d_star(0.8344) - rep["d_star_08344"]) < 1e-12] + [abs(t_bound(n, 0.8344) - b) < 1e-12 for n, b in zip((3, 5), rep["t_bounds_08344"])],
           "exclusion_least_excess": {n: sig(x, 3) for n, x in w["search"]["exclusion"].items()}}
    w["w3"] = got
    return [] if all(got["text_agrees"]) and all(got["at_08344"]) and min(got["exclusion_least_excess"].values()) > 0 \
        and got == w["domain_claim"] else [f"Cycle 03's domain: {got}"]


def w4_margin(w):
    """Cycle 03 sec. 6: s7 = M_U0(B7), the inner problem solved to agreement of its two bounds, minimized over
    every basin of orientation; the cycle's candidate and Cycle 01's grid value beside it"""
    L = w["search"]["landscape"]
    best = min(L["minima"], key=lambda m: m["up"])
    cand = w["crystals"][3]["numerical_evidence"]["representative_B7_margin_candidate"]
    deep = [m["grid"] for m in L["minima"] if m["up"] < best["up"] + 1e-5]
    cyc = lambda i, j: min(abs(i - j), 2048 - abs(i - j))
    reach = max((min(cyc(i, j) for j in deep) for i in L["within_slack"]), default=0)
    got = {"minima": [[round(m["phi"], 6), sig(m["up"], 10)] for m in sorted(L["minima"], key=lambda m: m["phi"])],
           "converged": all(m["up"] - m["low"] < 1e-12 for m in L["minima"]), "deep_basins": len(deep),
           "slack": sig(L["slack"], 3), "within_slack": [len(L["within_slack"]), reach],
           "s7": sig(best["up"], 10), "cycle03_minus_s7": sig(cand - best["up"], 3), "cycle01_grid_below": min(w["grids"]["7"]) < best["up"]}
    w["w4"] = got
    return [] if got["converged"] and reach <= 64 and got == w["margin_claim"] else [f"Cycle 03's margin: {got}"]


def w5_sharpness(w):
    """Cycle 03 sec. 13-16 and 14: every sampled direction out of the seed raises the exact area, at both step
    lengths; the least slope, minimized; the radius sec. 16 would give with it; coarse angle grids alone
    report areas below the minimum that the exact hull at the same placement does not have"""
    S, T = w["search"]["sharpness"], w["search"]["trap"]
    head = A3 - S["A0"]
    axes = min(S["1e-06"]["least"], S["1e-05"]["least"])
    got = {"headroom": sig(head, 4), "negative": [S["1e-05"]["negative"], S["1e-06"]["negative"]],
           "least": [sig(S["1e-05"]["least"], 3), sig(S["1e-06"]["least"], 3), sig(S["least_minimized"], 3)],
           "radius": sig(2 * head / S["least_minimized"], 2),
           "valley": {"turn_share": sig(abs(S["direction"][2]), 3), "slopes": [sig(S["profile"]["+1e-06"] / 1e-6, 2), sig(S["profile"]["-1e-06"] / 1e-6, 2)],
                      "reach": [sig(S["reach"]["1"], 2), sig(S["reach"]["-1"], 2)], "reach_along_axes_at_most": sig(head / axes, 2)},
           "trap": {N: {"grid_min": sig(t["grid_min"], 10), "exact_there": sig(t["exact_there"], 10),
                        "false_low": bool(t["grid_min"] < S["A0"] < t["exact_there"])} for N, t in T.items()}}
    w["w5"] = got
    return [] if not any(got["negative"]) and got == w["sharpness_claim"] else [f"Cycle 03's sharpness: {got}"]


def w6_replacement(w):
    """Cycle 03 sec. 17: the family D, B3, B7 goes far below 0.8344 - its searched minimum, and the outer
    polygons of 1,000 and 10^6 half-planes, which bound the family's minimum from above"""
    R = w["search"]["replacement"]
    got = {"area": sig(R["area"], 10), "outer_1000": sig(R["outer_1000"], 10), "outer_1e6": sig(R["outer_1e6"], 10),
           "vs_text": sig(R["area"] - 0.830638626, 2), "below_seed": R["outer_1e6"] < 0.8344}
    w["w6"] = got
    return [] if got["below_seed"] and got == w["replacement_claim"] else [f"Cycle 03's replacement family: {got}"]


def w7_crystals(w):
    """the three state crystals against the numbers rebuilt here"""
    c1, c2, c3 = (w["crystals"][i] for i in (1, 2, 3))
    s1, dom, ev = c1["representative_search"], c3["sharp_root_domain"], c3["numerical_evidence"]
    g7 = w["grids"]["7"]
    R = w["search"]["replacement"]
    got = {"C01": [s1["B7_grid_min"] == min(g7), s1["B7_orientation_loss_conservative"] == math.pi / (7 * 256),
                   s1["B7_structural_lower_before_fp_error"] == min(g7) - math.pi / (7 * 256),
                   repr(c1["master_gap_public"]) == str(round(0.8440935944 - 0.8344, 10))],
           "C02": [c2["family_ceiling"] == A3, c2["family"] == ["D", "B3", "B5"]],
           "C03_domain_ulps": [round(abs(dom["d_star"] - d_star(A3)) / math.ulp(d_star(A3))), round(abs(dom["tmax_B3"] - t_bound(3, A3)) / math.ulp(t_bound(3, A3))),
                               round(abs(dom["tmax_B5"] - t_bound(5, A3)) / math.ulp(t_bound(5, A3)))],
           "C03_factor": sig(dom["translation_square_4volume_shrink_vs_0.70"], 12),
           "C03_replacement": [sig(ev["replacement_family_D_B3_B7_exact_envelope_search_candidate"] - R["area"], 2),
                               sig(ev["replacement_family_D_B3_B7_outer_1000_candidate"] - R["outer_1000"], 2)]}
    w["w7"] = got
    return [] if all(got["C01"]) and all(got["C02"]) and got == w["crystal_claim"] else [f"the crystals: {got}"]


def w8_code(w):
    """the three scripts, read after the rebuild and never run"""
    sq = {i: gate.squash(t) for i, t in w["code"].items()}
    got = {"lines": {i: t.count("\n") for i, t in w["code"].items()},
           "cycle01": {"repository_placement": "-1.215883209899e-02" in sq[1] and "1.256661190387e+00" in sq[1],
                       "directions": "np.linspace(0.0,TAU,support_dirs,endpoint=False)" in sq[1], "loss": "radius_bound*period/(2.0*orientations)" in sq[1],
                       "prints": re.findall(r'"(B\d+)":orientation_grid_lower', sq[1])},
           "cycle02": {"split_weights": "R5*self.hrho" in sq[2], "inflate": "EPS_SPLIT=1e-11" in sq[2],
                       "injected": "beta_lower:Callable" in sq[2] and "margin_lower_center:Callable" in sq[2], "root": "h3x=0.70" in sq[2]},
           "cycle03": {"bisection": "for_inrange(220):" in sq[3], "imports": re.findall(r"^import (\w+)|^from (\w+)", w["code"][3], re.M),
                       "says_it_imports_geom": "importthepublished`geom.py`" in sq[3]}}
    w["w8"] = got
    return [] if got == w["code_facts"] else [f"the scripts: {got}"]


def record_of(b):
    t = b.decode("utf-8")
    return {"sha256": hashlib.sha256(b).hexdigest(), "bytes": len(b), "lines": len(t.split("\n")),
            "controls": sum(1 for ch in t if ord(ch) < 32 and ch not in "\t\n\r"),
            "delimiters": t.count("$$") % 2 == 0 and t.replace("$$", "").count("$") % 2 == 0 and not re.search(r"\\\[|\\\]|\\\(|\\\)", t)}


def p1_package(w):
    """each VALIDATION's record of the document, the script and the crystal, against their bytes hashed here and
    the archive's manifest rows"""
    out = []
    for i, v in w["validations"].items():
        doc = v["canonical_source"]
        code = v.get("python_file") or v.get("python")
        mine = record_of(w["files"][doc["file"]])
        controls = doc.get("hidden_ascii_controls", doc.get("hidden_ascii_control_count"))
        if (doc["sha256"], doc["bytes"], doc["lines"], controls, doc["canonical_math_delimiters"], doc["utf8"]) != \
                (mine["sha256"], mine["bytes"], mine["lines"], mine["controls"], mine["delimiters"], True) or v["status"] != "PASS":
            out.append(f"Cycle {i:02d}: VALIDATION's record of the document")
        for rec in (code, v["state"]):
            b = w["files"][rec["file"]]
            if rec["sha256"] != hashlib.sha256(b).hexdigest() or w["manifest_rows"][rec["file"]][2] != rec["sha256"]:
                out.append(f"Cycle {i:02d}: VALIDATION's digest of {rec['file']}")
    w["p1"] = {i: record_of(w["files"][v["canonical_source"]["file"]]) for i, v in w["validations"].items()}
    return out


CHECKS = {"A0": a0_anchors, "X1": x1_paper, "W1": w1_separator, "W2": w2_atlas, "W3": w3_domain, "W4": w4_margin, "W5": w5_sharpness,
          "W6": w6_replacement, "W7": w7_crystals, "W8": w8_code, "P1": p1_package}
DEPENDS = {"A0": {"texts"}, "X1": {"snapshot", "seed_depth", "paper_claim"},
           "W1": {"texts", "v0", "grids", "grid_paper", "areas", "separator_claim"},
           "W2": {"search", "four_body_search", "ceiling", "repository", "areas", "atlas_claim"}, "W3": {"texts", "repository", "search", "domain_claim"},
           "W4": {"search", "crystals", "grids", "margin_claim"}, "W5": {"search", "sharpness_claim"}, "W6": {"search", "replacement_claim"},
           "W7": {"crystals", "grids", "search", "crystal_claim"}, "W8": {"code", "code_facts"}, "P1": {"validations", "files", "manifest_rows"}}


def drill_cases(base):
    def edit(obj, fn):
        x = copy.deepcopy(obj)
        fn(x)
        return x

    texts, s = base["texts"], base["search"]
    crlf = {i: t.replace("\n", "\r\n") for i, t in texts.items()}
    return [
        ("K0-unmodified", "control", {}, set()),
        ("K1-crlf", "control", {"texts": crlf, "code": {i: t.replace("\n", "\r\n") for i, t in base["code"].items()}}, set()),
        ("K2-validation-keys-sorted", "control", {"validations": {i: json.loads(json.dumps(v, sort_keys=True)) for i, v in base["validations"].items()}}, set()),
        ("M1-orientation-loss", "mutation", {"texts": {**texts, 1: texts[1].replace(r"0.00175312090", r"0.00175312091")}}, {"A0"}),
        ("M2-snapshot-remark20", "mutation", {"snapshot": edit(base["snapshot"], lambda x: x["facts"].update(remark20=None))}, {"X1"}),
        ("M3-seed-depth", "mutation", {"seed_depth": 21}, {"X1"}),
        ("M4-grid-value", "mutation", {"grids": {**base["grids"], "7": [x + 1e-12 for x in base["grids"]["7"]]}}, {"W1", "W7"}),
        ("M5-ranking-row", "mutation", {"texts": {**texts, 1: texts[1].replace("| $B_9$ | $0.00517$ |", "| $B_9$ | $0.00527$ |")}}, {"W1"}),
        ("M6-hausdorff", "mutation", {"search": edit(s, lambda x: x.update(hausdorff=1.02))}, {"W2"}),
        ("M6b-ceiling-handovers", "mutation", {"ceiling": {**base["ceiling"], "handovers": 16}}, {"W2"}),
        ("M7-domain-text", "mutation", {"texts": {**texts, 3: texts[3].replace("0.193949748872303", "0.193949748872313")}}, {"A0", "W3"}),
        ("M8-exclusion", "mutation", {"search": edit(s, lambda x: x["exclusion"].update({"3": -1e-6}))}, {"W3"}),
        ("M9-margin-far-point", "mutation", {"search": edit(s, lambda x: x["landscape"]["within_slack"].append(1024))}, {"W4"}),
        ("M10-negative-slope", "mutation", {"search": edit(s, lambda x: x["sharpness"]["1e-06"].update(negative=1))}, {"W5"}),
        ("M11-replacement-area", "mutation", {"search": edit(s, lambda x: x["replacement"].update(area=x["replacement"]["area"] + 1e-6))}, {"W6", "W7"}),
        ("M12-crystal-loss", "mutation", {"crystals": edit(base["crystals"], lambda x: x[1]["representative_search"].update(B7_orientation_loss_conservative=0.00175))},
         {"W7"}),
        ("M13-script-directions", "mutation", {"code": {**base["code"], 1: base["code"][1].replace("endpoint=False)\n    hcover", "endpoint=True)\n    hcover")}},
         {"W8"}),
        ("M14-validation-digest", "mutation", {"validations": edit(base["validations"], lambda x: x[2]["canonical_source"].update(sha256="0" * 64))}, {"P1"}),
        ("M15-crystal-bytes", "mutation", {"files": {**base["files"], CRYSTALS[3].split("!/")[-1]: base["files"][CRYSTALS[3].split("!/")[-1]] + b" "}}, {"P1"}),
    ]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--refresh", action="store_true")
    ap.add_argument("--drill", action="store_true")
    ap.add_argument("--blind", metavar="CID")
    args = ap.parse_args()
    if args.refresh:
        snap = {"retrieved": datetime.date.today().isoformat(), **gate.fetch_arxiv_facts(*MISHRA, MISHRA_FACTS, strip_invisible=True)}
        SNAPSHOT.write_text(json.dumps(snap, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
    base = world({**load_inputs(), "snapshot": json.loads(SNAPSHOT.read_text(encoding="utf-8"))})

    def build():
        return {**copy.deepcopy(base), **copy.deepcopy(CLAIMS)}

    if args.blind:
        CHECKS[args.blind] = lambda w: []
        args.drill = True
    w = build()
    results = {}
    for c, fn in CHECKS.items():
        try:
            results[c] = fn(w)
        except KeyError as e:
            results[c] = [f"claim missing: {e}"]
    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 ("x1", "w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "p1"):
        print(key, "=", json.dumps(w.get(key), default=str, ensure_ascii=False))
    if not args.drill:
        return
    cases = drill_cases(base)
    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-044", "subject": "UESFCM Cycles 01-03: the B7 separator gate, the minimizer atlas and exact exchange, orbit localization",
           "documents": list(DOCS.values()), "checks": {c: {"pass": not f, "failures": f} for c, f in results.items()},
           **{k: w.get(k) for k in ("x1", "w1", "w2", "w3", "w4", "w5", "w6", "w7", "w8", "p1")}, "drill": summary}
    LOG.write_text(json.dumps(log, ensure_ascii=False, indent=1, default=str) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
