"""RUN-025 - Round 22: the symmetry-breaking Fourier witness oracle and the proof-cost Pareto search.

Round 22 opens odd Fourier modes k = 3..11 on an interiorised B7,
(1 - lambda) h_B7 + lambda/2 + sum (a_k cos k theta + b_k sin k theta), with a sufficient curvature
budget; states that any mode not a multiple of 7 costs a full 2 pi orientation domain; shows a
B7/B3 mixture whose reduced-period basin hides a lower one; finds no full-orientation candidate
that beats regular B7 on Round 20's four marked cells; and opens a second branch, pure harmonics
h = 1/2 + a cos k theta at 90% of their legality bound, compared with B7 by search minima and by a
generic support-core lift pilot on the tracked depth-50 cell. It ends in a proof-cost Pareto map:
B7 the primary closer, H11/H13 balanced auxiliaries, H17/H19 cheap but razor-thin. Here the
legality rules are checked, every witness is searched again on the four cells - B7 and the
mixture with the exact hull area, the smooth witnesses with a bracketed one - the lift pilot is
rebuilt node for node, and the same lifts are run with dense cores and with the support's own
motion bound, down to where each closes or is shown unable to.

Checks
  A0 anchors      the numbers and formulas below occur in Round 22 as written
  W1 legality     sec. 2-4, 9-12: width, the curvature budget and its sharpness, the recorded
                  candidate's budget; the pure-harmonic bound, reserve and amplitudes; symmetry
  W2 B7           sec. 7: regular B7 on the four marked cells, searched with the exact area
  W3 mixture      sec. 5: 0.92 B7 + 0.08 B3 as exact arcs; its basins
  W4 multi-mode   sec. 7: the recorded candidate searched over the full period, bracketed
  W5 harmonics    sec. 13-15 and the coarse scan: H7-H19 on the four cells, bracketed
  W6 pilot        sec. 16-18: the depth-20/22 lift pilot rebuilt; roots, volumes, tail rates
  W7 lift         the same lifts with dense cores and with the support's motion bound; the
                  limit each witness's bound can reach on the cell
  W8 code         what the package ships
  P1 package      the Pareto summary, the oracle spec, the crystal and the text agree
  P2 package      VALIDATION against the archive; its checks from the data
  R1 registry     Round 22's judgments reviewed, first-used statuses defined

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

import numpy as np
from scipy.optimize import minimize
from scipy.spatial import ConvexHull

import gate
import registry
import run008_round05_saturation_gate as r8
import run009_round06_witness_exchange as r9
import run011_round08_conditional_lift as r11
import run012_round09_adaptive_atlas as r12
import run013_round10_reference_dry_run as r13
import run019_round16_global_pilot as r19
import run020_round17_d3_cpg as r20
import run022_round19_necessity_lift as r22
import run023_round20_mixed_escalation as r23
from corpus import SOURCES, TREE, source_bytes, walk_sources
from run009_round06_witness_exchange import placed_disc, placed_reuleaux
from run010_round07_minimizer_atlas import d_star, t_text
from run012_round09_adaptive_atlas import piece_arrays, pieces_support, support_matrix
from run013_round10_reference_dry_run import contact_points

PKG = "main.zip!/AMRAL_LUC_FC_Round_22_Package_v0.1.zip!/"
DOC = PKG + "AMRAL_Lebesgue_Finite_Closure_Round_22_Fourier_Pareto_v0.1.md"
CRYSTAL = PKG + "AMRAL_LUC_FC_State_Crystal_Round_22_v0.1.md"
SPEC = PKG + "AMRAL_LUC_FC_Round_22_FOURIER_ORACLE_SPEC.json"
PARETO = PKG + "AMRAL_LUC_FC_Round_22_PARETO_SUMMARY.json"
VALIDATION = PKG + "AMRAL_LUC_FC_Round_22_VALIDATION.json"
REPRO = PKG + "AMRAL_LUC_FC_Round_22_repro.py"
R20_MANIFEST = "main.zip!/AMRAL_LUC_FC_Round_20_Package_v0.1.zip!/AMRAL_LUC_FC_Round_20_reference/mixed_shard/manifest.json"
R21_SYNTH = "main.zip!/AMRAL_LUC_FC_Round_21_Package_v0.1.zip!/AMRAL_LUC_FC_Round_21_SYNTHESIS_SUMMARY.json"
LOG = TREE / "data" / "gate-logs" / "run025-round22-fourier-pareto.json"
CACHE = TREE / "data" / "cache" / "run025-pareto.json"
MANIFEST = TREE / "data" / "SOURCE_MANIFEST.v1.json"

T, TM = 0.835, 0.8365
HARMONICS = (7, 9, 11, 13, 15, 17, 19)
PILOT = ((11, 20), (13, 20), (17, 22), (19, 22))       # sec. 17's witnesses and depths
ROOT_T, FRACTION = 0.21, 0.9                             # sec. 16's translation root, sec. 12's amplitude
SEARCH_STARTS, SEED = 28, 20260925
N_SEARCH, N_POLISH, N_BRACKET, N_DENSE = 6000, 24000, 64000, 4096
DENSE_MAX = 40

ANCHORS = {
    "W1": [r"q(\theta+\pi)=-q(\theta).", r"h(\theta)+h(\theta+\pi)=1.", r"(1-k^2)(a_k\cosk\theta+b_k\sink\theta).",
           r"\left|q+q''\right|\le\sum_k(k^2-1)\sqrt{a_k^2+b_k^2}.", r"\sum_{k\in\mathcalK}(k^2-1)\sqrt{a_k^2+b_k^2}\le\frac{\lambda}{2}.",
           r"d=\gcd(7,S).", r"P_\phi=\frac{2\pi}{d}.", r"\text{orientation-domainlength}\times7.",
           r"r_k(\theta)=\frac12-(k^2-1)a\cos(k\theta).", r"|a|\le\frac{1}{2(k^2-1)}.", r"\sigma_k=\frac12-(k^2-1)|a|.",
           r"\delta\le\sigma_k", r"99.5\%,", r"\sigma_k=0.0025.", r"0.9\cdot\frac1{2(k^2-1)}.", r"\sigma=0.05.",
           r"a_{11}=0.00375.", r"7/11\approx0.636.", r"a_{13}\approx0.00267857,", r"7/13\approx0.538.", r"7/17\approx0.412.",
           r"7/19\approx0.368."],
    "W2": [r"\boxed{0.83692628.}"],
    "W3": [r"K=(1-0.08)B_7+0.08B_3.", r"0.83742146.", r"\boxed{0.83583910.}"],
    "W4": [r"0.83770073.", r"0.83733308.", r"0.83683248,", r"0.83677292,", r"0.83674967,", r"\boxed{0.83668617.}"],
    "W5": [r"\boxed{0.83574698.}", r"0.83578614\leA\le0.83581539.", r"\boxed{0.83563803.}", r"0.83567775\leA\le0.83569731.",
           r"\min_{\rmsearch}\approx0.83507834.", r"\min_{\rmsearch}\approx0.83504963."],
    "W6": [r"[-0.21,0.21]^2.", r"[0,2\pi/k).", r"7037\text{nodes},", r"1.4107\times10^{-4}.", r"9623\text{nodes},",
           r"1.8536\times10^{-4}.", r"9211,", r"1.4270\times10^{-4}.", r"7399,", r"9.5317\times10^{-5}.", r"7221,",
           r"8.3671\times10^{-5}.", r"h_{\rmcore}=h-\delta"],
    "W7": [r"\text{cheapauxiliary/cell-specificwitness}", r"\text{CHEAP/RAZOR-THINAUXILIARY}", r"\text{BALANCEDAUXILIARY}",
           r"\text{PRIMARYROBUSTCLOSER}"],
}

CLAIMS = {
    # this tree's exact-area B7 search on Round 20's four cells
    "b7_minima": [0.8370777154, 0.8370210981, 0.8369847609, 0.8369262831],
    "b7_package_wrong_basin": [1],
    "b7_worst_text": 0.83692628,
    # the mixture on Round 21's image of q-dagger, exact arcs
    "mixture": {"full": 0.8358390980, "from_b7": 0.8374213467, "reduced": 0.8368710231, "reduced_min_on_the_edge": True},
    # the recorded multi-mode candidate: the facing of B7 that reproduces the package, and its minima
    "multimode_convention": "vertex at pi",
    "multimode_minima": [0.8368301985, 0.8367753081, 0.8367532965, 0.8366861861],
    # the pure harmonics at 90%: the least lower bracket over the four cells
    "harmonic_worst": {7: 0.8367395219, 9: 0.8354915864, 11: 0.8357638060, 13: 0.8356225717, 15: 0.8352261924,
                       17: 0.8350819469, 19: 0.8350481986},
    "coarse_signs": {7: "above", 9: "below", 11: "below", 13: "above", 15: "below", 17: "below", 19: "below"},
    "refined_signs": {11: "below", 13: "above", 17: "below", 19: "above"},
    "package_brackets_above_minimum": [11, 13],
    # the pilot with the support's own motion (depth 20 for H11/H13, 22 for H17/H19): nodes, open
    "pilot_support_motion": {11: [2893, 772], 13: [2737, 749], 17: [6225, 2111], 19: [5689, 2010]},
    "tail_rates": {"B7": 0.2576, "H17": 0.6934, "H19": 0.6819},
    # the depth-50 cell with its cores: the least hull area each witness's bound can reach
    "limits": {"B7": 0.8367313336, "H11": 0.8354118255, "H13": 0.8352941791, "H17": 0.8346707431, "H19": 0.8346480422},
    "cannot_close": ["H17", "H19"],
    # the same witnesses at the cell's centre with the whole base bodies: what a finer base cell tends to
    "centre_limits": {"H11": 0.8357992106, "H13": 0.8357061482, "H17": 0.8350991908, "H19": 0.8350827261},
    "dense_closes": {"B7": [21, 2509, 0], "H11-motion": [27, 21029, 0], "H11-support": [24, 1581, 0],
                     "H13-motion": [30, 43111, 0], "H13-support": [26, 3257, 0],
                     "H17-motion": [22, 7291, 1330], "H17-support": [22, 1677, 357], "H19-motion": [22, 6883, 1192],
                     "H19-support": [22, 1515, 348]},
    "code_facts": {"lines": 18, "functions": ["legality_budget", "pure_harmonic"], "searches_or_hulls": False, "lifts": False,
                   "absolute_paths": False, "legality_formulas": True},
    "balanced_margins": [0.0006, 0.0007],
}

# ---------------------------------------------------------------- witnesses (sec. 1-5, 9)

def amp(k, f=FRACTION):
    return f / (2 * (k * k - 1))


def reserve(k, a):
    return 0.5 - (k * k - 1) * abs(a)


def _owner(pieces, t):
    C, rho, ranged = piece_arrays(pieces)
    k = int(np.argmax(support_matrix(C, rho, ranged, np.array([t]))[:, 0]))
    return C[k], rho[k]


def mixture(lam, phi, t):
    """(1 - lam) B7 + lam B3, both turned by phi, moved by t, as exact pieces: on each interval
    where both owners are fixed the sum is one arc, its centre and radius the combinations of
    theirs (a radius 0 where both are vertices)"""
    b7, b3 = placed_reuleaux(7, phi, (0.0, 0.0)), placed_reuleaux(3, phi, (0.0, 0.0))
    cuts = sorted([(phi + math.pi / 14 + m * math.pi / 7) % (2 * math.pi) for m in range(14)]
                  + [(phi + math.pi / 6 + m * math.pi / 3) % (2 * math.pi) for m in range(6)])
    merged = [cuts[0]]
    for c in cuts[1:]:
        if c - merged[-1] > 1e-12:
            merged.append(c)
    if merged[0] + 2 * math.pi - merged[-1] <= 1e-12:
        merged.pop()
    out = []
    for i, s in enumerate(merged):
        e = merged[(i + 1) % len(merged)] + (2 * math.pi if i + 1 == len(merged) else 0.0)
        mid = (s + e) / 2
        c7, r7 = _owner(b7, mid)
        c3, r3 = _owner(b3, mid)
        out.append(((1 - lam) * c7 + lam * c3 + np.asarray(t, dtype=float), (1 - lam) * r7 + lam * r3, (mid, (e - s) / 2)))
    return out


def witness(spec):
    """(support, contact point) of a placement g = (phi, x, y) of the witness at directions th"""
    kind = spec["kind"]
    if kind == "harmonic":
        k, a = spec["k"], spec["a"]

        def sup(g, th):
            return 0.5 + a * np.cos(k * (th - g[0])) + g[1] * np.cos(th) + g[2] * np.sin(th)

        def con(g, th):
            h = sup(g, th)
            hp = -k * a * np.sin(k * (th - g[0])) - g[1] * np.sin(th) + g[2] * np.cos(th)
            return np.stack([h * np.cos(th) - hp * np.sin(th), h * np.sin(th) + hp * np.cos(th)], axis=1)
        return sup, con
    if kind == "multimode":
        lam, coef, turn, sgn = spec["lam"], spec["coef"], spec["turn"], spec["sign"]

        def four(g, th):
            s = th - g[0]
            q = sum(c[0] * np.cos(k * s) + sgn * c[1] * np.sin(k * s) for k, c in coef.items())
            qp = sum(k * (-c[0] * np.sin(k * s) + sgn * c[1] * np.cos(k * s)) for k, c in coef.items())
            return q, qp

        def sup(g, th):
            q, _ = four(g, th)
            return (1 - lam) * pieces_support(placed_reuleaux(7, g[0] + turn, (0.0, 0.0)), th) + lam / 2 + q \
                + g[1] * np.cos(th) + g[2] * np.sin(th)

        def con(g, th):
            q, qp = four(g, th)
            u = np.stack([np.cos(th), np.sin(th)], axis=1)
            up = np.stack([-np.sin(th), np.cos(th)], axis=1)
            return (1 - lam) * contact_points(placed_reuleaux(7, g[0] + turn, (0.0, 0.0)), th) \
                + (lam / 2 + q)[:, None] * u + qp[:, None] * up + np.array([g[1], g[2]])
        return sup, con
    pieces = (lambda g: mixture(spec["lam"], g[0], g[1:3])) if kind == "mixture" else \
        (lambda g: placed_reuleaux(spec["n"], g[0], g[1:3]))
    return (lambda g, th: pieces_support(pieces(g), th)), (lambda g, th: contact_points(pieces(g), th))


# ---------------------------------------------------------------- bracketed hull areas and searches

_BODIES, _BASE = {}, {}


def base_bodies(key):
    """a cell's base bodies at its centre, or the tracked depth-50 cell's common erosion cores"""
    kk = json.dumps(key)
    if kk not in _BODIES:
        if key[0] == "cell":
            q = np.asarray(key[1], dtype=float)
            _BODIES[kk] = [placed_disc(), placed_reuleaux(3, 0.0, q[:2]), placed_reuleaux(5, q[2], q[3:5])]
        else:
            c, h, _ = r23.branch(50)
            _BODIES[kk] = [placed_disc(), *r19.cores(np.asarray(c), np.asarray(h))]
    return _BODIES[kk]


def base_points(key, N):
    """the base's contact points at N directions, reduced to their hull's vertices"""
    kk = (json.dumps(key), N)
    if kk not in _BASE:
        th = 2 * np.pi * np.arange(N) / N
        pts = np.vstack([contact_points(p, th) for p in base_bodies(key)])
        _BASE[kk] = pts[ConvexHull(pts).vertices]
    return _BASE[kk]


def inner(key, spec, g, N):
    """the hull of true boundary points at N directions: never above the hull's area"""
    th = 2 * np.pi * np.arange(N) / N
    return float(ConvexHull(np.vstack([base_points(key, N), witness(spec)[1](g, th)])).volume)


def support_polygon(th, sups):
    """the polygon of the support lines at the sorted directions th: never below the area"""
    H = np.stack([s(th) for s in sups]).max(axis=0)
    dm = th - np.roll(th, 1)
    dm[0] += 2 * np.pi
    dp = np.roll(dm, -1)
    L = ((np.roll(H, 1) - H) + 2 * H * np.sin(dm / 2) ** 2) / np.sin(dm) \
        + ((np.roll(H, -1) - H) + 2 * H * np.sin(dp / 2) ** 2) / np.sin(dp)
    return 0.5 * math.fsum(H * L)


def kinks(th, sups):
    """the normals of the hull's bridging segments, where the owning body changes: a support
    polygon missing them overshoots by O(L^2 / N) each, one that has them by O(1/N^2)"""
    own = np.argmax(np.stack([s(th) for s in sups]), axis=0)
    out = []
    for i in np.nonzero(own != np.roll(own, -1))[0]:
        a, b = own[i], own[(i + 1) % len(th)]
        lo, hi = th[i], th[i] + 2 * np.pi / len(th)
        for _ in range(60):
            m = (lo + hi) / 2
            if sups[a](np.array([m]))[0] >= sups[b](np.array([m]))[0]:
                lo = m
            else:
                hi = m
        out.append((lo + hi) / 2 % (2 * np.pi))
    return out


def bracket(key, spec, g, N):
    sup = witness(spec)[0]
    sups = [lambda t, p=p: pieces_support(p, t) for p in base_bodies(key)] + [lambda t: sup(g, t)]
    th = 2 * np.pi * np.arange(N) / N
    return [inner(key, spec, g, N), support_polygon(np.unique(np.concatenate([th, kinks(th, sups)])), sups)]


def _search(args):
    key, spec, g0, N = args
    r = minimize(lambda g: inner(key, spec, g, N), g0, method="Nelder-Mead",
                 options={"xatol": 1e-10, "fatol": 1e-13, "maxiter": 3000, "maxfev": 4000})
    return [float(r.fun), [float(v) for v in r.x]]


def starts(rng, period, n=SEARCH_STARTS):
    return [[rng.uniform(0, period), rng.uniform(-0.02, 0.02), rng.uniform(-0.02, 0.02)] for _ in range(n)]


def search(pool, key, spec, st):
    """the starts searched at N_SEARCH, the best four polished at N_POLISH, the best bracketed
    at N_BRACKET"""
    coarse = sorted(pool.map(_search, [(key, spec, g, N_SEARCH) for g in st]))
    fine = sorted(pool.map(_search, [(key, spec, r[1], N_POLISH) for r in coarse[:4]]))
    return {"coarse": coarse, "fine": fine, "bracket": bracket(key, spec, fine[0][1], N_BRACKET)}


def exact_area(key, spec, g):
    """the exact hull area, for witnesses made of arcs"""
    pieces = mixture(spec["lam"], g[0], g[1:3]) if spec["kind"] == "mixture" else placed_reuleaux(spec["n"], g[0], g[1:3])
    return r19.exact_area([p for body in base_bodies(key) for p in body] + pieces)


def _polish(args):
    """an exact-area polish; with a period, phi is held to [0, period]"""
    key, spec, g0, fev, period = args
    kw = {"bounds": [(0.0, period), (-0.05, 0.05), (-0.05, 0.05)]} if period else {}
    r = minimize(lambda g: exact_area(key, spec, g), g0, method="Nelder-Mead",
                 options={"xatol": 1e-11, "fatol": 1e-15, "maxiter": fev, "maxfev": fev}, **kw)
    return [float(r.fun), [float(v) for v in r.x]]


# ---------------------------------------------------------------- the generic support-core lift (sec. 16-17)

def delta(kind, k, a, h):
    """how far the placed witness's support can fall over a box of half-widths h: the pilot's
    boundary-point motion |t| + 2 R sin(h_phi / 2), R = 1/2 + |a| the witness's radius; or the
    support's own motion |t| + 2 |a| sin(k h_phi / 2)"""
    if kind == "motion":
        return math.hypot(h[1], h[2]) + 2 * (0.5 + abs(a)) * math.sin(h[0] / 2)
    return math.hypot(h[1], h[2]) + 2 * abs(a) * math.sin(min(k * h[0] / 2, math.pi / 2))


def harmonic_core(k, a, g, dl, th):
    """the contact points of h - delta: a legal support while delta <= the reserve"""
    h = 0.5 + a * np.cos(k * (th - g[0])) + g[1] * np.cos(th) + g[2] * np.sin(th) - dl
    hp = -k * a * np.sin(k * (th - g[0])) - g[1] * np.sin(th) + g[2] * np.cos(th)
    return np.stack([h * np.cos(th) - hp * np.sin(th), h * np.sin(th) + hp * np.cos(th)], axis=1)


_CORES = {}


def _core_points(c, hc, dense):
    kk = (tuple(c), tuple(hc), dense)
    if kk not in _CORES:
        k3, k5 = r19.cores(np.asarray(c, dtype=float), np.asarray(hc, dtype=float))
        if dense:
            th = 2 * np.pi * np.arange(N_DENSE) / N_DENSE
            pts = np.vstack([contact_points(p, th) for p in (placed_disc(), k3, k5)])
            _CORES[kk] = pts[ConvexHull(pts).vertices]
        else:
            _CORES[kk] = np.vstack([r19.DISC] + [contact_points(p, r19.TH) for p in (k3, k5)])
    return _CORES[kk]


def _hvalue(args):
    """a box's lower bound: the hull of the disc, the base cores and the witness core - the
    pilot's 40 directions, or N_DENSE; pi/4 while the core is not a legal support"""
    c, hc, k, a, wc, dl, dense = args
    if dl > reserve(k, a):
        return math.pi / 4
    th = 2 * np.pi * np.arange(N_DENSE) / N_DENSE if dense else r19.TH
    return float(ConvexHull(np.vstack([_core_points(c, hc, dense), harmonic_core(k, a, wc, dl, th)])).volume) - r19.PAD


def hlift(pool, c, hc, k, kind, dense, max_depth):
    """H_k's lift tree: root phi in [0, 2 pi/k), |x|, |y| <= 0.21; RUN-023's split - the least
    child delta, ties to phi then x; a box closes at T. Per depth: (nodes so far, closed so
    far, open at that depth)"""
    a = amp(k)
    level = [((math.pi / k, 0.0, 0.0), (math.pi / k, ROOT_T, ROOT_T))]
    per, nodes, closed = {}, 0, 0
    for d in range(max_depth + 1):
        vals = pool.map(_hvalue, [(list(c), list(hc), k, a, wc, delta(kind, k, a, wh), dense) for wc, wh in level], chunksize=16)
        nodes += len(level)
        opened = [(wc, wh) for (wc, wh), v in zip(level, vals) if v < T]
        closed += len(level) - len(opened)
        per[d] = [nodes, closed, len(opened)]
        if not opened or d == max_depth:
            break
        level = []
        for wc, wh in opened:
            trial = []
            for ax in range(3):
                hh = list(wh)
                hh[ax] /= 2
                trial.append(delta(kind, k, a, hh))
            ax = int(np.argmin(trial))
            hh = list(wh)
            hh[ax] /= 2
            lo, hi = list(wc), list(wc)
            lo[ax] -= hh[ax]
            hi[ax] += hh[ax]
            level += [(tuple(lo), tuple(hh)), (tuple(hi), tuple(hh))]
    return per


# ---------------------------------------------------------------- the computation

MM_CONVENTIONS = {"vertex at pi": (math.pi / 7, 1.0), "vertex at 0": (0.0, 1.0),
                  "vertex at pi, mirrored": (math.pi / 7, -1.0), "vertex at 0, mirrored": (0.0, -1.0)}


def multimode_spec(pareto, convention):
    """the recorded candidate. The text writes h_B7 without saying which way B7 faces, nor which
    way theta runs: a B7 with a vertex at theta = 0 or at pi, the sine terms as written or mirrored"""
    fb = pareto["full_symmetry_breaking_candidate"]
    turn, sign = MM_CONVENTIONS[convention]
    return {"kind": "multimode", "lam": fb["lambda"], "coef": {int(k): v for k, v in fb["coefficients"].items()},
            "turn": turn, "sign": sign}


def basin(phi):
    """which of B7's two channels a phase lies in (RUN-024: 7 phi near 2.45 or 5.89)"""
    return "A" if (phi % (2 * math.pi / 7)) < 0.6 else "B"


def channels(results):
    """the best placement found in each of B7's two channels"""
    return {b: min(r for r in results if basin(r[1][0]) == b)[1] for b in ("A", "B")}


def compute(cells, pareto, q21, g21):
    out = {}
    rng = np.random.default_rng(SEED)
    c50, h50, _ = r23.branch(50)
    keys = [["cell", q] for q in cells]
    with Pool(14) as pool:
        out["b7"] = [pool.map(r23._search, [(q, 7, g) for g in starts(rng, 2 * math.pi / 7)]) for q in cells]
        mix, key = {"kind": "mixture", "lam": 0.08}, ["cell", q21]
        spread = [[2 * math.pi * j / 28 + rng.uniform(0, 2 * math.pi / 28), rng.uniform(-0.015, 0.015), rng.uniform(-0.015, 0.015)]
                  for j in range(28)]
        out["mixture"] = {"full": pool.map(_polish, [(key, mix, g, 2500, None) for g in spread]),
                          "from_b7": pool.apply(_polish, ((key, mix, g21, 2500, None),)),
                          "reduced": pool.map(_polish, [(key, mix, g, 2500, 2 * math.pi / 7) for g in [g21] + starts(rng, 2 * math.pi / 7, 13)])}
        out["multimode"] = {}
        for name, (turn, _) in MM_CONVENTIONS.items():
            spec = multimode_spec(pareto, name)
            out["multimode"][name] = []
            for key, res in zip(keys, out["b7"]):
                ch = channels(res)
                st = [[ch[b][0] - turn + 2 * math.pi * j / 7, ch[b][1], ch[b][2]] for j in range(7) for b in "AB"]
                out["multimode"][name].append(search(pool, key, spec, st + starts(rng, 2 * math.pi)))
        out["harmonic"] = {str(k): [search(pool, key, {"kind": "harmonic", "k": k, "a": amp(k)}, starts(rng, 2 * math.pi / k))
                                    for key in keys] for k in HARMONICS}
        out["pilot"] = {"B7": r23.lift(c50, h50, 7, False, pool, 22)["per"]}
        for k, d in PILOT:
            out["pilot"][str(k)] = {kind: hlift(pool, c50, h50, k, kind, False, d) for kind in ("motion", "support")}
        out["exact_B7"] = r23.lift(c50, h50, 7, True, pool, 34)["per"]
        out["dense"] = {str(k): {kind: hlift(pool, c50, h50, k, kind, True, DENSE_MAX if k in (11, 13) else d)
                                 for kind in ("motion", "support")} for k, d in PILOT}
        cores, centre = ["cores50"], ["cell", [float(v) for v in c50]]
        b7 = pool.map(_polish, [(cores, {"kind": "reuleaux", "n": 7}, g, 3000, None) for g in starts(rng, 2 * math.pi / 7)])
        out["limit"] = {"cores_alone": float(ConvexHull(base_points(cores, N_BRACKET)).volume), "B7": min(b7)}
        for k, _ in PILOT:
            spec = {"kind": "harmonic", "k": k, "a": amp(k)}
            out["limit"][str(k)] = search(pool, cores, spec, starts(rng, 2 * math.pi / k))
            out["limit"][f"{k}-centre"] = search(pool, centre, spec, starts(rng, 2 * math.pi / k))
    return out


def _code_key(files):
    digest = hashlib.sha256()
    for fn in (amp, reserve, _owner, mixture, witness, base_bodies, base_points, inner, support_polygon, kinks, bracket,
               _search, starts, search, exact_area, _polish, delta, harmonic_core, _core_points, _hvalue, hlift, multimode_spec,
               basin, channels, compute):
        digest.update(inspect.getsource(fn).encode())
    for mod in (r8, r9, r11, r12, r13, r19, r20, r22, r23):
        digest.update(open(mod.__file__, "rb").read())
    digest.update(files)
    digest.update(repr((HARMONICS, PILOT, ROOT_T, FRACTION, SEARCH_STARTS, SEED, N_SEARCH, N_POLISH, N_BRACKET, N_DENSE,
                        DENSE_MAX, MM_CONVENTIONS)).encode())
    return digest.hexdigest()


_COMPUTED = {}


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


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

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


def symmetry_order(sup, m_max=40, N=4096):
    """the largest m <= m_max with h(theta - 2 pi/m) = h(theta) at N directions"""
    th = 2 * np.pi * np.arange(N) / N
    h = sup(th)
    return max(m for m in range(1, m_max + 1) if np.max(np.abs(sup(th - 2 * np.pi / m) - h)) < 1e-13)


def b7_radius(th, phi=0.0):
    """B7's radius of curvature at the normal th: 1 on its arcs' normals, 0 at its vertices"""
    return np.where(np.abs(np.mod(th - phi - math.pi / 7, 2 * math.pi / 7) - math.pi / 7) > math.pi / 14, 1.0, 0.0)


def w1_legality(w):
    """sec. 2-4 and 9-12, analytic, checked on the recorded candidate and on random draws"""
    out, ps, sp = [], w["pareto"], w["spec"]
    fb = ps["full_symmetry_breaking_candidate"]
    coef = {int(k): v for k, v in fb["coefficients"].items()}
    lam = fb["lambda"]
    used = math.fsum((k * k - 1) * math.hypot(*c) for k, c in coef.items())
    if not near(used, fb["curvature_budget_used"], 1e-17) or not near(lam / 2, fb["curvature_budget_available"], 1e-17) \
            or not near(used / (lam / 2), fb["budget_fraction"], 1e-15) or not used <= lam / 2 \
            or sorted(coef) != sp["allowed_modes"]:
        out.append(f"the recorded candidate's budget: {used!r} of {lam / 2!r}")
    th = 2 * np.pi * np.arange(8192) / 8192
    sup = witness({"kind": "multimode", "lam": lam, "coef": coef, "turn": 0.0, "sign": 1.0})[0]
    h = sup((0.0, 0.0, 0.0), th)
    width = float(np.max(np.abs(h + np.roll(h, 4096) - 1)))
    rho = (1 - lam) * b7_radius(th) + lam / 2 + sum((1 - k * k) * (c[0] * np.cos(k * th) + c[1] * np.sin(k * th)) for k, c in coef.items())
    order = symmetry_order(lambda t: sup((0.0, 0.0, 0.0), t))
    if width > 1e-15 or float(rho.min()) < lam / 2 - used - 1e-15 or order != 1:
        out.append(f"the recorded candidate: width error {width:.1e}, least radius {rho.min():.3e}, symmetry order {order}")
    # the budget is sufficient on random draws, and sharp: one mode whose trough sits on a vertex's normals
    rng = np.random.default_rng(SEED)
    least, sharp = np.inf, []
    for _ in range(48):
        lam_ = rng.uniform(0.02, 0.2)
        ks = [k for k in (3, 5, 7, 9, 11) if rng.random() < 0.6] or [5]
        raw = {k: rng.normal(size=2) for k in ks}
        scale = lam_ / 2 / sum((k * k - 1) * math.hypot(*c) for k, c in raw.items())
        r = (1 - lam_) * b7_radius(th) + lam_ / 2 + sum((1 - k * k) * scale * (c[0] * np.cos(k * th) + c[1] * np.sin(k * th))
                                                         for k, c in raw.items())
        least = min(least, float(r.min()))
    for k in (3, 5, 7, 9, 11):
        a = 1.02 * lam / (2 * (k * k - 1))
        sharp.append(float(((1 - lam) * b7_radius(th) + lam / 2 + (1 - k * k) * a * np.cos(k * th)).min()) < 0)
    if least < -1e-15 or not all(sharp):
        out.append(f"the budget: least radius {least:.2e} on draws at the budget; broken just past it for k {sharp}")
    # sec. 9-12: the pure harmonics
    harm = {}
    for k in HARMONICS:
        a = amp(k)
        edge = 1 / (2 * (k * k - 1))
        r_edge = float((0.5 - (k * k - 1) * edge * np.cos(k * th)).min())
        r_past = float((0.5 - (k * k - 1) * 1.001 * edge * np.cos(k * th)).min())
        hk = lambda t, k=k, a=a: 0.5 + a * np.cos(k * t)
        wk = float(np.max(np.abs(hk(th) + hk(th + np.pi) - 1)))
        harm[k] = {"a": a, "reserve": reserve(k, a), "reserve_995": reserve(k, amp(k, 0.995)), "order": symmetry_order(hk)}
        if abs(r_edge) > 1e-15 or not r_past < 0 or wk > 1e-15 or not near(harm[k]["reserve"], 0.05, 1e-15) \
                or not near(harm[k]["reserve_995"], 0.0025, 1e-15) or harm[k]["order"] != k:
            out.append(f"H{k}: radius at the bound {r_edge:.1e}, past it {r_past:.1e}, width {wk:.1e}, {harm[k]}")
    for c in ps["pure_harmonic_candidates"]:
        k = c["k"]
        if not near(c["a"], amp(k), 1e-18) or not near(c["curvature_reserve"], reserve(k, amp(k)), 1e-15) \
                or c["amplitude_fraction"] != FRACTION or c["orientation_ratio_vs_B7"] != 7 / k:
            out.append(f"{c['id']}: amplitude, reserve or ratio")
    if any(r["orientation_ratio"] != 7 / r["k"] or not near(r["reserve"], 0.05, 1e-15) or r["frac"] != FRACTION
           for r in ps["coarse_pure_harmonic_scan"]) or fb["orientation_ratio_vs_B7"] != 7.0:
        out.append("the coarse scan's or the candidate's ratios")
    # sec. 4: gcd(7, S) on examples
    orders = {}
    for modes, want in (((5,), 1), ((7,), 7), ((21,), 7), ((7, 21), 7), ((3, 7), 1)):
        c = {k: [1e-4, 5e-5] for k in modes}
        s = witness({"kind": "multimode", "lam": 0.05, "coef": c, "turn": 0.0, "sign": 1.0})[0]
        orders[str(modes)] = symmetry_order(lambda t: s((0.0, 0.0, 0.0), t))
        if orders[str(modes)] != math.gcd(7, *modes) or orders[str(modes)] != want:
            out.append(f"B7 with modes {modes}: symmetry order {orders[str(modes)]}")
    w["w1"] = {"budget_used": used, "budget_available": lam / 2, "candidate_least_radius": float(rho.min()),
               "radius_floor": lam / 2 - used, "width_error": width, "draws_least_radius": least, "harmonics": harm,
               "orders": orders}
    return out


def w2_b7(w):
    """sec. 7's B7 minima on the four cells, against this tree's exact-area search"""
    out, comp, rec = [], w["computed"]["b7"], w["pareto"]["regular_B7"]
    got = []
    for i, (res, pkg) in enumerate(zip(comp, rec["four_marked_cells_search_minima"])):
        best = min(res)
        by = {b: min((r for r in res if basin(r[1][0]) == b), default=None) for b in ("A", "B")}
        row = {"package": pkg, "min": best[0], "basin": basin(best[1][0]), "A": by["A"][0] if by["A"] else None,
               "B": by["B"][0] if by["B"] else None, "package_above_min": pkg - best[0]}
        row["package_above_its_basin"] = pkg - max(v for v in (row["A"], row["B"]) if v is not None and v <= pkg + 1e-12)
        got.append(row)
        if by["A"] is None or by["B"] is None:
            out.append(f"cell-0{i}: the starts did not reach both channels")
        if not near(best[0], w["b7_minima"][i], 5e-11) or best[0] > pkg + 1e-12:
            out.append(f"cell-0{i}: this tree's least {best[0]!r}, claimed {w['b7_minima'][i]}, package {pkg}")
    wrong = [i for i, r in enumerate(got) if r["package_above_min"] > 1e-5]
    if wrong != w["b7_package_wrong_basin"] or any(got[i]["package_above_its_basin"] > 1e-6 for i in wrong):
        out.append(f"cells whose package value lies in the other channel: {wrong}")
    worst = min(r["min"] for r in got)
    if not near(worst, rec["worst_search_min"], 5e-9) or rec["worst_search_min"] != min(rec["four_marked_cells_search_minima"]) \
            or round(rec["worst_search_min"], 8) != w["b7_worst_text"]:
        out.append(f"the worst cell: {worst!r} against {rec['worst_search_min']!r}")
    w["w2"] = {"cells": got, "worst": worst}
    return out


def w3_mixture(w):
    """sec. 5: the mixture as exact arcs, on Round 21's image of q-dagger - the base whose values
    the package's fit"""
    out, comp, ex = [], w["computed"]["mixture"], w["pareto"]["structured_false_basin_example"]
    th = 2 * np.pi * np.arange(4096) / 4096
    worst = 0.0
    for phi in (0.0, 0.3, 1.1, 2.5):
        direct = 0.92 * pieces_support(placed_reuleaux(7, phi, (0.0, 0.0)), th) \
            + 0.08 * pieces_support(placed_reuleaux(3, phi, (0.0, 0.0)), th) + 0.01 * np.cos(th) - 0.02 * np.sin(th)
        worst = max(worst, float(np.max(np.abs(pieces_support(mixture(0.08, phi, (0.01, -0.02)), th) - direct))))
    h0 = pieces_support(mixture(0.08, 0.0, (0.0, 0.0)), th)
    width = float(np.max(np.abs(h0 + np.roll(h0, 2048) - 1)))
    order = symmetry_order(lambda t: pieces_support(mixture(0.08, 0.0, (0.0, 0.0)), t))
    if worst > 1e-15 or width > 1e-15 or order != 1 or ex["lambda"] != 0.08 or ex["relative_rotation"] != 0.0 \
            or ex["family"] != "(1-lambda)B7 + lambda B3":
        out.append(f"the mixture's arcs: support error {worst:.1e}, width error {width:.1e}, symmetry order {order}")
    full, fb7, red = min(comp["full"]), comp["from_b7"], min(comp["reduced"])
    pkg_full, pkg_opt = ex["multi_seed_full_orientation_exact_min"], ex["optimistic_single_basin_exact_search"]
    cl = w["mixture"]
    if not 0 <= pkg_full - full[0] <= 1e-8 or not near(full[0], cl["full"], 5e-11):
        out.append(f"the full-period minimum {full[0]!r}; package {pkg_full!r}, claimed {cl['full']}")
    if not 0 <= pkg_opt - fb7[0] <= 1e-6 or not near(fb7[0], cl["from_b7"], 5e-11):
        out.append(f"from B7's own placement {fb7[0]!r}; package's optimistic {pkg_opt!r}")
    edge = min(red[1][0], 2 * math.pi / 7 - red[1][0]) < 1e-9
    outside = not 0 <= full[1][0] % (2 * math.pi) < 2 * math.pi / 7
    if not near(red[0], cl["reduced"], 5e-10) or edge != cl["reduced_min_on_the_edge"] or not outside \
            or not full[0] < red[0] < fb7[0]:
        out.append(f"the reduced period: least {red[0]!r} at phi {red[1][0]!r}; the full minimum at phi {full[1][0]!r}")
    w["w3"] = {"support_error": worst, "width_error": width, "symmetry_order": order, "full": full, "from_b7": fb7,
               "reduced": red, "package_full_above": pkg_full - full[0], "package_optimistic_above": pkg_opt - fb7[0],
               "second_full": sorted(comp["full"])[1]}
    return out


def w4_multimode(w):
    """sec. 7: the recorded candidate on the four cells, under each way of facing B7"""
    out, comp, fb = [], w["computed"]["multimode"], w["pareto"]["full_symmetry_breaking_candidate"]
    pkg = fb["multi_seed_fresh_four_cell_minima"]
    got = {}
    for name, rows in comp.items():
        br = [r["bracket"] for r in rows]
        got[name] = {"cells": [b[0] for b in br], "width": max(b[1] - b[0] for b in br),
                     "package_minus": [p - b[0] for p, b in zip(pkg, br)]}
        got[name]["worst_gap"] = max(abs(d) for d in got[name]["package_minus"])
    fits = sorted(n for n, g in got.items() if g["worst_gap"] < 5e-6)
    if fits != [w["multimode_convention"]] or any(g["width"] > 3e-9 for g in got.values()):
        out.append(f"conventions within 5e-6 of the package: {fits}; gaps {[round(g['worst_gap'], 9) for g in got.values()]}")
    mine = got[w["multimode_convention"]]["cells"]
    if any(not near(a, b, 5e-10) for a, b in zip(mine, w["multimode_minima"])):
        out.append(f"the candidate's minima {mine}")
    b7 = [min(r)[0] for r in w["computed"]["b7"]]
    below = [b - m for b, m in zip(b7, mine)]
    if min(below) < 2e-4 or not near(min(mine), fb["robust_worst"], 1e-7):
        out.append(f"B7 above the candidate by {below}")
    w["w4"] = {"conventions": got, "fits": fits, "b7_above_candidate": below}
    return out


def w5_harmonics(w):
    """sec. 13-15 and the coarse scan: the pure harmonics searched again on the four cells"""
    out, comp, ps = [], w["computed"]["harmonic"], w["pareto"]
    coarse = {r["k"]: r["worst"] for r in ps["coarse_pure_harmonic_scan"]}
    cand = {c["k"]: c for c in ps["pure_harmonic_candidates"]}
    got = {}
    for k in HARMONICS:
        br = [s["bracket"] for s in comp[str(k)]]
        i = int(np.argmin([b[0] for b in br]))
        row = {"cells": [b[0] for b in br], "worst": br[i], "worst_cell": i, "width": max(b[1] - b[0] for b in br),
               "margin": br[i][0] - T, "coarse": coarse[k], "coarse_minus_worst": coarse[k] - br[i][0]}
        if k in cand:
            c = cand[k]
            row["refined"] = c.get("worst_search_min", c.get("worst_search_min_high_resolution"))
            row["refined_minus_worst"] = row["refined"] - br[i][0]
            d = c.get("dense_bracket_at_found_worst_placement")
            if d:
                row["package_bracket"] = [d["inner"], d["outer"]]
                row["package_bracket_minus_worst"] = d["inner"] - br[i][1]
                if not d["inner"] <= d["outer"]:
                    out.append(f"H{k}: the package's bracket is inverted")
        got[k] = row
        if row["width"] > 3e-9 or not near(br[i][0], w["harmonic_worst"][k], 5e-10) or not br[i][0] > T:
            out.append(f"H{k}: least over the cells {br[i]}, claimed {w['harmonic_worst'][k]}")
    signs = {k: "below" if got[k]["coarse_minus_worst"] < 0 else "above" for k in HARMONICS}
    refined = {k: "below" if got[k]["refined_minus_worst"] < 0 else "above" for k in cand}
    brackets_above = sorted(k for k in cand if got[k].get("package_bracket_minus_worst", -1) > 0)
    if signs != w["coarse_signs"] or refined != w["refined_signs"] or brackets_above != w["package_brackets_above_minimum"]:
        out.append(f"the package's values against the minima: coarse {signs}, refined {refined}, brackets above {brackets_above}")
    w["w5"] = got
    return out


def w6_pilot(w):
    """sec. 16-18: the pilot's depth-20 and -22 trees rebuilt, roots, volumes and tail rates"""
    out, comp, ps = [], w["computed"]["pilot"], w["pareto"]
    rec7 = ps["regular_B7"]["depth20_lift"]
    root7 = 2 * math.pi / 7 * (2 * t_text(7, d_star(TM))) ** 2
    n, _, o = r23.at(comp["B7"], 20)
    if (n, o) != (rec7["nodes"], rec7["pending"]) or rec7["pending_fraction"] != o / 2 ** 20 \
            or not near(rec7["root_volume"], root7, 1e-15) or not near(rec7["unresolved_volume"], o / 2 ** 20 * rec7["root_volume"], 1e-18):
        out.append(f"B7: rebuilt {n, o}, recorded {rec7['nodes'], rec7['pending']}; root {root7!r}")
    got = {"B7": {"20": [n, o]}}
    rates = {"B7": (r23.at(comp["B7"], 22)[2] / 2 ** 22) / (o / 2 ** 20)}
    for c in ps["pure_harmonic_candidates"]:
        k = c["k"]
        per = comp[str(k)]["motion"]
        root = 2 * math.pi / k * (2 * ROOT_T) ** 2
        got[f"H{k}"] = {}
        for d in (20, 22):
            rec = c.get(f"depth{d}_lift")
            if rec is None:
                continue
            nodes, _, opened = per[str(d)]
            got[f"H{k}"][str(d)] = [nodes, opened]
            # the volumes to 1e-12 relative: H19's depth-22 volume differs from fraction x root in its 13th
            # digit, as a sum of the open boxes' volumes would
            if (nodes, opened) != (rec["nodes"], rec["pending"]) or rec["pending_fraction"] != opened / 2 ** d \
                    or not near(rec["unresolved_volume"], opened / 2 ** d * root, 1e-12 * rec["unresolved_volume"]) \
                    or ("root_volume" in rec and not near(rec["root_volume"], root, 1e-16)):
                out.append(f"H{k} depth {d}: rebuilt {nodes, opened}, recorded {rec['nodes'], rec['pending']}")
        if "22" in got[f"H{k}"]:
            rates[f"H{k}"] = (got[f"H{k}"]["22"][1] / 2 ** 22) / (got[f"H{k}"]["20"][1] / 2 ** 20)
    support = {str(k): [comp[str(k)]["support"][str(d)][0], comp[str(k)]["support"][str(d)][2]] for k, d in PILOT}
    if support != {str(k): v for k, v in w["pilot_support_motion"].items()}:
        out.append(f"the pilot with the support's own motion: {support}")
    fastest = min(rates, key=rates.get)
    if fastest != "B7" or any(not near(v, w["tail_rates"][k], 5e-4) for k, v in rates.items()):
        out.append(f"the depth-20 to -22 contraction: {rates}")
    w["w6"] = {"rebuilt": got, "tail_rates_20_22": rates, "support_motion": support}
    return out


def w7_lift(w):
    """the same cell with dense cores: where each tree closes, and what its bound can reach"""
    out, comp = [], w["computed"]
    lim = comp["limit"]
    limits = {"B7": [lim["B7"][0], lim["B7"][0]]}
    limits.update({f"H{k}": lim[str(k)]["bracket"] for k, _ in PILOT})
    can = {name: b[0] > T for name, b in limits.items()}
    cannot = {name: b[1] < T for name, b in limits.items()}
    if any(not near(limits[n][0], v, 5e-10) for n, v in w["limits"].items()) or not all(can[n] or cannot[n] for n in limits) \
            or sorted(n for n in limits if cannot[n]) != w["cannot_close"]:
        out.append(f"the bounds' limits on the cell: {limits}")
    last = max(comp["exact_B7"], key=int)
    closes = {"B7": [int(last), comp["exact_B7"][last][0], comp["exact_B7"][last][2]]}
    for k, _ in PILOT:
        for kind in ("motion", "support"):
            per = comp["dense"][str(k)][kind]
            d = max(per, key=int)
            closes[f"H{k}-{kind}"] = [int(d), per[d][0], per[d][2]]
    if closes != {n: list(v) for n, v in w["dense_closes"].items()}:
        out.append(f"the dense trees: {closes}")
    for name in w["cannot_close"]:
        k = int(name[1:])
        g = lim[str(k)]["fine"][0][1]
        if any(closes[f"{name}-{kind}"][2] == 0 for kind in ("motion", "support")) \
                or not (0 <= g[0] < 2 * math.pi / k and max(abs(g[1]), abs(g[2])) <= ROOT_T):
            out.append(f"{name}: a tree closed that its limit says cannot, or the placement {g} is outside the root")
    centre = {f"H{k}": lim[f"{k}-centre"]["bracket"] for k, _ in PILOT}
    if any(not near(centre[n][0], v, 5e-10) or not centre[n][0] > T for n, v in w["centre_limits"].items()):
        out.append(f"at the cell's centre with the whole base: {centre}")
    # the open volume at lift depth 20 with dense or exact cores, against the pilot's
    roots = {"B7": 2 * math.pi / 7 * (2 * t_text(7, d_star(TM))) ** 2}
    roots.update({f"H{k}": 2 * math.pi / k * (2 * ROOT_T) ** 2 for k, _ in PILOT})
    volume20 = {"B7": r23.at(comp["exact_B7"], 20)[2] / 2 ** 20 * roots["B7"]}
    for k, _ in PILOT:
        for kind in ("motion", "support"):
            volume20[f"H{k}-{kind}"] = r23.at(comp["dense"][str(k)][kind], 20)[2] / 2 ** 20 * roots[f"H{k}"]
    if min(volume20, key=volume20.get) != "B7":
        out.append(f"the depth-20 open volume with dense cores: {volume20}")
    w["w7"] = {"limits": limits, "cores_alone": lim["cores_alone"], "closes": closes, "centre": centre,
               "loss_to_the_cores": {n: centre[n][0] - limits[n][0] for n in centre}, "volume20": volume20,
               "B7_limit_placement": lim["B7"][1]}
    return out


def w8_code(w):
    """what the package ships to replay itself; the one script is read, never run"""
    import re
    code = w["repro"]
    facts = {"lines": code.count("\n"), "functions": re.findall(r"^def (\w+)", code, re.M),
             "searches_or_hulls": any(k in code for k in ("minimize", "ConvexHull", "scipy", "numpy")),
             "lifts": any(k in code for k in ("lift", "delta", "core", "node")),
             "absolute_paths": bool(re.search(r"[\"']/", code)),
             "legality_formulas": "frac/(2*(k*k-1))" in code and "0.5-(k*k-1)*abs(a)" in code and "7/k" in code}
    w["w8"] = facts
    return [] if facts == w["code_facts"] else [f"the shipped script: {facts}"]


def p1_package(w):
    """the text's numbers against the Pareto summary; the spec; the crystal"""
    out, text, ps, sp = [], gate.squash(w["text"]), w["pareto"], w["spec"]
    fb, ex = ps["full_symmetry_breaking_candidate"], ps["structured_false_basin_example"]
    cand = {c["k"]: c for c in ps["pure_harmonic_candidates"]}
    vals = {"0.83742146": ex["optimistic_single_basin_exact_search"], "0.83583910": ex["multi_seed_full_orientation_exact_min"],
            "0.83770073": fb["training_min"], "0.83733308": fb["single_seed_fresh_min"],
            "0.83692628": ps["regular_B7"]["worst_search_min"],
            "0.83574698": cand[11]["worst_search_min"], "0.83563803": cand[13]["worst_search_min"],
            "0.83578614": cand[11]["dense_bracket_at_found_worst_placement"]["inner"],
            "0.83581539": cand[11]["dense_bracket_at_found_worst_placement"]["outer"],
            "0.83567775": cand[13]["dense_bracket_at_found_worst_placement"]["inner"],
            "0.83569731": cand[13]["dense_bracket_at_found_worst_placement"]["outer"],
            "0.83507834": cand[17]["worst_search_min_high_resolution"], "0.83504963": cand[19]["worst_search_min_high_resolution"]}
    vals.update({s: v for s, v in zip(("0.83683248", "0.83677292", "0.83674967", "0.83668617"), fb["multi_seed_fresh_four_cell_minima"])})
    for s, v in vals.items():
        if round(v, 8) != float(s) or s not in text:
            out.append(f"the text's {s} against the summary's {v}")
    volumes = {"7037": ps["regular_B7"]["depth20_lift"]["unresolved_volume"]}
    volumes.update({str(c["depth20_lift"]["nodes"]): c["depth20_lift"]["unresolved_volume"] for c in cand.values()})
    for nodes, v in volumes.items():
        m, e = f"{v:.4e}".split("e")
        if rf"{m}\times10^{{{int(e)}}}" not in text or nodes not in text:
            out.append(f"sec. 17: {nodes} nodes, {v}")
    if fb["robust_worst"] != min(fb["multi_seed_fresh_four_cell_minima"]) or not fb["robust_worst"] < ps["regular_B7"]["worst_search_min"]:
        out.append("the candidate's robust worst")
    for c in cand.values():
        worst = c.get("worst_search_min", c.get("worst_search_min_high_resolution"))
        if not near(c["search_margin_over_target"], worst - T, 1e-15):
            out.append(f"{c['id']}: the recorded margin")
    margins = sorted(round(cand[k]["search_margin_over_target"], 4) for k in (11, 13))
    if margins != w["balanced_margins"]:
        out.append(f"sec. 20's 6-7e-4 margins: {margins}")
    ph = sp["pure_harmonic_family"]
    if sp["allowed_modes"] != [3, 5, 7, 9, 11] or ph["orientation_period"] != "2pi/k" or ph["generic_support_core_condition"] != "motion_delta <= sigma" \
            or "gcd(7" not in sp["symmetry_rule"]["with_B7_base"] or ps["status"] != "PROOF-COST-PARETO-PILOT-NOT-THEOREM":
        out.append("the oracle spec's rules")
    crystal = gate.squash(w["crystal"])
    for frag in ("H11:~0.835747", "7/11", "H13:~0.835638", "H17:~0.835078", "H19:~0.835050", "B7:~1.4107e-4", "H11:~1.8536e-4",
                 "H13:~1.4270e-4", "H17:~9.5317e-5", "H19:~8.3671e-5", r"\boxed{0.83583910}", "0.83770073.", r"\text{worst}\approx0.83668617.",
                 r"\boxed{0.83692628.}", r"\sigma=0.05."):
        if frag not in crystal:
            out.append(f"crystal: {frag}")
    w["p1"] = {"values": len(vals), "volumes": volumes, "balanced_margins": margins}
    return out


def p2_package(w):
    import re
    out, v = [], w["validation"]
    leaves = {row[0]: row for row in w["manifest"]["leaves"]}
    for key, leaf_id, text in (("round22", DOC, w["text"]), ("state_crystal", CRYSTAL, w["crystal"])):
        rec, (_, size, digest) = v[key], leaves[leaf_id]
        n = text.count("$$")
        if rec["sha256"] != digest or rec["bytes"] != size or not rec["utf8"] \
                or rec["double_dollar_count"] != n or rec["double_dollar_even"] != (n % 2 == 0) \
                or rec["contains_unicode_escape_sequence"] != bool(re.search(r"\\u[0-9a-fA-F]{4}", text)) \
                or rec["contains_bracket_math_delimiter"] != bool(re.search(r"\\[\[\]()]", text)):
            out.append(f"VALIDATION {key} against the archive and the document")
    for key, leaf_id in (("fourier_oracle_spec_sha256", SPEC), ("pareto_summary_sha256", PARETO), ("repro_sha256", REPRO)):
        if v[key] != leaves[leaf_id][2]:
            out.append(f"VALIDATION {key} against the archive")
    ps = w["pareto"]
    fb, cand = ps["full_symmetry_breaking_candidate"], {c["k"]: c for c in ps["pure_harmonic_candidates"]}
    kc = {"multi_mode_legality_budget_satisfied": fb["curvature_budget_used"] <= fb["curvature_budget_available"],
          "full_breaking_candidate_worse_than_B7_search": fb["robust_worst"] < ps["regular_B7"]["worst_search_min"],
          "H11_curvature_reserve_positive": cand[11]["curvature_reserve"] > 0,
          "H19_orientation_domain_smaller_than_B7": cand[19]["orientation_ratio_vs_B7"] < 1,
          "H19_depth20_unresolved_volume_smaller_than_B7":
              cand[19]["depth20_lift"]["unresolved_volume"] < ps["regular_B7"]["depth20_lift"]["unresolved_volume"],
          "no_global_theorem_claim": "NOT-THEOREM" in ps["status"]}
    if kc != v["checks"] or v["status"] != "PASS":
        out.append(f"VALIDATION checks {kc}")
    w["p2"] = kc
    return out


# ---------------------------------------------------------------- world, checks, drill

def load_inputs():
    blobs = {n: source_bytes(n) for n in SOURCES}
    want = {DOC, CRYSTAL, SPEC, PARETO, VALIDATION, REPRO, R20_MANIFEST, R21_SYNTH}
    got = {leaf.id: d for leaf, d in walk_sources(blobs, keep=lambda l: l.id in want) if d is not None}
    syn = json.loads(got[R21_SYNTH])
    return {"text": got[DOC].decode("utf-8"), "crystal": got[CRYSTAL].decode("utf-8"), "spec": json.loads(got[SPEC]),
            "pareto": json.loads(got[PARETO]), "validation": json.loads(got[VALIDATION]), "repro": got[REPRO].decode("utf-8"),
            "cells": [c["base_center"] for c in json.loads(got[R20_MANIFEST])["base_cells"]],
            "q21": syn["base_configuration"]["q"], "g21": syn["regular_B7_reference"]["placement"],
            "key_bytes": got[PARETO] + got[R20_MANIFEST] + got[R21_SYNTH], "manifest": json.loads(MANIFEST.read_text(encoding="utf-8"))}


R22_DEFINITIONS = {
    "TRAINING-SCORE": ("in-line", "sec. 6: a witness's least hull area over a finite set of adversarial placements only"),
    "OPTIMISTIC-CANDIDATE": ("in-line", "sec. 6: a fresh placement search, but with too few seeds or too coarse a resolution"),
    "ROBUST-SEARCH-CANDIDATE": ("in-line", "sec. 6: searched over the full proven orientation period by a multi-seed fresh oracle"),
    "COMPILED-CANDIDATE": ("in-line", "sec. 6: representable in Round 02's finite support dictionary"),
    "LIFT-VERIFIED": ("in-line", "sec. 6: every relevant placement root closed by certificates - the one level with theorem value"),
    "SEARCH ARCHIVE": ("in-line", "sec. 21: where candidates not promoted are kept, for later multi-base or batch synthesis"),
    "PRIMARY ROBUST CLOSER": ("in-line", "sec. 20: regular B7's role - thick forcing, a specialised erosion, fast tail contraction"),
    "BALANCED AUXILIARY": ("in-line", "sec. 20: H11 and H13's role - a 6-7e-4 search margin, a smaller orientation domain, "
                                      "reserve 0.05"),
    "CHEAP / RAZOR-THIN AUXILIARY": ("in-line", "sec. 20: H17 and H19's role - a small orientation root and unresolved volume, "
                                                "a margin of a few 1e-5"),
    "NOT PROMOTED TO PRODUCTION WITNESS POOL": ("in-line", "sec. 21: the verdict on the full symmetry-breaking candidates"),
    "PURE-HARMONIC-CW": ("in-line", "sec. 25: a proposed compiler path for h = 1/2 + a cos k theta - odd k, the amplitude bound, "
                                    "the period, the reserve, support and contact evaluation"),
}
R22_REVIEWS = [
    ("CLOSED", "MULTI-MODE FOURIER LEGALITY COMPILER", "analytic", "PASS",
     "odd modes keep width 1, and the curvature budget is sufficient by the triangle inequality and sharp for a single mode "
     "(W1); a rule - no compiler is shipped (W8)"),
    ("CLOSED", "FULL-ORIENTATION ORACLE RULE", "analytic", "PASS",
     "a reduced period is sound exactly when the body has that symmetry (W1); on the B7/B3 mixture the full minimum lies "
     "outside [0, 2 pi/7) (W3)"),
    ("COMPUTE-DEFERRED", "a_{Leb}≥0.8350", "n/a", "n/a", "sec. 0's boxed summary; read from census v5 on (RUN-003)"),
    ("SEARCH-ONLY", "24. Search status warning", "reading", "PASS",
     "rightly: here the package's own searched values sit on both sides of the minima, by up to 1.2e-4 (W2, W5)"),
    ("ESTABLISHED", "PROOF-COST PARETO MAP", "computation", "FAIL",
     "the forcing and orientation axes rebuild (W1, W2, W5), but the volume axis is the pilot's 40-direction bound with a "
     "boundary-motion delta, and it inverts: with dense cores B7 closes the depth-50 cell at lift depth 21 with 2509 nodes, "
     "H11 and H13 take 21029 and 43111, and H17/H19 cannot close it at any depth (W7)"),
    ("COMPILED-CANDIDATE", "", "n/a", "n/a", "a level of sec. 6, defined there; not a judgment"),
    ("LIFT-VERIFIED", "", "n/a", "n/a", "a level of sec. 6, defined there; not a judgment"),
    ("NOT FOUND", "NEW SINGLE WITNESS DOMINATING B_7", "computation", "PARTIAL",
     "true of every candidate the package records: the multi-mode candidate is 2.3-2.5e-4 below B7 on every cell (W4), the "
     "harmonics at least 1.8e-4 below (W5); sec. 8's re-trained candidates are not recorded"),
    ("OPTIMISTIC-CANDIDATE", "", "n/a", "n/a", "a level of sec. 6, defined there; not a judgment"),
    ("PURE-HARMONIC-CW", "25. New compiler path", "analytic", "PASS",
     "its checks are the right ones - odd k, the exact amplitude bound, the period 2 pi/k, the reserve (W1); proposed, not "
     "shipped (W8)"),
    ("ROBUST-SEARCH-CANDIDATE", "", "n/a", "n/a", "a level of sec. 6, defined there; not a judgment"),
    ("SEARCH ARCHIVE", "21. Full symmetry-breaking candidate verdict", "reading", "PARTIAL",
     "one candidate is archived with its coefficients, and they rebuild its minima - once B7 has a vertex at theta = pi, which the "
     "text does not say (W4); sec. 8's candidates are not archived"),
    ("TRAINING-SCORE", "", "n/a", "n/a", "a level of sec. 6, defined there; not a judgment"),
    ("BALANCED AUXILIARY", "", "computation", "PARTIAL",
     "the margins rebuild at 7.6e-4 and 6.2e-4 (W5), the domains and reserves exactly (W1); but on the depth-50 cell they cost "
     "21029 and 43111 nodes with the pilot's delta, 1581 and 3257 with the support's own motion, against B7's 2509 (W7)"),
    ("CHEAP / RAZOR-THIN AUXILIARY", "", "computation", "FAIL",
     "razor-thin, yes - 8.2e-5 and 4.8e-5 (W5); cheap, no: with the depth-50 cell's cores their hull falls to 0.83467 and "
     "0.83465, below T with its outer bound, so no lift depth closes the cell (W7)"),
    ("NOT PROMOTED TO PRODUCTION WITNESS POOL", "", "computation", "PASS",
     "the recorded candidate is below B7 on every cell (W4) and needs 7 times the orientation domain (W1)"),
    ("PRIMARY ROBUST CLOSER", "", "computation", "PASS",
     "the thickest forcing of every witness here (W2, W5), and with exact cores it closes the depth-50 cell at lift depth 21 (W7)"),
]


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


CHECKS = {"A0": gate.anchors_check(ANCHORS), "W1": w1_legality, "W2": w2_b7, "W3": w3_mixture, "W4": w4_multimode,
          "W5": w5_harmonics, "W6": w6_pilot, "W7": w7_lift, "W8": w8_code, "P1": p1_package, "P2": p2_package,
          "R1": r1_registry}
DEPENDS = {"A0": {"text"}, "W1": {"pareto", "spec"},
           "W2": {"computed", "pareto", "b7_minima", "b7_package_wrong_basin", "b7_worst_text"},
           "W3": {"computed", "pareto", "mixture"},
           "W4": {"computed", "pareto", "multimode_convention", "multimode_minima"},
           "W5": {"computed", "pareto", "harmonic_worst", "coarse_signs", "refined_signs", "package_brackets_above_minimum"},
           "W6": {"computed", "pareto", "pilot_support_motion", "tail_rates"},
           "W7": {"computed", "limits", "cannot_close", "dense_closes", "centre_limits"},
           "W8": {"repro", "code_facts"},
           "P1": {"text", "pareto", "spec", "crystal", "balanced_margins"},
           "P2": {"validation", "manifest", "text", "crystal", "pareto"},
           "R1": {"registry", "definitions", "reviews"}}


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--drill", action="store_true")
    ap.add_argument("--blind", metavar="CID")
    args = ap.parse_args()
    inputs = load_inputs()
    results_computed = computed(inputs["cells"], inputs["pareto"], inputs["q21"], inputs["g21"], inputs["key_bytes"])

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

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

    def edit(fn):
        p = copy.deepcopy(ps)
        fn(p)
        return p

    cases = [
        ("K0-unmodified", "control", {}, set()),
        ("K1-doc-crlf", "control", {"text": text.replace("\n", "\r\n")}, set()),
        ("K2-pareto-keys-sorted", "control", {"pareto": json.loads(json.dumps(ps, sort_keys=True))}, set()),
        ("K3-candidates-reversed", "control",
         {"pareto": edit(lambda p: p.update(pure_harmonic_candidates=list(reversed(p["pure_harmonic_candidates"]))))}, set()),
        ("M1-doc-ratio", "mutation", {"text": text.replace(r"7/19\approx0.368.", r"7/19\approx0.369.")}, {"A0"}),
        ("M2-budget-used", "mutation",
         {"pareto": edit(lambda p: p["full_symmetry_breaking_candidate"].update(
             curvature_budget_used=p["full_symmetry_breaking_candidate"]["curvature_budget_used"] + 1e-12))}, {"W1"}),
        ("M3-harmonic-amplitude", "mutation",
         {"pareto": edit(lambda p: p["pure_harmonic_candidates"][1].update(a=0.0026785))}, {"W1"}),
        ("M4-b7-cell01-true-min", "mutation",
         {"pareto": edit(lambda p: p["regular_B7"]["four_marked_cells_search_minima"].__setitem__(1, 0.8370210981))}, {"W2"}),
        ("M5-b7-claim", "mutation", {"b7_minima": [*CLAIMS["b7_minima"][:2], 0.8369847619, CLAIMS["b7_minima"][3]]}, {"W2"}),
        ("M6-mixture-claim", "mutation", {"mixture": {**CLAIMS["mixture"], "from_b7": 0.8374214584}}, {"W3"}),
        ("M7-mixture-full-below", "mutation",
         {"pareto": edit(lambda p: p["structured_false_basin_example"].update(multi_seed_full_orientation_exact_min=0.83583909))},
         {"W3", "P1"}),
        ("M8-multimode-convention", "mutation", {"multimode_convention": "vertex at 0"}, {"W4"}),
        ("M9-multimode-cell", "mutation",
         {"pareto": edit(lambda p: p["full_symmetry_breaking_candidate"]["multi_seed_fresh_four_cell_minima"].__setitem__(2, 0.8367596726))},
         {"W4", "P1"}),
        ("M10-harmonic-claim", "mutation", {"harmonic_worst": {**CLAIMS["harmonic_worst"], 17: 0.8350819479}}, {"W5"}),
        ("M11-coarse-scan", "mutation", {"pareto": edit(lambda p: p["coarse_pure_harmonic_scan"][1].update(worst=0.8356))}, {"W5"}),
        ("M12-pilot-pending", "mutation",
         {"pareto": edit(lambda p: p["pure_harmonic_candidates"][2]["depth22_lift"].update(
             pending=p["pure_harmonic_candidates"][2]["depth22_lift"]["pending"] + 1))}, {"W6"}),
        ("M13-support-motion-claim", "mutation",
         {"pilot_support_motion": {**CLAIMS["pilot_support_motion"], 13: [2737, 748]}}, {"W6"}),
        ("M14-tail-rate-claim", "mutation", {"tail_rates": {**CLAIMS["tail_rates"], "H19": 0.66}}, {"W6"}),
        ("M15-cannot-close", "mutation", {"cannot_close": ["H19"]}, {"W7"}),
        ("M16-dense-claim", "mutation", {"dense_closes": {**CLAIMS["dense_closes"], "H11-motion": [26, 21029, 0]}}, {"W7"}),
        ("M16b-centre-claim", "mutation", {"centre_limits": {**CLAIMS["centre_limits"], "H19": 0.8350827361}}, {"W7"}),
        ("M17-repro-computes", "mutation", {"repro": inputs["repro"] + "\nimport numpy\n"}, {"W8"}),
        ("M18-crystal-value", "mutation", {"crystal": inputs["crystal"].replace("H17: ~0.835078", "H17: ~0.835079")}, {"P1"}),
        ("M19-validation-digest", "mutation", {"validation": {**inputs["validation"], "pareto_summary_sha256": "0" * 64}}, {"P2"}),
        ("M20-validation-check", "mutation",
         {"validation": {**inputs["validation"], "checks": {**inputs["validation"]["checks"], "H11_curvature_reserve_positive": False}}},
         {"P2"}),
        ("M21-review-dropped", "mutation", {"reviews": list(R22_REVIEWS[1:])}, {"R1"}),
    ]
    if args.blind:
        cases = [c for c in cases if args.blind in c[3]]
    d = gate.run_drill(build, CHECKS, DEPENDS, cases)
    summary = gate.summarize(d, CHECKS)
    print(gate.report_drill(summary))
    for x in d:
        if not x["ok"]:
            print("   DRILL FAIL", x)
    if args.blind:
        n = sum(1 for x in d if args.blind in x["expected"] and args.blind not in x["tripped"])
        print(f"blind {args.blind}: drill reported it blind in {n} cases (nothing written)")
        return
    log = {"run": "RUN-025", "subject": "Round 22: the symmetry-breaking Fourier witness oracle and the proof-cost Pareto search",
           "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", "p2")}, "drill": summary}
    LOG.write_text(json.dumps(log, ensure_ascii=False, indent=1, default=float) + "\n", encoding="utf-8")
    if not results["R1"]:
        registry.record("R22", "RUN-025", R22_DEFINITIONS, R22_REVIEWS)
        print(f"registry: {len(R22_DEFINITIONS)} definitions, {len(R22_REVIEWS)} reviews recorded for R22")


if __name__ == "__main__":
    main()
