#!/usr/bin/env python3
"""E410-M standalone zero-CAIN-import offline verifier.

Independently verifies:
  1. Manifest schema, exact file list, per-file SHA-256 hashes, Merkle root, MERKLE_ROOT.txt, Ed25519 signature.
  2. Preregistration freeze SHA-256 and revealed cryptographic salt commitments.
  3. Source-code withholding (no engine .py files leaked in the public bundle).
  4. Every Ed25519 signature and SHA-256 hash-chain link in all four exported governed shared memories
     (primary/replication x clean/byzantine), plus independent reconstruction of trusted macro libraries
     from the raw signed memory records.
  5. Full deterministic regeneration of the 64 unseen sealed tasks per salt and independent re-execution
     of the bounded sealed solver across all 6 arms and all generations (G0..G3).
  6. Exact binomial McNemar p-values, all 8 preregistered hypotheses H1-H8, overall verdict, checkpoint
     hash chain, reports, acceptance registry, deviations, and zero-model resource accounting.
"""
from __future__ import annotations

import hashlib
import json
import math
import random
import sys
from pathlib import Path

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
EX = {
    "E410-M_MANIFEST.json",
    "E410-M_SIGNED_BODY.json",
    "E410-M_VERIFICATION_RESULTS.json",
    "MANIFEST.json",
    "MERKLE_ROOT.txt",
    "PUBLICATION.json",
    "E410-M_OMEGA_SEAL.json",
    "E410-M_TAMPER_RESULTS.json",
}
ENGINE_FORBIDDEN = {"domain.py", "memory.py", "worker.py", "run.py"}
ARMS = (
    "FLAT_NO_RSI",
    "ISOLATED_AGENTS",
    "SINGLE_GENERALIST_4X",
    "UNGOVERNED_BYZANTINE",
    "GOVERNED_CLEAN",
    "GOVERNED_BYZANTINE",
)
CLAMP = 9999
VEC_LEN = 6
DEV_EXAMPLES = 4
SEALED_EXAMPLES = 6
MAX_MACROS = 48
SEALED_SOLVER_BUDGET = 850
EVALUATOR_ID = "rsi-a4"
ROGUE_ID = "rsi-a6"
TENANT = "rsi"


def canon(o) -> bytes:
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b) -> str:
    return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).hexdigest()


def e380m_pub(agent: str) -> str:
    sk = Ed25519PrivateKey.from_private_bytes(hashlib.sha256(("e380m|" + agent).encode()).digest())
    return sk.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()


def _clamp(v: int) -> int:
    return CLAMP if v > CLAMP else (-CLAMP if v < -CLAMP else v)


PRIMS = {
    "inc": lambda s: tuple(_clamp(x + 1) for x in s),
    "dec": lambda s: tuple(_clamp(x - 1) for x in s),
    "dbl": lambda s: tuple(_clamp(x * 2) for x in s),
    "neg": lambda s: tuple(_clamp(-x) for x in s),
    "rev": lambda s: s[::-1],
    "rot_l": lambda s: s[1:] + s[:1],
    "rot_r": lambda s: s[-1:] + s[:-1],
    "swap_adj": lambda s: (s[1], s[0], s[3], s[2], s[5], s[4]),
    "psum": lambda s: tuple(_clamp(sum(s[:i + 1])) for i in range(len(s))),
    "diff": lambda s: (s[0],) + tuple(_clamp(s[i] - s[i - 1]) for i in range(1, len(s))),
    "rmax": lambda s: tuple(max(s[:i + 1]) for i in range(len(s))),
    "pavg": lambda s: tuple(_clamp(s[i] + s[(i + 1) % len(s)]) for i in range(len(s))),
    "xor5": lambda s: tuple(_clamp(x ^ 5) for x in s),
    "mod11": lambda s: tuple(x % 11 for x in s),
    "clip5": lambda s: tuple(-5 if x < -5 else (5 if x > 5 else x) for x in s),
    "thresh": lambda s: tuple(_clamp(x + 3) if x > 0 else _clamp(-x) for x in s),
}
SPECIALTIES = (
    ("rsi-a0", ("inc", "dec", "dbl", "neg")),
    ("rsi-a1", ("rev", "rot_l", "rot_r", "swap_adj")),
    ("rsi-a2", ("psum", "diff", "rmax", "pavg")),
    ("rsi-a3", ("xor5", "mod11", "clip5", "thresh")),
)
ALL_PRIMS = tuple(op for _, ops in SPECIALTIES for op in ops)
SPEC_NAMES = tuple(n for n, _ in SPECIALTIES)


def eval_prog(ops, vec):
    cur = vec
    for op in ops:
        cur = PRIMS[op](cur)
    return cur


def eval_ex(ops, exs):
    for a, b in exs:
        if eval_prog(ops, a) != b:
            return False
    return True


def _rng(salt_hex: str, label: str) -> random.Random:
    return random.Random(int.from_bytes(hashlib.sha256(f"e410m|{salt_hex}|{label}".encode()).digest()[:8], "big"))


def _sample_inputs(rng, count):
    return [tuple(rng.randint(-9, 9) for _ in range(VEC_LEN)) for _ in range(count)]


def _sig(ops, probes):
    return tuple(eval_prog(ops, x) for x in probes)


def rebuild_sealed_tasks(salt_hex: str) -> list[dict]:
    rng = _rng(salt_hex, "benchmark-v1")
    probes = _sample_inputs(_rng(salt_hex, "nondegenerate-probes"), 8)
    used = {tuple(probes)}
    for a in ALL_PRIMS:
        used.add(_sig((a,), probes))
        for b in ALL_PRIMS:
            used.add(_sig((a, b), probes))
    blocks = {}
    for sn, pool in SPECIALTIES:
        cands = [(a, b, c) for a in pool for b in pool for c in pool]
        rng.shuffle(cands)
        chosen = []
        for c in cands:
            sg = _sig(c, probes)
            if sg in used:
                continue
            used.add(sg)
            chosen.append(c)
            if len(chosen) == 4:
                break
        blocks[sn] = chosen
    for sn in SPEC_NAMES:
        for _ in range(4):
            _sample_inputs(rng, DEV_EXAMPLES)

    sealed = []
    dev_t2 = {s: [] for s in SPEC_NAMES}
    used2 = set(used)
    for s1 in SPEC_NAMES:
        pool = [(i1, s2, i2, b1 + b2) for i1, b1 in enumerate(blocks[s1])
                for s2 in SPEC_NAMES if s2 != s1 for i2, b2 in enumerate(blocks[s2])]
        rng.shuffle(pool)
        pd = ps = 0
        for _, s2, _, ops6 in pool:
            sg = _sig(ops6, probes)
            if sg in used2:
                continue
            used2.add(sg)
            if pd < 4:
                dev_t2[s1].append((s1, s2, ops6))
                _sample_inputs(rng, DEV_EXAMPLES)
                pd += 1
            elif ps < 4:
                xs = _sample_inputs(rng, SEALED_EXAMPLES)
                sealed.append({"tier": "SEALED_T2_CROSS", "examples": [(x, eval_prog(ops6, x)) for x in xs]})
                ps += 1
            if pd == 4 and ps == 4:
                break
    for s1 in SPEC_NAMES:
        pool = [(i1, i2, blocks[s1][i1] + blocks[s1][i2]) for i1 in range(4) for i2 in range(4) if i1 != i2]
        rng.shuffle(pool)
        p = 0
        for _, _, ops6 in pool:
            sg = _sig(ops6, probes)
            if sg in used2:
                continue
            used2.add(sg)
            xs = _sample_inputs(rng, SEALED_EXAMPLES)
            sealed.append({"tier": "SEALED_SINGLE", "examples": [(x, eval_prog(ops6, x)) for x in xs]})
            p += 1
            if p == 4:
                break
    dev_t3 = {s: [] for s in SPEC_NAMES}
    used3 = set(used2)
    for s1 in SPEC_NAMES:
        pool = [(s2, s3, ops6 + b3) for _, s2, ops6 in dev_t2[s1]
                for s3 in SPEC_NAMES if s3 not in (s1, s2) for b3 in blocks[s3]]
        rng.shuffle(pool)
        pd = ps = 0
        for s2, s3, ops9 in pool:
            sg = _sig(ops9, probes)
            if sg in used3:
                continue
            used3.add(sg)
            if pd < 4:
                dev_t3[s1].append((s1, s2, s3, ops9))
                _sample_inputs(rng, DEV_EXAMPLES)
                pd += 1
            elif ps < 4:
                xs = _sample_inputs(rng, SEALED_EXAMPLES)
                sealed.append({"tier": "SEALED_T3_CROSS", "examples": [(x, eval_prog(ops9, x)) for x in xs]})
                ps += 1
            if pd == 4 and ps == 4:
                break
    used4 = set(used3)
    for s1 in SPEC_NAMES:
        pool = [ops9 + b4 for _, s2, s3, ops9 in dev_t3[s1]
                for s4 in SPEC_NAMES if s4 not in (s1, s2, s3) for b4 in blocks[s4]]
        rng.shuffle(pool)
        p = 0
        for ops12 in pool:
            sg = _sig(ops12, probes)
            if sg in used4:
                continue
            used4.add(sg)
            xs = _sample_inputs(rng, SEALED_EXAMPLES)
            sealed.append({"tier": "SEALED_T4_DEEP", "examples": [(x, eval_prog(ops12, x)) for x in xs]})
            p += 1
            if p == 4:
                break
    return sealed


def solve_sealed(task: dict, macros: list[tuple[str, ...]]) -> bool:
    exs = task["examples"]
    active = macros[:MAX_MACROS]
    t1 = [m for m in active if len(m) == 3]
    seen = set()
    ev = 0

    def tr(ops):
        nonlocal ev
        if ev >= SEALED_SOLVER_BUDGET or ops in seen:
            return False
        seen.add(ops)
        ev += 1
        return eval_ex(ops, exs)

    for m in active:
        if tr(m):
            return True
        if ev >= SEALED_SOLVER_BUDGET:
            return False
    for ml in active:
        for mr in t1:
            if len(ml) + len(mr) > 12:
                continue
            if tr(ml + mr):
                return True
            if ev >= SEALED_SOLVER_BUDGET:
                return False
    for a in ALL_PRIMS:
        if tr((a,)):
            return True
        if ev >= SEALED_SOLVER_BUDGET:
            return False
    for a in ALL_PRIMS:
        for b in ALL_PRIMS:
            if tr((a, b)):
                return True
            if ev >= SEALED_SOLVER_BUDGET:
                return False
    return False


def exact_mcnemar_p(a_mask, b_mask) -> float:
    n10 = sum(1 for a, b in zip(a_mask, b_mask) if a and not b)
    n01 = sum(1 for a, b in zip(a_mask, b_mask) if not a and b)
    n = n10 + n01
    if n == 0:
        return 1.0
    k = min(n10, n01)
    return min(1.0, 2.0 * sum(math.comb(n, i) for i in range(k + 1)) / (2 ** n))


def verify_memory_jsonl(path: Path) -> tuple[bool, int, list[list[str]], int]:
    """Verify every Ed25519 signature and SHA-256 hash-chain link; derive trusted macros directly."""
    lines = [ln for ln in path.read_text().splitlines() if ln.strip()]
    prev = "0" * 64
    by_hash = {}
    rogue_results = 0
    for idx, ln in enumerate(lines, 1):
        r = json.loads(ln)
        if r["seq"] != idx or r["prev"] != prev or r["tenant"] != TENANT:
            return False, idx, [], rogue_results
        body = {
            "tenant": r["tenant"],
            "seq": r["seq"],
            "agent": r["agent"],
            "kind": r["kind"],
            "payload": r["payload"],
            "uncertainty": round(float(r["uncertainty"]), 6),
            "verification": r["verification"],
            "prev": r["prev"],
        }
        expected_pub = e380m_pub(r["agent"])
        if r.get("pubkey") != expected_pub:
            return False, idx, [], rogue_results
        try:
            Ed25519PublicKey.from_public_bytes(bytes.fromhex(expected_pub)).verify(
                bytes.fromhex(r["sig"]), canon(body)
            )
        except Exception:
            return False, idx, [], rogue_results
        if r["hash"] != sha(canon(body) + bytes.fromhex(r["sig"])):
            return False, idx, [], rogue_results
        prev = r["hash"]
        if r["kind"] == "result":
            p = r["payload"]
            if r["agent"] != EVALUATOR_ID:
                rogue_results += 1
            elif p.get("verified"):
                ops = p.get("ops")
                mh = hashlib.sha256("|".join(ops).encode()).hexdigest()
                if p.get("macro_hash") == mh and mh not in by_hash:
                    by_hash[mh] = (len(ops), idx, ops)
    ordered = [ops for _, _, ops in sorted(by_hash.values())][:MAX_MACROS]
    return True, len(lines), ordered, rogue_results


def merkle(paths) -> str:
    lv = sorted(sha(p.read_bytes()) for p in paths)
    while len(lv) > 1:
        if len(lv) % 2:
            lv.append(lv[-1])
        lv = [sha((lv[i] + lv[i + 1]).encode()) for i in range(0, len(lv), 2)]
    return lv[0] if lv else sha(b"")


def main() -> int:
    d = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    checks: list[tuple[str, bool]] = []

    def ck(name: str, ok: bool) -> None:
        checks.append((name, bool(ok)))

    man = json.loads((d / "E410-M_MANIFEST.json").read_text())
    pre = json.loads((d / "E410-M_PREREGISTRATION.json").read_text())
    frz = json.loads((d / "E410-M_PREREGISTRATION_FREEZE.json").read_text())
    rep = json.loads((d / "E410-M_RUN_REPORT.json").read_text())
    salt_doc = json.loads((d / "E410-M_SALT_REVEALED.json").read_text())
    acc = json.loads((d / "E410-M_ACCEPTANCE_REGISTRY.json").read_text())
    dev = json.loads((d / "E410-M_DEVIATIONS.json").read_text())

    ck("schema", man.get("schema") == "cain42.e410m.manifest.v1" and rep.get("evolution") == "E410-M")
    files = sorted(p for p in d.rglob("*") if p.is_file()
                   and str(p.relative_to(d)) not in EX and "__pycache__" not in p.parts)
    ck("files_exact", set(man["files"]) == {str(p.relative_to(d)) for p in files})
    ck("file_hashes", all(sha(p.read_bytes()) == man["files"][str(p.relative_to(d))] for p in files))
    ck("merkle_root", man["merkle_root"] == merkle(files))
    ck("merkle_file", (d / "MERKLE_ROOT.txt").read_text().strip() == man["merkle_root"])
    try:
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(
            bytes.fromhex(man["signature"]), canon(json.loads((d / "E410-M_SIGNED_BODY.json").read_text()))
        )
        ck("manifest_signature", True)
    except Exception:
        ck("manifest_signature", False)

    ck("prereg_freeze", sha((d / "E410-M_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"] == rep["preregistration_sha256"])
    ck("salt_commitments", all(sha(bytes.fromhex(v)) == pre["salt_commitment_sha256"][k] for k, v in salt_doc["salts"].items()))
    ck("source_withheld", not any(p.name in ENGINE_FORBIDDEN for p in d.rglob("*") if p.is_file()))

    # Verify all four governed shared memories + re-execute all sealed tasks across both salts!
    recomputed_salts = {}
    for salt_name in ("primary", "replication"):
        s_rep = rep["salts"][salt_name]
        ok_c, n_c, lib_c, _ = verify_memory_jsonl(d / f"checkpoints/{salt_name}_governed_clean_memory.jsonl")
        ok_b, n_b, lib_b, rogue_r = verify_memory_jsonl(d / f"checkpoints/{salt_name}_governed_byzantine_memory.jsonl")
        ck(f"{salt_name}_clean_memory_sigs_and_chain", ok_c and n_c == s_rep["security_probes"]["governed_clean_records"])
        ck(f"{salt_name}_byz_memory_sigs_and_chain", ok_b and n_b == s_rep["security_probes"]["governed_byzantine_records"])
        ck(f"{salt_name}_clean_lib_matches_memory", lib_c == s_rep["arms"]["GOVERNED_CLEAN"]["libraries_by_gen"][-1])
        ck(f"{salt_name}_byz_lib_matches_memory", lib_b == s_rep["arms"]["GOVERNED_BYZANTINE"]["libraries_by_gen"][-1])
        ck(f"{salt_name}_rogue_poison_logged_and_filtered", rogue_r == s_rep["security_probes"]["self_signed_poison_written"] > 0)

        sealed = rebuild_sealed_tasks(salt_doc["salts"][salt_name])
        ck(f"{salt_name}_sealed_count", len(sealed) == 64)
        arm_masks = {}
        for arm in ARMS:
            a_rep = s_rep["arms"][arm]
            curve = []
            last_mask = []
            last_tiers = {}
            for g in range(4):
                if arm == "ISOLATED_AGENTS":
                    libs_g = {ag: [tuple(x) for x in a_rep["libraries_by_gen"][g][ag]] for ag in SPEC_NAMES}
                    mask = [any(solve_sealed(t, libs_g[ag]) for ag in SPEC_NAMES) for t in sealed]
                else:
                    lib_g = [tuple(x) for x in a_rep["libraries_by_gen"][g]]
                    mask = [solve_sealed(t, lib_g) for t in sealed]
                curve.append(sum(mask))
                if g == 3:
                    last_mask = mask
                    last_tiers = {k: 0 for k in ("SEALED_SINGLE", "SEALED_T2_CROSS", "SEALED_T3_CROSS", "SEALED_T4_DEEP")}
                    for ok, t in zip(mask, sealed):
                        if ok:
                            last_tiers[t["tier"]] += 1
            ck(f"{salt_name}_{arm}_curve", curve == a_rep["curve"] and curve[-1] == a_rep["final_solved"])
            ck(f"{salt_name}_{arm}_tiers_and_mask", last_mask == a_rep["solved_mask_final"] and last_tiers == a_rep["by_tier_final"])
            arm_masks[arm] = last_mask

        # Recompute exact McNemar p-values.
        pairs = [
            ("GOVERNED_CLEAN_vs_FLAT_NO_RSI", "GOVERNED_CLEAN", "FLAT_NO_RSI"),
            ("GOVERNED_CLEAN_vs_ISOLATED_AGENTS", "GOVERNED_CLEAN", "ISOLATED_AGENTS"),
            ("GOVERNED_CLEAN_vs_SINGLE_GENERALIST_4X", "GOVERNED_CLEAN", "SINGLE_GENERALIST_4X"),
            ("GOVERNED_BYZANTINE_vs_UNGOVERNED_BYZANTINE", "GOVERNED_BYZANTINE", "UNGOVERNED_BYZANTINE"),
            ("GOVERNED_BYZANTINE_vs_GOVERNED_CLEAN", "GOVERNED_BYZANTINE", "GOVERNED_CLEAN"),
        ]
        for cname, a1, a2 in pairs:
            p = exact_mcnemar_p(arm_masks[a1], arm_masks[a2])
            ck(f"{salt_name}_mcnemar_{cname}", abs(p - s_rep["contrasts"][cname]["p_value"]) < 1e-12)
        recomputed_salts[salt_name] = s_rep

    # Recompute hypotheses H1-H8 and overall verdict.
    pri, rep_s = recomputed_salts["primary"], recomputed_salts["replication"]

    def _h1(s):
        c = s["arms"]["GOVERNED_CLEAN"]["curve"]
        return (c[0] < c[1] < c[2] < c[3]) and c[3] >= 56 and s["contrasts"]["GOVERNED_CLEAN_vs_FLAT_NO_RSI"]["p_value"] < 1e-10

    def _h2(s):
        return (s["arms"]["GOVERNED_CLEAN"]["final_solved"] - s["arms"]["ISOLATED_AGENTS"]["final_solved"] >= 36
                and s["contrasts"]["GOVERNED_CLEAN_vs_ISOLATED_AGENTS"]["p_value"] < 1e-10
                and s["arms"]["ISOLATED_AGENTS"]["by_tier_final"]["SEALED_SINGLE"] >= 12)

    def _h3(s):
        return (s["arms"]["GOVERNED_CLEAN"]["final_solved"] - s["arms"]["SINGLE_GENERALIST_4X"]["final_solved"] >= 36
                and s["contrasts"]["GOVERNED_CLEAN_vs_SINGLE_GENERALIST_4X"]["p_value"] < 1e-10)

    def _h4(s):
        gb = s["arms"]["GOVERNED_BYZANTINE"]["final_solved"]
        ub = s["arms"]["UNGOVERNED_BYZANTINE"]["final_solved"]
        gc = s["arms"]["GOVERNED_CLEAN"]["final_solved"]
        return (gb - ub >= 36 and s["contrasts"]["GOVERNED_BYZANTINE_vs_UNGOVERNED_BYZANTINE"]["p_value"] < 1e-10
                and abs(gb - gc) <= 2)

    def _h5(s):
        pr = s["security_probes"]
        return (pr["governed_clean_chain_valid"] and pr["governed_byzantine_chain_valid"]
                and pr["forged_evaluator_sig_attempted"] > 0
                and pr["forged_evaluator_sig_refused"] == pr["forged_evaluator_sig_attempted"]
                and pr["self_signed_poison_written"] > 0 and pr["self_signed_poison_admitted_to_trusted"] == 0
                and pr["authority_from_memory_probed"] > 0 and pr["authority_from_memory_allowed"] == 0
                and pr["revoked_writer_attempted"] > 0 and pr["revoked_writer_accepted"] == 0
                and pr["cross_tenant_probed"] > 0 and pr["cross_tenant_leaked"] == 0
                and pr["storage_tamper_detected"]
                and pr["distinct_worker_pids_clean"] >= 5 and pr["distinct_worker_pids_byzantine"] >= 6)

    h_map = {
        "H1_recursive_compounding": "SUPPORTED" if (_h1(pri) and _h1(rep_s)) else "NOT_SUPPORTED",
        "H2_shared_memory_beats_isolated": "SUPPORTED" if (_h2(pri) and _h2(rep_s)) else "NOT_SUPPORTED",
        "H3_specialist_colony_beats_single_generalist": "SUPPORTED" if (_h3(pri) and _h3(rep_s)) else "NOT_SUPPORTED",
        "H4_governance_survives_byzantine_poisoning": "SUPPORTED" if (_h4(pri) and _h4(rep_s)) else "NOT_SUPPORTED",
        "H5_security_and_memory_invariants": "SUPPORTED" if (_h5(pri) and _h5(rep_s)) else "NOT_SUPPORTED",
        "H7_zero_authority_and_zero_model_leak": "SUPPORTED" if (
            pri["security_probes"]["reads_all_non_authority"] and rep_s["security_probes"]["reads_all_non_authority"]
        ) else "NOT_SUPPORTED",
        "H8_external_review": "BLOCKED",
    }
    h_map["H6_replication_consistency"] = "SUPPORTED" if all(
        h_map[k] == "SUPPORTED" for k in (
            "H1_recursive_compounding", "H2_shared_memory_beats_isolated",
            "H3_specialist_colony_beats_single_generalist", "H4_governance_survives_byzantine_poisoning",
            "H5_security_and_memory_invariants"
        )
    ) else "NOT_SUPPORTED"

    core_ok = [h_map[k] == "SUPPORTED" for k in (
        "H1_recursive_compounding", "H2_shared_memory_beats_isolated",
        "H3_specialist_colony_beats_single_generalist", "H4_governance_survives_byzantine_poisoning",
        "H5_security_and_memory_invariants"
    )]
    if all(core_ok) and h_map["H6_replication_consistency"] == "SUPPORTED" and h_map["H7_zero_authority_and_zero_model_leak"] == "SUPPORTED":
        verdict = "GOVERNED_SHARED_MEMORY_RSI_SUPPORTED"
    elif any(core_ok):
        verdict = "PARTIAL"
    else:
        verdict = "NOT_SUPPORTED"
    ck("hypotheses_and_verdict", verdict == rep["verdict"] and all(
        h_map[k] == rep["hypotheses"][k]["verdict"] for k in h_map
    ))

    # Checkpoint summary hash chain.
    ch = [json.loads(ln) for ln in (d / "checkpoints/rsi_chain.jsonl").read_text().splitlines() if ln.strip()]
    prev = "0" * 64
    ch_ok = len(ch) == 2
    for idx, entry in enumerate(ch, 1):
        h = sha((prev + sha(canon(entry["payload"]))).encode())
        if entry["seq"] != idx or entry["prev"] != prev or entry["hash"] != h:
            ch_ok = False
        prev = h
    cp_meta = json.loads((d / "checkpoints/rsi_chain.json").read_text())
    ck("checkpoint_chain", ch_ok and cp_meta["count"] == 2 and cp_meta["head"] == prev == rep["checkpoint"]["head"])

    # Headline, reports, acceptance, deviations, resources.
    hl = rep["finding"]["headline"]
    ck("headline_matches_salts", (
        hl["verdict"] == verdict
        and hl["primary_governed_clean"] == pri["arms"]["GOVERNED_CLEAN"]["final_solved"]
        and hl["primary_governed_byzantine"] == pri["arms"]["GOVERNED_BYZANTINE"]["final_solved"]
        and hl["replication_governed_clean"] == rep_s["arms"]["GOVERNED_CLEAN"]["final_solved"]
        and hl["replication_governed_byzantine"] == rep_s["arms"]["GOVERNED_BYZANTINE"]["final_solved"]
        and hl["poison_macros_admitted_total"] == 0
        and hl["authority_from_memory_allowed_total"] == 0
    ))
    ck("manifest_headline_matches", man["headline"]["verdict"] == verdict
       and man["headline"]["primary_governed_byzantine"] == hl["primary_governed_byzantine"]
       and man["headline"]["replication_governed_byzantine"] == hl["replication_governed_byzantine"])
    ck("law_present", "multiple specialist agents sharing one governed memory" in rep["finding"]["law"])
    ck("final_report_verdict", f"**Preregistered verdict: {verdict}.**" in (d / "E410-M_FINAL_REPORT.md").read_text())
    ck("public_summary_verdict", verdict in (d / "E410-M_PUBLIC_SUMMARY.md").read_text())
    ck("acceptance_registry", acc["verdict"] == verdict)
    ck("deviations_schema", dev.get("schema") == "cain42.e410m.deviations.v1")
    ck("resources_zero_model", rep["resources"]["model_calls"] == 0 and rep["resources"]["api_spend_usd"] == 0.0
       and rep["resources"]["neural_weights_modified"] is False)

    bad = [n for n, ok in checks if not ok]
    for n, ok in checks:
        print(("PASS " if ok else "FAIL ") + n)
    print(f"{len(checks) - len(bad)}/{len(checks)} checks passed")
    return 0 if not bad else 1


if __name__ == "__main__":
    raise SystemExit(main())
