Skip to content
AgenticAIWiki
  1. Learn
  2. Part 9
  3. 53. Specialised agents: coding, research and browser
  4. 53.1

Lesson 53.1 · 1 of 5 · 6 min read · Reviewed 24 Nov 2026

Coding agents: repo maps, diffs and test loops

By the end, you can

  • Describe the loop a coding agent runs: map, read, edit, test.
  • Explain why small diffs and a test loop make coding agents reliable.

A coding agent is the agent loopAgent loop: The cycle of calling the model, running any tools it requests, returning the results and repeating until it stops. from chapter 42 with three special tools: a way to see the repo, a way to change files, and a way to run checks. Tools such as Claude CodeClaude Code: Anthropic’s agentic coding tool that works in your terminal, IDE and CI, reading and editing code and running commands., Aider, OpenHands and SWE-agent all differ in detail, but they share this shape.

Step 1: a repo map, not the whole repo

A real repository can hold millions of tokens. The agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. starts with a repo map: a compactCompaction: Summarising older conversation history so a long session fits in the context window while keeping what matters. outline of files and the main symbols in each.

src/cart/total.py      def cart_total(items, coupon)   def apply_coupon(total, code)
src/cart/models.py     class Item(sku, price, qty)
tests/test_total.py    test_total_empty  test_total_with_coupon

From the map it picks a few files to read in full, using search tools (grep, glob, “find references”) to fill gaps. This is just-in-time retrieval (58.2) applied to code.

Step 2: small diffs

The agent edits by proposing a diff: replace these lines with those lines, in this file.

-    return total - discount
+    return max(0, total - discount)

Small diffs are good for three reasons: they are cheap in output tokensOutput tokens: The tokens the model generates in its reply, including any tool calls and thinking., a person can review them in seconds, and a failed one is easy to revert. Rewriting whole files invites the agent to drop code it did not mean to touch.

Step 3: the test loop

Tests turn “I think this is fixed” into a fact the agent can see.

Turn Agent does It sees
1 Runs pytest tests/test_total.py 1 failed: total is -5, expected 0
2 Reads total.py, edits one line Diff applied
3 Runs the test again 1 passed
4 Runs the whole suite 48 passed
5 Stops and reports the diff

The best loops start with a failing test that reproduces the bug. If there is none, the agent should write one first. Then “done” means the new test passes and the old ones still pass.

Guard the loop

  • Step limit. Stop after, say, 15 edit-and-test rounds and report what was tried.
  • Run tests in a sandboxSandbox: An isolated environment that limits what code or an agent can reach, such as files, network or credentials. (53.4). Test code is still code, and it runs with whatever access the machine has.
  • Read the failure, not just the exit code. Feeding the last 40 lines of test output back is usually enough; the full log floods the context.
  • Never edit the test to make it pass, unless the test itself is wrong and a person agrees.

Common mistakes

  • Pasting the whole repo into the prompt instead of a map plus search.
  • Letting the agent declare success without running anything.
  • Running only the one test it changed, and missing the three it broke elsewhere.
  • No step limit, so a stuck agent edits the same line back and forth for an hour.

Benchmarks such as SWE-bench measure exactly this loop: given a real issue and a repo, does the agent produce a patch that makes the hidden tests pass?

Key points

  • A coding agent cannot read a whole repo, so it starts from a repo map: files, symbols and how they connect.
  • It changes code as small diffs, which are cheap to review, easy to apply and easy to undo.
  • The test run is the agent's feedback signal: edit, run, read the failure, edit again, with a step limit.
  • A failing test written before the fix is the clearest definition of done.
Hands-on labRuns in the Playground

Build a repo map with ast

Turn a small repository into a compact map of files and symbols that a coding agent can read instead of the whole codebase.

You will have: A Python function that prints a repo map, plus a comparison of its size with the full source.

Steps

  1. Read the four files held in the REPO dictionary (no real files are used).
  2. Parse each file with the ast module and collect top-level functions with their arguments, and classes with their methods.
  3. Print one line per file: the path followed by its symbols.
  4. Estimate tokens for the map and for the full source (about 4 characters per token) and print the ratio.
  5. Use the map to name the file an agent should open first for the bug 'coupon makes the total negative'.

Done when

  • Every file in REPO appears in the map with at least one symbol.
  • The map is at least 2x smaller than the full source.
  • The suggested file is src/cart/total.py.

Open in the Playground No API key needed.

Starter code (Python)
REPO = {
    "src/cart/total.py": "def cart_total(items, coupon=0):\n    total = sum(i.price * i.qty for i in items)\n    return apply_coupon(total, coupon)\n\ndef apply_coupon(total, coupon):\n    return total - coupon\n",
    "src/cart/models.py": "class Item:\n    def __init__(self, sku, price, qty=1):\n        self.sku, self.price, self.qty = sku, price, qty\n\n    def line_total(self):\n        return self.price * self.qty\n",
    "src/shipping/rates.py": "FLAT = 4\n\ndef shipping_for(total, country='GB'):\n    if total > 50:\n        return 0\n    return FLAT if country == 'GB' else FLAT * 2\n",
    "tests/test_total.py": "def test_total_empty():\n    assert cart_total([]) == 0\n\ndef test_total_with_coupon():\n    assert cart_total([Item('a', 4)], coupon=10) == 0\n",
}

import ast

def symbols(source):
    # TODO: parse the source with ast.parse and return a list such as
    # ["def cart_total(items, coupon)", "class Item: __init__, line_total"]
    return []

def repo_map(repo):
    lines = []
    for path, src in sorted(repo.items()):
        lines.append(path + "  " + "  ".join(symbols(src)))
    return "\n".join(lines)

def tokens(text):
    return max(1, len(text) // 4)

m = repo_map(REPO)
print(m)
full = "".join(REPO.values())
print("map tokens:", tokens(m), "full tokens:", tokens(full))
# TODO: pick the file whose symbols mention "coupon" and print it as the file to open first
print("open first: ?")
Show a solution
REPO = {
    "src/cart/total.py": "def cart_total(items, coupon=0):\n    total = sum(i.price * i.qty for i in items)\n    return apply_coupon(total, coupon)\n\ndef apply_coupon(total, coupon):\n    return total - coupon\n",
    "src/cart/models.py": "class Item:\n    def __init__(self, sku, price, qty=1):\n        self.sku, self.price, self.qty = sku, price, qty\n\n    def line_total(self):\n        return self.price * self.qty\n",
    "src/shipping/rates.py": "FLAT = 4\n\ndef shipping_for(total, country='GB'):\n    if total > 50:\n        return 0\n    return FLAT if country == 'GB' else FLAT * 2\n",
    "tests/test_total.py": "def test_total_empty():\n    assert cart_total([]) == 0\n\ndef test_total_with_coupon():\n    assert cart_total([Item('a', 4)], coupon=10) == 0\n",
}

import ast

def symbols(source):
    out = []
    for node in ast.parse(source).body:
        if isinstance(node, ast.FunctionDef):
            out.append("def " + node.name + "(" + ", ".join(a.arg for a in node.args.args) + ")")
        elif isinstance(node, ast.ClassDef):
            methods = [n.name for n in node.body if isinstance(n, ast.FunctionDef)]
            out.append("class " + node.name + ": " + ", ".join(methods))
    return out

def repo_map(repo):
    lines = []
    for path, src in sorted(repo.items()):
        lines.append(path + "  " + "  ".join(symbols(src)))
    return "\n".join(lines)

def tokens(text):
    return max(1, len(text) // 4)

m = repo_map(REPO)
print(m)
full = "".join(REPO.values())
print("map tokens:", tokens(m), "full tokens:", tokens(full))
print("ratio: %.1fx smaller" % (tokens(full) / tokens(m)))
candidates = [p for p, src in REPO.items() if not p.startswith("tests/") and any("coupon" in s for s in symbols(src))]
print("open first:", candidates[0])
Quick checkA coding agent keeps 'fixing' a bug but the same test still fails on CI. What is the most likely gap in its loop?
How sure are you?
Pick an answer and how sure you are