llm-bench

"""Agentic-fix instrument: bug fixes in two tiers (suite v3, 2026-10-12; absorbed coding-suite).

easy  single turn: the symptom and the buggy code in one message; the model answers with the
      corrected code in a fenced block, which runs against a hidden test with the real toolchain
      (bench/core/runners.py). Items: bench/tasks/fix_easy/<lang>.py. Swift runs on macOS only;
      elsewhere its rows are "skipped" (infra), never a fail.
hard  multi-turn, cross-file: the failing test output, then read-only tools (list_files,
      read_file, search) over a small project and one submit_fix with the complete new contents
      of ONE file. Gate: the submission is merged, the hidden tests are restored as written, and
      TEST_CMD must exit 0 with every named test passing. Items: bench/tasks/fix_hard/<item>.py.

  bench.py agentic-fix validate [--tier easy|hard|all] [item ...]
  bench.py agentic-fix run [--tier easy|hard|all] [item ...] [--samples K --concurrency N
                           --resume RUN_DIR --max-turns T]
Item sets fix-easy@<hash> and fix-hard@<hash> (separate runs); categories easy/<lang>, hard/<lang>.
"""
import argparse
import hashlib
import json
import os
import re
import shutil
import sys

from bench.core import client, results, tools
from bench.core.runners import RUNNERS, extract_code, work_dir
from bench.tasks import agentic_multitask as harness
from bench.tasks import fix_easy, fix_hard

INSTRUMENT = "agentic-fix"
EASY_MAX_TOKENS, HARD_MAX_TOKENS = 8000, 4000  # instrument defaults; the lane overrides
TEMPERATURE = 0.0
MAX_TURNS = 24
TEST_TIMEOUT = 300
LANG_NAMES = {"go": "Go", "rust": "Rust", "ts": "TypeScript", "swift": "Swift", "python": "Python",
              "sh": "Bash", "sql": "SQL (SQLite)"}


# ============================================================ easy tier

def easy_messages(t):
    lang = LANG_NAMES[t["lang"]]
    sysmsg = ("You are an expert %s developer. Fix the bug in the code. Respond with ONLY the corrected "
              "code in a single fenced code block. Keep the same names and signatures. Do NOT add tests, "
              "a main function, explanations, or extra declarations." % lang)
    ctx = "%s\n\n" % t["context"] if t.get("context") else ""
    user = ("%sThe following %s code has a bug. %s\n\n```%s\n%s```\n\nReturn the corrected code."
            % (ctx, lang, t["symptom"], t["lang"], t["buggy"]))
    return [{"role": "system", "content": sysmsg}, {"role": "user", "content": user}]


def easy_item_set(items):
    defs = [dict(t, messages=easy_messages(t)) for t in sorted(items, key=lambda t: t["id"])]
    return "fix-easy@%s" % hashlib.sha256(json.dumps(defs, sort_keys=True).encode()).hexdigest()[:12]


def _easy_attempt(store, lane, t, k):
    def grade(resp):
        code = extract_code(client.content(resp))
        ok, detail = (False, "empty answer") if not code.strip() else \
            RUNNERS[t["lang"]](t, code, work_dir(store.run_id, t["id"], k))
        row = {"correct": None if ok is None else bool(ok), "code_head": code[:400],
               "detail_head": (detail or "")[:400]}
        if ok is None:  # toolchain unavailable: not a model failure
            row["status"] = "skipped"
        return row
    results.call_attempt(store, lane, t["id"], k, "easy/" + t["lang"], easy_messages(t), grade,
                         max_tokens=EASY_MAX_TOKENS, temperature=TEMPERATURE)


def easy_validate(items, log=print):
    ok_all = True
    for t in items:
        bug_pass, bug_out = RUNNERS[t["lang"]](t, t["buggy"])
        fix_pass, fix_out = RUNNERS[t["lang"]](t, t["fix"])
        if bug_pass is None or fix_pass is None:
            log("[SKIP] %-22s %s" % (t["id"], (fix_out or bug_out).splitlines()[0]))
            continue
        ok = (not bug_pass) and fix_pass
        ok_all = ok_all and ok
        log("[%s] %-22s buggy_fails=%-5s fix_passes=%s" % ("OK " if ok else "BAD", t["id"], not bug_pass, fix_pass))
        if bug_pass:
            log("     !! buggy code PASSED the test")
        if not fix_pass:
            log("     !! reference fix FAILED:\n     " + fix_out.replace("\n", "\n     ")[:800])
    return ok_all


def easy_run(items, a):
    """items: the whole tier (it defines the item set); a.items selects within it."""
    plan = lambda _args: (easy_item_set(items), [(t["id"], t) for t in items])  # noqa: E731
    _store, summary = results.run_attempts(INSTRUMENT, results.run_args(a, tier="easy"), plan,
                                           _easy_attempt, resume=a.resume)
    return 3 if summary["stopped"] else 0


# ============================================================ hard tier

HARD_SYSTEM = ("You are a coding agent working in a {lang} project. A test is failing. Use the tools to "
               "explore the codebase, find the root cause (it may span multiple files), and fix it. When "
               "you are confident, call submit_fix with the COMPLETE corrected contents of the single file "
               "that needs changing. Keep every other file untouched and preserve all names and "
               "signatures. Do not submit until you have read enough to be sure.")
HARD_USER = "`{cmd}` fails in this project:\n\n```\n{out}\n```\n\nInvestigate with the tools and submit a fix."
NUDGE = "You must either call a tool to keep investigating or call submit_fix. Do not answer in prose."
BAD_JSON = "ERROR: invalid JSON args ({e}); re-emit the {name} call."
CUT_OFF_MSG = ("ERROR: your output hit the max_tokens limit and this call was cut off; it was NOT "
               "executed. Re-issue it.")
HARD_TOOLS = [
    {"type": "function", "function": {
        "name": "list_files", "description": "List all file paths in the project.",
        "parameters": {"type": "object", "properties": {}}}},
    {"type": "function", "function": {
        "name": "read_file", "description": "Return the full contents of one file.",
        "parameters": {"type": "object", "properties": {
            "path": {"type": "string", "description": "Project-relative file path"}}, "required": ["path"]}}},
    {"type": "function", "function": {
        "name": "search", "description": "Regex-search the whole project; returns matching path:line: text.",
        "parameters": {"type": "object", "properties": {"pattern": {"type": "string"}}, "required": ["pattern"]}}},
    {"type": "function", "function": {
        "name": "submit_fix",
        "description": "Submit the complete corrected contents of ONE file to fix the failing test. Call "
                       "this exactly once when you have the fix.",
        "parameters": {"type": "object", "properties": {
            "path": {"type": "string"},
            "content": {"type": "string", "description": "Full new file contents"}},
            "required": ["path", "content"]}}},
]


def run_tests(ws, item, files):
    """Materialize `files` into a clean work dir and run the item's TEST_CMD -> (rc_ok, output)."""
    for name in os.listdir(ws.dir):
        p = os.path.join(ws.dir, name)
        shutil.rmtree(p) if os.path.isdir(p) and not os.path.islink(p) else os.remove(p)
    ws.materialize(files)
    r = ws.run(list(item.TEST_CMD), TEST_TIMEOUT)
    out = (r.out + "\n" + r.err).strip()
    return (not r.timed_out and r.rc == 0), ("TIMEOUT\n" + out if r.timed_out else out)


def score(ws, item, path, content):
    """Merge one submitted file, restore the hidden tests, run them -> (passed, detail)."""
    files = dict(item.PROJECT, **{path: content})
    files.update({h: item.PROJECT[h] for h in item.HIDDEN})
    ok, out = run_tests(ws, item, files)
    passed_names = set(re.findall(item.PASS_RE, out, re.M))
    missing = [t for t in item.TESTS if t not in passed_names]
    d = {"tests_passed": len(passed_names & set(item.TESTS)), "tests": len(item.TESTS)}
    if missing:
        d["tests_not_passed"] = missing
    passed = ok and not missing
    if not passed:
        d["test_output"] = out[-800:]
    return passed, d


def _hard_toolset(item):
    def st(ws):
        ws.state.setdefault("reads", [])
        ws.state.setdefault("searches", 0)
        return ws.state

    def list_files(ws, args):
        return "\n".join(sorted(item.PROJECT))

    def read_file(ws, args):
        path = args.get("path", "")
        if not isinstance(path, str):
            raise tools.ToolError("`path` must be a string")
        st(ws)["reads"].append(path)
        return item.PROJECT.get(path, f"ERROR: no such file {path!r}. Use list_files.")

    def search(ws, args):
        st(ws)["searches"] += 1
        pat = args.get("pattern", "")
        if not isinstance(pat, str):
            raise tools.ToolError("`pattern` must be a string")
        try:
            rx = re.compile(pat)
        except re.error as e:
            return f"ERROR: bad regex: {e}"
        hits = [f"{p}:{i}: {line.strip()}" for p, c in sorted(item.PROJECT.items())
                for i, line in enumerate(c.splitlines(), 1) if rx.search(line)]
        return "\n".join(hits) if hits else "(no matches)"

    def submit_fix(ws, args):
        path, content = args.get("path", ""), args.get("content", "")
        if not isinstance(path, str) or not path.strip():
            raise tools.ToolError("submit_fix needs `path`: the project-relative file to replace")
        norm = os.path.normpath(path)
        if os.path.isabs(path) or norm == "." or norm.startswith(".."):
            raise tools.ToolError(f"path {path!r} is not a file inside the project; use list_files")
        if not isinstance(content, str):
            raise tools.ToolError("`content` must be the full file contents as a string")
        st(ws)["submission"] = (norm, content)
        return tools.ToolResult("fix received", stop=True)

    return tools.Toolset(
        "fix-hard-readonly", HARD_TOOLS,
        {"list_files": list_files, "read_file": read_file, "search": search, "submit_fix": submit_fix},
        cut_off_msg=CUT_OFF_MSG, unknown_fmt="ERROR: unknown tool {name}",
        commands={"test_gate": " ".join(item.TEST_CMD) + " (hidden tests restored)"})


def hard_task(item):
    def user(ws):
        if shutil.which(item.TOOL) is None:
            raise tools.InfraError(f"{item.TOOL} not on PATH")
        _, out = run_tests(ws, item, item.PROJECT)
        return HARD_USER.format(cmd=" ".join(item.TEST_CMD), out=out[-1500:])

    def gates(ws, port=None):
        sub = ws.state.get("submission")
        if not sub:
            return {"test": False}, {"reason": "no fix submitted (turn cap or error)"}
        passed, d = score(ws, item, *sub)
        return {"test": passed}, d

    def extra(ws):
        sub = ws.state.get("submission")
        return {"reads": ws.state.get("reads", []), "searches": ws.state.get("searches", 0),
                "submitted_path": sub[0] if sub else None,
                "fixed_file": sub[0] in item.FIX if sub else None}

    def validate(ws, port=None):
        if shutil.which(item.TOOL) is None:
            print(f"{item.ITEM_ID}: SKIP, {item.TOOL} not on PATH")
            return True, {"skipped_no_toolchain": True}, {}
        (fpath, fcontent), = item.FIX.items()
        bug_ok, bug_out = run_tests(ws, item, item.PROJECT)
        g = {"buggy_fails": not bug_ok,
             "fix_passes": score(ws, item, fpath, fcontent)[0],
             "gate_rejects_buggy": not score(ws, item, fpath, item.PROJECT[fpath])[0],
             "gate_rejects_test_rewrite": not score(ws, item, item.HIDDEN[0], "")[0],
             "wrong_rejected": not any(score(ws, item, *next(iter(w.items())))[0]
                                       for w in getattr(item, "WRONG", ()))}
        return all(g.values()), g, {"buggy_output": bug_out[-300:]}

    return harness.AgenticTask(
        item_id=item.ITEM_ID, category="hard/" + item.LANG, plan="", starter={},
        toolset=_hard_toolset(item), gates=gates, gate_names=("test",), validate=validate,
        system_tmpl=HARD_SYSTEM.format(lang=LANG_NAMES[item.LANG]), user=user, nudge=NUDGE,
        give_up_after=None, done_word=False, bad_json_fmt=BAD_JSON, trunc_fmt=None,
        max_tokens=HARD_MAX_TOKENS, temperature=TEMPERATURE, extra=extra,
        source_files=(os.path.abspath(item.__file__),), prune=("target", "node_modules", ".build"))


def hard_tasks():
    return [hard_task(m) for m in fix_hard.load()]


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

def main(argv=None):
    ap = argparse.ArgumentParser(prog="bench.py " + INSTRUMENT)
    sub = ap.add_subparsers(dest="cmd")
    for name in ("validate", "run"):
        sp = sub.add_parser(name)
        sp.add_argument("--tier", choices=("easy", "hard", "all"), default="all")
        sp.add_argument("ids", nargs="*", help="item ids (default: all in the tier)")
        if name == "run":
            results.add_run_args(sp)
            sp.add_argument("--max-turns", type=int, default=None)
    a = ap.parse_args(sys.argv[1:] if argv is None else argv)
    if a.cmd is None:
        ap.print_help()
        sys.exit(1)
    ids = set(a.ids) | {i for i in (getattr(a, "items", "") or "").split(",") if i}
    easy_all, hard_all = fix_easy.load(), hard_tasks()
    known = {t["id"] for t in easy_all} | {t.item_id for t in hard_all}
    if ids - known:
        raise SystemExit("unknown items: %s" % ", ".join(sorted(ids - known)))
    tiers = ("easy", "hard") if a.tier == "all" else (a.tier,)
    easy = [t for t in easy_all if not ids or t["id"] in ids] if "easy" in tiers else []
    hard = [t for t in hard_all if not ids or t.item_id in ids] if "hard" in tiers else []
    if a.cmd == "validate":
        ok = easy_validate(easy) if easy else True
        ok = (harness.run_validate(hard) if hard else True) and ok
        sys.exit(0 if ok else 1)
    if a.resume and a.tier == "all":
        raise SystemExit("--resume needs --tier easy or --tier hard")
    rc = 0
    if easy:  # the item set is always the whole tier; ids select within it
        a.items = ",".join(t["id"] for t in easy) if ids else ""
        rc = easy_run(easy_all, a)
    if hard and rc == 0:
        max_turns = a.max_turns or int(os.environ.get("MAX_TURNS") or MAX_TURNS)
        harness.run_instrument(INSTRUMENT, "fix-hard", hard_all, samples=a.samples,
                               concurrency=a.concurrency, resume=a.resume, max_turns=max_turns,
                               items=[t.item_id for t in hard] if ids else None)
    sys.exit(rc)


if __name__ == "__main__":
    main()