#!/usr/bin/env python3
"""Replay agent-smith's escalation ladder over answers a model already gave, with no model calls.

agent-smith's --cascade (github.com/negativetime/agent-smith-plugin, scripts/cascade.py)
sends a prompt to the cheapest rung first and climbs to the next only when the answer
fails a mechanical gate: empty, cut off, JSON that will not parse, Python that will not
parse. The gate cannot tell a right answer from a wrong one that is well formed. This
script measures what that costs, using answers our Agent Gym kept from earlier runs of
the same models on the same tasks, each already graded by the gym's hidden tests.

For every one-shot task and every rung it reads each kept first answer (L0), runs the
gate on it (check_output, copied below from cascade.py), and writes:

    answers.csv  one row per kept answer: task, rung, model, run, the gym's grade, its seconds, the gate
    ladders.csv  one row per task and ladder: the rung the climb stopped on, and whether
                 the answer it stopped on was right. Each rung uses its LATEST kept answer.
                 A climb that reaches a rung with no answer for that task is "untested".
                 Its seconds are the gym's timing of each rung's kept answer, added up.
    meta.json    the rung map, the ladders, and the gate's source check

A rung's answer counts as no answer (the gate fails it as empty) when the gym recorded
that none arrived: a timeout, an API error, a model that spent its whole budget thinking.
A graded answer whose file the gym did not keep is listed as "not kept" and left out of
the ladders, because the gate cannot be run on it.

Usage:
    python3 -I cascade-replay.py TASKS RUNS OUT
    python3 -I cascade-replay.py TASKS RUNS OUT --plugin ~/.claude/skills/agent-smith
"""
import argparse
import ast
import csv
import glob
import hashlib
import inspect
import json
import os
import sys

# The ladder's rungs (cascade.py, 2026-10-20) and the gym label each one's answers are under.
# T3 in the ladder is Gemini Pro through the Gemini CLI; the gym ran Gemini Pro through the API.
RUNGS = {"T0": ("llama3.2:3b", "llama3.2-3b"), "T1": ("gpt-oss:20b", "gpt-oss-20b"),
         "T2": ("glm-5.3 on z.ai", "zai-glm-5.3"), "T3": ("Gemini Pro", "gemini-pro")}
# Notes the gym writes when no answer arrived (timeout, API error, a model that spent its
# whole budget thinking). The live ladder would see an empty reply and climb.
NO_ANSWER = ("task-timeout", "gen-error", "gen-timeout", "harness-error", "gen-empty")
PAID = {"T2", "T3"}   # flat-rate plans already paid for, but not free and not on this Mac
LADDERS = {"from T0": ["T0", "T1", "T2", "T3"], "from T1": ["T1", "T2", "T3"],
           "from T2": ["T2", "T3"], "T2 only": ["T2"]}


# ---- copied from cascade.py; --plugin checks the copy still matches -----------------

def _strip_fence(text):
    s = text.strip()
    if not s.startswith("```"):
        return s
    lines = s.splitlines()[1:]
    if lines and lines[-1].strip().startswith("```"):
        lines = lines[:-1]
    return "\n".join(lines).strip()


def check_output(text, finish_reason=None, want_json=False, want_python=False,
                 extra=()):
    """Return None when the output passes every mechanical gate, else a short reason.

    `extra` is a sequence of callables (text) -> reason-or-None, for gates that live in
    gemini.py (the agentic-non-answer detector)."""
    if not text or not text.strip():
        return "empty"
    if finish_reason in ("length", "max_tokens", "MAX_TOKENS"):
        return "truncated"
    if want_json:
        try:
            json.loads(_strip_fence(text))
        except ValueError:
            return "bad-json"
    if want_python:
        import ast
        try:
            ast.parse(_strip_fence(text))
        except SyntaxError as e:
            return f"py-syntax (line {e.lineno})"
    for fn in extra:
        why = fn(text)
        if why:
            return why
    return None

# ---- end of copy --------------------------------------------------------------------


def check_copy(plugin):
    """Compare the two functions above with cascade.py's, character for character."""
    src = open(os.path.join(plugin, "scripts", "cascade.py"), encoding="utf-8").read()
    theirs = {n.name: ast.get_source_segment(src, n) for n in ast.parse(src).body
              if isinstance(n, ast.FunctionDef)}
    for fn in (_strip_fence, check_output):
        if theirs.get(fn.__name__) != inspect.getsource(fn).rstrip("\n"):
            sys.exit(f"{fn.__name__} here no longer matches {plugin}/scripts/cascade.py; copy it again")
    return hashlib.sha256(src.encode("utf-8")).hexdigest()


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("tasks")
    ap.add_argument("runs")
    ap.add_argument("out")
    ap.add_argument("--plugin", help="an agent-smith checkout, to check the gate copy")
    a = ap.parse_args()
    cascade_sha = check_copy(os.path.expanduser(a.plugin)) if a.plugin else None

    tasks = {}
    for name in sorted(os.listdir(a.tasks)):
        p = os.path.join(a.tasks, name, "task.json")
        if os.path.isfile(p):
            t = json.load(open(p, encoding="utf-8"))
            if t.get("mode") == "oneshot":
                tasks[name] = t
    label_to_rung = {lab: rung for rung, (_, lab) in RUNGS.items()}

    answers = []
    for f in sorted(glob.glob(os.path.join(a.runs, "*", "results.jsonl"))):
        run = os.path.basename(os.path.dirname(f))
        for line in open(f, encoding="utf-8"):
            try:
                r = json.loads(line)
            except ValueError:
                continue
            rung, t = label_to_rung.get(r.get("model")), tasks.get(r.get("task"))
            if not rung or not t or r.get("condition") != "L0":
                continue
            graded = r.get("outcome") or ("pass" if r.get("pass") else "fail")
            # A repeated run keeps each repeat in <task>.rep<N>/.
            folders = ([f"{r['task']}.rep{r['rep']}"] if r.get("rep") else []) + [r["task"]]
            path = next((p for d in folders for p in
                         (os.path.join(a.runs, run, r["model"], d, "work", "L0." + t["artifact"]),
                          os.path.join(a.runs, run, r["model"], d, "work", t["artifact"]))
                         if os.path.isfile(p)), None)
            no_answer = graded == "unmeasurable" or any(m in (r.get("note") or "") for m in NO_ANSWER)
            if no_answer:
                text, gate = "", "empty"
            elif path:
                text = open(path, encoding="utf-8", errors="replace").read()
                gate = check_output(text, want_json=t["artifact"].endswith(".json"),
                                    want_python=t["artifact"].endswith(".py")) or "pass"
            else:
                text, gate = "", "not kept"   # graded, but the file is gone: the gate cannot be replayed
            answers.append(dict(task=r["task"], capability=t.get("capability", ""), rung=rung,
                                model=r["model"], run=run, ts=r.get("ts", ""), rep=r.get("rep") or "",
                                graded=graded, seconds=r.get("seconds", ""),
                                gate=gate, kept="yes" if path else "no",
                                sha256=hashlib.sha256(text.encode()).hexdigest() if text else ""))

    latest = {}
    for x in sorted(answers, key=lambda x: (x["run"], x["ts"], str(x["rep"]))):
        if x["gate"] != "not kept":
            latest[(x["task"], x["rung"])] = x

    ladders = []
    for name in sorted(tasks):
        for lname, rungs in LADDERS.items():
            tried, row = [], dict(task=name, ladder=lname)
            for rung in rungs:
                x = latest.get((name, rung))
                if not x:
                    row.update(stopped="untested", at=rung, right="", tried=" ".join(tried))
                    break
                tried.append(rung)
                if x["gate"] == "pass":
                    row.update(stopped="answer", at=rung, right="yes" if x["graded"] == "pass" else "no",
                               tried=" ".join(tried))
                    break
            else:
                row.update(stopped="every rung failed the gate", at="", right="no", tried=" ".join(tried))
            row["paid_rungs"] = sum(1 for r in tried if r in PAID)
            # The time the climb took, as the gym timed each rung's kept answer, one rung after the other.
            secs = [latest[(name, r)]["seconds"] for r in tried]
            row["seconds"] = round(sum(float(x) for x in secs), 1) if secs and all(x != "" for x in secs) else ""
            ladders.append(row)

    os.makedirs(a.out, exist_ok=True)
    write(os.path.join(a.out, "answers.csv"),
          ["task", "capability", "rung", "model", "run", "rep", "graded", "seconds", "gate", "kept", "sha256"], answers)
    write(os.path.join(a.out, "ladders.csv"),
          ["task", "ladder", "stopped", "at", "right", "tried", "paid_rungs", "seconds"], ladders)
    meta = dict(rungs={k: dict(model=m, gym_label=lab) for k, (m, lab) in RUNGS.items()},
                ladders=LADDERS, paid=sorted(PAID), oneshot_tasks=len(tasks),
                gate_copy_checked_against=(dict(file="scripts/cascade.py", sha256=cascade_sha)
                                           if cascade_sha else None))
    with open(os.path.join(a.out, "meta.json"), "w", encoding="utf-8") as f:
        json.dump(meta, f, indent=2)
        f.write("\n")

    for rung in RUNGS:
        xs = [x for x in answers if x["rung"] == rung]
        through = [x for x in xs if x["gate"] == "pass"]
        wrong = sum(1 for x in through if x["graded"] != "pass")
        print(f"{rung} {RUNGS[rung][0]:16} {len(xs):3} answers, {len(through):3} through the gate, "
              f"{wrong:3} of those wrong")
    for lname in LADDERS:
        rs = [r for r in ladders if r["ladder"] == lname and r["stopped"] != "untested"]
        print(f"{lname:8} {len(rs):2} tasks climbed, {sum(r['right'] == 'yes' for r in rs):2} right")


def write(path, cols, rows):
    with open(path, "w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore")
        w.writeheader()
        w.writerows(rows)


if __name__ == "__main__":
    main()
