"""RUN-009 - Round 08 (v0.8.3): the finite-width tanh curvature layer and its candidate gain over the event five-link.

Round 08 smooths the inner corner of the event five-link's wings (RUN-006) with an endpoint-normalized tanh layer:
the wing's tangent angle is theta(u) = beta + delta F(u), F(u) = (tanh((c - u)/eps) - tanh((c - 1)/eps)) /
(tanh(c/eps) - tanh((c - 1)/eps)), u in [0, 1] along a wing of length w, with a horizontal centre of length 1 - 2w and
a mirrored wing; as eps -> 0 the wing tends to two straight pieces. It sweeps eleven widths, re-equalizes four branches
at nine widths and six more near the peak, and reports a best candidate at eps = 0.037 with least scale
0.998914339084632, 1.058e-5 above the event five-link, cross-checked by a dense point cloud (0.998914339084602).

Checks (each returns a list of failures; empty = pass)
  L1 sweep curves   each of the eleven sweep curves is its parameters' wing (2,400 equal steps in u) with a centre of
                    49 equal steps and the mirrored wing, to 1e-7 against the exact curve; mirror-symmetric, length 1
  L2 best curve     the best candidate's curve file: its left wing is the candidate's (to 1e-7), its centre has the
                    candidate's length 1 - 2w, it is its own mirror image, and its length is 1
  L3 sweep values   for each sweep width: the full audit's least scale is the least exact scale of its parameters'
                    curve, and the fixed-event-parameters audit is that of the event five-link's parameters with the
                    layer, to 2e-8; the local minima number as stated
  L4 equalized      for each of the fifteen equalized widths: the stated best scale and each audit row are the least
                    exact scale of its parameters' curve, to 1e-10; the local minima number as stated; the gains
  L5 best           the best candidate's least exact scale is the stated stationary-support scale, to 1e-13, at
                    3pi/2; the gain, the distance and the manifest's figures follow
  L6 point cloud    each dense-point-cloud figure lies at or below the exact scale at its phase, within 1e-11
                    (a cloud of points can only miss an extreme), and the stated differences follow
  L7 curvature      each curvature ledger is its curve's on an equal grid of the wing (2,400 steps for the sweep,
                    12,000 for the candidate): the peak is the largest central difference delta |F'|/w on the grid,
                    to 1e-10 relative; the 5-95 % width is the span of the grid points with F in [0.05, 0.95]; the
                    total turning is delta, to 1e-8; the curvature centroid, to 1e-6
  L8 consistency    the README, the report and the three audit notes state the data's numbers and tables

Drill: each plant names the checks that must trip - trip meaning a failure the unplanted package does not already
have; controls must trip nothing.

Usage:
  python code/run009_round08_smooth_layer.py [--drill [--log PATH] | --blind L#]
"""
import argparse
import copy
import csv
import io
import json
import math
import pathlib
import re

import mpmath as mp
import numpy as np

from corpus import TREE, sha256, source_bytes
import gate
from run001_corpus_identity import restore_escapes
from run003_round02_phase_scan_chirality import exact_min, golden, legs, mirror
from run004_round03_symmetric_links import load, same_B
from run005_round04_branch_equalization import num, table

RID = "round-v0.8.3"
LOG = TREE / "data" / "gate-logs" / "run009-round08-smooth-layer.json"
GX, GW = np.polynomial.legendre.leggauss(20)
PANELS = 2000


# ---------------------------------------------------------------- the world

def build_world():
    f, f5 = load(RID), load("round-v0.5")
    md = lambda n: restore_escapes(f[n].decode("utf-8"))
    xy = lambda n: np.array([[float(r["x"]), float(r["y"])] for r in csv.DictReader(io.StringIO(f[n].decode("utf-8")))])
    S = json.loads(f["data/round08_summary.json"])
    return {
        "readme": md("README.md"), "report": md("reports/ROUND_08_REPORT.md"),
        "audit_note": md("reports/ROUND_08_FINITE_WIDTH_AUDIT.md"), "cloud_note": md("reports/ROUND_08_DENSE_POINTCLOUD_CROSSCHECK.md"),
        "peak_cloud_note": md("reports/ROUND_08_PEAK_DENSE_POINTCLOUD_CROSSCHECK.md"),
        "manifest": json.loads(f["MANIFEST.json"]),
        "summary": S,
        "focused": json.loads(f["data/round08_focused_equalization.json"]),
        "peak": json.loads(f["data/round08_peak_scan.json"]),
        "cloud": json.loads(f["data/round08_dense_pointcloud_crosscheck.json"]),
        "peak_cloud": json.loads(f["data/round08_peak_dense_pointcloud_crosscheck.json"]),
        "sweep_curves": {k: xy(f"data/smooth_eps_{float(k):.3f}.csv") for k in S["results"]},
        "best_curve": xy("data/best_finite_width_smooth_curve.csv"),
        "round05": json.loads(f5["data/round05_summary.json"]),
        "legs": ((3 + 4 * math.sqrt(3)) / 18, (4 + math.sqrt(3)) / 6),
        "cert_scale_divisor": 1.0048,
        "rot_sign": 1,
        "formula_B": same_B,
    }


# ---------------------------------------------------------------- the smooth wing

class Wing:
    """the tanh-layer curve: wing parameters (w, beta, delta, c) in radians, layer width eps; positions by composite
    20-point Gauss-Legendre quadrature of the exact tangent (2,000 panels, exact to rounding)"""

    def __init__(self, w, b, d, c, eps):
        self.w, self.b, self.d, self.c, self.eps = w, b, d, c, eps
        self.T0, self.T1 = math.tanh(c / eps), math.tanh((c - 1) / eps)
        self.edges = np.linspace(0, 1, PANELS + 1)
        lo, hi = self.edges[:-1], self.edges[1:]
        t = (hi - lo)[:, None] / 2 * GX[None, :] + (lo + hi)[:, None] / 2
        th = self.theta(t)
        inc = (hi - lo)[:, None] / 2 * np.stack([(GW * np.cos(th)).sum(1), (GW * np.sin(th)).sum(1)], 1)
        self.cum = w * np.concatenate([np.zeros((1, 2)), np.cumsum(inc, 0)])
        self.P1 = self.cum[-1]
        self.l0 = 1 - 2 * w
        self.P2 = self.P1 + np.array([self.l0, 0.0])
        self.mid = self.P1[0] + self.l0 / 2

    def F(self, u):
        return (np.tanh((self.c - u) / self.eps) - self.T1) / (self.T0 - self.T1)

    def theta(self, u):
        return self.b + self.d * self.F(u)

    def pos(self, u):
        u = np.atleast_1d(np.asarray(u, dtype=float))
        i = np.minimum((u * PANELS).astype(int), PANELS - 1)
        lo = self.edges[i]
        t = (u - lo)[:, None] / 2 * GX[None, :] + (u + lo)[:, None] / 2
        th = self.theta(t)
        inc = (u - lo)[:, None] / 2 * np.stack([(GW * np.cos(th)).sum(1), (GW * np.sin(th)).sum(1)], 1)
        return self.cum[i] + self.w * inc

    def u_of(self, theta):
        """the wing parameter where the tangent angle is theta (theta decreases from alpha to beta along u)"""
        Fv = (theta - self.b) / self.d
        if not 0 <= Fv <= 1:
            return None
        arg = self.T1 + Fv * (self.T0 - self.T1)
        lim = np.nextafter(1.0, 0.0)
        return self.c - self.eps * math.atanh(max(min(arg, lim), -lim))

    def points(self, nw, nc):
        W = self.pos(np.linspace(0, 1, nw + 1))
        cen = np.stack([self.P1[0] + self.l0 * np.arange(1, nc) / nc, np.full(nc - 1, self.P1[1])], 1)
        right = np.stack([2 * self.mid - W[::-1, 0], W[::-1, 1]], 1)
        return np.concatenate([W, cen, right])


def wing_of(P, eps):
    if isinstance(P, dict):
        return Wing(P["wing_length"], math.radians(P["beta_degrees"]), math.radians(P["delta_degrees"]),
                    P["transition_center"], eps)
    w, b, d, c = P
    return Wing(w, b, d, c, eps)


def scale(wv, wing, phi):
    """the exact scale of the smooth curve at phase phi: each linear functional's extreme lies at a junction or at the
    wing point whose tangent is perpendicular to it (theta is monotone, so there is one such point per wing)"""
    A, B = legs(wv)
    ph = wv["rot_sign"] * phi
    c, s = math.cos(ph), math.sin(ph)
    ux, uy = np.array([c, -s]), np.array([s, c])
    pts = [np.zeros(2), wing.P1, wing.P2, np.array([wing.P2[0] + wing.P1[0], 0.0])]
    us, mirrored = [], []
    for u in (ux, uy, ux / A + uy / B):
        t0 = math.atan2(-u[0], u[1])
        for t in (t0, t0 + math.pi, t0 - math.pi):
            a = wing.u_of(t)
            if a is not None:
                us.append(a)
            a = wing.u_of(-t)
            if a is not None:
                mirrored.append(a)
    if us:
        pts.extend(wing.pos(us))
    if mirrored:
        q = wing.pos(mirrored)
        pts.extend(np.stack([2 * wing.mid - q[:, 0], q[:, 1]], 1))
    Q = np.array(pts)
    x = Q[:, 0] * c - Q[:, 1] * s
    y = Q[:, 0] * s + Q[:, 1] * c
    return float((x / A + y / B).max() - x.min() / A - y.min() / wv["formula_B"](B))


def minima(wv, wing, scan=3600):
    """every local minimum over phases, refined by golden section, with the exact phases 2pi/3 and 3pi/2 of the
    symmetric ties added: [(phase, value)]"""
    f = lambda x: scale(wv, wing, x)
    phis = 2 * math.pi * np.arange(scan) / scan
    vals = np.array([f(x) for x in phis])
    st = 2 * math.pi / scan
    out = []
    for i in range(scan):
        if vals[i] <= vals[i - 1] and vals[i] <= vals[(i + 1) % scan]:
            v, x = golden(f, phis[i] - st, phis[i] + st)
            for ex in (2 * math.pi / 3, 3 * math.pi / 2):
                if abs(math.remainder(x - ex, 2 * math.pi)) < 2 * st:
                    v, x = min((v, x), (f(ex), ex))
            out.append((float(x % (2 * math.pi)), float(v)))
    return sorted(out)


_cache = {}


def least(wv, P, eps):
    key = (json.dumps(P) if isinstance(P, dict) else tuple(P), eps, wv["legs"], wv["cert_scale_divisor"], wv["rot_sign"],
           id(wv["formula_B"]))
    if key not in _cache:
        wing = wing_of(P, eps)
        m = minima(wv, wing)
        _cache[key] = (min(v for _, v in m), m, wing)
    return _cache[key]


def event_params(wv):
    E = wv["round05"]["event_solution"]["parameters"]
    w = E["l1"] + E["l2"]
    return {"wing_length": w, "beta_degrees": E["beta_degrees"], "delta_degrees": E["delta_degrees"],
            "transition_center": E["l1"] / w}


def hp_cusp(P, eps, dps=40):
    """the scale at 3pi/2 in arbitrary precision: there it is y1/A + (D - x1)/B with (x1, y1) the wing's end"""
    mp.mp.dps = dps
    w, b, d, c = (mp.mpf(repr(v)) for v in P)
    E = mp.mpf(repr(eps))
    T0, T1 = mp.tanh(c / E), mp.tanh((c - 1) / E)
    th = lambda u: b + d * (mp.tanh((c - u) / E) - T1) / (T0 - T1)
    x1 = w * mp.quad(lambda u: mp.cos(th(u)), [0, c, 1])
    y1 = w * mp.quad(lambda u: mp.sin(th(u)), [0, c, 1])
    A = (3 + 4 * mp.sqrt(3)) / 18 / mp.mpf("1.0048")
    B = (4 + mp.sqrt(3)) / 6 / mp.mpf("1.0048")
    D = 2 * x1 + (1 - 2 * w)
    return y1 / A + (D - x1) / B


# ---------------------------------------------------------------- the checks

def curve_dev(q, p):
    return float(np.abs((q - q[0]) - (p - p[0])).max()) if q.shape == p.shape else float("inf")


def l1_sweep_curves(w):
    failures = []
    for k, R in w["summary"]["results"].items():
        P = R["parameters"]
        if abs(P["center_length"] - (1 - 2 * P["wing_length"])) > 1e-15 or abs(P["alpha_degrees"] - P["beta_degrees"] - P["delta_degrees"]) > 1e-12:
            failures.append(f"eps {k}: centre or alpha is not the family's")
        q = w["sweep_curves"][k]
        dev = curve_dev(q, wing_of(P, float(k)).points(2400, 49))
        if dev > 1e-7:
            failures.append(f"eps {k}: the curve file differs from its parameters' curve by {dev:.2e}")
        r = (q * np.array([-1.0, 1.0]))[::-1]
        if np.abs((r - r[0]) - (q - q[0])).max() > 1e-12 or abs(np.linalg.norm(np.diff(q, axis=0), axis=1).sum() - 1) > 1e-12:
            failures.append(f"eps {k}: the curve file is not mirror-symmetric of length 1")
    return failures


def l2_best_curve(w):
    failures = []
    q = w["best_curve"]
    P = w["summary"]["best_verified_candidate"]["parameters"]
    wing = wing_of(P, w["summary"]["best_verified_candidate"]["epsilon"])
    d = np.diff(q, axis=0)
    L = np.linalg.norm(d, axis=1)
    centre = np.flatnonzero(np.abs(np.arctan2(d[:, 1], d[:, 0])) < 1e-12)
    nw = int(centre.min()) if len(centre) else 0
    left = wing.pos(np.linspace(0, 1, nw + 1)) if nw else None
    # fixed texts: the file's defects are failures of the unplanted package, so a plant must make a new one
    if left is None or np.abs((q[:nw + 1] - q[0]) - (left - left[0])).max() > 1e-7:
        failures.append("the file's left wing is not the candidate's")
    if not len(centre) or abs(L[centre].sum() - wing.l0) > 1e-9:
        failures.append("the file's centre does not have the candidate's length 1 - 2w")
    r = (q * np.array([-1.0, 1.0]))[::-1]
    if np.abs((r - r[0]) - (q - q[0])).max() > 1e-9:
        failures.append("the file is not its own mirror image")
    if abs(L.sum() - 1) > 1e-9:
        failures.append("the file's length is not 1")
    return failures


def l3_sweep_values(w):
    failures = []
    for k, R in w["summary"]["results"].items():
        # the sweep's audits deviate from the exact least scale by up to 1.1e-8 where the least sits at a smooth
        # branch (the mechanism is not shown): 2e-8 holds them
        s, mins, _ = least(w, R["parameters"], float(k))
        if abs(s - R["full_audit"]["scale"]) > 2e-8:
            failures.append(f"eps {k}: least scale {s!r}, the full audit {R['full_audit']['scale']!r}")
        if len(mins) != R["full_audit"]["local_minimum_count"]:
            failures.append(f"eps {k}: {len(mins)} local minima, stated {R['full_audit']['local_minimum_count']}")
        se, me, _ = least(w, event_params(w), float(k))
        if abs(se - R["fixed_event_parameters_audit"]["scale"]) > 2e-8:
            failures.append(f"eps {k}: the event parameters give {se!r}, stated {R['fixed_event_parameters_audit']['scale']!r}")
        for label, got, want in (("distance to event", R["distance_to_event"], w["summary"]["reference_event_scale"] - R["full_audit"]["scale"]),
                                 ("distance to one", R["distance_to_one"], 1 - R["full_audit"]["scale"])):
            if abs(got - want) > 1e-18:
                failures.append(f"eps {k} {label}: stated {got!r}, the difference is {want!r}")
    return failures


def equalized(w):
    out = dict(w["focused"]["focused_equalization"])
    out.update(w["peak"]["peak_scan"])
    return out


def l4_equalized(w):
    failures = []
    ref = w["summary"]["reference_event_scale"]
    for k, R in equalized(w).items():
        s, mins, _ = least(w, R["parameters"], float(k))
        if abs(s - R["best_scale"]) > 1e-10:
            failures.append(f"eps {k}: least scale {s!r}, stated {R['best_scale']!r}")
        for row in R["audits"]:
            if abs(row["scale"] - s) > 1e-10:
                failures.append(f"eps {k}: audit on {row['curve_grid']}/{row['phase_grid']} gives {row['scale']!r}")
        if len(mins) != R["audits"][-1]["local_minimum_count"]:
            failures.append(f"eps {k}: {len(mins)} local minima, stated {R['audits'][-1]['local_minimum_count']}")
        if abs(R["gain_over_event"] - (R["best_scale"] - ref)) > 1e-18:
            failures.append(f"eps {k}: gain {R['gain_over_event']!r}")
        if abs(R["tracked_spread"] - (max(R["tracked_values"]) - min(R["tracked_values"]))) > 1e-18:
            failures.append(f"eps {k}: tracked spread")
    S = w["summary"]
    if S["focused_equalization"] != w["focused"] or S["peak_scan"] != w["peak"]:
        failures.append("the summary's equalization records are not the data files")
    return failures


def l5_best(w):
    failures = []
    B = w["summary"]["best_verified_candidate"]
    s, mins, _ = least(w, B["parameters"], B["epsilon"])
    at = min(mins, key=lambda m: m[1])[0]
    if abs(s - B["stationary_support_scale"]) > 1e-13:
        failures.append(f"best: least scale {s!r}, stated {B['stationary_support_scale']!r}")
    if abs(math.remainder(at - 3 * math.pi / 2, 2 * math.pi)) > 1e-12:
        failures.append(f"best: least at phase {at!r}, not 3pi/2")
    ref = w["summary"]["reference_event_scale"]
    if abs(B["gain_over_event"] - (B["dense_pointcloud_exact_cusp_scale"] - ref)) > 1e-18:
        failures.append("best: the gain is not the point cloud's value minus the event scale")
    pk = w["peak"]["peak_scan"]["0.037"]
    if list(B["parameters"]) != list(pk["parameters"]) or B["stationary_support_scale"] != pk["best_scale"]:
        failures.append("best: not the peak scan's eps = 0.037 record")
    M = w["manifest"]
    for label, got, want in (("manifest eps", M["best_epsilon"], B["epsilon"]), ("manifest scale", M["best_scale"], B["stationary_support_scale"]),
                             ("manifest gain", M["gain_over_event"], B["stationary_support_scale"] - ref)):
        if abs(got - want) > 1e-18:
            failures.append(f"{label}: stated {got!r}, the data {want!r}")
    return failures


def l6_cloud(w):
    failures = []
    ref = w["summary"]["reference_event_scale"]
    for tag, C in (("eps 0.04", w["cloud"]), ("eps 0.037", w["peak_cloud"])):
        wing = wing_of(C["parameters"], C["epsilon"])
        figs = [(b["phase"], b["scale"]) for b in C["branches"]]
        figs += [(2 * math.pi / 3, C["special_phases"]["120deg"]), (3 * math.pi / 2, C["special_phases"]["270deg"]),
                 (C["pointcloud_global_with_exact_cusps"]["phase"], C["pointcloud_global_with_exact_cusps"]["scale"])]
        for ph, v in figs:
            exact = scale(w, wing, ph)
            if not -1e-11 <= v - exact <= 1e-13:
                failures.append(f"{tag}: the cloud's {v!r} at {ph:.9f} vs the exact {exact!r}")
        s, _, _ = least(w, C["parameters"], C["epsilon"])
        if abs(C["stationary_support_scale"] - s) > 1e-12:
            failures.append(f"{tag}: stationary support {C['stationary_support_scale']!r}, this run {s!r}")
        for label, got, want in (("difference", C["difference_pointcloud_minus_stationary"],
                                  C["pointcloud_global_with_exact_cusps"]["scale"] - C["stationary_support_scale"]),
                                 ("gain", C["gain_over_event"], C["pointcloud_global_with_exact_cusps"]["scale"] - ref)):
            if abs(got - want) > 1e-18:
                failures.append(f"{tag} {label}: stated {got!r}, the difference is {want!r}")
        if C["points"] != 240017:
            failures.append(f"{tag}: {C['points']} points")
    return failures


def ledger(wing):
    u = np.linspace(0, 1, 200001)
    k = np.abs(wing.d * np.gradient(wing.F(u), u)) / wing.w          # |d theta / d s|
    Fv = wing.F(u)
    # F(u) = f solves to u = c - eps atanh(T1 + f (T0 - T1)): the width between F = 0.95 and F = 0.05, in arc length
    width = wing.w * wing.eps * (math.atanh(wing.T1 + 0.95 * (wing.T0 - wing.T1)) - math.atanh(wing.T1 + 0.05 * (wing.T0 - wing.T1)))
    peak = wing.d * (1 / wing.eps) / (wing.T0 - wing.T1) / wing.w
    return {"peak_abs_curvature": peak, "total_turning": wing.d, "effective_width_5_95": width,
            "curvature_centroid_u": float((u * k).sum() / k.sum())}


def ledger_items(w):
    items = [(k, R["parameters"], float(k), R["curvature_ledger"], 2400) for k, R in w["summary"]["results"].items()]
    B = w["summary"]["best_verified_candidate"]
    items.append(("best", B["parameters"], B["epsilon"], B["curvature_ledger"], 12000))
    return items


def grid_ledger(wing, n):
    """the ledger as a grid of n equal steps of the wing gives it: the peak, the largest central difference
    delta |F'| / w on the grid; the 5-95 % width, the span of the grid points with F in [0.05, 0.95], in arc length"""
    u = np.linspace(0, 1, n + 1)
    Fv = wing.F(u)
    band = np.flatnonzero((Fv >= 0.05) & (Fv <= 0.95))
    return {"peak_abs_curvature": float(np.abs(wing.d * np.gradient(Fv, u)).max() / wing.w),
            "effective_width_5_95": float(wing.w * (u[band[-1]] - u[band[0]]))}


def l7_curvature(w):
    failures = []
    for k, P, eps, L, n in ledger_items(w):
        wing = wing_of(P, eps)
        mine, grid = ledger(wing), grid_ledger(wing, n)
        if abs(L["peak_abs_curvature"] / grid["peak_abs_curvature"] - 1) > 1e-10:
            failures.append(f"{k}: peak curvature {L['peak_abs_curvature']!r}, the grid's {grid['peak_abs_curvature']!r}")
        if abs(L["effective_width_5_95"] - grid["effective_width_5_95"]) > 1e-12:
            failures.append(f"{k}: width {L['effective_width_5_95']!r}, the grid's {grid['effective_width_5_95']!r}")
        for key, tol in (("total_turning", 1e-8), ("curvature_centroid_u", 1e-6)):
            if key in L and abs(L[key] - mine[key]) > tol:
                failures.append(f"{k}: {key} stated {L[key]!r}, this run {mine[key]!r}")
    return failures


def l8_consistency(w):
    failures = []
    S, B = w["summary"], w["summary"]["best_verified_candidate"]
    ref = S["reference_event_scale"]
    rd, rp = gate.squash(w["readme"]), gate.squash(w["report"])
    an, cn, pn = gate.squash(w["audit_note"]), gate.squash(w["cloud_note"]), gate.squash(w["peak_cloud_note"])

    def same(label, got, want, tol):
        if got is None or abs(got - want) > tol:
            failures.append(f"{label}: stated {got}, the data {want!r}")
    same("README event", num(r"五連桿事件尺度：(\d+\.\d+)", rd), ref, 6e-16)
    same("README eps", num(r"最佳測試寬度：(\d+\.\d+)", rd), B["epsilon"], 0)
    same("README stationary", num(r"駐點支撐尺度：(\d+\.\d+)", rd), B["stationary_support_scale"], 6e-16)
    same("README cloud", num(r"密集點雲精確尖點尺度：(\d+\.\d+)", rd), B["dense_pointcloud_exact_cusp_scale"], 6e-16)
    same("README gain", num(r"相對事件根提升：(\d+\.\d+e-?\d+)", rd), B["gain_over_event"], 6e-18)
    same("README difference", num(r"兩種支撐路徑差：(-\d+\.\d+e-?\d+)", rd), w["peak_cloud"]["difference_pointcloud_minus_stationary"], 6e-27)
    for row in table(w["report"], "追蹤分支差距 |"):
        R = equalized(w)[str(float(row[0])) if row[0] not in equalized(w) else row[0]]
        same(f"report table eps {row[0]}", float(row[1]), R["best_scale"], 6e-16)
        same(f"report table eps {row[0]} gain", float(row[2]), R["gain_over_event"], 6e-4 * abs(R["gain_over_event"]))
        same(f"report table eps {row[0]} spread", float(row[3]), R["tracked_spread"], 6e-4 * R["tracked_spread"])
    for row in table(w["report"][w["report"].index("峰值窄掃描"):], "高解析尺度"):
        R = w["peak"]["peak_scan"][row[0]]
        same(f"report peak eps {row[0]}", float(row[1]), R["best_scale"], 6e-16)
        same(f"report peak eps {row[0]} gain", float(row[2]), R["gain_over_event"], 6e-4 * abs(R["gain_over_event"]))
    w_, b_, d_, c_ = B["parameters"]
    same("report w", num(r"w=(\d+\.\d+),", rp), w_, 6e-16)
    same("report l0", num(r"l_0=(\d+\.\d+)", rp), 1 - 2 * w_, 6e-16)
    same("report beta", num(r"\\beta=(\d+\.\d+)\^\\circ", rp), math.degrees(b_), 6e-13)
    same("report delta", num(r"\\alpha-\\beta=(\d+\.\d+)\^\\circ", rp), math.degrees(d_), 6e-13)
    same("report alpha", num(r"\\alpha=(\d+\.\d+)\^\\circ,\\qquadc", rp), math.degrees(b_ + d_), 6e-13)
    same("report c", num(r"c=(\d+\.\d+)\.", rp), c_, 6e-16)
    same("report s*", num(r"\\boxed\{s_\*=(\d+\.\d+)\}", rp), B["stationary_support_scale"], 6e-16)
    same("report gain", num(r"\\boxed\{s_\*-s_0=(\d+\.\d+e-?\d+)\}", rp), B["stationary_support_scale"] - ref, 6e-18)
    same("report distance", num(r"1-s_\*=(\d+\.\d+e-?\d+)", rp), 1 - B["stationary_support_scale"], 6e-16)
    pk = w["peak"]["peak_scan"]["0.037"]
    for row, v, ph in zip(table(w["report"], "| 分支 | 相位 | 追蹤尺度 |"), pk["tracked_values"], pk["tracked_phases"]):
        same(f"report branch {row[0]}", float(row[2]), v, 6e-16)
        same(f"report branch {row[0]} phase", float(row[1]), ph, 6e-13)
    same("report tracked spread", num(r"追蹤分支差距：\$\$(\d+\.\d+e-?\d+)", rp), pk["tracked_spread"], 6e-21)
    for row, a in zip(table(w["report"], "曲線積分網格"), pk["audits"]):
        if int(row[0]) != a["curve_grid"] or int(row[1]) != a["phase_grid"] or abs(float(row[2]) - a["scale"]) > 6e-16 \
                or int(row[4]) != a["local_minimum_count"]:
            failures.append(f"report audit row {row[0]} is not the data's")
    same("report cloud", num(r"s_\{\\mathrm\{cloud\}\}=(\d+\.\d+)", rp), B["dense_pointcloud_exact_cusp_scale"], 6e-16)
    same("report cloud diff", num(r"s_\{\\mathrm\{cloud\}\}-s_\*=(-\d+\.\d+e-?\d+)", rp), w["peak_cloud"]["difference_pointcloud_minus_stationary"], 6e-27)
    L = B["curvature_ledger"]
    same("report peak curvature", num(r"\\\|\\kappa\\\|_\\infty=(\d+\.\d+)", rp), L["peak_abs_curvature"], 6e-13)
    same("report width", num(r"W_\{5\\%-95\\%\}=(\d+\.\d+)", rp), L["effective_width_5_95"], 6e-13)
    same("report turning", num(r"\\int\|\\kappa\|\\,ds\\approx(\d+\.\d+)", rp), L["total_turning"], 6e-13)
    C = w["cloud"]
    same("audit note s*", num(r"\\boxed\{s_\*=(\d+\.\d+)\}", an), equalized(w)["0.04"]["best_scale"], 6e-16)
    same("audit note gain", num(r"s_\*-s_0=(\d+\.\d+e-?\d+)", an), equalized(w)["0.04"]["gain_over_event"], 6e-18)
    same("audit note spread", num(r"四追蹤分支差距：\$\$(\d+\.\d+e-?\d+)", an), equalized(w)["0.04"]["tracked_spread"], 6e-21)
    same("cloud note stationary", num(r"s_\{\\mathrm\{stat\}\}=(\d+\.\d+)", cn), C["stationary_support_scale"], 6e-16)
    same("cloud note cloud", num(r"s_\{\\mathrm\{cloud\}\}=(\d+\.\d+)", cn), C["pointcloud_global_among_tracked"]["scale"], 6e-16)
    same("peak note stationary", num(r"駐點支撐法：\$s=(\d+\.\d+)\$", pn), B["stationary_support_scale"], 6e-16)
    same("peak note difference", num(r"方法差：\$(-\d+\.\d+e-?\d+)\$", pn), w["peak_cloud"]["difference_pointcloud_minus_stationary"], 6e-27)
    same("peak note gain", num(r"相對事件根：\$(\d+\.\d+e-?\d+)\$", pn), w["peak_cloud"]["gain_over_event"], 6e-18)
    same("report cloud gain", num(r"s_\{\\mathrm\{cloud\}\}-s_0=(\d+\.\d+e-?\d+)", rp), B["gain_over_event"], 6e-18)
    same("audit note eps", num(r"\\varepsilon_\*=(\d+\.\d+)\.", an), 0.04, 0)
    # the eps = 0.04 note's difference and gain are those of the cloud's value among the tracked branches
    tracked = C["pointcloud_global_among_tracked"]["scale"]
    same("cloud note difference", num(r"s_\{\\mathrm\{cloud\}\}-s_\{\\mathrm\{stat\}\}=(\d+\.\d+e-?\d+)", cn), tracked - C["stationary_support_scale"], 6e-21)
    same("cloud note gain", num(r"s_\{\\mathrm\{cloud\}\}-s_0=(\d+\.\d+e-?\d+)", cn), tracked - ref, 6e-18)
    same("peak note cloud", num(r"點雲在精確尖點的全域值：\$s=(\d+\.\d+)\$", pn), B["dense_pointcloud_exact_cusp_scale"], 6e-16)
    return failures


CHECKS = {"L1": l1_sweep_curves, "L2": l2_best_curve, "L3": l3_sweep_values, "L4": l4_equalized, "L5": l5_best,
          "L6": l6_cloud, "L7": l7_curvature, "L8": l8_consistency}
GEOM = {"legs", "cert_scale_divisor", "rot_sign", "formula_B"}
DEPENDS = {
    "L1": {"summary", "sweep_curves"},
    "L2": {"summary", "best_curve"},
    "L3": {"summary", "round05"} | GEOM,
    "L4": {"summary", "focused", "peak"} | GEOM,
    "L5": {"summary", "peak", "manifest"} | GEOM,
    "L6": {"summary", "cloud", "peak_cloud"} | GEOM,
    "L7": {"summary"},
    "L8": {"readme", "report", "audit_note", "cloud_note", "peak_cloud_note", "summary", "focused", "peak", "cloud", "peak_cloud"},
}


# ---------------------------------------------------------------- findings

def event_root_hp(wv, dps=40):
    mp.mp.dps = dps
    P = wv["round05"]["event_solution"]["parameters"]
    l1, l2, b, d = (mp.mpf(repr(P[k])) for k in ("l1", "l2", "beta_radians", "delta_radians"))
    a = b + d
    l3 = 1 - 2 * (l1 + l2)
    A = (3 + 4 * mp.sqrt(3)) / 18 / mp.mpf("1.0048")
    B = (4 + mp.sqrt(3)) / 6 / mp.mpf("1.0048")
    q1 = (l1 * mp.cos(a), l1 * mp.sin(a))
    q2 = (q1[0] + l2 * mp.cos(b), q1[1] + l2 * mp.sin(b))
    q3 = (q2[0] + l3, q2[1])
    D = 2 * l1 * mp.cos(a) + 2 * l2 * mp.cos(b) + l3
    X = lambda ph, q: q[0] * mp.cos(ph) - q[1] * mp.sin(ph)
    Y = lambda ph, q: q[0] * mp.sin(ph) + q[1] * mp.cos(ph)
    H = lambda ph, q: X(ph, q) / A + Y(ph, q) / B
    f1, f2, f3 = mp.pi / 2 - a, mp.pi / 2 - b, 2 * mp.pi / 3
    m = [H(f1, q3), H(f2, q3) - X(f2, q1) / A, -X(f3, q3) / A - Y(f3, q2) / B, q2[1] / A + (D - q2[0]) / B]
    return [mp.nstr(v, 22) for v in m]


def file_right_wing(wv, q, wing, nw, nc):
    """the best curve file after its centre: one junction chord, then a right wing of nw points. Against the candidate's
    right wing sampled at u = 1 - (k + 2/3)/nw (k = 0 .. nw - 1), measured from the curve's start point; and what the
    file's least scale becomes with the candidate's right wing restored, or with only the true endpoint appended"""
    right = q[nw + nc + 1:] - q[0]
    u = 1 - (np.arange(nw) + 2 / 3) / nw
    left = wing.pos(u)
    model = np.stack([2 * wing.mid - left[:, 0], left[:, 1]], 1)
    P3 = np.array([wing.P2[0] + wing.P1[0], 0.0])
    true_right = wing.points(nw, 34)[nw + 34:]
    restored = np.concatenate([q[:nw + nc] - q[0], true_right])
    with_end = np.concatenate([q - q[0], P3[None, :]])
    corner = q[nw] - q[0] + np.array([wing.l0, 0.0])
    with_corner = np.concatenate([q[:nw + nc + 1] - q[0], corner[None, :], q[nw + nc + 1:] - q[0]])
    with_both = np.concatenate([with_corner, P3[None, :]])
    s_restored = min(exact_min(wv, restored)[0], exact_min(wv, mirror(restored))[0])
    s_end = min(exact_min(wv, with_end)[0], exact_min(wv, mirror(with_end))[0])
    s_corner = min(exact_min(wv, with_corner)[0], exact_min(wv, mirror(with_corner))[0])
    s_both = min(exact_min(wv, with_both)[0], exact_min(wv, mirror(with_both))[0])
    return {"right_wing_points": int(len(right)), "right_wing_vs_candidate_at_offset_samples": float(np.abs(right - model).max()),
            "endpoint_gap_candidate_minus_file": (P3 - right[-1]).tolist(),
            "centre_end_over_candidate_centre": float((q[nw + nc][0] - q[nw][0]) / wing.l0),
            "least_with_candidate_right_wing_restored": s_restored, "least_with_true_endpoint_appended": s_end,
            "least_with_corner_inserted": s_corner, "least_with_corner_and_endpoint_added": s_both}


def cloud_note_reading(w):
    """the eps = 0.04 note's 'difference between the two methods' compares the cloud at the tracked B3 phase, just
    beside the 120-degree cusp, with the stationary least at 270 degrees; the record's own method difference is at the
    exact cusp"""
    C = w["cloud"]
    s, mins, wing = least(w, C["parameters"], C["epsilon"])
    tr = C["pointcloud_global_among_tracked"]
    return {"note_difference": tr["scale"] - C["stationary_support_scale"],
            "record_method_difference": C["difference_pointcloud_minus_stationary"],
            "exact_at_tracked_phase_minus_least": scale(w, wing, tr["phase"]) - s,
            "exact_at_2pi_3_minus_least": scale(w, wing, 2 * math.pi / 3) - s,
            "tracked_phase_minus_2pi_3": math.remainder(tr["phase"] - 2 * math.pi / 3, 2 * math.pi),
            "record_gain": C["gain_over_event"]}


def corner_cut(q, wing, nw, nc):
    """the distance from the candidate's corner (its centre's end) to the file's junction chord"""
    a, b = q[nw + nc], q[nw + nc + 1]
    corner = q[nw] + np.array([wing.l0, 0.0])
    e, f = b - a, corner - a
    return float(abs(e[0] * f[1] - e[1] * f[0]) / np.linalg.norm(e))


def cloud_figures(w):
    """each point-cloud figure minus the exact scale at its phase"""
    out = {}
    for tag, C in (("0.04", w["cloud"]), ("0.037", w["peak_cloud"])):
        wing = wing_of(C["parameters"], C["epsilon"])
        figs = [(b.get("name", f"branch {i + 1}"), b["phase"], b["scale"]) for i, b in enumerate(C["branches"])]
        figs += [("120deg", 2 * math.pi / 3, C["special_phases"]["120deg"]), ("270deg", 3 * math.pi / 2, C["special_phases"]["270deg"]),
                 ("global with exact cusps", C["pointcloud_global_with_exact_cusps"]["phase"], C["pointcloud_global_with_exact_cusps"]["scale"])]
        out[tag] = {name: v - scale(w, wing, ph) for name, ph, v in figs}
    return out


def margins(w, sweep_dev, sweep_vals, clouds):
    """each tolerance over the largest deviation it admits on the package"""
    peak, width = 0.0, 0.0
    for k, P, eps, L, n in ledger_items(w):
        grid = grid_ledger(wing_of(P, eps), n)
        peak = max(peak, abs(L["peak_abs_curvature"] / grid["peak_abs_curvature"] - 1))
        width = max(width, abs(L["effective_width_5_95"] - grid["effective_width_5_95"]))
    low = -min(v for c in clouds.values() for v in c.values())
    return {"L1_curve": 1e-7 / max(sweep_dev.values()),
            "L3_values": 2e-8 / max(abs(v) for r in sweep_vals.values() for v in r.values()),
            "L6_lower": 1e-11 / low,
            "L7_peak": 1e-10 / peak,
            "L7_width": 1e-12 / width if width else None}


def findings(w):
    B = w["summary"]["best_verified_candidate"]
    ref = w["summary"]["reference_event_scale"]
    s, mins, wing = least(w, B["parameters"], B["epsilon"])
    hp = hp_cusp(B["parameters"], B["epsilon"])
    q = w["best_curve"]
    sp, sm = exact_min(w, q)[0], exact_min(w, mirror(q))[0]
    d = np.diff(q, axis=0)
    L = np.linalg.norm(d, axis=1)
    centre = np.flatnonzero(np.abs(np.arctan2(d[:, 1], d[:, 0])) < 1e-12)
    pk = w["peak"]["peak_scan"]["0.037"]
    true4 = [min(mins, key=lambda m: abs(math.remainder(m[0] - ph, 2 * math.pi)))[1] for ph in pk["tracked_phases"]]
    sweep_dev = {k: curve_dev(w["sweep_curves"][k], wing_of(R["parameters"], float(k)).points(2400, 49))
                 for k, R in w["summary"]["results"].items()}
    hp_peak = {k: float(hp_cusp(R["parameters"], float(k), 30) - mp.mpf(repr(least(w, R["parameters"], float(k))[0])))
               for k, R in w["peak"]["peak_scan"].items()}
    sweep_vals = {k: {"full": R["full_audit"]["scale"] - least(w, R["parameters"], float(k))[0],
                      "event_parameters": R["fixed_event_parameters_audit"]["scale"] - least(w, event_params(w), float(k))[0]}
                  for k, R in w["summary"]["results"].items()}
    clouds = cloud_figures(w)
    return {
        "best_high_precision": {"scale_at_3pi_2_40_digits": mp.nstr(hp, 25), "minus_double": float(hp - mp.mpf(repr(s))),
                                "gain_over_event": mp.nstr(hp - mp.mpf(repr(ref)), 15),
                                "minus_stated_stationary": float(hp - mp.mpf(repr(B["stationary_support_scale"]))),
                                "minus_stated_cloud": float(hp - mp.mpf(repr(B["dense_pointcloud_exact_cusp_scale"])))},
        "best_minima": mins,
        "best_true_branches_at_tracked_phases": true4,
        "best_tracked_minus_true": [t - v for t, v in zip(pk["tracked_values"], true4)],
        "best_tracked_minus_exact_at_tracked_phase": [t - scale(w, wing, ph) for t, ph in zip(pk["tracked_values"], pk["tracked_phases"])],
        "best_tracked_phase_minus_cusp": [math.remainder(pk["tracked_phases"][2] - 2 * math.pi / 3, 2 * math.pi),
                                          math.remainder(pk["tracked_phases"][3] - 3 * math.pi / 2, 2 * math.pi)],
        "event_root_branches_40_digits": event_root_hp(w),
        "best_width_stated_over_w_times_12000": B["curvature_ledger"]["effective_width_5_95"] / wing.w * 12000,
        "cloud_eps_0.04_note": cloud_note_reading(w),
        "peak_scan_cusp_high_precision_minus_double": hp_peak,
        "best_curve_file": {"points": int(len(q)), "congruent_least_scale_as_polyline": min(sp, sm), "plus": sp, "minus": sm,
                            "below_event": min(sp, sm) - ref, "length": float(L.sum()),
                            "centre_length": float(L[centre].sum()), "candidate_centre": wing.l0,
                            "centre_segments": int(len(centre)), "largest_chord": float(L.max()),
                            "largest_chord_angle_degrees": float(np.degrees(np.arctan2(d[int(L.argmax()), 1], d[int(L.argmax()), 0]))),
                            "junction_chord": [float(L[int(centre.max()) + 1]),
                                               float(np.degrees(np.arctan2(d[int(centre.max()) + 1, 1], d[int(centre.max()) + 1, 0])))],
                            "corner_cut": corner_cut(q, wing, int(centre.min()), int(len(centre))),
                            "right_wing": file_right_wing(w, q, wing, int(centre.min()), int(len(centre)))},
        "sweep_curve_files_minus_exact": sweep_dev,
        "event_parameters_small_eps": {k: least(w, event_params(w), float(k))[0] - ref
                                       for k in ("0.008", "0.005", "0.003", "0.002", "0.001", "0.0005", "0.00025")},
        "event_parameters_small_eps_rise_over_eps": {k: (least(w, event_params(w), float(k))[0] - ref) / float(k)
                                                     for k in ("0.008", "0.005", "0.003", "0.002", "0.001", "0.0005", "0.00025")},
        "ledger_grid": {k: {"peak_stated_over_grid_minus_1": L["peak_abs_curvature"] / grid_ledger(wing_of(P, eps), n)["peak_abs_curvature"] - 1,
                            "width_over_step": L["effective_width_5_95"] / (wing_of(P, eps).w / n)}
                        for k, P, eps, L, n in ledger_items(w)},
        "sweep_values_minus_exact": sweep_vals,
        "sweep_least_phase_degrees": {k: math.degrees(min(least(w, R["parameters"], float(k))[1], key=lambda m: m[1])[0])
                                      for k, R in w["summary"]["results"].items()},
        "pointcloud_minus_exact": clouds,
        "check_margins": margins(w, sweep_dev, sweep_vals, clouds),
        "ledger_peak_stated_over_analytic": {k: R["curvature_ledger"]["peak_abs_curvature"] / ledger(wing_of(R["parameters"], float(k)))["peak_abs_curvature"]
                                             for k, R in w["summary"]["results"].items()},
        "best_ledger_exact": ledger(wing),
        "best_ledger_stated_minus_exact": {key: B["curvature_ledger"][key] - ledger(wing)[key]
                                           for key in ("peak_abs_curvature", "total_turning", "effective_width_5_95")},
        "equalized_minus_exact": {k: R["best_scale"] - least(w, R["parameters"], float(k))[0] for k, R in equalized(w).items()},
    }


# ---------------------------------------------------------------- the drill

def drill_cases(base):
    def edit(key, fn):
        v = copy.deepcopy(base[key])
        fn(v)
        return v
    Rs = lambda s, k: s["results"][k]
    s_par = edit("summary", lambda s: Rs(s, "0.05")["parameters"].__setitem__("transition_center", Rs(s, "0.05")["parameters"]["transition_center"] + 1e-4))
    def full(s):
        R = Rs(s, "0.012")
        R["full_audit"]["scale"] += 1e-7
        R["distance_to_event"] = s["reference_event_scale"] - R["full_audit"]["scale"]
        R["distance_to_one"] = 1 - R["full_audit"]["scale"]
    s_full = edit("summary", full)
    s_fixed = edit("summary", lambda s: Rs(s, "0.2")["fixed_event_parameters_audit"].__setitem__("scale", Rs(s, "0.2")["fixed_event_parameters_audit"]["scale"] + 1e-7))
    s_led = edit("summary", lambda s: s["best_verified_candidate"]["curvature_ledger"].__setitem__("peak_abs_curvature", 2.0926189248))
    new = 0.998914339085632
    ref = base["summary"]["reference_event_scale"]

    def best_rec(r):
        r["best_scale"] = new
        r["gain_over_event"] = new - ref

    def best_sum(s):
        s["best_verified_candidate"]["stationary_support_scale"] = new
        best_rec(s["peak_scan"]["peak_scan"]["0.037"])
    s_best = edit("summary", best_sum)
    pk_best = edit("peak", lambda p: best_rec(p["peak_scan"]["0.037"]))
    man_best = edit("manifest", lambda m: (m.__setitem__("best_scale", new), m.__setitem__("gain_over_event", new - ref)))
    # M7, M8: a record file and the summary's copy of it, planted alike
    def f_scale(f):
        R = f["focused_equalization"]["0.02"]
        R["best_scale"] += 1e-9
        R["gain_over_event"] = R["best_scale"] - ref
    foc = edit("focused", f_scale)
    s_foc = edit("summary", lambda s: f_scale(s["focused_equalization"]))
    p_par = lambda p: p["peak_scan"]["0.041"]["parameters"].__setitem__(3, p["peak_scan"]["0.041"]["parameters"][3] + 1e-6)
    pk = edit("peak", p_par)
    s_pk = edit("summary", lambda s: p_par(s["peak_scan"]))
    # M17: the summary's copy alone
    s_copy = edit("summary", lambda s: s["focused_equalization"]["focused_equalization"]["0.025"].__setitem__(
        "tracked_spread", s["focused_equalization"]["focused_equalization"]["0.025"]["tracked_spread"] * 2))
    cl = edit("cloud", lambda c: c["special_phases"].__setitem__("270deg", c["special_phases"]["270deg"] + 1e-10))
    man = edit("manifest", lambda m: m.__setitem__("best_scale", 0.998914339084633))
    sc = copy.deepcopy(base["sweep_curves"])
    sc["0.08"][100, 1] += 1e-6
    bc = base["best_curve"].copy()
    bc[1000, 0] += 1e-6
    rep = base["report"].replace("c=0.580178166885777", "c=0.580178166885787")
    readme = base["readme"].replace("密集點雲精確尖點尺度：0.998914339084602", "密集點雲精確尖點尺度：0.998914339084612")
    note = base["audit_note"].replace("3.782521451612e-08", "3.782521451622e-08")
    for a, b in ((rep, base["report"]), (readme, base["readme"]), (note, base["audit_note"])):
        assert a != b, "a plant must hit the raw text"
    a, b = base["legs"]
    return [
        ("K0-unmodified", "control", {}, set()),
        ("K1-report-crlf", "control", {"report": base["report"].replace("\n", "\r\n")}, set()),
        ("K2-sweep-curves-copied", "control", {"sweep_curves": copy.deepcopy(base["sweep_curves"])}, set()),
        ("K3-readme-trailing-spaces", "control", {"readme": "\n".join(l + " " for l in base["readme"].split("\n"))}, set()),
        ("M1-triangle-leg", "mutation", {"legs": (a * 1.0005, b)}, {"L3", "L4", "L5", "L6"}),
        ("M2-sweep-centre", "mutation", {"summary": s_par}, {"L1", "L3", "L7"}),
        ("M3-sweep-full-audit", "mutation", {"summary": s_full}, {"L3"}),
        ("M4-sweep-event-audit", "mutation", {"summary": s_fixed}, {"L3"}),
        ("M5-ledger-peak", "mutation", {"summary": s_led}, {"L7", "L8"}),
        ("M6-best-scale", "mutation", {"summary": s_best, "peak": pk_best, "manifest": man_best}, {"L5", "L8"}),
        ("M7-focused-scale", "mutation", {"focused": foc, "summary": s_foc}, {"L4", "L8"}),
        ("M8-peak-parameter", "mutation", {"peak": pk, "summary": s_pk}, {"L4"}),
        ("M9-cloud-cusp", "mutation", {"cloud": cl}, {"L6"}),
        ("M10-manifest", "mutation", {"manifest": man}, {"L5"}),
        ("M11-sweep-curve-point", "mutation", {"sweep_curves": sc}, {"L1"}),
        ("M12-best-curve-point", "mutation", {"best_curve": bc}, {"L2"}),
        ("M13-report-digit", "mutation", {"report": rep}, {"L8"}),
        ("M14-readme-digit", "mutation", {"readme": readme}, {"L8"}),
        ("M15-audit-note-digit", "mutation", {"audit_note": note}, {"L8"}),
        ("M16-formula-term", "mutation", {"formula_B": lambda B: 2 * B}, {"L3", "L4", "L5", "L6"}),
        ("M17-summary-copy", "mutation", {"summary": s_copy}, {"L4"}),
    ]


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--drill", action="store_true")
    ap.add_argument("--blind", metavar="CID")
    ap.add_argument("--log", default=None)
    args = ap.parse_args()
    if args.blind:
        CHECKS[args.blind] = lambda w: []
        args.drill = True
    w = build_world()
    results = {cid: fn(w) for cid, fn in CHECKS.items()}
    for cid, f in results.items():
        print(f"{cid} {'PASS' if not f else 'FAIL'}  ({len(f)} failures)")
        for x in f[:6]:
            print("    ", x)
    log = {"run": "RUN-009",
           "subject": "Round 08 (v0.8.3): the finite-width tanh curvature layer and its candidate gain over the event five-link",
           "package": {"id": RID, "sha256": sha256(source_bytes(RID))},
           "checks": {cid: {"pass": not f, "failures": f} for cid, f in results.items()},
           "findings": None if args.blind else findings(w)}
    if log["findings"]:
        print(json.dumps(log["findings"], indent=1)[:6000])
    if args.drill:
        drill = gate.run_drill(build_world, CHECKS, DEPENDS, drill_cases(build_world()))
        log["drill"] = gate.summarize(drill, CHECKS)
        print(gate.report_drill(log["drill"]))
        for d in drill:
            if not d["ok"]:
                print("   DRILL FAIL", d)
    if args.blind:
        seen = sum(1 for d in log["drill"]["cases"] if args.blind in d["expected"] and args.blind not in d["tripped"])
        print(f"blind {args.blind}: reported blind in {seen} cases (log not written)")
        return
    if args.drill:
        path = pathlib.Path(args.log) if args.log else LOG
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(json.dumps(log, ensure_ascii=False, indent=1) + "\n", encoding="utf-8", newline="\n")


if __name__ == "__main__":
    main()
