Building Repeatable Evaluation Test Harnesses for Autonomous Agent Workflows

Building Repeatable Evaluation Test Harnesses for Autonomous Agent Workflows

A team changes the system prompt of its coding agent on a Thursday afternoon. The new wording reads better, the three demo tasks that the author tries all succeed, and the change ships on Friday. By Monday the support channel has a pattern: the agent now finishes faster, but it quietly skips running the test suite on about one task in five. Nobody can say whether that is new, because nobody ever measured how often the old prompt ran the tests. The "improvement" was a feeling, and the regression that came with it was invisible until users paid for it.

This is the default state of agent development. A model call is nondeterministic, an agent is a loop of many such calls interleaved with tool output, and the final result depends on the environment as much as on the prompt. Without a harness, every change is judged by whichever three examples the author happened to try. This article describes what a repeatable evaluation harness for an agent is made of, why single runs mislead, how to grade without fooling yourself, and how to wire the result into a delivery pipeline you can trust.

1. What an agent evaluation harness is made of

A harness is a program that runs an agent on a fixed set of tasks, in controlled environments, several times each, and turns the outcomes into numbers you can compare across versions. It has six parts, and most failed evaluation efforts are missing one of them.

  1. Tasks. A task is a prompt plus everything the agent needs to attempt it: a repository snapshot, a database seed, a set of documents. It also states what success means in a form a program can check.
  2. Environment. A fresh, disposable workspace per trial. If trial two inherits files from trial one, you are measuring contamination, not the agent.
  3. The agent under test. Pinned to an exact configuration: model identifier, prompt, tool set, temperature, step and time limits. Anything you cannot name, you cannot reproduce.
  4. Graders. Code that looks at the end state (and sometimes the trajectory) and returns pass or fail, or a score.
  5. A runner. Fans trials out in parallel, enforces timeouts, captures transcripts, and never lets one crashing trial take down the run.
  6. A report. Per-task pass rates with uncertainty, a diff against the previous run, and links to the transcripts of every failure.

The unit that matters is the trial: one attempt by one agent configuration at one task. A task with five trials produces five independent outcomes, and the rest of the harness is about handling those outcomes honestly.

Offline evals versus online monitoring

A harness answers "did this change make the agent better or worse on tasks we understand". It does not tell you what real users are asking for. Production monitoring, transcript sampling and user feedback answer that second question, and they feed the first: every real failure you diagnose is a candidate for a new task. Teams that only run offline evals overfit to their own imagination; teams that only monitor production find regressions after users do. You need both, and the harness is the half you control.

2. Why one run tells you almost nothing

Suppose an agent solves a task correctly 70 percent of the time. Run it once and you will see "pass" seven times in ten, and "fail" three times in ten. If you compare two agent versions on a single run each, a version that is genuinely worse will look better in a large fraction of comparisons. The underlying cause is sampling variance, and with agents it has several sources stacked together: token sampling, tool latency and ordering, nondeterministic test suites in the environment, and a web page or API that changed since yesterday.

Setting temperature to zero helps less than people hope. Many hosted models are not bitwise deterministic even at zero temperature, a long trajectory amplifies any tiny early difference, and fixing the seed of one component does nothing for the tools around it. Treat nondeterminism as a property to measure rather than a bug to eliminate.

pass@k and pass^k

Two summary statistics answer different questions, and mixing them up is a common source of inflated claims.

  • pass@k is the probability that at least one of k attempts succeeds. It fits settings where you can verify a result cheaply and retry: a code generator with a test suite as oracle, for instance.
  • pass^k is the probability that all k attempts succeed. It fits settings where each run is an irreversible action for a user and reliability across repeated use is the product: a customer-facing agent, a deployment bot.

An agent with a per-attempt success probability of 0.8 has a pass@3 above 0.99 and a pass^3 around 0.51. The same agent can be described as "nearly always works" or "fails about half of three-in-a-row sequences", and both statements are arithmetically true. Decide which one matches how the agent is used before you pick the headline number. With n trials and c successes, an unbiased estimator for pass@k is 1 minus C(n-c, k) divided by C(n, k), and for pass^k it is C(c, k) divided by C(n, k). The code in the next section implements both.

How many trials

There is no universal number, but the arithmetic is simple. The standard error of a pass rate shrinks with the square root of the number of trials, so going from 5 to 20 trials per task roughly halves the width of the uncertainty. Across a suite of tasks the effective sample is trials times tasks, which is why a suite of 100 distinct tasks with 3 trials each is usually more informative than 10 tasks with 30 trials each: tasks differ more than trials do. Report a confidence interval, not just a rate, and refuse to call a difference real when the intervals overlap heavily.

3. Hermetic tasks: pinning down the environment

A trial is only as repeatable as its environment. The goal is hermeticity: the same inputs always produce the same starting state, and nothing outside the workspace can leak in or out.

  • Snapshot the starting state. Keep the repository, seed data or documents as a pristine fixture and copy it into a fresh directory for each trial. Never run trials in place.
  • Pin dependencies. Lockfiles, a vendored package cache or a prebuilt container image. A trial that downloads "latest" is measuring the package registry.
  • Fake the outside world. Replace live APIs with recorded responses or local stand-ins. If a task needs the web, record it once and replay it, or you will see failures that appear and vanish with the weather.
  • Control time and randomness where the task depends on them. A fixed clock for date-sensitive code, seeded random number generators in the fixture.
  • Budget every trial. A wall-clock timeout, a step limit and a token ceiling. A trial that runs away should count as a failure and be cheap.
  • Isolate trials from each other. A separate directory, and for anything that executes untrusted generated code, a container or sandbox with no access to credentials.

The last point matters more than it seems. An evaluation harness runs model-generated commands thousands of times. It should be treated as a hostile environment even when the model is yours.

A minimal runner

The following Python module is a compact version of the core loop. Each trial copies a fixture into a temporary directory, runs the agent command with a timeout, restores the protected files from the pristine fixture, runs a deterministic grader, and returns a record. It then aggregates pass rates with a Wilson interval and the two estimators above.

import json
import math
import shutil
import subprocess
import sys
import tempfile
import time
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass, field
from pathlib import Path


@dataclass
class Task:
    id: str
    fixture: Path                      # pristine starting repo
    prompt: str
    grade_cmd: list                    # deterministic grader, runs after the agent exits
    protected: list = field(default_factory=list)   # paths the agent may not change
    timeout_s: int = 600


def run_trial(task, agent_cmd, trial):
    with tempfile.TemporaryDirectory(prefix=f"{task.id}-{trial}-") as tmp:
        ws = Path(tmp) / "ws"
        shutil.copytree(task.fixture, ws)
        started = time.monotonic()
        try:
            subprocess.run(agent_cmd + [task.prompt], cwd=ws, timeout=task.timeout_s,
                           capture_output=True, text=True)
            agent_status = "exited"
        except subprocess.TimeoutExpired:
            agent_status = "timeout"
        elapsed = time.monotonic() - started

        # Restore protected files (tests, fixtures) before grading, so the
        # agent cannot pass by editing the grader's inputs.
        for rel in task.protected:
            src, dst = task.fixture / rel, ws / rel
            if src.is_dir():
                shutil.rmtree(dst, ignore_errors=True)
                shutil.copytree(src, dst)
            else:
                shutil.copy2(src, dst)

        grade = subprocess.run(task.grade_cmd, cwd=ws, capture_output=True, text=True)
        return {"task": task.id, "trial": trial, "agent": agent_status,
                "passed": grade.returncode == 0 and agent_status == "exited",
                "seconds": round(elapsed, 1), "grader_tail": grade.stdout[-400:]}


def wilson(successes, n, z=1.96):
    if n == 0:
        return (0.0, 1.0)
    p = successes / n
    denom = 1 + z * z / n
    centre = (p + z * z / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    return (max(0.0, centre - half), min(1.0, centre + half))


def pass_at_k(n, c, k):                # at least one of k sampled trials passes
    return 1.0 if n - c < k else 1.0 - math.comb(n - c, k) / math.comb(n, k)


def pass_hat_k(n, c, k):               # all k sampled trials pass
    return math.comb(c, k) / math.comb(n, k) if c >= k else 0.0


def main(tasks, agent_cmd, trials=5, workers=4):
    jobs = [(t, i) for t in tasks for i in range(trials)]
    with ThreadPoolExecutor(max_workers=workers) as pool:
        results = list(pool.map(lambda j: run_trial(j[0], agent_cmd, j[1]), jobs))
    for t in tasks:
        rows = [r for r in results if r["task"] == t.id]
        c = sum(r["passed"] for r in rows)
        lo, hi = wilson(c, len(rows))
        print(f"{t.id}: {c}/{len(rows)} passed, 95% CI [{lo:.2f}, {hi:.2f}], "
              f"pass@3={pass_at_k(len(rows), c, 3):.2f}, pass^3={pass_hat_k(len(rows), c, 3):.2f}")
    Path("results.jsonl").write_text("\n".join(json.dumps(r) for r in results) + "\n")


if __name__ == "__main__":
    task = Task("slugify-punct", Path("fixtures/t1"), "Make the failing test pass.",
                [sys.executable, "-m", "pytest", "-q", "test_slug.py"],
                protected=["test_slug.py"])
    main([task], ["my-agent", "--non-interactive"], trials=5)

Two choices here are worth copying. Restoring protected files makes editing the tests useless rather than merely discouraged, and a timeout counts as a recorded failure instead of hanging the run.

4. Graders: deciding what counts as success

The grader is where most evaluation bias enters. Three families exist, and a good harness mixes them.

Deterministic, state-based checks

Run the test suite, compare a database row, parse the generated file, check that the pull request exists. These are cheap, repeatable and impossible to argue with. Grade the outcome in the environment, not the agent's description of it: an agent that says "I fixed the bug" has produced text, and the test result is the evidence. Prefer checks that accept every valid solution rather than one reference answer, otherwise you penalize correct approaches you did not anticipate.

Rubric grading with a model as judge

Some qualities have no program: whether a summary is faithful, whether an explanation is clear, whether a refusal was appropriate. A second model can grade against a written rubric. It is useful and it has known biases: judges tend to favor longer answers, to favor outputs similar to their own style, and to be sensitive to the order in which candidates are presented. Mitigations are mechanical: grade one criterion per call with a binary or narrow scale, randomize order in pairwise comparisons, give the judge the reference facts, and calibrate it against human labels on a sample before trusting it. Keep the judge model and prompt pinned, because changing them changes your scores independent of the agent.

Trajectory checks

Sometimes the path matters even when the end state is right. Did the agent run the tests before declaring completion? Did it touch files outside the allowed directory? Did it call a destructive command? These are checks over the transcript and tool log. Use them for constraints and safety properties, and be cautious about grading style of reasoning: two correct trajectories can look very different, and a rigid expectation of one path will fail good agents.

Grader type Best for Repeatability Main weakness
Deterministic state check Code, data, structured outputs with a testable end state High Narrow: rejects valid solutions that do not match the assertion
Model-as-judge with rubric Faithfulness, tone, helpfulness, free-text quality Medium; depends on judge pinning and calibration Systematic biases, judge drift, cost per trial
Trajectory or tool-log check Safety constraints, required steps, forbidden actions High Over-specifies the path and penalizes unusual but valid approaches
Human review of a sample Calibrating judges, finding failure categories you did not predict Low to medium Slow and expensive; does not scale to every run
Grade what the world looks like afterwards. If a score can be raised by changing how the agent talks about its work rather than the work itself, the grader is measuring the wrong thing.

5. A worked example: a bug-fixing eval from scratch

Take a concrete case. You maintain an agent that fixes small bugs in Python repositories, and you want to know whether a new prompt that says "read the failing test before editing" helps. Here is how the harness gets built, in the order you would do it.

  1. Collect tasks from real failures. Pick twenty past bugs that were fixed by humans. For each, create a fixture at the commit before the fix, and keep the human's regression test as the grader. Remove any hints from the prompt: the agent gets the issue text a human would have received, and nothing from the eventual fix.
  2. Verify every task before it counts. Run the grader on the unfixed fixture: it must fail. Apply the known human fix: it must pass. A task that fails this check is a broken task, and broken tasks poison every later comparison. Do this step in CI whenever a task is added.
  3. Protect the oracle. The regression test is in the protected list, so the runner restores it before grading. Add a trajectory check that flags any edit to files under the test directory, as information even when the restore makes it harmless.
  4. Run both prompts on the same tasks. Five trials each, same model, same limits, same fixtures. Interleave the two configurations so that an outage mid-run affects both equally.
  5. Compare per task, then in aggregate. Look at tasks where the two prompts disagree most, open the transcripts, and write down why. The aggregate pass rate tells you whether the change is worth shipping; the transcripts tell you what the change actually did.

Suppose the result is that the new prompt raises the aggregate pass rate slightly but the intervals overlap, while on six tasks the old prompt was clearly better. That is a normal outcome and an informative one: you have six transcripts to read, a hypothesis about when reading the test first misleads the agent, and a decision to make that does not rest on a demo.

6. Wiring it into delivery

An evaluation that runs only when someone remembers is a report, not a gate. The practical question is cost, because agent trials consume model tokens and wall-clock time.

Tiers

  • Smoke tier on every change. A handful of fast, high-signal tasks, run once or twice. It catches broken wiring, crashed tool schemas and gross regressions in minutes.
  • Regression tier before merge or release. The full task set with several trials each. Gate on a drop that exceeds the uncertainty, not on any difference.
  • Exploration tier on demand. Large sweeps for comparing models, prompts or tool designs. Not a gate, a research instrument.

Gating without crying wolf

Gate on a lower confidence bound or on a drop larger than a threshold you chose in advance. Track per-task history, and quarantine tasks that flip between pass and fail without any change to the agent: they are flaky, and a flaky task should be fixed or removed, not averaged in. Keep the last good run as a baseline and always report the diff against it, with links to the transcripts for every task that changed state.

Controlling cost

Cache what is deterministic, such as environment builds and recorded external responses. Use cheaper models for the judge only after calibration shows they agree with a stronger judge on your rubric. Stop early on a trial once its outcome is determined. Run the smoke tier on every change and the expensive tier on a schedule, and record the cost of each run next to its score so that a prompt that improves quality by a little at several times the token spend is visible as such.

7. How harnesses fail

  • Broken tasks. An unsolvable task, or a task with a grader that passes on the unfixed repository. Verify every task against a known-bad and known-good state.
  • Reward hacking. The agent edits the test, hard-codes the expected value, or exploits a quirk of the environment. Protect the grader's inputs, grade end states in a clean copy, and read transcripts of surprisingly successful trials, not only failures.
  • Contamination. Tasks that leaked into the agent's training data or into its own memory or retrieval store between trials. Use fresh tasks derived from your own systems, and reset all state between trials.
  • Overfitting to the suite. After enough tuning against the same fifty tasks, the score rises while real-world quality does not. Keep a held-out set that you look at rarely, and keep adding tasks from new production failures.
  • Saturation. When every version passes 98 percent of tasks, the suite can no longer tell versions apart. Add harder tasks rather than celebrating.
  • Harness bugs read as agent bugs. A timeout set too low, a missing dependency in the image, a race in parallel workers. When many unrelated tasks fail the same way, suspect the harness first.
  • Measuring only success. A version that passes the same tasks while using several times more steps or tokens is a regression for most deployments. Record steps, tokens, wall time and tool errors with every trial.

8. When not to build one, and what to do on Monday

A full harness is overhead when the agent is a throwaway, when the task space is so open that no program can say what correct means, or when you have fewer than a few dozen real examples to learn from. In those cases a lighter practice is still better than none: keep a spreadsheet of twenty real prompts, run them by hand before each change, save the transcripts, and read them. The discipline of a fixed set, a written expectation and a saved record is most of the value, and the automation comes later.

Decision checklist

  • Can every task be reset to an identical starting state in a fresh directory?
  • Does each task have a grader that passes on a known-good solution and fails on the starting state?
  • Is the agent configuration (model, prompt, tools, limits) pinned and recorded with every run?
  • Are there at least a few trials per task, with intervals reported rather than a single number?
  • Are the grader's inputs protected from the agent?
  • Does every failure link to a transcript someone can read in under five minutes?
  • Do you record cost and step counts alongside correctness?
  • Is there a held-out set, and a path for turning production failures into new tasks?

Common mistakes

  • Comparing two versions on one run each and calling the winner better.
  • Letting the same model family write the tasks, run the agent and judge the output without calibration against humans.
  • Averaging flaky tasks into the score instead of fixing them.
  • Grading the agent's claim of completion instead of the state of the environment.
  • Treating a rising score on a frozen suite as proof of real improvement.

Questions teams ask

Should evals block merges? The smoke tier should, because it is cheap and catches wiring failures. The full tier should block on a statistically meaningful drop, and warn otherwise.

Can a model write the tasks? It can draft them, and that is a good use of one. A human should review the task and, more importantly, the check that the grader fails on the starting state and passes on a known fix.

What about tasks with no right answer? Use pairwise comparison with a calibrated judge or human reviewers, and report win rates with intervals. Do not pretend a rubric score has more precision than it does.

Monday morning. Pick the ten most expensive failures from the last month, turn each into a task with a reset fixture and a grader that fails before the fix, run your current agent against them five times each, and save the output. That one directory is the seed of a harness, and the first number it gives you is your baseline.

In a production agent stack the same idea shows up as a working habit: no claim that a change is fixed or complete is accepted without fresh evidence from a command run in an isolated workspace. A harness is that habit, applied to the agent itself and repeated enough times to be believed.