llm-bench

"""Agentic multi-task instrument + the agentic harness shared with agentic-fix (hard tier) and sleuth.

Each task is a module under bench/tasks/multitask/ (contract in its __init__.py) modelling a
real small-app shape, so a model is measured on each language/pattern separately. Two tiers
(suite v3, 2026-10-12), run separately (`run --tier easy|hard|all`, default all):
  easy  go_htmx   Go + HTMX partials + embedded SQLite, multi-table schema with a recursive-CTE read
        ts_next   Next.js App Router + Prisma (SQLite) + a Zod-validated API route + server page
  hard  rust_cli  Rust + reqwest + quick-xml + tokio CLI fetching XML behind Digest auth (where
                  local models fail most)
Item sets multitask-easy@<hash> / multitask-hard@<hash>.

One row per (task, sample): category <tier>/<go|rust|ts>, correct = every gate passed, score =
fraction of gates passed, plus gates, gate_detail, stop_reason (done | max_turns | gave_up |
<CallError label> | harness_error), turn totals and a per-turn sidecar (turn_log). A CallError
stops the loop: the row gets its label (correct None) and the gates still run, as information.
The model's leftover processes are killed BEFORE the gates run (a stale server can't answer a
gate); heavy build dirs are pruned after them unless --keep-work. go_htmx's "8080" becomes the
item's free port; ts_next's PLAN names no port, so two concurrent ts_next attempts that run
`npm run dev` can reach each other's dev server (Next's default 3000).
item_set covers the task text, tool schema and the task module's source; run.json records the
harness git sha.
"""
import argparse
import hashlib
import importlib
import json
import os
import sys
import time
import traceback

from bench.core import claude_cli
from bench.core import client
from bench.core import lane as lane_mod
from bench.core import results
from bench.core import tools

HERE = os.path.dirname(os.path.abspath(__file__))
MULTITASK_DIR = os.path.join(HERE, "multitask")

MAX_TOKENS_DEFAULT = 16000
TEMPERATURE_DEFAULT = 0.0
MAX_TURNS_DEFAULT = 40

SYSTEM_TMPL = (
    "You are a coding agent working in a project work dir. You are given "
    "a task plan below. Execute it step by step using the tools. You can "
    "write files, edit files, run builds and tests, and run shell commands "
    "in the work dir. Keep going until the build is green, the tests pass, "
    "and the app/binary works. Use the tools to verify your own progress — "
    "don't guess; compile and test.\n\n"
    "When you are confident the task is complete and tests pass, say "
    "`DONE` in your final message (no tool call) and stop.\n\n"
    "TASK PLAN:\n")
USER_MSG = ("The work dir has the starter scaffold. Execute the task plan. Begin "
            "by adding any dependencies and writing the files. Use the tools to "
            "build and test as you go.")
NUDGE = ("You must either call a tool to keep working, or say DONE if "
         "you believe the task is complete and tests pass.")
BAD_JSON = "ERROR: invalid JSON args ({e}); re-emit the {name} call."
TRUNC = "\n...[truncated, {n} total]"
GIVE_UP_AFTER = 2


def _sha_file(path):
    with open(path, "rb") as f:
        return hashlib.sha256(f.read()).hexdigest()


class AgenticTask:
    """One agentic item: what the model is told, which tools it gets, how it is graded.

    gates(ws, port) -> (dict gate->bool, dict detail); validate(ws, port) -> (ok, g, d).
    user: str, or callable(ws) -> str (agentic-fix computes the failing-test output).
    extra(ws) -> dict of instrument-specific row fields (optional)."""

    def __init__(self, *, item_id, category, plan, starter, toolset, gates, gate_names,
                 validate=None, system_tmpl=SYSTEM_TMPL, user=USER_MSG,
                 nudge=NUDGE, give_up_after=GIVE_UP_AFTER, done_word=True,
                 bad_json_fmt=BAD_JSON, trunc_fmt=TRUNC, max_tokens=MAX_TOKENS_DEFAULT,
                 temperature=TEMPERATURE_DEFAULT, port_token=None, env=None,
                 extra=None, source_files=(), prune=("node_modules", "target", ".next")):
        self.item_id = item_id
        self.category = category
        self.plan = plan
        self.starter = starter
        self.toolset = toolset
        self.gates = gates
        self.gate_names = tuple(gate_names)
        self.validate = validate
        self.system_tmpl = system_tmpl
        self.user = user
        self.nudge = nudge
        self.give_up_after = give_up_after
        self.done_word = done_word
        self.bad_json_fmt = bad_json_fmt
        self.trunc_fmt = trunc_fmt
        self.max_tokens = max_tokens
        self.temperature = temperature
        self.port_token = port_token
        self.env = dict(env or {})
        self.extra = extra
        self.source_files = tuple(source_files)
        self.prune = tuple(prune or ())

    def plan_for(self, port):
        if self.port_token and port is not None:
            return self.plan.replace(self.port_token, str(port))
        return self.plan

    def system_for(self, port):
        return self.system_tmpl + self.plan_for(port)

    def definition_hash(self):
        h = hashlib.sha256()
        parts = [self.item_id, self.category, self.system_tmpl, self.plan,
                 self.user if isinstance(self.user, str) else "<callable>",
                 self.nudge, repr(self.give_up_after), repr(self.done_word), self.bad_json_fmt,
                 repr(self.trunc_fmt), repr(self.port_token), json.dumps(self.env, sort_keys=True),
                 json.dumps(self.starter, sort_keys=True),
                 json.dumps(self.toolset.schema, sort_keys=True),
                 json.dumps(self.toolset.commands, sort_keys=True), repr(self.gate_names)]
        for p in parts:
            h.update(p.encode())
            h.update(b"\0")
        for f in self.source_files:
            h.update(_sha_file(f).encode())
        return h.hexdigest()


def item_set(name, tasks):
    h = hashlib.sha256()
    for t in sorted(tasks, key=lambda t: t.item_id):
        h.update(f"{t.item_id}:{t.definition_hash()}\n".encode())
    return f"{name}@{h.hexdigest()[:12]}"


# ============================================================ multitask task modules

def available_tasks():
    if not os.path.isdir(MULTITASK_DIR):
        return []
    return sorted(f[:-3] for f in os.listdir(MULTITASK_DIR)
                  if f.endswith(".py") and not f.startswith("_"))


def reference_validate(reference, gates, prep=()):
    """validate(ws, port) that grades the reference solution after running the `prep` commands."""
    def validate(ws, port):
        ws.materialize(reference)
        for cmd in prep:
            print(f"{cmd}: {ws.run(cmd, 600).text()[-300:]}")
        g, d = gates(ws, port)
        return all(g.values()), g, d
    return validate


TIERS = {"easy": ("go_htmx", "ts_next"), "hard": ("rust_cli",)}


def tier_of(name):
    return next((t for t, names in TIERS.items() if name in names), "easy")


def load_task(name):
    if name not in available_tasks():
        raise SystemExit(f"ERROR: no such task module: {name} (available: "
                         f"{', '.join(available_tasks())})")
    m = importlib.import_module(f"bench.tasks.multitask.{name}")
    return AgenticTask(
        item_id=m.TASK_NAME, category=f"{tier_of(name)}/{m.CATEGORY}", plan=m.PLAN, starter=m.STARTER,
        toolset=m.TOOLSET, gates=m.gates, gate_names=m.GATES,
        validate=reference_validate(m.REFERENCE, m.gates, getattr(m, "VALIDATE_PREP", ())),
        port_token=getattr(m, "PORT_TOKEN", None),
        env=getattr(m, "ENV", None), source_files=(os.path.abspath(m.__file__),))


# ============================================================ one attempt

def _sidecar_name(store, base):
    name, n = base, 1
    while os.path.exists(os.path.join(store.dir, results.safe_label(name) + ".json")):
        n += 1
        name = f"{base}-retry{n}"
    return name


def _report(row, log=print):
    g = row.get("gates") or {}
    log(f"\n===================== {row['item_id']} #{row['sample_idx']} =====================")
    log(f"status / stop      : {row.get('status')} / {row.get('stop_reason')}")
    log(f"turns used         : {row.get('turns_used')}/{row.get('max_turns')}  "
        f"(cut-off turns: {row.get('cut_off_turns')})")
    log(f"wall clock         : {row.get('wall_s')}s (loop {row.get('loop_s')}s, "
        f"gates {row.get('gates_s')}s)")
    log(f"tokens             : prompt {row.get('prompt_tokens')} (peak "
        f"{row.get('peak_prompt_tokens')}), completion {row.get('completion_tokens')}, "
        f"reasoning {row.get('reasoning_tokens')}")
    log(f"finish reasons     : {row.get('finish_counts')}")
    log("--- gates ---")
    for k, v in g.items():
        log(f"  {k:16s}: {'PASS' if v else 'fail'}")
    verdict = "ALL PASS" if row.get("correct") else (
        "NOT GRADED (" + str(row.get("status")) + ")" if row.get("correct") is None else "INCOMPLETE")
    log(f"  => {verdict}")
    if row.get("gate_detail"):
        log(f"  detail: {json.dumps(row['gate_detail'])[:600]}")


def run_item(task, store, sample_idx, *, max_turns, keep_work=False, lane=None, log=print):
    """Run one (task, sample) attempt end to end and record it; re-raises budget_stop."""
    lane = lane or lane_mod.current()
    tag = f"[{task.item_id}#{sample_idx}] "
    ws_dir = os.path.join(tools.WORK_ROOT, store.run_id, f"{task.item_id}-{sample_idx}")
    t0 = time.time()
    loop, harness_err, port = None, None, None
    with tools.Workspace(ws_dir, env=task.env) as ws:
        try:
            port = ws.allocate_port() if task.port_token else None
            ws.materialize(task.starter)
            user = task.user(ws) if callable(task.user) else task.user
            messages = [{"role": "system", "content": task.system_for(port)},
                        {"role": "user", "content": user}]
            loop_fn = claude_cli.agent_loop if claude_cli.is_claude(lane) else tools.agent_loop
            loop = loop_fn(
                ws, messages, task.toolset, max_turns=max_turns, max_tokens=task.max_tokens,
                temperature=task.temperature, item_id=task.item_id, run_id=store.run_id,
                lane=lane, done_word=task.done_word, give_up_after=task.give_up_after,
                nudge=task.nudge, bad_json_fmt=task.bad_json_fmt, trunc_fmt=task.trunc_fmt,
                log=log, tag=tag)
        except Exception as e:  # noqa: BLE001 — harness bug: record, still clean up + grade
            harness_err = e
            log(f"  {tag}HARNESS ERROR {e!r}\n{traceback.format_exc()}")
        if loop is not None and loop.get("harness_error") is not None:
            harness_err = loop["harness_error"]
        loop_s = time.time() - t0

        # The model's leftover processes must not answer the gates.
        survivors_tools = ws.kill_all()
        gate_port = port
        detail_pre = {}
        if port is not None and not tools.wait_port_free(port, 5):
            gate_port = ws.allocate_port()
            detail_pre["port_conflict"] = f"plan port {port} still busy before gates; gate used {gate_port}"
        tg = time.time()
        try:
            g, gd = task.gates(ws, gate_port)
            gd = dict(detail_pre, **(gd or {}))
        except Exception as e:  # noqa: BLE001
            g = {k: False for k in task.gate_names}
            gd = dict(detail_pre, gate_error=repr(e)[:300])
            log(f"  {tag}GATE ERROR {e!r}\n{traceback.format_exc()}")
        gates_s = time.time() - tg
        g = {k: bool(v) for k, v in g.items()}
        survivors = ws.kill_all()
        released = None
        if port is not None:
            released = all(tools.wait_port_free(p, 5) for p in sorted({port, gate_port}))
        extra = {}
        if task.extra:
            try:
                extra = task.extra(ws) or {}
            except Exception as e:  # noqa: BLE001
                extra = {"extra_error": repr(e)[:200]}
        if not keep_work and task.prune:
            tools.prune(ws.dir, task.prune)
    wall = time.time() - t0

    n_pass = sum(1 for v in g.values() if v)
    row = {"gates": g, "gate_detail": gd, "max_turns": max_turns,
           "loop_s": round(loop_s, 2), "gates_s": round(gates_s, 2),
           "port": port, "port_released": released,
           "survivors": len(survivors_tools) + len(survivors),
           "item_hash": task.definition_hash()[:12], "work_dir": os.path.relpath(ws_dir, tools.WORK_ROOT)}
    row.update(extra)
    if harness_err is not None:
        status_fields = client.error_meta(harness_err, wall)
        row.update(status_fields)
        row["stop_reason"] = "harness_error"
        correct, score = None, None
    elif loop["error"] is not None:
        row.update(client.error_meta(loop["error"], wall))
        row["error_call_s"] = round(loop["error_dt"] or 0, 2)
        row["stop_reason"] = loop["stop_reason"]
        correct, score = None, None
    else:
        row["status"] = "ok"
        row["stop_reason"] = loop["stop_reason"]
        row["wall_s"] = round(wall, 2)
        correct = bool(g) and n_pass == len(g)
        score = round(n_pass / len(g), 4) if g else 0.0
    if loop is not None:
        row.update(loop.get("row_extra") or {})
        last = loop.get("last_resp")
        b = (last or {}).get("_bench") or {}
        row.update({k: loop[k] for k in ("turns_used", "cut_off_turns", "prompt_tokens",
                                         "completion_tokens", "reasoning_tokens",
                                         "peak_prompt_tokens", "cost_usd", "finish_counts",
                                         "tool_calls", "model_s")})
        row["finish"] = client.finish_reason(last) if last else None
        row["request_hash"] = b.get("request_hash")
        rt = [t.get("reasoning_tokens") for t in loop["turns"] if t.get("reasoning_tokens") is not None]
        row["max_reasoning_in_a_turn"] = max(rt) if rt else None
        row["long_think_turns"] = sum(1 for r in rt if r > 4000) if rt else None
    else:
        row.update({"turns_used": 0, "cut_off_turns": 0})
    side = {"item_id": task.item_id, "sample_idx": sample_idx, "stop_reason": row["stop_reason"],
            "status": row.get("status"), "plan_port": port, "gates": g, "gate_detail": gd,
            "toolset": task.toolset.describe(), "turns": (loop or {}).get("turns", [])}
    if harness_err is not None:
        side["harness_error"] = traceback.format_exception_only(type(harness_err), harness_err)
    row["turn_log"] = store.sidecar(_sidecar_name(store, f"{task.item_id}-{sample_idx}.turns"), side)
    row = store.add(item_id=task.item_id, sample_idx=sample_idx, category=task.category,
                    correct=correct, score=score, **row)
    _report(row, log)
    if loop is not None and loop["error"] is not None and loop["error"].label() == "budget_stop":
        raise loop["error"]
    return row


# ============================================================ a run

def _print_table(rows, log=print):
    log(f"\n{'=' * 60}\n=== SUMMARY ===\n{'=' * 60}")
    log(f"{'task':16s} {'#':>2s} {'gates':>8s} {'stop':>12s} {'wall':>8s} {'turns':>6s} "
        f"{'comp tok':>9s} {'rsn tok':>9s} {'cut':>4s}")
    for r in rows:
        g = r.get("gates") or {}
        gs = f"{sum(1 for v in g.values() if v)}/{len(g)}"
        rt = r.get("reasoning_tokens")
        log(f"{r['item_id']:16s} {r['sample_idx']:>2d} {gs:>8s} {str(r.get('stop_reason'))[:12]:>12s} "
            f"{(r.get('wall_s') or 0) / 60:>7.1f}m {r.get('turns_used', 0):>6} "
            f"{(r.get('completion_tokens') or 0):>9,} {('-' if rt is None else format(rt, ',')):>9s} "
            f"{r.get('cut_off_turns', 0):>4}")


def run_instrument(instrument, set_name, tasks, *, samples=1, concurrency=1, resume=None,
                   max_turns=MAX_TURNS_DEFAULT, items=None, keep_work=False, lane=None,
                   log=print):
    """Run every (task, sample) not yet done; returns the run dir."""
    args = {"items": items, "samples": samples, "concurrency": concurrency,
            "max_turns": max_turns, "keep_work": keep_work,
            "defaults": {t.item_id: {"max_tokens": t.max_tokens, "temperature": t.temperature}
                         for t in tasks},
            "toolsets": {t.item_id: t.toolset.describe() for t in tasks},
            "env": {t.item_id: t.env for t in tasks if t.env},
            "work_root": tools.WORK_ROOT}

    def attempt(store, lane, task, k):
        a = store.run["args"]
        log(f"\n{'=' * 60}\n=== {task.item_id} sample {k} ===\n{'=' * 60}")
        run_item(task, store, k, max_turns=a["max_turns"], keep_work=a.get("keep_work"),
                 lane=lane, log=log)

    plan = lambda _args: (item_set(set_name, tasks), [(t.item_id, t) for t in tasks])  # noqa: E731
    store, _summary = results.run_attempts(instrument, args, plan, attempt, resume=resume,
                                           lane=lane, log=log)
    _print_table(store.rows(), log)
    return store.dir


def run_validate(tasks, log=print):
    """Reference solutions against the gates, offline (no model)."""
    stamp = time.strftime("%Y%m%d-%H%M%S")
    ok_all = True
    for t in tasks:
        if t.validate is None:
            log(f"{t.item_id}: no reference solution to validate")
            continue
        log(f"=== VALIDATION: {t.item_id} reference ===")
        with tools.Workspace(os.path.join(tools.WORK_ROOT, f"validate-{stamp}", t.item_id),
                             env=t.env) as ws:
            port = ws.allocate_port() if t.port_token else None
            try:
                ok, g, d = t.validate(ws, port)
            except Exception as e:  # noqa: BLE001
                ok, g, d = False, {}, {"error": repr(e)}
                log(traceback.format_exc())
            survivors = ws.kill_all()
            released = tools.wait_port_free(port, 5) if port is not None else None
            if t.prune:
                tools.prune(ws.dir, t.prune)
        log(f"{t.item_id}: gates={g} -> {'OK' if ok else 'BAD'}"
            f"{'' if not d else '  detail=' + json.dumps(d)[:600]}"
            f"{'' if released in (None, True) else '  PORT NOT RELEASED'}"
            f"{'' if not survivors else '  SURVIVORS ' + str(survivors)}")
        ok_all = ok_all and ok and released is not False and not survivors
    return ok_all


# ============================================================ CLI

def _parser(prog, multi):
    p = argparse.ArgumentParser(prog=prog)
    sub = p.add_subparsers(dest="cmd")
    for name in (("run", "cohort", "validate") if multi else ("run", "validate")):
        sp = sub.add_parser(name)
        if multi:
            sp.add_argument("tasks", nargs="*", help="task names (default: all)")
        if name == "validate":
            sp.add_argument("--items", default="", help="comma-separated item ids")
            continue
        results.add_run_args(sp)
        sp.add_argument("--max-turns", type=int, default=None,
                        help="tool-loop cap (default: $MAX_TURNS, else per instrument)")
        sp.add_argument("--keep-work", action="store_true",
                        help="keep node_modules/target/.next in work dirs")
    return p


def cli_main(instrument, set_name, all_tasks, argv, *, multi, default_cmd, max_turns_default,
             log=print):
    """Shared CLI. all_tasks: list of AgenticTask (multi: loaded lazily from names)."""
    argv = list(argv)
    if not argv:
        argv = [default_cmd]
    p = _parser(f"bench.py {instrument}", multi)
    a = p.parse_args(argv)
    if a.cmd is None:
        p.print_help()
        return 1
    names = [t.item_id for t in all_tasks]
    sel = list(getattr(a, "tasks", []) or [])
    sel += [i for i in (a.items or "").split(",") if i]
    for s in sel:
        if s not in names:
            p.error(f"unknown task {s!r}; available: {', '.join(names)}")
    if a.cmd == "validate":
        chosen = [t for t in all_tasks if not sel or t.item_id in sel]
        return 0 if run_validate(chosen, log=log) else 1
    if a.cmd == "cohort" and not sel:
        p.error("cohort needs task names")
    max_turns = a.max_turns or int(os.environ.get("MAX_TURNS") or max_turns_default)
    run_instrument(instrument, set_name, all_tasks, samples=a.samples,
                   concurrency=a.concurrency, resume=a.resume, max_turns=max_turns,
                   items=sel or None, keep_work=a.keep_work, log=log)
    return 0


def main(argv=None):
    pre = argparse.ArgumentParser(add_help=False)
    pre.add_argument("--tier", choices=("easy", "hard", "all"), default="all")
    a, rest = pre.parse_known_args(sys.argv[1:] if argv is None else argv)
    named = [x for x in rest if x in available_tasks()]
    tiers = [t for t in (("easy", "hard") if a.tier == "all" else (a.tier,))
             if not named or set(named) & set(TIERS[t])]
    if not tiers:
        raise SystemExit(f"--tier {a.tier} has none of {named}; tiers: {TIERS}")
    rc = 0
    for tier in tiers:
        args = [x for x in rest if x not in named or x in TIERS[tier]]
        rc = cli_main("agentic-multitask", f"multitask-{tier}", [load_task(n) for n in TIERS[tier]],
                      args, multi=True, default_cmd="--help", max_turns_default=MAX_TURNS_DEFAULT) or rc
    sys.exit(rc)


if __name__ == "__main__":
    main()