Tutorial
Evaluate coding agents on your own repository
Run Claude Code and Codex headless against 10 closed issues from your repo, then score them with the real fix's tests and a blind review rubric.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
The most useful comparison of coding agents is the one you run on your own code. Pick 10 issues your team has already closed with a fix and a test. For each one, give an agent the repository as it was before the fix and the issue text, run it headless, then score the result two ways: do the tests from the real fix pass, and would a reviewer on your team accept the diff? Run every agent the same way, review the diffs blind, and you have evidence for your codebase rather than someone else’s benchmark.
This tutorial builds that harness in about 110 lines of Python, using Claude Code and Codex as the two agents. It is different from evaluating AI agents, which tests an agent you build; here you are testing agents you buy. Commands and flags were checked against the Claude Code CLI reference and the Codex non-interactive docs on 25 November 2026 (Claude Code 2.1.331).
Why your own repository
Public benchmarks such as SWE-bench measure agents on popular open-source projects. They are useful for tracking the field and useless for deciding what your team should use, for three reasons:
- Your code is different. Your framework, your conventions, your build. An agent that does well on a well-known Python library may struggle with your monorepo’s build scripts.
- Contamination. Public repositories and their fixes are likely to be in a model’s training data. Your private code is not.
- Your bar is different. “The tests pass” is necessary, not sufficient. A fix that passes but rewrites a module nobody asked it to touch would be rejected in your code review.
1. Pick 10 closed issues
Look through your closed issues and merged pull requests for ones that:
- were fixed in a single commit (or a squashed merge) that added or changed a test proving the fix,
- have issue text a new colleague could act on, without a Slack thread you cannot include,
- run on your normal test command in a few minutes,
- span what your team actually does: a few bug fixes, a small feature, a refactor, something in an area people find hard.
Skip issues whose fix was mainly a dependency upgrade or config change; they test something else. Ten is enough to see large differences and small enough to review by hand. Write them into bench-tasks.json at the root of your repository:
[
{
"id": "issue-12",
"title": "Order total ignores quantity",
"body": "total() in src/prices.py adds up price but ignores the qty field, so 3 mugs at 2 cost 2.",
"base": "<commit before the fix>",
"fix": "<the fix commit>",
"tests": ["tests/test_qty.py"],
"test_command": "python -m pytest -q"
}
]
base is the commit the agent starts from, usually the fix commit’s parent (git rev-parse <fix>^). tests lists the test files the fix added or changed; the agent never sees them. Copy title and body from the issue as written, including its vagueness, because that is what an agent gets in real use. Do not paste in hints from the fix.
2. Write the harness
Create bench.py next to bench-tasks.json. Here it is in full:
"""Run coding agents headless against closed issues and score them with the fix's own tests."""
import csv
import json
import random
import shlex
import subprocess
import sys
import time
from pathlib import Path
REPO = Path.cwd()
RUNS = REPO.parent / f"{REPO.name}-bench" # outside the repo, so runs never touch it
AGENTS = {
# Claude Code: edits allowed, shell limited to the test runner, no prompts, capped turns.
"claude": lambda prompt: [
"claude", "-p", prompt,
"--permission-mode", "dontAsk",
"--allowedTools", "Read,Grep,Glob,Edit,Write,Bash(python -m pytest *)",
"--max-turns", "30",
"--output-format", "json",
],
# Codex: workspace-write sandbox, nothing persisted between runs.
"codex": lambda prompt: [
"codex", "exec", "--sandbox", "workspace-write", "--ephemeral", prompt,
],
}
PROMPT = """Fix this issue from our tracker. Make the smallest change that fixes it,
follow the existing code style, and add or update tests if needed. Do not commit.
Issue: {title}
{body}"""
def git(*args: str, cwd: Path = REPO) -> str:
return subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, text=True).stdout
def fresh_checkout(commit: str, work: Path) -> None:
"""Copy the repo at `commit` into a new repo with no history, so the agent cannot find the fix in git log."""
subprocess.run(["rm", "-rf", str(work)], check=True)
work.mkdir(parents=True)
archive = subprocess.run(["git", "archive", "--format=tar", commit], cwd=REPO, check=True, capture_output=True)
subprocess.run(["tar", "-x", "-C", str(work)], input=archive.stdout, check=True)
git("init", "-q", cwd=work)
git("add", "-A", cwd=work)
git("-c", "user.name=bench", "-c", "user.email=bench@localhost", "commit", "-qm", "base", cwd=work)
def run_one(agent: str, task: dict, timeout: int) -> dict:
work = RUNS / agent / task["id"]
fresh_checkout(task["base"], work)
cmd = AGENTS[agent](PROMPT.format(**task))
start = time.monotonic()
try:
p = subprocess.run(cmd, cwd=work, capture_output=True, text=True, timeout=timeout)
status = "ok" if p.returncode == 0 else f"exit {p.returncode}"
(work.parent / f"{task['id']}.log").write_text(p.stdout + p.stderr)
except subprocess.TimeoutExpired:
status = "timeout"
seconds = round(time.monotonic() - start)
# Keep the agent's change, untracked files included, before we touch the tree.
git("add", "-A", cwd=work)
diff = git("diff", "--cached", cwd=work)
(work.parent / f"{task['id']}.diff").write_text(diff)
# Bring in the tests from the real fix and run them. The agent never saw these.
for path in task["tests"]:
(work / path).parent.mkdir(parents=True, exist_ok=True)
(work / path).write_text(git("show", f"{task['fix']}:{path}"))
t = subprocess.run(shlex.split(task["test_command"]), cwd=work, capture_output=True, text=True)
return {
"agent": agent, "task": task["id"], "status": status, "seconds": seconds,
"tests_pass": t.returncode == 0,
"lines_changed": sum(1 for l in diff.splitlines() if l[:1] in "+-" and l[:3] not in ("+++", "---")),
}
def review_packet(rows: list[dict]) -> None:
"""Write diffs under random labels so reviewers do not know which agent made which."""
out = RUNS / "review"
out.mkdir(exist_ok=True)
key = {}
for task in sorted({r["task"] for r in rows}):
agents = [r["agent"] for r in rows if r["task"] == task]
random.shuffle(agents)
for label, agent in zip("ABCD", agents):
(out / f"{task}-{label}.diff").write_text((RUNS / agent / f"{task}.diff").read_text())
key[f"{task}-{label}"] = agent
(RUNS / "review-key.json").write_text(json.dumps(key, indent=2))
def main() -> None:
tasks = json.loads((REPO / "bench-tasks.json").read_text())
agents = sys.argv[1:] or list(AGENTS)
RUNS.mkdir(exist_ok=True)
rows = [run_one(a, t, timeout=900) for t in tasks for a in agents]
with open(RUNS / "results.csv", "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0]))
w.writeheader()
w.writerows(rows)
for a in agents:
mine = [r for r in rows if r["agent"] == a]
passed = sum(r["tests_pass"] for r in mine)
print(f"{a:<8} tests pass {passed}/{len(mine)} median time {sorted(r['seconds'] for r in mine)[len(mine) // 2]} s")
review_packet(rows)
if __name__ == "__main__":
main()
The decisions that make the comparison fair:
- A fresh copy with no history.
fresh_checkoutexports the tree atbasewithgit archiveinto a new repository with a single commit. A worktree or clone would carry every later commit, and an agent that runsgit log --allcould find the fix. The cost is that agents cannot usegit blameor history; that is the same for every agent. - The same prompt for every agent. Only the command differs. If you have an
AGENTS.mdorCLAUDE.md, it is part of the tree atbaseand every agent reads what it would read in real use. - Held-out tests. The fix’s tests are written into the tree only after the agent finishes. An agent that writes its own test for the issue gets no credit for it; the question is whether its change makes the real test pass.
- Comparable permissions. Claude Code runs with
--permission-mode dontAsk, which denies anything not pre-approved instead of waiting for a prompt, and--allowedToolslimits the shell to the test runner. Codex runscodex execwith--sandbox workspace-write, which lets it edit the workspace, and--ephemeralso no session files persist between runs. Change the test command in both places to match your project. - A hard timeout. Fifteen minutes per task. Record timeouts as failures; an agent that loops is a real result.
3. Check the harness before you spend agent time
A scoring harness has bugs like any other code, and a bug here produces convincing nonsense. Calibrate it with two fake agents whose scores you already know: an “oracle” that applies the real fix, which must score 100%, and a “noop” that changes nothing, which must score 0%. Create check_harness.py:
"""Run bench.py with two fake agents: 'oracle' copies the real fix's source, 'noop' does nothing."""
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent))
import bench
tasks = {t["id"]: t for t in json.loads((bench.REPO / "bench-tasks.json").read_text())}
def oracle(prompt):
fix = next(t["fix"] for t in tasks.values() if t["title"] in prompt)
return ["sh", "-c", f"git -C {bench.REPO} show {fix}:src/prices.py > src/prices.py"]
bench.AGENTS = {"oracle": oracle, "noop": lambda prompt: ["true"]}
sys.argv = ["bench.py"]
bench.main()
Change src/prices.py to the source file your first task’s fix changed (for a fix that touches several files, check out each). On our two-task demo repository it printed:
oracle tests pass 2/2 median time 0 s
noop tests pass 0/2 median time 0 s
If the noop agent passes anything, the “held-out” tests are not testing the fix: perhaps they passed before it too. Drop that task or pick a better test. If the oracle fails anything, the test command or the file list is wrong.
4. Run the agents
python bench.py claude codex
Each task runs once per agent, one after another. Expect minutes per task. While it runs, each agent’s log goes to <repo>-bench/<agent>/<task>.log; Claude Code’s JSON output includes total_cost_usd, which you can sum for the cost per run.
Run the whole set more than once if you can afford it. Agent results vary between runs, and one run of 10 tasks cannot tell 6/10 from 7/10. Three runs per agent and a look at which tasks flip between pass and fail tell you far more than one.
5. Review the diffs blind
Tests answer “does it work”. Your reviewers answer “would we merge it”. review_packet writes each task’s diffs to <repo>-bench/review/ as issue-12-A.diff, issue-12-B.diff and so on, with the key to which agent made which in review-key.json. Give the review folder, not the key, to the person who would normally review that code, with a short rubric. Score each item 0, 1 or 2:
| Criterion | 0 | 1 | 2 |
|---|---|---|---|
| Correctness | Wrong or incomplete | Fixes the issue with a gap | Fixes it, edge cases handled |
| Scope | Touches unrelated code | Some unneeded changes | Only what the issue needs |
| Style | Ignores project conventions | Minor deviations | Reads like the team wrote it |
| Tests | None, or tests that pass either way | A test, but weak | A test that fails without the fix |
| Mergeable | Would reject | Would merge after changes | Would merge as is |
Blind review matters. People who prefer one tool rate its output more kindly, usually without meaning to. The reviewing AI-written code article lists what to look for.
6. Read the results
Put the test results and the rubric scores in one table, one row per task and agent, and look for patterns rather than a winner:
- Where does each agent fail? If one agent fails every task in your legacy billing module, that is the finding, more than its total.
- Passing but unmergeable. Count diffs that pass the tests but score 0 on scope or mergeable. That is review time you would spend in real use.
- Time and cost per accepted fix. Divide each agent’s total time and cost by the number of diffs your reviewer would merge.
- Variance. Tasks that pass in one run and fail in the next show where an agent is guessing.
Write the result up with the date, the agent versions and models, and the task list, so it can be repeated when the tools change. They change monthly.
Pitfalls
Issue text that gives the answer away. “Change line 4 of prices.py to multiply by qty” tests typing, not problem solving. Use the issue as reported.
Held-out tests that already pass. If the fix’s test passes on base, it does not test the fix. The noop check in step 3 catches this.
Different instructions per agent. If one agent gets a tuned prompt or an extra rules file, you are comparing your prompting, not the agents.
Leaking history. Running agents in a clone or worktree of the full repository lets them find the fix in git log. Use the history-free copy.
Declaring a winner from one run. Ten tasks, one run each, is a sample of ten. Use it to spot large differences and patterns, not to rank agents by a point.
Next steps
- Set up the headless runs safely in CI with Claude Code and Codex in GitHub Actions.
- Compare the products beyond test scores in Claude Code vs Codex vs Cursor.
- Turn the findings into a team rollout with the coding agents for teams path.
- Build evals for an agent you write yourself with evaluate AI agents.
Covers
- Tools
Check your understanding
Evaluate coding agents on your repo quiz
Why your own repository beats a public benchmark, choosing closed issues, history-free copies, held-out tests, calibrating with oracle and noop agents, blind review and reading the results.
8 questions · pass mark 70%
Review
Related
- Run coding agents headless in CI
Run claude -p and codex exec in GitHub Actions with pinned versions, narrow permissions, scoped secrets and separate jobs for writing back to the pull request.
- Evaluate AI agents: outcomes, trajectories and tool use
Build an agent eval harness that checks the final state, the tool-call trajectory and a judged transcript, run each task several times and read the traces.
- Claude Code vs Codex vs Cursor
One task walked through in Claude Code, Codex and Cursor, plus where each runs, how it is priced, its skills and MCP support, and who each one suits.
- Reviewing AI-written code: what to look for
The ways agent-written diffs fail, a practical review checklist, and how to set up the work so review stays manageable.
- Rolling out coding agents to a team
Roll out coding agents to a team: shared instruction files, permissions and hooks, spec-first work, agent review in CI and vetted Agent Skills for everyone.