#!/usr/bin/env python3 """Clean-room verifier for the CAIN-42 E39 (Governed Agent Factory) evidence bundle. Imports nothing from CAIN; only `cryptography` and the standard library. The factory does not certify its own output: from the published missions, blueprints, organizations, workflows, evaluations, deployment manifest, action proofs, factory proof and provenance this script independently re-derives * each mission envelope = requested INTERSECT sponsor (INTERSECT limits), and that it never exceeds the sponsor; * each blueprint's authority = (role need) INTERSECT (envelope) -- the minimum-authority rule -- and that its role is one the mission's phases call for; * each organization is acyclic and every child's authority is a subset of its parent's; * every consequential task is gated by govern.authorize and assigned to an agent whose authority covers it; * every evaluation is signed by the registered evaluator, is not a self-evaluation, and PASSED only with zero false allows and every gate true; * every deployed agent went APPROVED -> PROVISIONED -> ADMITTED -> ACTIVE in order; * every executed action proof is signed and bound to its real E8 commit; * the factory proof is not self-certified and its status is the weakest component; the provenance root recomputes; and it must reject every object in MALICIOUS.json. Malformed material fails closed. python3 verify_e39.py """ 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 D39 = lambda k: "CAIN42/E39-" + k + "/v1" # noqa: E731 D38 = lambda k: "CAIN42/E38-" + k + "/v1" # noqa: E731 UNKNOWN = "UNKNOWN" COMPOSE_ORDER = ("ENFORCED", "COMPLETE", "PARTIAL", "OBSERVED_ONLY", "UNVERIFIED", "INCOMPLETE", "SIMULATED", "STALE", "CONFLICTED", "REVOKED", "INVALID", "UNKNOWN") class Bad(Exception): pass def _chk(o): if isinstance(o, bool) or o is None or isinstance(o, int): return if isinstance(o, float): raise Bad("float") if isinstance(o, str): if not o.isascii(): raise Bad("ascii") return if isinstance(o, list): for v in o: _chk(v) return if isinstance(o, dict): for k, v in o.items(): if not isinstance(k, str): raise Bad("key") _chk(v) return raise Bad("type") def cj(o) -> bytes: _chk(o) return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=True).encode() def hh(o) -> str: return hashlib.sha256(cj(o)).hexdigest() def digest(domain, body) -> str: return hh({"domain": domain, "body": body}) def sig_ok(pub, sig, domain, 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, Bad): return False def obj_ok(domain, obj, pub) -> bool: try: return digest(domain, obj["body"]) == obj["hash"] and obj.get("pub") == pub and \ sig_ok(pub, obj["signature_b64"], domain, obj["body"]) except (KeyError, TypeError, Bad): return False def subset(child, parent) -> bool: return all(c in parent and all(any(x.startswith(q) for q in parent[c]) for x in v) for c, v in child.items()) def intersect(a, b): out = {} for c in set(a) & set(b): keep = set() for p in a[c]: for q in b[c]: if p.startswith(q): keep.add(p) elif q.startswith(p): keep.add(q) if keep: out[c] = sorted(keep) return out def norm(a): return {k: sorted(v) for k, v in a.items()} class Checks: 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}: {str(detail)[:120]}") def load(d, rel): return json.loads((d / rel).read_text()) def verify_mission(c, tag, m, mc, pub): spec = m["spec"] b = spec["body"] roles, phase_roles, always = mc["roles"], mc["phase_roles"], set(mc["always_roles"]) c.check(f"{tag}.spec.sig", obj_ok(D39("MISSION-SPEC"), spec, pub), "sig") c.check(f"{tag}.spec.no_authority", b["grants_authority"] is False and b["execution_authority"] is None, "authority") env = b["authority_envelope"] want = intersect(m["input"].get("requested_authority", {}), m["sponsor"]) if m["input"].get("authority_limits"): want = intersect(want, m["input"]["authority_limits"]) c.check(f"{tag}.envelope.recomputed", norm(env) == norm(want), (env, want)) c.check(f"{tag}.envelope.within_sponsor", subset(env, m["sponsor"]), "exceeds sponsor") allowed = always | {r for p in b["phases"] for r in phase_roles.get(p, [])} bps = {} for bp in m["blueprints"]: bb = bp["body"] r = bb["role"] bps[r] = bb c.check(f"{tag}.bp.{r}.sig", obj_ok(D39("BLUEPRINT"), bp, pub), "sig") c.check(f"{tag}.bp.{r}.role_needed", r in allowed, r) c.check(f"{tag}.bp.{r}.minimum_authority", norm(bb["authority"]) == norm(intersect(roles[r]["caps"], env)), (bb["authority"], roles[r]["caps"])) c.check(f"{tag}.bp.{r}.within_envelope", subset(bb["authority"], env), "exceeds envelope") c.check(f"{tag}.bp.{r}.no_authority", bb["grants_authority"] is False, "authority") org = m["organization"] ob = org["body"] c.check(f"{tag}.org.sig", obj_ok(D39("ORGANIZATION"), org, pub), "sig") parent_of = ob["parent_of"] for r, p in sorted(parent_of.items()): seen, cur = set(), r while cur is not None: if cur in seen: break seen.add(cur) cur = parent_of.get(cur) c.check(f"{tag}.org.{r}.acyclic", cur is None, "cycle") if p is not None: pa = env if p == "Planner" else bps.get(p, {}).get("authority", {}) c.check(f"{tag}.org.{r}.child_within_parent", r in bps and subset(bps[r]["authority"], pa), (r, p)) c.check(f"{tag}.org.no_widening", all(rel == "DELEGATES" for _a, rel, _b in ob["graphs"]["authority"]) and not ob["problems"], ob["problems"]) wf = m["workflow"] wb = wf["body"] c.check(f"{tag}.wf.sig", obj_ok(D39("WORKFLOW"), wf, pub), "sig") deps = {tuple(x) for x in wb["dependencies"]} for t in wb["consequential"]: c.check(f"{tag}.wf.{t}.gated", ("govern.authorize", t) in deps, t) for t, r in sorted(wb["assignment"].items()): need = mc["task_needs"][t][1] c.check(f"{tag}.wf.{t}.covered", r in bps and subset(need, bps[r]["authority"]), (t, r)) return bps def main() -> int: d = Path(sys.argv[1] if len(sys.argv) > 1 else ".") c = Checks() mc = load(d, "E39_MISSION_COMPILER.json") wm = mc["world_mission"] bps = verify_mission(c, "world", wm, mc, mc["pubs"]["factory"]) for i, m in enumerate(mc["synthetic_missions"]): verify_mission(c, f"syn{i:02d}", m, mc, mc["pubs"]["synthetic"]) c.check("missions.count", len(mc["synthetic_missions"]) == 31, len(mc["synthetic_missions"])) ev = load(d, "E39_FACTORY_PROOFS/EVALUATIONS.json") epub = ev["evaluator_pub"] for role, e in sorted(ev["evaluations"].items()): b = e["body"] c.check(f"eval.{role}.sig", obj_ok(D39("EVALUATION"), e, epub), "sig") c.check(f"eval.{role}.independent", b["evaluator"] != b["agent"], "self-evaluation") c.check(f"eval.{role}.pass_rule", b["passed"] == (b["metrics"]["false_allows"] == 0 and all(b["gates"].values())), b["gates"]) c.check(f"eval.{role}.not_authorization", b["authorizes"] is False and b["grants_authority"] is False, "auth") for role, rt in sorted(ev["red_team"].items()): c.check(f"redteam.{role}", rt["landed"] == [] and rt["held"] == rt["attacks"], rt["landed"]) dep = load(d, "E39_FACTORY_PROOFS/DEPLOYMENT_MANIFEST.json") bp_hashes = {bp["hash"] for bp in wm["blueprints"]} order = ["APPROVED", "PROVISIONED", "ADMITTED", "ACTIVE"] for name, a in sorted(dep["agents"].items()): c.check(f"deploy.{name}.blueprint", a["blueprint"] in bp_hashes, "unknown blueprint") seq = [h["to"] for h in dep["lifecycle"][name]] idx = [seq.index(s) if s in seq else -1 for s in order] c.check(f"deploy.{name}.gated_order", all(i >= 0 for i in idx) and idx == sorted(idx) and seq[0] == "PROPOSED", seq) c.check(f"deploy.{name}.no_skip", all(seq[i] != "PROPOSED" or seq[i + 1] == "DESIGNED" for i in range(len(seq) - 1)), seq) ap = load(d, "E39_AGENT_PROOFS/ACTION_PROOFS.json") ipub = ap["issuer_pub"] for pid, p in sorted(ap["action_proofs"].items()): b = p["body"] c.check(f"proof.{pid}.sig", obj_ok(D38("ACTION-PROOF"), p, ipub), "sig") rec = ap["receipts"].get(b["execution_receipt"]) c.check(f"proof.{pid}.e8_bound", rec is not None and rec["body"]["e8_commit"] == b["e8_commit"] and b["e8_commit"] not in ("NO_E8_COMMIT", UNKNOWN), "E8") for k, lid in sorted(b["layer_proofs"].items()): lp = ap["layers"].get(lid) c.check(f"proof.{pid}.layer.{k}", lp is not None and obj_ok(D38("LAYER-PROOF"), lp, ipub) and lp["body"]["kind"] == k, k) for e in ap["executed"]: c.check(f"executed.{e['task']}", e["executed"] and e["e8_commit"] not in ("NO_E8_COMMIT", UNKNOWN), e) fp = load(d, "E39_FACTORY_PROOFS/FACTORY_PROOF.json") p = fp["proof"] c.check("factory_proof.sig", obj_ok(D39("FACTORY-PROOF"), p, fp["factory_pub"]), "sig") c.check("factory_proof.not_self_certified", p["body"]["self_certified"] is False, "self") comp = fp["composite"] c.check("factory_proof.composite_weakest", comp["body"]["status"] == max(comp["body"]["component_states"], key=COMPOSE_ORDER.index), "weakest") c.check("factory_proof.status_matches", p["body"]["status"] == comp["body"]["status"], "status") pv = load(d, "E39_PROVENANCE.json") c.check("provenance.root", pv["root_digest"] == hh({"n": pv["nodes"], "e": sorted(pv["edges"])}), "root") c.check("provenance.parents_exist", all(a in pv["nodes"] and b in pv["nodes"] for a, b in pv["edges"]), "dangling") bom = load(d, "E39_SUPPLY_CHAIN/BOM.json") c.check("bom.sig", obj_ok(D39("BOM"), bom, bom["pub"]), "sig") c.check("bom.deployable_rule", bom["body"]["deployable"] == (not bom["body"]["blocking"]), "rule") cf = load(d, "E39_CONFORMANCE/CONFORMANCE.json") c.check("conformance.real", cf["real_passed"] == cf["total"], cf["real_passed"]) c.check("conformance.defects", cf["defects_detected_exactly"] is True, "defects") ch = load(d, "E39_CHAOS.json") c.check("chaos.bounded", ch["chaos"]["failed"] == [] and ch["chaos"]["count"] == 15, ch["chaos"]["failed"]) c.check("twin.simulated", ch["twin"]["real_world_validation"] is False, "twin") iv = load(d, "E39_INVARIANTS.json") c.check("invariants", iv["total"] >= 1000 and iv["held"] == iv["total"], (iv["held"], iv["total"])) at = load(d, "E39_ATTACKS.json") c.check("attacks", at["total"] >= 3000 and at["held"] == at["total"], (at["held"], at["total"])) cl = load(d, "E39_CLAIMS.json") names = {str(x.relative_to(d)) for x in d.rglob("*") if x.is_file()} for x in cl["claims"]: c.check(f"claim.{x['id']}", all(e in names for e in x["evidence"]), x["evidence"]) blob = json.dumps(cl).lower() for w in ("creates safe ai", "agi", "guarantees alignment", "controls every", "eliminates rogue", "universal autonomy", "certified by"): c.check(f"claims.no:{w}", w not in blob, w) for mo in load(d, "MALICIOUS.json")["objects"]: c.check(f"malicious.{mo['class']}", rejected(mo, mc, epub, fp["factory_pub"], bps), mo["mutation"]) 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") sg = load(d, "E39_SIGNATURES.json") c.check("signature.files", sg["files"] == sums, "files") c.check("signature.digest", sg["master"]["hashes_digest"] == hh(sg["files"]), "digest") c.check("signature.valid", sig_ok(sg["signer_public_key_b64"], sg["signature_b64"], D39("MASTER"), sg["master"]), "sig") out = {"verifier": "verify_e39.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 def rejected(mo, mc, epub, fpub, bps) -> bool: k, o = mo["class"], mo["object"] pub = mc["pubs"]["factory"] try: if k == "blueprint_authority": env = mc["world_mission"]["spec"]["body"]["authority_envelope"] return not obj_ok(D39("BLUEPRINT"), o, pub) or not subset(o["body"]["authority"], env) if k == "self_evaluation": return o["body"]["evaluator"] == o["body"]["agent"] or not obj_ok(D39("EVALUATION"), o, epub) if k == "failed_as_passed": return not obj_ok(D39("EVALUATION"), o, epub) or (o["body"]["passed"] and o["body"]["metrics"]["false_allows"] > 0) if k == "circular_org": return not obj_ok(D39("ORGANIZATION"), o, pub) if k == "envelope_widened": return not obj_ok(D39("MISSION-SPEC"), o, pub) or not subset(o["body"]["authority_envelope"], mc["world_mission"]["sponsor"]) if k == "factory_self_certified": return o["body"]["self_certified"] is True or not obj_ok(D39("FACTORY-PROOF"), o, fpub) except (KeyError, TypeError, Bad): return True return True if __name__ == "__main__": sys.exit(main())