#!/usr/bin/env python3
"""Clean-room verifier for the CAIN-42 Evolution 19 evidence bundle (Governed Autonomy Operating Fabric).

Imports NOTHING from CAIN: Python standard library + `cryptography` only. From the published JSON it re-hashes every
file against MANIFEST.json, recomputes every published digest (state lineage, autonomy state, goals, beliefs, model,
mission, memory chain, checkpoint, contracts, decisions and the E8 canonical-action hash), re-derives the effective
authority as the intersection of the sixteen published factors, re-derives every published autonomy level with its
own copy of the rule, re-derives which bindings invalidated the invalidated contract, verifies every Ed25519
signature (E8 token, human approval, governance quorum, checkpoint, master), and checks the invariant, bench,
end-to-end and mutation records for consistency. It does not re-run the fabric, and it does NOT prove that any
belief is true or that any physical system is safe or controlled.

    python3 verify_e19.py <bundle dir>      -> JSON on stdout; exit 0 only if INTACT
"""
from __future__ import annotations

import base64
import hashlib
import json
import re
import sys
from pathlib import Path

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives.asymmetric import ed25519

D = {"state": "CAIN42/E19-GOVERNED-STATE/v1", "autonomy_state": "CAIN42/E19-GOVERNED-AUTONOMY-STATE/v1",
     "mission": "CAIN42/E19-MISSION/v1", "goal": "CAIN42/E19-GOAL/v1", "belief": "CAIN42/E19-BELIEF/v1",
     "memory": "CAIN42/E19-MEMORY/v1", "model": "CAIN42/E19-MODEL-PASSPORT/v1",
     "authority": "CAIN42/E19-EFFECTIVE-AUTHORITY/v1", "causal": "CAIN42/E19-CAUSAL-CHAIN/v1",
     "level": "CAIN42/E19-AUTONOMY-LEVEL/v1", "human": "CAIN42/E19-HUMAN-APPROVAL/v1",
     "contract": "CAIN42/E19-ACTION-CONTRACT/v1", "gate": "CAIN42/E19-CONTRACT-DECISION/v1",
     "checkpoint": "CAIN42/E19-CHECKPOINT/v1", "root": "CAIN42/E19-GOVERNANCE-ROOT/v1",
     "root_mutation": "CAIN42/E19-GOVERNANCE-MUTATION/v1", "adversarial": "CAIN42/E19-ADVERSARIAL/v1",
     "master": "CAIN42/E19-MASTER/v1", "e8_action": "CAIN42/E8-CANONICAL-ACTION/v1",
     "e8_token": "CAIN42/E8-GOVERNANCE-AUTHORIZATION-TOKEN/v1"}
REQUIRED = ("README.md", "MANIFEST.json", "SCHEMAS.json", "INVARIANTS.json", "ATTACK_MANIFEST.json",
            "TEST_RESULTS.json", "END_TO_END_RESULTS.json", "PERFORMANCE.json", "SIGNATURES.json", "HASHES.json",
            "CLEAN_ROOM_VERIFIER.json", "verify_e19.py.txt", "PUBLIC_SAFE_EXAMPLES.json", "LIMITATIONS.json",
            "LIMITATIONS.md", "PROVENANCE.json", "CAIN42_E19_EVIDENCE_BUNDLE.json", "MUTATION_RESULTS.json",
            "CAIN42_EVOLUTION19_CLAIMS.json", "REPRODUCE.txt", "index.html")
FORBIDDEN_MATERIAL = ("-----begin", "private_key", "secret_key", "password")
FORBIDDEN_WORDS = ("perfect", "guaranteed", "controls every ai", "solves agi safety", "fully controls",
                   "guarantees autonomous driving", "guarantees drone safety", "unhackable")
CLAIM_STATES = ("IMPLEMENTED", "TESTED", "VERIFIED", "REPRODUCIBLE", "SIMULATED", "DEMO_ONLY", "UNVERIFIED", "UNKNOWN",
                "NOT_IMPLEMENTED", "NOT_PERFORMED", "NOT_THIRD_PARTY_VERIFIED")
REQUIRED_CATEGORIES = ("identity", "goals", "beliefs", "memory", "models", "authority", "world", "planning",
                       "multi_agent", "learning", "execution", "recovery", "physical", "governance")
REQUIRED_E2E = ("MISSION", "GOAL", "BELIEF", "WORLD_STATE", "PREDICTION", "PLAN", "AUTHORIZATION", "ACTION",
                "WORLD_CHANGE", "INVALIDATION", "OUTCOME", "PREDICTION_ERROR", "TRUST_UPDATE", "DEGRADED_AUTONOMY",
                "RECOVERY", "RE_AUTHORIZATION", "CONTINUED_OPERATION")
INJECTION = ("ignore previous", "ignore all previous", "you are now authorized", "you are authorized",
             "grant yourself", "new policy:", "system prompt", "disregard the policy", "admin override",
             "elevate privileges")
# independent copy of the autonomy-level rule
REQ = {"SUPERVISED": (0.3, 1, 0.8), "LIMITED_AUTONOMY": (0.5, 2, 0.5), "AUTONOMOUS": (0.7, 3, 0.3),
       "HIGH_AUTONOMY": (0.85, 5, 0.15)}
RANK = {"UNKNOWN": 0, "OBSERVED": 0, "ASSESSED": 1, "RESTRICTED": 1, "SUPERVISED": 2, "LIMITED_AUTONOMY": 3,
        "AUTONOMOUS": 4, "HIGH_AUTONOMY": 5, "DEGRADED": 1, "CONTAINED": 0, "RECOVERY": 1, "REVOKED": 0,
        "TERMINATED": 0}


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


def h(o) -> str:
    return hashlib.sha256(canon(o)).hexdigest()


def dig(domain: str, fields: dict) -> str:
    return h({"domain": domain, **fields})


def sig_ok(pub: str, sig: str, domain: str, fields: dict) -> bool:
    try:
        ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify(
            base64.b64decode(sig), dig(domain, fields).encode())
        return True
    except (InvalidSignature, ValueError, TypeError):
        return False


def strip(d: dict, *keys: str) -> dict:
    return {k: v for k, v in d.items() if k not in keys}


def finite(x) -> bool:
    return isinstance(x, (int, float)) and not isinstance(x, bool) and x == x and x not in (float("inf"), float("-inf"))


def level_of(i: dict) -> str:
    if i.get("terminated"):
        return "TERMINATED"
    if i.get("revoked"):
        return "REVOKED"
    if i.get("contained") or i.get("anomalies", 0) >= 3:
        return "CONTAINED"
    if i.get("recovering"):
        return "RECOVERY"
    if i.get("identity_verified") is None or not finite(i.get("trust")) or not finite(i.get("uncertainty")):
        return "UNKNOWN"
    if not i["identity_verified"]:
        return "RESTRICTED"
    if i.get("anomalies", 0) >= 1:
        return "DEGRADED"
    lvl = "ASSESSED"
    for name in ("SUPERVISED", "LIMITED_AUTONOMY", "AUTONOMOUS", "HIGH_AUTONOMY"):
        t, n, u = REQ[name]
        if i["trust"] >= t and i.get("evidence_count", 0) >= n and i["uncertainty"] <= u:
            lvl = name
    if i.get("human_supervision") and RANK[lvl] > RANK["SUPERVISED"]:
        lvl = "SUPERVISED"
    return lvl


class Checks:
    def __init__(self) -> None:
        self.detail, self.problems = [], []

    def check(self, name: str, ok, detail="") -> None:
        ok = bool(ok)
        self.detail.append({"check": name, "result": "PASS" if ok else "FAIL", "detail": str(detail)[:160]})
        if not ok:
            self.problems.append(name)

    def guard(self, name: str, fn) -> None:
        try:
            self.check(name, fn())
        except Exception as e:  # noqa: BLE001  (a check that cannot run is a failure)
            self.check(name, False, f"{type(e).__name__}: {e}")


def main(root: Path) -> int:
    C = Checks()
    load = lambda n: json.loads((root / n).read_text())  # noqa: E731

    # ---- files, manifest, hashes, signatures ----
    C.check("files.required_present", all((root / n).exists() for n in REQUIRED),
            [n for n in REQUIRED if not (root / n).exists()])
    man = load("MANIFEST.json")
    bad = [n for n, s in man["files"].items() if not (root / n).exists()
           or hashlib.sha256((root / n).read_bytes()).hexdigest() != s]
    C.check("manifest.file_hashes", not bad, bad)
    # REPRODUCE.txt tells a reader to save the verifier next to the files as verify_e19.py; that copy is theirs
    local = ("MANIFEST.json", "index.html", "verify_e19.py")
    C.check("manifest.covers_all_files", sorted(man["files"]) == sorted(
        p.name for p in root.iterdir() if p.is_file() and p.name not in local), "coverage")
    C.check("manifest.presentation_unhashed", man.get("unhashed_presentation") == ["index.html"], "index.html")
    hs = load("HASHES.json")["files"]
    C.check("hashes.match_files", all(hashlib.sha256((root / n).read_bytes()).hexdigest() == s for n, s in hs.items()),
            "hashes")
    sg = load("SIGNATURES.json")
    C.check("signatures.master_binds_hashes", sg["master"]["hashes_digest"] == h(hs), "hashes digest")
    C.check("signatures.master_signature", sig_ok(sg["signer_public_key_b64"], sg["signature_b64"], D["master"],
                                                  sg["master"]), "ed25519")
    C.check("signatures.key_class_honest", sg.get("key_class") == "EPHEMERAL", sg.get("key_class"))
    texts = {p.name: p.read_text(errors="replace").lower() for p in root.iterdir()
             if p.is_file() and p.name not in ("verify_e19.py.txt", "verify_e19.py")}
    C.check("no_forbidden_material", not any(m in t for t in texts.values() for m in FORBIDDEN_MATERIAL), "material")

    ex = load("PUBLIC_SAFE_EXAMPLES.json")

    # ---- state lineage ----
    lin = ex["lineage"]
    recs = lin["records"]
    C.check("lineage.record_digests", [dig(D["state"], r) for r in recs] == lin["digests"], "digests")
    C.check("lineage.parent_links", all(r["parent_state_id"] == (recs[i - 1]["state_id"] if i else "genesis")
                                         for i, r in enumerate(recs)), "links")
    C.check("lineage.sequence_contiguous", [r["sequence_number"] for r in recs] == list(range(len(recs))), "seq")
    C.check("lineage.time_monotone", all(recs[i]["created_at"] <= recs[i + 1]["created_at"]
                                         for i in range(len(recs) - 1)), "time")
    C.check("lineage.provenance_present", all(r["provenance_digest"] for r in recs), "provenance")
    C.check("lineage.root", h({"lineage": lin["lineage_id"], "digests": lin["digests"]}) == lin["root"], "root")

    # ---- autonomy state ----
    st = ex["autonomy_state"]
    C.check("autonomy_state.digest", dig(D["autonomy_state"], st["body"]) == st["digest"], "digest")
    C.check("autonomy_state.unknown_components_honest",
            sorted(k for k, v in st["body"]["components"].items() if v == "UNKNOWN") == sorted(st["unknown_components"])
            and len(st["body"]["components"]) == 25, len(st["unknown_components"]))

    # ---- effective authority = intersection of the sixteen factors ----
    au = ex["effective_authority"]
    order = au["factor_order"]
    C.check("authority.sixteen_factors", len(order) == 16 and sorted(au["factors"]) == sorted(order), len(order))

    def inter(factors):
        sets = [set(factors[f]) for f in order]
        return sorted(set.intersection(*sets))
    C.check("authority.compiled_is_intersection", au["compiled"]["effective"] == inter(au["factors"]), "∩")
    C.check("authority.narrowed_is_intersection", au["narrowed"]["effective"] == inter(au["narrowed_factors"])
            and set(au["narrowed"]["effective"]) < set(au["compiled"]["effective"]), "shrinks")
    C.check("authority.unknown_factor_is_empty", au["unknown"]["state"] == "UNKNOWN" and au["unknown"]["effective"] == []
            and "human_authority" in au["unknown"]["unknown_factors"], au["unknown"]["state"])
    for name in ("compiled", "narrowed", "unknown"):
        C.check(f"authority.{name}.digest", dig(D["authority"], strip(au[name], "digest")) == au[name]["digest"], name)
    C.check("authority.no_authority_label", all(au[n]["authority"] == "NONE" for n in ("compiled", "narrowed", "unknown")),
            "NONE")

    # ---- autonomy levels, re-derived with an independent copy of the rule ----
    lv = ex["levels"]
    C.check("levels.requirements_match", {k: tuple(v) for k, v in lv["requirements"].items()} == REQ, "thresholds")
    for i, case in enumerate(lv["cases"]):
        C.check(f"levels.case{i}.rederived", level_of(case["inputs"]) == case["result"]["level"],
                (case["result"]["level"], level_of(case["inputs"])))
    C.check("levels.digests", all(dig(D["level"], strip(c["result"], "digest")) == c["result"]["digest"]
                                  for c in lv["cases"]), "digests")
    C.check("levels.autonomy_is_not_authority", all(c["result"]["autonomy_is_not_authority"] is True
                                                    and c["result"]["authority"] == "NONE" for c in lv["cases"]), "NONE")

    # ---- authorized contract, E8 action, token, decision ----
    az = ex["authorized"]
    con = az["contract"]
    C.check("contract.digest", dig(D["contract"], con) == az["contract_digest"], "digest")
    C.check("contract.sixteen_fields", sorted(con["fields"]) == sorted(ex["contract_fields"])
            and len(ex["contract_fields"]) == 16, len(con["fields"]))
    C.check("contract.binds_live_state", con["fields"]["WHAT_INVALIDATES_IT"] == {k: az["live_bindings"][k]
                                                                                  for k in ex["invalidation_bindings"]},
            "bindings")
    dec = az["decision"]
    C.check("decision.digest", dig(D["gate"], dec) == az["decision_digest"], "digest")
    C.check("decision.authorized_through_e8", dec["decision"] == "AUTHORIZED" and dec["reasons"] == []
            and az["decision_authority"] == "E8" and dec["contract_digest"] == az["contract_digest"], dec["decision"])
    C.check("e8.action_hash", dig(D["e8_action"], az["e8_action"]) == az["e8_action_hash"], "action hash")
    C.check("e8.action_carries_contract", az["e8_action"]["parameters"]["contract_digest"] == az["contract_digest"],
            "contract digest in parameters")
    tok = az["e8_token"]
    C.check("e8.token_signature", sig_ok(tok["issuer"], tok["signature_b64"], D["e8_token"],
                                         strip(tok, "issuer", "signature_b64")), "ed25519")
    C.check("e8.token_binds_action", tok["action_hash"] == az["e8_action_hash"], "action hash")
    C.check("e8.token_binds_world_and_policy", tok["world_state_root"] == con["fields"]["AGAINST_WHAT_WORLD_STATE"]
            and tok["policy_root"] == con["fields"]["UNDER_WHICH_POLICY"], "roots")
    C.check("e8.token_ttl_within_policy", 0 < tok["expires_at"] - tok["issued_at"] <= 30, tok["expires_at"] - tok["issued_at"])
    C.check("authority.capability_in_effective", con["fields"]["WITH_WHAT"]["capability"] in az["effective_authority"],
            "capability")
    C.check("contract.evidence_bound", len(con["fields"]["BASED_ON_WHAT_EVIDENCE"]) >= 1, "evidence")

    # ---- invalidated contract: re-derive which bindings changed ----
    iv = ex["invalidated"]
    C.check("invalidated.contract_digest", dig(D["contract"], iv["contract"]) == iv["contract_digest"], "digest")
    C.check("invalidated.decision_digest", dig(D["gate"], iv["decision"]) == iv["decision_digest"], "digest")
    changed = sorted(f"CONTRACT_INVALIDATED:{k.upper()}_CHANGED" for k in ex["invalidation_bindings"]
                     if iv["bound"].get(k) != iv["live_bindings_after"].get(k))
    C.check("invalidated.rederived_reasons", changed and set(changed) <= set(iv["decision"]["reasons"]), changed)
    C.check("invalidated.denied", iv["decision"]["decision"] == "DENY" and iv["decision_authority"] == "NONE", "DENY")

    # ---- consistently re-signed refusal ----
    rr = ex["reissued_refusal"]
    C.check("reissued.decision_digest", dig(D["gate"], rr["decision"]) == rr["decision_digest"], "digest")
    C.check("reissued.denied_by_verdict", rr["decision"]["decision"] == "DENY" and rr["decision_authority"] == "NONE"
            and "MISSION_TERMINATED" in rr["decision"]["reasons"], rr["decision"]["reasons"])

    # ---- human approval ----
    hu = ex["human"]
    ap = hu["approval"]
    C.check("human.signature", sig_ok(hu["human_pub"], ap["signature_b64"], D["human"], strip(ap, "signature_b64")),
            "ed25519")
    C.check("human.bound_to_contract", ap["contract_digest"] == az["contract_digest"], "contract")
    C.check("human.within_scope", ap["capability"] in hu["scope"] and ap["decision"] == "APPROVE"
            and ap["issued_at"] < ap["expires_at"], ap["capability"])

    # ---- governance root ----
    gv = ex["governance"]
    b4 = gv["before"]
    C.check("governance.root_digest", dig(D["root"], strip(b4, "digest")) == b4["digest"], "digest")
    C.check("governance.subject", gv["subject"] == f"mutation:{b4['digest']}:{h(gv['new_invariants'])}", "subject")
    valid = {pub for pub, sig in gv["signatures"] if pub in b4["keys"] and pub != gv["proposer_pub"]
             and sig_ok(pub, sig, D["root_mutation"], {"subject": gv["subject"]})}
    C.check("governance.quorum_excluding_proposer", len(valid) >= b4["threshold"] >= 2, len(valid))
    C.check("governance.core_invariants_kept", all(i in gv["new_invariants"] for i in gv["core_invariants"]), "core")
    C.check("governance.mutation_applied", gv["mutation_result"] == [] and gv["version_after"] == b4["version"] + 1,
            gv["version_after"])
    C.check("governance.core_removal_refused", any(r.startswith("CORE_INVARIANT_REMOVAL_REFUSED")
                                                   for r in gv["removal_result"]), gv["removal_result"])

    # ---- memory ----
    me = ex["memory"]
    C.check("memory.object_digests", [dig(D["memory"], o) for o in me["objects"]] == me["digests"], "digests")
    prev, chain = "genesis", []
    for d_ in me["digests"]:
        prev = h({"prev": prev, "m": d_})
        chain.append(prev)
    C.check("memory.chain_recomputed", chain == me["chain"], "chain")
    poisoned = sorted(o["memory_id"] for o in me["objects"] if any(m in o["content"].lower() for m in INJECTION))
    C.check("memory.poison_quarantined", poisoned and poisoned == me["quarantined"], poisoned)
    C.check("memory.never_policy_or_authority", {"policy", "authority", "instruction"} <= set(me["forbidden_kinds"])
            and all(o["kind"] not in me["forbidden_kinds"] for o in me["objects"]), "kinds")

    # ---- checkpoint ----
    cp = ex["checkpoint"]
    C.check("checkpoint.digest", dig(D["checkpoint"], cp["body"]) == cp["digest"], "digest")
    C.check("checkpoint.signature", sig_ok(cp["store_pub"], cp["signature"], D["checkpoint"],
                                           {"digest": cp["digest"], "parent": cp["parent"]}), "ed25519")
    C.check("checkpoint.rollback_intersects_now", cp["rollback_now"]["restored_authority"] ==
            sorted(set(cp["body"]["authority"]) & {"read", "route"}) and cp["rollback_now"]["problems"] == [], "∩")
    C.check("checkpoint.substitution_detected", "CHECKPOINT_SUBSTITUTED" in cp["substituted"]["problems"]
            and cp["substituted"]["restored_authority"] == [], cp["substituted"]["problems"])

    # ---- causal chain ----
    ca = ex["causal"]["explain"]
    C.check("causal.digest", dig(D["causal"], strip(ca, "digest")) == ca["digest"], "digest")
    C.check("causal.full_chain_in_order", [c["stage"] for c in ca["chain"]] == ex["causal"]["order"]
            and ca["explained"] is True and ca["missing"] == [], len(ca["chain"]))

    # ---- mission, goals, beliefs, model ----
    ms = ex["mission"]
    C.check("mission.digest", dig(D["mission"], ms["body"]) == ms["digest"], "digest")
    C.check("mission.active_and_bounded", ms["body"]["state"] == "ACTIVE" and set(ms["body"]["mission_authority"])
            <= set(ms["body"]["boundary"]["capability_scope"]), ms["body"]["state"])
    gs = ex["goals"]
    for gid, g in gs.items():
        C.check(f"goal.{gid}.digest", dig(D["goal"], g["body"]) == g["digest"], gid)
    ok_tree = True
    for g in gs.values():
        b = g["body"]
        if b["parent_id"]:
            p = gs[b["parent_id"]]["body"]
            ok_tree &= set(b["authority"]) <= set(p["authority"]) and set(p["constraints"]) <= set(b["constraints"])
        ok_tree &= set(b["authority"]) <= set(ms["body"]["mission_authority"]) and b["metric"] == b["declared_metric"]
    C.check("goals.inheritance", ok_tree, "subgoal ⊆ parent ⊆ mission; constraints inherited")
    for c, bl in ex["beliefs"].items():
        C.check(f"belief.{c}.digest", dig(D["belief"], bl["body"]) == bl["digest"], c)
    fact_rule = all((bl["status"] == "FACT") == (bl["body"]["layer"] == "VERIFIED" and bool(bl["body"]["evidence"])
                                                  and len(bl["body"]["principals"]) >= 2
                                                  and not bl["body"]["contradicts"])
                    for bl in ex["beliefs"].values())
    C.check("beliefs.fact_rule_rederived", fact_rule, "FACT needs VERIFIED + evidence + 2 principals")
    C.check("model.digest", dig(D["model"], ex["model"]["body"]) == ex["model"]["digest"], "digest")

    # ---- invariants ----
    inv = load("INVARIANTS.json")
    C.check("invariants.count", inv["checked"] >= 100 and len(inv["checks"]) == inv["checked"], inv["checked"])
    C.check("invariants.ids", [x["id"] for x in inv["checks"]] == [f"G{i}" for i in range(1, inv["checked"] + 1)], "ids")
    C.check("invariants.all_hold", inv["all_hold"] is True and not inv["failed"]
            and all(x["holds"] is True for x in inv["checks"]), inv["failed"])

    # ---- bench ----
    bm = load("ATTACK_MANIFEST.json")
    at = bm["attacks"]
    C.check("bench.distinct_minimum", bm["distinct_attacks"] >= 150 and bm["distinct_attacks"] ==
            bm["total"] - len(bm["alias_entries"]) and set(bm["alias_entries"]) <= set(at), bm["distinct_attacks"])
    C.check("bench.all_contained", bm["all_contained"] is True and bm["contained"] == bm["total"] == len(at)
            and all(a["contained"] is True and a["result"] == "CONTAINED" for a in at.values()),
            f"{bm['contained']}/{bm['total']}")
    C.check("bench.entry_digests", all(dig(D["adversarial"], strip(a, "digest")) == a["digest"] for a in at.values()),
            "digests")
    C.check("bench.entry_fields", all(all(a.get(k) not in (None, "") for k in ("attack", "expected_invariant", "defense",
                                                                              "test", "result")) for a in at.values()),
            "fields")
    cats = {}
    for a in at.values():
        cats[a["category"]] = cats.get(a["category"], 0) + 1
    C.check("bench.categories_consistent", cats == bm["categories"], "categories")
    C.check("bench.required_categories", all(c in cats for c in REQUIRED_CATEGORIES), sorted(set(REQUIRED_CATEGORIES) - set(cats)))
    C.check("bench.invariants_exist", all(a["expected_invariant"] in {x["id"] for x in inv["checks"]} for a in at.values()),
            "invariant refs")
    C.check("bench.honest", bm["real_world_attack_validation"] == "NOT_PERFORMED" and bm["authority"] == "NONE", "honest")

    # ---- end-to-end ----
    e2e = load("END_TO_END_RESULTS.json")
    C.check("e2e.all_steps_ok", e2e["all_steps_ok"] is True and all(s["ok"] for s in e2e["steps"]), "steps")
    C.check("e2e.required_stages", [s for s in REQUIRED_E2E if s not in {x["step"] for x in e2e["steps"]}] == [], "stages")
    C.check("e2e.stage_attacks_caught", e2e["all_mutations_caught"] is True and len(e2e["mutations"]) >= 15
            and all(m["caught"] for m in e2e["mutations"]), len(e2e["mutations"]))
    C.check("e2e.execution_simulated", e2e["execution"] == "SIMULATED", e2e["execution"])

    # ---- mutation self-test ----
    mu = load("MUTATION_RESULTS.json")
    base = mu["rows"][0]
    C.check("mutation.baseline_clean", base["mutant"] == "none" and base["bench_contained"] == base["bench_total"],
            base)
    C.check("mutation.every_mutant_caught", mu["all_mutants_caught"] is True and len(mu["rows"]) >= 4 and all(
        r["bench_contained"] < base["bench_contained"] and r["invariants_holding"] < base["invariants_holding"]
        for r in mu["rows"][1:]), len(mu["rows"]) - 1)

    # ---- tests ----
    te = load("TEST_RESULTS.json")
    C.check("tests.ran_and_passed", te.get("skipped") is not True and te.get("failed") == 0 and te.get("errors") == 0
            and te.get("passed", 0) > 0 and te.get("exit_code") == 0, te.get("summary"))

    # ---- claims, limitations, status ----
    cl = load("CAIN42_EVOLUTION19_CLAIMS.json")["claims"]
    ctext = json.dumps(cl).lower()
    C.check("claims.no_forbidden_words", not any(w in ctext for w in FORBIDDEN_WORDS), "words")
    C.check("claims.states_valid", all(c["state"] in CLAIM_STATES for c in cl), "states")
    by = {c["claim_id"]: c["state"] for c in cl}
    C.check("claims.physical_not_implemented", by.get("C42-E19-PHYSICAL-CONTROL") == "NOT_IMPLEMENTED", "physical")
    C.check("claims.third_party_not_performed", by.get("C42-E19-THIRD-PARTY") == "NOT_PERFORMED", "third party")
    C.check("claims.tested_claims_have_evidence", all(c["evidence"] and all((root / f"{e}.json").exists()
                                                                           or (root / f"{e}.md").exists()
                                                                           or e == "CLEAN_ROOM_VERIFIER"
                                                                           or (root / e).exists()
                                                                           or (root / f"{e.replace('INVARIANTS', 'INVARIANTS')}.json").exists()
                                                                           for e in c["evidence"])
                                                  for c in cl if c["state"] == "TESTED"), "evidence files")
    li = load("LIMITATIONS.json")["limitations"]
    C.check("limitations.classified", len(li) >= 5 and all(x["status"] in ("NOT_IMPLEMENTED", "UNKNOWN", "UNVERIFIED",
                                                                           "NOT_PERFORMED") for x in li), len(li))
    sm = load("CAIN42_E19_EVIDENCE_BUNDLE.json")
    C.check("summary.counts_match", sm["invariants"]["checked"] == inv["checked"] and sm["attacks"]["total"] ==
            bm["total"] and sm["attacks"]["distinct"] == bm["distinct_attacks"] and sm["end_to_end"]["steps"] ==
            len(e2e["steps"]), "counts")
    gates = sm["completion_gates"]
    C.check("summary.status_gated", (sm["status"] == "COMPLETE") == all(v is True for v in gates.values()), sm["status"])
    C.check("summary.honest_states", sm["states"]["physical_control"] == "NOT_IMPLEMENTED" and
            sm["states"]["third_party_review"] == "NOT_PERFORMED" and sm["states"]["hosted_service"] == "NOT_IMPLEMENTED",
            "states")

    # ---- performance, provenance ----
    pf = load("PERFORMANCE.json")
    C.check("performance.conditions_honest", pf["conditions"]["concurrency"] == 1 and "not production-scale" in pf["note"],
            pf["note"])
    C.check("performance.percentiles", pf["results"] and all(all(k in v for k in ("p50_us", "p95_us", "p99_us", "max_us"))
                                                              for v in pf["results"].values()), len(pf["results"]))
    pv = load("PROVENANCE.json")
    C.check("provenance.commit", bool(re.fullmatch(r"[0-9a-f]{40}", pv["commit"])), pv["commit"][:12])
    C.check("provenance.module_digests", all(re.fullmatch(r"[0-9a-f]{64}", v) for v in pv["modules"].values()), "modules")

    # ---- clean room ----
    src = (root / "verify_e19.py.txt").read_text()
    mods = re.findall(r"^\s*(?:from|import)\s+([A-Za-z_][\w.]*)", src, re.M)
    C.check("clean_room.imports_no_cain", mods and not any(m.split(".")[0] in ("cain", "cain45", "platform_gateway")
                                                           for m in mods), sorted(set(mods)))
    C.check("clean_room.sha_matches", load("CLEAN_ROOM_VERIFIER.json")["sha256"] ==
            hashlib.sha256((root / "verify_e19.py.txt").read_bytes()).hexdigest(), "sha")

    out = {"schema": "cain42.e19.verifier.v1", "result": "INTACT" if not C.problems else "FAILED",
           "checks": len(C.detail), "passed": len(C.detail) - len(C.problems), "problems": C.problems,
           "detail": C.detail}
    print(json.dumps(out))
    return 0 if not C.problems else 1


if __name__ == "__main__":
    try:
        raise SystemExit(main(Path(sys.argv[1])))
    except (KeyError, TypeError, ValueError, json.JSONDecodeError, FileNotFoundError) as e:
        print(json.dumps({"schema": "cain42.e19.verifier.v1", "result": "FAILED", "checks": 0, "passed": 0,
                          "problems": [f"malformed bundle: {type(e).__name__}: {e}"]}))
        raise SystemExit(1)
