Best-of-N for coding agents: run N attempts, keep the one that passes
Last updated
What N attempts gain depends on who picks
Perfect selector
Real selectors
Best-of-N means giving the same prompt to a coding agent N times, letting each attempt work in its own copy of the repository, then keeping the one attempt that scores best on a check you trust: the test suite first, then the size of the diff, the linter, or a second model acting as judge. OpenAI Codex has the first half built in: codex cloud exec --attempts runs 1 to 4 attempts in Codex Cloud. It does not pick the winner for you. Claude Code has no attempts flag at all; you build it from worktrees and headless runs.
The research agrees on one point: generating attempts is easy, and the gain depends on how well you choose among them. Below: what each tool offers, what the papers measured, what N costs, and a short script that runs N attempts in git worktrees and ranks them by npm test, with its real output.
What is best-of-N for coding agents?
Three steps, always the same:
- Generate. Start N runs of the same agent on the same prompt, from the same commit. Each run needs its own working directory, or the attempts overwrite each other.
- Evaluate. Score every attempt with something automatic: tests, type check, lint, diff size, a judge model, or agreement between attempts.
- Select. Keep the best one, apply its diff, throw the others away.
Parallel tasks split a backlog, one agent per issue; best-of-N spends N agents on one issue so that one of them gets it right. The machinery is the same, one isolated checkout per agent, so the setups in how to run Claude Code agents in parallel and Codex parallel tasks apply here too.
Papers call step 1 repeated sampling, and the share of problems where at least one attempt is correct coverage, or pass@k. Coverage is what a perfect selector would give you; the gap between it and what you get is the selector's.
Does Codex have best-of-N?
Yes, for cloud tasks. OpenAI's CLI reference lists codex cloud exec with one option for it:
--attempts1-4: Number of assistant attempts (best-of-N) Codex cloud should run.
--env, the Codex Cloud environment ID, is required, and codex cloud is marked "Experimental" in the reference on 31 October 2026. The attempts run in Codex Cloud, not on your machine.
What it doesn't do is choose. Daniel Vaughan's guide to the flag puts it directly: "Codex Cloud does not currently score or rank attempts for you." You review the attempts, in the web interface or from the terminal, and apply the one you want. codex apply takes a task ID and applies "the latest diff generated by a Codex cloud chat to your local working tree". If you want selection by tests, you script it yourself, which is what the rest of this page does.
Four attempts is the ceiling, and OpenAI's pricing page warns that "Cloud tasks may use more of your allowance than local messages." Locally, codex exec runs Codex non-interactively, so the script below can drive Codex CLI too.
Can you do best-of-N with Claude Code?
Not with a flag: the Claude Code CLI reference has no option to run N attempts of one prompt (checked on 31 October 2026). The pieces to build it are all documented:
- Worktrees.
claude --worktree <name>starts a session in its own git worktree. Anthropic's docs: worktrees "give each session a separate git checkout, so parallel sessions each edit their own copy of the files." - Headless runs.
claude -p "<prompt>"runs one non-interactive session and exits, which makes it scriptable: N of them in a loop, one per worktree. - Subagents in worktrees. Ask Claude to "use worktrees for your agents", or set
isolation: worktreein a custom subagent's frontmatter, and one session can spawn N subagents on the same task. The judge is then the session that wrote the prompt. - Cloud sessions. Each
claude --cloudtask "creates its own cloud session that runs independently", so you can start the same task several times on Anthropic's infrastructure and compare the branches.
None of these ranks the attempts. Unattended attempts also need permission to run commands; read how to use --dangerously-skip-permissions safely before you start N of them on your laptop.
How much does best-of-N improve results?
Each source below separates what the attempts contain (coverage) from what a selector picks. Public benchmarks, models of their date: they show the shape of the gain, not what your repository will see.
| Source (date) | Task | 1 attempt | N attempts, perfect selector | N attempts, real selector |
|---|---|---|---|---|
| Chen et al., Codex paper (Jul 2021) | HumanEval, Codex-S | 37.7% | 77.5% (100 samples, pick one that passes the unit tests) | 44.5% (100 samples, pick by mean log-probability) |
| Brown et al., Large Language Monkeys (Jul 2024) | SWE-bench Lite, DeepSeek-Coder-V2-Instruct | 15.9% | 56% (250 samples) | not the paper's focus; majority voting and reward models "plateau beyond several hundred samples" on tasks without an automatic verifier |
| Ehrlich et al., CodeMonkeys (Jan 2025) | SWE-bench Verified, Claude 3.5 Sonnet | — | 69.8% (10 candidates per issue) | 57.4% (tests written by the model, voting, then a selection pass); random pick: 45.8% |
| Anthropic, Claude 4 launch (May 2025) | SWE-bench Verified | 72.5% (Opus 4), 72.7% (Sonnet 4), standard score | not published | 79.4% and 80.2%: "sample multiple parallel attempts", drop patches that break visible regression tests, pick with "an internal scoring model" (number of attempts not stated) |
| Kim et al. (Apr 2026) | SWE-bench Verified (mini-SWE-agent) / Terminal-Bench 2.0 (Terminus 1), Claude Opus 4.5 | 70.9% / 46.9%, baseline | not in the abstract | 77.6% / 59.1%, with summaries of each attempt, tournament voting and refinement from earlier attempts (16 rollouts per round, two rounds) |
Three things to take from it:
- The selector decides. In the Codex paper, 100 samples picked by log-probability gained 6.8 points; the same 100 samples picked by unit tests gained 39.8 (calculation: 44.5 − 37.7 and 77.5 − 37.7). CodeMonkeys' selector closes "approximately half of the gap between random and oracle selection".
- Coverage keeps rising with N, slowly. Large Language Monkeys found the relation between coverage and the number of samples "often log-linear": if that holds for your tasks, going from 4 to 8 attempts adds about as much as going from 2 to 4, for twice the cost.
- Tests are the cheapest good selector. Where answers can be checked automatically, "these increases in coverage directly translate into improved performance" (Large Language Monkeys). Anthropic's recipe starts by dropping patches that break visible tests.
How do you pick the best attempt automatically?
Stack the checks from cheapest to most expensive, dropping attempts at each stage:
| Check | What it catches | What it misses | Cost per attempt |
|---|---|---|---|
| Test suite passes | Broken code, regressions | Behaviour no test covers; an agent that edits or deletes tests | One test run |
Tests untouched (git diff -- test/) |
Attempts that make the suite pass by changing it | Nothing on its own; it's a guard | Free |
| Lint and type check | Type errors, style drift | Wrong logic | One run |
| Diff size | Sprawl, unrelated rewrites | A small diff that is wrong | Free |
| Agreement between attempts | Outliers; CodeMonkeys votes with tests the model wrote | All attempts wrong the same way | Running tests across attempts |
| LLM judge reading the diffs | Readability, intent, design | Its own biases; it costs tokens and reads N diffs | One model call over N diffs |
The second row is the one people forget: to an agent told to "make every test pass", deleting the failing tests is a solution. The demo below includes such an attempt, and npm test exits 0 on it.
When several attempts pass everything, prefer the smallest diff, then let a human or a judge model read the two or three survivors. That review is the part best-of-N doesn't automate.
A minimal best-of-N script with git worktrees and npm test
We ran this on 31 October 2026 in /private/tmp/bon-demo (macOS 27.2 on arm64, git 2.50.1, Node 20.19.5). The repository has one function, slugify, and four tests run by node --test; one passes before any change. The prompt asks the agent to make all four pass.
To spend no tokens and keep the run reproducible, the agent is a stand-in: fake-agent.sh ignores the prompt and applies a different edit per attempt (sed, or a rewrite of the file). Attempt 1 fixes spacing only. Attempt 2 is a correct one-line fix. Attempt 3 fixes spacing and deletes the two tests it can't make pass. Attempt 4 is correct but rewrites the whole file. Attempt 5 leaves a syntax error. Real agents produce the same kinds of results, just not on demand.
#!/usr/bin/env bash
# Usage: best-of-n.sh N "prompt" (run from the repository root)
# Runs N attempts of the same prompt, one git worktree each, then ranks them by `npm test`.
set -euo pipefail
N=${1:?usage: best-of-n.sh N "prompt"}
PROMPT=${2:?usage: best-of-n.sh N "prompt"}
AGENT=${AGENT:?set AGENT to the agent command} # e.g. AGENT=/path/to/fake-agent.sh
BASE=$(git rev-parse HEAD)
RUNS=$(cd .. && pwd)/bon-runs
mkdir -p "$RUNS"
# 1. N worktrees from the same commit, one agent each, all at once.
for i in $(seq 1 "$N"); do
git worktree add -q -b "try-$i" "$RUNS/try-$i" "$BASE"
(cd "$RUNS/try-$i" && ATTEMPT=$i $AGENT "$PROMPT" > "$RUNS/try-$i.log" 2>&1) &
done
wait
# 2. Score each attempt: tests, diff size, edits to the tests themselves.
printf "try\tpass\tfail\tlines\ttests_edited\n" > "$RUNS/scores.tsv"
for i in $(seq 1 "$N"); do
d="$RUNS/try-$i"
git -C "$d" add -A
lines=$(git -C "$d" diff --cached --numstat "$BASE" | awk '{s += $1 + $2} END {print s + 0}')
tests_edited=$(git -C "$d" diff --cached --name-only "$BASE" -- test | wc -l | tr -d ' ')
out=$(cd "$d" && npm test --silent 2>&1 || true)
pass=$(awk '/^# pass/ {print $3}' <<< "$out")
fail=$(awk '/^# fail/ {print $3}' <<< "$out")
printf "%s\t%s\t%s\t%s\t%s\n" "$i" "${pass:-0}" "${fail:-0}" "$lines" "$tests_edited" >> "$RUNS/scores.tsv"
done
column -t "$RUNS/scores.tsv"
# 3. Pick: tests untouched, zero failures, most passes, smallest diff.
best=$(tail -n +2 "$RUNS/scores.tsv" | awk -F'\t' '$5 == 0 && $3 == 0' | sort -t$'\t' -k2,2nr -k4,4n | head -1 | cut -f1)
if [ -z "$best" ]; then echo "no attempt passes without editing the tests"; exit 1; fi
echo "best: try-$best"
git -C "$RUNS/try-$best" diff --cached --stat "$BASE"
The run, with five attempts:
$ AGENT=/private/tmp/bon-demo/fake-agent.sh ../best-of-n.sh 5 "Make every test in test/slugify.test.js pass"
try pass fail lines tests_edited
1 2 2 2 0
2 4 0 2 0
3 2 0 4 1
4 4 0 14 0
5 0 1 2 0
best: try-2
slugify.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
lines is lines added plus lines removed. Attempt 5 shows pass 0, fail 1 because Node counts the test file that failed to load (SyntaxError: Unexpected token '.') as one failed test. Attempt 4 ties with attempt 2 on tests and loses on diff size, 14 lines against 2.
Attempt 3 is why the tests_edited column exists. Selecting on the exit code of npm test alone would have kept it:
$ for i in 1 2 3 4 5; do (cd ../bon-runs/try-$i && npm test --silent >/dev/null 2>&1; echo "try-$i: npm test exit $?"); done
try-1: npm test exit 1
try-2: npm test exit 0
try-3: npm test exit 0
try-4: npm test exit 0
try-5: npm test exit 1
The attempts are staged, not committed, so apply the winner from the main checkout with git -C ../bon-runs/try-2 diff --cached | git apply (we ran it: slugify.js modified, 4 of 4 tests pass). To clean up, git worktree remove --force ../bon-runs/try-$i and git branch -D try-$i for each attempt.
For a real agent, set AGENT to its non-interactive mode, claude -p for Claude Code or codex exec for Codex CLI, with the permission flag that lets it edit and run tests unattended (see each tool's docs; we did not run real agents through this script). The stand-in hides two things: real attempts take minutes, so add a time limit per attempt, and worktrees don't separate ports or databases.
The five attempts of the demo, and what the script did with each
| Attempt | What the attempt did | Score, and what happened |
|---|---|---|
| Attempt 1 | Fixes spacing only | Gap: 2 pass, 2 fail |
| Attempt 2 | A correct one-line fix | Strength: 4 pass, 0 fail, 2 lines: best |
| Attempt 3 | Fixes spacing and deletes the two tests it can't make pass | Gap: npm test exits 0, but tests_ |
| Attempt 4 | Correct, but rewrites the whole file | Partial: 4 pass, 0 fail: loses on diff size, 14 lines against 2 |
| Attempt 5 | Leaves a syntax error | Gap: 0 pass, 1 fail |
What do N attempts cost?
Tokens. N attempts cost about N times the tokens of one. Anthropic's agent view docs: "running ten agents in parallel uses quota roughly ten times as fast as running one." On a subscription that is your usage limits; on an API key, the bill. CodeMonkeys gives a published order of magnitude: about 2,300 USD of inference for the 500 issues of SWE-bench Verified with 10 candidates each, that is $4.58 per issue (calculation: 2,291.90 / 500). The edit-generation line alone was 1,366.02 USD, or about $0.27 per candidate edit (calculation: 1,366.02 / 500 / 10), with a 2024 model.
Machines. Each attempt needs its own checkout, dependency install and test run: on a laptop, N installs and N test suites at once. On a per-second sandbox, machines cost little next to tokens. Example with Vercel Sandbox's published iad1 rates on 31 October 2026 ($0.128 per hour of active CPU, $0.0212 per GB-hour of memory): one attempt on 1 vCPU and 2 GB for 20 minutes at full CPU costs at most $0.057 (calculation: (0.128 + 2 × 0.0212) × 20 / 60), five attempts about $0.28.
Your time. If three attempts pass every check, someone reads three diffs.
What N attempts cost: machines cost little next to tokens
- per issue, 10 candidates each. About 2,300 USD of inference for the 500 issues of SWE-bench Verified.
- $4.58
- per candidate edit. The edit-generation line alone, with a 2024 model.
- $0.27
- at most, the machine of one attempt. One attempt on 1 vCPU and 2 GB for 20 minutes at full CPU, on a per-second sandbox.
- $0.057
How large should N be?
There is no published optimum for everyday coding tasks, and none is offered here. The sources above give bounds:
- Codex Cloud stops at 4 attempts; CodeMonkeys used 10 candidates per issue.
- If coverage grows log-linearly with N, as Large Language Monkeys observed, each doubling of N buys roughly the same gain at twice the cost.
- N pays off on tasks a single attempt often fails and a test can judge. Elsewhere, extra attempts mostly produce more diffs to read.
A practical start: N = 3 or 4 on bugs with a failing test that reproduces them, a guard against edited tests, and the smallest passing diff as tiebreak. Raise N only when no attempt passes but some come close.
Where should you run N attempts?
- On your laptop, with worktrees: free, fine for 2 to 4 attempts on a small repository, limited by RAM, CPU and ports. See the tmux setup for Claude Code.
- In Codex Cloud, with
--attempts: no setup, up to 4 attempts, OpenAI's environment, and no ranking. - One VM per attempt, off the laptop: each attempt gets its own OS, ports and database, and a destructive attempt only breaks its own VM. Tools that manage this are compared in parallel agent orchestrators; hosted sandboxes do it too, and E2B vs Daytona compares two of them.
flockvm runs each agent in its own Firecracker microVM, with sign-ups open (Google, GitHub or an email link) and a 7-day free trial: card required, nothing charged for 7 days. Today that means a VM that boots to SSH in about a second, pause and resume with memory, logs, per-second billing, and up to 15 small VMs at once on the one host in France, shared by all customers; other regions are planned. It does not fork yet: each attempt starts from a fresh VM and clones the repository itself, with the loop in the docs' parallel agents guide. Forking one prepared environment into N attempts, and swarms of 10 to 20 agents, are what flockvm is building next. See the coding agent swarm use case, Claude Code in a VM for one agent, or start a 7-day free trial.
Run your agents in their own microVMs
flockvm gives each coding agent a Firecracker microVM that pauses with its memory and resumes, billed per second. France is live, and you can start with a 7-day free trial.
Start your 7-day free trialCard required. Nothing charged for 7 days.