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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner The shape of the system

Four ways to work with one

ModeWhere it runsYou areSuits
CompletionYour editorTypingSmall, local code
Interactive agentEditor or terminalWatching and steeringFeatures, debugging, exploration
Background agentA separate machine or containerReviewing the resultWell-specified tasks
Pipeline agentYour build systemOften absentNarrow, 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

Understandsearch and read
Plandecide the change
Editapply patches
Verifyrun and read
A failed check sends the agent back to an earlier step. A budget ends the loop.

The parts

PartJobIf it is weak
InstructionsProject rules, commands and limitsWork ignores your conventions
Context selectionChooses files and output to show the modelThe agent edits the wrong place
Search toolsFind names, text and referencesIt guesses, or invents functions
Edit toolChanges files preciselyCorrupted or lost code
Execution environmentRuns tests, builds and lintersNo evidence that anything works
Permission layerDecides what may run or leaveDamage or data exposure
Session recordKeeps what was tried and learnedRepeated mistakes; no audit trail
Intermediate Understanding code

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.

MethodStrengthLimit
Text searchFast, exact, always currentMisses different wording
File names and structureCheap orientationDepends on tidy naming
Symbol outline from a parserShows definitions and imports compactlyNeeds support per language
Language serverAccurate definitions and referencesNeeds a working project setup
Embedding searchMatches meaning across wordingNeeds an index that stays fresh
Version historyShows why code changed and what changes togetherHistory may be noisy
Failing test or stack tracePoints straight at running codeOnly 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.

Read widely, then narrow

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.
Summaries lose things

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.

TurnAgent actionWhat the program doesWhat the agent learns
1Search for "total"Runs a read-only searchTwo files mention totals
2Read the cart moduleReturns the fileThe total calls a conversion helper
3Read the helperReturns the fileIt truncates instead of rounding
4Run the testsRuns them in the isolated copyOne test fails, confirming the report
5Replace one lineChecks the old text matches once, then writesThe edit applied
6Run the tests againReturns the resultAll pass
7ReportRecords the diff and the outputNothing 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

ToolGood behaviorPoor behavior
SearchLimits results and says how many were left outDumps thousands of lines
Read fileGives line numbers and accepts rangesAlways returns everything
EditFails clearly on no match or many matchesChanges the first match silently
Run commandReturns exit status, trimmed output and durationHangs on an interactive prompt
Error repliesSay what to try nextReturn 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

MethodHow it worksFailure to guard against
Rewrite the whole fileThe model returns the new contentLines silently dropped; expensive for large files
Search and replaceSwap an exact passageNo match, or several matches
Patch or diffApply listed changesWrong context lines
Structured refactoring toolA language tool renames or moves codeDynamic 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.

Advanced Verification and design choices

Verification is the engine

Without checks, the agent can only judge its own work by reading it. With them, it receives facts.

CheckCatchesMisses
Compile or type checkWrong names and typesWrong behavior
Linter and formatterStyle and common faultsDesign problems
Unit testsBehavior you describedBehavior you did not
Integration testsMismatches between partsProduction conditions
Running the programStartup and obvious failuresRare paths
Security scannersKnown risky patterns and packagesLogic 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

Interfaceeditor, terminal, issue tracker
Agent controllerloop, budgets, session record
Modelchooses the next action
Tools and permission layersearch, read, edit, run, external services
Isolated environmentrepository copy, limited network and credentials

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.

LimitProtects againstOn reaching it
Number of stepsWanderingReport progress and open questions
Model spendSurprise billsStop and ask
Wall-clock timeStuck commands and slow loopsEnd the process, keep the log
Repeated identical actionCirclesChange approach or hand back
Diff sizeScope creepPause 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.

  1. One command to set up, one to run all checks.
  2. Tests that pass on a clean copy.
  3. Small modules with descriptive names.
  4. Written rules where conventions are not obvious from the code.
  5. Sample configuration with fake values, and real secrets kept out.
  6. Protected branches and required reviews.

Diagnosing a poor result

SymptomLook atLikely fix
Edits the wrong moduleWhat search returnedClearer names, a map in the instruction file
Calls functions that do not existWhether the definition was readBetter search; type check after edits
Cannot run the testsEnvironment setup logA scripted, repeatable setup
Forgets a constraint late in a sessionSummaries and context sizeEnforce it with a check; shorter sessions
Declares success wronglyThe command output it relied onChecks with unambiguous exit status
Slow and expensiveSize of reads and command outputTrim results; narrow the task

Common mistakes

MistakeBetter
Blaming the model for missing contextCheck what it was actually shown
Very long instruction filesKeep essentials; link detail
Letting it install anythingPin dependencies and review additions
Accepting "done" without evidenceRequire command output and passing checks
Running it with your personal credentialsGive 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