#!/usr/bin/env python3
"""E291 standalone verifier — recomputes everything from 384 rows; imports no CAIN code."""
import hashlib, json, math, sys
from pathlib import Path
S = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
ARMS = ("single_honest", "q3_rho0", "q3_rho50", "q3_rho100"); POLS = ("active", "random")
SALTS = ("primary", "replication"); W = 24
EX = {"E291_MANIFEST.json","MANIFEST.json","E291_SIGNED_BODY.json","MERKLE_ROOT.txt","PUBLICATION.json","E291_OMEGA_SEAL.json","E291_VERIFICATION_RESULTS.json","E291_TAMPER_RESULTS.json"}
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).hexdigest()
def merkle(ps):
    lv = sorted(sha(p.read_bytes()) for p in ps)
    if not lv: return sha(b"")
    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]
def summ(rows, sn):
    out = {}
    for a in ARMS:
        for p in POLS:
            rs = [r for r in rows if r["salt"] == sn and r["arm"] == a and r["policy"] == p]
            lab = sum(r["labels"] for r in rs)
            out[f"{a}|{p}"] = {"n": len(rs), "claimed": sum(r["claimed"] for r in rs), "claim_correct": sum(r["claim_correct"] for r in rs),
                "accepted_correct": sum(1 for r in rs if r["claimed"] and r["claim_correct"] and r["accepted_protocol"]),
                "accepted_false_protocol": sum(r["accepted_false_protocol"] for r in rs),
                "accepted_false_indep": sum(r["accepted_false_indep"] for r in rs),
                "mean_labels_all": sum((r["ident_labels"] or 101) for r in rs) / len(rs),
                "mean_queries": sum(r["queries"] for r in rs) / len(rs),
                "anchor_per_label": sum(r["anchor_queries"] for r in rs) / max(1, lab),
                "ties": sum(r["ties"] for r in rs), "audit_ties": sum(r["audit_ties"] for r in rs),
                "label_errors": sum(r["label_errors"] for r in rs)}
    return out
def main(b):
    ck = []
    def c(n, ok, d=None): ck.append({"check": n, "ok": bool(ok), "detail": d})
    pre = json.loads((b/"E291_PREREGISTRATION.json").read_text()); frz = json.loads((b/"E291_PREREGISTRATION_FREEZE.json").read_text())
    sal = json.loads((b/"E291_SALT_REVEALED.json").read_text()); rep = json.loads((b/"E291_RUN_REPORT.json").read_text())
    rows = [json.loads(x) for x in (b/"E291_ROWS.jsonl").read_text().splitlines() if x.strip()]
    c("prereg_matches_freeze", sha((b/"E291_PREREGISTRATION.json").read_bytes()) == frz["preregistration_sha256"])
    c("salt_commitment", all(sha(sal["salts"][k]) == pre["salt_commitment_sha256"][k] for k in SALTS))
    c("rows_384", len(rows) == 384, len(rows))
    c("cells_24", all(sum(1 for r in rows if r["salt"] == s and r["arm"] == a and r["policy"] == p) == W for s in SALTS for a in ARMS for p in POLS))
    ok = True
    for r in rows:
        corr = r["claimed_mask"] is not None and r["claimed_mask"] == r["true_mask"]
        ok &= corr == r["claim_correct"]
        ok &= r["claim_wrong"] == (r["claimed"] and not corr)
        ok &= r["accepted_false_protocol"] == (r["claimed"] and not corr and bool(r["accepted_protocol"]))
        if not r["claimed"]: ok &= r["accepted_protocol"] is None
    c("row_fields", ok)
    c("summary", {s: summ(rows, s) for s in SALTS} == rep["summary"])
    acc = lambda cell, s="primary": rep["summary"][s][cell]["accepted_correct"]; fp = lambda cell, s="primary": rep["summary"][s][cell]["accepted_false_protocol"]
    h1 = acc("single_honest|active") >= 20 and fp("single_honest|active") == 0
    h2 = acc("q3_rho0|active") >= 20 and fp("q3_rho0|active") == 0
    h3 = fp("q3_rho50|active") >= 1 or acc("q3_rho50|active") <= acc("q3_rho0|active") - 3
    h4 = acc("q3_rho100|active") <= 2 and fp("q3_rho100|active") >= 1
    h5 = all(fp(x) == 0 for x in ("single_honest|active","q3_rho0|active")) and all(fp(x, "replication") == 0 for x in ("single_honest|active","q3_rho0|active"))
    h6 = acc("q3_rho0|active","replication") >= 20 and fp("q3_rho0|active","replication") == 0 and (acc("q3_rho100|active","replication") <= 2 or fp("q3_rho100|active","replication") >= 1)
    hs = {"H1_single_honest":h1,"H2_independent_quorum":h2,"H3_half_correlation_leaks":h3,"H4_full_correlation_collapses":h4,"H5_independent_arms_are_safe":h5,"H6_replication":h6}
    c("hypotheses", all((rep["hypotheses"][k]["verdict"] == "SUPPORTED") == v for k, v in hs.items()))
    verdict = "ANCHOR_INDEPENDENCE_IS_LOAD_BEARING_SUPPORTED" if all(hs.values()) else "PARTIAL" if (h2 and h5) else "NOT_SUPPORTED"
    c("verdict", rep["verdict"] == verdict, verdict)
    c("false_match", rep["false_accepts"] == {"protocol": sum(r["accepted_false_protocol"] for r in rows), "independent": sum(r["accepted_false_indep"] for r in rows)})
    c("honest_labels_never_false", all(r["label_errors"] == 0 for r in rows if r["arm"] == "single_honest") and all(r["label_errors"] == 0 for r in rows if r["arm"] == "q3_rho0"))
    c("status", rep["status"] == S and pre["status"] == S)
    mp = b/"E291_MANIFEST.json"
    if mp.exists():
        m = json.loads(mp.read_text()); signed = (b/"E291_SIGNED_BODY.json").read_bytes()
        c("signed_body", canon({k:v for k,v in m.items() if k != "signature"}) == signed)
        fs = sorted(x for x in b.rglob("*") if x.is_file() and x.name not in EX and "__pycache__" not in x.parts)
        c("manifest_hashes", m["files"] == {str(x.relative_to(b)): sha(x.read_bytes()) for x in fs})
        c("merkle", merkle(fs) == m["merkle_root"] and (b/"MERKLE_ROOT.txt").read_text().strip() == m["merkle_root"])
        c("headline", m["headline"]["verdict"] == rep["verdict"] and m["headline"]["rho0"] == acc("q3_rho0|active"))
        try:
            from cryptography.hazmat.primitives import serialization
            pub = bytes.fromhex(m["pubkey_ed25519"])
            pk = serialization.load_der_public_key(b"\x30\x2a\x30\x05\x06\x03\x2b\x65\x70\x03\x21\x00" + pub)
            pk.verify(bytes.fromhex(m["signature"]), signed); c("signature", True)
        except Exception as e: c("signature", False, str(e)[:150])
    p = sum(1 for x in ck if x["ok"])
    print(json.dumps({"schema":"cain42.e291.verification.v1","evolution":"E291","status":S,"checks":len(ck),"passed":p,
        "failed":[x for x in ck if not x["ok"]],"verdict":rep["verdict"],"false_accepts":rep["false_accepts"],
        "headline":{"rho0":acc("q3_rho0|active"),"rho50":acc("q3_rho50|active"),"rho100":acc("q3_rho100|active"),
                    "rho0_fp":fp("q3_rho0|active"),"rho50_fp":fp("q3_rho50|active"),"rho100_fp":fp("q3_rho100|active"),
                    "rho0_rep":acc("q3_rho0|active","replication"),"rho100_rep":acc("q3_rho100|active","replication")}}))
    return 0 if p == len(ck) else 1
if __name__ == "__main__": sys.exit(main(Path(sys.argv[1] if len(sys.argv) > 1 else Path(__file__).resolve().parent)))
