#!/usr/bin/env python3
"""E426-C verifier — imports no CAIN code. Re-executes every solve and checks the signed memory."""
import base64, hashlib, json, sys, types
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
DOMAIN = '"""E420-M — a value-algebra microcosm with four fields of two primitives each.\n\nA *program* is a sequence of primitive ids. Its *behaviour* is its output on six fixed\nexamples modulo 1009. A *macro* is a within-field pair of primitives. A task is a program\nwhose consecutive pairs come from different fields, so no single field can build it alone.\n\nNothing here is a model. The point is the arithmetic: a specialist that holds two primitives\ncannot compose a task that needs three fields; only the governed shared memory can carry the\nverified macros across the boundary.\n"""\nfrom __future__ import annotations\n\nimport hashlib\nimport itertools\nimport random\n\nMOD = 1009\nXS = [0, 1, 2, 3, 4, 5]\nNF = 8          # primitives\nNFIELD = 4      # fields, two primitives each\n\nPRIMS = [\n    ("add1", lambda x: (x + 1) % MOD),\n    ("mul2", lambda x: (x * 2) % MOD),\n    ("add7", lambda x: (x + 7) % MOD),\n    ("square", lambda x: (x * x) % MOD),\n    ("mul3", lambda x: (x * 3) % MOD),\n    ("neg", lambda x: (-x) % MOD),\n    ("add13", lambda x: (x + 13) % MOD),\n    ("cube1", lambda x: (x * x * x + 1) % MOD),\n]\nFUNCS = [f for _, f in PRIMS]\n\n\ndef field_of(p: int) -> int:\n    return p // 2\n\n\ndef field_prims(f: int) -> tuple[int, int]:\n    return (2 * f, 2 * f + 1)\n\n\ndef apply(ops, x: int) -> int:\n    for p in ops:\n        x = FUNCS[p](x)\n    return x\n\n\ndef beh(ops) -> tuple:\n    return tuple(apply(ops, x) for x in XS)\n\n\ndef apply_steps(b, steps):\n    for kind, val in steps:\n        seq = [val] if kind == "p" else list(val)\n        b = tuple(apply(seq, x) for x in b)\n    return b\n\n\ndef solve(target, steps, depth: int, cap: int = 400_000):\n    """Breadth-first search over ``steps`` up to ``depth``. Returns (program, expanded)."""\n    ident = tuple(XS)\n    seen = {ident}\n    cur = [(ident, [])]\n    expanded = 0\n    for d in range(depth + 1):\n        nxt = []\n        for b, prog in cur:\n            if b == target:\n                return prog, expanded\n            if d == depth:\n                continue\n            for s in steps:\n                nb = apply_steps(b, [s])\n                expanded += 1\n                if expanded > cap:\n                    return None, expanded\n                if nb in seen:\n                    continue\n                seen.add(nb)\n                nxt.append((nb, prog + [s]))\n        cur = nxt\n    return None, expanded\n\n\ndef prim_steps():\n    return [("p", i) for i in range(NF)]\n\n\ndef lib_steps(entries):\n    """Macros/compounds first, then primitives. ``entries`` hold ``ops``."""\n    return [("m", tuple(e["ops"])) for e in entries] + prim_steps()\n\n\n# ---- the closed task universe -------------------------------------------------\n# Every task is a concatenation of 3 macros (six steps) or 2 macros (four steps); the\n# constituent macros come from *different* fields by construction.\ndef all_pairs():\n    return [(a, b) for a in range(NF) for b in range(NF)]\n\n\ndef within_field_pairs():\n    out = []\n    for f in range(NFIELD):\n        a, b = field_prims(f)\n        for x in (a, b):\n            for y in (a, b):\n                out.append((x, y))\n    return out\n\n\ndef task_pool(length: int) -> list[tuple[int, ...]]:\n    """All field-diverse programs of ``length`` steps built from within-field macros."""\n    assert length in (4, 6)\n    macs = within_field_pairs()\n    if length == 4:\n        out = []\n        for m1 in macs:\n            for m2 in macs:\n                if field_of(m1[0]) != field_of(m2[0]):\n                    out.append(tuple(m1 + m2))\n        return out\n    out = []\n    for m1 in macs:\n        for m2 in macs:\n            for m3 in macs:\n                f = {field_of(m1[0]), field_of(m2[0]), field_of(m3[0])}\n                if len(f) == 3:\n                    out.append(tuple(m1 + m2 + m3))\n    return out\n\n\ndef _rng(*parts) -> random.Random:\n    return random.Random(int(hashlib.sha256("|".join(map(str, parts)).encode()).hexdigest()[:16], 16))\n\n\ndef split_pool(pool, salt: str, dev_n: int, sealed_n: int, tag: str):\n    """Deterministic, disjoint development and sealed samples."""\n    r = _rng("E420M", salt, tag)\n    idx = list(range(len(pool)))\n    r.shuffle(idx)\n    dev = [pool[i] for i in idx[:dev_n]]\n    sealed = [pool[i] for i in idx[dev_n:dev_n + sealed_n]]\n    return dev, sealed\n'
S="AGI: NOT ESTABLISHED · RSI: EXPERIMENTAL"
def canon(o): return json.dumps(o,sort_keys=True,separators=(",",":"),ensure_ascii=False).encode()
def sha(b): return hashlib.sha256(b).hexdigest()
def merkle(ps):
    l=sorted(sha(p.read_bytes()) for p in ps)
    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"")
class Fail(Exception): pass
def ck(c,m):
    if not c: raise Fail(m)
def load_domain(src):
    m=types.ModuleType("dom"); exec(src,m.__dict__); return m
def main(b):
    B=Path(b); r=json.loads((B/"CBT_RUN_REPORT.json").read_text())
    pre=json.loads((B/"CBT_PREREGISTRATION.json").read_text()); frz=json.loads((B/"CBT_PREREGISTRATION_FREEZE.json").read_text())
    salts=json.loads((B/"SALTS.json").read_text()); man=json.loads((B/"CBT_MANIFEST.json").read_text())
    D=load_domain(DOMAIN); n=0
    def ok(c,m):
        nonlocal n; ck(c,m); n+=1
    pub=Ed25519PublicKey.from_public_bytes(bytes.fromhex(man["pubkey_ed25519"]))
    pub.verify(bytes.fromhex(man["signature"]),canon({k:v for k,v in man.items() if k!="signature"})); ok(True,"manifest signature")
    EX={"CBT_MANIFEST.json","CBT_SIGNED_BODY.json","MANIFEST.json","MERKLE_ROOT.txt","PUBLICATION.json","CBT_OMEGA_SEAL.json"}
    fs=sorted(p for p in B.rglob("*") if p.is_file() and str(p.relative_to(B)) not in EX and "__pycache__" not in p.parts and not p.name.endswith(("-wal","-shm")))
    ok({str(p.relative_to(B)):sha(p.read_bytes()) for p in fs}==man["files"],"file hashes")
    ok(merkle(fs)==man["merkle_root"],"merkle root")
    ok(sha((B/"CBT_PREREGISTRATION.json").read_bytes())==frz["preregistration_sha256"],"preregistration hash")
    ok(pre["salts_commitment"]==frz["salt_commitments"] and all(sha(salts[k].encode())==pre["salts_commitment"][k] for k in ("salt1","salt2")),"salts")
    ok(r["status"]==S and r["model_calls"]==0,"status / zero model calls")
    macros=D.within_field_pairs(); L=[{"ops":list(p)} for p in macros]
    rec={}
    for salt in ("salt1","salt2"):
        rows=r["measurements"][salt]["rows"]
        ok(len(rows)==24,f"{salt}: 24 tasks")
        agg={"COLONY":{"solved":0,"expanded":0},"SOLO_ALL_PRIMS":{"solved":0,"expanded":0},
             "SOLO_ALL_MACROS":{"solved":0,"expanded":0},"SOLO_FIELD":{"solved":0,"expanded":0}}
        for row in rows:
            t=tuple(row["target"])
            c=D.solve(t,D.lib_steps(L),2); ap=D.solve(t,D.prim_steps(),4); am=D.solve(t,D.lib_steps(L),2)
            f=[D.solve(t,[("p",p) for p in D.field_prims(k)],4) for k in range(D.NFIELD)]
            ok((c[0] is not None)==row["colony"]["solved"] and c[1]==row["colony"]["expanded"],f"{salt}: colony {row['id']}")
            ok((ap[0] is not None)==row["solo_all_prims"]["solved"] and ap[1]==row["solo_all_prims"]["expanded"],f"{salt}: solo {row['id']}")
            ok((am[0] is not None)==row["solo_all_macros"]["solved"] and am[1]==row["solo_all_macros"]["expanded"],f"{salt}: macros {row['id']}")
            ok([x[0] is not None for x in f]==[x["solved"] for x in row["solo_field"]],f"{salt}: field {row['id']}")
            agg["COLONY"]["solved"]+=int(c[0] is not None); agg["COLONY"]["expanded"]+=c[1]
            agg["SOLO_ALL_PRIMS"]["solved"]+=int(ap[0] is not None); agg["SOLO_ALL_PRIMS"]["expanded"]+=ap[1]
            agg["SOLO_ALL_MACROS"]["solved"]+=int(am[0] is not None); agg["SOLO_ALL_MACROS"]["expanded"]+=am[1]
            ok(any(x[0] is not None for x in f)==row["siloed"],f"{salt}: siloed {row['id']}")
            agg["SOLO_FIELD"]["solved"]+=int(any(x[0] is not None for x in f)); agg["SOLO_FIELD"]["expanded"]+=sum(x[1] for x in f)
        for k,v in agg.items():
            ok(v["solved"]==r["measurements"][salt]["arms"][k]["solved"] and v["expanded"]==r["measurements"][salt]["arms"][k]["expanded"],f"{salt}: arm {k}")
        rec[salt]=agg
    a1,a2=rec["salt1"],rec["salt2"]
    H={"H1_content_parity":a1["COLONY"]["solved"]==a1["SOLO_ALL_PRIMS"]["solved"] and a2["COLONY"]["solved"]==a2["SOLO_ALL_PRIMS"]["solved"],
       "H2_search_efficiency":a1["COLONY"]["expanded"]<a1["SOLO_ALL_PRIMS"]["expanded"] and a2["COLONY"]["expanded"]<a2["SOLO_ALL_PRIMS"]["expanded"],
       "H3_content_boundary":(a1["COLONY"]["solved"]-a1["SOLO_FIELD"]["solved"]>=18 and a2["COLONY"]["solved"]-a2["SOLO_FIELD"]["solved"]>=18
                              and a1["SOLO_FIELD"]["solved"]<=8 and a2["SOLO_FIELD"]["solved"]<=8),
       "H4_all_content_single":a1["COLONY"]==a1["SOLO_ALL_MACROS"] and a2["COLONY"]==a2["SOLO_ALL_MACROS"],
       "H5_governance":all(r["measurements"]["salt1"]["probes"].values()) and r["measurements"]["salt1"]["claim_rejected"]}
    for k,v in H.items(): ok(r["hypotheses"][k]["verdict"]==("SUPPORTED" if v else "NOT_SUPPORTED"),f"reported {k}")
    ok(r["hypotheses"]["H6_external_review"]["verdict"]=="BLOCKED","reported H6")
    ok(r["verdict"]==("CONTENT_BOUNDARY_PARITY_SUPPORTED" if all(H.values()) else "NOT_SUPPORTED"),"verdict")
    pubs=json.loads((B/"CBT_MEMORY_PUBKEYS.json").read_text()); lines=[json.loads(x) for x in (B/"CBT_MEMORY.jsonl").read_text().splitlines() if x.strip()]
    ok(len(lines)==18,"memory 18 entries"); prev=""
    for e in lines:
        payload={k:e[k] for k in ("seq","tenant","agent","kind","key","value","prev","nonce","created_at")}; body=canon(payload)
        ok(e["prev"]==prev and sha(prev.encode()+body+bytes.fromhex(e["sig"]))==e["hash"],f"chain {e['seq']}")
        Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubs[e["agent"]])).verify(bytes.fromhex(e["sig"]),body); prev=e["hash"]
    ok(True,"memory signatures")
    print(f"OK {n}/{n}  verdict={r['verdict']}")
if __name__=="__main__":
    try: main(sys.argv[1] if len(sys.argv)>1 else "."); sys.exit(0)
    except Fail as ex: print(f"VERIFY FAILED: {ex}"); sys.exit(1)
