Build your own coding-agent benchmark in Node.js
- Authors
- Name
- Hamza Rahman
- Published on
- -16 mins read
Public leaderboards measure someone else's tasks. The AI coding benchmark comparison can help you pick candidates, but you need your own tasks to find out whether they work on your code.
In this tutorial we build a harness that runs a coding agent on tasks from your own repository and records pass rate, a confidence interval, time and reported cost. It uses only Node built-ins and Git, and includes a fake agent so you can run it all without an API key.
Checked on December 4, 2026 with Node.js v25.2.1 and v26.14.0 and Git 2.56.0 on Linux. Process-group cleanup uses POSIX behavior, so use Linux, macOS or a Linux container.
Define a task
A task has a prompt, a full starting commit hash, hidden test files and a verifier command:
{
"repo": "sample",
"repeats": 2,
"tasks": [
{
"id": "fix-sum",
"prompt": "Fix sum in math.js.",
"commit": "FULL_COMMIT_SHA",
"hiddenDir": "hidden/sum",
"verify": ["node", "--test", "sum.test.js"],
"agentTimeoutMs": 1000,
"verifyTimeoutMs": 10000
}
]
}
Paths are relative to the config file, and commands are arrays so no shell parses the prompt. The one-second limit is for the fake agent. Real agents need minutes.
The hidden files stay outside the checkout while the agent works. They're copied in afterwards and replace anything the agent wrote at the same path. Write them to cover behavior rather than one particular implementation.
Define an agent
An agent is a name, a function returning a command, and optionally an environment and a cost parser. Save this one as fake-agent.js:
import { fileURLToPath } from 'node:url'
const script = fileURLToPath(new URL('./fake-agent-cli.js', import.meta.url))
export default {
name: 'scripted-fake',
command: (task, repeat) => [process.execPath, script, task.id, String(repeat), task.prompt],
parseCost: (stdout) => {
try {
return JSON.parse(stdout.trim().split('\n').at(-1)).costUsd ?? null
} catch {
return null
}
},
}
The command runs in the worktree and edits files there. Exit code 0 only means the agent finished, and the hidden verifier decides whether it succeeded. If the agent reports no cost, the result stays null, so an unknown cost is never treated as free.
The agent runs this script, fake-agent-cli.js:
import { readFileSync, writeFileSync } from 'node:fs'
const [taskId, repeat] = process.argv.slice(2)
const edit = (file, from, to) =>
writeFileSync(file, readFileSync(file, 'utf8').replace(from, to))
if (taskId === 'fix-sum') edit('math.js', 'a - b', 'a + b')
// Solves this one on the first repeat only, to show variation.
if (taskId === 'fix-slug' && repeat === '1') edit('slug.js', "' '", '/\\s+/g')
// Cheats: edits the visible test instead of the code.
if (taskId === 'fix-clamp') writeFileSync('clamp.test.js', '')
// Hangs until the time limit.
if (taskId === 'fix-hang') setInterval(() => {}, 1000)
// Invented cost, so the reporting path runs.
if (taskId !== 'fix-hang') console.log(JSON.stringify({ costUsd: 0.01 }))
Each task takes a different path through the harness: a clean fix, a fix that only works on the first repeat, a cheat that edits the visible test, and a hang that hits the time limit. The one-cent cost is invented.
Run commands with a hard limit
Create run-command.js, which starts a command with a small environment and a time limit and keeps the last million characters of its output. detached: true gives the child its own process group on non-Windows platforms, so killing a negative process ID kills its children too.
import { spawn } from 'node:child_process'
// Only these variables reach the agent and the verifier.
function cleanEnv(home) {
const env = { HOME: home, LANG: 'C.UTF-8' }
for (const name of ['PATH', 'TMPDIR']) {
if (process.env[name]) env[name] = process.env[name]
}
return env
}
export function runCommand([command, ...args], { cwd, timeoutMs, home, env = {} }) {
return new Promise((resolve) => {
const started = performance.now()
let stdout = ''
let stderr = ''
let timedOut = false
let settled = false
const child = spawn(command, args, {
cwd,
env: { ...cleanEnv(home), ...env },
stdio: ['ignore', 'pipe', 'pipe'],
detached: true, // own process group, so we can kill grandchildren (POSIX)
})
const killGroup = () => {
try {
process.kill(-child.pid, 'SIGKILL')
} catch {
// The group has already gone.
}
}
let timer
let exitTimer
const finish = (exitCode, error = null) => {
if (settled) return
settled = true
clearTimeout(timer)
clearTimeout(exitTimer)
child.stdout?.destroy()
child.stderr?.destroy()
resolve({ exitCode, timedOut, error, stdout, stderr, ms: performance.now() - started })
}
timer = setTimeout(() => {
timedOut = true
killGroup()
finish(null)
}, timeoutMs)
const append = (text, chunk) => (text + chunk).slice(-1_000_000)
child.stdout.setEncoding('utf8').on('data', (chunk) => (stdout = append(stdout, chunk)))
child.stderr.setEncoding('utf8').on('data', (chunk) => (stderr = append(stderr, chunk)))
child.on('error', (error) => finish(null, error.message))
child.on('exit', (code) => {
killGroup() // stop anything the command left running
// In case an escaped process holds the pipes.
if (!settled) exitTimer = setTimeout(() => finish(code), 500)
})
child.on('close', (code) => finish(code))
})
}
A process can still leave that group by starting a new session. The 500 ms fallback keeps the harness from hanging on it, but only a container reliably ends it.
Run one attempt
Create attempt.js. It makes a detached worktree, runs the agent, adds the hidden files, runs the verifier, and removes everything.
import { execFileSync } from 'node:child_process'
import { cpSync, mkdtempSync, mkdirSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { runCommand } from './run-command.js'
const git = (repo, ...args) =>
execFileSync('git', ['-C', repo, ...args], { encoding: 'utf8', stdio: 'pipe' }).trim()
export async function runAttempt({ repo, task, agent, repeat }) {
const root = mkdtempSync(join(tmpdir(), 'agent-bench-'))
const worktree = join(root, 'work')
const home = join(root, 'home')
mkdirSync(home)
const row = {
agent: agent.name,
taskId: task.id,
repeat,
status: 'error',
agentMs: 0,
costUsd: null,
detail: '',
}
try {
git(repo, 'worktree', 'add', '--detach', worktree, task.commit)
const result = await runCommand(agent.command(task, repeat), {
cwd: worktree,
home,
timeoutMs: task.agentTimeoutMs,
env: agent.env,
})
row.agentMs = Math.round(result.ms)
row.costUsd = agent.parseCost?.(result.stdout) ?? null
if (result.error) {
row.detail = `agent did not start: ${result.error}`
return row
}
if (result.timedOut) {
row.status = 'fail'
row.detail = 'agent timed out'
return row
}
if (result.exitCode !== 0) {
row.detail = `agent exited ${result.exitCode}`
return row
}
// Restore hidden tests last, so agent edits to them do not count.
cpSync(task.hiddenDir, worktree, { recursive: true, force: true })
const check = await runCommand(task.verify, {
cwd: worktree,
home,
timeoutMs: task.verifyTimeoutMs,
})
if (check.error) {
row.detail = `verifier did not start: ${check.error}`
return row
}
row.status = check.exitCode === 0 && !check.timedOut ? 'pass' : 'fail'
row.detail = check.timedOut ? 'verifier timed out' : `verifier exited ${check.exitCode}`
return row
} catch (error) {
row.detail = error.message
return row
} finally {
try {
git(repo, 'worktree', 'remove', '--force', worktree)
} catch {
git(repo, 'worktree', 'prune')
}
rmSync(root, { recursive: true, force: true })
}
}
Three outcomes matter:
pass: the verifier exited 0.fail: the verifier rejected the work or timed out, or the agent ran out of time.error: the agent or verifier would not start, the agent exited nonzero, or setup failed.
An agent that writes an infinite loop should fail, so a verifier timeout counts as a failure. Errors are left out of the pass rate but always counted, and you shouldn't compare agents until each one is explained. Rerun attempts that failed because of a bad key. An agent that crashes by itself, or stops at a budget limit, should be scored as a failure.
Summarize the attempts
Create stats.js to summarize the rows and calculate the Wilson interval, which stays within 0 to 1 and does not collapse to zero width when every attempt passes.
export function wilson(passed, total, z = 1.96) {
if (total === 0) return { low: 0, high: 1 }
const p = passed / total
const z2 = z * z
const denominator = 1 + z2 / total
const center = (p + z2 / (2 * total)) / denominator
const half =
(z * Math.sqrt((p * (1 - p)) / total + z2 / (4 * total * total))) / denominator
return { low: Math.max(0, center - half), high: Math.min(1, center + half) }
}
export function summarize(rows) {
const scored = rows.filter((row) => row.status === 'pass' || row.status === 'fail')
const passed = scored.filter((row) => row.status === 'pass').length
const costs = rows.map((row) => row.costUsd).filter((cost) => cost !== null)
const solvedTasks = new Set(
scored.filter((row) => row.status === 'pass').map((row) => row.taskId)
).size
const totalCostUsd = costs.length === rows.length ? costs.reduce((a, b) => a + b, 0) : null
return {
attempts: rows.length,
scored: scored.length,
errors: rows.length - scored.length,
passed,
passRate: scored.length ? passed / scored.length : null,
wilson95: wilson(passed, scored.length),
tasks: new Set(rows.map((row) => row.taskId)).size,
solvedTasks,
meanAgentMs: rows.length
? rows.reduce((sum, row) => sum + row.agentMs, 0) / rows.length
: null,
reportedCosts: costs.length,
totalCostUsd,
costPerSolvedTask:
totalCostUsd !== null && solvedTasks > 0 ? totalCostUsd / solvedTasks : null,
}
}
If any attempt lacks a cost, the total is null and reportedCosts shows how many were reported. A partial total would make an agent that times out look cheap. The cost per solved task article explains that last calculation.
Tie it together with bench.js
bench.js is the entry point. It loads the config and the agent, runs every attempt, and writes the results file:
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { dirname, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
import { runAttempt } from './attempt.js'
import { summarize } from './stats.js'
const [configPath, agentPath, outPath = 'results.json'] = process.argv.slice(2)
const base = dirname(resolve(configPath))
const config = JSON.parse(readFileSync(configPath, 'utf8'))
const { default: agent } = await import(pathToFileURL(resolve(agentPath)).href)
const repo = resolve(base, config.repo)
const rows = []
for (let repeat = 1; repeat <= config.repeats; repeat++) {
for (const entry of config.tasks) {
const task = { ...entry, hiddenDir: resolve(base, entry.hiddenDir) }
const row = await runAttempt({ repo, task, agent, repeat })
rows.push(row)
console.log(`${row.taskId} #${repeat}: ${row.status} (${row.detail}, ${row.agentMs} ms)`)
}
}
const summary = summarize(rows)
mkdirSync(dirname(resolve(outPath)), { recursive: true })
writeFileSync(
outPath,
JSON.stringify({ agent: agent.name, node: process.version, summary, rows }, null, 2)
)
console.log(JSON.stringify(summary, null, 2))
Run it on the sample
The sample repository has broken sum, slug and clamp functions, with four tasks that each run twice. Create setup-sample.sh to generate the repository, hidden tests and tasks.json (it deletes sample and hidden next to itself, so use an empty folder):
#!/usr/bin/env bash
set -euo pipefail
cd "$(dirname "$0")"
rm -rf sample hidden && mkdir -p sample hidden/{sum,slug,clamp,hang}
echo '{"type":"module"}' > sample/package.json
echo 'export const sum = (a, b) => a - b' > sample/math.js
echo "export const slug = (s) => s.trim().toLowerCase().replace(' ', '-')" > sample/slug.js
echo 'export const clamp = (n, lo, hi) => Math.max(lo, n)' > sample/clamp.js
t() { printf "import test from 'node:test'\nimport assert from 'node:assert/strict'\nimport { %s } from './%s.js'\ntest('%s', () => %s)\n" "$1" "$2" "$1" "$3"; }
t sum math 'assert.equal(sum(2, 3), 5)' > hidden/sum/sum.test.js
t slug slug "assert.equal(slug('A b c'), 'a-b-c')" > hidden/slug/slug.test.js
t clamp clamp 'assert.equal(clamp(9, 0, 5), 5)' > hidden/clamp/clamp.test.js
cp hidden/sum/sum.test.js hidden/hang/hang.test.js
cp hidden/clamp/clamp.test.js sample/
git -C sample init -q -b main
git -C sample add -A
git -C sample -c user.name=bench -c user.email=bench@example.invalid -c commit.gpgsign=false commit -qm 'starting point'
SHA=$(git -C sample rev-parse HEAD)
task() { printf '{"id":"%s","prompt":"%s","commit":"%s","hiddenDir":"hidden/%s","verify":["node","--test","%s.test.js"],"agentTimeoutMs":1000,"verifyTimeoutMs":10000}' "$1" "$2" "$SHA" "$3" "$3"; }
printf '{"repo":"sample","repeats":2,"tasks":[%s,%s,%s,%s]}' \
"$(task fix-sum 'Fix sum in math.js.' sum)" "$(task fix-slug 'Make slug collapse whitespace.' slug)" \
"$(task fix-clamp 'Make clamp respect the upper bound.' clamp)" "$(task fix-hang 'Fix sum in math.js.' hang)" > tasks.json
Put all the files in one folder with a package.json containing {"type":"module"}, then run:
bash setup-sample.sh
node bench.js tasks.json fake-agent.js results.json
This is the output from one run on one machine with Node.js v25.2.1:
fix-sum #1: pass (verifier exited 0, 36 ms)
fix-slug #1: pass (verifier exited 0, 36 ms)
fix-clamp #1: fail (verifier exited 1, 52 ms)
fix-hang #1: fail (agent timed out, 1002 ms)
fix-sum #2: pass (verifier exited 0, 56 ms)
fix-slug #2: fail (verifier exited 1, 36 ms)
fix-clamp #2: fail (verifier exited 1, 36 ms)
fix-hang #2: fail (agent timed out, 1001 ms)
{
"attempts": 8,
"scored": 8,
"errors": 0,
"passed": 3,
"passRate": 0.375,
"wilson95": {
"low": 0.13684175946152105,
"high": 0.6942621454161981
},
"tasks": 4,
"solvedTasks": 2,
"meanAgentMs": 281.875,
"reportedCosts": 6,
"totalCostUsd": null,
"costPerSolvedTask": null
}
The edited visible test didn't help fix-clamp, because the hidden version replaced it. Both hanging attempts stopped at the limit. Afterwards, git worktree list showed only the original checkout.
Before using a real agent, run two checks:
- An agent that changes nothing. Every task should fail.
- A scripted agent that applies a known solution. Every task should pass.
The first one is short. Save it as noop-agent.js:
export default {
name: 'noop',
command: () => [process.execPath, '-e', ''],
}
Then run it the same way:
node bench.js tasks.json noop-agent.js results-noop.json
On this sample the two checks give 0 of 8 and 8 of 8. If yours give anything else, repair the verifier before comparing models.
What five tasks can tell you
With one attempt on each of five tasks, 4 passes give a Wilson interval of 37.6% to 96.4%, and five passes give 56.6% to 100%. Ranges that wide can't separate two good agents.
A small run helps you catch problems early: an agent that can't operate your repository, an unclear prompt, costs far from what you expected, or one specific task that fails repeatedly. It can't establish a ranking or predict a general success rate.
Repeats don't create new tasks. Ten attempts on each of five tasks are not fifty independent samples, because attempts on the same task share its difficulty. The interval in results.json ignores that grouping and is too narrow as a claim about new tasks, so read it as a rough guide, look at results per task, and add tasks before adding repeats.
When you compare agents, hold the model version, effort setting, prompt, time limit and machine constant, and choose tasks before you see results. Run both agents on the same tasks and alternate the order, since services change during the day.
Plug in a real agent
These examples were not executed. The flags were checked on December 4, 2026 against each CLI's docs and the installed help output. Read the Safety section before you run either one on a real repository.
The harness gives the agent an empty temporary HOME, so a CLI login stored in your home directory isn't available to it. That's why both examples pass an API key.
Claude Code 2.1.333, from its non-interactive docs:
export default {
name: `claude-code ${process.env.BENCH_MODEL}`,
command: (task) => [
'claude', '--bare', '-p', task.prompt,
'--model', process.env.BENCH_MODEL,
'--allowedTools', 'Read,Edit,Bash',
'--output-format', 'json',
'--no-session-persistence',
'--max-budget-usd', '2',
],
env: { ANTHROPIC_API_KEY: process.env.BENCH_ANTHROPIC_KEY },
parseCost: (stdout) => {
try {
return JSON.parse(stdout).total_cost_usd ?? null
} catch {
return null
}
},
}
--bare skips your hooks, skills, MCP servers and CLAUDE.md, and needs an API key. The docs say total_cost_usd is a client-side estimate that can differ from the bill, and that spend can pass the budget cap.
Codex CLI 0.172.0, from its non-interactive docs:
export default {
name: `codex ${process.env.BENCH_MODEL}`,
command: (task) => [
'codex', 'exec', '--json', '--ephemeral', '--ignore-user-config',
'--sandbox', 'workspace-write',
'--model', process.env.BENCH_MODEL, task.prompt,
],
env: { CODEX_API_KEY: process.env.BENCH_OPENAI_KEY },
}
Its documented JSON events report token usage in turn.completed, not dollars. Without a parser that prices those tokens, cost stays null.
The agent process can read these keys. Passing them is an exception to the no-credentials rule in the next section, so use a dedicated key with a low spending limit, or a proxy that keeps the real key outside the container.
Safety
A worktree keeps an agent's edits out of your main checkout, but it's not a security boundary.
- Run the harness in a disposable container as a non-root user, with no home directory, SSH agent or Docker socket mounted. Limit network access to what the agent needs.
- Keep credentials out of the environment. This code passes a short allowlist and a temporary
HOME, but outside a container an agent can still read any file your user can. - Never point it at a checkout with unpushed work. Linked worktrees share refs, hooks and objects, so an agent can damage the original repository or read a solution from a later commit.
- Keep the hidden files out of the container while the agent runs if it might search for them. The code above does not. The verifier also runs agent-written code, so it needs the same isolation.
- Review the diff too. Hidden tests do not stop an agent from changing the test runner or package configuration.
Build a separate repository containing only the starting commit:
git init bench-repo
git -C bench-repo fetch --depth 1 "file:///absolute/path/to/repo" FULL_COMMIT_SHA
Repeat the fetch for other starting commits, and set repo to bench-repo. Running git log inside a worktree from bench-repo shows only the starting commit and no later history.
Where to go from here
Start with a few real bugs whose fixes you understand, add tasks as you find them, and keep the raw rows so you can check every total. To build the agent side yourself, start with tool calling in the Vercel AI SDK.
References
Related articles
What an AI coding model costs per solved task
Turn per-million-token prices into cost per attempt and cost per solved task with small JavaScript functions, including caching, retries and review time.
Build an MCP server in TypeScript with Node.js
Build a stateless MCP server in TypeScript with SDK v2: SQLite tools, elicitation, stdio and HTTP, a test client, client setup and Code Mode.
Migrate to Vercel AI SDK 7: a tool-calling guide
Move a tool-calling app from Vercel AI SDK 6 to 7: what breaks, what the codemod misses, a before/after agent, and the new features worth adopting.

