Coding agent: reading, editing, and testing code in a safe loop
A coding agent reads a codebase, proposes edits as a diff, runs tests in a sandbox, and learns from failures. Use it for bug fixes and routine changes that a person reviews before merging.
Coding agent in 60 seconds
- What: an agent that reads code, edits files, runs tests, and repeats until the tests pass or its budget runs out.
- The key idea: tests are the feedback signal. The agent knows it is wrong when they fail.
- Best for: well-described bugs, small features, refactors, and test writing in a codebase with decent tests.
- Weak spots: vague tasks, weak tests, large cross-cutting changes, and code that passes tests but is wrong.
- Origin: SWE-bench (Jimenez et al., 2023) set up real GitHub issues from Python projects and judged a fix by the project's tests.
Where this type fits
In the Types of AI agents hub, the coding agent belongs to the family about the kind you build, next to the tool-using, browser, voice, and long-running agents. It is a tool-using agent with a specific toolset and a very clear feedback signal: whether the tests pass.
The problem it solves
Writing code from a prompt alone fails in a familiar way. The model produces a plausible function that calls an helper that does not exist, uses an old version of a library, or breaks a rule that only the rest of the codebase reveals. Nothing checks it, so the errors reach a person.
A person-only workflow has its own cost. Small tasks such as a failing test, a renamed field, or a missing null check eat time because most of the effort is finding the right place and running the checks, not typing the fix.
A coding agent connects the model to the real project. It can search to find the right file, read the code that surrounds the problem, make a change, and run the tests. The test output feeds back to the model, which sees the actual error rather than imagining one. This turns guessing into a loop with a measurable result. It still needs fences: the agent must work in a sandbox, within a step budget, and hand back a diff for review.
How it works
- Read the task: a bug report, a failing test, or a feature request, with any acceptance criteria.
- Explore: search the code, open the relevant files, and read tests and recent changes. Good agents read before they write.
- Edit as a diff: change only what is needed, and express edits as a diff so a person can see exactly what moved.
- Run the tests in a sandbox: an isolated environment with no access to secrets, production, or the open internet. Capture the output.
- Check the result: if the tests pass, move on. If they fail, read the error, and return to editing. The loop has a fixed step budget.
- Hand over for review: present the diff, the test results, and a short explanation. A person approves the merge.
The loop between 'tests pass?' and 'edit' does most of the work. A first attempt is often close but not right, and the failing test shows what is missing. The label 'within a step budget' matters: without a cap, a stuck agent will keep trying variations and spend money.
The final box is not decoration. Passing tests show the code does what the tests check. They do not show the change is wise, secure, or in the team's style. A person reads the diff before it merges.
A worked example
Acme Shop reports a bug: 'The discount code SAVE10 gives 10 percent off, but a cart of zero items crashes the checkout.' The repository has a test suite of 340 tests.
Step 1: reproduce. The agent searches for apply_discount and finds pricing/discount.py. It writes a new failing test, test_discount_on_empty_cart, which calls apply_discount(cart=[], code="SAVE10"). It runs the test. Result: ZeroDivisionError on line 41, in the percentage calculation.
Step 2: read. It opens the function and sees that it divides by cart.total(). For an empty cart the total is 0. It also reads two related tests to learn the expected return type: a dictionary with total and discount.
Step 3: edit. It proposes a three-line diff: return {total: 0, discount: 0} early when the cart is empty.
Step 4: test. It runs the new test: pass. It then runs the whole suite: 339 pass, 1 fails. test_discount_rounding now fails, because the early return skipped a rounding step used elsewhere.
Step 5: fix. It reads the failure, moves the early return after the rounding setup, and runs again. All 340 pass.
Hand-over. The agent presents a diff of two files (the fix and the new test), the test summary, and a note: 'Empty carts now return zero totals. Added one regression test.' A developer reviews it, spots no style issues, and merges. The run used 11 steps from a budget of 25.
{
"task": "Checkout crashes on empty cart with SAVE10",
"files_changed": ["pricing/discount.py", "tests/test_discount.py"],
"lines_added": 14,
"lines_removed": 1,
"tests": { "run": 340, "passed": 340, "failed": 0 },
"steps_used": 11,
"step_budget": 25,
"notes": "Added regression test. No dependency or config changes."
}Building it
The sketch below keeps the shape of the loop and its limits. Tool functions and the sandbox are placeholders. In a real system, the sandbox is the most important part to get right.
# Placeholders: llm, sandbox, and repo are stand-ins, not real libraries.
MAX_STEPS = 25 # total tool calls per task
TEST_TIMEOUT_S = 300 # a hung test must not stall the run
MAX_OUTPUT_CHARS = 6000 # trim logs so the context stays small
MAX_FILES_CHANGED = 10 # a bigger change needs a person to scope it
ALLOWED_TOOLS = {"search", "read_file", "apply_diff", "run_tests"}
def run_coding_agent(task):
# Work on a throwaway copy, never the main branch.
workspace = sandbox.create(repo.snapshot(task.branch), network=False)
history = [{"role": "user", "content": task.description}]
for step in range(MAX_STEPS):
action = llm.generate(history, tools=sorted(ALLOWED_TOOLS))
if action.done:
break
if action.tool not in ALLOWED_TOOLS:
history.append({"role": "tool", "content": "tool not allowed"})
continue
if action.tool == "apply_diff":
result = workspace.apply_diff(action.args["diff"])
if workspace.files_changed() > MAX_FILES_CHANGED:
return hand_over(task, workspace, status="too_large")
elif action.tool == "run_tests":
result = workspace.run_tests(timeout_s=TEST_TIMEOUT_S)
else:
result = workspace.call(action.tool, action.args)
history.append({"role": "tool", "content": str(result)[:MAX_OUTPUT_CHARS]})
final = workspace.run_tests(timeout_s=TEST_TIMEOUT_S)
status = "tests_pass" if final.all_passed else "tests_fail"
# Always end with a diff for a person. The agent never merges itself.
return hand_over(task, workspace, status=status)
def hand_over(task, workspace, status):
return {
"status": status,
"diff": workspace.diff(),
"tests": workspace.last_test_summary(),
}
Design decisions
- Sandbox: run every command in an isolated container or virtual machine, with no secrets, no production access, and by default no network. This is the main safety control.
- Permissions: give the agent a branch and a pull request, never direct write access to the main branch. Merging stays with a person or a protected pipeline.
- Edit format: use diffs rather than whole-file rewrites. Diffs are smaller, cheaper, easier to review, and less likely to remove code by accident.
- Context strategy: do not load the whole repository. Search first, then read only the relevant files, and trim long test logs. A recommended default is to cap each tool result at a few thousand characters.
- Budgets: set limits on steps, wall-clock time, and files changed. A task that exceeds them returns as 'needs a person' with notes on what was tried.
- Test strategy: run the specific test first for speed, then the full suite before hand-over. Slow suites may need a selected subset plus a full run in continuous integration.
- Secrets and dependencies: block changes to credentials, build pipelines, and dependency lists unless a person asks for them, and flag any such change loudly.
Measuring it
- Resolution rate: the share of tasks where the hidden or project tests pass after the agent's change, as in SWE-bench. Use tasks the agent has not seen.
- Regression rate: tasks that fix the target test but break others. Run the full suite, not just the target.
- Review acceptance: the share of agent diffs a reviewer merges without major changes. This captures quality that tests miss.
- Steps and cost per resolved task: total tool calls and model usage divided by resolved tasks, with the 95th percentile to find runaway cases.
- Test tampering rate: diffs that delete, skip, or weaken tests. Detect these by scanning diffs for removed assertions.
def evaluate(tasks):
resolved = regressed = 0
for t in tasks:
out = run_coding_agent(t)
tests = out["tests"]
target_ok = t.target_test in tests.passed
others_ok = not (set(t.previously_passing) - set(tests.passed))
resolved += 1 if (target_ok and others_ok) else 0
regressed += 1 if (target_ok and not others_ok) else 0
n = max(len(tasks), 1)
return {"resolved": resolved / n, "regressed": regressed / n}
When to use it, and when not to
| Situation | Use this type? | Why |
|---|---|---|
| A clear bug with a way to reproduce it | Yes | The failing test gives a precise target and quick feedback. |
| Routine changes such as renames, upgrades, or adding tests | Yes | The work is repetitive, and tests check the result. |
| The codebase has few or weak tests | Not yet | Passing tests will not mean much. Improve the tests first. |
| The task is vague, such as 'make it faster' | No | The agent lacks a target, so it guesses. Define the measure first. |
| Large design changes across many services | No | The context is too wide, and decisions need people. |
| Security-sensitive code, such as authentication | Only with close review | Subtle flaws can pass tests, so require an expert review. |
| Code that cannot run in a sandbox | Not yet | Without safe execution the agent cannot get feedback. |
Trade-offs
| Dimension | Effect | What to do about it |
|---|---|---|
| Quality | Good on well-specified tasks with strong tests, weaker on vague ones. | Write clear tasks, keep tests strong, and review every diff. |
| Latency | Minutes per task, since each step may run tests. | Run targeted tests first, and treat the agent as asynchronous. |
| Cost | Many model calls with large contexts, plus sandbox compute. | Cap steps, trim context, and stop early on stuck runs. |
| Complexity | Needs sandboxing, repository integration, and review flow. | Begin with one repository and one task type. |
| Failure modes | Tests passed but behaviour wrong, weakened tests, and unsafe commands. | Review diffs, scan for test changes, and restrict the sandbox. |
Compared with related types
A ReAct agent alternates thought and action in general. A coding agent is that loop specialised, with file and test tools and a concrete pass or fail signal. Compared with a general tool-using agent, the main differences are the sandbox and the diff, which exist because the tools can change code.
A person stays in the loop through a human checkpoint at review time. For a wider view of limits and checks, see guardrails and safety.
What this means for your role
Common mistakes
Further reading
- Types of AI agents: the hub page for all agent types.
- SWE-bench (Jimenez et al., 2023): a benchmark of real GitHub issues from Python projects, where a proposed fix is judged by the project's tests.
- Tool-using agent: the call handling that a coding agent builds on.
- Guardrails and safety: controls for actions that change things.
A coding agent is only as good as its tests and its fence. Give it a sandbox, a budget, and a reviewer, and it becomes a steady helper for the small jobs.