#!/usr/bin/env python3
"""RBC standalone auditor. Imports no CAIN code."""
import hashlib, json, random, statistics, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
FAMILIES, DEPTHS, PER_CELL = 4, 3, 5
CANDIDATES, TESTABLE, HELDOUT, CALIB, PROMOTION, BUDGET = 60, 48, 12, 12, 36, 240
K_CELL, K_CAND = 8.0, 4.0
BASE = [0.60, 0.48, 0.36, 0.24]; DEPTH_BONUS = [0.04, 0.00, -0.04]; JITTER = 0.03
INFLATE, CORRUPT = 0.90, 6
ARMS = ["standard", "inflated", "trimmed", "oracle"]
AGENTS = ["atlas", "borealis", "cetus", "draco", "mallory"]
WORLDS = 32; TENANT, SEED = "cain42-rbc", "rbc"
STATUS = "AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
def sha(b): return hashlib.sha256(b).hexdigest()
def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()
def mean(xs): return statistics.mean(xs) if xs else 0.0
def draws(salt, world, cand, run_no):
    h = sha(canon([salt, world, cand, run_no])); return int(h[:16], 16) / float(16 ** 16)
def world(salt, w):
    rng = random.Random(int(sha(canon([salt, w, "world"]))[:16], 16)); cands = []; i = 0
    for f in range(FAMILIES):
        for d in range(DEPTHS):
            for k in range(PER_CELL):
                p = min(0.88, max(0.12, BASE[f] + DEPTH_BONUS[d] + rng.uniform(-JITTER, JITTER)))
                role = "test" if k == 0 else ("calib" if k == 1 else "promote")
                cands.append({"i": i, "family": f, "depth": d + 2, "p": p, "role": role}); i += 1
    return cands
def cell_of(c): return c["family"] * DEPTHS + c["depth"] - 2
def fit(cands, obs, only_role=None):
    by = {c["i"]: c for c in cands}; tn = ts = 0; cells = {}
    for c in cands: cells.setdefault(cell_of(c), [0, 0])
    for i, v in obs.items():
        c = by[i]
        if only_role and c["role"] != only_role: continue
        tn += len(v); ts += sum(v); cells[cell_of(c)][0] += sum(v); cells[cell_of(c)][1] += len(v)
    glob = (ts / tn) if tn else 0.5
    ch = {k: ((s + K_CELL * glob) / (n + K_CELL) if (n + K_CELL) else glob) for k, (s, n) in cells.items()}
    phat, ns = {}, {}
    for c in cands:
        v = obs.get(c["i"], []) if (only_role is None or c["role"] == only_role) else []
        n = len(v); h = ch[cell_of(c)]
        phat[c["i"]] = (sum(v) + K_CAND * h) / (n + K_CAND) if (n + K_CAND) else h; ns[c["i"]] = n
    return phat, ns
def q_at(res, coverage):
    n = len(res); k = min(max(int(-(-((n + 1) * coverage) // 1)), 1), n); return res[k - 1]
def campaign(cands, salt, w, arm):
    testable = [c for c in cands if c["role"] != "test"]; promotion = [c for c in cands if c["role"] == "promote"]
    obs = {}; runs = 0
    def run(c):
        nonlocal runs
        n = len(obs.setdefault(c["i"], [])); obs[c["i"]].append(1 if draws(salt, w, c["i"], n) < c["p"] else 0); runs += 1
    for _ in range(2):
        for c in testable: run(c)
    for _ in range(4):
        for c in promotion: run(c)
    phat, ns = fit(cands, obs, only_role="promote")
    res = sorted(abs(c["p"] - phat[c["i"]]) for c in cands if c["role"] == "calib")
    inflated = sorted(res + [INFLATE] * CORRUPT)
    test = [c for c in cands if c["role"] == "test"]; errs = [abs(phat[c["i"]] - c["p"]) for c in test]
    oq = sorted(errs)[min(len(errs) - 1, int(-(-((len(errs) + 1) * 0.9) // 1)) - 1)]
    q = q_at(res, 0.90) if arm == "standard" else q_at(inflated, 0.90) if arm == "inflated" else max(inflated[:len(inflated) - CORRUPT]) if arm == "trimmed" else oq
    q = min(q, 2.0); cov = sum(1 for e in errs if e <= q) / len(errs)
    return {"runs": runs, "q": q, "coverage": cov, "width": 2 * q, "q50": q_at(res, 0.50), "q90": q_at(res, 0.90)}
def summarize(rows):
    return {"coverage": mean([r["coverage"] for r in rows]), "q_mean": mean([r["q"] for r in rows]),
            "width_mean": mean([r["width"] for r in rows]), "width_max": max(r["width"] for r in rows),
            "q50_mean": mean([r["q50"] for r in rows]), "q90_mean": mean([r["q90"] for r in rows]),
            "runs_mean": mean([r["runs"] for r in rows]), "runs_max": max(r["runs"] for r in rows)}
def keypair(a): return Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())
def pubhex(a): return keypair(a).public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw).hex()
def verify_entries(entries, pubs):
    prev = ""; bad = []
    for e in entries:
        payload = {k: e[k] for k in ("seq", "tenant", "agent", "kind", "key", "value", "prev", "created_at", "grants_authority", "executable")}
        body = canon(payload)
        ok = (e["prev"] == prev and e["tenant"] == TENANT and sha(e["prev"].encode() + body + bytes.fromhex(e["sig"])) == e["hash"])
        if ok:
            try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(bytes.fromhex(e["sig"]), body)
            except Exception: ok = False
        if not ok: bad.append(e["seq"])
        prev = e["hash"]
    return bad
def merkle(files):
    l = sorted(sha(p.read_bytes()) for p in files)
    while len(l) > 1:
        if len(l) % 2: l.append(l[-1])
        l = [sha((l[i] + l[i + 1]).encode()) for i in range(0, len(l), 2)]
    return l[0] if l else sha(b"")
def fail(m): print("FAIL:", m); sys.exit(1)
def main():
    root = Path(sys.argv[1] if len(sys.argv) > 1 else ".")
    man = json.loads((root / "RBC_MANIFEST.json").read_text())
    if man.get("status") != STATUS or man.get("external_review") != "NOT_OBTAINED": fail("manifest fields")
    body = {k: v for k, v in man.items() if k != "signature"}
    try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]), canon(body))
    except Exception: fail("signature")
    for n, h in man["files"].items():
        p = root / n
        if not p.exists() or sha(p.read_bytes()) != h: fail(f"file {n}")
    if merkle([root / n for n in man["files"]]) != man["merkle_root"]: fail("merkle")
    rep = json.loads((root / "RBC_RUN_REPORT.json").read_text()); salts = json.loads((root / "SALTS.json").read_text())
    for k in ("salt1", "salt2"):
        if sha(salts[k].encode()) != rep["salt_commitment"][k]: fail(f"salt {k}")
    if rep["design"]["model_calls"] != 0: fail("model")
    worlds = int(rep["design"]["worlds_per_salt"]); pubs = {a: pubhex(a) for a in AGENTS}; exp = {}
    for key in ("salt1", "salt2"):
        salt = salts[key]; got = {a: [] for a in ARMS}
        for w in range(worlds):
            cands = world(salt, w)
            for a in ARMS:
                r = campaign(cands, salt, w, a); got[a].append(r); want = rep["scenarios"][key]["worlds"][a][w]
                if r["runs"] != want["runs"]: fail(f"{key} w{w} {a} runs")
                for f in ("q", "coverage", "width", "q50", "q90"):
                    if abs(r[f] - want[f]) > 1e-9: fail(f"{key} w{w} {a} {f}")
        for a in ARMS:
            agg = summarize(got[a])
            for f, v in agg.items():
                rv = rep["scenarios"][key]["arms"][a][f]
                if isinstance(v, float):
                    if rv is None or abs(v - rv) > 1e-9: fail(f"{key} agg {a} {f}")
                elif v != rv: fail(f"{key} agg {a} {f}")
        mem = rep["scenarios"][key]["memory"]; ents = mem["entries"]
        if verify_entries(ents, pubs): fail(f"{key} chain")
        if any(e["tenant"] != TENANT or e["grants_authority"] is not False for e in ents): fail(f"{key} tenant/authority")
        if mem["tenant_visible"] != 0 or not mem["tamper_detected"] or not mem["authority_refused"] or mem["distinct_pids"] != 4: fail(f"{key} probes")
        obs = {}
        for e in ents:
            if e["kind"] == "experiment": obs.setdefault(e["value"]["candidate"], []).append(e["value"]["success"])
        phat, ns = fit(world(salt, mem["world"]), obs, only_role="promote"); r = sorted(abs(c["p"] - phat[c["i"]]) for c in world(salt, mem["world"]) if c["role"] == "calib")
        inf = sorted(r + [INFLATE] * CORRUPT); q = min(max(inf[:len(inf) - CORRUPT]), 2.0)
        test = [c for c in world(salt, mem["world"]) if c["role"] == "test"]
        cov = sum(1 for c in test if abs(phat[c["i"]] - c["p"]) <= q) / len(test)
        if abs(cov - mem["live_coverage"]) > 1e-12 or not mem["replay_equal"]: fail(f"{key} replay")
        a = rep["scenarios"][key]["arms"]
        exp[key] = {
            "H1_inflation_breaks": a["inflated"]["width_mean"] >= 1.0 and a["inflated"]["coverage"] >= 0.99,
            "H2_trim_restores": a["trimmed"]["coverage"] >= 0.70 and a["trimmed"]["width_mean"] <= 0.70,
            "H3_clean_control": a["standard"]["coverage"] >= 0.85 and a["standard"]["width_mean"] <= 0.60,
            "H4_budget": max(v["runs_max"] for v in a.values()) <= BUDGET,
            "H5_governance": not mem["chain_bad"] and mem["replay_equal"] and mem["tenant_visible"] == 0 and mem["tamper_detected"] and mem["authority_refused"] and mem["distinct_pids"] == 4,
        }
    for k in ("H1_inflation_breaks", "H2_trim_restores", "H3_clean_control", "H4_budget", "H5_governance"):
        ok = all(exp[key][k] for key in ("salt1", "salt2")); want = "SUPPORTED" if ok else "NOT_SUPPORTED"
        if rep["hypotheses"][k]["verdict"] != want: fail(k)
    if rep["hypotheses"]["H6_external_review"]["verdict"] != "BLOCKED": fail("H6")
    want_v = "ROBUST_CONFORMAL_SUPPORTED" if all(rep["hypotheses"][k]["verdict"] in ("SUPPORTED", "BLOCKED") for k in rep["hypotheses"]) else "NOT_SUPPORTED"
    if rep["verdict"] != want_v: fail("verdict")
    rows = sum(len(rep["scenarios"][k]["worlds"][a]) for k in ("salt1", "salt2") for a in ARMS)
    print(f"OK: RBC verified — 2 salts, {rows} arm-world rows re-derived, {len(rep['scenarios']['salt1']['memory']['entries'])} memory entries checked")
    return 0
if __name__ == "__main__":
    sys.exit(main())
