#!/usr/bin/env python3 """CAIN-42 E30 clean-room verifier. Imports NOTHING from CAIN. python3 verify_e30.py [bundle-dir] Re-derives from the published artifacts: every universal action receipt (chain, signature, and that its UMA digest is the digest of the published action object; that ALLOW receipts name an E28 receipt that reached the E8 kernel log); the E28 governance-receipt chain; the autonomy budget ledger (chain, signatures, that every CONSUME names an E28 receipt); the autonomy state history (every transition allowed by the published transition table; no REVOKED -> AUTHORIZED, no TRUSTED); the 30-step end-to-end proof; bench, invariant, mutation, coverage, immune and scale results; registers; claims and bundle integrity. Prints one JSON object; exit 0 only when every check holds. """ from __future__ import annotations import base64 import hashlib import json import sys from pathlib import Path from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric import ed25519 D_UMA = "CAIN42/E30-UNIVERSAL-MACHINE-ACTION/v1" D_UAR = "CAIN42/E30-UNIVERSAL-ACTION-RECEIPT/v1" D_BUDGET = "CAIN42/E30-AUTONOMY-BUDGET-ENTRY/v1" D_RECEIPT = "CAIN42/E28-GOVERNANCE-RECEIPT/v1" D_MASTER = "CAIN42/E30-MASTER/v1" UMA_FIELDS = ["principal", "identity", "intent", "context", "observation", "memory", "model", "runtime", "capability", "delegation", "policy", "authority", "risk", "consequence", "transaction", "environment", "action", "execution", "outcome", "evidence"] E2E_STEPS = ["AGENT", "IDENTITY", "PERCEPTION", "MEMORY", "REASONING", "PLANNING", "CAPABILITY", "DELEGATION", "NEGOTIATION", "CONTRACT", "AUTHORITY", "RISK", "CONSEQUENCE", "AUTHORIZATION", "TRANSACTION", "E8", "EXECUTION", "ENVIRONMENT", "OBSERVATION", "EVIDENCE", "LEARNING", "SELF_TEST", "SELF_IMPROVEMENT_PROPOSAL", "GOVERNANCE_REVIEW", "CANARY", "PROMOTION", "REJECTION", "CONTINUOUS_REAUTHORIZATION"] TARGETS = {"protocol_integration": 100, "self_improvement": 100, "identity_delegation": 100, "economic": 100, "memory_perception": 100, "supply_chain": 100, "multi_agent": 100, "world_action": 100} COVERAGE = ["ENFORCED", "MONITORED", "OBSERVED", "PARTIALLY_ENFORCED", "BYPASSABLE", "UNCONTROLLED", "UNKNOWN"] def canonical(o) -> bytes: return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() def h(o) -> str: return hashlib.sha256(canonical(o)).hexdigest() def digest(domain: str, body) -> str: return h({"domain": domain, "body": body}) def verify(pub: str, sig: str, domain: str, body) -> bool: try: ed25519.Ed25519PublicKey.from_public_bytes(base64.b64decode(pub)).verify( base64.b64decode(sig), digest(domain, body).encode()) return True except (InvalidSignature, ValueError, TypeError): return False class Checker: def __init__(self): self.checks, self.passed, self.problems = 0, 0, [] def check(self, name, ok, detail=""): self.checks += 1 if ok: self.passed += 1 else: self.problems.append(f"{name}: {detail}"[:300]) def load(d: Path, n: str): return json.loads((d / n).read_text()) def main() -> int: d = Path(sys.argv[1] if len(sys.argv) > 1 else ".") c = Checker() try: art = load(d, "E2E_ARTIFACTS.json") e2e = load(d, "END_TO_END.json") except (OSError, ValueError) as x: print(json.dumps({"result": "ERROR", "checks": 0, "passed": 0, "problems": [str(x)]})) return 1 kev = set(art["kernel_evidence"]) gr = art["governance_receipts"] by = {} prev = "0" * 64 for i, r in enumerate(gr["receipts"]): b = r["body"] c.check(f"e28[{i}].chain", b["seq"] == i and b["prev"] == prev and digest(D_RECEIPT, b) == r["receipt_hash"], "chain") c.check(f"e28[{i}].signature", verify(gr["signer_pub"], r["signature_b64"], D_RECEIPT, b), "sig") prev = r["receipt_hash"] by[r["receipt_hash"]] = r # ---- universal action receipts ua = art["universal_receipts"] prev = "0" * 64 for i, r in enumerate(ua["receipts"]): b = r["body"] c.check(f"uar[{i}].chain", b["seq"] == i and b["prev"] == prev and digest(D_UAR, b) == r["hash"], "chain") c.check(f"uar[{i}].signature", verify(ua["pub"], r["signature_b64"], D_UAR, b), "sig") c.check(f"uar[{i}].uma_fields", sorted(r["uma"]) == sorted(UMA_FIELDS), sorted(r["uma"])) c.check(f"uar[{i}].uma_digest", digest(D_UMA, r["uma"]) == b["uma_digest"], "uma digest") pre = {k: v for k, v in r["uma"].items() if k not in ("execution", "outcome", "evidence")} c.check(f"uar[{i}].authorized_digest", digest(D_UMA, pre) == b["authorized_digest"], "authorized digest") if b["decision"] == "ALLOW": e = by.get(b["e28_receipt"]) c.check(f"uar[{i}].allow_has_e28_receipt", e is not None, b["e28_receipt"][:16]) if e: c.check(f"uar[{i}].allow_reached_e8", any(x in kev for x in e["body"]["evidence_references"]), "no E8") c.check(f"uar[{i}].allow_same_identity", e["body"]["execution_identity"] == b["identity"], "identity") c.check(f"uar[{i}].allow_bound_action", e["body"]["action_digest"] == r["uma"]["transaction"], "action binding") else: c.check(f"uar[{i}].deny_has_reason", bool(b["reasons"]) or bool(b["e28_receipt"]), "no reason") prev = r["hash"] # ---- budget ledger bl = art["budget_ledger"] prev = "0" * 64 for i, e in enumerate(bl["entries"]): b = e["body"] c.check(f"budget[{i}].chain", b["seq"] == i and b["prev"] == prev and digest(D_BUDGET, b) == e["hash"], "chain") c.check(f"budget[{i}].signature", verify(bl["pub"], e["signature_b64"], D_BUDGET, b), "sig") if b["kind"] == "CONSUME" and not b["receipt"].startswith(("evc_", "compute:")): c.check(f"budget[{i}].names_receipt", b["receipt"] in by, b["receipt"][:16]) prev = e["hash"] # ---- state history table = art["state_transitions"] last = {} for i, s in enumerate(art["state_history"]): rule = table.get(s["to"]) c.check(f"state[{i}].known", rule is not None, s["to"]) if rule: c.check(f"state[{i}].allowed_from", s["from"] in rule["from"], f"{s['from']}->{s['to']}") c.check(f"state[{i}].continuity", last.get(s["agent"], s["from"]) == s["from"], "gap") c.check(f"state[{i}].no_trusted", s["to"] != "TRUSTED", "TRUSTED") c.check(f"state[{i}].no_revoked_to_authorized", not (s["from"] == "REVOKED" and s["to"] == "AUTHORIZED"), "revoked->authorized") last[s["agent"]] = s["to"] # ---- e2e got = [s["step"] for s in e2e["steps"]] c.check("e2e.steps", got == E2E_STEPS, got) for s in e2e["steps"]: c.check(f"e2e.{s['step']}", s["ok"] is True, s) rp = art["replay"] c.check("replay.allowed_explained", rp["allowed"]["decision"] == "ALLOW" and rp["allowed"]["why"].startswith("ALLOWED"), rp["allowed"]["why"][:60]) c.check("replay.denied_explained", rp["denied"]["decision"] == "DENY" and rp["denied"]["why"].startswith("DENIED"), rp["denied"]["why"][:60]) tm = art["time_machine"] c.check("time_machine.append_only", tm["source"] == "append-only records", tm["source"]) # ---- bench / invariants / mutation b = load(d, "SECURITY_RESULTS.json") c.check("bench.all_held", b["held"] == b["scenarios"], f"{b['held']}/{b['scenarios']}") c.check("bench.at_least_500", b["scenarios"] >= 500, b["scenarios"]) c.check("bench.ids_distinct", len({r["id"] for r in b["rows"]}) == b["scenarios"], "dups") for cat, t in TARGETS.items(): n = sum(1 for r in b["rows"] if r["category"] == cat) c.check(f"bench.category.{cat}", n >= t, f"{n}<{t}") for r in b["rows"]: c.check(f"bench.row.{r['id']}", r["held"] is True, r["detail"][:80]) inv = load(d, "INVARIANTS.json") c.check("invariants.at_least_150", inv["total"] >= 150, inv["total"]) c.check("invariants.all_hold", inv["passed"] == inv["total"], [r["id"] for r in inv["rows"] if not r["ok"]][:5]) ids = {r["id"] for r in inv["rows"]} c.check("invariants.laws", all(f"E30-L{i}" in ids for i in range(1, 21)), "laws") mut = load(d, "MUTATION_RESULTS.json") c.check("mutation.all_killed", mut["killed"] == mut["mutants"] and not mut["survived"], mut["survived"]) c.check("mutation.at_least_8", mut["mutants"] >= 8, mut["mutants"]) # ---- coverage, immune, scale, registers cov = load(d, "COVERAGE_MAP.json") c.check("coverage.classes", cov["classes"] == COVERAGE, cov["classes"]) for p in cov["paths"]: c.check(f"coverage.{p['path'][:40]}", p["class"] in COVERAGE and bool(p["basis"]), p["class"]) c.check("coverage.uncontrolled_present", any(p["class"] == "UNCONTROLLED" for p in cov["paths"]), "no uncontrolled paths reported") c.check("coverage.monitored_not_enforced", all(p["class"] != "ENFORCED" for p in cov["paths"] if "health" in p["path"]), "monitored as enforced") im = load(d, "IMMUNE_METRICS.json") c.check("immune.detected", im["detected"] is True, im) c.check("immune.recovered_new_identity", im["recovered_as_new_identity"] is True, im) for k in ("time_to_detect_ms", "time_to_contain_ms", "time_to_revoke_ms", "time_to_recover_ms"): c.check(f"immune.{k}", isinstance(im[k], (int, float)) and im[k] >= 0, im.get(k)) sc = load(d, "SCALE_RESULTS.json") c.check("scale.synthetic_label", "SYNTHETIC" in sc["classification"], "label") sizes = [r["agents"] for r in sc["rows"]] for n in (10, 100, 1000, 10000, 100000): c.check(f"scale.size_{n}", n in sizes, sizes) for r in sc["rows"]: c.check(f"scale.{r['agents']}.no_failures", r["failures"] == 0, r["failures"]) reg = load(d, "REGISTERS.json") c.check("registers.research_not_running", "NOT RUNNING" in reg["research_engine"]["status"], "status") c.check("registers.lab_isolated", all(b_["isolated_from_production"] for b_ in reg["frontier_lab"]["branches"]), "isolation") c.check("registers.lab_ideas_only", all(b_["status"] == "IDEA" for b_ in reg["frontier_lab"]["branches"]), "status") ts = load(d, "TYPESCRIPT_SDK_RESULTS.json") c.check("typescript_sdk.intact", ts.get("result") == "INTACT", ts) c.check("typescript_sdk.detects_tamper", ts.get("tamper_result") == "BROKEN", ts) # ---- claims + integrity cl = load(d, "E30_PUBLIC_CLAIMS.json") for k in cl["claims"]: c.check(f"claim.{k['id']}", all((d / f).exists() for f in k["evidence"]), k["evidence"]) lim = load(d, "KNOWN_LIMITATIONS.json") c.check("limitations.published", len(lim["limitations"]) >= 8, len(lim["limitations"])) sums = {} for line in (d / "SHA256SUMS").read_text().splitlines(): hx, name = line.split(" ", 1) sums[name] = hx for name, hx in sorted(sums.items()): c.check(f"sha256.{name}", hashlib.sha256((d / name).read_bytes()).hexdigest() == hx, "hash") sig = load(d, "SIGNATURE.json") c.check("signature.files", sig["files"] == sums, "files") c.check("signature.master_digest", sig["master"]["hashes_digest"] == h(sig["files"]), "digest") c.check("signature.valid", verify(sig["signer_public_key_b64"], sig["signature_b64"], D_MASTER, sig["master"]), "sig") out = {"verifier": "verify_e30.py", "imports_cain": False, "checks": c.checks, "passed": c.passed, "result": "INTACT" if c.passed == c.checks else "BROKEN", "problems": c.problems[:50]} print(json.dumps(out)) return 0 if out["result"] == "INTACT" else 1 if __name__ == "__main__": sys.exit(main())