"""RUN-067 - BCODR LUC 05: the balanced overlap germ taxonomy, root 127 against root 131.

BCODR-LUC-05 (2026-09-21) classifies LUC 03's two balanced germs. 127 is face-constrained (FCBG: rank 2, a three-
dimensional critical tangent space, LUC 04). 131 is an interior midpoint (IMBG): its meeting point is the midpoint of the
nearest ray/155 pair (rho* = 0.00254068891729192, T* = 0.0473333498919449), by a midpoint theorem; no face is active,
g- = -g+, the rank is 1 and the critical space four-dimensional; with H- = diag(1, 0, 1, 0, 1) and the Schur-complement
H+, kappa_131 = 0.454649807778291 against LUC 04's kappa_127 = 0.45429481027797 - "they differ by less than one tenth of
one percent" (ratio 1.00078142539226), "different first-order class, same second-order isolation outcome" - with
radius costs 4.80263713445372 and 1.78921498757354 and tangent extents 0.456310132719225 and 0.747599042164318; and a
rule: kappa_germ > 0 isolated, = 0 flat, < 0 unstable. Here 131's germ is rebuilt at 50 digits like 127's in RUN-066,
the growth is measured on slices, and 127's numbers are RUN-066's.

Checks
  A0 anchors       the statements below occur in the document as written
  W1 midpoint      sec. 2-5: the nearest pair, T*, the midpoint inside 131, and that the pair is the nearest of all
  W2 first order   sec. 6-8, 10: g- = -g+, rank 1, dimension 4, the active pattern of 155
  W3 stiffness     sec. 9, 11-12, 15-19: the straight-line kappa_131, its direction, C_R and C_H
  W4 growth        the Lagrangian form at alpha = 1/2 and the slices: here the straight-line constant is the right one
  W5 comparison    sec. 13-14, 23, 27: kappa_131 / kappa_127 as printed, and the ratio of the overlaps' own constants
  W6 rule          sec. 9, 20-22: what the sign of kappa_germ can and cannot decide
  W7 records       the result record and the state against each other and the rebuild
  W8 verifier      the verifier, read after this rebuild and never run
  P1 package       the VALIDATION record against the bytes and the archive

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

import mpmath as mp

import gate
import run048_uesfcm_cycles_12_14 as r48
import run064_bcodr_luc02 as r64
import run065_bcodr_luc03 as r65
import run066_bcodr_luc04 as r66
from corpus import SOURCES, TREE, source_bytes, walk_sources

PKG = "main.zip!/BCODR/BCODR_LUC_05_Package_v0.1.zip!/"
DOC = PKG + "BCODR_LUC_05_Balanced_Overlap_Germ_Taxonomy_v0.1.md"
RESULT = PKG + "BCODR_LUC_05_Germ_Taxonomy_Result_v0.1.json"
PLOT = PKG + "BCODR_LUC_05_Germ_Stiffness_Comparison.png"
VERIFIER = PKG + "BCODR_LUC_05_Verify_Germ_Taxonomy.py"
STATE = PKG + "BCODR_LUC_05_STATE_v0.1.json"
VALIDATION = PKG + "BCODR_LUC_05_VALIDATION.json"
LOG = TREE / "data" / "gate-logs" / "run067-bcodr-luc05.json"
LOG65 = TREE / "data" / "gate-logs" / "run065-bcodr-luc03.json"
MANIFEST = TREE / "data" / "SOURCE_MANIFEST.v1.json"
CACHE = TREE / "data" / "cache" / "run067-searches.json"     # data/cache is not committed
DPS = 50
SLICES = ("1e-3", "3e-4", "1e-4")


def load_inputs():
    blobs = {n: source_bytes(n) for n in SOURCES}
    want = (DOC, RESULT, PLOT, VERIFIER, STATE, VALIDATION)
    got = {leaf.id: d for leaf, d in walk_sources(blobs, keep=lambda l: l.id in want) if d is not None}
    manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))["leaves"]
    c11 = r48.load_inputs()
    return {"text": got[DOC].decode("utf-8"), "result": json.loads(got[RESULT]), "verifier": got[VERIFIER].decode("utf-8"), "state": json.loads(got[STATE]),
            "validation": json.loads(got[VALIDATION]), "bytes": {k: got[k] for k in want}, "manifest_rows": {r[0]: r for r in manifest if r[0] in want},
            "luc_files": sorted({m.group(1) for r in manifest for m in [re.search(r"BCODR_LUC_(\d\d)_", r[0])] if m}), "subroots": c11["subroots"],
            "root": c11["root"], "log65": json.loads(LOG65.read_text(encoding="utf-8"))}


# ---------------------------------------------------------------- 131's germ, rebuilt

def germ131(sub, root):
    """the nearest pair of the ray (0 <= rho <= 0.003) and box 155, from the stationarity of its squared distance; the
    midpoint and its margins in 131; g+-; the ray's distance to every prune box; D+, H+-, an orthonormal basis of g+'s
    complement, Q+-; the straight-line kappa and its direction; the Lagrangian form at alpha = 1/2; C_R and C_H"""
    s = lambda x: mp.nstr(x, 30)
    with mp.workdps(DPS):
        g, lo, hi, ql, qh = r66.frame(sub, root)
        lo, hi = r65.nbox(g, 131)

        def pair(r):
            p = r65.ray_n(g, r)
            q = [min(max(p[k], ql[k]), qh[k]) for k in range(5)]
            return sum((p[k] - q[k]) ** 2 for k in range(5)), p, q
        rs = mp.findroot(lambda r: mp.diff(lambda x: pair(x)[0], r), mp.mpf("0.00254068887"))
        d2, p, q = pair(rs)
        T = mp.sqrt(d2) / 2
        z = [(p[k] + q[k]) / 2 for k in range(5)]
        gp, gm = [z[k] - p[k] for k in range(5)], [z[k] - q[k] for k in range(5)]
        W = [2 * mp.mpf(root[1][k]) for k in range(5)]
        S, U, V = mp.mpf(r64.S), mp.mpf(r64.U), mp.mpf(r64.V)
        dp = [S * U * mp.sin(rs * U) / W[0], S * U * mp.cos(rs * U) / W[1], 1 / W[2], mp.mpf(0), V / W[4]]
        ddp = [S * U ** 2 * mp.cos(rs * U) / W[0], -S * U ** 2 * mp.sin(rs * U) / W[1], mp.mpf(0), mp.mpf(0), mp.mpf(0)]
        Dp = sum(x * x for x in dp) - sum(gp[k] * ddp[k] for k in range(5))
        Hp = mp.matrix(5, 5)
        for i in range(5):
            for j in range(5):
                Hp[i, j] = (1 if i == j else 0) - dp[i] * dp[j] / Dp
        Hm = mp.diag([1, 0, 1, 0, 1])
        n = mp.matrix(gp) / mp.norm(mp.matrix(gp))
        cols = []
        for e in ([0, 1, 0, 0, 0], [0, 0, 0, 1, 0], [1, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1]):
            v = mp.matrix(e) - (n.T * mp.matrix(e))[0] * n
            for c in cols:
                v = v - (c.T * v)[0] * c
            if mp.norm(v) > mp.mpf("1e-20") and len(cols) < 4:
                cols.append(v / mp.norm(v))
        B = mp.matrix(5, 4)
        for j, c in enumerate(cols):
            for i in range(5):
                B[i, j] = c[i]
        Qp, Qm = B.T * Hp * B, B.T * Hm * B
        qg = (mp.sqrt(5) - 1) / 2
        f, t = r65.golden_max(lambda x: min(mp.eigsy(x * Qp + (1 - x) * Qm)[0]), mp.mpf(0), mp.mpf(1), qg, 160)
        E, Qv = mp.eigsy(t * Qp + (1 - t) * Qm)
        k0 = min(range(4), key=lambda i: E[i])
        vs = B * Qv[:, k0]
        vs = vs * (1 if vs[1] < 0 else -1)
        QL = (Qp + Qm) / 2
        EL = sorted(mp.eigsy(QL)[0])
        QLi = QL ** -1
        ray_to = {str(j): s(r64.t_plus(g["LO"][j], g["HI"][j], g)[0]) for j in r64.PRUNE}
        return {"r": s(rs), "T": s(T), "z": [s(x) for x in z], "margins": [s(min(z[k] - lo[k], hi[k] - z[k])) for k in range(5)],
                "outside_155": [k for k in range(5) if not (ql[k] <= p[k] <= qh[k])], "g_sum": s(max(abs(gp[k] + gm[k]) for k in range(5))),
                "gp_dot_dp": s(sum(gp[k] * dp[k] for k in range(5))), "rank": int(sum(1 for x in mp.svd_r(mp.matrix([gp, gm]), compute_uv=False) if x > mp.mpf("1e-40"))),
                "D_plus": s(Dp), "eig_Q_plus": [s(x) for x in sorted(mp.eigsy(Qp)[0])], "eig_Q_minus": [s(x) for x in sorted(mp.eigsy(Qm)[0])],
                "kappa_line": s(f), "t_line": s(t), "v_soft": [s(x) for x in vs], "lagrangian": [s(x) for x in EL],
                "predicted": {"x5": s(1 / QLi[1, 1]), "y3": s(1 / QLi[0, 0])}, "ray_to": ray_to}


def slices131(sub, root, gm):
    """the least max(d+, d-) over 131's box with x5 (then y3) pinned at z* + h; (T^2 - T*^2) / h^2"""
    out = {}
    with mp.workdps(DPS):
        g, lo, hi, ql, qh = r66.frame(sub, root)
        lo, hi = r65.nbox(g, 131)
        z, rs, T2 = [mp.mpf(x) for x in gm["z"]], mp.mpf(gm["r"]), mp.mpf(gm["T"]) ** 2
        qg = (mp.sqrt(5) - 1) / 2
        for k, name in ((3, "x5"), (1, "y3")):
            out[name] = {}
            for h in SLICES:
                l2, h2 = list(lo), list(hi)
                l2[k] = h2[k] = z[k] + mp.mpf(h)
                at = lambda r: -r65.at_point(r65.ray_n(g, r), l2, h2, ql, qh, qg, 120, mp.mpf(1))[0]
                v, r = r65.golden_max(at, rs - mp.mpf("4e-5"), rs + mp.mpf("4e-5"), qg, 120)
                out[name][h] = mp.nstr((-v - T2) / mp.mpf(h) ** 2, 20)
    return out


def critical_weight(g127):
    """for 127's own Q+-, the KKT weight above which alpha Q+ + (1 - alpha) Q- stops being positive definite"""
    with mp.workdps(DPS):
        Qp = mp.matrix([[mp.mpf(x) for x in row] for row in g127["Q_plus"]])
        Qm = mp.matrix([[mp.mpf(x) for x in row] for row in g127["Q_minus"]])
        lm = lambda a: min(mp.eigsy(a * Qp + (1 - a) * Qm)[0])
        ac = mp.findroot(lm, (mp.mpf("0.99"), mp.mpf("0.99999")), solver="bisect")
        return {"alpha_c": mp.nstr(ac, 20), "at_1": mp.nstr(lm(mp.mpf(1)), 12), "at_alpha": mp.nstr(lm(mp.mpf(g127["alpha"])), 12)}


def _key(fn, extra=""):
    digest = hashlib.sha256(inspect.getsource(fn).encode())
    for helper in (r66.frame, r66.germ, r66.reduced, r65.nbox, r65.ray_n, r65.phi, r65.golden_max, r65.at_point, r64.grid_boxes, r64.ray_units, r64.t_plus):
        digest.update(inspect.getsource(helper).encode())
    digest.update(f"{DPS} {SLICES} {r64.X30} {r64.S} {r64.X5} {r64.U} {r64.V}".encode())
    digest.update(extra.encode())
    return digest.hexdigest()


def searches(inputs):
    cached = json.loads(CACHE.read_text(encoding="utf-8")) if CACHE.exists() else {}
    out = {}
    sub, root = inputs["subroots"], inputs["root"]
    tag = json.dumps([sub, root], sort_keys=True)
    jobs = (("germ131", germ131, lambda: germ131(sub, root)), ("slices131", slices131, lambda: slices131(sub, root, out["germ131"])),
            ("germ127", r66.germ, lambda: r66.germ(sub, root)), ("weight", critical_weight, lambda: critical_weight(out["germ127"])))
    for name, fn, call in jobs:
        key = _key(fn, tag)
        if cached.get(name, {}).get("key") != key:
            cached[name] = {"key": key, "value": json.loads(json.dumps(call()))}
            CACHE.parent.mkdir(parents=True, exist_ok=True)
            CACHE.write_text(json.dumps(cached, indent=1) + "\n", encoding="utf-8")
        out[name] = cached[name]["value"]
    return out


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

ANCHORS = {"A0": [r"\text{differentfirst-orderclass,samesecond-orderisolationoutcome}.", r"\rho_{131}^\star=0.00254068891729192.",
                  r"T_{131}^\star=0.0473333498919449.", "ThisreproducestheBCODR-LUC-03truecommon-pointoverlaptime.", r"T^\star=\frac12\|p^\star-q^\star\|.",
                  r"\|p^\star-q^\star\|\le\|p^\star-z\|+\|z-q^\star\|\le2T.", r"g_-=-g_+.", r"\boxed{5-1=4}", r"H_-^{131}=\operatorname{diag}(1,0,1,0,1).",
                  r"\kappa_{131}=0.454649807778291.", r"\kappa_{127}=0.45429481027797.", r"\frac{\kappa_{131}}{\kappa_{127}}=1.00078142539226.",
                  "Theydifferbylessthanonetenthofonepercent.", r"C_R^{127}=1.78921498757354.", r"C_R^{131}=4.80263713445372.",
                  r"C_H^{127}=0.747599042164318.", r"C_H^{131}=0.456310132719225.", r"\kappa_{\rmgerm}<0", r"\text{second-orderisolatedbirth}.",
                  r"\kappa_{\rmgerm}\approx0.454>0."]}
CLAIMS = {
    "midpoint_claim": {"r": "0.002540688874928299", "T": "0.04733334989194495657", "printed_r": 4.2e-11, "printed_T": 6e-17, "luc03_printed": 7.9e-13,
                       "luc03_rebuilt": True, "min_margin": 0.0095, "nearest_box": "155", "next": ["144", "0.246383"], "half_distance": True},
    "first_claim": {"g_sum_zero": True, "stationary": True, "rank": 1, "dimension": 4, "outside_155": [0, 2, 4], "D_plus": "1709.2110247947"},
    "stiffness_claim": {"kappa": ["0.45464980777815", 1.4e-13], "t": "0.50003", "eig_Q_plus": [0.0001098, 1.0, 1.0, 1.0], "eig_Q_minus": [0.0, 0.0, 1.0, 1.0],
                        "C_R": ["4.802637134452", 1e-12], "C_H": ["0.4563101327193", 7e-14], "v_soft_vs_record": 2e-07},
    # at the midpoint the straight-line constant is the overlap's own, to 1e-8
    "growth_claim": {"lagrangian": ["0.4546497978", "0.5", "0.5454051121", "1.0"], "line_minus_lagrangian": 1e-08, "predicted": {"x5": "0.5", "y3": "0.491831"},
                     "slices": {"x5": {"1e-3": "0.500027", "3e-4": "0.500002", "1e-4": "0.500000"}, "y3": {"1e-3": "0.491857", "3e-4": "0.491834", "1e-4": "0.491831"}},
                     "slice_error_at_1e-4": {"x5": 3e-07, "y3": 3e-07}},
    # the overlaps' own constants differ by a factor 1.92, not 0.08 %
    "comparison_claim": {"line_ratio": ["1.00078142542", 3e-11], "lagrangian": ["0.236577", "0.45465"], "ratio": "1.92179", "both_isolated": True,
                         "cost": ["0.931745", "4.80264", "5.154"], "extent": ["1.03598", "0.45631", "0.4405"], "record": [2.6842146795153217, 0.6103674656914958]},
    "rule_claim": {"Q_minus_psd": [True, True], "alpha_c": "0.9987", "at_alpha_1": "-0.00119", "at_actual_alpha": "0.236576", "alpha_127": "0.2394", "Q_plus_131_pd": True},
    "records_claim": {"ratios": [True, True, True], "gap_vs_T": 7.9e-13, "rule": "kappa_germ > 0",
                      "state": {"127": "FCBG_SECOND_ORDER_ISOLATED", "131": "IMBG_SECOND_ORDER_ISOLATED"},
                      "next": "BCODR-LUC-06 — Frontier Spine Closure Against the Aref Tail", "luc_files": ["01", "02", "03", "04", "05", "07"]},
    "verifier_facts": {"lines": 45, "reads": 1, "fails": 10, "thresholds": ["0.4", "0.4"], "computes": False},
    "package_claim": {"digests": {"paper_sha256": True, "result_sha256": True, "plot_sha256": True, "verifier_sha256": True, "state_sha256": True}, "manifest": True,
                      "utf8": True, "delimiters": ["PASS", []],
                      "replay": ["PASS", "root127 type = FCBG", "root127 tangent dim = 3", "root127 kappa = 0.45429481027797036", "root131 type = IMBG",
                                 "root131 tangent dim = 4", "root131 kappa = 0.45464980777829145", "kappa ratio = 1.0007814253922556"]},
}


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


def w1_midpoint(w):
    """the nearest ray/155 pair: rho* (the printed one 4e-11 off), T* (the printed one right to its digits; LUC 03's
    printed 0.0473333498927312 is 8e-13 higher, so sec. 3 "reproduces" it to that much); the midpoint inside 131 by at least
    0.0095; and 155's pair is the nearest of all five boxes, which the midpoint theorem needs"""
    with mp.workdps(DPS):
        gm = w["search"]["germ131"]
        T = mp.mpf(gm["T"])
        ray = {j: mp.mpf(v) for j, v in gm["ray_to"].items()}
        got = {"r": gm["r"][:20], "T": gm["T"][:22], "printed_r": sig(abs(mp.mpf("0.00254068891729192") - mp.mpf(gm["r"])), 2),
               "printed_T": sig(abs(mp.mpf("0.0473333498919449") - T), 1), "luc03_printed": sig(mp.mpf("0.0473333498927312") - T, 2),
               "luc03_rebuilt": abs(T - mp.mpf(w["log65"]["w4"]["T"])) < 1e-15, "min_margin": sig(min(mp.mpf(x) for x in gm["margins"]), 2),
               "nearest_box": min(ray, key=lambda j: ray[j]), "next": [sorted(ray, key=lambda j: ray[j])[1], mp.nstr(sorted(ray.values())[1], 6)],
               "half_distance": abs(ray["155"] / 2 - T) < 1e-40}
    w["w1"] = got
    return [] if got == w["midpoint_claim"] else [f"the midpoint: {got}"]


def w2_first(w):
    """g- = -g+ exactly at the midpoint, so the rank is 1 and the critical space is g+'s four-dimensional complement; the
    ray point is the nearest one; the ray point is outside 155 in x3, rho5 and y5 only, so H- = diag(1, 0, 1, 0, 1)"""
    with mp.workdps(DPS):
        gm = w["search"]["germ131"]
        got = {"g_sum_zero": mp.mpf(gm["g_sum"]) < 1e-45, "stationary": abs(mp.mpf(gm["gp_dot_dp"])) < 1e-45, "rank": gm["rank"], "dimension": 5 - gm["rank"],
               "outside_155": gm["outside_155"], "D_plus": gm["D_plus"][:15]}
    w["w2"] = got
    return [] if got == w["first_claim"] else [f"the first order: {got}"]


def w3_stiffness(w):
    """the straight-line kappa_131 (max over t of lambda_min(t Q+ + (1 - t) Q-)), reached at t = 0.50003, its direction, Q+ positive
    definite here (the ray bends away from z), and C_R = kappa / 2T*, C_H = sqrt(2T* / kappa) as printed"""
    with mp.workdps(DPS):
        gm, R = w["search"]["germ131"], w["result"]["root131"]
        k, T = mp.mpf(gm["kappa_line"]), mp.mpf(gm["T"])
        vs = [float(x) for x in gm["v_soft"]]
        got = {"kappa": [gm["kappa_line"][:16], sig(abs(k - mp.mpf("0.454649807778291")), 2)], "t": gm["t_line"][:7],
               "eig_Q_plus": [round(float(x), 7) for x in gm["eig_Q_plus"]], "eig_Q_minus": [round(float(x), 7) for x in gm["eig_Q_minus"]],
               "C_R": [mp.nstr(k / (2 * T), 13), sig(abs(k / (2 * T) - mp.mpf("4.80263713445372")), 1)],
               "C_H": [mp.nstr(mp.sqrt(2 * T / k), 13), sig(abs(mp.sqrt(2 * T / k) - mp.mpf("0.456310132719225")), 1)],
               "v_soft_vs_record": sig(max(abs(a - b) for a, b in zip(vs, R["soft_direction_normalized_parameter_coordinates"])), 1)}
    w["w3"] = got
    return [] if got == w["stiffness_claim"] else [f"the stiffness: {got}"]


def w4_growth(w):
    """at the midpoint the KKT weight is 1/2 and the straight-line optimum is t = 0.50003, so the two constants agree:
    the Lagrangian minimum is 0.4546497978, 1e-8 below the straight-line one; the slices (x5: 1/2, y3: 0.4918) confirm it"""
    with mp.workdps(DPS):
        gm, sl = w["search"]["germ131"], w["search"]["slices131"]
        got = {"lagrangian": [mp.nstr(mp.mpf(x), 10) for x in gm["lagrangian"]], "line_minus_lagrangian": sig(mp.mpf(gm["kappa_line"]) - mp.mpf(gm["lagrangian"][0]), 1),
               "predicted": {k: v[:8] for k, v in gm["predicted"].items()}, "slices": {k: {h: v[:8] for h, v in d.items()} for k, d in sl.items()},
               "slice_error_at_1e-4": {k: sig(abs(mp.mpf(sl[k]["1e-4"]) - mp.mpf(gm["predicted"][k])), 1) for k in sl}}
    w["w4"] = got
    return [] if got == w["growth_claim"] else [f"the growth: {got}"]


def w5_comparison(w):
    """the printed ratio is the straight-line one; the overlaps' own constants are 0.2366 (127, RUN-066) and 0.4546 (131):
    a ratio of 1.92, not 1.0008; both positive, so both germs are isolated; the radius costs are 0.932 and 4.80 (ratio 5.2,
    not 2.68), the lens coefficients 1.036 and 0.456 (ratio 0.44, not 0.61)"""
    with mp.workdps(DPS):
        a, b = w["search"]["germ127"], w["search"]["germ131"]
        Ta, Tb = mp.mpf(a["T"]), mp.mpf(b["T"])
        la, lb = mp.mpf(a["lagrangian"][0]), mp.mpf(b["lagrangian"][0])
        line = mp.mpf(b["kappa_line"]) / mp.mpf(a["kappa_line"])
        got = {"line_ratio": [mp.nstr(line, 12), sig(abs(line - mp.mpf("1.00078142539226")), 1)], "lagrangian": [mp.nstr(la, 6), mp.nstr(lb, 6)],
               "ratio": mp.nstr(lb / la, 6), "both_isolated": la > 0 and lb > 0,
               "cost": [mp.nstr(la / (2 * Ta), 6), mp.nstr(lb / (2 * Tb), 6), mp.nstr((lb / (2 * Tb)) / (la / (2 * Ta)), 4)],
               "extent": [mp.nstr(mp.sqrt(2 * Ta / la), 6), mp.nstr(mp.sqrt(2 * Tb / lb), 6), mp.nstr(mp.sqrt(2 * Tb / lb) / mp.sqrt(2 * Ta / la), 4)],
               "record": [w["result"]["comparison"]["radius_cost_ratio_131_over_127"], w["result"]["comparison"]["tangent_extent_ratio_131_over_127"]]}
    w["w5"] = got
    return [] if got == w["comparison_claim"] else [f"the comparison: {got}"]


def w6_rule(w):
    """sec. 22 decides by the straight-line kappa, which never sees the KKT weight; the second-order condition is the
    Lagrangian at that weight. Because the inward seed is a box, Q- is positive semidefinite and the straight-line kappa can
    never be negative: sec. 21's unstable class cannot occur under its own definition. With 127's own forms the Lagrangian
    would lose positivity above alpha = 0.9988 while kappa_germ stayed 0.4543; 127's actual alpha is 0.24"""
    with mp.workdps(DPS):
        a, b, wt = w["search"]["germ127"], w["search"]["germ131"], w["search"]["weight"]
        got = {"Q_minus_psd": [min(mp.mpf(x) for x in sum(a["Q_minus"], [])) >= 0 and min(mp.eigsy(mp.matrix([[mp.mpf(x) for x in r] for r in a["Q_minus"]]))[0]) >= 0,
                               min(mp.mpf(x) for x in b["eig_Q_minus"]) >= 0],
               "alpha_c": wt["alpha_c"][:6], "at_alpha_1": wt["at_1"][:8], "at_actual_alpha": wt["at_alpha"][:8], "alpha_127": a["alpha"][:6],
               "Q_plus_131_pd": min(mp.mpf(x) for x in b["eig_Q_plus"]) > 0}
    w["w6"] = got
    return [] if got == w["rule_claim"] else [f"the rule: {got}"]


def w7_records(w):
    R, st = w["result"], w["state"]
    A, B, C = R["root127"], R["root131"], R["comparison"]
    got = {"ratios": [abs(C["kappa_ratio_131_over_127"] - B["kappa_germ"] / A["kappa_germ"]) < 1e-15, abs(C["birth_radius_ratio_131_over_127"] - B["T_true"] / A["T_true"]) < 1e-15,
                      abs(C["radius_cost_ratio_131_over_127"] - B["radius_increment_coefficient"] / A["radius_increment_coefficient"]) < 1e-15],
           "gap_vs_T": sig(B["container_separation_gap"] - (B["T_true"] - B["T_box"]), 2), "rule": R["classification_rule"]["isolated_birth"],
           "state": st["classified_germs"], "next": st["next"], "luc_files": w["luc_files"]}
    w["w7"] = got
    return [] if got == w["records_claim"] else [f"the records: {got}"]


def w8_verifier(w):
    """read after the rebuild and never run: it reads the result record alone and checks types, dimensions, both kappas
    above 0.4, two flags and the soft balance; it computes nothing"""
    code = w["verifier"]
    got = {"lines": code.count("\n"), "reads": len(re.findall(r"json\.load\(", code)), "fails": len(re.findall(r"raise SystemExit\(\"FAIL", code)),
           "thresholds": re.findall(r"\"kappa_germ\"\] > ([\d.]+)", code), "computes": bool(re.search(r"math\.\w+\(|sqrt|\bray\b|subroot", code))}
    w["w8"] = got
    return [] if got == w["verifier_facts"] else [f"the verifier: {got}"]


def p1_package(w):
    v, B = w["validation"], w["bytes"]
    sha = lambda b: hashlib.sha256(b).hexdigest()
    keys = {"paper_sha256": DOC, "result_sha256": RESULT, "plot_sha256": PLOT, "verifier_sha256": VERIFIER, "state_sha256": STATE}
    body = B[DOC].decode("utf-8")
    got = {"digests": {k: v[k] == sha(B[f]) for k, f in keys.items()}, "manifest": all(w["manifest_rows"][k][2] == sha(b) for k, b in B.items()),
           "utf8": v["utf8"] is True, "delimiters": [v["math_delimiters"], sorted(set(re.findall(r"\\\(|\\\)|\\\[|\\\]", body)))], "replay": v["fresh_replay_stdout"].split("\n")}
    w["p1"] = got
    return [] if got == w["package_claim"] else [f"the package: {got}"]


def a0_anchors(w):
    text = gate.squash(w["text"])
    return [f"anchor not found: {a[:60]}" for a in ANCHORS["A0"] if a not in text]


CHECKS = {"A0": a0_anchors, "W1": w1_midpoint, "W2": w2_first, "W3": w3_stiffness, "W4": w4_growth, "W5": w5_comparison, "W6": w6_rule, "W7": w7_records,
          "W8": w8_verifier, "P1": p1_package}
DEPENDS = {"A0": {"text"}, "W1": {"search", "log65", "midpoint_claim"}, "W2": {"search", "first_claim"}, "W3": {"search", "result", "stiffness_claim"},
           "W4": {"search", "growth_claim"}, "W5": {"search", "result", "comparison_claim"}, "W6": {"search", "rule_claim"},
           "W7": {"result", "state", "luc_files", "records_claim"}, "W8": {"verifier", "verifier_facts"}, "P1": {"validation", "bytes", "manifest_rows", "package_claim"}}


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

    text, s, R = base["text"], base["search"], base["result"]
    return [
        ("K0-unmodified", "control", {}, set()),
        ("K1-crlf", "control", {"text": text.replace("\n", "\r\n")}, set()),
        ("K2-validation-keys-sorted", "control", {"validation": json.loads(json.dumps(base["validation"], sort_keys=True))}, set()),
        ("K3-result-keys-sorted", "control", {"result": json.loads(json.dumps(R, sort_keys=True))}, set()),
        ("M1-text-ratio", "mutation", {"text": text.replace("1.00078142539226.", "1.00078142539227.")}, {"A0"}),
        ("M2-nearest-box", "mutation", {"search": edit(s, lambda x: x["germ131"]["ray_to"].update({"144": "0.09"}))}, {"W1"}),
        ("M3-luc03", "mutation", {"log65": edit(base["log65"], lambda x: x["w4"].update(T="0.0473333498927312"))}, {"W1"}),
        ("M4-rank", "mutation", {"search": edit(s, lambda x: x["germ131"].update(rank=2))}, {"W2"}),
        ("M5-outside", "mutation", {"search": edit(s, lambda x: x["germ131"].update(outside_155=[0, 1, 2, 4]))}, {"W2"}),
        ("M6-kappa131", "mutation", {"search": edit(s, lambda x: x["germ131"].update(kappa_line="0.4547"))}, {"W3", "W4", "W5"}),
        ("M7-soft-direction", "mutation", {"result": edit(R, lambda x: x["root131"]["soft_direction_normalized_parameter_coordinates"].__setitem__(1, -0.7))}, {"W3"}),
        ("M8-slice", "mutation", {"search": edit(s, lambda x: x["slices131"]["x5"].update({"1e-4": "0.4546"}))}, {"W4"}),
        ("M9-lagrangian127", "mutation", {"search": edit(s, lambda x: x["germ127"]["lagrangian"].__setitem__(0, "0.4542948102"))}, {"W5"}),
        ("M10-record-ratio", "mutation", {"result": edit(R, lambda x: x["comparison"].update(radius_cost_ratio_131_over_127=2.6))}, {"W5", "W7"}),
        ("M11-alpha-c", "mutation", {"search": edit(s, lambda x: x["weight"].update(alpha_c="0.95"))}, {"W6"}),
        ("M12-Q-minus", "mutation", {"search": edit(s, lambda x: x["germ127"]["Q_minus"][0].__setitem__(0, "-0.001"))}, {"W6"}),
        ("M13-state", "mutation", {"state": edit(base["state"], lambda x: x["classified_germs"].update({"131": "IMBG_FLAT"}))}, {"W7"}),
        ("M14-gap", "mutation", {"result": edit(R, lambda x: x["root131"].update(container_separation_gap=0.04733334989194494))}, {"W7"}),
        ("M15-verifier-computes", "mutation", {"verifier": base["verifier"] + "\nr = math.sqrt(2)\n"}, {"W8"}),
        ("M16-validation-digest", "mutation", {"validation": {**base["validation"], "result_sha256": "0" * 64}}, {"P1"}),
        ("M17-paper-bytes", "mutation", {"bytes": {**base["bytes"], DOC: base["bytes"][DOC] + b" "}}, {"P1"}),
    ]


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()
    base = {**inputs, "search": searches(inputs)}

    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 ("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)
    summ = gate.summarize(d, CHECKS)
    print(gate.report_drill(summ))
    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-067", "subject": "BCODR LUC 05: the balanced overlap germ taxonomy, root 127 against root 131", "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", "w8", "p1")}, "drill": summ}
    LOG.write_text(json.dumps(log, ensure_ascii=False, indent=1, default=float) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
