Coding Agent Architecture and Code Understanding
A coding agent is a model in a loop with your repository and a terminal. Its quality depends on what it reads, what it can run and how it checks itself.
A coding agent repeats a cycle: find the relevant code, change it, run checks and read the results, until the goal is met or a limit is reached. The model supplies judgment. The surrounding program supplies tools, context selection, permissions and stopping rules. Reliable work comes from good retrieval and checks the agent cannot talk its way past.
What you will learn: the parts of a coding agent, how it understands a large codebase, how edits are applied and verified, and how to prepare a repository so it works well.
Prerequisites: Single-Agent, Router and Retrieval Patterns and Agent Tools, Function Calling and Tool Registries.
Written in November 2026. The examples use only the Python standard library. Products change quickly, so this page describes the common design and names few tools.
Four ways to work with one
| Mode | Where it runs | You are | Suits |
|---|---|---|---|
| Completion | Your editor | Typing | Small, local code |
| Interactive agent | Editor or terminal | Watching and steering | Features, debugging, exploration |
| Background agent | A separate machine or container | Reviewing the result | Well-specified tasks |
| Pipeline agent | Your build system | Often absent | Narrow, repetitive jobs with strict limits |
As you move down the table, clear instructions and automatic checks matter more, because nobody is there to notice a wrong turn.
The work loop
The parts
| Part | Job | If it is weak |
|---|---|---|
| Instructions | Project rules, commands and limits | Work ignores your conventions |
| Context selection | Chooses files and output to show the model | The agent edits the wrong place |
| Search tools | Find names, text and references | It guesses, or invents functions |
| Edit tool | Changes files precisely | Corrupted or lost code |
| Execution environment | Runs tests, builds and linters | No evidence that anything works |
| Permission layer | Decides what may run or leave | Damage or data exposure |
| Session record | Keeps what was tried and learned | Repeated mistakes; no audit trail |
Finding the right files
A repository is usually far larger than what a model should read for one task. Agents combine several ways of narrowing it down.
| Method | Strength | Limit |
|---|---|---|
| Text search | Fast, exact, always current | Misses different wording |
| File names and structure | Cheap orientation | Depends on tidy naming |
| Symbol outline from a parser | Shows definitions and imports compactly | Needs support per language |
| Language server | Accurate definitions and references | Needs a working project setup |
| Embedding search | Matches meaning across wording | Needs an index that stays fresh |
| Version history | Shows why code changed and what changes together | History may be noisy |
| Failing test or stack trace | Points straight at running code | Only exists once something fails |
A small repository map
A repository map is a compact list of files and what they define, ranked for the task at hand. This script builds one with Python's own parser. The first file below creates a tiny shop project for it to read; save it as sample.py.
"""A tiny shop project, written to a temporary folder for the other examples."""
from pathlib import Path
FILES = {
"shop/__init__.py": "",
"shop/money.py": '''def to_cents(amount):
"""Convert a decimal amount to whole cents."""
return int(amount * 100)
''',
"shop/cart.py": '''from shop.money import to_cents
class Cart:
def __init__(self):
self.lines = []
def add(self, price, quantity=1):
self.lines.append((price, quantity))
def total_cents(self):
return sum(to_cents(price) * quantity for price, quantity in self.lines)
''',
"shop/receipt.py": '''from shop.cart import Cart
def render(cart: Cart) -> str:
return f"TOTAL {cart.total_cents() / 100:.2f}"
''',
"shop/newsletter.py": '''def subscribe(address, book):
book.add(address.strip().lower())
''',
"tests/test_cart.py": '''import unittest
from shop.cart import Cart
class CartTests(unittest.TestCase):
def test_two_items(self):
cart = Cart()
cart.add(2.50, 2)
self.assertEqual(cart.total_cents(), 500)
def test_awkward_price(self):
cart = Cart()
cart.add(19.99)
self.assertEqual(cart.total_cents(), 1999)
''',
}
def create(root):
for name, text in FILES.items():
path = Path(root) / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return Path(root)
"""Choose which files to read first: symbols, imports and a simple ranking."""
import ast
import re
import tempfile
from pathlib import Path
import sample
ISSUE = "Cart total is one cent short for a price of 19.99"
def outline(root):
"""For each Python file: the names it defines and the local files it imports."""
index = {}
for path in sorted(root.rglob("*.py")):
name = path.relative_to(root).as_posix()
tree = ast.parse(path.read_text(encoding="utf-8"))
defines = [node.name for node in ast.walk(tree)
if isinstance(node, (ast.FunctionDef, ast.ClassDef))
and not node.name.startswith("__")]
imports = [node.module.replace(".", "/") + ".py" for node in ast.walk(tree)
if isinstance(node, ast.ImportFrom) and node.module]
index[name] = {"defines": defines, "imports": imports}
return index
def words(text):
return set(re.findall(r"[a-z]+", text.lower()))
def rank(index, issue):
wanted = words(issue)
score = {name: 2 * len(wanted & words(name + " " + " ".join(info["defines"])))
for name, info in index.items()}
direct = {name: value for name, value in score.items() if value}
for name, info in index.items(): # neighbors of matches matter too
for other in info["imports"]:
if other in index:
if name in direct:
score[other] += 1
if other in direct:
score[name] += 1
return sorted(score.items(), key=lambda item: (-item[1], item[0]))
with tempfile.TemporaryDirectory() as folder:
index = outline(sample.create(folder))
print("issue:", ISSUE)
print(f"{'score':5} {'file':20} defines")
for name, score in rank(index, ISSUE):
if score:
print(f"{score:5} {name:20} {', '.join(index[name]['defines']) or '-'}")
print("left out:", ", ".join(n for n, s in rank(index, ISSUE) if not s))
Output:
issue: Cart total is one cent short for a price of 19.99
score file defines
5 shop/cart.py Cart, add, total_cents
5 tests/test_cart.py CartTests, test_two_items, test_awkward_price
1 shop/money.py to_cents
1 shop/receipt.py render
left out: shop/__init__.py, shop/newsletter.py
The ranking is deliberately crude: matching words score points, and files connected by imports gain a little. It still keeps the unrelated newsletter module out. It also shows a limit: money.py, where the bug actually lives, ranks below the files that mention the cart. A ranking suggests where to start. Running the failing test and following the calls finds the fault.
Give the agent a cheap outline first and let it request full files. Pasting everything wastes context and buries the important lines.
Managing context
Long sessions fill the model's working memory with old file versions and long command output. See What Is Context Engineering? Stack and Token Budgets for the underlying limit and Context Poisoning, Distraction, Confusion, Clash and Rot for how it goes wrong.
- Trim command output to the failing lines, keeping the full log available on request.
- Re-read a file after editing instead of trusting an old copy.
- Summarize finished steps: goal, decisions, files changed, what is still failing.
- Hand a side investigation to a separate sub-task and bring back only the finding.
- Start a fresh session for unrelated work.
When a long session is condensed, constraints can quietly disappear. Keep rules that must hold in instruction files and in enforced checks, not only in conversation.
One task, traced
An illustrative session for the one-cent bug shows how the pieces take turns.
| Turn | Agent action | What the program does | What the agent learns |
|---|---|---|---|
| 1 | Search for "total" | Runs a read-only search | Two files mention totals |
| 2 | Read the cart module | Returns the file | The total calls a conversion helper |
| 3 | Read the helper | Returns the file | It truncates instead of rounding |
| 4 | Run the tests | Runs them in the isolated copy | One test fails, confirming the report |
| 5 | Replace one line | Checks the old text matches once, then writes | The edit applied |
| 6 | Run the tests again | Returns the result | All pass |
| 7 | Report | Records the diff and the output | Nothing more to do |
The model never touches the disk. It asks, and the program decides whether and how to act. That boundary is where permissions, logging and limits live.
Designing the tools
| Tool | Good behavior | Poor behavior |
|---|---|---|
| Search | Limits results and says how many were left out | Dumps thousands of lines |
| Read file | Gives line numbers and accepts ranges | Always returns everything |
| Edit | Fails clearly on no match or many matches | Changes the first match silently |
| Run command | Returns exit status, trimmed output and duration | Hangs on an interactive prompt |
| Error replies | Say what to try next | Return a bare failure |
These are the same principles as for any agent tool; Designing Tool Schemas and Contracts covers them in detail.
Instruction files
Most tools read a project file with guidance for agents; AGENTS.md is a shared convention, and some tools have their own name for it. Keep it short and factual.
# Project guide for coding agents
## Commands
- Install: make setup
- Test one file: python -m unittest tests/test_cart.py
- All checks before finishing: make check
## Rules
- Money is stored as integer cents.
- Do not edit files under migrations/ or .github/ without asking.
- Add or update a test for every behavior change.
## Map
- shop/ business logic
- tests/ unit tests, one file per module
This file is advice to a model. Anything that must never happen belongs in a permission rule, a protected branch or a pipeline check as well.
Applying edits
| Method | How it works | Failure to guard against |
|---|---|---|
| Rewrite the whole file | The model returns the new content | Lines silently dropped; expensive for large files |
| Search and replace | Swap an exact passage | No match, or several matches |
| Patch or diff | Apply listed changes | Wrong context lines |
| Structured refactoring tool | A language tool renames or moves code | Dynamic references it cannot see |
A good edit tool refuses ambiguity: if the text to replace appears twice, it should say so, not choose. It should also notice that a file changed since it was read.
Verification is the engine
Without checks, the agent can only judge its own work by reading it. With them, it receives facts.
| Check | Catches | Misses |
|---|---|---|
| Compile or type check | Wrong names and types | Wrong behavior |
| Linter and formatter | Style and common faults | Design problems |
| Unit tests | Behavior you described | Behavior you did not |
| Integration tests | Mismatches between parts | Production conditions |
| Running the program | Startup and obvious failures | Rare paths |
| Security scanners | Known risky patterns and packages | Logic flaws |
Make checks fast, repeatable and quiet when they pass. A flaky test teaches an agent to ignore failures or to "fix" things that are not broken. Issue-to-Pull-Request, Debugging and TDD Workflows shows a loop that refuses to accept a change to the tests themselves.
Where the pieces sit
Open-source projects show this separation clearly. The OpenHands Software Agent SDK, for instance, is MIT licensed, offers isolation as an option and records state as a sequence of events. External services usually arrive through MCP servers, each of which widens what the agent can reach.
Stopping rules
A loop needs reasons to end other than success.
| Limit | Protects against | On reaching it |
|---|---|---|
| Number of steps | Wandering | Report progress and open questions |
| Model spend | Surprise bills | Stop and ask |
| Wall-clock time | Stuck commands and slow loops | End the process, keep the log |
| Repeated identical action | Circles | Change approach or hand back |
| Diff size | Scope creep | Pause for approval |
Questions to ask of any coding agent
- How does it find code in a repository of our size and languages?
- Which commands run without asking, and who can change that?
- Where does code and context go, and how long is it kept?
- Can it run our checks in an environment like our build system?
- Can we see and export what it did?
- Can we change the model without rebuilding our setup?
- What happens when it hits a limit: a clear report, or silence?
Prepare the repository
Much of what helps an agent also helps a new colleague.
- One command to set up, one to run all checks.
- Tests that pass on a clean copy.
- Small modules with descriptive names.
- Written rules where conventions are not obvious from the code.
- Sample configuration with fake values, and real secrets kept out.
- Protected branches and required reviews.
Diagnosing a poor result
| Symptom | Look at | Likely fix |
|---|---|---|
| Edits the wrong module | What search returned | Clearer names, a map in the instruction file |
| Calls functions that do not exist | Whether the definition was read | Better search; type check after edits |
| Cannot run the tests | Environment setup log | A scripted, repeatable setup |
| Forgets a constraint late in a session | Summaries and context size | Enforce it with a check; shorter sessions |
| Declares success wrongly | The command output it relied on | Checks with unambiguous exit status |
| Slow and expensive | Size of reads and command output | Trim results; narrow the task |
Common mistakes
| Mistake | Better |
|---|---|
| Blaming the model for missing context | Check what it was actually shown |
| Very long instruction files | Keep essentials; link detail |
| Letting it install anything | Pin dependencies and review additions |
| Accepting "done" without evidence | Require command output and passing checks |
| Running it with your personal credentials | Give it its own limited identity |
Questions people ask
Does the agent need to index the whole repository first?
No. Many agents search on demand. An index can help with very large codebases or vague questions, at the price of keeping it current.
Why does it invent functions that do not exist?
Usually it did not see the real code and filled the gap with a plausible name. Better search and an automatic compile or type check catch this quickly.
Is a bigger context window the answer?
It helps, but irrelevant material still costs money and attention. Selecting well remains important.
Which languages work best?
Results vary by model and project. Good tests, type information and conventional structure tend to matter as much as the language. Measure on your own code.
References
Next steps
Issue-to-Pull-Request, Debugging and TDD Workflows
From an issue to a reviewed change.
Sandboxes, Safety and Security for Coding Agents
Keep the agent inside limits.
Code Review, Refactoring and Quality Measures
Judge what it produces.