Agent Harness Engineering: The Code Around the Model
Part 1
〇一Same Model, Different Harness
Not one behaviour parameter of the model changed, and real completion went from 66.8% to 96.2%
In February 2026 LangChain published an engineering write-up: their coding agent's score on Terminal Bench 2.0 rose from 52.8% to 66.5%, moving it from outside the top 30 into the top 5. Terminal Bench is a benchmark of 89 tasks an agent completes in a real terminal, covering compiling, debugging, training machine learning models and more. Through all 13.7 points the model stayed the same gpt-5.2-codex. Everything that changed was code outside the model: the system prompt, the tools, the middleware, and a self-check step inserted before the agent declares it is done.
That code outside the model is now often called the harness. The word comes from the gear strapped onto a horse, which decides where its strength goes. For an agent it means all the code wrapped around the model that decides what to prepare before each model call and what to do after it.
The same model with different harnesses can differ by more than ten points. A single total score does not show where the gap comes from. Below, a small controlled experiment splits the harness into parts, switches them on one at a time, and watches the completion rate at each step.
What a harness is made of
Article 01 of the Agents in Practice series described an agent as "model plus runtime": the model decides the next step and the runtime carries it out. Harness is a wider word for the runtime. Its emphasis is less on executing and more on constraining and guiding: besides running tool calls, it decides which calls may run, in what form results go back to the model, and whether to believe the model when it says it is done.
The DeepSeek Harness architecture (in Chinese) is one complete implementation: the model adapter, tool registry, permission approval, sandbox and session event log are separate plugins, and the model is one replaceable plugin among them. Grouped by responsibility, the parts fall roughly into the eight blocks below:
A few of the terms:
- argument validation: a tool declares the shape of its arguments when it is registered, often with JSON Schema (a JSON format for saying which fields an object has, their types and which are required). A call written by the model is checked against it before it runs;
- verification: when the model declares the task done, the harness checks once by a means independent of the model's judgement, for example by running the tests itself;
- trajectory: the ordered record of every model output, tool call and tool result in one task;
- repeat detection: when the model calls the same tool with the same arguments several times in a row and gets the same result each time, the harness appends a hint for the model.
The experiment switches on only the three parts marked in red. The other five get their own articles later in the series.
Experiment design: hold the model still
Running this comparison on a real model has two problems. One is cost: 2,000 tasks per harness at 5 to 7 calls per task is about 50,000 requests for the four harnesses. The other is noise: a real model's output is random, the same harness run twice differs by a few points, and the differences between parts drown in it.
So the model here is a fake model: a piece of Python that picks its next action with fixed probabilities. It imitates behaviours common in bug-fix tasks: writing an argument name wrongly, making the wrong edit, declaring done without running the tests, and reading the same file over and over. Each behaviour has a constant probability, identical under all four harnesses.
| Parameter | Value | Meaning |
|---|---|---|
P_BAD_ARGS | 0.25 | a tool call writes the argument path as file |
P_FIX_GENERIC | 0.30 | after only tool failed, the next call fixes the argument |
P_FIX_STRUCTURED | 0.95 | after "path missing, file unexpected", the next call fixes it |
P_EDIT_RIGHT | 0.55 | the first edit is right |
P_EDIT_RIGHT_FB | 0.80 | an edit made after seeing a test failure is right |
P_SKIP_TESTS | 0.50 | after editing, declare done without running the tests |
P_STUCK | 0.35 | after a test failure, start rereading the same file |
P_UNSTUCK | 0.15 | without a hint, stop rereading on its own, per read |
P_OBEY_HINT | 0.90 | after a repeat hint, try something else |
These values are assumptions, not measurements of any real model. The question the experiment answers is "with the same model behaviour, which part of the harness changes which kind of outcome", so the exact probabilities change the size of the effects, not the mechanism.
Each task ends in one of three outcomes:
- success: the model declares done, and the tests really pass;
- false completion: the model declares done, and the code is still wrong. The user sees "fixed" while the bug is still there;
- step limit: 14 model calls are used up and the task has not ended.
Each harness adds one part to the one before:
- H0 bare: when a tool function raises, the harness swallows it with
except Exception: return "tool failed", and the model's "done" ends the task. Many agent prototypes are written this way; - H1 +schema: required arguments are checked before execution, and a missing field returns
invalid arguments for read_file: missing ['path'], unexpected ['file']; - H2 +verify: when the model declares done, the harness runs the tests itself. If they fail it does not end the task and hands the failure output back to the model;
- H3 +loop: when the same call repeats 3 times with the same arguments and the same result, the harness replaces the third result with a hint.
The code
Save it as harness_variants.py. Python 3.9+, no third-party dependencies. Each task uses its own random seed (the starting value of a pseudo-random generator; the same seed gives the same random sequence), so every run prints the same numbers:
"""One fake model, four harnesses: compare the task outcomes.
Task: a repo has one bug; the model reads a file, edits code and runs tests. The fake
model acts with fixed probabilities, and what it observes changes the odds of its next
step. The four harnesses stack three parts one at a time:
H0 bare a tool exception is swallowed into "tool failed"; the model's "done" ends the task
H1 +schema arguments are checked before the call; a failure names the wrong field
H2 +verify when the model claims done, the harness runs the tests itself and hands back failures
H3 +loop after 3 identical calls with identical results, the harness appends a hint
Usage: python3 harness_variants.py statistics of the four harnesses over 2000 seeds
python3 harness_variants.py --trace 289 step-by-step trace of seed 289 under H0 and H3
Python 3.9+, no third-party dependencies.
"""
import json
import random
import sys
from dataclasses import dataclass, field
# ---------------- fake-model behaviour (assumed values for the demo, not measurements) ----------------
P_BAD_ARGS = 0.25 # a tool call names an argument wrongly
P_FIX_GENERIC = 0.30 # after a bare "tool failed", the next call fixes the argument
P_FIX_STRUCTURED = 0.95 # after an error naming the field, the next call fixes it
P_EDIT_RIGHT = 0.55 # the first edit is right
P_EDIT_RIGHT_FB = 0.80 # an edit made after seeing a test failure is right
P_SKIP_TESTS = 0.50 # after editing, claim done without running tests
P_OBEY_HINT = 0.90 # after a repeat hint, try something else
P_STUCK = 0.35 # after a test failure, start rereading the same file
P_UNSTUCK = 0.15 # without a hint, stop rereading on its own per step
MAX_STEPS = 14 # at most 14 model calls per task
@dataclass
class Repo:
"""The repo being edited: all that matters is whether the bug is really fixed."""
fixed: bool = False
def tests_pass(self):
return self.fixed
@dataclass
class Call:
"""One tool call written by the model, or a claim of done (name == "finish")."""
name: str
args: dict = field(default_factory=dict)
def key(self):
return self.name + json.dumps(self.args, sort_keys=True)
TOOLS = { # tool name -> required arguments
"read_file": ["path"],
"edit_file": ["path", "patch"],
"run_tests": [],
}
class FakeModel:
"""A fake model that picks its next step from what it observed.
rng: one random generator per task, so the same seed reproduces the same run.
"""
def __init__(self, rng):
self.rng = rng
self.read = False # has it read the faulty file
self.edits = 0 # how many edits so far
self.saw_failure = False # has it seen a test failure
self.pending_bad = None # the wrong arguments it repeats until it fixes them
self.tested_since_edit = False
self.stuck = False # stuck rereading the same file
def _args(self, name, good):
"""Build the arguments; the mistake is writing path as file."""
if self.pending_bad is not None:
return self.pending_bad
if self.rng.random() < P_BAD_ARGS:
bad = {"file": "app/orders.py"}
if name == "edit_file":
bad["patch"] = "..."
self.pending_bad = bad
return bad
return good
def step(self, obs):
"""obs is what the harness handed back after the last call (a string)."""
r = self.rng.random
# ---- update internal state from the observation ----
if obs.startswith("tool failed"):
if r() < P_FIX_GENERIC:
self.pending_bad = None # guessed what was wrong
elif obs.startswith("invalid arguments"):
if r() < P_FIX_STRUCTURED:
self.pending_bad = None # the error named the field
elif obs.startswith("FAILED"):
self.saw_failure = True
self.tested_since_edit = True
self.stuck = r() < P_STUCK # wants another look at the source, then cannot stop
elif obs.startswith("repeated call"):
if r() < P_OBEY_HINT:
self.pending_bad = None # tries another way
self.stuck = False
elif obs.startswith("content of"):
self.read = True
if self.stuck and r() < P_UNSTUCK:
self.stuck = False
elif obs.startswith("edited"):
self.edits += 1
self.tested_since_edit = False
elif obs.startswith("PASSED"):
return Call("finish", {"answer": "Fixed, tests pass."})
# ---- choose the next step ----
if not self.read or self.stuck:
return Call("read_file", self._args("read_file", {"path": "app/orders.py"}))
if self.edits == 0 or (self.saw_failure and self.tested_since_edit):
return Call("edit_file", self._args("edit_file", {"path": "app/orders.py", "patch": "fix"}))
if not self.tested_since_edit and r() >= P_SKIP_TESTS:
return Call("run_tests")
return Call("finish", {"answer": "Fixed."})
@dataclass
class Harness:
"""The three optional parts of the harness."""
name: str
schema_check: bool = False
verify_on_finish: bool = False
loop_detect: bool = False
def execute(call, repo, model_rng, feedback_seen):
"""The runtime executes a tool. With an argument missing, the real function raises KeyError."""
args = call.args
if call.name == "read_file":
return f"content of {args['path']}: 42 lines"
if call.name == "edit_file":
_ = args["path"], args["patch"]
p = P_EDIT_RIGHT_FB if feedback_seen else P_EDIT_RIGHT
repo.fixed = model_rng.random() < p
return f"edited {args['path']}"
if call.name == "run_tests":
return "PASSED 12 tests" if repo.tests_pass() else "FAILED test_orders_total: expected 120, got 100"
raise KeyError(call.name)
def run(seed, h, trace=None):
"""Run one task; return (outcome, model calls, harness interventions).
Outcomes:
success claimed done, and the tests really pass
false_completion claimed done, but the code is still wrong
step_limit 14 calls used up, not done
"""
rng = random.Random(seed)
model, repo = FakeModel(rng), Repo()
obs, last_key, repeats, interventions = "task: test_orders_total fails, fix it", None, 0, 0
for step in range(1, MAX_STEPS + 1):
call = model.step(obs)
if call.name == "finish":
if h.verify_on_finish and not repo.tests_pass():
# verification gate: the harness does not take the model's word
obs = "FAILED test_orders_total: expected 120, got 100 (checked by harness)"
interventions += 1
if trace is not None:
trace.append((step, "finish", "verify", obs))
continue
result = "success" if repo.tests_pass() else "false_completion"
if trace is not None:
trace.append((step, "finish", "", result))
return result, step, interventions
# ---- argument validation ----
missing = [k for k in TOOLS[call.name] if k not in call.args]
if missing and h.schema_check:
extra = [k for k in call.args if k not in TOOLS[call.name]]
obs = f"invalid arguments for {call.name}: missing {missing}, unexpected {extra}"
interventions += 1
tag = "schema"
else:
try:
obs = execute(call, repo, rng, model.saw_failure)
tag = ""
except KeyError:
obs = "tool failed" # the common pattern: except Exception: return "tool failed"
tag = ""
# ---- repeat detection ----
k = call.key() + obs
repeats = repeats + 1 if k == last_key else 1
last_key = k
if h.loop_detect and repeats >= 3:
obs = f"repeated call: {call.name} with the same arguments 3 times, result unchanged; try a different approach"
interventions += 1
repeats, tag = 0, (tag + "+loop").strip("+")
if trace is not None:
trace.append((step, call.name, tag, obs))
return "step_limit", MAX_STEPS, interventions
HARNESSES = [
Harness("H0 bare"),
Harness("H1 +schema", schema_check=True),
Harness("H2 +verify", schema_check=True, verify_on_finish=True),
Harness("H3 +loop", schema_check=True, verify_on_finish=True, loop_detect=True),
]
if __name__ == "__main__":
if len(sys.argv) == 3 and sys.argv[1] == "--trace":
seed = int(sys.argv[2])
for h in (HARNESSES[0], HARNESSES[3]):
tr = []
res, steps, _ = run(seed, h, tr)
print(f"== {h.name}: {res} after {steps} model calls")
for step, name, tag, obs in tr:
print(f" {step:>2} {name:<10} {tag:<7} {obs[:70]}")
sys.exit()
N = 2000
print(f"{'harness':<12}{'success':>9}{'false_done':>12}{'step_limit':>12}{'calls':>8}{'interv':>8}")
for h in HARNESSES:
counts = {"success": 0, "false_completion": 0, "step_limit": 0}
calls = interv = 0
for seed in range(N):
res, steps, iv = run(seed, h)
counts[res] += 1
calls += steps
interv += iv
print(f"{h.name:<12}{counts['success'] / N:>9.1%}{counts['false_completion'] / N:>12.1%}"
f"{counts['step_limit'] / N:>12.1%}{calls / N:>8.2f}{interv / N:>8.2f}")
Run it:
python3 harness_variants.py
Output:
harness success false_done step_limit calls interv
H0 bare 66.8% 23.1% 10.2% 6.46 0.00
H1 +schema 72.5% 24.3% 3.2% 5.00 0.92
H2 +verify 91.6% 0.0% 8.4% 6.25 1.42
H3 +loop 96.2% 0.0% 3.9% 6.08 1.55
calls is the average number of model calls per task, and interv is the average number of times the harness stepped in (returned a validation error, refused a completion, or appended a hint).
Each part removes one failure and exposes the next
H0: the model declares done in 89.8% of tasks, and 23.1 points of that are false completions. Counting tasks that ended, H0 looks close to 90%; counting tasks whose tests pass, it is 66.8%. Under H0 the model's "done" is the end of the task, and the harness has no way to tell the two apart.
Another 10.2% of tasks used up all 14 calls. Reading the trajectories, 197 of those 204 tasks are stuck at the same place: the model writes path as file, the tool raises KeyError, and the harness returns tool failed. The model does not know what went wrong, and 70% of the time it sends the same call again.
H1: validation brings the step-limit rate from 10.2% down to 3.2% and the average call count from 6.46 to 5.00. The error says which field is missing and which is unexpected, and the model fixes it in one try.
The counter-intuitive number is false completion: it rises from 23.1% to 24.3%. Validation does not make the model write worse code. The change comes from the denominator: tasks that used to loop on tool failed and never reached "declare done" now reach it. Some of them declare done without running the tests while the code happens to be wrong, and they move from "step limit" to "false completion".
So a part that makes tasks progress faster, without changing how the end of a task is judged, also delivers wrong conclusions to the user faster.
H2: verification brings false completion to 0. Each time the model declares done, the harness runs the tests and on failure hands FAILED test_orders_total: expected 120, got 100 back to the model. An edit made after seeing a failure is right with probability 0.80, above the 0.55 of the first edit. Success goes from 72.5% to 91.6%.
The cost is that the step-limit rate climbs back from 3.2% to 8.4%, and the average call count from 5.00 to 6.25. The cause is P_STUCK: after seeing a test failure the model rereads the source file 35% of the time and stops on its own after each read only 15% of the time. Under H1 most of these tasks had already declared done before the failure surfaced; H2 surfaces the failure and in doing so sends the model into the reread loop.
H3: repeat detection brings the step-limit rate from 8.4% to 3.9%, and success reaches 96.2%. About four fifths of the remaining 3.9% are still reread loops: the model ignores the hint 10% of the time and can fall back into the loop after obeying it. The rest are tasks that made several wrong edits in a row and ran out of calls.
One concrete trajectory
Seed 289, step by step under H0 and H3 (python3 harness_variants.py --trace 289):
The first two steps are the same in both: read the file, edit the code, and this edit is wrong. At step 3 the model declares done without running the tests. H0 ends there with a false completion after 3 calls.
H3 runs the tests at step 3, and they fail. The model wants to reread the source; at step 4 it writes the argument wrongly and the validation error names the field; at steps 5 and 6 the reads succeed but return the same content, and the model keeps rereading; at step 7 the harness detects three identical calls and tells the model to try something else. Step 8 edits again, step 9 passes the tests, step 10 ends the task.
H3 spent 7 more calls. Billed per call, this trajectory costs 3.3 times as much as under H0, and what it buys is a bug that is actually fixed instead of a false "fixed".
Parts do not add up independently
Switching on verification alone in the same script (no validation, no repeat detection) gives:
verify only success 82.7% false_done 0.0% step_limit 17.3% calls 7.64
With verification alone, success is 82.7%, 8.9 points below H2 (validation plus verification), and 17.3% of tasks hit the step limit. Verification makes tasks take a few more steps, and those steps have already been spent in tool failed loops: the extra chances to fix the code that verification creates do not fit in a budget of 14 calls.
Switching on repeat detection alone gives results close to H1 (72.7% success, 24.4% false completion), because it also breaks the tool failed loop, only later than a structured error does: it waits for the third repeat.
So what a part achieves depends on which other parts exist. An ablation (removing or adding one part at a time and watching the result) run against one baseline gives numbers that hold for that baseline only.
What this experiment cannot show
The numbers depend on the assumed probabilities. With other parameters every percentage moves, and H1's false completion need not rise. The conclusions the experiment supports are qualitative: without verification, false and real completions are mixed together in the results; verification exposes failures, and exposed failures need later parts to handle them or they turn into step-limit failures.
A harness does not replace model capability. Lower P_EDIT_RIGHT to 0.05 and P_EDIT_RIGHT_FB to 0.10 to imitate a model that can hardly fix this bug:
H0 bare success 8.8% false_done 67.7% step_limit 23.6%
H3 +loop success 27.4% false_done 0.0% step_limit 72.7%
H3 removes every false completion, but success is only 27.4% and most tasks end at the step limit. Verification turns a wrong "done" into a clear "not done"; it cannot turn code the model cannot fix into correct code.
The LangChain result should be read the same way: those 13.7 points sit on top of the planning, coding and debugging ability gpt-5.2-codex already had. A June 2026 survey of agent system and harness design describes agent performance as the product of model capability, runtime infrastructure, task structure and evaluation design acting together, none of which explains a total score alone. What a harness does is turn the ability the model already has into results more completely.
Real models fail in more ways. The fake model has nine probability parameters. A real model also invents file paths that do not exist, forgets earlier constraints in a long context, and uses sed to get around the edit tool. Each failure mode maps to a part of the harness, which is why five parts in the figure above are still switched off.
Start by recording false completions
In H0's results the hardest thing to notice is the 23.1% of false completions: the agent reports success, the logs show no error, and only a user who checks later finds out. The first value of the verification part is to separate these results from successes; raising the completion rate comes second.
Anthropic's November 2025 post on effective harnesses for long-running agents uses a related idea: an initializer agent first writes a feature list (over 200 entries in their claude.ai clone example), all initially marked failing; coding agents may only change each entry's passes field, and only after end-to-end testing with browser automation tools, the way a human user would test. There the judgement is still made by the agent itself. H2 goes one step further and moves the judgement out of the model and into the harness.
The next article starts from "tool registry and validation" in the figure: if the error missing ['path'], unexpected ['file'] from H1 is worded differently, how much does the chance of the model fixing its arguments change?