"""Fail-closed G32C-bound log-H recovery pilot, freeze, and new heldout.

The interval through relative N=0.10 was consumed by the failed G32B heldout
and is therefore development information only.  This driver may recompute it
as a non-blind log-H recovery pilot.  Only after a complete pilot PASS may it
freeze new method tolerances.  The preregistered N=0.105..0.12 interval is
then eligible for one prospective heldout evaluation.

Only aggregate diagnostics may be serialized.  NONPASS reports, trajectories,
and seeds are never written.  The physical equations, model parameters,
counterterms, PV basis, moving split, mode transport, operator settings, and
all existing gate ceilings remain unchanged.
"""
from __future__ import annotations

import argparse
from dataclasses import asdict
from datetime import datetime, timezone
from hashlib import sha256
import json
import math
from pathlib import Path
from types import SimpleNamespace
from typing import Any, Callable

import numpy as np

import ap1_m1_balanced_coupled_stage_pilot as g32b
import ap1_m1_balanced_coupled_stage_preflight as g32
import ap1_m1_coupled_moving_split_background as g29
import ap1_m1_logh_positive_branch_recovery_preflight as g32c


EXPECTED_G32C_AUTHORITIES = {
    "AP1/APEIRON_AP1_M1_LOGH_POSITIVE_BRANCH_RECOVERY_PREFLIGHT_LATEST.json": (
        "c25bff80552343198987c4c324c38ad2e696b3870ea7fa6f09ea944d2f1a8fd1"
    ),
    "AP1/APEIRON_AP1_M1_LOGH_POSITIVE_BRANCH_RECOVERY_PREFLIGHT_CHECKPOINT_LATEST.md": (
        "9282b1dfdbb03b32b88201c4bff8f653292dc6fa204a66e55de9924efc0f20f5"
    ),
    "AP1/CODE/ap1_m1_logh_positive_branch_recovery_preflight.py": (
        "1096e20e94bc60bdd0d484c3c940c207c83a7dadec2ba3a8db93cc626b839695"
    ),
    "AP1/CODE/test_ap1_m1_logh_positive_branch_recovery_preflight.py": (
        "43ed61f5c628701d3653820dbf477370ebfa75ee1a55e6e7f33c0aafa7e89091"
    ),
}


class LogHRecoveryPilotError(g29.CoupledBackgroundError):
    """An authority, chronology, numerical, or physical gate failed."""


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 verify_g32c_preflight(root: Path) -> dict[str, Any]:
    observed = {
        name: file_sha256(root / name) for name in EXPECTED_G32C_AUTHORITIES
    }
    if observed != EXPECTED_G32C_AUTHORITIES:
        changed = [
            name
            for name, expected in EXPECTED_G32C_AUTHORITIES.items()
            if observed.get(name) != expected
        ]
        raise LogHRecoveryPilotError(f"G32C authority drift: {changed}")
    report = json.loads(
        (
            root
            / "AP1/APEIRON_AP1_M1_LOGH_POSITIVE_BRANCH_RECOVERY_PREFLIGHT_LATEST.json"
        ).read_text(encoding="utf-8")
    )
    if not report.get("all_preflight_gates_pass") or not report.get(
        "recovery_pilot_eligible"
    ):
        raise LogHRecoveryPilotError("G32C preflight is not recovery-pilot PASS")
    if report.get("prospective_heldout_eligible"):
        raise LogHRecoveryPilotError("G32C improperly opened the new heldout")
    if any(
        int(report.get(name, -1)) != 0
        for name in ("background_runs", "physical_response_kernel_runs")
    ):
        raise LogHRecoveryPilotError("G32C preflight contains an unexpected run")
    audit = report["failed_G32B_heldout_audit"]
    if not (
        audit["registered_G32B_heldout_attempts"] == 1
        and not audit["G32B_heldout_report_written"]
        and not audit["G32B_heldout_checkpoint_or_seed_released"]
        and not audit["consumed_N_le_0p10_domain_is_blind"]
    ):
        raise LogHRecoveryPilotError("consumed-domain audit is inconsistent")
    plan = g32c.LogHRecoveryPlan(**report["recovery_plan"])
    plan.validate()
    g32c.verify_authorities(root)
    return report


def _load_arrays(root: Path) -> dict[str, np.ndarray]:
    _, arrays, _ = g29.load_inputs(root)
    return arrays


def _phase_settings(
    plan: g32c.LogHRecoveryPlan, phase: str
) -> tuple[tuple[int, int, int], float, float]:
    if phase == "recovery_pilot":
        return (
            plan._level_nodes(phase),
            plan.recovery_pilot_span_N,
            plan.recovery_pilot_evaluation_start_N,
        )
    if phase == "prospective_heldout":
        return (
            plan._level_nodes(phase),
            plan.prospective_heldout_span_N,
            plan.prospective_heldout_evaluation_start_N,
        )
    raise LogHRecoveryPilotError("unknown recovery phase")


def evaluate_three_level_phase(
    arrays: dict[str, np.ndarray],
    plan: g32c.LogHRecoveryPlan,
    phase: str,
    overlap_reference: dict[str, float],
    progress: Callable[[str], None] | None = None,
) -> dict[str, Any]:
    plan.validate()
    nodes, span, evaluation_start = _phase_settings(plan, phase)
    runs: dict[str, dict[str, Any]] = {}
    for label, count in zip(("coarse", "middle", "fine"), nodes):
        if progress is not None:
            progress(f"{phase}:{label}:start nodes={count}")
        runs[label] = g32c.run_logh_balanced_coupled(
            arrays, span, count, plan
        )
        if progress is not None:
            progress(
                f"{phase}:{label}:done closure="
                f"{runs[label]['validation_source_gross_relative_change']:.17g}"
            )

    coarse_to_middle = g29.time_convergence_metrics(
        runs["middle"], runs["coarse"], evaluation_start
    )
    middle_to_fine = g29.time_convergence_metrics(
        runs["fine"], runs["middle"], evaluation_start
    )
    convergence = g32b.three_level_convergence_audit(
        coarse_to_middle,
        middle_to_fine,
        float(g32.PREDECLARED_POLICY["minimum_observed_Richardson_order"]),
    )
    if progress is not None:
        progress(f"{phase}:operator_checks:start")
    physical = g29.physical_diagnostics(runs["fine"], arrays, evaluation_start)
    operator = g32b.balanced_operator_convergence_metrics(
        runs["fine"], arrays, plan, evaluation_start
    )
    precision = g29.decimal_precision_metrics(
        runs["fine"],
        evaluation_start,
        plan.decimal_low_digits,
        plan.decimal_high_digits,
    )
    if progress is not None:
        progress(f"{phase}:operator_checks:done")

    overlap_N = float(overlap_reference["N_relative"])
    overlap_expected = float(overlap_reference["H_Mpl"])
    overlap_values = {
        label: g32b._grid_value(run, overlap_N, "H")
        for label, run in runs.items()
    }
    overlap_by_level = {
        label: abs(value - overlap_expected)
        / max(abs(value), abs(overlap_expected), 1.0e-300)
        for label, value in overlap_values.items()
    }
    fine = runs["fine"]
    metrics = {
        "max_fixed_point_source_gross_relative_change": float(
            fine["validation_source_gross_relative_change"]
        ),
        "max_background_time_relative_delta": float(
            middle_to_fine["max_background_time_relative_delta"]
        ),
        "max_source_time_gross_relative_delta": float(
            middle_to_fine["max_source_time_gross_relative_delta"]
        ),
        "max_entry_quadrature_gross_relative_delta": float(
            operator["max_entry_quadrature_gross_relative_delta"]
        ),
        "max_tail_quadrature_gross_relative_delta": float(
            operator["max_tail_quadrature_gross_relative_delta"]
        ),
        "max_uv_cutoff_gross_relative_delta": float(
            operator["max_uv_cutoff_gross_relative_delta"]
        ),
        "max_friedmann_normalized": float(
            physical["max_friedmann_normalized"]
        ),
        "max_raychaudhuri_normalized": float(
            physical["max_raychaudhuri_normalized"]
        ),
        "ward_normalized": float(physical["ward_normalized"]),
        "standard_continuity_normalized": float(
            physical["standard_continuity_normalized"]
        ),
        "max_stage_overlap_H_relative_delta": float(overlap_by_level["fine"]),
    }
    return {
        "phase": phase,
        "gate_interval_N": [float(evaluation_start), float(span)],
        "level_nodes": list(nodes),
        "same_operator_settings_on_all_levels": True,
        "levels": {
            name: g32b._level_summary(run) for name, run in runs.items()
        },
        "physical_diagnostics": physical,
        "time_convergence": {
            "coarse_to_middle": coarse_to_middle,
            "middle_to_fine": middle_to_fine,
            "three_level_audit": convergence,
        },
        "operator_convergence": operator,
        "precision": precision,
        "source_diagnostics": fine["source_diagnostics"],
        "overlap_audit": {
            "reference_N_relative": overlap_N,
            "reference_H_Mpl": overlap_expected,
            "observed_H_Mpl_by_level": overlap_values,
            "relative_delta_by_level": overlap_by_level,
        },
        "stage_endpoint_aggregate_not_a_seed": {
            "N_relative": float(span),
            "physical_N": float(physical["physical_N_endpoint"]),
            "H_Mpl": float(physical["H_endpoint_Mpl"]),
            "delta_H_over_H": float(physical["delta_H_over_H"]),
        },
        "metrics_for_freeze_or_gate": metrics,
        "trajectory_rows_persisted": 0,
        "new_AP1_M1_background_resolution_runs": 3,
        "physical_response_kernel_runs": 0,
    }


def _phase_gates(
    ensemble: dict[str, Any],
    plan: g32c.LogHRecoveryPlan,
    phase: str,
) -> dict[str, bool]:
    if phase not in ("recovery_pilot", "prospective_heldout"):
        raise LogHRecoveryPilotError("unknown recovery phase")
    adapter = SimpleNamespace(
        max_pilot_resolved_modes=plan.max_recovery_pilot_resolved_modes,
        max_heldout_resolved_modes=plan.max_prospective_heldout_resolved_modes,
    )
    legacy_phase = "pilot" if phase == "recovery_pilot" else "heldout"
    gates = g32b._phase_gates(ensemble, adapter, legacy_phase)
    levels = ensemble["levels"]
    return {
        **gates,
        "all_background_levels_use_exact_logH_chart": bool(
            all(
                item["config"].get("background_chart") == g32c.LOGH_CHART
                for item in levels.values()
            )
        ),
        "all_level_endpoints_remain_finite_positive_H": bool(
            all(
                math.isfinite(float(item["H_endpoint_Mpl"]))
                and float(item["H_endpoint_Mpl"]) > 0.0
                for item in levels.values()
            )
        ),
    }


def _ceiling_gates(ensemble: dict[str, Any]) -> dict[str, bool]:
    return g32b._ceiling_gates(ensemble)


def build_pilot(
    root: Path,
    code_path: Path,
    test_path: Path,
    progress: Callable[[str], None] | None = None,
) -> dict[str, Any]:
    preflight = verify_g32c_preflight(root)
    plan = g32c.LogHRecoveryPlan(**preflight["recovery_plan"])
    plan.validate()
    old_pilot = json.loads(
        (
            root / "AP1/APEIRON_AP1_M1_BALANCED_COUPLED_STAGE_PILOT_LATEST.json"
        ).read_text(encoding="utf-8")
    )
    if not old_pilot.get("all_pilot_gates_pass"):
        raise LogHRecoveryPilotError("G32B overlap authority is not PASS")
    old_endpoint = old_pilot["pilot_ensemble"]["stage_endpoint_aggregate_not_a_seed"]
    overlap = {
        "N_relative": float(old_endpoint["N_relative"]),
        "H_Mpl": float(old_endpoint["H_Mpl"]),
    }
    arrays = _load_arrays(root)
    ensemble = evaluate_three_level_phase(
        arrays, plan, "recovery_pilot", overlap, progress=progress
    )
    gates = {
        "G32C_preflight_hash_bound_and_PASS": True,
        "G32B_failed_heldout_not_reused_as_validation_or_seed": True,
        "N_le_0p10_domain_used_as_explicitly_nonblind_recovery_pilot": bool(
            plan.recovery_pilot_span_N == plan.consumed_G32B_span_N
        ),
        "future_N_0p105_to_0p12_heldout_strictly_disjoint_and_unseen": bool(
            plan.prospective_heldout_evaluation_start_N
            > plan.recovery_pilot_span_N
        ),
        **_phase_gates(ensemble, plan, "recovery_pilot"),
        **_ceiling_gates(ensemble),
        "production_tolerances_present_anchor_and_response_kernel_locked": True,
    }
    passed = bool(all(gates.values()))
    return {
        "schema": "apeiron-ap1-m1-logh-recovery-three-level-pilot-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "M1_LOGH_RECOVERY_THREE_LEVEL_PILOT_PASS_G32D_TOLERANCE_FREEZE_OPEN_NEW_HELDOUT_LOCKED_PHYSICAL_KERNEL_BLOCKED"
            if passed
            else "M1_LOGH_RECOVERY_THREE_LEVEL_PILOT_NONPASS"
        ),
        "authority_sha256": {
            **EXPECTED_G32C_AUTHORITIES,
            "AP1/CODE/ap1_m1_logh_recovery_pilot.py": file_sha256(code_path),
            "AP1/CODE/test_ap1_m1_logh_recovery_pilot.py": file_sha256(test_path),
        },
        "plan": asdict(plan),
        "predeclared_policy": g32.PREDECLARED_POLICY,
        "pilot_is_nonblind_development": True,
        "consumed_G32B_heldout_was_not_retried_as_validation": True,
        "recovery_pilot_ensemble": ensemble,
        "gates": gates,
        "all_pilot_gates_pass": passed,
        "prospective_heldout_evaluated": False,
        "checkpoint_eligible": False,
        "method_tolerances_frozen": False,
        "production_background_tolerances_frozen": False,
        "trajectory_rows_persisted": 0,
        "new_AP1_M1_background_resolution_runs": 3,
        "physical_response_kernel_runs": 0,
        "retarded_response_applicable": False,
        "memory_convergence_applicable": 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,
        "AP1_status": "ORANGE",
        "claim_boundary": (
            "non-blind log-H numerical recovery pilot through relative N=0.10 "
            "only; no prospective heldout, production background, present "
            "anchor, response kernel, observable, curve, fit, or significance"
        ),
        "next_required": (
            "freeze new log-H method tolerances before evaluating the "
            "preregistered disjoint N=0.105..0.12 heldout once"
            if passed
            else "stop fail-closed; do not persist, freeze, evaluate, or seed"
        ),
    }


def _verify_pilot_code_hashes(
    pilot: dict[str, Any], code_path: Path, test_path: Path
) -> None:
    expected = {
        "AP1/CODE/ap1_m1_logh_recovery_pilot.py": file_sha256(code_path),
        "AP1/CODE/test_ap1_m1_logh_recovery_pilot.py": file_sha256(test_path),
    }
    for name, digest in expected.items():
        if pilot["authority_sha256"].get(name) != digest:
            raise LogHRecoveryPilotError(f"pilot authority changed: {name}")


def build_freeze(
    pilot_path: Path, code_path: Path, test_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(
        "prospective_heldout_evaluated"
    ):
        raise LogHRecoveryPilotError("complete pre-heldout recovery pilot PASS required")
    _verify_pilot_code_hashes(pilot, code_path, test_path)
    plan = g32c.LogHRecoveryPlan(**pilot["plan"])
    plan.validate()
    metrics = pilot["recovery_pilot_ensemble"]["metrics_for_freeze_or_gate"]
    thresholds = g32b._thresholds_from_metrics(metrics)
    policy = g32.PREDECLARED_POLICY["inherited_metric_freeze_policy"]
    gates = {
        "recovery_pilot_hash_bound_before_new_heldout": True,
        **{
            f"{name}_threshold_below_predeclared_ceiling": bool(
                math.isfinite(thresholds[name])
                and thresholds[name] <= float(specification["ceiling"])
            )
            for name, specification in policy.items()
        },
        "new_heldout_interval_registered_disjoint_and_unseen": bool(
            plan.prospective_heldout_evaluation_start_N
            > plan.consumed_G32B_span_N
        ),
        "production_tolerances_present_anchor_and_response_kernel_locked": True,
    }
    passed = bool(all(gates.values()))
    endpoint = pilot["recovery_pilot_ensemble"]["stage_endpoint_aggregate_not_a_seed"]
    return {
        "schema": "apeiron-ap1-m1-logh-recovery-three-level-freeze-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "M1_LOGH_RECOVERY_METHOD_TOLERANCES_FROZEN_G32D_NEW_HELDOUT_UNSEEN"
            if passed
            else "M1_LOGH_RECOVERY_METHOD_TOLERANCE_FREEZE_NONPASS"
        ),
        "input_sha256": {
            pilot_path.name: file_sha256(pilot_path),
            "AP1/CODE/ap1_m1_logh_recovery_pilot.py": file_sha256(code_path),
            "AP1/CODE/test_ap1_m1_logh_recovery_pilot.py": file_sha256(test_path),
        },
        "predeclared_policy": g32.PREDECLARED_POLICY,
        "thresholds": thresholds,
        "prospective_heldout_plan": {
            "span_N": plan.prospective_heldout_span_N,
            "evaluation_start_N": plan.prospective_heldout_evaluation_start_N,
            "nodes": list(plan._level_nodes("prospective_heldout")),
            "overlap_reference": {
                "N_relative": float(endpoint["N_relative"]),
                "H_Mpl": float(endpoint["H_Mpl"]),
            },
        },
        "gates": gates,
        "all_tolerance_freeze_gates_pass": passed,
        "tolerances_frozen_before_prospective_heldout": passed,
        "prospective_heldout_evaluated": False,
        "method_tolerances_frozen": passed,
        "production_background_tolerances_frozen": False,
        "trajectory_rows_persisted": 0,
        "physical_response_kernel_runs": 0,
        "seed_released": False,
        "nonpass_stored_or_used_as_seed": False,
        "AP1_status": "ORANGE",
        "claim_boundary": (
            "non-blind recovery-pilot-derived method tolerances only; new "
            "prospective heldout, production background, present anchor, and "
            "physical response kernel remain unseen"
        ),
        "next_required": (
            "evaluate the preregistered disjoint N=0.105..0.12 heldout once "
            "and persist only a full PASS"
            if passed
            else "stop fail-closed; do not evaluate the new heldout"
        ),
    }


def build_heldout(
    root: Path,
    pilot_path: Path,
    freeze_path: Path,
    code_path: Path,
    test_path: Path,
    progress: Callable[[str], None] | None = None,
) -> 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 LogHRecoveryPilotError("recovery pilot is not PASS")
    if not freeze.get("all_tolerance_freeze_gates_pass"):
        raise LogHRecoveryPilotError("recovery tolerance freeze is not PASS")
    if freeze["input_sha256"].get(pilot_path.name) != file_sha256(pilot_path):
        raise LogHRecoveryPilotError("recovery pilot changed after freeze")
    _verify_pilot_code_hashes(pilot, code_path, test_path)
    for name, path in (
        ("AP1/CODE/ap1_m1_logh_recovery_pilot.py", code_path),
        ("AP1/CODE/test_ap1_m1_logh_recovery_pilot.py", test_path),
    ):
        if freeze["input_sha256"].get(name) != file_sha256(path):
            raise LogHRecoveryPilotError(f"code changed after freeze: {name}")
    preflight = verify_g32c_preflight(root)
    plan = g32c.LogHRecoveryPlan(**pilot["plan"])
    if asdict(plan) != preflight["recovery_plan"]:
        raise LogHRecoveryPilotError("recovery plan differs from G32C")
    plan.validate()
    heldout_plan = freeze["prospective_heldout_plan"]
    if not (
        heldout_plan["span_N"] == plan.prospective_heldout_span_N
        and heldout_plan["evaluation_start_N"]
        == plan.prospective_heldout_evaluation_start_N
        and heldout_plan["nodes"]
        == list(plan._level_nodes("prospective_heldout"))
    ):
        raise LogHRecoveryPilotError("new heldout plan changed after freeze")
    arrays = _load_arrays(root)
    ensemble = evaluate_three_level_phase(
        arrays,
        plan,
        "prospective_heldout",
        heldout_plan["overlap_reference"],
        progress=progress,
    )
    metrics = ensemble["metrics_for_freeze_or_gate"]
    if set(metrics) != set(freeze["thresholds"]):
        raise LogHRecoveryPilotError(
            "prospective heldout metric set differs from frozen thresholds"
        )
    numerical = {
        f"{name}_below_frozen_threshold": bool(
            math.isfinite(float(value))
            and float(value) <= float(freeze["thresholds"][name])
        )
        for name, value in metrics.items()
    }
    gates = {
        "pilot_and_freeze_hash_bound_before_new_heldout": True,
        "registered_new_disjoint_heldout_used_once": True,
        **_phase_gates(ensemble, plan, "prospective_heldout"),
        **numerical,
        "production_tolerances_present_anchor_and_response_kernel_locked": True,
    }
    passed = bool(all(gates.values()))
    return {
        "schema": "apeiron-ap1-m1-logh-recovery-three-level-heldout-v1.0",
        "updated_utc": _utc_now(),
        "classification": (
            "M1_LOGH_RECOVERY_THREE_LEVEL_HELDOUT_PASS_G32E_CHECKPOINT_OPEN_PHYSICAL_KERNEL_BLOCKED"
            if passed
            else "M1_LOGH_RECOVERY_THREE_LEVEL_HELDOUT_NONPASS"
        ),
        "authority_sha256": {
            **EXPECTED_G32C_AUTHORITIES,
            pilot_path.name: file_sha256(pilot_path),
            freeze_path.name: file_sha256(freeze_path),
            "AP1/CODE/ap1_m1_logh_recovery_pilot.py": file_sha256(code_path),
            "AP1/CODE/test_ap1_m1_logh_recovery_pilot.py": file_sha256(test_path),
        },
        "frozen_thresholds": freeze["thresholds"],
        "heldout_was_unseen_when_tolerances_frozen": True,
        "prospective_heldout_ensemble": ensemble,
        "gates": gates,
        "all_heldout_gates_pass": passed,
        "checkpoint_eligible": passed,
        "new_AP1_M1_background_resolution_runs": 6,
        "method_tolerances_frozen": True,
        "production_background_tolerances_frozen": False,
        "trajectory_rows_persisted": 0,
        "physical_response_kernel_runs": 0,
        "seed_released": False,
        "nonpass_stored_or_used_as_seed": False,
        "equations_changed": False,
        "physics_changed": False,
        "parameters_changed": False,
        "existing_gate_thresholds_changed": False,
        "AP1_status": "ORANGE",
        "claim_boundary": (
            "log-H recovery prefix through relative N=0.12 only; no production "
            "background, present anchor, response kernel, observable, curve, "
            "fit, or significance"
        ),
        "next_required": (
            "promote the bounded G32E checkpoint and predeclare the next long "
            "pilot; production tolerances and physical kernel remain locked"
            if passed
            else "stop fail-closed; do not persist, checkpoint, or seed"
        ),
    }


def build_checkpoint(
    pilot_path: Path,
    freeze_path: Path,
    heldout_path: Path,
    code_path: Path,
    test_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 (
        pilot.get("all_pilot_gates_pass")
        and freeze.get("all_tolerance_freeze_gates_pass")
        and heldout.get("all_heldout_gates_pass")
    ):
        raise LogHRecoveryPilotError("full recovery pilot/freeze/heldout PASS required")
    expected = {
        pilot_path.name: file_sha256(pilot_path),
        freeze_path.name: file_sha256(freeze_path),
        "AP1/CODE/ap1_m1_logh_recovery_pilot.py": file_sha256(code_path),
        "AP1/CODE/test_ap1_m1_logh_recovery_pilot.py": file_sha256(test_path),
    }
    for name, digest in expected.items():
        if heldout["authority_sha256"].get(name) != digest:
            raise LogHRecoveryPilotError(f"heldout authority mismatch: {name}")
    ensemble = heldout["prospective_heldout_ensemble"]
    return {
        "schema": "apeiron-ap1-m1-logh-recovery-three-level-checkpoint-v1.0",
        "updated_utc": _utc_now(),
        "classification": "M1_LOGH_RECOVERY_THREE_LEVEL_HELDOUT_PASS_G32E_NEXT_LONG_PILOT_OPEN_PHYSICAL_KERNEL_BLOCKED",
        "authority_sha256": {
            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_logh_recovery_pilot.py": file_sha256(code_path),
            "AP1/CODE/test_ap1_m1_logh_recovery_pilot.py": file_sha256(test_path),
        },
        "frozen_method_thresholds": freeze["thresholds"],
        "heldout_metrics": ensemble["metrics_for_freeze_or_gate"],
        "heldout_three_level_convergence": ensemble["time_convergence"],
        "heldout_physical_diagnostics": ensemble["physical_diagnostics"],
        "heldout_source_diagnostics": ensemble["source_diagnostics"],
        "heldout_operator_convergence": ensemble["operator_convergence"],
        "heldout_precision": ensemble["precision"],
        "heldout_overlap_audit": ensemble["overlap_audit"],
        "gates": {
            "nonblind_recovery_pilot_complete": True,
            "method_tolerances_frozen_before_new_heldout": True,
            "new_prospective_heldout_full_PASS": True,
            "only_PASS_promoted": True,
            "no_production_background_kernel_seed_or_observable": True,
        },
        "all_checkpoint_gates_pass": True,
        "checkpoint_eligible": True,
        "new_AP1_M1_background_resolution_runs": 6,
        "validated_relative_N_endpoint": 0.12,
        "method_tolerances_frozen": True,
        "production_background_tolerances_frozen": False,
        "trajectory_rows_persisted": 0,
        "physical_response_kernel_runs": 0,
        "seed_released": False,
        "nonpass_stored_or_used_as_seed": False,
        "equations_changed": False,
        "physics_changed": False,
        "parameters_changed": False,
        "existing_gate_thresholds_changed": False,
        "AP1_status": "ORANGE",
        "claim_boundary": (
            "bounded log-H recovery prefix through relative N=0.12 only; no "
            "production trajectory, present anchor, response kernel, observable, "
            "curve, fit, or significance"
        ),
        "next_required": (
            "predeclare a separate long pilot; production tolerances, present "
            "anchor, and physical response kernel remain locked"
        ),
    }


def checkpoint_markdown(report: dict[str, Any]) -> str:
    metrics = report["heldout_metrics"]
    physical = report["heldout_physical_diagnostics"]
    source = report["heldout_source_diagnostics"]
    audit = report["heldout_three_level_convergence"]["three_level_audit"]
    return f"""# Apeiron AP1 – G32E log-H recovery checkpoint

**Updated UTC:** {report['updated_utc']}  
**Classification:** `{report['classification']}`  
**AP1 status:** ORANGE

The consumed N<=0.10 domain was used only as a non-blind log-H recovery pilot.
Only after its complete PASS were new method tolerances frozen.  The disjoint
N=0.105..0.12 heldout was then evaluated once on three nested grids.
Equations, physics, parameters, counterterms, PV sectors, moving split, mode
transport, and all existing gate thresholds remained unchanged.

## Heldout aggregate

- validated relative endpoint: `{report['validated_relative_N_endpoint']}`
- fixed-point source closure: `{metrics['max_fixed_point_source_gross_relative_change']:.17g}`
- middle-to-fine background delta: `{metrics['max_background_time_relative_delta']:.17g}`
- middle-to-fine source delta: `{metrics['max_source_time_gross_relative_delta']:.17g}`
- minimum resolved Richardson order: `{audit['minimum_finite_observed_Richardson_order_above_floor']}`
- Friedmann residual: `{physical['max_friedmann_normalized']:.17g}`
- Raychaudhuri residual: `{physical['max_raychaudhuri_normalized']:.17g}`
- flux-balanced Ward residual: `{physical['ward_normalized']:.17g}`
- standard continuity residual: `{physical['standard_continuity_normalized']:.17g}`
- Wronskian error: `{source['resolved']['max_wronskian_relative_error']:.17g}`

All frozen heldout gates pass.  Zero trajectory rows and zero seeds were
released.  This validates only the bounded prefix through relative N=0.12;
production tolerances, the present anchor, the physical two-time response
kernel, AP2/AP3, curves, observables, fits, and significances remain locked.
"""


def _write_pass_json(report: dict[str, Any], output: Path, pass_key: str) -> None:
    if not report.get(pass_key):
        raise LogHRecoveryPilotError("NONPASS report was not written")
    serialized = json.dumps(report, indent=2, allow_nan=False) + "\n"
    output.parent.mkdir(parents=True, exist_ok=True)
    with output.open("x", encoding="utf-8") as stream:
        stream.write(serialized)


def _nonpass_summary(report: dict[str, Any]) -> dict[str, Any]:
    gates = report.get("gates", {})
    ensemble = (
        report.get("recovery_pilot_ensemble")
        or report.get("prospective_heldout_ensemble")
        or {}
    )
    return {
        "classification": report.get("classification"),
        "failed_gates": [name for name, passed in gates.items() if not passed],
        "metrics": ensemble.get("metrics_for_freeze_or_gate"),
        "three_level_audit": ensemble.get("time_convergence", {}).get(
            "three_level_audit"
        ),
        "output_written": False,
    }


def _write_or_fail(report: dict[str, Any], output: Path, pass_key: str) -> None:
    if not report.get(pass_key):
        print(json.dumps(_nonpass_summary(report), indent=2, allow_nan=False))
        raise SystemExit(2)
    _write_pass_json(report, output, pass_key)


def main() -> None:
    parser = argparse.ArgumentParser()
    sub = parser.add_subparsers(dest="command", required=True)
    pilot_parser = sub.add_parser("pilot")
    pilot_parser.add_argument("apeiron_root", type=Path)
    pilot_parser.add_argument("--test-path", type=Path, required=True)
    pilot_parser.add_argument("--output", type=Path, required=True)
    freeze_parser = sub.add_parser("freeze")
    freeze_parser.add_argument("pilot", type=Path)
    freeze_parser.add_argument("--test-path", type=Path, required=True)
    freeze_parser.add_argument("--output", type=Path, required=True)
    heldout_parser = sub.add_parser("heldout")
    heldout_parser.add_argument("apeiron_root", type=Path)
    heldout_parser.add_argument("pilot", type=Path)
    heldout_parser.add_argument("freeze", type=Path)
    heldout_parser.add_argument("--test-path", type=Path, required=True)
    heldout_parser.add_argument("--output", type=Path, required=True)
    checkpoint_parser = sub.add_parser("checkpoint")
    checkpoint_parser.add_argument("pilot", type=Path)
    checkpoint_parser.add_argument("freeze", type=Path)
    checkpoint_parser.add_argument("heldout", type=Path)
    checkpoint_parser.add_argument("--test-path", type=Path, required=True)
    checkpoint_parser.add_argument("--json-output", type=Path, required=True)
    checkpoint_parser.add_argument("--md-output", type=Path, required=True)
    args = parser.parse_args()
    code_path = Path(__file__).resolve()
    progress = lambda message: print(message, flush=True)
    if args.command == "pilot":
        report = build_pilot(
            args.apeiron_root, code_path, args.test_path, progress=progress
        )
        _write_or_fail(report, args.output, "all_pilot_gates_pass")
    elif args.command == "freeze":
        report = build_freeze(args.pilot, code_path, args.test_path)
        _write_or_fail(
            report, args.output, "all_tolerance_freeze_gates_pass"
        )
    elif args.command == "heldout":
        report = build_heldout(
            args.apeiron_root,
            args.pilot,
            args.freeze,
            code_path,
            args.test_path,
            progress=progress,
        )
        _write_or_fail(report, args.output, "all_heldout_gates_pass")
    else:
        report = build_checkpoint(
            args.pilot, args.freeze, args.heldout, code_path, args.test_path
        )
        if args.json_output.exists() or args.md_output.exists():
            raise FileExistsError("checkpoint output already exists")
        _write_pass_json(report, args.json_output, "all_checkpoint_gates_pass")
        with args.md_output.open("x", encoding="utf-8") as stream:
            stream.write(checkpoint_markdown(report))


if __name__ == "__main__":
    main()
