Building a Code Agent from Scratch: Architecture and Implementation
A code agent is not a chat wrapper around an LLM but a closed-loop system that treats the repository as its workspace, tools as its hands, and verifiable results as its constraints. This article walks through defining the problem boundary, a five-layer reference architecture, core data structures in Python, context retrieval strategies, planning and execution safeguards, prompt and protocol design, evaluation with task sets, engineering trade-offs, and a concrete build order for shipping a minimal but controllable agent.
A code agent is not “send a prompt to the model and paste the answer.” It is a closed-loop system that treats the codebase as its working object, tools as its hands and feet, and verifiable results as its constraints. It receives a requirement, retrieves relevant context, plans a change, invokes tools for reading, writing, searching, executing, and testing, then corrects based on feedback until the change is explainable, reproducible, and reversible. If you develop primarily in Python, rather than chasing the minutiae of some closed-source interface, it is more valuable to decompose this loop into replaceable modules, build a minimal working version yourself, and only then thicken it for specific scenarios.
1. Define the Problem Boundary First
What a code agent must solve is not open-ended chit-chat, but “completing a reviewable code change within existing engineering constraints.” Typical inputs include a requirement description, the target repository, allowed paths, forbidden configurations, and acceptance criteria (unit tests, static checks, a manual checklist). The typical output is not an isolated snippet of code, but: a change description, the diff, a summary of commands executed, a record of failures and retries, and any unresolved risks.
Unclear boundaries are the main source of failure. Before implementing anything, write down three things:
- What it can do: read designated directories, search symbols, edit files, run whitelisted checks within a defined scope, generate change descriptions.
- What it cannot do: access private directories outside the repository, execute system commands not on the whitelist, expand dependencies or modify release configuration on its own.
- When to stop: tests pass, the maximum step count is reached, consecutive failures exceed a threshold, or the model cannot produce a parseable next step.
Writing “stop conditions” into the state machine is far more reliable than repeatedly telling the model to “be careful” in the prompt.
2. Reference Architecture: A Five-Layer Loop
A maintainable implementation can be split into five layers, where layers communicate only through explicit data structures.
- Task layer. Normalize user requirements into a task object: goal, constraints, acceptance criteria, and a budget (maximum rounds, maximum tokens, maximum command duration).
- Context layer. From the repository, select files, symbols, error logs, and recent diffs relevant to the current goal, controlling the volume of information sent to the model.
- Planning layer. Have the model produce a structured plan: observation, hypothesis, next action, expected result. The plan can be revised, but every step must be traceable.
- Tool layer. Provide a small set of tools with stable semantics: list directories, read files, search by symbol or text, modify files via patches, run whitelisted commands in a sandbox, read test results.
- Memory and evaluation layer. Persist the trajectory, compress history, compare expected versus actual outcomes, and replay the run after the task completes.
The data flow can be summarized as: task enters → assemble context → model produces an action → tool executes → observation written back → decide whether to continue. The model never touches the file system directly; every side effect is validated through the tool layer.
3. Core Data Structures
Plain Python data classes can express the state without depending on any particular framework:
from dataclasses import dataclass, field@dataclassclass Task:goal: strroot: strallow_paths: list[str]checks: list[str]max_steps: int = 12@dataclassclass Action:name: strargs: dictreason: str@dataclassclass Observation:ok: boolsummary: strdata: dict = field(default_factory=dict)@dataclassclass Trace:step: intaction: Actionobservation: Observation
Model output should first be parsed into an Action; if parsing fails, treat it as an invalid step and request a retry, rather than executing free-form text directly as a command. Parameter validation belongs at the tool entry point: paths must fall within root and allow_paths, commands must match whitelist prefixes, and timeouts and output length must be truncated.
4. Context: Small and Precise, Not Big and Comprehensive
Repositories typically far exceed the model’s context window. A practical strategy is layered retrieval:
- Structural index: file tree, languages, entry modules, test directories — used to locate “possibly relevant” regions.
- Symbol index: functions, classes, import relationships — used to answer “who calls this logic.”
- Text retrieval: error messages, requirement keywords, constraints embedded in comments.
- Dynamic context: the stack trace from the last failed round, the diff just applied, the checks that have not yet passed.
Each round should only inject “the evidence the current hypothesis requires.” When reading a file, prefer the relevant function and its direct callers over the whole file. When the trajectory grows too long, keep the most recent steps verbatim and compress earlier ones into “what was tried, what the result was, which hypotheses were ruled out.” Compression must be generated programmatically; letting the model freely rewrite history leads to factual drift.
5. Planning and Execution: Small Steps, Reversible
Effective planning is not writing a perfect design document upfront — it is “verify every step.” Each step performs exactly one kind of action: read, search, edit, or run a check. Edits should use patch semantics (locate a snippet, replace it with a new snippet), with conflict detection before application. After applying a patch, immediately run the narrowest possible check instead of waiting until the end to run the full test suite.
The executor needs three kinds of protection:
- Working copy: make changes on a copy or temporary branch; failures can simply be discarded.
- Idempotency: re-applying the same patch should be detected, preventing back-and-forth edits.
- Budget: caps on step count, command duration, and output bytes, preventing infinite loops or logs flooding the context.
When a check fails, send the failure summary, the relevant source snippet, and the intent of the last edit back to the planning layer, requiring the model to first explain the cause of the failure before deciding whether to roll back, apply a local fix, or widen its reading. If two consecutive rounds fail to narrow the failure scope, stop and hand over a human-readable blocker description.
6. Prompts and Protocols: Constrain the Output, Don’t Stack the Personas
The system prompt only needs to state the role, available tools, output format, and safety boundaries. Each per-round user message is assembled programmatically: current goal, confirmed facts, latest observation, unmet acceptance items. Require the model to return a fixed structure, such as “thinking summary, action name, arguments, completion criteria.” The thinking summary is for human review; the action arguments are for the program to execute. Separating the two prevents long-form reasoning from being mistaken for a patch.
Tool descriptions should be short, stable, and unambiguous. Rather than offering dozens of fragmentary tools, provide a few clearly composed capabilities, and state in the description what is returned on failure. Models choose better within a small action space.
7. Evaluation: Replace Subjective Feelings with a Task Set
An agent without evaluation cannot be iterated on. Prepare a set of small, automatically judgeable tasks: fix a clearly failing unit test, add a pure function, complete boundary checks based on comments, or refactor a local implementation without changing the public interface. For each task, record:
- Whether it was completed within the step budget;
- Whether the check commands passed;
- Whether files outside the allowed scope were modified;
- The proportion of invalid actions and the number of repeated edits;
- Whether the final diff is readable by a human.
Replaying the trajectory is more valuable than only looking at final correctness. Common degradations include: editing without reading the code first, repeatedly reading the same file, expanding into unrelated refactoring after a test failure, and echoing error messages verbatim without forming a new hypothesis. Tightening tools or adjusting context against these patterns is often more effective than swapping in a different model.
8. Engineering Trade-offs
A minimal viable version can be a single process with a synchronous loop: read the task, call the model, execute one tool, write the trace. When tasks get longer, consider async tools, result caching, and multi-task queues. When cloud collaboration is needed, object storage suits storing traces and diff snapshots; message queues suit separating “run checks” from the planning process; container platforms suit providing isolated command execution environments; logging, monitoring, and alerting suit tracking step counts, failure rates, and timeouts. These are all generic capabilities and should be access-controlled according to data sensitivity — keys and production configurations must never enter the model’s context.
On security, adhere to least privilege: start read-only, authorize writes explicitly; command whitelists; network access off by default; keys never appear in prompts or logs. Treat generated code with the same review rigor as human commits: type checks, tests, and code review are all mandatory. An agent is an accelerator, not a transfer of responsibility.
9. An Actionable Build Order
- Define
Task,Action, andObservation, and get a “dry-run” loop working — without the model first. - Implement file reading and retrieval with path validation, and confirm context assembly is reproducible.
- Plug in the model with read-only tools only, and observe whether it can locate the right code.
- Add patch application and unit test commands, enforcing check-after-every-step.
- Add trace compression, stop conditions, and task-set evaluation.
- Only then expand to UI, multi-user collaboration, and cloud execution environments.
Following this order, you end up not with an imitation of some existing product’s interface, but with a code agent skeleton with swappable models, auditable tools, and regression-testable evaluation. Ground the theory in state and constraints, ground the practice in small verified steps — once the two are aligned, an AI coding assistant finally becomes controllable.
