Coding and Software-Engineering Agents

Michael BrenndoerferDecember 1, 202637 min read

Learn how coding agents navigate repositories, verify edits with tests, and produce reviewable patches. Build a test-driven repair loop in Python.

Language AI HandbookAll chapters
Part 49 of 67Long-Horizon Agents and Interoperability
Chapter 374Coding and Software-Engineering Agents
Reading the full chapter · 12 sections · 37 min12 sections · 37 min

All 12 sections · 37 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Coding and Software-Engineering Agents

A request to fix a date parser may arrive with one line of expected behavior and no file name. A coding agent must find the implementation and its callers, establish what fails, make the change, and show what happened to the tests that already passed. The test suite gives feedback about the cases it exercises. A reviewer still needs the patch and evidence about the behavior outside those cases.

We will trace a small repair in a local repository. The example separates repository search, the visible test suite, independent checks, and review of the complete diff. It uses a predetermined patch and Python’s standard library, so you can run the exercise without a model or a package download.

The model proposes actions and edits. The environment supplies the repository, interpreter and tests. The harness connects them by setting the available tools, writable paths, test feedback and stopping rules. A stronger model can propose a better edit. The harness determines what that edit can touch and what evidence reaches the reviewer.

Coding agent

A system that uses a large language model in a loop to observe a software repository, decide on an action (search, read, edit, run a command), execute that action against a real or sandboxed environment, and repeat until a stopping condition such as "the target tests pass" is met. The essential properties are (a) repository-level context rather than a single file, (b) verifiable feedback from execution, and (c) changes materialized as inspectable patches rather than opaque prose.

What makes software a good environment for agents

Before we look at the loop, it is worth understanding why this domain rewards agentic treatment more than, say, open-ended question answering. The answer comes down to four properties, and each one shapes how we design the system.

A test runner records whether its assertions held for the cases it executed. A failed test can identify the expected output, the observed output, or an exception. The cost depends on the suite and what the environment has to start or install.

Verification can have different unit costs. The first figure compares two assumed unit costs under the same modeled budgets. A local test result and a human judgment answer different questions, so the example isolates the cost calculation.

PythonIn [3]
CollapseExpand
# Cost per verification sample, in USD. Order-of-magnitude estimates for
# illustration: a human rater's attention for one judgment vs. one cheap
# local subprocess test run.
cost_human_rater = 1.0
cost_subprocess = 0.0005
budgets = [10.0, 100.0, 1000.0]
budget_trials = {
    "human rater": [b / cost_human_rater for b in budgets],
    "test runner": [b / cost_subprocess for b in budgets],
}
for b in budgets:
    print(
        f"budget=${b:>7.0f}: human={b / cost_human_rater:>9.0f}  tests={b / cost_subprocess:>9.0f}"
    )
print("ratio (tests per human sample):", cost_human_rater / cost_subprocess)
ConsoleOut [3]
CollapseExpand
budget=$     10: human=       10  tests=    20000
budget=$    100: human=      100  tests=   200000
budget=$   1000: human=     1000  tests=  2000000
ratio (tests per human sample): 2000.0

The assumed costs give 2,000 test runs per human judgment at a fixed budget. Use measured costs for your own test suite and include the judgments it cannot replace.

VisualizationOut [4]
CollapseExpand
Bar chart of affordable trials by budget for human versus test feedback
Modeled trials under three budgets on a log scale. At the assumed 1 USD per human judgment and 0.0005 USD per test run, a budget buys 2,000 times as many test runs. The two feedback types answer different questions.

The second is composability of context. A repository is a structured corpus. Files import other files, functions call other functions, and tests reference the exact symbols under test. An agent with the right search tools can navigate this structure deliberately, jumping from a failing test to the function it exercises to the helper that function depends on, rather than being handed a fixed context window of code and hoping the relevant part is inside it. This is a very different problem from the "stuff everything into the prompt" approach, and it is why repository navigation is a first-class skill. The graph structure of imports and calls also means the agent can follow edges rather than guessing: from a failing assertion it can traverse to the definition, then to the callee that returned the wrong value, then to the constant that was misconfigured, each hop a principled step instead of a leap of faith.

A small, well-scoped diff is easier to review. For a localized behavior change, record which files changed and inspect how the modified code relates to its callers. Larger changes may still be necessary when the required behavior crosses a module boundary.

The fourth is auditability. A version-control diff records tracked content changes. If you also want to reconstruct how an agent reached the patch, retain the tools it called, their outcomes, and the model and resource settings used to make the decisions.

Verification is not correctness

Passing tests support the behavior they exercise. The evidence weakens if the proposed change can alter the verifier or make an overly narrow case pass.

HumanEval checks generated standalone Python functions against unit tests. Repository-level evaluations also ask the system to locate and change existing code, where compatibility with callers and the supplied checkout matters.

Give an agent the existing specification and the test result first. Repository search reveals where the implementation lives and which callers could be affected.

The repository navigation problem

Repository tasks usually expose more source than the model should read for one change. Start with a failing test or a symbol name, then use imports, references and call sites to determine which files belong in the working context. The right search scope depends on repository size and the task.

A small change may require reading several files around a much larger repository. Use search output as a starting point for selecting source to read.

Repository navigation uses lexical matches and code relationships such as imports and call sites. Document retrieval also retrieves selectively, though its search units and relevance judgments often differ.

An exact search for an identifier can narrow the files to inspect. Follow references or use a symbol index when several definitions share a name.

The navigation toolbelt

The tools a competent repository agent exposes to itself are, essentially, the tools a careful human engineer uses. You can think of them in increasing order of resolution:

  • Grep / regex search (Part I, Ch 3) finds every occurrence of a symbol, string, or pattern across the repository. It is the fastest way to answer "where is this function defined?" or "which files reference this class?" This is usually the first move.
  • Glob / directory listing gives the agent the shape of the repository, so it can learn the project layout, find the test directory, and understand which files are even candidates.
  • Symbol-aware search (an LSP, tree-sitter, or language-specific index) resolves definitions, references, and types, which plain grep cannot do when a name is overloaded across files.
  • Read opens a specific file or line range at full text. This is expensive in context, so you spend it only on candidates you have narrowed down.
  • Git history and blame reveals how a piece of code came to be and why, which is frequently the most informative evidence about how to change it.
  • The test suite itself is a navigation tool: a failing test names the exact function, the exact scenario, and often the exact expected output, which is a shortcut to the code you need.

Search results usually cost fewer input tokens than complete files. Start with a capped list and refine a broad query before reading files. A cap bounds what the tool returns; it does not make the underlying search free.

The fixture has 12 candidate files and 13 points on the progress axis. At zero, no candidate has been processed. The search-first policy has already paid for three search results. It then opens only the second and third candidates. The exhaustive policy reads a file at each candidate position.

PythonIn [5]
CollapseExpand
# Deterministic model of context cost. A grep returns ~200 tokens for a
# candidate list; reading a file costs ~4000 tokens. The funnel runs a fixed
# number of cheap searches first, then reads only the narrowed candidates.
n_candidate_files = 12
grep_cost = 200
read_cost = 4000
n_searches = 3

funnel_positions = list(range(n_candidate_files + 1))
shortlist = (2, 3)
blind_cumulative = [p * read_cost for p in funnel_positions]
funnel_cumulative = [
    n_searches * grep_cost + read_cost * sum(i <= p for i in shortlist)
    for p in funnel_positions
]

print("blind total tokens:", blind_cumulative[-1])
print("funnel total tokens:", funnel_cumulative[-1])
print("savings factor:", round(blind_cumulative[-1] / funnel_cumulative[-1], 1))
ConsoleOut [5]
CollapseExpand
blind total tokens: 48000
funnel total tokens: 8600
savings factor: 5.6

The search-first route costs 8,600 tokens in the calculation, compared with 48,000 for exhaustive reads. This result assumes the searches find the two useful files. A missed file or a broader shortlist changes the comparison.

VisualizationOut [6]
CollapseExpand
Line chart comparing cumulative context tokens for funnel versus blind reading
Modeled context costs for twelve candidates. Reading every file costs 48,000 tokens. Three search results cost 600 tokens up front; reading two shortlisted files brings that total to 8,600 tokens.

Inspect what the search excluded when a later test shows a missing dependency or caller. Refine the search before reading more source.

A symbol index can help distinguish same-named definitions or references where its language analysis supports them. Text search returns the matching text without deciding what a call resolves to.

Repository map

A compact outline of the repository. It can list important directories, top-level definitions and links to README and configuration files. A large index needs a selection budget so only relevant entries reach the model.

What the agent needs from the test name

A name like test_parse_iso_date_handles_leap_year suggests where to search and what to examine. Read the assertion to learn the input and the expected result before changing the parser.

A test name can expose a useful search term. test_case_7 gives little direction; a name containing the public API can point to callers and tests.

When no test exists, the engineer (or the agent) must write one first. That is the next section.

Test-driven changes

The loop that makes coding agents reliable is the classic red-green-refactor rhythm, adapted so the agent can drive it. It has a specific structure you should internalize because every design decision in the implementation follows from it.

Red-green loop
  1. Red: Establish a failing test that captures the desired behavior. If the test suite already has one, start here. If not, write a new test that fails for the right reason, and confirm it fails before touching the implementation.
  2. Green: Make the smallest change that turns the failing test green, using execution feedback from the test runner to guide the edits.
  3. Regress. Run the original suite after the change. Compare the named earlier passes with their new outcomes.

Check that the target fails because of the reported behavior. A missing dependency or a skipped case tells you little about whether the proposed edit is justified.

In the date fixture, the visible exception identifies the rejected leap day. Keep that exception in the run record so the green result can be related to the original failure.

Keep the edit close to the required behavior. This example constrains the changed path and verifies the final diff. Apply separate review to additional behavior changes.

Behavior under test is not behavior under use

Tests cover the cases they exercise. Run the existing suite because a changed function can affect callers other than the one in the issue. Passing that suite leaves unexercised behavior for review and further tests.

The general leap-year rule and a special case for 2000-02-29 can both pass the target test. The other visible tests and held-out cases check additional behavior. The reviewer can inspect whether the patch implements the rule and consider inputs the tests leave out.

Execution feedback

Execution is the agent's verifier and its teacher. As we established in Part XLVII, Ch 5, running the code and reading the result is what separates iterative refinement from one-shot generation. But not all execution feedback is created equal, and the quality of the loop depends heavily on how the feedback is presented to the model.

A raw test runner output can be enormous. A single failing import in a large suite might produce thousands of lines of traceback. If the agent hands that to the model verbatim, the useful signal (which assertion failed, what was expected, what was actual) is buried in noise. Good coding agents pass the model a structured summary: the failing test names, the assertion expression and its expected/actual values, the file and line of the failure, and a truncated stack trace. The model can then read the actual source at the cited line to understand the issue. This is the same "structured tool return" pattern from Part XLVIII, Ch 2.

The principle generalizes: every tool return is a lossy channel from the environment to the model, and the design of that channel is a design decision. A summary that keeps the failing assertion, the expected value, the actual value, and the file:line is nearly always sufficient; a summary that keeps ten thousand lines of framework traceback is nearly always harmful. The rule of thumb is: keep the information a human engineer would read first, and truncate the rest. If the model needs more, it can ask for it with a targeted read of the cited line. The truncation is safe precisely because the environment is queryable: the model can always go back for detail it was not shown.

Truncation has a subtle cost that should be recognized: a summary that drops too much can hide the reason for a failure in a way that sends the agent down the wrong path. A test that fails because of a missing import and a test that fails because of a wrong assertion can look similar in a too-aggressive summary. The design target is not minimalism for its own sake; it is the failure cause, expressed compactly. A good summary answers "what failed, and why, in one line per failure."

There is also a decision about which commands the agent may run. Running the tests is essential; running an arbitrary shell command from a suggestion is dangerous. We will devote real space to this in the safety section, because it is the sharpest risk surface of the whole chapter. For now, note the principle: the agent's action space should include the smallest set of execution capabilities that lets it verify its work, and nothing more.

Signal quality and the "green but wrong" problem

Here is the crux of execution feedback. The signal is crisp but narrow. It tells you exactly whether the tests pass. It says nothing about whether the tests are the right tests, whether they cover the behavior that matters, or whether the change that turned them green is the change the human wanted. There are at least four ways a coding agent can produce a fully green suite and still be wrong:

  • Test tampering: the agent deletes, skips, or weakens the failing test instead of fixing the code. Common, and easy to detect if you forbid edits to test files.
  • Special-casing: the agent makes the specific test input pass while leaving the general behavior broken, for example if input == "2024-02-29": return True.
  • Overfitting to visible tests: the change passes the visible tests the agent can see but fails held-out behavior the human wanted. This is the coding-agent analog of train/test contamination from Part XX, Ch 6, and it is why we evaluate against tests the agent cannot see.
  • Collateral regressions: the change fixes the target test but silently changes behavior the suite doesn't cover.

Keep the visible verifier outside the edit scope and run separate cases against a copied candidate. Compare the complete diff with the original. These checks expose different classes of errors.

Each check answers one question. Stable test contents say something about the verifier, while new cases test behavior outside the examples the proposer used. Reviewing changed paths helps preserve unrelated files.

Repository-level evaluation: SWE-bench and friends

If this chapter has a canonical benchmark, it is SWE-bench. It deserves a paragraph both because it defines how the field measures repository-level agents and because how it is constructed illustrates every pitfall we are about to defend against.

SWE-bench pairs real GitHub issues with their resolving pull requests from Python repositories. The system gets the issue and a pre-fix checkout and proposes a patch. The benchmark checks designated fail-to-pass and pass-to-pass tests. These test lists define the scoring rule; a passing result does not assert that the repository’s entire suite or every behavior was checked.

SWE-bench separates a pull request's test changes from the reference solution. During task validation, the builders apply the test patch to the pre-PR checkout and run the tests before and after applying the solution. Tests that move from failing to passing form the F2P list. Tests that pass in both runs form the P2P list. The agent sees the issue and the pre-PR checkout, which can contain earlier versions of the edited tests. The benchmark applies the PR test patch when it grades the agent's proposed changes.

SWE-bench Verified began as a human-screened 500-instance subset. The screening considered whether the issue description provided enough information and whether the tests reasonably assessed the fix. Compare results only with the named dataset revision, subset, test and tool visibility, retry policy, and resource budget.

RepoBench evaluates repository-level retrieval and code completion. Those tasks differ from submitting a repository patch against an issue and checking the result with tests. For any comparison, report what the system could see and which evidence decided success.

We will build our worked example in the spirit of SWE-bench, at a scale that fits in a chapter: a toy repository, a target test that fails, a few held-out behavioral checks the agent cannot see, and a constraint that the agent may only edit non-test source files. The goal is not to reproduce a benchmark score but to make every piece of the pipeline legible.

A worked example: fixing a date parser

The small datekit fixture splits three dash-separated integer fields. Its only calendar check rejects February 29 in years that lack a leap day. The issue says it rejects a leap-year date. We will locate the failing test, apply a constrained edit and review the result.

The repository layout is:

datekit/ datekit/ __init__.py parse.py <- contains parse_iso_date tests/ test_parse.py <- the visible test suite

The buggy parser reads three dash-separated integer fields. Its leap-year check accepts years divisible by 4 and rejects every year divisible by 100. The Gregorian rule makes one exception for century years divisible by 400, so the fixture wrongly rejects 2000.

PythonIn [7]
CollapseExpand
# datekit/datekit/parse.py  (buggy)
def _is_leap(year):
    if year % 100 == 0:
        return False  # BUG: 2000 is a leap year (divisible by 400)
    return year % 4 == 0


def parse_iso_date(s):
    year, month, day = (int(p) for p in s.split("-"))
    if month == 2 and day == 29 and not _is_leap(year):
        raise ValueError(f"invalid date: {s}")
    return (year, month, day)

The visible test only covers a non-century leap year (2024) and a non-leap year (2023), so it passes. A new test, written by the reporter, exercises 2000-02-29 (a leap year, divisible by 400) and fails. This is our red state. The agent's task is to turn it green and keep the rest of the suite green without touching the tests.

We are going to build this entire pipeline in code. Everything below runs with the standard library, uses no network, and produces the same output each run. Let's set it up.

A temporary fixture repository

We create a private temporary directory holding a fixed parser and its visible tests. The parser illustrates leap-year behavior. The exercise does not implement a general ISO date validator, and dates outside that scope are not graded as if it did.

PythonIn [8]
CollapseExpand
import ast
import difflib
import re
import subprocess
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from textwrap import dedent

fixture_directory = TemporaryDirectory(prefix="datekit-notebook-")
ROOT = Path(fixture_directory.name)
(ROOT / "datekit").mkdir()
(ROOT / "tests").mkdir()

(ROOT / "datekit" / "__init__.py").write_text(
    "from .parse import parse_iso_date\n", encoding="utf-8"
)
(ROOT / "datekit" / "parse.py").write_text(
    dedent("""            def _is_leap(year):
        if year % 100 == 0:
            return False  # century years are incorrectly rejected
        return year % 4 == 0

    def parse_iso_date(s):
        year, month, day = (int(p) for p in s.split("-"))
        if month == 2 and day == 29 and not _is_leap(year):
            raise ValueError(f"invalid date: {s}")
        return (year, month, day)
    """).lstrip(),
    encoding="utf-8",
)
(ROOT / "tests" / "test_parse.py").write_text(
    dedent("""            import unittest

    from datekit import parse_iso_date


    class DateParserTests(unittest.TestCase):
        def test_regular_leap_year(self):
            self.assertEqual(parse_iso_date("2024-02-29"), (2024, 2, 29))

        def test_ordinary_non_leap_year(self):
            with self.assertRaises(ValueError):
                parse_iso_date("2023-02-29")

        def test_century_leap_year(self):
            self.assertEqual(parse_iso_date("2000-02-29"), (2000, 2, 29))
    """).lstrip(),
    encoding="utf-8",
)

VISIBLE_FILES = tuple(sorted(p.relative_to(ROOT) for p in ROOT.rglob("*.py")))
SOURCE_ONLY = Path("datekit/parse.py")


def snapshot(root=ROOT):
    return {
        p.relative_to(root): p.read_text(encoding="utf-8")
        for p in sorted(root.rglob("*"))
        if p.is_file()
    }


initial_files = snapshot()

The setup writes the known source and test files and saves a before-edit snapshot. It compares relative paths and decoded UTF-8 text. The snapshot does not preserve filesystem metadata, and text reading normalizes line endings.

Each run begins with a new directory. The directory makes the example easy to reset and keeps it separate from any working project.

The read-only navigation tools

The navigation functions read an enumerated set of fixture files. The search output has a hit limit, and the reader only accepts a known visible file. For production access, enforce the repository boundary independently of tool prompts.

PythonIn [9]
CollapseExpand
def grep(pattern, max_hits=20):
    """Search the fixed visible fixture files, returning at most max_hits rows."""
    if max_hits < 1:
        return []
    regex = re.compile(pattern)
    hits = []
    for path in VISIBLE_FILES:
        for number, line in enumerate(
            (ROOT / path).read_text().splitlines(), 1
        ):
            if regex.search(line):
                hits.append((str(path), number, line.strip()))
                if len(hits) == max_hits:
                    return hits
    return hits


def read_file(relative_path, start=1, end=None):
    """Read a known visible fixture file using a 1-indexed inclusive line range."""
    path = Path(relative_path)
    if path not in VISIBLE_FILES:
        raise ValueError("Choose one of the visible fixture files.")
    lines = (ROOT / path).read_text().splitlines()
    if start < 1 or (end is not None and end < start):
        raise ValueError("Invalid line range.")
    return "\n".join(lines[start - 1 : end]), len(lines)


def repo_map():
    """Summarize the fixed visible Python files and their top-level symbols."""
    out = []
    for path in VISIBLE_FILES:
        tree = ast.parse((ROOT / path).read_text())
        names = [
            node.name
            for node in tree.body
            if isinstance(node, (ast.FunctionDef, ast.ClassDef))
        ]
        out.append((str(path), names))
    return out
ConsoleOut [10]
CollapseExpand
== Repository map ==
datekit/__init__.py: []
datekit/parse.py: ['_is_leap', 'parse_iso_date']
tests/test_parse.py: ['DateParserTests']

== grep for 'leap' ==
datekit/parse.py:1: def _is_leap(year):
datekit/parse.py:8: if month == 2 and day == 29 and not _is_leap(year):
tests/test_parse.py:7: def test_regular_leap_year(self):
tests/test_parse.py:10: def test_ordinary_non_leap_year(self):
tests/test_parse.py:14: def test_century_leap_year(self):

The repository map names the parser functions and the visible test class. Searching for leap brings both the implementation and the relevant test names into view. The test body gives the exact input and expected tuple.

The max_hits cap on grep is a small but important design choice. Without it, a search for a common token like leap in a large repository could return thousands of lines and flood the model's context. The cap forces the first search to return a triage list, not an exhaustive answer, and the agent's next move is to refine the query if twenty hits are not enough. This mirrors how a human uses grep | head interactively. The cap is not a limitation; it is a context-discipline mechanism.

Now the agent reads the two files that matter, spending context only where the grep pointed.

ConsoleOut [11]
CollapseExpand
--- datekit/parse.py (10 lines) ---
def _is_leap(year):
    if year % 100 == 0:
        return False  # century years are incorrectly rejected
    return year % 4 == 0

def parse_iso_date(s):
    year, month, day = (int(p) for p in s.split("-"))
    if month == 2 and day == 29 and not _is_leap(year):
        raise ValueError(f"invalid date: {s}")
    return (year, month, day)

--- tests/test_parse.py (15 lines) ---
import unittest

from datekit import parse_iso_date


class DateParserTests(unittest.TestCase):
    def test_regular_leap_year(self):
        self.assertEqual(parse_iso_date("2024-02-29"), (2024, 2, 29))

    def test_ordinary_non_leap_year(self):
        with self.assertRaises(ValueError):
            parse_iso_date("2023-02-29")

    def test_century_leap_year(self):
        self.assertEqual(parse_iso_date("2000-02-29"), (2000, 2, 29))

The two reads locate _is_leap in datekit/parse.py and test_century_leap_year in the visible suite. The target expects (2000, 2, 29). Establish that this is the failing behavior before touching the source.

Running the tests to establish the red state

Run the notebook interpreter with -m unittest discover to select a known fixture suite. The child runs in the fixture’s working directory with a fixed command, a timeout and a small replacement environment. These settings make the local exercise repeatable. Filesystem and network isolation require separate controls.

PythonIn [12]
CollapseExpand
def run_suite(root=ROOT, test_dir="tests"):
    """Run the named trusted fixture suite with the notebook's Python."""
    if test_dir not in {"tests", "independent_checks"}:
        raise ValueError("Choose a known local fixture suite.")
    proc = subprocess.run(
        [
            sys.executable,
            "-B",
            "-m",
            "unittest",
            "discover",
            "-s",
            test_dir,
            "-v",
        ],
        cwd=root,
        env={"PYTHONIOENCODING": "utf-8", "PYTHONNOUSERSITE": "1"},
        capture_output=True,
        text=True,
        timeout=20,
        check=False,
    )
    output = proc.stdout + proc.stderr
    statuses = dict(
        re.findall(r"^(test_\w+) \(.*\) \.\.\. (ok|FAIL|ERROR)$", output, re.M)
    )
    errors = re.findall(r"^(?:ValueError|AssertionError): (.+)$", output, re.M)
    return {"returncode": proc.returncode, "status": statuses, "errors": errors}


red = run_suite()
ConsoleOut [13]
CollapseExpand
Visible suite before patch, exit: 1
  ERROR test_century_leap_year
  ok    test_ordinary_non_leap_year
  ok    test_regular_leap_year
Failure detail: ['invalid date: 2000-02-29']

Before editing, two cases pass and the century case errors with the exact invalid-date exception. An unrelated import or setup error would not establish the expected red state. Check the target test’s identity and error before applying the known repair.

Verbose unittest output names each fixture test and reports ok, FAIL, or ERROR. Together with the process exit status, that map lets the example distinguish a fixed target from missing or newly failing tests.

A minimal patch, enforced

Now the agent proposes a change. In a real system this would be the model's output; here we simulate the fact of the proposal and focus on the machinery that surrounds it: applying the patch as a surgical edit and enforcing constraints on what may change.

The repair changes the return value in the century branch. A century divisible by 400 is a leap year. Ordinary years continue through the existing divisibility-by-four branch. Apply the edit only after checking the red result.

PythonIn [14]
CollapseExpand
def apply_patch(relative_path, old, new):
    """Edit the one allowed source file in the trusted fixture."""
    if Path(relative_path) != SOURCE_ONLY:
        raise PermissionError("Only the fixture parser can change.")
    path = ROOT / SOURCE_ONLY
    if path.is_symlink() or path.parent.is_symlink() or not path.is_file():
        raise ValueError("The expected fixture file is missing or replaced.")
    text = path.read_text(encoding="utf-8")
    if text.count(old) != 1:
        raise ValueError("The old fragment must match exactly once.")
    path.write_text(text.replace(old, new), encoding="utf-8")
PythonIn [15]
CollapseExpand
target_test = "test_century_leap_year"
assert red["returncode"] == 1 and red["status"].get(target_test) == "ERROR"
assert red["errors"] == ["invalid date: 2000-02-29"]
old = "        return False  # century years are incorrectly rejected"
new = "        return year % 400 == 0"
apply_patch(SOURCE_ONLY, old, new)
print("Patch applied to", SOURCE_ONLY)
ConsoleOut [15]
CollapseExpand
Patch applied to datekit/parse.py

The patch function checks the permitted fixture path and requires one exact old fragment. It rejects an unexpected file and a missing or duplicated match before writing. The final full-tree snapshot checks which paths changed.

The fixture keeps the verifier files outside the write allowlist. The patch helper checks the file again before opening it. The two snapshots reveal changes to file membership and decoded text.

The green step, and a check the agent cannot see

Run the visible tests again. Separately, the evaluator copies the two source files into a new temporary directory and creates its own tests there. Those tests were outside the earlier search and patch workflow. The reader can see both sides of the simulation.

The separate checks compare century cases from 1700 to 2500 with calendar.isleap and include an unrelated ordinary date. This tests additional years beyond the visible examples.

PythonIn [16]
CollapseExpand
INDEPENDENT_CHECKS = dedent("""            import unittest
    from calendar import isleap

    from datekit import parse_iso_date


    class IndependentDateChecks(unittest.TestCase):
        def test_century_boundaries_against_standard_library(self):
            for year in range(1700, 2501, 100):
                with self.subTest(year=year):
                    example = f"{year}-02-29"
                    if isleap(year):
                        self.assertEqual(parse_iso_date(example), (year, 2, 29))
                    else:
                        with self.assertRaises(ValueError):
                            parse_iso_date(example)

        def test_unrelated_ordinary_date(self):
            self.assertEqual(parse_iso_date("2023-01-15"), (2023, 1, 15))
""").lstrip()


def run_held_out(candidate_files):
    """Evaluate a snapshot with grader-owned checks outside the fixture tree."""
    with TemporaryDirectory(prefix="datekit-checks-") as other:
        other_root = Path(other)
        (other_root / "datekit").mkdir()
        (other_root / "independent_checks").mkdir()
        for relative_path in (Path("datekit/__init__.py"), SOURCE_ONLY):
            (other_root / relative_path).write_text(
                candidate_files[relative_path], encoding="utf-8"
            )
        (other_root / "independent_checks" / "test_dates.py").write_text(
            INDEPENDENT_CHECKS, encoding="utf-8"
        )
        return run_suite(other_root, "independent_checks")

The independent suite includes century cases such as 1900, 2000 and 2400, as well as an ordinary date. For example, a proposal that accepts only the two known leap years in the visible suite would still fail the independent century cases.

The 1900 case catches a rule that admits all century leap days. The 2400 case catches an edit specific to 2000. The ordinary date checks that the change leaves that unrelated behavior intact.

PythonIn [17]
CollapseExpand
green = run_suite()
held = run_held_out(snapshot())
pass_to_pass = [
    name for name, status in red["status"].items() if status == "ok"
]
print("Visible suite after patch, exit:", green["returncode"])
for name, status in green["status"].items():
    print(f"  {status:5s} {name}")
print("Target fixed:", green["status"].get(target_test) == "ok")
print(
    "Earlier passes preserved:",
    all(green["status"].get(name) == "ok" for name in pass_to_pass),
)
print("Independent suite:", held["status"])
ConsoleOut [17]
CollapseExpand
Visible suite after patch, exit: 0
  ok    test_century_leap_year
  ok    test_ordinary_non_leap_year
  ok    test_regular_leap_year
Target fixed: True
Earlier passes preserved: True
Independent suite: {'test_century_boundaries_against_standard_library': 'ok', 'test_unrelated_ordinary_date': 'ok'}

The target changes from an error to a pass, earlier visible passes remain passes, and the independent suite succeeds. Check that the same visible test identities remain present. These results support the patch for the cases evaluated and leave approval to a reviewer.

  • F2P (fail-to-pass): the target test went red to green. Here, test_century_leap_year.
  • P2P (pass-to-pass): the previously passing tests still pass. Here, the other two visible tests.
  • Held-out behavioral checks: the agent-invisible suite passes. It catches the tested century special cases and checks one ordinary date.

Require each of the three checks before sending the patch to review. Other special cases can still pass these checks, so the reviewer reads the proposed rule and considers where the tests leave gaps.

A tiny review pass

The last step is review. We can't automate a human judgment in a chapter, but we can automate the mechanical review checks that a reviewer would otherwise do by hand, and we can produce the diff that a human would look at. A reviewer model (a second LLM, or the human) then reads the diff and the check summary.

For this fixture, compare every file present before or after the edit. Require just datekit/parse.py to differ, then check the full-file diff contains exactly one removed and one added line.

PythonIn [18]
CollapseExpand
def mechanical_review(before, after):
    paths = set(before) | set(after)
    changed = {p for p in paths if before.get(p) != after.get(p)}
    if changed != {SOURCE_ONLY}:
        raise AssertionError(
            f"Unexpected changed paths: {sorted(map(str, changed))}"
        )
    diff = list(
        difflib.unified_diff(
            before[SOURCE_ONLY].splitlines(),
            after[SOURCE_ONLY].splitlines(),
            fromfile=f"before/{SOURCE_ONLY}",
            tofile=f"after/{SOURCE_ONLY}",
            lineterm="",
        )
    )
    added_lines = sum(line.startswith("+") for line in diff[2:])
    removed_lines = sum(line.startswith("-") for line in diff[2:])
    if (added_lines, removed_lines) != (1, 1):
        raise AssertionError(
            "This fixture expects one removed and one added line."
        )
    return diff
PythonIn [19]
CollapseExpand
assert green["returncode"] == 0 and held["returncode"] == 0
assert red["status"].keys() == green["status"].keys()
assert green["status"].get(target_test) == "ok"
assert all(green["status"].get(name) == "ok" for name in pass_to_pass)
changed_diff = mechanical_review(initial_files, snapshot())
print("Only the allowlisted file changed. Full-file diff:")
print("\n".join(changed_diff))
ConsoleOut [19]
CollapseExpand
Only the allowlisted file changed. Full-file diff:
--- before/datekit/parse.py
+++ after/datekit/parse.py
@@ -1,6 +1,6 @@
 def _is_leap(year):
     if year % 100 == 0:
-        return False  # century years are incorrectly rejected
+        return year % 400 == 0
     return year % 4 == 0
 
 def parse_iso_date(s):

The full-file diff shows one replaced line and its surrounding code. Read that context along with the before/after test results. A small patch makes review easier, but the size check alone cannot verify the intent or the behavior.

The mechanical checks enforce scope and preserve the complete diff. A reviewer still checks the Gregorian rule, surrounding assumptions, and coverage of additional cases.

The diff is the artifact

Hand over the patch with its observed test results and mechanical scope check. The complete diff shows what changed. The reviewer uses that evidence to decide whether the change is ready.

The worked example in one loop

Before moving on, let's restate the whole pipeline as the loop a real agent would run, because the narrative above is what the loop does over one task. The loop is: map the repository, grep for the failing test's subject, read the candidate files, run the tests to confirm red, propose a minimal patch, apply it under constraint, run visible tests, run held-out checks, run mechanical review, and hand off the diff. Every step is either a read-only observation or a constrained mutation followed by a verifier. Nothing in the loop trusts the model's confidence. The model's output is a candidate action; the environment decides whether it was any good.

Long-running and multi-step tasks

The toy example fits in one turn. Real engineering work does not. A typical issue touches several files, takes many edit-test cycles, and may run for tens of minutes to hours. This creates a set of concerns that are specific to long-horizon agents and that we should name even though the full treatment belongs in Part XLIX, Ch 4 and Part XLIX, Ch 8.

Resumability. Retain the starting revision, working changes, test results and next planned step. Git records tracked content, while a separate trace can preserve decisions and command outcomes.

The second is step and time budgets. An agent can loop forever on a flaky test. You need a hard cap on iterations, wall-clock time, and (for cost) total tokens, plus a "give up and hand off to a human" path. This is not a limitation to work around; it is a design requirement. A coding agent that runs until it decides it is done is a liability. The budget is also a predictability mechanism: a team adopting an agent wants to know that a task will either succeed or escalate within a bounded cost, not that it might run all night and burn a budget.

Convergence detection. Stop editing when the declared acceptance checks pass. Here they include the target test, earlier passes, the independent checks and the mechanical scope check. Hand the candidate to the reviewer. A green visible suite alone does not meet that acceptance criterion.

Context management. Over several iterations, keep a concise working summary of the available evidence, unresolved questions and next action. Supply that summary to later model calls and retain the raw command and decision trace separately for audit.

Environment drift. Version the dependencies and execution image, and retain the test inputs. Even in a pinned environment, test scheduling, external state or randomness can produce different results.

Safety: executing untrusted code and provenance

A repository test run can execute code from the repository and its dependencies. A production service that accepts untrusted repositories needs a boundary to control where that code runs and what it can access.

Use the same execution policy for code run by test hooks as for any other user-controlled program.

The agent's verifier is attacker-controlled

When a coding agent runs a repository's tests, the tests come from the repository being edited, which may be a user-supplied or third-party codebase. Test files, conftest.py, setup.py, and imported modules are all code that executes during a test run. Treat every test runner invocation as executing untrusted code, and sandbox accordingly.

Least privilege for the agent

Give the test runner the permissions, data and resources the task needs. Layer controls that match the application’s threat model so the runner cannot reach unrelated assets or consume unbounded resources.

  • Filesystem isolation: limit access to the task repository and supporting files needed by the runner. Keep unrelated directories and host credentials outside that boundary.
  • Network access: deny outbound connections by default. Grant only destinations and credentials the authorized task needs.
  • Resource limits: use memory, CPU and elapsed-time limits to bound the impact of runaway work.
  • Drop privileges: run as an unprivileged user with no ability to sudo, and use a fresh container per run.
  • Ephemeral state: give each run a clean snapshot and keep retained results separate from its writable environment.
  • Egress allowlist, if you must allow some networking (package installation), limited to the package registry, and pinned.

The notebook runs only trusted local fixture code. Its clean temporary directories, fixed command, environment variables, and timeout are for a repeatable teaching example. A service that runs untrusted code needs a separate enforcement boundary with minimal permissions and explicit filesystem, network, and resource controls.

Filesystem access, network access, privileges, resource limits and clean snapshots control different parts of the job. Overlapping controls can limit some failures. Verify each boundary against the actual execution environment and the task’s threat model.

Dependency provenance

Dependency installation adds another trust decision. Review registry, package identity, artifact integrity and resolution policy, including transitive dependencies. A pinned name or version alone cannot establish that a package is appropriate.

Use a reviewed dependency specification, a trusted registry or build source, and integrity checks. Install needed dependencies in a controlled build separate from running the task. The fixture introduces no third-party dependency and permits only the parser source file to change.

Limit installation to the dependency artifacts the project has approved. A new dependency needs its own approval and a fresh build using the intended source.

Defensive review of generated code

Finally, the review step itself is a safety control. A human (or a separate reviewer model) should look for the failure modes we have been cataloguing, in roughly this order:

  • Did the tests change, and if so, why? Any modification, deletion, skip, or assertion weakening is a red flag until explained.
  • Is the change minimal and local? A one-line fix to a subtle bug should be roughly one line. Large diffs deserve large review.
  • Does the change special-case the tests? Look for literal inputs from the test file in the source, or conditionals keyed on specific values.
  • Does it introduce dangerous constructs? eval, exec, os.system, subprocess, dynamic imports, or network calls in a function that had none.
  • Does it match repo conventions? A patch in a style foreign to the codebase is suspicious, or at best needs reformatting.
  • Are the held-out checks green? Always re-run them independently of the agent's claim.

This is a review checklist, not a substitute for human judgment. The human owns the approve button; the agent owns the proposal.

Start with changed paths, verifier integrity and expected patch scope. Then review the behavior and its coverage. A passing scope check can still leave a wrong change in the one allowed file.

Limitations and open problems

The picture we have drawn is honest about its boundaries, and it is worth stating the remaining ones plainly, because they are where the field is still working and where you will get bitten.

Test coverage. Visible tests and separate evaluator cases still reflect choices made by their authors. Review the actual diff and consider behavior those cases leave out.

Benchmark scores depend on the protocol. Compare the named subset, runner, attempt budget and visibility conditions. A result on a public benchmark gives evidence about those tasks. Performance on a different repository needs its own evaluation with the relevant constraints.

Repository navigation. A search can return several definitions with the same name, miss generated code, or leave a dynamically selected call unresolved. Inspect the relevant callers and build rules when text search leaves those questions open.

Flaky tests. An initial pass and a pass after retries give different evidence about the verifier. Keep both outcomes and investigate variation before treating it as a repair.

Untrusted repository text. Source comments and issue descriptions can contain instructions from someone who lacks permission to act. Treat those strings as task data and enforce available actions outside the model. Keep the separate agent safety discussion in view when designing that boundary.

The practical deliverable is a patch plus evidence about the tests and files affected. The review can then address behavior the test suite has not exercised.

Summary

A coding and software-engineering agent is a language model operating a disciplined read-evaluate-edit loop over a real repository, using execution as a verifier. The domain rewards agentic treatment because code is executable (crisp feedback), composable (navigable structure), discrete (small changes), and auditable (inspectable patches).

  • Navigation is a funnel. Use grep, glob, and symbol search to narrow, then read to examine. Build a cheap repository map so the first search is informed. The test name itself is a locator.
  • Test-driven flow is what makes the loop reliable. Establish a failing test (red), make the smallest change that turns it green, then verify the whole suite (regress). Insist the target test fails for the right reason before editing.
  • Test evidence has a scope. Keep the evaluator independent from the edit. Earlier passes and independent cases check selected behaviors. Inspect the complete diff for collateral changes and the untested branches.
  • Hand off the complete diff. Include the observed test results and scope checks so the reviewer can decide whether to accept the change.
  • Evaluate like SWE-bench. F2P (target goes red-to-green), P2P (the designated previously passing tests still pass), and held-out checks. Be suspicious of any single benchmark score: subset, harness, retries, and test visibility all change it.
  • Bound the work. Save the current state and test results. Limit iterations and time, then hand the candidate over when the declared acceptance checks pass or the budget expires.
  • Test execution needs an isolation boundary. Use restricted permissions, bounded resources, fresh state and reviewed dependencies. In the fixture, the mechanical check enforces the changed path and edit size. Review capabilities introduced by the diff separately and run independent behavior checks before accepting the patch.

The persistent lesson across all of it is that the model is the proposal engine and the environment is the judge. You never trust the proposal; you trust the verifier, the diff, and the review. Everything else is engineering discipline around that loop.

As we head into Part XLIX, Ch 3: Deep-Research Agents, you will see the same shape of problem, many navigation tools and a long-horizon verification loop, applied to web research rather than source code, with the additional twist that the "test" for a research answer is far fuzzier than a unit test. The contrast is instructive: what makes coding agents tractable is not that they are smarter, but that software gives them a verifier they can trust.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about coding and software-engineering agents.

Coding and Software-Engineering Agents

Question 1 of 80 of 8 completed
According to the chapter, what does the harness determine, as distinct from what the model proposes?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 16

Model Context Protocol

Learn how MCP connects AI hosts to tools, resources, and prompts using JSON-RPC, covering versions, capabilities, transports, and trust boundaries.

30 min read
Language AI Handbook · Vol. 16

Durable and Asynchronous Agent Work

Design agent runners for recovery with event logs, leases, idempotency keys, retries, deadlines, and reconciliation.

46 min read
Language AI Handbook · Vol. 16

Deep-Research Agents

Build deep-research agents that plan multi-step investigations, verify citations, count independent evidence, and abstain when sources are thin.

51 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026codingsoftware, author = {Michael Brenndoerfer}, title = {Coding and Software-Engineering Agents}, year = {2026}, url = {https://mbrenndoerfer.com/writing/coding-software-engineering-agents-repository-navigation-test-driven-patches}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Coding and Software-Engineering Agents. Retrieved from https://mbrenndoerfer.com/writing/coding-software-engineering-agents-repository-navigation-test-driven-patches
MLAAcademic
Michael Brenndoerfer. "Coding and Software-Engineering Agents." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/coding-software-engineering-agents-repository-navigation-test-driven-patches>.
CHICAGOAcademic
Michael Brenndoerfer. "Coding and Software-Engineering Agents." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/coding-software-engineering-agents-repository-navigation-test-driven-patches.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Coding and Software-Engineering Agents'. Available at: https://mbrenndoerfer.com/writing/coding-software-engineering-agents-repository-navigation-test-driven-patches (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Coding and Software-Engineering Agents. https://mbrenndoerfer.com/writing/coding-software-engineering-agents-repository-navigation-test-driven-patches
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy