TEXTBOOK·ENGINEERING AI AGENTSPreviousCHAPTER 12 OF 15NextContents
12CODING & SOFTWARE AGENTS

Coding agents

A repository is an unusually honest environment: the tests either pass or they do not, and the agent cannot argue with the result.

12.1What SWE-bench actually measures

SWE-bench takes 2,294 resolved issues from twelve widely-used Python repositories and turns each into a task. The agent receives the issue text and a repository checked out at the commit immediately before the fix. It must produce a patch. No file list, no function name, no hint about which of several thousand source files matters.

Grading is executional rather than textual. Each instance carries two test sets taken from the merged pull request. The first fails before the fix and passes after it — these are the tests the human change was written to satisfy. The second passes in both states, and exists to catch a patch that solves the issue by breaking something else. An instance counts as resolved only if every test in both sets passes.

The second set does more work than its description suggests. Without it, an agent could satisfy the target tests by deleting a guard clause or short-circuiting a code path, fixing the reported symptom while breaking behaviour the repository already depended on. Executional grading on target tests alone rewards local success and is blind to collateral damage.

A patch that differs entirely from the human one still counts as resolved if the tests agree. The benchmark scores behaviour, not authorship, which is why it survived the transition from completion models to multi-turn agents while text-similarity code benchmarks did not.

COMPONENTDEFINITIONFAILURE IT CATCHES
Issue textThe issue body, verbatim—
Base commitRepository state just before the merge—
Fail-to-pass testsFailing before, passing afterThe agent did not fix the bug
Pass-to-pass testsPassing in both statesThe agent broke something else
Gold patchThe human diff, never shown to the agentUsed only to build the dataset

12.2Localisation is the bill

In a mature repository the agent must decide, before writing a character of code, which of roughly three thousand files is the one to modify. This is the localisation problem, and on real issue-fixing tasks it consumes most of the run.

Sparse lexical retrieval fails here for a reason specific to bug reports. Issue text is written in the vocabulary of symptoms — the legend disappears when a particular flag is set — while the fix lives in code written in the vocabulary of implementation, some update method three inheritance levels down. The two vocabularies barely overlap. Term matching cannot bridge cause and effect.

This is why agentic search beat retrieve-then-generate pipelines. An agent that greps for an error string, reads the traceback frame by frame, opens the file, and follows a call upward is doing iterative localisation with feedback at every step, narrowing the hypothesis space using evidence from the repository rather than one similarity ranking computed once.

The practical consequence is to instrument localisation separately. Log, per instance, whether the agent ever opened a file the gold patch touches. That single boolean splits your failures into two populations needing entirely different fixes. If the agent never opened the right file, better reasoning cannot help. If it did and still failed, retrieval is fine and the problem is elsewhere.

P(resolve) = P(locate) · P(fix | locate)
The two factors need different interventions, so measure them separately. Running with and without oracle files gives you both directly.
LOCALISATION INSTRUMENTATION
def localization_hit(trajectory, gold_patch):
    gold = files_in_diff(gold_patch)
    opened = {
        step.path for step in trajectory
        if step.tool in ("open", "edit", "search_file")
    }
    return bool(gold & opened)

# Split every failure by this flag before analysing anything else.

12.3The agent–computer interface

SWE-agent turned an implicit idea into a design discipline: the interface an agent uses is not the interface a human uses, and building it to feel familiar to humans costs accuracy. Tool design is a first-class engineering surface with its own ablations.

The baseline was a plain shell — give the model bash and let it do anything a developer could. Replacing that with a purpose-built command set, a file viewer, a structured edit command, and summarising search moved the same model from eleven to eighteen per cent on SWE-bench Lite. The interface, not the model, produced the gain.

The individual ablations teach more than the headline. A viewer showing a hundred lines beat both a thirty-line window and dumping the whole file. Both directions of error hurt: thirty lines forces the agent to page repeatedly and lose surrounding structure, while the full file floods the context with material that must be re-read every subsequent turn.

The most transferable result is the edit command with integrated linting. When an edit produced a syntax error the tool refused the write, reported the error, and left the file unchanged. Without it the agent writes broken code, discovers the breakage several turns later when a test fails for an unrelated-looking reason, and spends turns diagnosing a problem it created. Rejecting the bad edit converts a multi-turn detour into one error message.

The unifying principle is that terse structured output beats a raw dump — not for elegance, but because context is a fixed shared resource. Every token a tool emits is unavailable for reasoning. A tool returning eight hundred lines of search output has not informed the agent; it has spent the agent's budget on its behalf.

EDIT COMMAND WITH A LINT GUARDRAIL
def edit(path, start, end, new_text):
    candidate = splice(read(path), start, end, new_text)
    err = syntax_check(candidate)
    if err:
        return f"Edit not applied. {err.msg} at line {err.line}"
    write(path, candidate)
    return window(candidate, start, radius=6)   # confirm, don't dump

# The rejected write is the point: the file never breaks.
CONFIGURATIONRESOLVE RATEDELTA
Shell-only baseline11.0%—
Full purpose-built interface18.0%+7.0
No edit linting15.0%−3.0
Unsummarised search12.0%−6.0
Thirty-line viewer window14.3%−3.7
Full-file viewer12.7%−5.3

12.4Verification and long-running harnesses

A coding agent that cannot run tests is guessing. Test-time verification is what separates an agent from a completion system: it proposes an edit, executes the suite, reads the failure, and revises, taking ground truth from the environment rather than from its own confidence, which is not well calibrated on whether a patch works.

Since the grading tests are hidden, the agent must construct its own verification — usually by writing a reproduction script from the issue text, confirming it fails on the base commit, and re-running after the edit. This is a good habit independent of benchmarks, because it forces the agent to state its understanding in executable form before editing. An agent that cannot write a failing reproduction usually has not understood the issue, and that signal arrives early.

On patch format, unified diffs applied to specific line ranges beat whole-file rewriting on real repositories. Rewriting a nine-hundred-line module requires reproducing eight hundred and ninety unrelated lines correctly, and models silently drop code that no test in the file covers. A diff bounds the blast radius to the lines it names. Most production agents settled on a structured edit taking an exact anchor string, which keeps the small blast radius without the fragility of drifting line numbers.

Long-running harnesses need checkpointing for an unglamorous reason: runs take twenty to sixty minutes and things crash. Rate limits, container memory, a hung test. Persist the message history, the working tree diff, and the tool state after each step, and resume from the last committed one. Make checkpoints content-addressed so a resumed run is verifiably the same run, and two trajectories sharing a prefix can be diffed to find where they diverged.

Set a step budget and a wall-clock budget, and instrument what happens at the limit. A meaningful share of failures are not wrong answers but non-terminations — the agent opens a file, edits, reverts, and opens it again. Detecting a repeated state-action pair and injecting a note into the context is cheap and recovers runs that would otherwise burn their entire budget in a three-step cycle.

STEP CHECKPOINT AND RESUME
def run(task, max_steps=75, deadline_s=2400):
    st = load_checkpoint(task.id) or State(task)
    while st.step < max_steps and st.elapsed() < deadline_s:
        action = policy(st.history)
        if st.seen(action):                 # loop guard
            st.note("Repeated action; try another approach.")
        st.append(action, st.env.execute(action))
        save_checkpoint(task.id, st)        # after every step
        if action.name == "submit":
            break
    return st.working_diff()
STUDIO 12

Repair a real repository issue

Pick an open issue in a project you did not write. Have your agent produce a patch, and record where its time actually went — locating the code, understanding conventions, or writing the change. Report the ratio; most teams are surprised by it.

KNOWLEDGE CHECK
READING
PRIMARYSWE-bench: Can Language Models Resolve Real-World GitHub Issues?
PRIMARYSWE-agent: Agent-Computer Interfaces Enable Automated Software Engineering
PRACTICEBuilding Effective Agents