"""AP1-M1 moving UV-tail to resolved-mode handoff reference.

This isolated diagnostic path validates the representation change required at
the moving physical boundary q_cut = 0.6 Lambda.  It copies an adiabatic
order-0/2/4 canonical state into the already validated log-amplitude/Riccati
chart, evaluates the resolved source directly from that state, and compares it
with an independent order-0/2/4 source expansion.  All Pauli--Villars sums are
performed with signed Decimal arithmetic at two precisions.

The background prefixes are fixed-source, short, nonphysical diagnostics.
This module does not run a coupled AP1-M1 background, persist trajectory rows,
change the frozen equations or parameters, release a seed, start the physical
response kernel, or produce observables.
"""
from __future__ import annotations

import argparse
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from decimal import Decimal, localcontext
from hashlib import sha256
import json
import math
from pathlib import Path
from typing import Any

import numpy as np

from ap1_m1_log_amplitude_transport_reference import (
    load_inputs as load_transport_inputs,
    short_diagnostic_trajectory,
)
from chi_background_closure import (
    ChiParameters,
    ChiTrajectory,
    PV_C,
    PV_J,
    cosmic_derivative,
    portal_terms,
)


EXPECTED_AUTHORITIES = {
    "AP1/APEIRON_AP1_M1_LOG_AMPLITUDE_TRANSPORT_REFERENCE_CHECKPOINT_LATEST.json": (
        "87fa3dce63f7b1747cad591eb0e5a6a932cad38066ed8a2f137791d102b737e6"
    ),
    "AP1/APEIRON_AP1_M1_LOG_AMPLITUDE_TRANSPORT_HELDOUT_LATEST.json": (
        "4ba0e1a590fe0a607893ca8cce64c72f756fe963776b0cafbc171d6deaf24281"
    ),
    "AP1/CODE/ap1_m1_log_amplitude_transport_reference.py": (
        "129cf197f08a178eab43c52a2fd9946d161945d16e19ff7f49cdf1d1b12ea523"
    ),
    "AP1/CODE/chi_background_closure.py": (
        "1097888c72fbe9152e1905a2a3ab37c15df9ca681639571b87d76de6ddf072a7"
    ),
    "AP1/APEIRON_AP1_R2B_CHI_BACKGROUND_SPEC_LATEST.md": (
        "95195f416b24ed5c29e2a60da5257183aa8c2345168de4530327aea9ac63fa81"
    ),
    "AP1/APEIRON_AP1_M1_JUNCTION_128_SEED_CHECKPOINT_LATEST.json": (
        "cf946bfcde4c10a36d5eee99a18fe1a8745483e111304d52f4cc17b3fdf103b4"
    ),
    "AP1/APEIRON_AP1_M1_JUNCTION_128_SEED_LATEST.npz": (
        "644126925fcff32df6f881ee604787751dbe48829072671bf541552bd65dc729"
    ),
}


# These are numerical-reference policies, not changes to a physical gate.
# New convergence thresholds are derived only from the non-held-out pilot and
# must remain below the ceilings declared here before any held-out evaluation.
FREEZE_POLICY = {
    "time_grid_multiplier": 128.0,
    "time_grid_floor": 1.0e-10,
    "time_grid_ceiling": 5.0e-4,
    "momentum_stencil_multiplier": 128.0,
    "momentum_stencil_floor": 1.0e-10,
    "momentum_stencil_ceiling": 5.0e-4,
    "adiabatic_remainder_multiplier": 128.0,
    "adiabatic_remainder_floor": 1.0e-10,
    "adiabatic_remainder_ceiling": 5.0e-4,
    "decimal_60_to_80_gross_relative_cap": 1.0e-30,
    "float64_to_decimal80_gross_relative_cap": 1.0e-12,
    "moving_cutoff_map_cap": 1.0e-12,
    "state_transfer_relative_cap": 1.0e-12,
    "wronskian_relative_cap": 1.0e-11,
}

PI_DECIMAL = Decimal(
    "3.141592653589793238462643383279502884197169399375105820974944592307816406286"
)
SOURCE_KEYS = ("rho", "pressure", "chi2")


class UVHandoffError(RuntimeError):
    """A chronology, authority, or fail-closed boundary condition failed."""


@dataclass(frozen=True)
class HandoffConfig:
    qcut_over_Lambda: float = 0.6
    pilot_sample_relative_N: tuple[float, ...] = (0.0125, 0.0275, 0.0425)
    heldout_sample_relative_N: tuple[float, ...] = (0.0625, 0.0825, 0.1025)
    pilot_envelope_endpoint_relative_N: float = 0.05
    heldout_envelope_endpoint_relative_N: float = 0.115
    coarse_step_N: float = 2.5e-5
    fine_step_N: float = 1.25e-5
    diagnostic_rtol: float = 2.0e-11
    momentum_band_halfwidth_over_Lambda: float = 0.01
    coarse_momentum_nodes: int = 8
    fine_momentum_nodes: int = 16
    decimal_low_digits: int = 60
    decimal_high_digits: int = 80

    def validate(self) -> None:
        if self.qcut_over_Lambda != 0.6:
            raise ValueError("the frozen physical split is q_cut/Lambda = 0.6")
        pilot = self.pilot_sample_relative_N
        heldout = self.heldout_sample_relative_N
        for samples, endpoint in (
            (pilot, self.pilot_envelope_endpoint_relative_N),
            (heldout, self.heldout_envelope_endpoint_relative_N),
        ):
            if not samples or tuple(sorted(set(samples))) != samples:
                raise ValueError("sample times must be unique and increasing")
            if samples[0] <= 0.0 or samples[-1] >= endpoint:
                raise ValueError("samples must be interior to their diagnostic envelope")
            for value in (*samples, endpoint):
                fine_intervals = value / self.fine_step_N
                coarse_intervals = value / self.coarse_step_N
                if abs(fine_intervals - round(fine_intervals)) > 1.0e-10:
                    raise ValueError("fine grid must contain every registered time")
                if abs(coarse_intervals - round(coarse_intervals)) > 1.0e-10:
                    raise ValueError("coarse grid must contain every registered time")
        if set(pilot) & set(heldout):
            raise ValueError("pilot and held-out sample times must be disjoint")
        if not self.pilot_envelope_endpoint_relative_N < heldout[0]:
            raise ValueError("held-out samples must lie beyond the pilot envelope")
        if not 0.0 < self.fine_step_N < self.coarse_step_N <= 5.0e-5:
            raise ValueError("bounded nested time steps required")
        ratio = self.coarse_step_N / self.fine_step_N
        if abs(ratio - round(ratio)) > 1.0e-12:
            raise ValueError("time grids must be nested")
        if not 0.0 < self.momentum_band_halfwidth_over_Lambda < self.qcut_over_Lambda:
            raise ValueError("momentum band must remain at positive q")
        if not 4 <= self.coarse_momentum_nodes < self.fine_momentum_nodes:
            raise ValueError("ordered momentum quadrature resolutions required")
        if not 32 <= self.decimal_low_digits < self.decimal_high_digits:
            raise ValueError("ordered Decimal precisions required")


def file_sha256(path: Path) -> str:
    digest = sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def _utc_now() -> str:
    return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")


def _write_json(report: dict[str, Any], output: Path) -> None:
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(
        json.dumps(report, indent=2, sort_keys=False) + "\n", encoding="utf-8"
    )


def load_inputs(
    apeiron_root: Path,
) -> tuple[dict, dict[str, np.ndarray], dict[str, str]]:
    observed = {
        name: file_sha256(apeiron_root / name) for name in EXPECTED_AUTHORITIES
    }
    if observed != EXPECTED_AUTHORITIES:
        changed = [
            name
            for name, expected in EXPECTED_AUTHORITIES.items()
            if observed.get(name) != expected
        ]
        raise UVHandoffError(f"authority drift: {changed}")
    checkpoint = json.loads(
        (
            apeiron_root
            / "AP1/APEIRON_AP1_M1_LOG_AMPLITUDE_TRANSPORT_REFERENCE_CHECKPOINT_LATEST.json"
        ).read_text(encoding="utf-8")
    )
    heldout = json.loads(
        (
            apeiron_root
            / "AP1/APEIRON_AP1_M1_LOG_AMPLITUDE_TRANSPORT_HELDOUT_LATEST.json"
        ).read_text(encoding="utf-8")
    )
    if not checkpoint.get("all_checkpoint_gates_pass"):
        raise UVHandoffError("G27 transport checkpoint is not PASS")
    if not heldout.get("all_heldout_gates_pass"):
        raise UVHandoffError("G27 held-out transport reference is not PASS")
    if checkpoint.get("new_AP1_M1_background_runs") != 0:
        raise UVHandoffError("G27 authority already claims a background run")
    seed_report, arrays, _ = load_transport_inputs(apeiron_root)
    return seed_report, arrays, observed


def _sample_index(trajectory: ChiTrajectory, relative_N: float) -> int:
    target = float(trajectory.N[0] + relative_N)
    index = int(np.argmin(np.abs(trajectory.N - target)))
    if abs(float(trajectory.N[index] - target)) > 2.0e-13:
        raise UVHandoffError("registered handoff time is not on the trajectory grid")
    if index < 5 or index > len(trajectory.N) - 6:
        raise UVHandoffError("handoff time lacks a derivative safety margin")
    return index


def adiabatic_boundary_primitives(
    trajectory: ChiTrajectory,
    sample_relative_N: float,
    q_now: np.ndarray,
    p: ChiParameters | None = None,
) -> dict[str, np.ndarray | float]:
    """Evaluate the frozen order-0/2/4 hierarchy for fixed-k crossing modes."""

    p = ChiParameters() if p is None else p
    tr = trajectory.validated()
    q_now = np.asarray(q_now, dtype=float)
    if q_now.ndim != 1 or not np.all(np.isfinite(q_now)) or np.any(q_now <= 0.0):
        raise ValueError("positive finite one-dimensional q stencil required")
    index = _sample_index(tr, sample_relative_N)
    crossing_N = float(tr.N[index])
    physical_q = q_now[None, :] * np.exp(crossing_N - tr.N[:, None])
    mass2 = np.asarray(portal_terms(tr.sigma, tr.theta, p)[0], dtype=float)
    muR2 = (p.muR_over_Lambda * p.Lambda) ** 2
    masses2 = np.broadcast_to(
        mass2[:, None, None] + PV_J[None, :, None] * muR2,
        (len(tr.N), 4, len(q_now)),
    ).copy()
    omega2 = physical_q[:, None, :] ** 2 + masses2
    if np.min(omega2) <= 0.0:
        raise UVHandoffError("moving boundary entered omega^2 <= 0")
    omega = np.sqrt(omega2)
    omega_dot = cosmic_derivative(omega, tr)
    omega_ddot = cosmic_derivative(omega_dot, tr)
    logarithmic0 = omega_dot / omega
    s2 = -2.25 * tr.H[:, None, None] ** 2 - 1.5 * tr.Hdot[:, None, None]
    q2 = 0.75 * logarithmic0**2 - 0.5 * omega_ddot / omega
    W2 = (s2 + q2) / (2.0 * omega)
    W2_dot = cosmic_derivative(W2, tr)
    W2_ddot = cosmic_derivative(W2_dot, tr)
    logarithmic2 = W2_dot / omega - logarithmic0 * W2 / omega
    q4 = (
        1.5 * logarithmic0 * logarithmic2
        - 0.5 * (W2_ddot / omega - omega_ddot * W2 / omega**2)
    )
    W4 = (q4 - W2**2) / (2.0 * omega)
    W = omega + W2 + W4
    W_dot = cosmic_derivative(W, tr)
    if np.min(W) <= 0.0 or not all(
        np.all(np.isfinite(value))
        for value in (omega, omega_dot, W2, W2_dot, W4, W, W_dot)
    ):
        raise UVHandoffError("nonpositive or nonfinite adiabatic frequency")
    return {
        "q": q_now.copy(),
        "crossing_N": crossing_N,
        "H": float(tr.H[index]),
        "mass2": masses2[index, :, :].copy(),
        "omega": omega[index, :, :].copy(),
        "omega_dot": omega_dot[index, :, :].copy(),
        "W2": W2[index, :, :].copy(),
        "W2_dot": W2_dot[index, :, :].copy(),
        "W4": W4[index, :, :].copy(),
        "W": W[index, :, :].copy(),
        "W_dot": W_dot[index, :, :].copy(),
    }


def direct_resolved_flux(primitives: dict[str, Any]) -> dict[str, np.ndarray]:
    """Direct boundary flux from the handed-off canonical mode state."""

    q = np.asarray(primitives["q"], dtype=float)[None, :]
    mass2 = np.asarray(primitives["mass2"], dtype=float)
    W = np.asarray(primitives["W"], dtype=float)
    W_dot = np.asarray(primitives["W_dot"], dtype=float)
    H = float(primitives["H"])
    amplitude2 = 1.0 / (2.0 * W)
    B = W_dot / (2.0 * W) + 1.5 * H
    kinetic = (W**2 + B**2) * amplitude2
    measure = q**3 / (2.0 * np.pi**2)
    return {
        "rho": measure * 0.5 * (kinetic + (q**2 + mass2) * amplitude2),
        "pressure": measure
        * (0.5 * kinetic - (q**2 / 6.0 + 0.5 * mass2) * amplitude2),
        "chi2": measure * amplitude2,
    }


def expanded_tail_flux(primitives: dict[str, Any]) -> dict[str, np.ndarray]:
    """Independent order-0/2/4 source expansion at the moving boundary."""

    q = np.asarray(primitives["q"], dtype=float)[None, :]
    mass2 = np.asarray(primitives["mass2"], dtype=float)
    omega = np.asarray(primitives["omega"], dtype=float)
    omega_dot = np.asarray(primitives["omega_dot"], dtype=float)
    W2 = np.asarray(primitives["W2"], dtype=float)
    W2_dot = np.asarray(primitives["W2_dot"], dtype=float)
    W4 = np.asarray(primitives["W4"], dtype=float)
    H = float(primitives["H"])
    A0 = 1.0 / (2.0 * omega)
    A2 = -W2 / (2.0 * omega**2)
    A4 = 0.5 * (W2**2 / omega**3 - W4 / omega**2)
    logarithmic0 = omega_dot / omega
    logarithmic2 = W2_dot / omega - logarithmic0 * W2 / omega
    B1 = 1.5 * H + 0.5 * logarithmic0
    B3 = 0.5 * logarithmic2
    C0 = omega**2
    C2 = 2.0 * omega * W2 + B1**2
    C4 = W2**2 + 2.0 * omega * W4 + 2.0 * B1 * B3
    D0 = A0 * C0
    D2 = A0 * C2 + A2 * C0
    D4 = A0 * C4 + A2 * C2 + A4 * C0
    amplitude024 = A0 + A2 + A4
    kinetic024 = D0 + D2 + D4
    measure = q**3 / (2.0 * np.pi**2)
    return {
        "rho": measure
        * 0.5 * (kinetic024 + (q**2 + mass2) * amplitude024),
        "pressure": measure
        * (0.5 * kinetic024 - (q**2 / 6.0 + 0.5 * mass2) * amplitude024),
        "chi2": measure * amplitude024,
    }


def _decimal(value: float) -> Decimal:
    return Decimal(repr(float(value)))


def decimal_direct_flux(
    primitives: dict[str, Any], q_index: int, digits: int
) -> dict[str, Any]:
    """Re-evaluate and sign-sum direct sector fluxes using Decimal arithmetic."""

    coefficients = tuple(Decimal(int(value)) for value in (1, -3, 3, -1))
    with localcontext() as context:
        context.prec = int(digits)
        q = _decimal(np.asarray(primitives["q"])[q_index])
        H = _decimal(primitives["H"])
        measure = q**3 / (Decimal(2) * PI_DECIMAL**2)
        output: dict[str, Any] = {}
        each = {key: [] for key in SOURCE_KEYS}
        for sector in range(4):
            mass2 = _decimal(np.asarray(primitives["mass2"])[sector, q_index])
            W = _decimal(np.asarray(primitives["W"])[sector, q_index])
            W_dot = _decimal(np.asarray(primitives["W_dot"])[sector, q_index])
            amplitude2 = Decimal(1) / (Decimal(2) * W)
            B = W_dot / (Decimal(2) * W) + Decimal("1.5") * H
            kinetic = (W**2 + B**2) * amplitude2
            each["rho"].append(
                measure
                * (kinetic + (q**2 + mass2) * amplitude2)
                / Decimal(2)
            )
            each["pressure"].append(
                measure
                * (
                    kinetic / Decimal(2)
                    - (q**2 / Decimal(6) + mass2 / Decimal(2)) * amplitude2
                )
            )
            each["chi2"].append(measure * amplitude2)
        for key in SOURCE_KEYS:
            signed = sum(
                (coefficient * value for coefficient, value in zip(coefficients, each[key])),
                Decimal(0),
            )
            gross = sum(
                (abs(coefficient * value) for coefficient, value in zip(coefficients, each[key])),
                Decimal(0),
            )
            output[key] = {
                "sector_flux": [str(+value) for value in each[key]],
                "signed_PV_flux": str(+signed),
                "gross_abs_PV_flux": str(+gross),
                "cancellation_ratio": str(+(abs(signed) / gross)),
            }
        return output


def decimal_expanded_tail_flux(
    primitives: dict[str, Any], q_index: int, digits: int
) -> dict[str, Any]:
    """Re-evaluate and sign-sum the independent order-0/2/4 tail in Decimal."""

    coefficients = tuple(Decimal(int(value)) for value in (1, -3, 3, -1))
    with localcontext() as context:
        context.prec = int(digits)
        q = _decimal(np.asarray(primitives["q"])[q_index])
        H = _decimal(primitives["H"])
        measure = q**3 / (Decimal(2) * PI_DECIMAL**2)
        each = {key: [] for key in SOURCE_KEYS}
        for sector in range(4):
            mass2 = _decimal(np.asarray(primitives["mass2"])[sector, q_index])
            omega = _decimal(np.asarray(primitives["omega"])[sector, q_index])
            omega_dot = _decimal(
                np.asarray(primitives["omega_dot"])[sector, q_index]
            )
            W2 = _decimal(np.asarray(primitives["W2"])[sector, q_index])
            W2_dot = _decimal(
                np.asarray(primitives["W2_dot"])[sector, q_index]
            )
            W4 = _decimal(np.asarray(primitives["W4"])[sector, q_index])
            A0 = Decimal(1) / (Decimal(2) * omega)
            A2 = -W2 / (Decimal(2) * omega**2)
            A4 = (W2**2 / omega**3 - W4 / omega**2) / Decimal(2)
            logarithmic0 = omega_dot / omega
            logarithmic2 = W2_dot / omega - logarithmic0 * W2 / omega
            B1 = Decimal("1.5") * H + logarithmic0 / Decimal(2)
            B3 = logarithmic2 / Decimal(2)
            C0 = omega**2
            C2 = Decimal(2) * omega * W2 + B1**2
            C4 = W2**2 + Decimal(2) * omega * W4 + Decimal(2) * B1 * B3
            D0 = A0 * C0
            D2 = A0 * C2 + A2 * C0
            D4 = A0 * C4 + A2 * C2 + A4 * C0
            amplitude024 = A0 + A2 + A4
            kinetic024 = D0 + D2 + D4
            each["rho"].append(
                measure
                * (kinetic024 + (q**2 + mass2) * amplitude024)
                / Decimal(2)
            )
            each["pressure"].append(
                measure
                * (
                    kinetic024 / Decimal(2)
                    - (q**2 / Decimal(6) + mass2 / Decimal(2)) * amplitude024
                )
            )
            each["chi2"].append(measure * amplitude024)
        output: dict[str, Any] = {}
        for key in SOURCE_KEYS:
            signed = sum(
                (coefficient * value for coefficient, value in zip(coefficients, each[key])),
                Decimal(0),
            )
            gross = sum(
                (abs(coefficient * value) for coefficient, value in zip(coefficients, each[key])),
                Decimal(0),
            )
            output[key] = {
                "sector_flux": [str(+value) for value in each[key]],
                "signed_PV_flux": str(+signed),
                "gross_abs_PV_flux": str(+gross),
                "cancellation_ratio": str(+(abs(signed) / gross)),
            }
        return output


def _pv_float_summary(source: dict[str, np.ndarray], index: int) -> dict[str, dict]:
    output = {}
    for key in SOURCE_KEYS:
        each = np.asarray(source[key], dtype=float)[:, index]
        weighted = PV_C * each
        gross = float(np.sum(np.abs(weighted), dtype=np.longdouble))
        output[key] = {
            "each": each,
            "signed": float(np.sum(weighted, dtype=np.longdouble)),
            "gross": gross,
        }
    return output


def _relative_to_gross(delta: float, *gross_values: float) -> float:
    return float(abs(delta) / max(*(abs(value) for value in gross_values), 1.0e-300))


def _max_source_metric(values: dict[str, float]) -> float:
    return max(float(values[key]) for key in SOURCE_KEYS)


def handoff_state_metrics(primitives: dict[str, Any], q_index: int) -> dict[str, Any]:
    W = np.asarray(primitives["W"], dtype=float)[:, q_index]
    W_dot = np.asarray(primitives["W_dot"], dtype=float)[:, q_index]
    tail_u = 1.0 / np.sqrt(2.0 * W)
    tail_v = (-W_dot / (2.0 * W) - 1j * W) * tail_u
    log_amplitude = -0.5 * np.log(2.0 * W)
    riccati_real = -W_dot / (2.0 * W)
    log_abs_riccati_imag = np.log(W)
    phase = np.zeros_like(W)
    resolved_u = np.exp(log_amplitude) * np.exp(1j * phase)
    resolved_v = (
        riccati_real - 1j * np.exp(log_abs_riccati_imag)
    ) * resolved_u
    observed = -2.0 * np.imag(np.conj(resolved_u) * resolved_v)
    state_relative = max(
        float(np.max(np.abs(resolved_u - tail_u) / np.maximum(np.abs(tail_u), 1e-300))),
        float(np.max(np.abs(resolved_v - tail_v) / np.maximum(np.abs(tail_v), 1e-300))),
    )
    return {
        "origin": "same_order_0_2_4_tail_state_at_first_resolved_point",
        "phase_convention": "zero_global_phase_at_boundary",
        "state_reinitialized_to_instantaneous_order0_vacuum": False,
        "max_tail_to_log_chart_state_relative_error": state_relative,
        "max_wronskian_relative_error": float(np.max(np.abs(observed - 1.0))),
        "log_wronskian_identity_error": float(
            np.max(np.abs(math.log(2.0) + 2.0 * log_amplitude + log_abs_riccati_imag))
        ),
    }


def point_metrics(
    fine: ChiTrajectory,
    coarse: ChiTrajectory,
    sample_relative_N: float,
    config: HandoffConfig,
) -> dict[str, Any]:
    p = ChiParameters()
    qcut = config.qcut_over_Lambda * p.Lambda
    coarse_x, coarse_weights = np.polynomial.legendre.leggauss(
        config.coarse_momentum_nodes
    )
    fine_x, fine_weights = np.polynomial.legendre.leggauss(
        config.fine_momentum_nodes
    )
    halfwidth = config.momentum_band_halfwidth_over_Lambda * p.Lambda
    coarse_q = qcut + halfwidth * coarse_x
    fine_q = qcut + halfwidth * fine_x
    q_stencil = np.concatenate(([qcut], coarse_q, fine_q))
    center = 0
    coarse_slice = slice(1, 1 + config.coarse_momentum_nodes)
    fine_slice = slice(1 + config.coarse_momentum_nodes, len(q_stencil))
    fine_primitives = adiabatic_boundary_primitives(
        fine, sample_relative_N, q_stencil, p
    )
    coarse_primitives = adiabatic_boundary_primitives(
        coarse, sample_relative_N, q_stencil, p
    )
    direct = direct_resolved_flux(fine_primitives)
    expanded = expanded_tail_flux(fine_primitives)
    coarse_direct = direct_resolved_flux(coarse_primitives)
    direct_summary = _pv_float_summary(direct, center)
    expanded_summary = _pv_float_summary(expanded, center)
    coarse_summary = _pv_float_summary(coarse_direct, center)
    decimal_low = decimal_direct_flux(
        fine_primitives, center, config.decimal_low_digits
    )
    decimal_high = decimal_direct_flux(
        fine_primitives, center, config.decimal_high_digits
    )
    tail_decimal_low = decimal_expanded_tail_flux(
        fine_primitives, center, config.decimal_low_digits
    )
    tail_decimal_high = decimal_expanded_tail_flux(
        fine_primitives, center, config.decimal_high_digits
    )

    time_grid = {}
    momentum_stencil = {}
    boundary_closure = {}
    decimal_delta = {}
    float_decimal_delta = {}
    cancellation_ratio = {}
    signed_fluxes = {}
    for key in SOURCE_KEYS:
        fine_signed = direct_summary[key]["signed"]
        coarse_signed = coarse_summary[key]["signed"]
        time_grid[key] = _relative_to_gross(
            fine_signed - coarse_signed,
            direct_summary[key]["gross"],
            coarse_summary[key]["gross"],
        )
        signed_by_q = np.asarray(direct[key], dtype=float).T @ PV_C
        gross_center = direct_summary[key]["gross"]
        # Both rules integrate the same fixed symmetric momentum band.  The
        # factor 1/2 converts the Gauss integral on [-1,1] to a band average,
        # retaining the units of the boundary flux.
        coarse_centered = 0.5 * float(
            np.dot(coarse_weights, signed_by_q[coarse_slice])
        )
        fine_centered = 0.5 * float(
            np.dot(fine_weights, signed_by_q[fine_slice])
        )
        momentum_stencil[key] = _relative_to_gross(
            fine_centered - coarse_centered, gross_center
        )
        low_signed = Decimal(decimal_low[key]["signed_PV_flux"])
        high_signed = Decimal(decimal_high[key]["signed_PV_flux"])
        high_gross = Decimal(decimal_high[key]["gross_abs_PV_flux"])
        tail_low_signed = Decimal(tail_decimal_low[key]["signed_PV_flux"])
        tail_high_signed = Decimal(tail_decimal_high[key]["signed_PV_flux"])
        tail_high_gross = Decimal(
            tail_decimal_high[key]["gross_abs_PV_flux"]
        )
        decimal_delta[key] = max(
            float(abs(low_signed - high_signed) / high_gross),
            float(abs(tail_low_signed - tail_high_signed) / tail_high_gross),
        )
        float_decimal_delta[key] = max(
            _relative_to_gross(
                fine_signed - float(high_signed), float(high_gross)
            ),
            _relative_to_gross(
                expanded_summary[key]["signed"] - float(tail_high_signed),
                float(tail_high_gross),
            ),
        )
        boundary_closure[key] = float(
            abs(high_signed - tail_high_signed) / max(high_gross, tail_high_gross)
        )
        cancellation_ratio[key] = float(
            Decimal(decimal_high[key]["cancellation_ratio"])
        )
        signed_fluxes[key] = {
            "resolved_gain_decimal80": decimal_high[key]["signed_PV_flux"],
            "tail_loss_order024_decimal80": str(-tail_high_signed),
            "net_split_residual_decimal80": str(high_signed - tail_high_signed),
        }

    W0 = np.asarray(fine_primitives["omega"], dtype=float)
    W2 = np.asarray(fine_primitives["W2"], dtype=float)
    W4 = np.asarray(fine_primitives["W4"], dtype=float)
    W = np.asarray(fine_primitives["W"], dtype=float)
    crossing_N = float(fine_primitives["crossing_N"])
    k_comoving = qcut * math.exp(crossing_N)
    recovered_q = k_comoving * math.exp(-crossing_N)
    hierarchy_W2 = float(np.max(np.abs(W2 / W0)))
    hierarchy_W4 = float(np.max(np.abs(W4 / W0)))
    return {
        "sample_relative_N": float(sample_relative_N),
        "sample_physical_N": crossing_N,
        "qcut_Mpl": qcut,
        "qcut_over_Lambda": config.qcut_over_Lambda,
        "moving_cutoff_map_relative_error": abs(recovered_q / qcut - 1.0),
        "min_boundary_omega2_Mpl2": float(np.min(W0**2)),
        "min_boundary_W_Mpl": float(np.min(W)),
        "max_abs_W2_over_W0": hierarchy_W2,
        "max_abs_W4_over_W0": hierarchy_W4,
        "adiabatic_hierarchy_ordered": bool(hierarchy_W4 < hierarchy_W2 < 1.0),
        "handoff_state": handoff_state_metrics(fine_primitives, center),
        "signed_decimal80_direct_flux": decimal_high,
        "signed_decimal80_order024_tail_flux": tail_decimal_high,
        "max_decimal_60_to_80_gross_relative_delta": _max_source_metric(
            decimal_delta
        ),
        "max_float64_to_decimal80_gross_relative_delta": _max_source_metric(
            float_decimal_delta
        ),
        "decimal_60_to_80_gross_relative_delta_by_source": decimal_delta,
        "float64_to_decimal80_gross_relative_delta_by_source": float_decimal_delta,
        "PV_cancellation_ratio_by_source": cancellation_ratio,
        "time_grid_gross_relative_delta_by_source": time_grid,
        "max_time_grid_gross_relative_delta": _max_source_metric(time_grid),
        "momentum_stencil_gross_relative_delta_by_source": momentum_stencil,
        "max_momentum_stencil_gross_relative_delta": _max_source_metric(
            momentum_stencil
        ),
        "tail_to_resolved_gross_relative_residual_by_source": boundary_closure,
        "max_tail_to_resolved_gross_relative_residual": _max_source_metric(
            boundary_closure
        ),
        "signed_boundary_flux_convention": signed_fluxes,
        "all_values_finite": bool(
            all(
                math.isfinite(float(value))
                for mapping in (
                    time_grid,
                    momentum_stencil,
                    boundary_closure,
                    decimal_delta,
                    float_decimal_delta,
                    cancellation_ratio,
                )
                for value in mapping.values()
            )
        ),
    }


def aggregate_metrics(points: list[dict[str, Any]]) -> dict[str, Any]:
    return {
        "points": len(points),
        "min_boundary_omega2_Mpl2": min(
            point["min_boundary_omega2_Mpl2"] for point in points
        ),
        "min_boundary_W_Mpl": min(point["min_boundary_W_Mpl"] for point in points),
        "max_abs_W2_over_W0": max(point["max_abs_W2_over_W0"] for point in points),
        "max_abs_W4_over_W0": max(point["max_abs_W4_over_W0"] for point in points),
        "max_moving_cutoff_map_relative_error": max(
            point["moving_cutoff_map_relative_error"] for point in points
        ),
        "max_state_transfer_relative_error": max(
            point["handoff_state"]["max_tail_to_log_chart_state_relative_error"]
            for point in points
        ),
        "max_wronskian_relative_error": max(
            point["handoff_state"]["max_wronskian_relative_error"] for point in points
        ),
        "max_time_grid_gross_relative_delta": max(
            point["max_time_grid_gross_relative_delta"] for point in points
        ),
        "max_momentum_stencil_gross_relative_delta": max(
            point["max_momentum_stencil_gross_relative_delta"] for point in points
        ),
        "max_tail_to_resolved_gross_relative_residual": max(
            point["max_tail_to_resolved_gross_relative_residual"] for point in points
        ),
        "max_decimal_60_to_80_gross_relative_delta": max(
            point["max_decimal_60_to_80_gross_relative_delta"] for point in points
        ),
        "max_float64_to_decimal80_gross_relative_delta": max(
            point["max_float64_to_decimal80_gross_relative_delta"] for point in points
        ),
        "max_PV_cancellation_ratio": max(
            max(point["PV_cancellation_ratio_by_source"].values()) for point in points
        ),
        "min_PV_cancellation_ratio": min(
            min(point["PV_cancellation_ratio_by_source"].values()) for point in points
        ),
        "all_adiabatic_hierarchies_ordered": all(
            point["adiabatic_hierarchy_ordered"] for point in points
        ),
        "all_values_finite": all(point["all_values_finite"] for point in points),
        "any_state_reinitialized": any(
            point["handoff_state"][
                "state_reinitialized_to_instantaneous_order0_vacuum"
            ]
            for point in points
        ),
    }


def evaluate_samples(
    arrays: dict[str, np.ndarray],
    samples: tuple[float, ...],
    envelope_endpoint: float,
    config: HandoffConfig,
) -> tuple[list[dict[str, Any]], dict[str, Any]]:
    fine = short_diagnostic_trajectory(
        arrays, envelope_endpoint, config.fine_step_N, config.diagnostic_rtol
    )
    coarse = short_diagnostic_trajectory(
        arrays, envelope_endpoint, config.coarse_step_N, config.diagnostic_rtol
    )
    points = [point_metrics(fine, coarse, sample, config) for sample in samples]
    return points, aggregate_metrics(points)


def _pv_moments_exact() -> dict[str, str]:
    coefficients = (Decimal(1), Decimal(-3), Decimal(3), Decimal(-1))
    indices = (Decimal(0), Decimal(1), Decimal(2), Decimal(3))
    return {
        str(order): str(
            sum(
                (
                    coefficient * (Decimal(1) if order == 0 else index**order)
                    for coefficient, index in zip(coefficients, indices)
                ),
                Decimal(0),
            )
        )
        for order in range(3)
    }


def build_pilot(
    apeiron_root: Path,
    code_path: Path,
    config: HandoffConfig | None = None,
) -> dict[str, Any]:
    config = HandoffConfig() if config is None else config
    config.validate()
    seed_report, arrays, authorities = load_inputs(apeiron_root)
    points, aggregate = evaluate_samples(
        arrays,
        config.pilot_sample_relative_N,
        config.pilot_envelope_endpoint_relative_N,
        config,
    )
    pv_moments = _pv_moments_exact()
    gates = {
        "G27_checkpoint_hash_bound_and_PASS": True,
        "pilot_and_heldout_times_disjoint": not bool(
            set(config.pilot_sample_relative_N) & set(config.heldout_sample_relative_N)
        ),
        "heldout_times_beyond_pilot_envelope": (
            config.pilot_envelope_endpoint_relative_N
            < min(config.heldout_sample_relative_N)
        ),
        "frozen_qcut_and_PV_basis_unchanged": (
            config.qcut_over_Lambda == 0.6
            and np.array_equal(PV_C, np.array([1.0, -3.0, 3.0, -1.0]))
            and np.array_equal(PV_J, np.array([0.0, 1.0, 2.0, 3.0]))
        ),
        "PV_moments_0_1_2_cancel_exactly": all(
            value == "0" for value in pv_moments.values()
        ),
        "boundary_frequencies_positive": (
            aggregate["min_boundary_omega2_Mpl2"] > 0.0
            and aggregate["min_boundary_W_Mpl"] > 0.0
        ),
        "adiabatic_hierarchy_ordered": aggregate[
            "all_adiabatic_hierarchies_ordered"
        ],
        "moving_cutoff_map_below_predeclared_cap": (
            aggregate["max_moving_cutoff_map_relative_error"]
            <= FREEZE_POLICY["moving_cutoff_map_cap"]
        ),
        "tail_state_copied_to_log_chart_below_predeclared_cap": (
            aggregate["max_state_transfer_relative_error"]
            <= FREEZE_POLICY["state_transfer_relative_cap"]
        ),
        "wronskian_below_existing_cap": (
            aggregate["max_wronskian_relative_error"]
            <= FREEZE_POLICY["wronskian_relative_cap"]
        ),
        "signed_PV_decimal_precision_below_predeclared_cap": (
            aggregate["max_decimal_60_to_80_gross_relative_delta"]
            <= FREEZE_POLICY["decimal_60_to_80_gross_relative_cap"]
        ),
        "float64_decimal80_agreement_below_predeclared_cap": (
            aggregate["max_float64_to_decimal80_gross_relative_delta"]
            <= FREEZE_POLICY["float64_to_decimal80_gross_relative_cap"]
        ),
        "all_pilot_values_finite": aggregate["all_values_finite"],
        "no_vacuum_reset": not aggregate["any_state_reinitialized"],
        "no_background_candidate_seed_or_kernel": True,
    }
    complete = bool(all(gates.values()))
    return {
        "schema": "apeiron-ap1-m1-uv-tail-handoff-pilot-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "UV_TAIL_HANDOFF_PILOT_COMPLETE_TOLERANCE_FREEZE_OPEN"
            if complete
            else "UV_TAIL_HANDOFF_PILOT_INCOMPLETE"
        ),
        "authority_sha256": {
            **authorities,
            "AP1/CODE/ap1_m1_uv_tail_handoff_reference.py": file_sha256(code_path),
        },
        "seed_classification": seed_report["classification"],
        "config": asdict(config),
        "predeclared_freeze_policy": FREEZE_POLICY,
        "PV_moment_residuals_decimal_exact": pv_moments,
        "boundary_flux_definition": (
            "moving k_cut=a*q_cut gives dk_cut/dN=k_cut and physical boundary "
            "measure q_cut^3/(2*pi^2) per e-fold"
        ),
        "pilot_points": points,
        "pilot_aggregate": aggregate,
        "gates": gates,
        "all_pilot_gates_pass": complete,
        "checkpoint_eligible": False,
        "heldout_evaluated": False,
        "new_AP1_M1_background_runs": 0,
        "diagnostic_envelope_integrations": 2,
        "trajectory_rows_persisted": 0,
        "background_candidate_assessed": False,
        "background_tolerances_frozen": False,
        "physical_response_kernel_started": False,
        "seed_released": False,
        "claim_boundary": (
            "non-held-out local moving-boundary reference pilot on a short "
            "fixed-source diagnostic envelope; no physical background, source "
            "history, kernel, observable, curve, fit or significance"
        ),
        "next_required": (
            "freeze pilot-derived time-grid, momentum-stencil and adiabatic-"
            "remainder tolerances before evaluating the registered disjoint "
            "held-out boundary times"
        ),
    }


def _derived_threshold(
    observed: float, multiplier_key: str, floor_key: str
) -> float:
    return max(
        float(FREEZE_POLICY[floor_key]),
        float(FREEZE_POLICY[multiplier_key]) * float(observed),
    )


def build_freeze(pilot_path: Path, code_path: Path) -> dict[str, Any]:
    pilot = json.loads(pilot_path.read_text(encoding="utf-8"))
    if not pilot.get("all_pilot_gates_pass") or pilot.get("heldout_evaluated"):
        raise UVHandoffError("complete pre-held-out pilot required")
    code_hash = file_sha256(code_path)
    if pilot["authority_sha256"].get(
        "AP1/CODE/ap1_m1_uv_tail_handoff_reference.py"
    ) != code_hash:
        raise UVHandoffError("handoff code changed after pilot")
    aggregate = pilot["pilot_aggregate"]
    thresholds = {
        "max_time_grid_gross_relative_delta": _derived_threshold(
            aggregate["max_time_grid_gross_relative_delta"],
            "time_grid_multiplier",
            "time_grid_floor",
        ),
        "max_momentum_stencil_gross_relative_delta": _derived_threshold(
            aggregate["max_momentum_stencil_gross_relative_delta"],
            "momentum_stencil_multiplier",
            "momentum_stencil_floor",
        ),
        "max_tail_to_resolved_gross_relative_residual": _derived_threshold(
            aggregate["max_tail_to_resolved_gross_relative_residual"],
            "adiabatic_remainder_multiplier",
            "adiabatic_remainder_floor",
        ),
        "max_decimal_60_to_80_gross_relative_delta": FREEZE_POLICY[
            "decimal_60_to_80_gross_relative_cap"
        ],
        "max_float64_to_decimal80_gross_relative_delta": FREEZE_POLICY[
            "float64_to_decimal80_gross_relative_cap"
        ],
        "max_moving_cutoff_map_relative_error": FREEZE_POLICY[
            "moving_cutoff_map_cap"
        ],
        "max_state_transfer_relative_error": FREEZE_POLICY[
            "state_transfer_relative_cap"
        ],
        "max_wronskian_relative_error": FREEZE_POLICY[
            "wronskian_relative_cap"
        ],
    }
    freeze_gates = {
        "pilot_hash_bound_before_heldout": True,
        "time_grid_threshold_below_predeclared_ceiling": (
            thresholds["max_time_grid_gross_relative_delta"]
            <= FREEZE_POLICY["time_grid_ceiling"]
        ),
        "momentum_threshold_below_predeclared_ceiling": (
            thresholds["max_momentum_stencil_gross_relative_delta"]
            <= FREEZE_POLICY["momentum_stencil_ceiling"]
        ),
        "adiabatic_remainder_threshold_below_predeclared_ceiling": (
            thresholds["max_tail_to_resolved_gross_relative_residual"]
            <= FREEZE_POLICY["adiabatic_remainder_ceiling"]
        ),
        "heldout_plan_disjoint_and_unseen": True,
        "no_background_candidate_seed_or_kernel": True,
    }
    complete = bool(all(freeze_gates.values()))
    config = pilot["config"]
    return {
        "schema": "apeiron-ap1-m1-uv-tail-handoff-freeze-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "UV_TAIL_HANDOFF_TOLERANCES_FROZEN_HELDOUT_UNSEEN"
            if complete
            else "UV_TAIL_HANDOFF_TOLERANCE_FREEZE_FAILED"
        ),
        "input_sha256": {
            pilot_path.name: file_sha256(pilot_path),
            "AP1/CODE/ap1_m1_uv_tail_handoff_reference.py": code_hash,
        },
        "pilot_updated_utc": pilot["updated_utc"],
        "predeclared_freeze_policy": FREEZE_POLICY,
        "heldout_plan": {
            "sample_relative_N": config["heldout_sample_relative_N"],
            "envelope_endpoint_relative_N": config[
                "heldout_envelope_endpoint_relative_N"
            ],
            "qcut_over_Lambda": config["qcut_over_Lambda"],
            "fine_step_N": config["fine_step_N"],
            "coarse_step_N": config["coarse_step_N"],
            "decimal_high_digits": config["decimal_high_digits"],
        },
        "thresholds": thresholds,
        "gates": freeze_gates,
        "all_tolerance_freeze_gates_pass": complete,
        "tolerances_frozen_before_heldout": complete,
        "heldout_evaluated": False,
        "checkpoint_eligible": False,
        "new_AP1_M1_background_runs": 0,
        "trajectory_rows_persisted": 0,
        "background_candidate_assessed": False,
        "background_tolerances_frozen": False,
        "physical_response_kernel_started": False,
        "seed_released": False,
        "claim_boundary": (
            "pilot-derived local boundary-reference tolerances only; registered "
            "held-out times, coupled background and physical kernel remain unseen"
        ),
        "next_required": (
            "evaluate the registered held-out boundary times once and release no "
            "checkpoint unless every frozen gate passes"
        ),
    }


def _config_from_report(report: dict[str, Any]) -> HandoffConfig:
    data = dict(report["config"])
    for key in ("pilot_sample_relative_N", "heldout_sample_relative_N"):
        data[key] = tuple(data[key])
    config = HandoffConfig(**data)
    config.validate()
    return config


def build_heldout(
    apeiron_root: Path,
    pilot_path: Path,
    freeze_path: Path,
    code_path: Path,
) -> dict[str, Any]:
    pilot = json.loads(pilot_path.read_text(encoding="utf-8"))
    freeze = json.loads(freeze_path.read_text(encoding="utf-8"))
    if not pilot.get("all_pilot_gates_pass"):
        raise UVHandoffError("pilot is not complete")
    if not freeze.get("all_tolerance_freeze_gates_pass"):
        raise UVHandoffError("tolerance freeze is not PASS")
    code_hash = file_sha256(code_path)
    if freeze["input_sha256"].get(pilot_path.name) != file_sha256(pilot_path):
        raise UVHandoffError("pilot hash differs from frozen authority")
    if freeze["input_sha256"].get(
        "AP1/CODE/ap1_m1_uv_tail_handoff_reference.py"
    ) != code_hash:
        raise UVHandoffError("handoff code changed after tolerance freeze")
    config = _config_from_report(pilot)
    plan = freeze["heldout_plan"]
    if list(config.heldout_sample_relative_N) != plan["sample_relative_N"]:
        raise UVHandoffError("held-out sample plan changed after freeze")
    _, arrays, authorities = load_inputs(apeiron_root)
    points, aggregate = evaluate_samples(
        arrays,
        config.heldout_sample_relative_N,
        config.heldout_envelope_endpoint_relative_N,
        config,
    )
    thresholds = freeze["thresholds"]
    gates = {
        "pilot_and_freeze_hash_bound_before_heldout": True,
        "registered_disjoint_heldout_times_used_once": True,
        "frozen_qcut_and_PV_basis_unchanged": (
            config.qcut_over_Lambda == 0.6
            and np.array_equal(PV_C, np.array([1.0, -3.0, 3.0, -1.0]))
            and np.array_equal(PV_J, np.array([0.0, 1.0, 2.0, 3.0]))
        ),
        "boundary_frequencies_positive": (
            aggregate["min_boundary_omega2_Mpl2"] > 0.0
            and aggregate["min_boundary_W_Mpl"] > 0.0
        ),
        "adiabatic_hierarchy_ordered": aggregate[
            "all_adiabatic_hierarchies_ordered"
        ],
        "time_grid_convergence_below_frozen_threshold": (
            aggregate["max_time_grid_gross_relative_delta"]
            <= thresholds["max_time_grid_gross_relative_delta"]
        ),
        "momentum_stencil_convergence_below_frozen_threshold": (
            aggregate["max_momentum_stencil_gross_relative_delta"]
            <= thresholds["max_momentum_stencil_gross_relative_delta"]
        ),
        "tail_to_resolved_remainder_below_frozen_threshold": (
            aggregate["max_tail_to_resolved_gross_relative_residual"]
            <= thresholds["max_tail_to_resolved_gross_relative_residual"]
        ),
        "signed_PV_decimal_precision_below_frozen_cap": (
            aggregate["max_decimal_60_to_80_gross_relative_delta"]
            <= thresholds["max_decimal_60_to_80_gross_relative_delta"]
        ),
        "float64_decimal80_agreement_below_frozen_cap": (
            aggregate["max_float64_to_decimal80_gross_relative_delta"]
            <= thresholds["max_float64_to_decimal80_gross_relative_delta"]
        ),
        "moving_cutoff_map_below_frozen_cap": (
            aggregate["max_moving_cutoff_map_relative_error"]
            <= thresholds["max_moving_cutoff_map_relative_error"]
        ),
        "tail_state_transfer_below_frozen_cap": (
            aggregate["max_state_transfer_relative_error"]
            <= thresholds["max_state_transfer_relative_error"]
        ),
        "wronskian_below_existing_frozen_cap": (
            aggregate["max_wronskian_relative_error"]
            <= thresholds["max_wronskian_relative_error"]
        ),
        "all_heldout_values_finite": aggregate["all_values_finite"],
        "no_handoff_vacuum_reset": not aggregate["any_state_reinitialized"],
        "no_background_candidate_seed_or_kernel": True,
    }
    passed = bool(all(gates.values()))
    return {
        "schema": "apeiron-ap1-m1-uv-tail-handoff-heldout-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "UV_TAIL_HANDOFF_AND_SIGNED_PV_REFERENCE_PASS"
            if passed
            else "UV_TAIL_HANDOFF_HELDOUT_NONPASS"
        ),
        "authority_sha256": {
            **authorities,
            pilot_path.name: file_sha256(pilot_path),
            freeze_path.name: file_sha256(freeze_path),
            "AP1/CODE/ap1_m1_uv_tail_handoff_reference.py": code_hash,
        },
        "heldout_was_unseen_when_tolerances_frozen": True,
        "heldout_points": points,
        "heldout_aggregate": aggregate,
        "frozen_thresholds": thresholds,
        "gates": gates,
        "all_heldout_gates_pass": passed,
        "checkpoint_eligible": passed,
        "new_AP1_M1_background_runs": 0,
        "diagnostic_envelope_integrations": 2,
        "trajectory_rows_persisted": 0,
        "background_candidate_assessed": False,
        "background_tolerances_frozen": False,
        "physical_response_kernel_started": False,
        "seed_released": False,
        "nonpass_stored_or_used_as_seed": False,
        "equations_changed": False,
        "physics_changed": False,
        "parameters_changed": False,
        "existing_gate_thresholds_changed": False,
        "local_memory_convergence_scope": (
            "not_applicable_to_local_adiabatic_handoff; physical two-time kernel "
            "and its memory convergence remain locked"
        ),
        "validated_scope": (
            "moving physical boundary state transfer, local order-0/2/4 split "
            "closure, time-grid and momentum-stencil convergence, exact PV "
            "moments and signed Decimal cancellation"
        ),
        "unvalidated_scope": (
            "coupled moving-split backreaction, long AP1-M1 background, physical "
            "unequal-time response kernel and memory convergence"
        ),
        "claim_boundary": (
            "short fixed-source boundary reference only; no physical background, "
            "source history, kernel, observable, curve, fit or significance"
        ),
        "next_required": (
            "implement the moving split in a bounded coupled AP1-M1 background "
            "pilot, then freeze background tolerances before any candidate assessment"
        ),
    }


def build_checkpoint(
    pilot_path: Path,
    freeze_path: Path,
    heldout_path: Path,
    code_path: Path,
) -> dict[str, Any]:
    pilot = json.loads(pilot_path.read_text(encoding="utf-8"))
    freeze = json.loads(freeze_path.read_text(encoding="utf-8"))
    heldout = json.loads(heldout_path.read_text(encoding="utf-8"))
    if not heldout.get("all_heldout_gates_pass"):
        raise UVHandoffError("only a full held-out PASS may become a checkpoint")
    hashes = {
        pilot_path.name: file_sha256(pilot_path),
        freeze_path.name: file_sha256(freeze_path),
        heldout_path.name: file_sha256(heldout_path),
        "AP1/CODE/ap1_m1_uv_tail_handoff_reference.py": file_sha256(code_path),
    }
    if heldout["authority_sha256"].get(pilot_path.name) != hashes[pilot_path.name]:
        raise UVHandoffError("held-out report is not bound to this pilot")
    if heldout["authority_sha256"].get(freeze_path.name) != hashes[freeze_path.name]:
        raise UVHandoffError("held-out report is not bound to this freeze")
    if heldout["authority_sha256"].get(
        "AP1/CODE/ap1_m1_uv_tail_handoff_reference.py"
    ) != hashes["AP1/CODE/ap1_m1_uv_tail_handoff_reference.py"]:
        raise UVHandoffError("held-out report is not bound to this code")
    gates = {
        "pilot_complete": bool(pilot["all_pilot_gates_pass"]),
        "tolerances_frozen_before_heldout": bool(
            freeze["tolerances_frozen_before_heldout"]
        ),
        "heldout_full_PASS": bool(heldout["all_heldout_gates_pass"]),
        "only_PASS_promoted": True,
        "no_background_kernel_seed_or_observable": True,
    }
    passed = bool(all(gates.values()))
    return {
        "schema": "apeiron-ap1-m1-uv-tail-handoff-reference-checkpoint-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "M1_UV_TAIL_RESOLVED_HANDOFF_AND_SIGNED_PV_REFERENCE_PASS_"
            "LONG_BACKGROUND_PILOT_OPEN_PHYSICAL_KERNEL_BLOCKED"
        ),
        "authority_sha256": hashes,
        "frozen_thresholds": freeze["thresholds"],
        "heldout_aggregate": heldout["heldout_aggregate"],
        "gates": gates,
        "all_checkpoint_gates_pass": passed,
        "checkpoint_eligible": passed,
        "new_AP1_M1_background_runs": 0,
        "trajectory_rows_persisted": 0,
        "background_candidate_assessed": False,
        "background_tolerances_frozen": False,
        "physical_response_kernel_started": False,
        "seed_released": False,
        "nonpass_stored_or_used_as_seed": False,
        "equations_changed": False,
        "physics_changed": False,
        "parameters_changed": False,
        "existing_gate_thresholds_changed": False,
        "next_required": (
            "implement and run a bounded coupled moving-split AP1-M1 background "
            "pilot; freeze pilot-based background tolerances before a disjoint "
            "candidate run; keep the physical response kernel locked"
        ),
        "claim_boundary": heldout["claim_boundary"],
    }


def checkpoint_markdown(report: dict[str, Any]) -> str:
    aggregate = report["heldout_aggregate"]
    thresholds = report["frozen_thresholds"]
    return f"""# Apeiron AP1-M1 – UV-Tail→Resolved-Handoff-Referenz (Latest)

**Stand:** {report['updated_utc']}  
**Klassifikation:** `{report['classification']}`  
**AP1:** ORANGE

## Ergebnis

Der bewegte physische Rand `q_cut=0.6 Lambda` ist auf kurzen, nichtphysischen
Diagnosepräfixen als Zustands- und Quellenübergang bestanden. Der kanonische
adiabatische Zustand der Ordnungen 0/2/4 wird ohne Vakuum-Neustart in die
Log-Amplituden/Riccati-Darstellung übernommen. Die direkte Modenquelle und die
unabhängige abgeschnittene adiabatische Quellenentwicklung schließen bis auf
den explizit behandelten Ordnung-6-Rest.

Die signierten Pauli–Villars-Summen verwenden `C=(1,-3,3,-1)` bei 60 und 80
Decimal-Stellen. Die PV-Momente 0, 1 und 2 verschwinden exakt.

## Heldout-Maxima

- Zeitgitterdelta relativ zur groben PV-Skala: `{aggregate['max_time_grid_gross_relative_delta']}`
  (Freeze `{thresholds['max_time_grid_gross_relative_delta']}`)
- Impulsstencildelta relativ zur groben PV-Skala: `{aggregate['max_momentum_stencil_gross_relative_delta']}`
  (Freeze `{thresholds['max_momentum_stencil_gross_relative_delta']}`)
- Tail→Resolved-Rest relativ zur groben PV-Skala: `{aggregate['max_tail_to_resolved_gross_relative_residual']}`
  (Freeze `{thresholds['max_tail_to_resolved_gross_relative_residual']}`)
- Decimal-60→80-Delta: `{aggregate['max_decimal_60_to_80_gross_relative_delta']}`
- Float64→Decimal80-Delta: `{aggregate['max_float64_to_decimal80_gross_relative_delta']}`
- Wronskianfehler: `{aggregate['max_wronskian_relative_error']}`
- `max |W2/W0|`: `{aggregate['max_abs_W2_over_W0']}`
- `max |W4/W0|`: `{aggregate['max_abs_W4_over_W0']}`

## Grenze

Dies ist kein gekoppelter oder langer AP1-M1-Hintergrundlauf. Es wurden keine
Trajektorienreihen, Produktionsquellen, Seeds, Antwortkerne, Kurven, Fits oder
Signifikanzen freigegeben. Die Gedächtniskonvergenz gehört zum weiterhin
gesperrten zweizeitigen physikalischen Antwortkern und ist für diesen lokalen
Handoff nicht anwendbar.

## Nächster zulässiger Schritt

Den bewegten Split in einen begrenzten gekoppelten AP1-M1-Hintergrundpilot
integrieren. Erst danach pilotbasierte Hintergrundtoleranzen separat einfrieren
und einen disjunkten Kandidatenlauf prüfen. Der physikalische Antwortkern bleibt
gesperrt.
"""


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    subparsers = parser.add_subparsers(dest="command", required=True)
    pilot_parser = subparsers.add_parser("pilot")
    pilot_parser.add_argument("--root", type=Path, required=True)
    pilot_parser.add_argument("--output", type=Path, required=True)
    freeze_parser = subparsers.add_parser("freeze")
    freeze_parser.add_argument("--pilot", type=Path, required=True)
    freeze_parser.add_argument("--output", type=Path, required=True)
    heldout_parser = subparsers.add_parser("heldout")
    heldout_parser.add_argument("--root", type=Path, required=True)
    heldout_parser.add_argument("--pilot", type=Path, required=True)
    heldout_parser.add_argument("--freeze", type=Path, required=True)
    heldout_parser.add_argument("--output", type=Path, required=True)
    checkpoint_parser = subparsers.add_parser("checkpoint")
    checkpoint_parser.add_argument("--pilot", type=Path, required=True)
    checkpoint_parser.add_argument("--freeze", type=Path, required=True)
    checkpoint_parser.add_argument("--heldout", type=Path, required=True)
    checkpoint_parser.add_argument("--output-json", type=Path, required=True)
    checkpoint_parser.add_argument("--output-md", type=Path, required=True)
    args = parser.parse_args()
    code_path = Path(__file__).resolve()
    if args.command == "pilot":
        report = build_pilot(args.root.resolve(), code_path)
        _write_json(report, args.output)
    elif args.command == "freeze":
        report = build_freeze(args.pilot.resolve(), code_path)
        _write_json(report, args.output)
    elif args.command == "heldout":
        report = build_heldout(
            args.root.resolve(), args.pilot.resolve(), args.freeze.resolve(), code_path
        )
        _write_json(report, args.output)
    else:
        report = build_checkpoint(
            args.pilot.resolve(),
            args.freeze.resolve(),
            args.heldout.resolve(),
            code_path,
        )
        _write_json(report, args.output_json)
        args.output_md.write_text(checkpoint_markdown(report), encoding="utf-8")


if __name__ == "__main__":
    main()
