"""Bounded formal checker for the PF-002 C3-S completion, version 1.

Virtual lab - simulated experiment tooling. Stdlib only. It evaluates the
frozen formal checks VS1-VS12 and AC-T1/AC-T2 of the reviewed revision 7
proposal as exact rational algebra on declared definitions. Finite point
evaluations are checks, not continuum proofs, and nothing here is a field
solver, dynamics integrator, detector simulation or physical inference.
"""

import json
import math
import unicodedata
from dataclasses import dataclass
from decimal import Decimal, localcontext
from fractions import Fraction
from weakref import WeakKeyDictionary

VARS = ("n", "m", "C", "S", "chibar", "chibarX", "eta", "hbar", "r",
        "s", "nu", "X", "N0", "bP", "s0", "Ks", "Aeff", "ndot", "Xdot",
        "ptc", "ndot_H", "Vb", "omg", "Delta", "u1r", "u1i", "u2r", "u2i")
IDX = {name: i for i, name in enumerate(VARS)}
MAX_DEGREE = 12
MAX_TERMS = 256
MAX_COEFF_BITS = 256
MAX_OPS = 100000
_ops = [0]


class Refusal(Exception):
    pass


def _tick(n=1):
    _ops[0] += n
    if _ops[0] > MAX_OPS:
        raise Refusal("operation_cap")


def _mono(**kw):
    e = [0] * len(VARS)
    for k, v in kw.items():
        e[IDX[k]] = v
    return tuple(e)


def _check(poly):
    if len(poly) > MAX_TERMS:
        raise Refusal("term_cap")
    for mono, coeff in poly.items():
        if sum(mono) > MAX_DEGREE:
            raise Refusal("degree_cap")
        if coeff.numerator.bit_length() > MAX_COEFF_BITS or \
                coeff.denominator.bit_length() > MAX_COEFF_BITS:
            raise Refusal("coefficient_cap")
    return poly


def _reduce(poly):
    """Reduce r^2 -> n^2-m^2 and C^2 -> 1-S^2 until neither occurs."""
    poly = dict(poly)
    _check(poly)
    changed = True
    while changed:
        _check(poly)
        changed = False
        for mono, coeff in list(poly.items()):
            if mono[IDX["r"]] >= 2:
                _tick()
                del poly[mono]
                base = list(mono)
                base[IDX["r"]] -= 2
                for var, sign in (("n", 1), ("m", -1)):
                    b = list(base)
                    b[IDX[var]] += 2
                    poly[tuple(b)] = poly.get(tuple(b), Fraction(0)) + sign * coeff
                changed = True
                break
            if mono[IDX["C"]] >= 2:
                _tick()
                del poly[mono]
                base = list(mono)
                base[IDX["C"]] -= 2
                poly[tuple(base)] = poly.get(tuple(base), Fraction(0)) + coeff
                b = list(base)
                b[IDX["S"]] += 2
                poly[tuple(b)] = poly.get(tuple(b), Fraction(0)) - coeff
                changed = True
                break
    return _check({m: c for m, c in poly.items() if c})


def padd(a, b):
    if len(a) + len(b) > MAX_TERMS + min(len(a), len(b)):
        # growth is bounded by the union; refuse only on proven overflow
        pass
    _tick(len(a) + len(b))
    out = dict(a)
    for m, c in b.items():
        out[m] = out.get(m, Fraction(0)) + c
    return _reduce({m: c for m, c in out.items() if c})


def pmul(a, b):
    # refuse before growth: degree and term upper bounds first
    if a and b:
        if max(sum(m) for m in a) + max(sum(m) for m in b) > MAX_DEGREE:
            raise Refusal("degree_cap")
        if len(a) * len(b) > MAX_TERMS * 4:
            raise Refusal("term_cap")
    _tick(len(a) * len(b))
    out = {}
    for m1, c1 in a.items():
        for m2, c2 in b.items():
            m = tuple(x + y for x, y in zip(m1, m2))
            out[m] = out.get(m, Fraction(0)) + c1 * c2
    return _reduce(out)


def pvar(name, power=1):
    if isinstance(power, bool) or not isinstance(power, int) \
            or power < 0 or power > MAX_DEGREE:
        raise Refusal("invalid_exponent")
    return {_mono(**{name: power}): Fraction(1)}


def pconst(value):
    if isinstance(value, bool) or not isinstance(value, (int, Fraction)):
        raise Refusal("invalid_constant")
    value = Fraction(value)
    _tick()
    if value and (value.numerator.bit_length() > MAX_COEFF_BITS
                  or value.denominator.bit_length() > MAX_COEFF_BITS):
        raise Refusal("coefficient_cap")
    return {_mono(): value} if value else {}


def pscale(a, factor):
    if isinstance(factor, bool) or not isinstance(factor, (int, Fraction)):
        raise Refusal("invalid_scalar")
    factor = Fraction(factor)
    if not factor:
        return {}
    _tick(len(a))
    if factor.numerator.bit_length() > MAX_COEFF_BITS or \
            factor.denominator.bit_length() > MAX_COEFF_BITS:
        raise Refusal("coefficient_cap")
    return _check({m: c * factor for m, c in a.items()})


class Rat:
    """Polynomial divided by r**rpow (the only denominator in core checks)."""

    def __init__(self, num, rpow=0):
        if isinstance(rpow, bool) or not isinstance(rpow, int) \
                or rpow < 0 or rpow > 3:
            raise Refusal("denominator_cap:r")
        self.num = _reduce(num)
        self.rpow = rpow
        while self.num and self.rpow and all(m[IDX["r"]] >= 1 for m in self.num):
            self.num = {tuple(v - 1 if i == IDX["r"] else v for i, v in enumerate(m)): c
                        for m, c in self.num.items()}
            self.rpow -= 1

    def __eq__(self, other):
        if not self.num or not other.num:
            return not self.num and not other.num
        left = pmul(self.num, pvar("r", other.rpow))
        right = pmul(other.num, pvar("r", self.rpow))
        return padd(left, pscale(right, -1)) == {}

    def __repr__(self):
        return f"Rat({self.num},{self.rpow})"


def radd(a, b):
    k = max(a.rpow, b.rpow)
    def lift(x):
        p = x.num
        for _ in range(k - x.rpow):
            p = pmul(p, pvar("r"))
        return p
    return Rat(padd(lift(a), lift(b)), k)


def rsub(a, b):
    return radd(a, Rat(pscale(b.num, -1), b.rpow))


def rmul(a, b):
    return Rat(pmul(a.num, b.num), a.rpow + b.rpow)


def deriv(poly, var):
    """Constrained derivative of a polynomial numerator (before clearing)."""
    out = {}
    for mono, coeff in poly.items():
        # ordinary part in var, plus chain terms through r, C, S, chibar
        terms = []
        if var in IDX and mono[IDX[var]]:
            b = list(mono)
            b[IDX[var]] -= 1
            terms.append((tuple(b), coeff * mono[IDX[var]], 0))
        if var in ("n", "m") and mono[IDX["r"]]:
            b = list(mono)
            b[IDX["r"]] -= 1
            b[IDX[var]] += 1
            sign = 1 if var == "n" else -1
            terms.append((tuple(b), sign * coeff * mono[IDX["r"]], 1))
        if var == "phi":
            if mono[IDX["C"]]:
                b = list(mono)
                b[IDX["C"]] -= 1
                b[IDX["S"]] += 1
                terms.append((tuple(b), -coeff * mono[IDX["C"]], 0))
            if mono[IDX["S"]]:
                b = list(mono)
                b[IDX["S"]] -= 1
                b[IDX["C"]] += 1
                terms.append((tuple(b), coeff * mono[IDX["S"]], 0))
        if var == "X" and mono[IDX["chibar"]]:
            b = list(mono)
            b[IDX["chibar"]] -= 1
            b[IDX["chibarX"]] += 1
            terms.append((tuple(b), coeff * mono[IDX["chibar"]], 0))
        for m, c, extra_r in terms:
            key = (m, extra_r)
            out[key] = out.get(key, Fraction(0)) + c
    # group by extra denominator power of r
    result = Rat({}, 0)
    for (m, extra), c in out.items():
        result = radd(result, Rat({m: c}, extra))
    return result


def rderiv(rat, var):
    """Derivative of num / r**k under the constrained derivations."""
    dp = deriv(rat.num, var)
    out = Rat(dp.num, dp.rpow + rat.rpow)
    if rat.rpow and var in ("n", "m"):
        coeff = -rat.rpow if var == "n" else rat.rpow
        chain = Rat(pscale(pmul(rat.num, pvar(var)), coeff), rat.rpow + 2)
        out = radd(out, chain)
    return out


def curvature():
    global _CURVATURE_CACHE
    if _CURVATURE_CACHE is None:
        _CURVATURE_CACHE = _curvature_compute()
    return _CURVATURE_CACHE


def loop_values():
    return {"Ks": _edge_integral(SQUARE, "Ks"),
            "Ks_reversed": _edge_integral(SQUARE[::-1], "Ks"),
            "Ls": _edge_integral(SQUARE, "Ls"),
            "Ls_reversed": _edge_integral(SQUARE[::-1], "Ls"),
            "AXnu": _edge_integral(RECT, "AXnu"),
            "Bsnu": _edge_integral(SQUARE, "Bsnu"),
            "Ks_depth": _edge_integral(DEPTH, "Ks"),
            "collapsed": _edge_integral(
                [(Fraction(1), Fraction(1))] * 2, "Ks")}


def _A():
    eta, ch, n, m, S, C, r = (pvar("eta"), pvar("chibar"), pvar("n"),
                              pvar("m"), pvar("S"), pvar("C"), pvar("r"))
    chx = pvar("chibarX")
    return {
        "n": Rat(pmul(pmul(pmul(eta, ch), pmul(m, m)), S), 1),
        "m": Rat(pscale(pmul(pmul(pmul(pmul(eta, ch), n), m), S), -1), 1),
        "phi": Rat(pmul(pmul(pmul(eta, ch), n), pmul(r, C)), 0),
        "X": Rat({}, 0), "thetabar": Rat({}, 0),
    }


_CURVATURE_CACHE = None


def _curvature_compute():
    a = _A()
    out = {}
    for i in ("n", "m", "phi", "X"):
        for j in ("n", "m", "phi", "X"):
            out[f"F_{i}{j}"] = rsub(rderiv(a[j], i), rderiv(a[i], j))
    return out


def _expected_curvature():
    eta, ch, chx, n, m, S, C, r = (pvar("eta"), pvar("chibar"), pvar("chibarX"),
                                  pvar("n"), pvar("m"), pvar("S"), pvar("C"), pvar("r"))
    two = pconst(2)
    return {
        "F_mphi": Rat({}, 0),
        "F_nphi": Rat(pmul(pmul(pmul(two, eta), ch), pmul(r, C)), 0),
        "F_Xphi": Rat(pmul(pmul(pmul(chx, eta), n), pmul(r, C)), 0),
        "F_Xn": Rat(pmul(pmul(pmul(eta, chx), pmul(m, m)), S), 1),
        "F_Xm": Rat(pscale(pmul(pmul(pmul(pmul(eta, chx), n), m), S), -1), 1),
        "F_nm": Rat(pscale(pmul(pmul(pmul(eta, ch), m), S), -2), 1),
    }


def _edge_integral(vertices, kind):
    """Exact integral over a closed rational polygon for frozen loop forms."""
    total = Fraction(0)
    count = len(vertices)
    for i in range(count):
        s0, v0 = vertices[i]
        s1, v1 = vertices[(i + 1) % count]
        ds, dv = s1 - s0, v1 - v0
        if kind == "Ks":  # integral s^2 dnu along the edge
            total += dv * (s0 * s0 + s0 * ds + ds * ds / 3)
        elif kind == "Ls":  # integral s dnu
            total += dv * (s0 + ds / 2)
        elif kind == "AXnu":  # integral X dnu, vertices are (X, nu)
            total += dv * (s0 + ds / 2)
        elif kind == "Bsnu":  # integral (s dnu - nu ds)
            total += dv * (s0 + ds / 2) - ds * (v0 + dv / 2)
    return total


SQUARE = [(Fraction(1, 2), Fraction(1)), (Fraction(1), Fraction(1)),
          (Fraction(1), Fraction(-1)), (Fraction(1, 2), Fraction(-1))]
DEPTH = [(Fraction(1), Fraction(1)), (Fraction(3, 2), Fraction(1)),
         (Fraction(3, 2), Fraction(-1)), (Fraction(1), Fraction(-1))]
RECT = [(Fraction(0), Fraction(1)), (Fraction(1), Fraction(1)),
        (Fraction(1), Fraction(-1)), (Fraction(0), Fraction(-1))]


def _pf6(mat):
    """Pfaffian of a 6x6 antisymmetric matrix of Rat by perfect matchings."""
    import itertools
    total = Rat({}, 0)
    indices = (0, 1, 2, 3, 4, 5)
    def matchings(rest):
        if not rest:
            yield [], 1
            return
        first = rest[0]
        for k in range(1, len(rest)):
            second = rest[k]
            others = rest[1:k] + rest[k + 1:]
            for tail, sign in matchings(others):
                yield [(first, second)] + tail, sign
    seen = set()
    for pairs, _ in matchings(indices):
        key = tuple(pairs)
        if key in seen:
            continue
        seen.add(key)
        # sign by permutation parity of the flattened pairing
        flat = [x for pair in pairs for x in pair]
        inversions = sum(1 for i in range(6) for j in range(i + 1, 6)
                         if flat[i] > flat[j])
        term = Rat(pconst(1), 0)
        for i, j in pairs:
            term = rmul(term, mat[i][j])
        if inversions % 2:
            term = Rat(pscale(term.num, -1), term.rpow)
        total = radd(total, term)
    return total


def _pfaffian_check(witness=None):
    f = curvature()
    hbar = pvar("hbar")
    zero = Rat({}, 0)
    # order (n, thetabar, m, phi, X, P_X); only F block plus Omega0 pairings
    def e(i, j, value):
        return (i, j, value)
    entries = {}
    def put(i, j, value):
        # W = Omega0 + F: entries add, never replace.
        prev = entries.get((i, j), Rat({}, 0))
        entries[(i, j)] = radd(prev, value)
        entries[(j, i)] = Rat(pscale(entries[(i, j)].num, -1),
                              entries[(i, j)].rpow)
    put(0, 1, Rat(hbar, 0))
    put(2, 3, Rat(pscale(hbar, Fraction(1, 2)), 0))
    put(4, 5, Rat(pconst(1), 0))
    names = ("n", "m", "phi", "X")
    idx = {"n": 0, "m": 2, "phi": 3, "X": 4}
    for a in names:
        for b in names:
            if a < b:
                put(idx[a], idx[b], f[f"F_{a}{b}"])
    mat = [[entries.get((i, j), zero) for j in range(6)] for i in range(6)]
    pf = _pf6(mat)
    expected = Rat(pscale(pmul(hbar, hbar), Fraction(1, 2)), 0)
    if witness is not None:
        witness.update(computed=_rat_witness(pf), expected=_rat_witness(expected))
    return pf == expected


# --- exact complex arithmetic on Gaussian rationals -----------------------
def _cx(re_, im_):
    return (Fraction(re_), Fraction(im_))


def _cx_mul(a, b):
    return (a[0] * b[0] - a[1] * b[1], a[0] * b[1] + a[1] * b[0])


def _cx_div(a, b):
    den = b[0] * b[0] + b[1] * b[1]
    return ((a[0] * b[0] + a[1] * b[1]) / den, (a[1] * b[0] - a[0] * b[1]) / den)


def _readout_derivatives(u1, u2, expi):
    """f'(0), f''(0) for z(e)=u1 sqrt(1+e)+expi*u2 sqrt(1-e), cleared form."""
    z0 = (u1[0] + _cx_mul(expi, u2)[0], u1[1] + _cx_mul(expi, u2)[1])
    w = _cx_mul(expi, u2)
    zp = (u1[0] / 2 - w[0] / 2, u1[1] / 2 - w[1] / 2)
    zpp = (-u1[0] / 4 - w[0] / 4, -u1[1] / 4 - w[1] / 4)
    ratio = _cx_div(zp, z0)
    ratio2 = _cx_div(zpp, z0)
    sq = _cx_mul(ratio, ratio)
    return ratio[1], (ratio2[1] - sq[1])


def _rat_m0(rat):
    """Substitute m = 0 (so r = n, positive branch) into a Rat."""
    num = {}
    for mono, coeff in rat.num.items():
        if mono[IDX["m"]]:
            continue
        b = list(mono)
        b[IDX["n"]] += b[IDX["r"]] - rat.rpow  # r = n at m = 0
        b[IDX["r"]] = 0
        num[tuple(b)] = num.get(tuple(b), Fraction(0)) + coeff
    return Rat(num, 0)


def _vs1_at_m0(f):
    eta, ch, chx, n, c_ = (pvar("eta"), pvar("chibar"), pvar("chibarX"),
                           pvar("n"), pvar("C"))
    expected = {
        "F_mphi": Rat({}, 0), "F_nm": Rat({}, 0),
        "F_nphi": Rat(pmul(pmul(pmul(pconst(2), eta), ch), pmul(n, c_)), 0),
        "F_Xphi": Rat(pmul(pmul(pmul(eta, chx), n), pmul(n, c_)), 0),
        "F_Xn": Rat({}, 0), "F_Xm": Rat({}, 0),
    }
    # F_Xphi at m=0: eta*chibarX*n*r*C with r=n gives eta*chibarX*n^2*C,
    # which _rat_m0 produces from the general Rat.
    return all(_rat_m0(f[k]) == v for k, v in expected.items())


def _vs3_symbolic(witness=None):
    """Symbolic m=0 EL identity: the phi row with mdot eliminated.

    Multiplied through by hbar to stay in the r-localised grammar. With
    HM = hbar*mdot_formula = -2*eta*C*D_t(chibar*n^2), the row
    -hbar*F_nphi*ndot - (1/2)*hbar*HM - hbar*F_Xphi*Xdot
    - hbar*eta*ptc*n*r*C must be the zero Rat. This is an exact symbolic
    identity in (n, C, chibar, chibarX, ndot, Xdot, ptc), not a sample.
    """
    f = {k: _rat_m0(v) for k, v in curvature().items()}  # m = 0 identity
    eta, ch, chx, n, r, c_ = (pvar("eta"), pvar("chibar"), pvar("chibarX"),
                              pvar("n"), pvar("r"), pvar("C"))
    hbar, ndot, xdot, ptc = (pvar("hbar"), pvar("ndot"), pvar("Xdot"),
                             pvar("ptc"))
    dt_poly = padd(pmul(pmul(pconst(2), ch), pmul(n, ndot)),
                   padd(pmul(chx, pmul(xdot, pmul(n, n))),
                        pmul(ptc, pmul(n, n))))
    hm = Rat(pscale(pmul(pmul(eta, c_), dt_poly), -2), 0)
    terms = [
        rmul(Rat(pmul(hbar, f["F_nphi"].num), f["F_nphi"].rpow),
             Rat(ndot, 0)),
        rmul(Rat(pscale(hbar, Fraction(1, 2)), 0),
             Rat(hm.num, hm.rpow)),
        rmul(Rat(pmul(hbar, f["F_Xphi"].num), f["F_Xphi"].rpow),
             Rat(xdot, 0)),
        Rat(pmul(pmul(pmul(hbar, eta), ptc), pmul(pmul(n, n), c_)), 0),
    ]
    total = terms[0]
    for term in terms[1:]:
        total = radd(total, term)
    # the row is the negative of this sum by construction of HM; the
    # identity checked is that the assembled row expression vanishes
    # when mdot is eliminated, i.e. total == eta*C*hbar*Dt*0 form:
    if witness is not None:
        witness["cleared_row_residual"] = _rat_witness(total)
    return total == Rat(pscale(pmul(pmul(hbar, eta),
                                    pmul(c_, dt_poly)), 0), 0) or total.num == {}


def _hinv_matrix():
    """hbar * Omega0^-1 for order (n, thetabar, m, phi), as Rats."""
    zero, one = Rat({}, 0), Rat(pconst(1), 0)
    neg = Rat(pconst(-1), 0)
    two, negtwo = Rat(pconst(2), 0), Rat(pconst(-2), 0)
    return [[zero, neg, zero, zero], [one, zero, zero, zero],
            [zero, zero, zero, negtwo], [zero, zero, two, zero]]


def _mat_rat_vec(mat, vec):
    out = []
    for row in mat:
        total = Rat({}, 0)
        for entry, v in zip(row, vec):
            total = radd(total, rmul(entry, v))
        out.append(total)
    return out


def _vs8_symbolic(witness=None):
    """Compare all hbar-scaled optical rows at m=0 to closed forms."""
    zero = Rat({}, 0)
    hb = Rat(pvar("hbar"), 0)
    f = {key: _rat_m0(value) for key, value in curvature().items()}
    fnphi, fxphi = f["F_nphi"], f["F_Xphi"]
    names = ("n", "thetabar", "m", "phi")
    fmat = [[f.get(f"F_{i}{j}", zero) for j in names] for i in names]
    hinv = _hinv_matrix()
    omega, delta, bath_phi, xdot = (
        Rat(pvar(name), 0) for name in ("omg", "Delta", "Vb", "Xdot")
    )
    total_n, hamiltonian_n = (Rat(pvar(name), 0) for name in ("ndot", "ndot_H"))
    total_phi = radd(delta, bath_phi)
    v0 = [total_n, omega, zero, total_phi]
    vh = [hamiltonian_n, omega, zero, delta]
    pt_phi = Rat(pmul(pmul(pmul(pvar("eta"), pvar("ptc")),
                           pmul(pvar("n"), pvar("n"))), pvar("C")), 0)
    field_source = [zero, zero, zero, radd(pt_phi, rmul(fxphi, xdot))]
    field_velocity = _mat_rat_vec(hinv, field_source)
    passed = True
    for name, drive, phase_drive in (("OM-S", v0, total_phi), ("OM-2", vh, delta)):
        curvature_velocity = _mat_rat_vec(hinv, _mat_rat_vec(fmat, drive))
        scaled = [radd(rsub(rmul(hb, base), cv), tv)
                  for base, cv, tv in zip(v0, curvature_velocity, field_velocity)]
        imbalance = radd(field_source[3], rmul(fnphi, drive[0]))
        expected = [
            rmul(hb, total_n),
            rsub(rmul(hb, omega), rmul(fnphi, phase_drive)),
            Rat(pscale(imbalance.num, -2), imbalance.rpow),
            rmul(hb, total_phi),
        ]
        if witness is not None:
            witness[name] = {row: {"hbar_scaled_velocity": _rat_witness(actual),
                                   "expected": _rat_witness(target)}
                             for row, actual, target in zip(
                                 names, scaled, expected)}
        passed &= all(actual == target for actual, target in zip(scaled, expected))
    return passed


def _rat_witness(value):
    return {"r_denominator_power": value.rpow,
            "terms": [{"powers": {name: exp for name, exp in zip(VARS, mono) if exp},
                       "coefficient": str(coeff)}
                      for mono, coeff in sorted(value.num.items())]}


CHECK_GUARDS = {
    'VS11': ('n > |m|', 'r > 0'),
    'VS1': ('m = 0', 'n > 0'),
    'VS2': ('u = s*nu',),
    'VS3': ('m = 0', 'n > 0', 'hbar != 0'),
    'VS4': ('r > 0', 'hbar != 0'),
    'VS5': ('exact integration along frozen piecewise-linear paths',),
    'VS6': ('matched mirror histories', 'Cmode != 0 before clearing'),
    'VS7': ('D > 0', 'P != 0', 'E = exp(-mu D) > 0'),
    'VS8': ('m = 0', 'n > 0', 'hbar != 0', 'first order in eta', 'nonzero readout field'),
    'VS9': ('positive separation on the declared collinear branch', 'P != 0'),
    'VS10': ('arithmetic conversion only; physical bound conditional on declared source scope',),
    'VS12': ('closed frozen paths', 'r > 0', 'nonzero readout field', 'quotient requires nonzero product'),
    'AC-T1': ('nonzero field throughout the endpoint interval', 'frozen 1e-9 relative arithmetic allowance'),
    'AC-T2': ('nonzero field throughout the endpoint interval', 'frozen 1e-9 relative arithmetic allowance'),
}


def _evaluate_checks():
    """Collect outcomes and the witnesses used to compute them."""
    global _ops
    checks = {}

    def retain(name, outcome, quantity):
        checks[name] = {"outcome": outcome, "quantity": quantity,
                        "guard": list(CHECK_GUARDS[name])}
        _ops[0] = 0

    _ops = [0]
    f = curvature()
    _ops[0] = 0
    exp = _expected_curvature()
    retain("VS11", all(f[k] == v for k, v in exp.items()),
           {k: _rat_witness(f[k]) for k in exp})
    retain("VS1", _vs1_at_m0(f),
           {k: _rat_witness(_rat_m0(f[k])) for k in exp})
    s = Rat(pvar("s"))
    u = Rat(pmul(pvar("s"), pvar("nu")))
    dnu_coeff = rmul(s, rderiv(u, "nu"))
    ds_coeff = rsub(rmul(s, rderiv(u, "s")), u)
    retain("VS2", dnu_coeff == Rat(pvar("s", 2)) and ds_coeff == Rat({}),
           {"dnu_coefficient": _rat_witness(dnu_coeff),
            "ds_coefficient": _rat_witness(ds_coeff)})
    vs3 = {}
    symbolic = _vs3_symbolic(vs3)
    samples = _mdot_terms(vs3)
    retain("VS3", symbolic and samples, vs3)
    pfaffian = {}
    retain("VS4", _pfaffian_check(pfaffian), pfaffian)
    loops = loop_values()
    expected = {"Ks": Fraction(-3, 2), "Ls": -1, "Ls_reversed": 1,
                "Ks_reversed": Fraction(3, 2), "Ks_depth": Fraction(-5, 2),
                "AXnu": -2, "Bsnu": -2, "collapsed": 0}
    retain("VS5", loops == expected, {k: str(v) for k, v in loops.items()})
    closure = {}
    retain("VS6", _closure_check(closure), closure)
    yukawa = {}
    retain("VS7", _yukawa_check(yukawa), yukawa)
    models = {}
    symbolic = _vs8_symbolic(models)
    adverse = _om_adverse_check(models)
    retain("VS8", symbolic and adverse, models)
    third_law = {}
    retain("VS9", _third_law_check(third_law), third_law)
    kapner = {}
    retain("VS10", _kapner_check(kapner), kapner)
    nulls = {}
    retain("VS12", _null_cases_check(nulls), nulls)
    for case in (1, 2):
        quantity = {}
        retain(f"AC-T{case}", _ac_case(case, quantity), quantity)
    return checks


def evaluate_all():
    """Return the existing Boolean checker interface."""
    return {name: result["outcome"] for name, result in _evaluate_checks().items()}


def _mdot_terms(witness=None):
    """Derive the m=0 imbalance equation from the W row for phi.

    At m = 0 the phi row sum_j W_phi,j qdot_j = (partial_t A)_phi reads
    -F_nphi*ndot - (hbar/2)*mdot - F_Xphi*Xdot = eta*n^2*C*pt_chibar, with
    the F values taken from this module's derived curvature, not inserted.
    Solving for mdot must reproduce -eta*C*D_t(chibar*n^2)/(hbar/2) with
    D_t(chibar*n^2) = 2*chibar*n*ndot + chibarX*Xdot*n^2 + pt*n^2, for
    several independent rational velocity triples. A wrong coefficient
    or sign in either side fails.
    """
    f = curvature()
    pt = {"n": Fraction(2), "m": Fraction(0), "r": Fraction(2),
          "C": Fraction(3, 5), "S": Fraction(4, 5),
          "chibar": Fraction(1, 3), "chibarX": Fraction(1, 2),
          "hbar": Fraction(2), "eta": Fraction(1), "s": Fraction(0),
          "nu": Fraction(0), "X": Fraction(0), "N0": Fraction(1),
          "bP": Fraction(0), "s0": Fraction(0), "Ks": Fraction(0),
          "Aeff": Fraction(0)}
    f_nphi = eval_rat(f["F_nphi"], pt)
    f_xphi = eval_rat(f["F_Xphi"], pt)
    half_hbar = Fraction(1)  # hbar = 2 at this point
    samples = []
    for ndot, xdot, ptc in ((Fraction(3), Fraction(-1), Fraction(2)),
                            (Fraction(-2), Fraction(5), Fraction(1)),
                            (Fraction(0), Fraction(1), Fraction(-3))):
        mdot_from_row = (-f_nphi * ndot - f_xphi * xdot
                         - 1 * 4 * Fraction(3, 5) * ptc) / half_hbar
        dt_ch_n2 = (2 * Fraction(1, 3) * 2 * ndot
                    + Fraction(1, 2) * xdot * 4 + ptc * 4)
        mdot_formula = -1 * Fraction(3, 5) * dt_ch_n2 / half_hbar
        samples.append({"ndot": str(ndot), "xdot": str(xdot), "partial_t_chibar": str(ptc),
                        "computed_mdot": str(mdot_from_row), "expected_mdot": str(mdot_formula)})
    if witness is not None:
        witness["m0_row_samples"] = samples
    return all(sample["computed_mdot"] == sample["expected_mdot"] for sample in samples)


def _closure_check(witness=None):
    eta, n0, bp, s0, ks, aeff, hbar = (pvar("eta"), pvar("N0"), pvar("bP"),
                                       pvar("s0"), pvar("Ks"), pvar("Aeff"),
                                       pvar("hbar"))
    cmode = pmul(hbar, n0)
    t_f = pscale(pmul(pmul(eta, pmul(n0, n0)), pmul(bp, ks)), -4)
    t_psi = pscale(pmul(pmul(pmul(eta, pmul(n0, n0)), bp),
                        pmul(s0, aeff)), -8)
    # Cmode*T_Psi*Ks - 2*s0*T_F*Aeff with T_Psi carrying 1/Cmode: multiply
    # through by Cmode symbolically by treating T_Psi*Cmode as t_psi_num.
    expr = padd(pmul(t_psi, ks), pscale(pmul(pmul(s0, t_f), aeff), -2))
    if witness is not None:
        witness["cleared_closure_residual"] = _rat_witness(Rat(expr))
    return expr == {}


def _mono_deriv_dist(expr):
    """d/d(dist) on monomials (mu, D, E, P): D-power rule plus dE = -mu*E."""
    out = {}
    for (a, b, c, d), coeff in expr.items():
        if b:
            key = (a, b - 1, c, d)
            out[key] = out.get(key, Fraction(0)) + coeff * b
        if c:
            key = (a + 1, b, c, d)
            out[key] = out.get(key, Fraction(0)) - coeff * c
    return {k: v for k, v in out.items() if v}


def _mono_mul_mu_plus_inv_d(expr):
    out = {}
    for (a, b, c, d), coeff in expr.items():
        out[(a + 1, b, c, d)] = out.get((a + 1, b, c, d), Fraction(0)) + coeff
        out[(a, b - 1, c, d)] = out.get((a, b - 1, c, d), Fraction(0)) + coeff
    return {k: v for k, v in out.items() if v}


def _yukawa_check(witness=None):
    # expr = E/(P*D) as (mu, D, E, P) exponents; dist = D - X so d_X = -d_dist.
    expr = {(0, -1, 1, -1): Fraction(1)}
    d_dist = _mono_deriv_dist(expr)
    d_x = {k: -v for k, v in d_dist.items()}
    expected = _mono_mul_mu_plus_inv_d(expr)
    if witness is not None:
        witness.update(d_X=_yukawa_terms(d_x), expected=_yukawa_terms(expected))
    return d_x == expected and d_x != {}


def _yukawa_terms(expr):
    return [{"powers": dict(zip(("mu", "D", "E", "P"), powers)),
             "coefficient": str(coefficient)}
            for powers, coefficient in sorted(expr.items())]


def _third_law_check(witness=None):
    # Same shared source expression; dist = Y - X so d_Y = +d_dist.
    expr = {(0, -1, 1, -1): Fraction(1)}
    d_dist = _mono_deriv_dist(expr)
    d_x = {k: -v for k, v in d_dist.items()}
    d_y = dict(d_dist)
    total = {k: d_x.get(k, Fraction(0)) + d_y.get(k, Fraction(0))
             for k in set(d_x) | set(d_y)}
    if witness is not None:
        witness.update(d_X=_yukawa_terms(d_x), d_Y=_yukawa_terms(d_y),
                       derivative_sum=_yukawa_terms(total))
    return all(v == 0 for v in total.values()) and d_x == \
        {k: -v for k, v in d_y.items()} and d_y != {}


def _kapner_check(witness=None):
    with localcontext() as ctx:
        ctx.prec = 50
        pi = Decimal("3.1415926535897932384626433832795028841971693993751")
        g = Decimal("6.67430E-11")
        u = Decimal("1.66053906660E-27")
        value = (4 * pi * g).sqrt() * u
        computed = math.sqrt(4 * math.pi * float(g)) * float(u)
        relative_error = abs(Decimal.from_float(computed) - value) / value
        if witness is not None:
            witness.update(computed=computed, reference=str(value),
                           relative_error=str(relative_error), relative_limit="1e-12")
        return (relative_error <= Decimal("1e-12")
                and abs(value - Decimal("4.81E-32")) < Decimal("0.01E-32"))


def _mat_inv(mat):
    size = len(mat)
    aug = [list(row) + [Fraction(1) if i == j else Fraction(0)
                         for j in range(size)] for i, row in enumerate(mat)]
    for col in range(size):
        piv = next(r for r in range(col, size) if aug[r][col])
        aug[col], aug[piv] = aug[piv], aug[col]
        scale = aug[col][col]
        aug[col] = [v / scale for v in aug[col]]
        for row in range(size):
            if row != col and aug[row][col]:
                factor = aug[row][col]
                aug[row] = [a - factor * b for a, b in zip(aug[row], aug[col])]
    return [row[size:] for row in aug]


def _mat_vec(mat, vec):
    return [sum(mat[i][j] * vec[j] for j in range(len(vec)))
            for i in range(len(vec))]


def row_mdot_at(ndot, xdot, ptc):
    """mdot solved from the derived W phi row at the VS3 point."""
    f = curvature()
    pt = {"n": Fraction(2), "m": Fraction(0), "r": Fraction(2),
          "C": Fraction(3, 5), "S": Fraction(4, 5),
          "chibar": Fraction(1, 3), "chibarX": Fraction(1, 2),
          "hbar": Fraction(2), "eta": Fraction(1), "s": Fraction(0),
          "nu": Fraction(0), "X": Fraction(0), "N0": Fraction(1),
          "bP": Fraction(0), "s0": Fraction(0), "Ks": Fraction(0),
          "Aeff": Fraction(0)}
    return (-eval_rat(f["F_nphi"], pt) * ndot
            - eval_rat(f["F_Xphi"], pt) * xdot
            - 4 * Fraction(3, 5) * ptc)


def mdot_value(ndot, xdot, ptc):
    """mdot from the VS3 formula at the VS3 point (hbar = 2)."""
    dt_ch_n2 = (2 * Fraction(1, 3) * 2 * ndot
                + Fraction(1, 2) * xdot * 4 + ptc * 4)
    return -1 * Fraction(3, 5) * dt_ch_n2 / Fraction(1)


def om_terms_at():
    """Return (force_S, force_2, F_Xphi) from the _om_adverse derivation."""
    f = curvature()
    pt = {"n": Fraction(2), "m": Fraction(0), "r": Fraction(2),
          "C": Fraction(1), "S": Fraction(0), "chibar": Fraction(1, 3),
          "chibarX": Fraction(1, 2), "hbar": Fraction(2),
          "eta": Fraction(1), "s": Fraction(0), "nu": Fraction(0),
          "X": Fraction(0), "N0": Fraction(1), "bP": Fraction(0),
          "s0": Fraction(0), "Ks": Fraction(0), "Aeff": Fraction(0)}
    val = lambda name: eval_rat(f[name], pt)
    omega0 = [[Fraction(0)] * 4 for _ in range(4)]
    omega0[0][1], omega0[1][0] = Fraction(2), Fraction(-2)
    omega0[2][3], omega0[3][2] = Fraction(1), Fraction(-1)
    wmat = [row[:] for row in omega0]
    order = ["n", "thetabar", "m", "phi"]
    for (a, b), v in {("n", "phi"): val("F_nphi"),
                      ("m", "phi"): val("F_mphi"),
                      ("n", "m"): val("F_nm")}.items():
        i, j = order.index(a), order.index(b)
        wmat[i][j] = wmat[i][j] + v
        wmat[j][i] = wmat[j][i] - v
    winv = _mat_inv(wmat)
    v0 = [Fraction(0), Fraction(1), Fraction(0), Fraction(3)]
    dh = [Fraction(2), Fraction(0), Fraction(0), Fraction(0)]
    rhs_s = [sum(omega0[i][j] * v0[j] for j in range(4)) for i in range(4)]
    qdot_s = _mat_vec(winv, rhs_s)
    qdot_h = _mat_vec(winv, dh)
    f_xphi = val("F_Xphi")
    return f_xphi * qdot_s[3], f_xphi * qdot_h[3], f_xphi


def om_terms_general(assignment, v0, dh, pta=None):
    """(force_S, force_2) by exact W inversion at an arbitrary point."""
    f = curvature()
    val = lambda name: eval_rat(f[name], assignment)
    omega0 = [[Fraction(0)] * 4 for _ in range(4)]
    hb = assignment["hbar"]
    omega0[0][1], omega0[1][0] = hb, -hb
    omega0[2][3], omega0[3][2] = hb / 2, -hb / 2
    wmat = [row[:] for row in omega0]
    order = ["n", "thetabar", "m", "phi"]
    for (a, b) in (("n", "phi"), ("m", "phi"), ("n", "m")):
        i, j = order.index(a), order.index(b)
        v = val(f"F_{a}{b}")
        wmat[i][j] = wmat[i][j] + v
        wmat[j][i] = wmat[j][i] - v
    winv = _mat_inv(wmat)
    pta = list(pta) if pta is not None else [Fraction(0)] * 4
    rhs = [sum(omega0[i][j] * v0[j] for j in range(4)) + pta[i]
           for i in range(4)]
    qdot_s = _mat_vec(winv, rhs)
    qdot_h = _mat_vec(winv, [dh[i] + pta[i] for i in range(4)])
    return val("F_Xphi") * qdot_s[3], val("F_Xphi") * qdot_h[3]


def velocity_components_general(assignment, v0, dh, pta=None):
    """Full first-order-model velocity vectors at a point.

    Returns (qdot_S, qdot_2): OM-S is W^-1 (Omega0 V0 + ptA); OM-2 is
    W^-1 (dH + ptA) plus the bath velocity V0 - Omega0^-1 dH, both by
    exact rational inversion of the same W the forces use.
    """
    f = curvature()
    val = lambda name: eval_rat(f[name], assignment)
    hb = assignment["hbar"]
    omega0 = [[Fraction(0)] * 4 for _ in range(4)]
    omega0[0][1], omega0[1][0] = hb, -hb
    omega0[2][3], omega0[3][2] = hb / 2, -hb / 2
    wmat = [row[:] for row in omega0]
    order = ["n", "thetabar", "m", "phi"]
    for (a, b) in (("n", "phi"), ("m", "phi"), ("n", "m")):
        i, j = order.index(a), order.index(b)
        v = val(f"F_{a}{b}")
        wmat[i][j] = wmat[i][j] + v
        wmat[j][i] = wmat[j][i] - v
    winv = _mat_inv(wmat)
    oinv = _mat_inv(omega0)
    pta = list(pta) if pta is not None else [Fraction(0)] * 4
    rhs_s = [sum(omega0[i][j] * v0[j] for j in range(4)) + pta[i]
             for i in range(4)]
    qdot_s = _mat_vec(winv, rhs_s)
    qdot_h = _mat_vec(winv, [dh[i] + pta[i] for i in range(4)])
    bath = [v0[i] - _mat_vec(oinv, list(dh))[i] for i in range(4)]
    qdot_2 = [qdot_h[i] + bath[i] for i in range(4)]
    return qdot_s, qdot_2


@dataclass(frozen=True, slots=True, init=False, eq=False, weakref_slot=True)
class _CheckedRow:
    """An identity-bound handle for a checker-issued witness."""

    name: str
    payload: bytes

    def __init__(self):
        raise TypeError("checked rows come from evaluate_report_rows")


# A dataclass restoration hook can change a row's slots. Retain the
# evaluation's original bytes independently of that state. Identity keys
# prevent unissued copies from matching and expire with the issued rows.
_ISSUED_WITNESSES: WeakKeyDictionary[_CheckedRow, tuple[str, bytes]] = WeakKeyDictionary()


def evaluate_report_rows():
    """Bind every check ID to its computed outcome, quantities and guards."""
    rows = {}
    for name, witness in _evaluate_checks().items():
        row = object.__new__(_CheckedRow)
        payload = json.dumps(witness, separators=(",", ":"), allow_nan=False).encode()
        object.__setattr__(row, "name", name)
        object.__setattr__(row, "payload", payload)
        _ISSUED_WITNESSES[row] = (name, payload)
        rows[name] = row
    return rows


def report_witness(name, row):
    """Decode the original result only if identity, check ID and bytes match."""
    issued = _ISSUED_WITNESSES.get(row) if type(row) is _CheckedRow else None
    if issued is not None:
        issued_name, issued_payload = issued
        row_name = getattr(row, "name", None)
        payload = getattr(row, "payload", None)
        if (type(row_name) is str and row_name == issued_name == name
                and type(payload) is bytes and payload == issued_payload):
            return json.loads(issued_payload)
    raise ValueError(f"invalid_check_witness:{name}")


def evaluate_quantities():
    """Return computed witnesses and their declared domains without dispatch."""
    return _evaluate_checks()


def yukawa_dx_ratio_at(mu, dist):
    """Evaluate the checker's monomial d_X(E/(P D)) divided by E/(P D)."""
    expr = {(0, -1, 1, -1): Fraction(1)}
    d_x = {k: -v for k, v in _mono_deriv_dist(expr).items()}
    def ev(e):
        return sum(c * mu ** a * dist ** b for (a, b, c_, d), c in
                   [(k, v) for k, v in e.items()] for a, b, c_, d in [k])
    # evaluate with E = P = 1
    def ev2(e):
        total = Fraction(0)
        for (a, b, c_, d), coeff in e.items():
            total += coeff * mu ** a * dist ** b
        return total
    return ev2(d_x) / ev2(expr)


def _om_adverse_check(witness=None):
    """Velocities from the two declared open-model definitions.

    At a rational m=0 point with Delta = 0, static field and a bath/drive
    phi velocity Vb != 0: OM-S qdot = W^-1 (Omega0 V0 + ptA) gives a
    mechanical C3-S term +F_Xphi*phidot_S, while OM-2, whose bath velocity
    is added after the inversion, gives zero. F values come from the
    derived curvature; the matrices are inverted exactly.
    """
    f = curvature()
    pt = {"n": Fraction(2), "m": Fraction(0), "r": Fraction(2),
          "C": Fraction(1), "S": Fraction(0), "chibar": Fraction(1, 3),
          "chibarX": Fraction(1, 2), "hbar": Fraction(2),
          "eta": Fraction(1), "s": Fraction(0), "nu": Fraction(0),
          "X": Fraction(0), "N0": Fraction(1), "bP": Fraction(0),
          "s0": Fraction(0), "Ks": Fraction(0), "Aeff": Fraction(0)}
    val = lambda name: eval_rat(f[name], pt)
    # optical order (n, thetabar, m, phi); Omega0 pairings hbar, hbar/2
    omega0 = [[Fraction(0)] * 4 for _ in range(4)]
    omega0[0][1], omega0[1][0] = Fraction(2), Fraction(-2)
    omega0[2][3], omega0[3][2] = Fraction(1), Fraction(-1)
    wmat = [row[:] for row in omega0]
    pairs = {("n", "phi"): val("F_nphi"), ("m", "phi"): val("F_mphi"),
             ("n", "m"): val("F_nm")}
    order = ["n", "thetabar", "m", "phi"]
    for (a, b), v in pairs.items():
        i, j = order.index(a), order.index(b)
        wmat[i][j] = wmat[i][j] + v
        wmat[j][i] = wmat[j][i] - v
    winv = _mat_inv(wmat)
    vb = Fraction(3)
    v0 = [Fraction(0), Fraction(1), Fraction(0), vb]  # omega = 1 here
    dh = [Fraction(2), Fraction(0), Fraction(0), Fraction(0)]
    pta = [Fraction(0)] * 4
    rhs_s = [sum(omega0[i][j] * v0[j] for j in range(4)) + pta[i]
             for i in range(4)]
    qdot_s = _mat_vec(winv, rhs_s)
    qdot_h = _mat_vec(winv, dh)
    f_xphi = val("F_Xphi")
    force_s = f_xphi * qdot_s[3]
    force_2 = f_xphi * qdot_h[3]
    fp, _ = _readout_derivatives(_cx(1, 0), _cx(Fraction(1, 2), 0),
                                 _cx(0, 1))
    if witness is not None:
        witness["adverse_static_drive"] = {
            "OM-S_signed_projection": str(force_s),
            "OM-2_signed_projection": str(force_2),
            "projection_convention": "+F_Xphi * phi_velocity",
            "readout_derivative": str(fp), "Delta": "0", "bath_phi_velocity": str(vb)}
    return force_2 == 0 and force_s == Fraction(6) and fp == Fraction(-2, 5)


def _closure_quotient(product):
    if product == 0:
        return "quotient_undefined"
    return Fraction(1, 1) / product


def _null_cases_check(witness=None):
    f = curvature()
    pt = {"n": Fraction(2), "m": Fraction(0), "r": Fraction(2),
          "C": Fraction(1), "S": Fraction(0), "chibar": Fraction(0),
          "chibarX": Fraction(1), "hbar": Fraction(2), "eta": Fraction(1),
          "s": Fraction(0), "nu": Fraction(0), "X": Fraction(0),
          "N0": Fraction(1), "bP": Fraction(0), "s0": Fraction(0),
          "Ks": Fraction(0), "Aeff": Fraction(0)}
    local_gradient = eval_rat(f["F_Xphi"], pt) != 0       # chibar=0 case
    pt2 = dict(pt, chibar=Fraction(1, 3))
    local_phase = eval_rat(f["F_nphi"], pt2) != 0
    collapsed = _edge_integral([(Fraction(1), Fraction(1))] * 2, "Ks") == 0
    # total variation of X over the rectangle is 2*DX = 2 (DX = 1)
    travel = sum(abs(RECT[(i + 1) % 4][0] - RECT[i][0])
                 for i in range(4)) == 2
    # spring integral over the closed rectangle: sum (x1^2-x0^2)/2 = 0
    spring = sum((RECT[(i + 1) % 4][0] ** 2 - RECT[i][0] ** 2) / 2
                 for i in range(4)) == 0
    # formal mechanical difference OM-S minus OM-2 is F_Xphi*Vb, a
    # nonzero Rat (not merely a nonzero number at one point)
    mech_diff = rmul(f["F_Xphi"], Rat(pvar("Vb"), 0))
    # detected m/n phase term: exact readout derivative is nonzero here
    fp, _ = _readout_derivatives(_cx(1, 0), _cx(Fraction(1, 2), 0),
                                  _cx(0, 1))
    u1r, u1i, u2r, u2i = (pvar("u1r"), pvar("u1i"), pvar("u2r"),
                          pvar("u2i"))
    cc, ss = pvar("C"), pvar("S")
    wr = padd(pmul(cc, u2r), pscale(pmul(ss, u2i), -1))
    wi = padd(pmul(cc, u2i), pmul(ss, u2r))
    zr = padd(u1r, wr)
    zi = padd(u1i, wi)
    zpr = pscale(padd(u1r, pscale(wr, -1)), Fraction(1, 2))
    zpi = pscale(padd(u1i, pscale(wi, -1)), Fraction(1, 2))
    nonidentity = padd(pmul(zr, zpi), pscale(pmul(zi, zpr), -1))
    phase_point = {"u1r": Fraction(1), "u1i": Fraction(0),
                   "u2r": Fraction(1, 2), "u2i": Fraction(0),
                   "C": Fraction(0), "S": Fraction(1), "r": Fraction(2)}
    phase_numerator_at_point = eval_rat(Rat(nonidentity), phase_point)
    phase_denominator_at_point = sum(
        eval_rat(Rat(component), phase_point) ** 2 for component in (zr, zi))
    if witness is not None:
        witness.update(phase_numerator=_rat_witness(Rat(nonidentity)),
                       phase_numerator_at_point=str(phase_numerator_at_point),
                       phase_denominator_at_point=str(phase_denominator_at_point),
                       mechanical_difference=_rat_witness(mech_diff),
                       phase_derivative=str(fp), gradient_at_chibar_zero=str(eval_rat(f["F_Xphi"], pt)),
                       local_phase_curvature=str(eval_rat(f["F_nphi"], pt2)),
                       collapsed_zero=collapsed, travel_matches=travel,
                       spring_integral_zero=spring,
                       zero_product_state=_closure_quotient(Fraction(0)),
                       nonzero_product_quotient=str(_closure_quotient(Fraction(2))))
    return (nonidentity != {} and local_gradient and local_phase and collapsed and travel
            and spring and mech_diff.num != {} and fp == Fraction(-2, 5)
            and phase_numerator_at_point == Fraction(-1, 2)
            and phase_denominator_at_point == Fraction(5, 4)
            and phase_numerator_at_point == fp * phase_denominator_at_point
            and _closure_quotient(Fraction(0)) == "quotient_undefined"
            and _closure_quotient(Fraction(2)) == Fraction(1, 2))


def f2_bound(u_abs_sum, epsilon_max, z_min):
    """Complete |f''| bound F2 = Z2/z_min + Z1^2/z_min^2 (float)."""
    z1 = u_abs_sum / (2 * math.sqrt(1 - epsilon_max))
    z2 = u_abs_sum / (4 * (1 - epsilon_max) ** 1.5)
    return z2 / z_min + z1 * z1 / (z_min * z_min)


def _ac_case(which, witness=None):
    if which == 1:
        u1, u2, expi = _cx(1, 0), _cx(Fraction(-9, 10), Fraction(1, 10)), _cx(1, 0)
        fp, fpp = _readout_derivatives(u1, u2, expi)
        def phase(e):
            z = complex(math.sqrt(1 + e), 0) + complex(-0.9, 0.1) * math.sqrt(1 - e)
            return math.atan2(z.imag, z.real)
        residual = abs(phase(0.001) - phase(0.0) - (-5.0) * 0.001)
        u_sum = 1 + math.hypot(-0.9, 0.1)
        bound = f2_bound(u_sum, 0.001, 0.13) / 2 * 0.001 ** 2
        if witness is not None:
            witness.update(first_derivative=str(fp), second_derivative=str(fpp),
                           residual_rad=residual, bound_rad=bound, epsilon_max=0.001,
                           z_min=0.13, relative_allowance=1e-9)
        return fp == -5 and fpp == 45 and 0 < residual <= bound * (1 + 1e-9)
    u1, u2, expi = _cx(1, 0), _cx(0, Fraction(1, 2)), _cx(1, 0)
    fp, fpp = _readout_derivatives(u1, u2, expi)
    def phase(e):
        z = complex(math.sqrt(1 + e), 0) + complex(0, 0.5) * math.sqrt(1 - e)
        return math.atan2(z.imag, z.real)
    increment = abs(phase(0.001) - phase(-0.001))
    # summed two-endpoint linear bound plus F2*epsilon_max^2, frozen budget
    bound = (abs(float(fp)) * 0.001 + abs(float(fp)) * 0.001
             + f2_bound(1.5, 0.001, 1.0) * 0.001 ** 2)
    if witness is not None:
        witness.update(first_derivative=str(fp), increment_rad=increment,
                       bound_rad=bound, epsilon_max=0.001, z_min=1.0,
                       relative_allowance=1e-9)
    return fp == Fraction(-2, 5) and increment <= bound * (1 + 1e-9)


LAUNCH_TWIN_SHA256 = "e6756e1c579b8bb86177c9c1ea9f5919fd091a4e014262bfb58165861ae983be"
LAUNCH_KEYS = {
    "status", "study", "evidence_kind", "slice_kind", "precedence",
    "human_protocol", "source_ledger", "diagram", "protocol_state",
    "protocol_revision", "execution_authorised",
    "fixture_verification_authorised", "authorised_modes",
    "implementation_authorisation", "review_state", "base_commit",
    "revision_history", "bounded_question_revision_3",
    "bounded_question_revision_4", "bounded_question_revision_5",
    "root_findings_revision_2", "atlas_plan", "action", "system",
    "hypotheses", "symmetry", "control_H_c", "phase_definitions",
    "propositions", "reachable_loops", "open_models", "environment",
    "readout", "predictions", "falsification_predicates",
    "classifier_states", "interventions", "joint_rival",
    "guards_and_cases", "forward_paths", "verification_plan_prospective",
    "supported_claims", "prohibited_claims", "unproved",
    "authoritative_contract_revision_7", "frozen_references", "bounds",
    "denominators", "points"}
_PATH_PREFIX = "experiments/pf-001/"


def parse_launch_protocol(data):
    """Strict launch-twin validation. The checker itself accepts only
    fixed compiled expressions (no generic expression input exists);
    this validator is the single input boundary for launch data."""
    if len(data) > 131072:
        raise Refusal("input_bytes")
    import hashlib as _hashlib
    if _hashlib.sha256(data).hexdigest() != LAUNCH_TWIN_SHA256:
        raise Refusal("launch_twin_not_frozen")
    text = data.decode("utf-8")
    _depth = _max = _tokens = 0
    _in_str = _esc = False
    for _ch in text:
        if _in_str:
            if _esc:
                _esc = False
            elif _ch == "\\":
                _esc = True
            elif _ch == '"':
                _in_str = False
            continue
        if _ch == '"':
            _in_str = True
            _tokens += 1
        elif _ch in "[{":
            _depth += 1
            _max = max(_max, _depth)
            _tokens += 1
        elif _ch in "]}":
            _depth -= 1
        elif _ch in ",:":
            _tokens += 1
    if _max > 12:
        raise Refusal("depth_preflight")
    if _tokens > 10000:
        raise Refusal("nodes_preflight")
    def no_dup(pairs):
        out = {}
        for k, v in pairs:
            if k in out:
                raise Refusal("duplicate_key")
            out[k] = v
        return out
    def no_const(name):
        raise Refusal("nonfinite")
    def finite_float(text_value):
        number = float(text_value)
        if not math.isfinite(number):
            raise Refusal("nonfinite_value")
        return number
    try:
        value = json.loads(text, object_pairs_hook=no_dup,
                           parse_constant=no_const,
                           parse_float=finite_float)
    except Refusal:
        raise
    except Exception as error:
        raise Refusal(f"parse:{type(error).__name__}")
    if not isinstance(value, dict):
        raise Refusal("root_not_object")
    # decoded-string NFC (escaped sequences are checked after decoding)
    stack, nodes, depth_max = [value], 0, 0
    while stack:
        node = stack.pop()
        nodes += 1
        if nodes > 10000:
            raise Refusal("nodes")
        if isinstance(node, str) and unicodedata.normalize("NFC", node) != node:
            raise Refusal("non_nfc")
        if isinstance(node, dict):
            stack.extend(node.values())
        elif isinstance(node, list):
            stack.extend(node)
    def depth_of(node):
        if isinstance(node, dict):
            return 1 + max([depth_of(v) for v in node.values()] or [0])
        if isinstance(node, list):
            return 1 + max([depth_of(v) for v in node] or [0])
        return 0
    if depth_of(value) > 12:
        raise Refusal("depth")
    for key in value:
        if key not in LAUNCH_KEYS:
            raise Refusal(f"unknown_key:{key}")
    required = ("study", "human_protocol", "source_ledger", "diagram",
                "execution_authorised", "fixture_verification_authorised",
                "authorised_modes", "protocol_revision")
    for key in required:
        if key not in value:
            raise Refusal(f"missing_key:{key}")
    if value["study"] != "pf002-c3-completion-v1":
        raise Refusal("science_binding:study")
    if value["human_protocol"] != _PATH_PREFIX + "PF002_C3_COMPLETION_V1.md":
        raise Refusal("science_binding:human_protocol")
    if value["source_ledger"] != _PATH_PREFIX + \
            "PF002_C3_COMPLETION_V1_SOURCES.md":
        raise Refusal("science_binding:source_ledger")
    if value["diagram"] != _PATH_PREFIX + "pf002-c3-completion-v1.svg":
        raise Refusal("science_binding:diagram")
    if type(value["protocol_revision"]) is not int \
            or value["protocol_revision"] < 1:
        raise Refusal("science_binding:revision")
    # every float anywhere must be finite; every key must be NFC
    stack = [value]
    while stack:
        node = stack.pop()
        if isinstance(node, float) and not math.isfinite(node):
            raise Refusal("nonfinite_value")
        if isinstance(node, dict):
            for k, v in node.items():
                if not isinstance(k, str) or \
                        unicodedata.normalize("NFC", k) != k:
                    raise Refusal("non_nfc_key")
                stack.append(v)
        elif isinstance(node, list):
            stack.extend(node)
    if "action" in value:
        if not isinstance(value["action"], dict):
            raise Refusal("action_type")
        for sub in value["action"]:
            if sub not in ("L_B", "L_S", "L_chi", "L_mech", "L_opt", "bath", "covariance_note", "field_equation", "general_equations", "new_law_modification", "nulls", "units"):
                raise Refusal(f"action_key:{sub}")
            if not isinstance(value["action"][sub], (str, dict, list)):
                raise Refusal(f"action_value:{sub}")
    if "points" in value:
        pts = value["points"]
        if not isinstance(pts, dict):
            raise Refusal("points_type")
        for name in pts:
            if name not in ("n", "m", "r"):
                raise Refusal(f"point_key:{name}")
        for name in ("n", "m", "r"):
            if name in pts:
                v = pts[name]
                if isinstance(v, bool) or not isinstance(v, int) or v < 0:
                    raise Refusal(f"point_domain:{name}")
        if all(k in pts for k in ("n", "m", "r")):
            if pts["n"] < 1 or pts["r"] < 1 or pts["m"] > pts["n"] \
                    or pts["r"] ** 2 != pts["n"] ** 2 - pts["m"] ** 2:
                raise Refusal("point_off_chart")
    if "denominators" in value:
        validate_denominator(value["denominators"])
    return value


def validate_denominator(exponents):
    if not isinstance(exponents, dict):
        raise Refusal("denominator_type")
    caps = {"r": 3, "hbar": 2, "D": 2, "P": 2}
    for name, power in exponents.items():
        if name not in caps or isinstance(power, bool) \
                or not isinstance(power, int) or power < 0 \
                or power > caps[name]:
            raise Refusal(f"unsupported_denominator:{name}")
    return True


def parse_input(data, allowed_keys):
    """Strict bounded JSON input: size, NFC, duplicates, nonfinite, depth."""
    if len(data) > 131072:
        raise Refusal("input_bytes")
    text = data.decode("utf-8")
    if unicodedata.normalize("NFC", text) != text:
        raise Refusal("non_nfc")
    def no_dup(pairs):
        out = {}
        for k, v in pairs:
            if k in out:
                raise Refusal("duplicate_key")
            out[k] = v
        return out
    def no_const(name):
        raise Refusal("nonfinite")
    try:
        value = json.loads(text, object_pairs_hook=no_dup,
                           parse_constant=no_const)
    except Refusal:
        raise
    except Exception as error:
        raise Refusal(f"parse:{type(error).__name__}")
    def walk(node, depth):
        if depth > 12:
            raise Refusal("depth")
        count = 1
        if isinstance(node, dict):
            for k, v in node.items():
                if k not in allowed_keys:
                    raise Refusal(f"unknown_key:{k}")
                count += walk(v, depth + 1)
        elif isinstance(node, list):
            for v in node:
                count += walk(v, depth + 1)
        elif isinstance(node, float) and not math.isfinite(node):
            raise Refusal("nonfinite")
        if count > 10000:
            raise Refusal("nodes")
        return count
    walk(value, 0)
    return value





def eval_rat(rat, assignment):
    """Evaluate a Rat at exact rational values (Fraction assignment)."""
    total = Fraction(0)
    for mono, coeff in rat.num.items():
        term = coeff
        for name, power in zip(VARS, mono):
            if power:
                term *= assignment[name] ** power
        total += term
    return total / assignment["r"] ** rat.rpow


if __name__ == "__main__":
    result = evaluate_all()
    print(json.dumps(result, sort_keys=True))
    raise SystemExit(0 if all(result.values()) else 1)
