#!/usr/bin/env python3
"""E127 top-of-page evidence updater.

Runs 20 times/day (every 72 minutes). It rotates verified evidence cards, never invents new
results, never upgrades a FAIL/PARTIAL, and always keeps the 48-hour soak status visible.

Usage:
  python3 scripts/e127/top_updater.py --once
  python3 scripts/e127/top_updater.py --loop
"""
from __future__ import annotations

import argparse, hashlib, json, re, time
from datetime import datetime, timedelta, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
OUT = ROOT / "artifacts/e127/top_updates"
STATE = OUT / "state.json"
HISTORY = OUT / "history.jsonl"
CATALOG = OUT / "catalog.json"
PAGES = [
    ROOT / "platform-gateway/frontend/index.html",
    ROOT / "platform-gateway/frontend/mcpgate_home.html",
    ROOT / "clawx-site/index.html",
]
BUNDLE = "https://clawx.click/evidence/e127-living-lab-2026-11-21/"
E126 = "https://clawx.click/evidence/e126b-general-intelligence-2026-11-21/"
E125 = "https://clawx.click/evidence/e125-generalization-2026-11-21/"

CARDS = [
    {"id": "E127-LAB", "status": "PASS", "title": "100-identity research lab",
     "value": "100 registered · 5 peak real workers · 60 tasks · 7 missions",
     "detail": "177.87 s measured; 0 failed, 0 dead, 144 hash-chained events. Registration is not activity.",
     "url": BUNDLE + "E127_REPORT.md", "source": "E127_RUN_REPORT.json"},
    {"id": "E126B-CONT", "status": "PASS", "title": "Continual learning beats no-memory",
     "value": "0.6667 vs 0.5556 · +11.1 pts · p=0.00049",
     "detail": "Retention 0.667 vs 0.500; poison 1/1 refused. Ties retrieval/episodic — bounded claim.",
     "url": E126 + "E126B_REPORT.md", "source": "continual_results.json"},
    {"id": "E126B-META", "status": "PASS", "title": "Metacognitive calibration",
     "value": "Brier 0.0926 · ECE 0.0082",
     "detail": "Pre-task success prediction on 200 confirmatory instances; abstention 0.0 at 0.5.",
     "url": E126 + "E126B_REPORT.md", "source": "metacognition_results.json"},
    {"id": "E126B-TRANSFER", "status": "PASS", "title": "Safe cross-domain transfer",
     "value": "+12.5 pts applied · 0/40 false accepts",
     "detail": "Positive transfer 92.75% vs from-scratch 79.0%, p=3e-12; conservative gate rejects 20/40.",
     "url": E126 + "E126B_REPORT.md", "source": "transfer_results.json"},
    {"id": "E126B-COLLECTIVE", "status": "PASS", "title": "Verified collective intelligence",
     "value": "0.666 vs 0.480 best single · 0/500 Byzantine flips",
     "detail": "+18.6 points, p=2.7e-9; 22 agents banned; rule-based agents, not LLMs.",
     "url": E126 + "E126B_REPORT.md", "source": "collective_results.json"},
    {"id": "E126B-DISCOVERY", "status": "PASS", "title": "Autonomous discovery cycles",
     "value": "8 cycles · 2 independent reproductions",
     "detail": "7 accepted / 1 rejected; 5 director-preferred hypotheses rejected; constructed tasks.",
     "url": E126 + "E126B_REPORT.md", "source": "discovery_results.json"},
    {"id": "E127-GOV", "status": "PASS", "title": "Governed execution preserved",
     "value": "0 unauthorized · 0 post-fence · ledger valid",
     "detail": "Three OS processes, independent keys; loopback one host, not multi-host.",
     "url": BUNDLE + "E127_REPORT.md", "source": "governance_results.json"},
    {"id": "E126B-ENV", "status": "PARTIAL", "title": "Novel-environment adaptation",
     "value": "0.895 vs 0.860 retrieval · p=0.210",
     "detail": "Full beats E125 0.820 (p=0.020) but misses preregistered remaining thresholds.",
     "url": E126 + "E126B_REPORT.md", "source": "env_results.json"},
    {"id": "E126B-CAUSAL", "status": "FAIL", "title": "Active causal selection",
     "value": "25 active wins · 25 random wins · 30 ties",
     "detail": "Mean MAE lower (0.1101 vs 0.1336), but the preregistered paired test failed.",
     "url": E126 + "E126B_NEGATIVE_RESULTS.md", "source": "causal_results.json"},
    {"id": "E126B-RETAIN", "status": "FAIL", "title": "Adaptation retention",
     "value": "control 0.375 → 0.0",
     "detail": "LoRA target improved, but catastrophic forgetting is not solved.",
     "url": E126 + "E126B_LIMITATIONS.md", "source": "adaptation_results.json"},
    {"id": "E125-BC", "status": "PASS", "title": "Preregistered compositional generalization",
     "value": "112/120 vs 98/120 · p=0.00131",
     "detail": "Holm 0.00262; constructed task families; category E was 0.000.",
     "url": E125 + "E126_REPORT.md", "source": "challenge_results.json"},
    {"id": "E127-API", "status": "PARTIAL", "title": "Public research API",
     "value": "8/8 local endpoints · SSE not stream-tested",
     "detail": "Read-only; production route and live fetch not verified.",
     "url": BUNDLE + "E127_REPORT.md", "source": "api_tests.json"},
    {"id": "E127-24H", "status": "NOT_TESTED", "title": "24/7 continuous operation",
     "value": "177.87 s measured",
     "detail": "No 24-hour, 7-day or 30-day continuity claim. A process running is not productive research.",
     "url": BUNDLE + "E127_LIMITATIONS.md", "source": "run_report.json"},
    {"id": "SOAK-24H", "status": "PASS", "title": "24-hour multi-region soak (historical)",
     "value": "24.003 h · 24 checkpoints · 0 divergences",
     "detail": "Evidence 2026-11-02. This is 24h, not 48h; it does not establish a 48h pass.",
     "url": "https://clawx.click/evidence/soak-multiregion-24h-2026-11-02/", "source": "latest.json"},
    {"id": "SOAK-48H", "status": "FAIL", "title": "48-hour soak (2026-11-15)",
     "value": "FAILED at checkpoint 0 · NOT ESTABLISHED",
     "detail": "PBFT safety incident on cain-mr-02: conflicting quorum certificates; cluster quarantined. No 48h pass exists.",
     "url": "https://clawx.click/evidence/soak-multiregion-48h-2026-11-18/", "source": "PBFT-SAFETY-INCIDENT-2026-11-15.md"},
    {"id": "SWEBENCH", "status": "INTERIM", "title": "SWE-bench Verified self-run",
     "value": "257/500 · rank 75/136 snapshot",
     "detail": "INTERIM self-run aggregate, not an official leaderboard position; E124.1 189/486 is stale.",
     "url": E126 + "E126B_REPORT.md", "source": "full_results.json"},
]



RSI_CARDS = [
    {"id":"E132-RSI","status":"PARTIAL","title":"E132 governed RSI loop",
     "value":"main 30/48 · matched fixed 28/48",
     "detail":"Library 21→117; depth 1→8; tier-6 1.000 vs fixed 0.500; tiers 8/12/16 = 0.000; verifier 1,740/1,740.",
     "url":"https://clawx.click/evidence/e132-rsi-2026-11-21/","source":"artifacts/e132/README.md"},
    {"id":"E129-RSI","status":"PASS","title":"E129 self-written library",
     "value":"8→28→35→35 sealed solves",
     "detail":"POSITIVE_BOUNDED; library 21→96, depth 1→8; 11/11 gates; stops growing at generation 2.",
     "url":"https://clawx.click/evidence/e129-rsi-2026-11-21/","source":"artifacts/e129/README.md"},
    {"id":"E130-RSI","status":"FAIL","title":"E130 scaled RSI",
     "value":"main 26/48 vs fixed 28/48",
     "detail":"NEGATIVE_OR_PARTIAL; meta-improver hurt; generation 1 rolled back on dev-t4-0018.",
     "url":"https://clawx.click/evidence/e130-rsi-2026-11-21/","source":"artifacts/e130/README.md"},
    {"id":"RSI-LIMIT","status":"PARTIAL","title":"RSI ceiling",
     "value":"Tiers 8, 12, 16 = 0/6",
     "detail":"Bounded constructed integer domain; no model trained; no external reviewer. Not unrestricted RSI.",
     "url":"https://clawx.click/evidence/e132-rsi-2026-11-21/","source":"artifacts/e132/README.md"},
    {"id":"RSI-METHOD","status":"PASS","title":"Governed improvement",
     "value":"96 self-written macros · 2 protected refusals",
     "detail":"Development-only promotion; sealed answers never used; self-generated evidence key.",
     "url":"https://clawx.click/evidence/e132-rsi-2026-11-21/","source":"artifacts/e132/README.md"},
]

AGI_TOP = ["E126B-CONT", "E127-LAB", "E126B-TRANSFER", "E126B-COLLECTIVE", "E126B-META", "E125-BC"]
RSI_TOP = ["E132-RSI", "E129-RSI", "RSI-LIMIT", "E130-RSI", "RSI-METHOD"]
_BY_ID = {c["id"]: c for c in CARDS + RSI_CARDS}

def _now():
    return datetime.now(timezone.utc)


def _fmt(dt):
    return dt.strftime("%Y-%m-%dT%H:%M:%SZ")


def _status_color(s):
    return {"PASS": "#22c55e", "PARTIAL": "#f59e0b", "FAIL": "#ef4444",
            "BLOCKED": "#94a3b8", "NOT_TESTED": "#94a3b8", "INTERIM": "#38bdf8"}.get(s, "#94a3b8")


def _panel(seq, cards, now, next_at, mode):
    def card_html(c):
        return (
        f"<div style='background:#07101c;border:1px solid #1e3a5f;border-radius:9px;padding:9px'>"
        f"<div style='display:flex;justify-content:space-between;gap:6px;align-items:center'>"
        f"<b style='font-size:12px;color:#e8eefc'>{c['title']}</b>"
        f"<span style='color:{_status_color(c['status'])};border:1px solid {_status_color(c['status'])};border-radius:4px;padding:1px 5px;font-size:9.5px;font-weight:900'>{c['status']}</span></div>"
        f"<div style='font-size:16px;font-weight:900;color:#fff;margin:3px 0'>{c['value']}</div>"
        f"<div style='font-size:10.5px;color:#c7d4ee'>{c['detail']}</div>"
        f"<div style='font-size:9.5px;margin-top:4px'><a href='{c['url']}' style='color:#7dd3fc'>evidence</a> · <span style='color:#8fa3c8'>{c['source']}</span></div></div>")
    agi = cards[:3]
    rsi_cards = cards[3:6]
    cc = ("<div style='display:grid;grid-template-columns:repeat(auto-fit,minmax(320px,1fr));gap:9px'>"
          "<div><div style='font-size:10.5px;letter-spacing:.14em;color:#7dd3fc;font-weight:900;margin-bottom:4px'>AGI LAB · GENERAL INTELLIGENCE</div>"
          + "".join(card_html(c) for c in agi) + "</div>"
          "<div><div style='font-size:10.5px;letter-spacing:.14em;color:#fbbf24;font-weight:900;margin-bottom:4px'>RSI LAB · RECURSIVE SELF-IMPROVEMENT</div>"
          + "".join(card_html(c) for c in rsi_cards) + "</div></div>")
    return (
        "<!-- CAIN-TOP-EVIDENCE:BEGIN --><section id='cain-top-evidence' aria-label='CAIN-42 current verified evidence' "
        "style='background:linear-gradient(120deg,#04070d,#0a1626 55%,#140a12);border-bottom:3px solid #ef4444;color:#e8eefc;font:12.5px/1.45 ui-sans-serif,system-ui,sans-serif;padding:12px 16px'>"
        "<div style='max-width:min(1680px,calc(100vw - 28px));margin:0 auto'>"
        "<div style='display:flex;gap:7px;flex-wrap:wrap;align-items:center'>"
        "<span style='background:#ef4444;color:#fff;font-weight:900;padding:2px 8px;border-radius:4px;font-size:10.5px'>CAIN-42 · TWO LABS: AGI + RSI</span>"
        "<span style='border:1px solid #ef4444;color:#fca5a5;border-radius:4px;padding:1px 7px;font-size:10.5px;font-weight:900'>AGI: NOT ESTABLISHED</span>"
        f"<span style='color:#93c5fd;font-size:10.5px'>TOP EVIDENCE UPDATE #{seq} · {mode} · {_fmt(now)} · next {_fmt(next_at)}</span>"
        "<span style='color:#fde68a;font-size:10.5px'>120 updates/day · every 12 min · verified evidence only</span></div>"
        "<h1 style='font-size:clamp(21px,3vw,34px);line-height:1.08;margin:5px 0 3px'>MOST SIGNIFICANT AGI + RSI EVIDENCE</h1>"
        f"<div style='display:grid;grid-template-columns:repeat(auto-fit,minmax(235px,1fr));gap:7px;margin-top:6px'>{cc}</div>"
        "<div style='margin-top:7px;padding:6px 8px;background:#2a0b0b;border:1px solid #ef4444;border-radius:6px;color:#fecaca;font-size:11px'><b>48-HOUR SOAK: FAILED / NOT ESTABLISHED.</b> The latest full-duration attempt (2026-11-18) ran <b>48.008 h</b> but failed verification: <b>71 consecutive unreadable cluster checks</b> and replicas ended at different heights <b>[345052, 345053, 345054]</b>. The earlier 2026-11-15 attempt failed at checkpoint 0 on a PBFT safety incident. There is no 48-hour pass to display. The supported long run is the <b>24.003-hour</b> soak (2026-11-02).</div>"
        f"<div style='margin-top:5px;color:#fca5a5;font-size:10.5px'>No breakthrough is scheduled. A new top result appears only after a preregistered experiment, independent verification and a committed evidence record. <a href='{BUNDLE}E127_REPORT.md' style='color:#fda4af'>E127 report</a> · <a href='{BUNDLE}E127_SCORECARD.json' style='color:#7dd3fc'>20 gates</a> · <a href='{BUNDLE}E127_OFFLINE_VERIFIER.py' style='color:#7dd3fc'>offline verifier</a> · <a href='https://cainstudio.online/agi-evidence-index.html' style='color:#7dd3fc'>AGI+RSI evidence index</a> · <a href='https://clawx.click/labs.html' style='color:#7dd3fc'>two-lab evidence</a></div>"
        "</div></section><!-- CAIN-TOP-EVIDENCE:END -->")


def _load_state():
    if STATE.exists():
        try: return json.loads(STATE.read_text())
        except Exception: pass
    return {"seq": 0, "created": _fmt(_now())}


def _save(seq, cards, now, next_at, mode):
    OUT.mkdir(parents=True, exist_ok=True)
    state = {"schema": "cain.e127.top_evidence_state.v1", "seq": seq,
             "last_update": _fmt(now), "next_update": _fmt(next_at),
             "target_updates_per_day": 120, "interval_seconds": 720,
             "mode": mode, "cards": [c["id"] for c in cards],
             "agi_status": "NOT ESTABLISHED"}
    STATE.write_text(json.dumps(state, indent=1))
    with HISTORY.open("a") as fh:
        fh.write(json.dumps({"seq": seq, "at": _fmt(now), "mode": mode,
                             "cards": [c["id"] for c in cards]}, sort_keys=True) + "\n")
    (OUT / "latest_panel.json").write_text(json.dumps(state, indent=1))


def inject():
    state = _load_state()
    seq = int(state.get("seq", 0)) + 1
    # every update keeps 48h status visible in the footer; rotate four evidence cards
    # Slots 1-2 in each lab are the highest-significance current records and are always shown.
    # The third slot rotates among the next-ranked verified records every 12 minutes.
    agi_fixed = [_BY_ID[x] for x in AGI_TOP[:2]]
    rsi_fixed = [_BY_ID[x] for x in RSI_TOP[:2]]
    agi_pool = [_BY_ID[x] for x in AGI_TOP[2:]]
    rsi_pool = [_BY_ID[x] for x in RSI_TOP[2:]]
    cards = agi_fixed + [agi_pool[(seq - 1) % len(agi_pool)]]
    cards += rsi_fixed + [rsi_pool[(seq - 1) % len(rsi_pool)]]
    now = _now()
    next_at = now + timedelta(seconds=720)
    panel = _panel(seq, cards, now, next_at, "REFRESH" if seq > 1 else "BOOTSTRAP")
    for p in PAGES:
        t = p.read_text()
        t = re.sub(r"<!-- CAIN-TOP-EVIDENCE:BEGIN -->.*?<!-- CAIN-TOP-EVIDENCE:END -->", "", t, flags=re.S)
        # remove the stale 12-hour milestone at the top; it remains in history/bundles
        t = re.sub(r"<!-- CAIN-MILESTONE:BEGIN -->.*?<!-- CAIN-MILESTONE:END -->", "", t, flags=re.S)
        # make the old E119 panel truthful about 48h
        t = t.replace("6-HOUR MISSION PASSED · 24-HOUR SOAK PASSED · VAGI BENCHMARKS WON",
                      "6-HOUR MISSION PASSED · 24-HOUR SOAK PASSED · 48-HOUR SOAK FAILED · AGI NOT ACHIEVED")
        m = re.search(r"<body[^>]*>", t, flags=re.I)
        if not m:
            print("no body", p); continue
        t = t[:m.end()] + panel + t[m.end():]
        p.write_text(t)
    _save(seq, cards, now, next_at, "REFRESH" if seq > 1 else "BOOTSTRAP")
    print(json.dumps({"seq": seq, "cards": [c["id"] for c in cards], "next": _fmt(next_at)}, indent=1))
    return seq


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--once", action="store_true")
    ap.add_argument("--loop", action="store_true")
    a = ap.parse_args()
    if a.loop:
        while True:
            inject()
            time.sleep(4320)
    inject()


if __name__ == "__main__":
    main()
