"""RUN-066 - BCODR LUC 04: the tangent decomposition of root 127's true-overlap germ.

BCODR-LUC-04 (2026-09-21) takes LUC 03's earliest common point z* of root 127 (T* = 0.126953667790942, from prune 155) and
asks whether any tangent direction stays inside the overlap at that radius. It finds the active gradients g+ = z* - p*
and g- = z* - q* with a KKT relation alpha* g+ + (1 - alpha*) g- = eta* e_x3 (alpha* = 0.239444757052325), an active
normal rank of 2 and so a three-dimensional critical tangent space; the outward reduced Hessian H+ = I - p'p'^T / D+
(D+ = 1706.98000390147), the inward H- = diag(1, 0, 1, 0, 1), their restrictions Q+ and Q-, and a "combined germ
stiffness" kappa_germ = min over unit critical v of max(v^T H+ v, v^T H- v) = 0.45429481027797 > 0. From it: the birth
germ is isolated to second order, the overlap grows after birth with tangent extent |h| <~ 0.747599042164318 sqrt(eps),
and a radius cost eps >~ 1.78921498757354 h^2. Here every quantity is recomputed at 50 digits from the exact reduction,
and the growth is measured directly, by minimax on slices of 127's box.

Two curves that meet at a point can be pushed apart along a common tangent and bent back together: along a straight
critical direction v both squared distances grow like h^2 v^T H+- v, but a second-order correction along the active
normal trades one against the other, at the KKT weight. The overlap's own second-order law is therefore the Lagrangian
form alpha H+ + (1 - alpha) H-, not the larger of the two forms.

Checks
  A0 anchors      the statements below occur in the document as written
  W1 point        sec. 0-3: z*, T* and the active pattern
  W2 kkt          sec. 4-6: g+ and g-, alpha* and eta*, the stationarity in rho, the rank and why it is 2
  W3 tangent      sec. 7-13: the critical tangent space, D+, H+-, Q+-
  W4 stiffness    sec. 14-15: the straight-line stiffness and its softest direction, as defined
  W5 growth       sec. 16-19, 22-23: the overlap's true second-order law, measured on slices; isolation; the lens
  W6 records      the result record, state and plot against each other and the rebuild
  W7 verifier     the verifier, read after this rebuild and never run
  P1 package      the VALIDATION record against the bytes and the archive

Usage: python code/run066_bcodr_luc04.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
from corpus import SOURCES, TREE, source_bytes, walk_sources

PKG = "main.zip!/BCODR/BCODR_LUC_04_Package_v0.1.zip!/"
DOC = PKG + "BCODR_LUC_04_True_Overlap_Germ_Tangent_Decomposition_v0.1.md"
RESULT = PKG + "BCODR_LUC_04_Tangent_Decomposition_Result_v0.1.json"
PLOT = PKG + "BCODR_LUC_04_Tangent_Stiffness.png"
VERIFIER = PKG + "BCODR_LUC_04_Verify_Tangent_Decomposition.py"
STATE = PKG + "BCODR_LUC_04_STATE_v0.1.json"
VALIDATION = PKG + "BCODR_LUC_04_VALIDATION.json"
LOG = TREE / "data" / "gate-logs" / "run066-bcodr-luc04.json"
LOG65 = TREE / "data" / "gate-logs" / "run065-bcodr-luc03.json"
MANIFEST = TREE / "data" / "SOURCE_MANIFEST.v1.json"
CACHE = TREE / "data" / "cache" / "run066-searches.json"     # data/cache is not committed
DPS = 50
SLICES = ("1e-3", "3e-4", "1e-4")
PRINTED = {"z": ["-0.125", "-0.490449386049", "-0.429185812844", "0.104804263668", "0.395569590601"],
           "g_plus": ["0.10559856031", "0", "-0.0264085908998", "0", "-0.0653357800345"], "g_minus": ["0.125", "0", "0.00831418715568", "0", "0.0205695906014"],
           "alpha": "0.239444757052325", "eta": "0.120354426986961", "slope": "-0.404197989002394", "D_plus": "1706.98000390147",
           "Q_plus": [["0.9917527159", "0", "-0.09049364957"], ["0", "1", "0"], ["-0.09049364957", "0", "0.007054860947"]],
           "kappa": "0.45429481027797", "v_soft": ["0", "-0.738718613358", "-0.624897568788", "1.73650131834e-07", "0.252582340636"],
           "extent": "0.747599042164318", "cost": "1.78921498757354"}


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}
    rows = {r[0]: r for r in json.loads(MANIFEST.read_text(encoding="utf-8"))["leaves"] if r[0] in want}
    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": rows, "subroots": c11["subroots"],
            "root": c11["root"], "log65": json.loads(LOG65.read_text(encoding="utf-8"))}


# ---------------------------------------------------------------- the germ, rebuilt

def frame(sub, root):
    g = r64.grid_boxes(sub, root)
    lo, hi = r65.nbox(g, 127)
    ql, qh = r65.nbox(g, 155)
    return g, lo, hi, ql, qh


def reduced(g, lo, qh, r):
    """sec. 12-13 at ray parameter r: the meeting point on 127's lower x3 face, on the segment from the ray point to 155's
    corner in (rho5, y5), at equal distance from both"""
    p = r65.ray_n(g, r)
    r1, q1, q3, q5 = lo[0], qh[0], qh[2], qh[4]
    a, b = r1 - p[0], r1 - q1
    D2 = (p[2] - q3) ** 2 + (p[4] - q5) ** 2
    lam = (b ** 2 - a ** 2 + D2) / (2 * D2)
    z = [r1, p[1], p[2] + lam * (q3 - p[2]), p[3], p[4] + lam * (q5 - p[4])]
    return a ** 2 + lam ** 2 * D2, lam, p, z, [q1, p[1], q3, p[3], q5]


def germ(sub, root):
    """r* from the stationarity of the reduction; z*, p*, q*, g+-, alpha, eta; p' and p'' of the normalized ray; D+, H+-,
    the critical basis, Q+-; the straight-line stiffness max over t of lambda_min(t Q+ + (1 - t) Q-) and its direction;
    the Lagrangian form alpha Q+ + (1 - alpha) Q-; the singular values of [g+; g-; e_x3]; collinearity off r*"""
    s = lambda x: mp.nstr(x, 30)
    with mp.workdps(DPS):
        g, lo, hi, ql, qh = frame(sub, root)
        rs = mp.findroot(lambda r: mp.diff(lambda x: reduced(g, lo, qh, x)[0], r), mp.mpf("0.0025452863403"))
        T2, lam, p, z, q = reduced(g, lo, qh, rs)
        gp, gm = [z[k] - p[k] for k in range(5)], [z[k] - q[k] for k in range(5)]
        alpha = 1 - lam
        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])
        slope = -gp[2] / gp[4]
        nrm = mp.sqrt(1 + slope ** 2)
        B = mp.matrix([[0, 0, 0], [1, 0, 0], [0, 0, 1 / nrm], [0, 1, 0], [0, 0, slope / nrm]])
        Qp, Qm = B.T * Hp * B, B.T * Hm * B
        lmin = lambda t: min(mp.eigsy(t * Qp + (1 - t) * Qm)[0])
        qg = (mp.sqrt(5) - 1) / 2
        f, t = r65.golden_max(lmin, mp.mpf(0), mp.mpf(1), qg, 160)
        E, Qv = mp.eigsy(t * Qp + (1 - t) * Qm)
        k0 = min(range(3), key=lambda i: E[i])
        vs = Qv[:, k0] * (1 if Qv[0, k0] < 0 else -1)
        EL, QLv = mp.eigsy(alpha * Qp + (1 - alpha) * Qm)
        kL = min(range(3), key=lambda i: EL[i])
        QLi = (alpha * Qp + (1 - alpha) * Qm) ** -1
        A = mp.matrix([gp, gm, [1, 0, 0, 0, 0]])
        sv = mp.svd_r(A, compute_uv=False)
        far = reduced(g, lo, qh, rs + mp.mpf("1e-4"))
        gpf, gmf = [far[3][k] - far[2][k] for k in range(5)], [far[3][k] - far[4][k] for k in range(5)]
        return {"r": s(rs), "T": s(mp.sqrt(T2)), "lambda": s(lam), "alpha": s(alpha), "eta": s(alpha * gp[0] + (1 - alpha) * gm[0]),
                "z": [s(x) for x in z], "p": [s(x) for x in p], "q": [s(x) for x in q], "g_plus": [s(x) for x in gp], "g_minus": [s(x) for x in gm],
                "kkt": [s(alpha * gp[k] + (1 - alpha) * gm[k]) for k in (1, 2, 3, 4)], "gp_dot_dp": s(sum(gp[k] * dp[k] for k in range(5))),
                "D_plus": s(Dp), "slope": s(slope), "Q_plus": [[s(Qp[i, j]) for j in range(3)] for i in range(3)],
                "Q_minus": [[s(Qm[i, j]) for j in range(3)] for i in range(3)], "eig_Q_plus": [s(x) for x in sorted(mp.eigsy(Qp)[0])],
                "kappa_line": s(f), "t_line": s(t), "v_soft": [s(x) for x in B * vs], "soft_forms": [s((vs.T * Qp * vs)[0]), s((vs.T * Qm * vs)[0])],
                "lagrangian": [s(x) for x in sorted(EL)], "v_lagrangian": [s(x) for x in B * QLv[:, kL]], "predicted": {"x5": s(1 / QLi[1, 1]), "y3": s(1 / QLi[0, 0])},
                "singular_values": [s(x) for x in sv], "collinear_off_rstar": s(gpf[2] * gmf[4] - gpf[4] * gmf[2]),
                "inside_155": [ql[k] < p[k] < qh[k] for k in (1, 3)], "on_face": z[0] == lo[0], "inside_127": all(lo[k] <= z[k] <= hi[k] for k in range(5))}


def slices(sub, root, gm):
    """the overlap's growth measured directly: the least max(d+, d-) over 127's box with x5 (then y3) pinned at z* + h, by
    RUN-065's dual, for three h; (T^2 - T*^2) / h^2"""
    out = {}
    with mp.workdps(DPS):
        g, lo, hi, ql, qh = frame(sub, root)
        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 _key(fn, extra=""):
    digest = hashlib.sha256(inspect.getsource(fn).encode())
    for helper in (frame, reduced, r65.nbox, r65.ray_n, r65.phi, r65.golden_max, r65.at_point, r64.grid_boxes, r64.ray_units):
        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 = {}
    tag = json.dumps([inputs["subroots"], inputs["root"]], sort_keys=True)
    jobs = (("germ", germ, lambda: germ(inputs["subroots"], inputs["root"])), ("slices", slices, lambda: slices(inputs["subroots"], inputs["root"], out["germ"])))
    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"T^\star=0.126953667790942.", r"z^\star=[-0.125,-0.490449386049,-0.429185812844,0.104804263668,0.395569590601].",
                  r"g_+=[0.10559856031,0,-0.0264085908998,0,-0.0653357800345],", r"g_-=[0.125,0,0.00831418715568,0,0.0205695906014].",
                  r"\alpha^\star=0.239444757052325", r"\eta^\star=0.120354426986961>0.", r"\boxed{2.}", r"\boxed{5-2=3.}",
                  r"\deltay_5=-0.404197989002394\,\delta\rho_5", r"D_+=\|p'\|^2-g_+\cdotp''=1706.98000390147.", r"H_-=\operatorname{diag}(1,0,1,0,1).",
                  r"Q_+=[[0.9917527159,0,-0.09049364957];[0,1,0];[-0.09049364957,0,0.007054860947]],", r"Q_-=[[0,0,0];[0,0,0];[0,0,1]].",
                  r"\kappa_{\rmgerm}=\min_{v\inT_{\rmcrit},\\|v\|=1}\max\{v^TH_+v,v^TH_-v\}.", r"\kappa_{\rmgerm}=0.45429481027797.",
                  r"v_{\rmsoft}=[0,-0.738718613358,-0.624897568788,1.73650131834e-07,0.252582340636].",
                  r"\max(d_+^2,d_-^2)\ge(T^\star)^2+\kappa_{\rmgerm}h^2+o(h^2).", r"\text{theearliesttrue-overlapbirthgermislocallyisolatedtosecondorder.}",
                  r"|h|\lesssim0.747599042164318\sqrt{\varepsilon}", r"\boxed{1.78921498757354.}", r"\kappa_{\rmgerm}>0.4.", r"\text{0Dbirthgerm}."]}
CLAIMS = {
    # the printed z* is off by 3e-10, as the printed r* (RUN-065) makes it; the printed T* is LUC 03's 5-D value
    "point_claim": {"r": "0.002545286340304561", "T": "0.12695366779092487910", "T_is_luc03": True, "z_printed": 3e-10, "z_result": 3e-10, "T_printed": 1.7e-14,
                    "active": [True, True, [True, True]]},
    "kkt_claim": {"g": [1e-09, 3e-10], "alpha": ["0.23944475705941", 7.1e-12], "eta": ["0.12035442698726", 3e-13], "stationary": True, "singular": [1.0133, 0.07374, True],
                  "collinear_off_rstar": True, "result_rank": 2, "result_alpha": 7.1e-12},
    "tangent_claim": {"slope": ["-0.4041979697", 1.9e-08], "D_plus": ["1706.98000390142", 4e-11], "Q_plus": 6e-11, "Q_minus": True, "eig_Q_plus": [-0.0011924, 1.0, 1.0],
                      "dimension": [3, 3]},
    "stiffness_claim": {"kappa": ["0.45429481026314", 1.5e-11], "t": "0.4996", "v_soft": 2e-07, "x5": 0.0, "forms_equal": True, "result": 1.5e-11},
    # the overlap's law is the Lagrangian form: softest 0.2366, measured on the slices to 3e-7; the lens reaches
    # 1.036 sqrt(eps), not 0.7476 sqrt(eps); the germ is isolated all the same
    "growth_claim": {"lagrangian": ["0.236577", "0.239445", "0.763138"], "isolated": True, "softest": [0.0, -0.9992, -0.0382, 0.0, 0.0154],
                     "predicted": {"x5": "0.239444", "y3": "0.236854"},
                     "slices": {"x5": {"1e-3": "0.239473", "3e-4": "0.239447", "1e-4": "0.239445"}, "y3": {"1e-3": "0.236881", "3e-4": "0.236856", "1e-4": "0.236854"}},
                     "slice_error_at_1e-4": {"x5": 3e-07, "y3": 2e-07}, "extent": ["1.03598", "1.02976", "0.7475"], "cost": ["0.931745", "1.7892"],
                     "line_model": {"x5": 1, "y3": "0.991753"}},
    "records_claim": {"radius_is_luc03": True, "coefficients": [True, True], "state": ["SECOND_ORDER_ISOLATED_TRUE_OVERLAP_GERM", 2, 3, 0, True], "interpretation": [3, 0],
                      "definition": "min_{||v||=1,v in Tcrit} max(v^T Hplus v, v^T Hminus v)",
                      "next": "Compare root 131 balanced separated germ or delegate interval certification of root 127."},
    "verifier_facts": {"lines": 44, "reads": 1, "fails": 7, "threshold": ["0.4"], "geometry": 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", "active gradient rank = 2", "critical tangent dimension = 3", "kappa_germ = 0.45429481027797036",
                                 "Qplus soft = 0.45429481027797036", "Qminus soft = 0.4542948102779702", "radius growth coefficient = 1.7892149875735401"]},
}


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


def dev(a, b):
    """the largest absolute difference of two equally shaped lists of numbers (strings or floats)"""
    fa = [float(x) for x in (sum(a, []) if a and isinstance(a[0], list) else a)]
    fb = [float(x) for x in (sum(b, []) if b and isinstance(b[0], list) else b)]
    return max(abs(x - y) for x, y in zip(fa, fb))


def w1_point(w):
    """z* and T*: the printed z* to its rounding after the printed r*, the printed T* is the 5-D value of LUC 03; the meeting
    point is on 127's lower x3 face and inside 127, with y3 and x5 inside 155's ranges"""
    with mp.workdps(DPS):
        gm, R = w["search"]["germ"], w["result"]
        t65 = w["log65"]["w5"]
        got = {"r": gm["r"][:20], "T": gm["T"][:22], "T_is_luc03": abs(mp.mpf(gm["T"]) - mp.mpf(t65["T"])) < 1e-19, "z_printed": sig(dev(gm["z"], PRINTED["z"]), 1),
               "z_result": sig(dev(gm["z"], R["meeting_point_normalized"]), 1), "T_printed": sig(mp.mpf("0.126953667790942") - mp.mpf(gm["T"]), 2),
               "active": [gm["on_face"], gm["inside_127"], gm["inside_155"]]}
    w["w1"] = got
    return [] if got == w["point_claim"] else [f"the point: {got}"]


def w2_kkt(w):
    """g+- as printed; alpha* = 1 - lambda*, eta* = alpha g+ x3 + (1 - alpha) g- x3; the stationarity in rho5 and y5 holds
    to the working precision, and the nearest ray point is stationary (g+ . p' = 0); the rank is 2 because the reduction
    puts z on the segment from the ray point to 155's corner, which makes g+ and g- collinear off x3 for every r"""
    with mp.workdps(DPS):
        gm, R = w["search"]["germ"], w["result"]["active_geometry"]
        sv = [float(x) for x in gm["singular_values"]]
        got = {"g": [sig(dev(gm["g_plus"], PRINTED["g_plus"]), 1), sig(dev(gm["g_minus"], PRINTED["g_minus"]), 1)],
               "alpha": [gm["alpha"][:16], sig(abs(mp.mpf(gm["alpha"]) - mp.mpf(PRINTED["alpha"])), 2)],
               "eta": [gm["eta"][:16], sig(abs(mp.mpf(gm["eta"]) - mp.mpf(PRINTED["eta"])), 2)],
               "stationary": max(abs(float(x)) for x in gm["kkt"]) < 1e-45 and abs(float(gm["gp_dot_dp"])) < 1e-45,
               "singular": [round(sv[0], 4), round(sv[1], 5), sv[2] < 1e-40], "collinear_off_rstar": abs(float(gm["collinear_off_rstar"])) < 1e-45,
               "result_rank": R["active_gradient_rank"], "result_alpha": sig(abs(R["kkt_alpha"] - float(gm["alpha"])), 2)}
    w["w2"] = got
    return [] if got == w["kkt_claim"] else [f"the KKT relation: {got}"]


def w3_tangent(w):
    """the critical space {dx3 = 0, g+ . dz = 0} has dimension 3; its slope, D+ and Q+ as printed, to the rounding the
    printed r* allows; Q+ has a small negative eigenvalue (the curved ray), Q- is diag(0, 0, 1)"""
    with mp.workdps(DPS):
        gm, R = w["search"]["germ"], w["result"]
        got = {"slope": [gm["slope"][:13], sig(abs(mp.mpf(gm["slope"]) - mp.mpf(PRINTED["slope"])), 2)],
               "D_plus": [gm["D_plus"][:16], sig(abs(mp.mpf(gm["D_plus"]) - mp.mpf(PRINTED["D_plus"])), 1)],
               "Q_plus": sig(dev(gm["Q_plus"], R["second_order_forms"]["Q_plus"]), 1), "Q_minus": dev(gm["Q_minus"], [[0, 0, 0], [0, 0, 0], [0, 0, 1]]) == 0.0,
               "eig_Q_plus": [round(float(x), 7) for x in gm["eig_Q_plus"]], "dimension": [3, R["critical_tangent_space"]["dimension"]]}
    w["w3"] = got
    return [] if got == w["tangent_claim"] else [f"the tangent space: {got}"]


def w4_stiffness(w):
    """the straight-line stiffness as sec. 14 defines it - the max over t of lambda_min(t Q+ + (1 - t) Q-), reached near
    t = 1/2 - and its direction, where the two forms are equal; the printed x5 component of that direction is noise"""
    with mp.workdps(DPS):
        gm, R = w["search"]["germ"], w["result"]["combined_stiffness"]
        got = {"kappa": [gm["kappa_line"][:16], sig(abs(mp.mpf(gm["kappa_line"]) - mp.mpf(PRINTED["kappa"])), 2)], "t": gm["t_line"][:6],
               "v_soft": sig(dev(gm["v_soft"], PRINTED["v_soft"]), 1), "x5": float(gm["v_soft"][3]), "forms_equal": abs(mp.mpf(gm["soft_forms"][0]) - mp.mpf(gm["soft_forms"][1])) < 1e-20,
               "result": sig(abs(R["kappa"] - float(gm["kappa_line"])), 2)}
    w["w4"] = got
    return [] if got == w["stiffness_claim"] else [f"the stiffness: {got}"]


def w5_growth(w):
    """the overlap's second-order law is alpha Q+ + (1 - alpha) Q-: its eigenvalues are 0.2366, 0.2394 and 0.7631, so the
    germ is isolated (all positive) but its softest stiffness is 0.2366, not 0.4543. The slices confirm it without
    expansion: with x5 pinned at z* + h the least overlap radius grows like 0.2394 h^2 (= alpha), with y3 pinned like
    0.2369 h^2 - where the straight-line model says 1 and 0.9918, and sec. 14 says at least 0.4543. So at T* + eps the lens
    reaches 1.036 sqrt(eps), not 0.7476 sqrt(eps), and the least radius cost is 0.932 h^2, not 1.789 h^2"""
    with mp.workdps(DPS):
        gm, sl = w["search"]["germ"], w["search"]["slices"]
        T = mp.mpf(gm["T"])
        L = [mp.mpf(x) for x in gm["lagrangian"]]
        got = {"lagrangian": [mp.nstr(x, 6) for x in L], "isolated": L[0] > 0, "softest": [round(float(x), 4) for x in gm["v_lagrangian"]],
               "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},
               "extent": [mp.nstr(mp.sqrt(2 * T / L[0]), 6), mp.nstr(mp.sqrt(2 * T / mp.mpf(gm["predicted"]["x5"])), 6), PRINTED["extent"][:6]],
               "cost": [mp.nstr(L[0] / (2 * T), 6), PRINTED["cost"][:6]], "line_model": {"x5": 1, "y3": mp.nstr(mp.mpf(gm["Q_plus"][0][0]), 6)}}
    w["w5"] = got
    return [] if got == w["growth_claim"] else [f"the growth: {got}"]


def w6_records(w):
    R, st = w["result"], w["state"]
    cs = R["combined_stiffness"]
    T = R["meeting_radius"]
    got = {"radius_is_luc03": T == 0.12695366779094175, "coefficients": [abs(cs["radius_increment_coefficient"] - cs["kappa"] / (2 * T)) < 1e-15,
                                                                         abs(cs["tangent_extent_coefficient_sqrt_epsilon"] - (2 * T / cs["kappa"]) ** 0.5) < 1e-15],
           "state": [st["status"], st["active_gradient_rank"], st["critical_tangent_dimension"], st["birth_germ_dimension_second_order"], st["kappa_germ"] == cs["kappa"]],
           "interpretation": [R["interpretation"]["linearized_tangent_dimension"], R["interpretation"]["second_order_birth_dimension"]],
           "definition": cs["definition"], "next": st["next"]}
    w["w6"] = got
    return [] if got == w["records_claim"] else [f"the records: {got}"]


def w7_verifier(w):
    """read after the rebuild and never run: it reads the result record alone, checks the rank and the dimension as
    constants, the forms' symmetry, kappa > 0.4, that the stored direction reaches the stored kappa, and the stored KKT
    residual; it computes no geometry"""
    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)),
           "threshold": re.findall(r"kappa > ([\d.]+)", code), "geometry": bool(re.search(r"\bray\b|cos\(|sin\(|subroot|halfwidth|meeting_point", code))}
    w["w7"] = 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_point, "W2": w2_kkt, "W3": w3_tangent, "W4": w4_stiffness, "W5": w5_growth, "W6": w6_records, "W7": w7_verifier,
          "P1": p1_package}
DEPENDS = {"A0": {"text"}, "W1": {"search", "result", "log65", "point_claim"}, "W2": {"search", "result", "kkt_claim"}, "W3": {"search", "result", "tangent_claim"},
           "W4": {"search", "result", "stiffness_claim"}, "W5": {"search", "growth_claim"}, "W6": {"result", "state", "records_claim"},
           "W7": {"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-kappa", "mutation", {"text": text.replace("0.45429481027797.", "0.45429481027798.")}, {"A0"}),
        ("M2-meeting-point", "mutation", {"result": edit(R, lambda x: x["meeting_point_normalized"].__setitem__(2, -0.4291))}, {"W1"}),
        ("M3-luc03-T", "mutation", {"log65": edit(base["log65"], lambda x: x["w5"].update(T="0.12695366779092487999"))}, {"W1"}),
        ("M4-alpha", "mutation", {"result": edit(R, lambda x: x["active_geometry"].update(kkt_alpha=0.2394))}, {"W2"}),
        ("M5-collinear", "mutation", {"search": edit(s, lambda x: x["germ"].update(collinear_off_rstar="1e-20"))}, {"W2"}),
        ("M6-D-plus", "mutation", {"search": edit(s, lambda x: x["germ"].update(D_plus="1706.98"))}, {"W3"}),
        ("M7-Q-plus", "mutation", {"result": edit(R, lambda x: x["second_order_forms"]["Q_plus"][2].__setitem__(2, 0.00706))}, {"W3"}),
        ("M8-kappa-line", "mutation", {"search": edit(s, lambda x: x["germ"].update(kappa_line="0.4543"))}, {"W4"}),
        ("M9-result-kappa", "mutation", {"result": edit(R, lambda x: x["combined_stiffness"].update(kappa=0.4543))}, {"W4", "W6"}),
        ("M10-slice", "mutation", {"search": edit(s, lambda x: x["slices"]["x5"].update({"1e-4": "0.4542948102"}))}, {"W5"}),
        ("M11-lagrangian", "mutation", {"search": edit(s, lambda x: x["germ"]["lagrangian"].__setitem__(0, "0.4542948102"))}, {"W5"}),
        ("M12-coefficient", "mutation", {"result": edit(R, lambda x: x["combined_stiffness"].update(radius_increment_coefficient=1.79))}, {"W6"}),
        ("M13-state", "mutation", {"state": edit(base["state"], lambda x: x.update(birth_germ_dimension_second_order=1))}, {"W6"}),
        ("M14-verifier-geometry", "mutation", {"verifier": base["verifier"] + "\nray = D['meeting_point']\n"}, {"W7"}),
        ("M15-validation-digest", "mutation", {"validation": {**base["validation"], "result_sha256": "0" * 64}}, {"P1"}),
        ("M16-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", "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-066", "subject": "BCODR LUC 04: the tangent decomposition of root 127's true-overlap germ", "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")}, "drill": summ}
    LOG.write_text(json.dumps(log, ensure_ascii=False, indent=1, default=float) + "\n", encoding="utf-8")


if __name__ == "__main__":
    main()
