#!/usr/bin/env python3
"""Test the graders before trusting the grades: a known right answer must pass, an empty one must fail.

Works on an eval suite laid out the way our Agent Gym lays out its tasks, one folder per task:

    <task>/task.json   {"mode": "oneshot" or "agentic", "artifact": "solution.py", "capability": ...}
    <task>/grade/      the hidden grader: check.py (exit 0 = pass) or pytest test files
    <task>/public/     optional: a public check the model may see, same rules
    <task>/ref/        optional: a known right answer (for oneshot, ref/<artifact>)
    <task>/seed/       optional: files the model starts from

A grade is run the way the gym runs it: copy the answer and the seed into a fresh temporary
folder, lay the grader's files over them, run check.py, or pytest on the grader's test files,
and read the exit code. Model-written code runs when a grader imports it, exactly as it did
when the gym graded it, so run this on answers you would let the gym run.

Three commands:

  controls TASKS OUT
      For every task, grade three answers: the reference (must pass), an empty file
      (must fail), and nothing at all (must fail). For agentic tasks "nothing" is the
      seed left as it was. Writes controls.csv.

  regrade TASKS RUNS RUNS_GLOB TASK OUT
      Grade again, with today's grader, every first answer the gym kept for TASK in the
      runs matching RUNS_GLOB ("*" for all), and set each beside the grade the gym
      recorded at the time. Writes regrade.csv and copies the answers to OUT/answers/.

  history TASKS RUNS OUT
      Every first-try (L0) failure in RUNS/*/results.jsonl: what the gym recorded, whether
      its note was a timeout or API error or a grader's verdict, whether an answer is in
      the folder it kept, and, for a kept answer on a task with a public check, whether
      that public check passed it, and how many repair rounds the gym's L2 row says ran
      (where one ran before 2026-10-18, the kept file is the second try, not the first).
      Rows from before the gym scored a missing answer apart
      (no outcome field) say scoring=pass-fail. Writes history.csv. No note, prompt or
      answer is copied.

  cases TASKS OUT
      For every task that has a cases/ folder, grade each case with the task's own grader and
      say whether the grader gave the verdict the case's author wrote down. A case is one json
      file: {"name": ..., "expect": "pass" or "fail", "answer": the exact text of the answer
      file}. The tasks that need this are the ones with no reference answer, so the controls
      above never showed their graders a right answer. Writes cases.csv.

  mutate TASKS OUT
      For every task that has a reference answer, make wrong answers out of it with small, fixed
      edits (no randomness), grade each with the task's own grader, and say whether the grader
      CAUGHT it (failed it) or MISSED it (passed it). Writes mutants.csv, and every mutant and its
      diff under OUT/mutants/ so each miss can be read. A miss is not always a grader fault: some
      edits change nothing that matters, so read the misses before counting them. The edits:
        truncate_half     keep the first half of the lines
        drop_line         delete one line from the middle (not a comment)
        swap_lines        swap two neighbouring lines in the middle
        bump_number       raise the first number of 2 or more by one
        garbage_tail      append "}}}(((" to the end
        stub_functions    (Python) empty every function body
        flip_operator     (Python) swap one operator in a function: < <=, == !=, + -, and or
        typo_identifier   (HTML) drop a letter from the first CamelCase name in the page text
        mangle_placeholder (JSON) drop the % from the first format placeholder (%@, %lld, %1$lld)

  slice TASKS RUNS TASK OUT
      Copy one task, and every first answer the gym kept for it with its recorded row,
      into OUT/gym/ in the same layout, so the regrade can be run again from the copy.

Usage:
    python3 -I grader-controls.py controls ./tasks ./out
    python3 -I grader-controls.py regrade ./tasks ./runs '*' ground_absent_fact ./out
    python3 -I grader-controls.py history ./tasks ./runs ./out
    python3 -I grader-controls.py cases ./tasks ./out
    python3 -I grader-controls.py mutate ./tasks ./out
"""
import ast
import csv
import difflib
import glob
import hashlib
import io
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import tokenize

TIMEOUT = 120   # the gym's GRADE_TIMEOUT
# Notes the gym writes when no answer arrived: the model timed out, the API failed, or the
# model spent its whole budget thinking. None of these is a wrong answer.
NO_ANSWER = ("task-timeout", "gen-error", "gen-timeout", "grade-timeout", "harness-error", "gen-empty")


def load_task(tasks, name):
    path = os.path.join(tasks, name, "task.json")
    if not os.path.isfile(path):
        return None
    t = json.load(open(path, encoding="utf-8"))
    t["dir"] = os.path.join(tasks, name)
    t["name"] = name
    return t


def copy_in(src, dst):
    if os.path.isdir(src):
        shutil.copytree(src, dst, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__"))


def grade(task, workspace, which="grade"):
    """(passed, last line of output) for one workspace folder, or (None, why) if there is no grader."""
    src = os.path.join(task["dir"], which)
    if not os.path.isdir(src):
        return None, f"no {which} folder"
    tmp = tempfile.mkdtemp(prefix=f"controls_{which}_")
    try:
        copy_in(workspace, tmp)
        files = []
        for fn in sorted(os.listdir(src)):
            if fn == "__pycache__":
                continue
            s, d = os.path.join(src, fn), os.path.join(tmp, fn)
            if os.path.isdir(s):
                copy_in(s, d)
            else:
                shutil.copy(s, d)
                files.append(fn)
        cmd = ([sys.executable, "check.py"] if "check.py" in files else
               [sys.executable, "-m", "pytest", "-q", "-p", "no:cacheprovider"] + [f for f in files if f.endswith(".py")])
        try:
            p = subprocess.run(cmd, cwd=tmp, capture_output=True, text=True, timeout=TIMEOUT)
        except subprocess.TimeoutExpired:
            return False, "grader timed out"
        out = ((p.stdout or "") + "\n" + (p.stderr or "")).strip().splitlines()
        return p.returncode == 0, (out[-1] if out else "")[:160]
    finally:
        shutil.rmtree(tmp, ignore_errors=True)


def workspace(task, answer):
    """A temporary folder holding the seed plus one answer: a path, b"" for an empty file, or None."""
    ws = tempfile.mkdtemp(prefix="controls_ws_")
    copy_in(os.path.join(task["dir"], "seed"), ws)
    if task.get("mode") == "agentic":
        if answer:
            copy_in(answer, ws)
    elif answer == b"":
        open(os.path.join(ws, task["artifact"]), "wb").close()
    elif answer:
        shutil.copy(answer, os.path.join(ws, task["artifact"]))
    return ws


def reference(task):
    ref = os.path.join(task["dir"], "ref")
    if task.get("mode") == "agentic":
        return ref if os.path.isdir(ref) and [f for f in os.listdir(ref) if f != "__pycache__"] else None
    path = os.path.join(ref, task["artifact"])
    return path if os.path.isfile(path) else None


def word(ok):
    return "none" if ok is None else ("pass" if ok else "fail")


def run_controls(tasks, out):
    rows = []
    for name in sorted(os.listdir(tasks)):
        t = load_task(tasks, name)
        if not t:
            continue
        row = dict(task=name, capability=t.get("capability", ""), mode=t.get("mode", ""),
                   grader="check.py" if os.path.isfile(os.path.join(t["dir"], "grade", "check.py")) else "pytest")
        ref = reference(t)
        for label, answer in (("reference", ref), ("empty", b""), ("nothing", None)):
            if label == "reference" and not ref:
                row[label], row[label + "_note"] = "no reference", ""
                continue
            if label == "empty" and t.get("mode") == "agentic":
                row[label], row[label + "_note"] = "not applicable", ""
                continue
            ws = workspace(t, answer)
            try:
                ok, note = grade(t, ws)
            finally:
                shutil.rmtree(ws, ignore_errors=True)
            row[label] = word(ok)
            expected = label == "reference"
            row[label + "_note"] = "" if ok == expected else note
        rows.append(row)
        print(f"  {name:28} reference {row['reference']:13} empty {row['empty']:15} nothing {row['nothing']}")
    cols = ["task", "capability", "mode", "grader", "reference", "empty", "nothing",
            "reference_note", "empty_note", "nothing_note"]
    write_csv(os.path.join(out, "controls.csv"), cols, rows)


def run_cases(tasks, out):
    rows = []
    for name in sorted(os.listdir(tasks)):
        t = load_task(tasks, name)
        cdir = os.path.join(tasks, name, "cases")
        if not t or not os.path.isdir(cdir):
            continue
        for fn in sorted(os.listdir(cdir)):
            if not fn.endswith(".json"):
                continue
            c = json.load(open(os.path.join(cdir, fn), encoding="utf-8"))
            assert c["expect"] in ("pass", "fail"), f"{name}/{fn}: expect must be pass or fail"
            tmp = tempfile.mkdtemp(prefix="controls_case_")
            try:
                answer = os.path.join(tmp, "answer")
                open(answer, "w", encoding="utf-8").write(c["answer"])
                ws = workspace(t, answer)
                try:
                    ok, note = grade(t, ws)
                finally:
                    shutil.rmtree(ws, ignore_errors=True)
            finally:
                shutil.rmtree(tmp, ignore_errors=True)
            got = word(ok)
            rows.append(dict(task=name, case=fn[:-5], name=c["name"], expect=c["expect"], got=got,
                             agree="yes" if got == c["expect"] else "NO", note=note))
            print(f"  {name:26} {fn[:-5]:34} expected {c['expect']:4} got {got:4} {'' if got == c['expect'] else '<-- DISAGREES'}")
    cols = ["task", "case", "name", "expect", "got", "agree", "note"]
    write_csv(os.path.join(out, "cases.csv"), cols, rows)


# ---- mutate: wrong answers made from the reference -----------------------------------

def _comment(line):
    return line.strip().startswith(("#", "//", "/*", "*", "<!--"))


def _middle_candidates(lines, pairs=False):
    """Indices of lines worth editing in the middle half of a file, nearest the middle first."""
    n = len(lines)
    ok = lambda i: lines[i].strip() and not _comment(lines[i])
    idx = [i for i in range(n // 4, n - n // 4) if ok(i) and (not pairs or (i + 1 < n and ok(i + 1) and lines[i] != lines[i + 1]))]
    return sorted(idx, key=lambda i: abs(i - n // 2))


def op_truncate_half(text, ext):
    lines = text.splitlines(keepends=True)
    return "".join(lines[: len(lines) // 2]) if len(lines) >= 4 else None


def op_drop_line(text, ext):
    lines = text.splitlines(keepends=True)
    cand = _middle_candidates(lines) if len(lines) >= 4 else []
    return "".join(lines[: cand[0]] + lines[cand[0] + 1:]) if cand else None


def op_swap_lines(text, ext):
    lines = text.splitlines(keepends=True)
    cand = _middle_candidates(lines, pairs=True) if len(lines) >= 4 else []
    if not cand:
        return None
    i = cand[0]
    lines[i], lines[i + 1] = lines[i + 1], lines[i]
    return "".join(lines)


def op_garbage_tail(text, ext):
    return text.rstrip("\n") + "\n}}}(((\n"


def op_bump_number(text, ext):
    if ext == ".py":
        lines = text.splitlines(keepends=True)
        pick = None
        for tok in tokenize.generate_tokens(io.StringIO(text).readline):
            if tok.type == tokenize.NUMBER and re.fullmatch(r"\d+", tok.string) and int(tok.string) >= 2:
                pick = tok
                break
        if not pick:
            return None
        row, col = pick.start[0] - 1, pick.start[1]
        lines[row] = lines[row][:col] + str(int(pick.string) + 1) + lines[row][col + len(pick.string):]
        return "".join(lines)
    outside = _outside_blocks(text) if ext == ".html" else lambda a, b: True
    for m in re.finditer(r"\d+", text):
        if int(m.group()) >= 2 and outside(m.start(), m.end()):
            return text[: m.start()] + str(int(m.group()) + 1) + text[m.end():]
    return None


def _outside_blocks(text):
    """A test for 'this span is not inside a <style> or <script> block' (and not inside a tag)."""
    spans = [m.span() for m in re.finditer(r"<(style|script)\b.*?</\1>|<[^>]*>", text, flags=re.S | re.I)]
    return lambda a, b: not any(x <= a and b <= y for x, y in spans)


def op_stub_functions(text, ext):
    if ext != ".py":
        return None
    tree, changed = ast.parse(text), False

    class Stub(ast.NodeTransformer):
        def visit_FunctionDef(self, node):
            nonlocal changed
            node.body, changed = [ast.Pass()], True
            return node
        visit_AsyncFunctionDef = visit_FunctionDef
    new = Stub().visit(tree)
    return ast.unparse(ast.fix_missing_locations(new)) + "\n" if changed else None


def op_flip_operator(text, ext):
    if ext != ".py":
        return None
    swap = {"<": "<=", "<=": "<", ">": ">=", ">=": ">", "==": "!=", "!=": "==", "+": "-", "-": "+", "and": "or", "or": "and"}
    toks = list(tokenize.generate_tokens(io.StringIO(text).readline))
    first_def = min((t.start[0] for t in toks if t.type == tokenize.NAME and t.string == "def"), default=None)
    if first_def is None:
        return None
    lines = text.splitlines(keepends=True)
    for t in toks:
        if t.start[0] > first_def and t.string in swap and t.type in (tokenize.OP, tokenize.NAME):
            row, col = t.start[0] - 1, t.start[1]
            lines[row] = lines[row][:col] + swap[t.string] + lines[row][col + len(t.string):]
            return "".join(lines)
    return None


def op_typo_identifier(text, ext):
    if ext != ".html":
        return None
    outside = _outside_blocks(text)
    for m in re.finditer(r"\b[A-Z][a-z]+[A-Z][A-Za-z]+\b", text):
        if outside(m.start(), m.end()):
            w = m.group()
            return text[: m.start()] + w[:2] + w[3:] + text[m.end():]
    return None


def op_mangle_placeholder(text, ext):
    if ext != ".json":
        return None
    m = re.search(r"%(?:\d+\$)?l{0,2}[@dfsu]", text)     # %@  %lld  %1$lld  %d: the format placeholders
    return text[: m.start()] + text[m.start() + 1:] if m else None


OPERATORS = [("truncate_half", op_truncate_half), ("drop_line", op_drop_line), ("swap_lines", op_swap_lines),
             ("bump_number", op_bump_number), ("garbage_tail", op_garbage_tail), ("stub_functions", op_stub_functions),
             ("flip_operator", op_flip_operator), ("typo_identifier", op_typo_identifier),
             ("mangle_placeholder", op_mangle_placeholder)]


def _tidy_note(note):
    """A grader's failure message can carry the random name of its temporary folder, the home folder, or how long
    pytest took. Drop all three, so the same run writes the same file and no path of ours is published."""
    note = re.sub(r"/(?:private/)?var/folders/\S*?/tmp\w+", "<tmp>", note)
    note = re.sub(r"/Users/[A-Za-z0-9._-]+", "~", note)
    return re.sub(r" in \d+(?:\.\d+)?s\b", "", note)     # pytest's own "in 0.04s" differs from run to run


def run_mutate(tasks, out):
    rows = []
    for name in sorted(os.listdir(tasks)):
        t = load_task(tasks, name)
        ref = reference(t) if t else None
        if not ref:
            continue
        agentic = t.get("mode") == "agentic"
        if agentic:
            files = [os.path.join(r, f) for r, _, fs in os.walk(ref) for f in fs if f.endswith(".py") and f != "__pycache__"]
            target = max(files, key=os.path.getsize)
            rel, ext = os.path.relpath(target, ref), ".py"
        else:
            target, rel, ext = ref, t["artifact"], os.path.splitext(t["artifact"])[1]
        text = open(target, encoding="utf-8").read()
        def ref_passes(tries=3):
            """Some graders start a server and wait a few seconds, which a busy Mac can make them miss. Try the
            reference a few times before believing it fails."""
            for _ in range(tries):
                w = workspace(t, ref)
                try:
                    ok, _ = grade(t, w)
                finally:
                    shutil.rmtree(w, ignore_errors=True)
                if ok:
                    return True
            return False
        if not ref_passes():
            rows.append(dict(task=name, mode=t.get("mode", ""), file=rel, operator="(reference)", outcome="reference did not pass",
                             grader_note="the reference failed three tries, so no mutant of it was graded", mutant=""))
            print(f"  {name:26} SKIPPED: the reference did not pass")
            continue
        for op, fn in OPERATORS:
            new = fn(text, ext)
            row = dict(task=name, mode=t.get("mode", ""), file=rel, operator=op, outcome="", grader_note="", mutant="")
            if new is None:
                row["outcome"] = "not applicable"
            elif new == text:
                row["outcome"] = "unchanged"
            else:
                mdir = os.path.join(out, "mutants", name)
                os.makedirs(mdir, exist_ok=True)
                mpath = os.path.join(mdir, f"{op}{ext}")
                open(mpath, "w", encoding="utf-8").write(new)
                diff = "".join(difflib.unified_diff(text.splitlines(keepends=True), new.splitlines(keepends=True), rel, rel + " (mutant)", n=1))
                open(os.path.join(mdir, f"{op}.diff"), "w", encoding="utf-8").write(diff)
                if agentic:
                    tmp = tempfile.mkdtemp(prefix="controls_mut_")
                    copy_in(ref, tmp)
                    shutil.copy(mpath, os.path.join(tmp, rel))
                    answer = tmp
                else:
                    answer = mpath
                ws = workspace(t, answer)
                try:
                    ok, note = grade(t, ws)
                finally:
                    shutil.rmtree(ws, ignore_errors=True)
                    if agentic:
                        shutil.rmtree(answer, ignore_errors=True)
                if note == "grader timed out":
                    outcome = "timed out"
                elif ok:
                    outcome = "missed"
                elif ref_passes():          # a failure only counts as a catch if the reference still passes right now
                    outcome = "caught"
                else:
                    outcome = "inconclusive"
                row.update(outcome=outcome, grader_note="" if ok else _tidy_note(note), mutant=os.path.relpath(mpath, out))
            rows.append(row)
        got = [r["outcome"] for r in rows if r["task"] == name]
        print(f"  {name:26} caught {got.count('caught'):2}  missed {got.count('missed'):2}  of {len(got) - got.count('not applicable') - got.count('unchanged')} applied"
              + (f"  ({got.count('inconclusive')} inconclusive)" if 'inconclusive' in got else ""))
    cols = ["task", "mode", "file", "operator", "outcome", "grader_note", "mutant"]
    write_csv(os.path.join(out, "mutants.csv"), cols, rows)
    total = [r for r in rows if r["outcome"] in ("caught", "missed", "timed out")]
    print(f"{len(total)} wrong answers made; the graders caught {sum(r['outcome'] == 'caught' for r in total)} "
          f"and missed {sum(r['outcome'] == 'missed' for r in total)}")


def results_rows(runs, run=None):
    for f in sorted(glob.glob(os.path.join(runs, run or "*", "results.jsonl"))):
        for line in open(f, encoding="utf-8"):
            try:
                r = json.loads(line)
            except ValueError:
                continue
            r["run"] = os.path.basename(os.path.dirname(f))
            yield r


def kept_answer(runs, r, task):
    """The model's first answer as the gym kept it. A repeated run keeps each repeat in
    <task>.rep<N>/. Since 2026-10-18 the gym keeps the first answer as L0.<artifact> when
    a repair round ran; before that a repair overwrote it."""
    base = os.path.join(runs, r["run"], r["model"])
    folders = ([f"{r['task']}.rep{r['rep']}"] if r.get("rep") else []) + [r["task"]]
    for folder in folders:
        work = os.path.join(base, folder, "work")
        if not os.path.isdir(work):
            continue
        for fn in ("L0." + task["artifact"], task["artifact"]):
            p = os.path.join(work, fn)
            if os.path.isfile(p):
                return p, ("empty" if os.path.getsize(p) == 0 else "answered")
        return None, "empty"
    return None, "not kept"


def answer_name(r, task):
    """<run>.<model>[.rep<N>].<artifact>: one file per kept answer, repeats included."""
    rep = f".rep{r['rep']}" if r.get("rep") else ""
    return f"{r['run']}.{r['model']}{rep}.{task['artifact']}"


def run_regrade(tasks, runs, run_glob, name, out):
    t = load_task(tasks, name)
    rows = []
    os.makedirs(os.path.join(out, "answers"), exist_ok=True)
    for r in results_rows(runs, run_glob):
        if r.get("task") != name or r.get("condition") != "L0":
            continue
        path, state = kept_answer(runs, r, t)
        if state != "answered":
            continue
        row = dict(run=r["run"], model=r["model"], rep=r.get("rep") or "", task=name,
                   recorded=r.get("outcome") or ("pass" if r.get("pass") else "fail"),
                   recorded_note=(r.get("note") or "").splitlines()[0][:160] if r.get("note") else "",
                   answer=state, sha256="", bytes="", today="", today_note="")
        if path:
            data = open(path, "rb").read()
            row["sha256"], row["bytes"] = hashlib.sha256(data).hexdigest(), len(data)
            shutil.copy(path, os.path.join(out, "answers", answer_name(r, t)))
            ws = workspace(t, path)
            try:
                ok, note = grade(t, ws)
            finally:
                shutil.rmtree(ws, ignore_errors=True)
            row["today"], row["today_note"] = word(ok), note
        rows.append(row)
        print(f"  {r['run']} {r['model']:28} recorded {row['recorded']:5} today {row['today']}")
    cols = ["run", "model", "rep", "task", "recorded", "recorded_note", "answer", "sha256", "bytes", "today", "today_note"]
    write_csv(os.path.join(out, "regrade.csv"), cols, rows)


def run_history(tasks, runs, out):
    rows, cache = [], {}
    repairs = {(r["run"], r["model"], r["task"], r.get("rep")): r.get("repairs")
               for r in results_rows(runs) if r.get("condition") == "L2"}
    for r in results_rows(runs):
        if r.get("condition") != "L0" or r.get("pass") is not False:
            continue
        t = cache.setdefault(r["task"], load_task(tasks, r["task"]))
        if not t:
            continue   # the task has since been removed from the suite
        note = r.get("note") or ""
        path, state = kept_answer(runs, r, t)
        public = "-"
        if state == "answered" and os.path.isdir(os.path.join(t["dir"], "public")):
            ws = workspace(t, path)
            try:
                public = word(grade(t, ws, "public")[0])
            finally:
                shutil.rmtree(ws, ignore_errors=True)
        rows.append(dict(run=r["run"], model=r["model"], task=r["task"],
                         capability=r.get("capability", ""), recorded=r.get("outcome") or "fail",
                         scoring="three-outcome" if r.get("outcome") else "pass-fail",
                         cause="timeout or error" if any(m in note for m in NO_ANSWER) else "grader",
                         answer=state, public=public,
                         repairs=repairs.get((r["run"], r["model"], r["task"], r.get("rep")), "")))
    cols = ["run", "model", "task", "capability", "scoring", "recorded", "cause", "answer", "public", "repairs"]
    write_csv(os.path.join(out, "history.csv"), cols, rows)
    print(f"  {len(rows)} first-try failures read")


def run_slice(tasks, runs, name, out):
    t = load_task(tasks, name)
    dest = os.path.join(out, "gym")
    for part in ("task.json", "grade", "public", "ref", "seed"):
        src = os.path.join(t["dir"], part)
        d = os.path.join(dest, "tasks", name, part)
        if os.path.isdir(src):
            copy_in(src, d)
        elif os.path.isfile(src):
            os.makedirs(os.path.dirname(d), exist_ok=True)
            shutil.copy(src, d)
    n = 0
    for r in results_rows(runs):
        if r.get("task") != name or r.get("condition") != "L0":
            continue
        path, state = kept_answer(runs, r, t)
        if state != "answered":
            continue
        copy = os.path.join(dest, "runs", os.path.relpath(path, runs))
        os.makedirs(os.path.dirname(copy), exist_ok=True)
        shutil.copy(path, copy)
        keep = {k: r[k] for k in ("ts", "model", "task", "capability", "condition", "pass", "outcome", "note", "rep")
                if k in r}
        with open(os.path.join(dest, "runs", r["run"], "results.jsonl"), "a", encoding="utf-8") as f:
            f.write(json.dumps(keep) + "\n")
        n += 1
    print(f"  copied {name} and {n} kept answers to {dest}")


def write_csv(path, cols, rows):
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8", newline="") as f:
        w = csv.DictWriter(f, fieldnames=cols, extrasaction="ignore")
        w.writeheader()
        w.writerows(rows)
    print(f"wrote {path}")


def main():
    a = sys.argv[1:]
    if a[:1] == ["controls"] and len(a) == 3:
        run_controls(a[1], a[2])
    elif a[:1] == ["regrade"] and len(a) == 6:
        run_regrade(*a[1:])
    elif a[:1] == ["history"] and len(a) == 4:
        run_history(*a[1:])
    elif a[:1] == ["cases"] and len(a) == 3:
        run_cases(a[1], a[2])
    elif a[:1] == ["mutate"] and len(a) == 3:
        run_mutate(a[1], a[2])
    elif a[:1] == ["slice"] and len(a) == 5:
        run_slice(*a[1:])
    else:
        sys.exit(__doc__)


if __name__ == "__main__":
    main()
