#!/usr/bin/env python3
"""RWM standalone auditor — re-derives the real-workload study from the rows and the memory.
No CAIN imports: the row/memory checks and the redactor contract are re-implemented here."""
from __future__ import annotations
import gzip, hashlib, json, re, sys
from pathlib import Path
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey

N=8000; KILL_AT=4000; FENCE=600; QUERIES=500; TENANT="cain42-rwm"; SEED="rwm"
AGENTS=("writer","resumer","operator","reader")
CHECKS=[]
def ok(n,c): CHECKS.append((n,bool(c))); return bool(c)
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def pct(xs,p):
    if not xs: return 0.0
    xs=sorted(xs); k=(len(xs)-1)*p; lo,hi=int(k),min(int(k)+1,len(xs)-1)
    return round(xs[lo]+(xs[hi]-xs[lo])*(k-lo),1)
def pub(a):
    k=Ed25519PrivateKey.from_private_bytes(hashlib.sha256(f"{SEED}|{a}".encode()).digest())
    return k.public_key().public_bytes(serialization.Encoding.Raw,serialization.PublicFormat.Raw).hex()
def nonce(agent,kind,key,value): return sha(canon({"agent":agent,"kind":kind,"key":key,"value":value}))[:16]
TOKEN=re.compile(r"(?:sk-[A-Za-z0-9]{10,}|Bearer[%20 +][A-Za-z0-9._\-]{8,}|[A-Fa-f0-9]{32,})")
EMAIL=re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
IPV4=re.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b")
def main():
    d=Path(sys.argv[1]).resolve(); man=json.loads((d/"RWM_MANIFEST.json").read_text()); body={k:v for k,v in man.items() if k!="signature"}
    ok("manifest signature",Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"])).verify(bytes.fromhex(man["signature"]),canon(body)) is None)
    files={str(p.relative_to(d)):sha(p.read_bytes()) for p in sorted(d.rglob("*")) if p.is_file() and str(p.relative_to(d)) in man["files"]}
    ok("file hashes",files==man["files"]); ok("merkle root",man["merkle_root"]==(d/"MERKLE_ROOT.txt").read_text().strip())
    r=json.loads((d/"RWM_RUN_REPORT.json").read_text()); fp=json.loads((d/"RWM_SOURCE_FINGERPRINT.json").read_text())
    with gzip.open(d/"RWM_ROWS.jsonl.gz","rt") as f: rows=[json.loads(x) for x in f if x.strip()]
    with gzip.open(d/"RWM_MEMORY.json.gz","rt") as f: entries=json.load(f)
    ok("row count",len(rows)==N); ok("source lines",fp["lines_parsed"]==len(rows)==r["source"]["lines_parsed"])
    ok("real source",fp["real_source"]=="/etc/traefik/logs/access.log" and "not a customer" in r["source_note"].lower())
    admitted=[x for x in rows if x["a"]==1]; denied=[x for x in rows if x["a"]==0]
    ok("admitted",len(admitted)==r["measures"]["admitted"]==len(entries))
    ok("denied reasons",len(denied)==sum(r["measures"]["denied"].values()))
    ok("fence rows denied",all(x["a"]==0 for x in rows if KILL_AT<=x["i"]<KILL_AT+FENCE) and
       sum(1 for x in rows if KILL_AT<=x["i"]<KILL_AT+FENCE and x["r"]=="JIT_PRINCIPAL_REVOKED")==r["measures"]["fence_attempts"]==FENCE)
    ok("fence writes zero",r["measures"]["fence_writes"]==0)
    ok("resumed",sum(1 for x in rows if x["i"]>=KILL_AT+FENCE and x["a"]==1)==r["measures"]["resumed"]>0)
    lat=[x["l"] for x in admitted]; ok("latency n",len(lat)==r["measures"]["latency_us"]["n"])
    ok("latency p50",pct(lat,0.50)==r["measures"]["latency_us"]["p50"])
    ok("latency p95",pct(lat,0.95)==r["measures"]["latency_us"]["p95"])
    ok("latency p99",pct(lat,0.99)==r["measures"]["latency_us"]["p99"])
    ok("redaction total",sum(x["rd"] for x in rows)==sum(r["measures"]["redactions"].values()))
    ok("no raw pattern in rows",not any(TOKEN.search(str(x.get("rt",""))) or EMAIL.search(str(x.get("rt",""))) or IPV4.search(str(x.get("rt",""))) for x in rows))
    blob=" ".join(json.dumps(e["value"]) for e in entries)
    ok("no raw pattern in memory",not (TOKEN.search(blob) or EMAIL.search(blob) or IPV4.search(blob)))
    ok("host classes",all(e["value"].get("host") in ("cainstudio.online","mcpgate.online","clawx.click","ip","other","none") for e in entries))
    ok("window root",sha("".join(x["d"] for x in admitted).encode())==r["measures"]["window_root"])
    ok("salt commitment present",bool(re.fullmatch(r"[0-9a-f]{64}",r["measures"]["salt_commitment"] or "")))
    pubs={a:pub(a) for a in AGENTS}; prev=""; bad=[]; flags=True
    for e in entries:
        flags=flags and (not e["grants_authority"]) and (not e["executable"])
        body2=canon({k:e[k] for k in ("seq","tenant","agent","kind","key","value","prev","nonce","created_at","grants_authority","executable")})
        g=e["prev"]==prev and e["tenant"]==TENANT and sha(e["prev"].encode()+body2+bytes.fromhex(e["sig"]))==e["hash"]
        g=g and e["nonce"]==nonce(e["agent"],e["kind"],e["key"],e["value"])
        if g:
            try: Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(bytes.fromhex(e["sig"]),body2)
            except Exception: g=False
        if not g: bad.append(e["seq"])
        prev=e["hash"]
    ok("memory chain+sigs",not bad); ok("memory no-authority",flags)
    ok("every entry has a real row",all(0<=e["value"].get("window_i",-1)<N and rows[e["value"]["window_i"]]["a"]==1 for e in entries))
    ok("replay refused",r["measures"]["chain"]["replay_refused"] is True and "ALREADY_CONSUMED" in r["measures"]["chain"]["replay_reason"])
    ok("tenant isolation",r["measures"]["chain"]["cross_tenant_rows"]==0 and r["measures"]["chain"]["own_tenant_rows"]==len(entries))
    ok("tamper detected",r["measures"]["chain"]["tamper_detected"] is True)
    ok("authority refused",r["measures"]["chain"]["authority_from_memory_refused"] is True)
    fix=json.loads((d/"RWM_REDACTOR_FIXTURE.json").read_text())["cases"]
    ok("redactor fixture",not TOKEN.search("sk-ABCDEFGHIJKLMNOP1234") is False and bool(EMAIL.search("a@b.co")) and bool(TOKEN.search("0123456789abcdef0123456789abcdef")) and not TOKEN.search("/api/health"))
    H=r["hypotheses"]
    comp={"H1_real_window_ingested":len(rows)==N and len(admitted)>=0.95*(N-FENCE),
          "H2_pii_never_stored":r["measures"]["redactions"]["ip"]==N and not (TOKEN.search(blob) or EMAIL.search(blob) or IPV4.search(blob)),
          "H3_fence_stops_writes":r["measures"]["fence_writes"]==0 and r["measures"]["fence_attempts"]==FENCE and r["measures"]["resumed"]>0,
          "H4_memory_integrity":not bad and flags and r["measures"]["chain"]["tamper_detected"] and r["measures"]["chain"]["replay_refused"] and r["measures"]["chain"]["cross_tenant_rows"]==0,
          "H5_real_latency":r["measures"]["latency_us"]["n"]==len(admitted) and r["measures"]["latency_us"]["p95"]<=25000,
          "H6_queries_need_a_grant":r["measures"]["queries"]["grant_verified"] and r["measures"]["queries"]["without_grant_refused"] and r["measures"]["queries"]["count"]==QUERIES}
    for k,v in comp.items(): ok(f"{k} ok",H[k]["ok"]==v); ok(f"{k} verdict",H[k]["verdict"]==("SUPPORTED" if v else "NOT_SUPPORTED"))
    ok("H7 blocked",H["H7_external_review"]["verdict"]=="BLOCKED")
    core=all(H[k]["ok"] for k in H if k!="H7_external_review")
    ok("verdict",r["verdict"]==("REAL_WORKLOAD_GOVERNED_MEMORY_SUPPORTED" if core else "NOT_SUPPORTED"))
    ok("status line",r["status"]=="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL")
    ok("0 model calls",r["design"]["model_calls"]==0)
    passed=sum(1 for _,g in CHECKS if g)
    for n,g in CHECKS:
        if not g: print("FAIL",n)
    print(f"{passed}/{len(CHECKS)} checks passed"); return 0 if passed==len(CHECKS) else 1
if __name__=="__main__": sys.exit(main())
