A Coding Agent Architecture Guide: 6 Core Modules, Agent Harness Design, and a Minimal Implementation
Why do two coding tools powered by the same model behave so differently? This guide explains how the engineering around the model — control loops, tool design, context management, prompt caching, codebase navigation, and long-term memory — determines AI coding agent performance, and shows a minimal, runnable Mini Coding Agent to illustrate each module.
1. Why Do Agents Built on the Same Model Feel So Different?
In many real applications, the model alone doesn’t decide how good an agent feels. The full system built around the model does. Tool invocation, context management, memory, permission control, loop termination conditions — these engineering modules matter as much as raw model capability. That’s why mainstream commercial AI coding tools usually feel steadier than simply calling the same model in a chat window when the task involves reading code, editing multiple files, running commands, or breaking work into long chains. The advantage comes from better engineering in the agent control framework and the surrounding system.
A standalone language model only produces text from the context in front of it. A complete coding agent also has to observe, decide, invoke tools, check results, recover from errors, and bring the task to a close — all of it happening in a system outside the model. In other words, the model is the engine; the agent framework is the whole vehicle that lets that engine run safely, under control, and over long stretches.
This article uses a minimal but runnable Mini Coding Agent to walk through six core modules of an AI coding agent, plus tool design examples, prompt caching boundaries, security warnings, and a production checklist. The goal is to help developers move an AI agent from “it can chat” to “it can actually get work done.”
2. Core Concepts: Language Models, Reasoning Models, and the Agent Harness
1. What Each Layer Is Responsible For
| Layer | Core responsibility | Main inputs | Main outputs | Limitations |
|---|---|---|---|---|
| Large language model (LLM) | Predict tokens from context | Conversations, documents, code snippets | Text or structured output | Cannot act continuously; cannot directly read or write files or run a terminal |
| Reasoning model | Adds more thinking, verification, and comparison before answering | More complex problem context | Better-reasoned answers | Higher inference cost; behavior still needs an external framework |
| Agent harness | Control loop, tool dispatch, state management, permission boundaries | User goal, environment state, tool results | Multi-step action sequences | Poor design leads to infinite loops, overreach, or context explosion |
An LLM is best thought of as a pure “next-token prediction engine.” A reasoning model is a capability upgrade at the model layer: it spends extra reasoning time to handle harder problems, but it does not give you a full task loop by itself. What turns a model into an agent is the Agent Harness.
The Agent Harness is like a driving system: the model is the engine, a reasoning model is a more powerful engine, and the harness provides the throttle, the steering wheel, navigation, speed limits, and the brakes. When you optimize an AI coding agent, model benchmark scores are only part of the picture — the outer control loop, tool interfaces, context strategy, and safety mechanisms matter just as much.
3. The Six Core Modules of a Coding Agent
1. The Control Loop: From Q&A to Action
The foundation of an agent isn’t a single-turn conversation — it’s a control loop that keeps running. A typical loop looks like this:
observe → inspect → choose → act
Observe the environment, inspect the state, choose an action, execute it. Production-grade agents add step limits, error retries, termination conditions, and human confirmation.
Here is a minimal runnable example. It packages “check the directory, create a file, finish the task” into the smallest closed loop. In a real system, inspect and choose are usually handled by the model, while act runs through controlled tools.
from pathlib import Pathclass MiniAgent:def __init__(self):self.task_completed = Falseself.history = []def observe(self):return {"cwd": str(Path.cwd()),"files": [p.name for p in Path.cwd().iterdir() if p.is_file()],"history": self.history,}def inspect(self, state):# In production, this layer is where the model analyzes the context.if "mini-agent.py" not in state["files"]:return {"next": "write_mini_agent"}return {"next": "finish"}def choose(self, analysis):# In production, this layer is where the model generates tool-call args.if analysis["next"] == "write_mini_agent":return {"tool": "write","args": {"path": "mini-agent.py","text": "print('mini agent')\n",},}return {"tool": "finish", "args": {}}def act(self, action):tool = action["tool"]args = action.get("args", {})if tool == "write":Path(args["path"]).write_text(args["text"], encoding="utf-8")result = "written"elif tool == "finish":self.task_completed = Trueresult = "finished"else:raise ValueError("unknown tool: " + tool)self.history.append({"tool": tool, "result": result})return resultagent = MiniAgent()while not agent.task_completed:state = agent.observe()analysis = agent.inspect(state)action = agent.choose(analysis)agent.act(action)
The example is simple, but it captures the key engineering idea behind agents: a task is not a single answer to a single question — it’s a loop of observation, decision, action, and a termination condition. Production systems also add maximum step counts, timeouts, error retries, permission checks, and human confirmation, so the agent doesn’t run forever or take risky actions.
2. Tools: Atomic Interfaces with Lower Execution Risk
If the control loop is an agent’s soul, tools are its hands and feet. In a coding agent, tools decide whether the model can safely read and write files, run commands, search code, and run tests.
First, every tool needs a clear JSON Schema. Here is a tool definition for a precise find-and-replace edit:
{"name": "edit_file","description": "Replace old_text with new_text in the given file. Does not delete files and does not create new files.","parameters": {"type": "object","properties": {"path": {"type": "string"},"old_text": {"type": "string"},"new_text": {"type": "string"},"dry_run": {"type": "boolean","default": true}},"required": ["path", "old_text", "new_text"]}}
The boundaries in this definition are clear: the model can’t use it to delete a file, and it can’t use it to create unrelated files. The dry_run flag also lets you preview the replacement before anything is written.
Tools should also follow an atomicity principle. Atomic tools are easier for a model to pick correctly than all-in-one “do everything” tools, and they are easier to gate with permissions and easier to audit.
| Design approach | Catch-all tools | Atomic tool set |
|---|---|---|
| Typical shape | fix_project, repair_code, run_task |
read_file, edit_file, grep, run_tests |
| Pros | Simple on the surface | Explainable, verifiable, reversible |
| Cons | Fuzzy boundaries, higher risk of wrong actions | Requires more tools working together |
| Best fit | Not recommended for production | Complex software engineering tasks |
One thing needs special care: shell command execution, file writes, and file edits are all high-risk tools. If your system lets an agent run Bash, you need sandbox isolation, least-privilege permissions, a command allowlist, and blocking of dangerous commands. Destructive operations such as delete, format, outbound network calls, and privilege escalation should be restricted. For high-risk operations like bulk modifications, deletes, and renames, require a second confirmation or create a backup the agent can roll back to.
3. Context Management: The Agent’s Cognitive Boundary
The context window of an LLM is a limited resource. The goal of context management isn’t to cram in as much as possible — it’s to put the most decision-relevant information in front of the model.
A practical context structure has three layers:
- Fixed rules layer: system prompt, tool definitions, code style, Git conventions, security constraints.
- Task state layer: the current goal, completed steps, remaining work, key constraints.
- Dynamic evidence layer: tool call results, error stacks, file diffs, test output, retrieval snippets.
A system prompt shouldn’t just say “you are a coding assistant.” It should spell out what the agent may do, what it must not do, how to verify results, and how to handle failure. For the dynamic layer, prioritize high-value information — for example, why the last test failed, which file is being edited, and which dependencies are directly relevant to the task.
For large projects, don’t blindly load the whole codebase. A better strategy is fetch on demand: first look at the directory structure, then read key configuration files, then search for the relevant symbols, and only then read the files you actually need. This cuts context noise significantly and improves the quality of the model’s judgments.
4. Keeping the Prompt Prefix Stable to Hit the Cache
With long contexts and many tool calls, prompt prefix stability directly affects latency and cost. Many model providers cache long, repeated prefixes, but the exact rules depend on the provider, the model version, and billing policy.
In practice, watch these points:
- No universal minimum cacheable length: a common requirement is that the prefix reach a certain length — maybe a few hundred to a few thousand tokens — but always check the docs of the platform you’re on.
- Cache TTL isn’t fixed: it may be minutes, hours, or whatever the platform’s policy sets.
- Any change to the prefix may break the cache: even a small change — a timestamp, a random ID, a dynamic log line, or a tool description — can make the prefix stop matching.
- Monitor the hit rate: use latency, token billing, and request duration to judge whether caching is working.
So an agent architecture should put stable content first — system instructions, tool definitions, project conventions, coding conventions — and dynamic content later, such as conversation history, tool output, the current diff, and error stacks. Don’t inject the current time, a random request ID, or volatile environment info into the prefix.
5. Codebase Navigation: From Keyword Search to Structural Understanding
For a large repository, agents can’t rely on plain full-text search alone. A more reliable navigation strategy has three layers:
- Lexical search: locate candidate files by keyword, function name, or error message.
- Syntax structure: use the AST, import relationships, and symbol indexes to understand how classes, functions, and modules depend on each other.
- Engineering structure: start from the directory tree, package manager files, build scripts, and test directories to build an overall picture of the project.
For example, if a user asks to “refactor the authentication module,” the agent shouldn’t just grep for “authentication.” It should also locate the auth entry point, route registration, middleware, data models, tests, and configuration. That way the resulting change stays consistent and verifiable.
6. Memory: Supporting Very Long Tasks
Real development work can span hours or even days. An agent that relies only on the context window tends to “forget the goal” on long chains, so memory needs to be designed in layers.
- Short-term working memory: the current loop’s tool output, error messages, the current step, and temporary conclusions.
- Long-term external memory: key decisions, completed subtasks, open TODOs, and lessons from failures, written to an external file.
A simple, practical approach is to keep an agent memory file in the project, for example agent-memory.md. At the start of a task, or after a key milestone, the agent reads this file to see what’s done and what the current goal is; after each phase, it updates the file. Even if the context gets compressed or truncated, the agent can still recover the main thread of the task from external memory.
4. Choosing a Model and an Agent Framework
Don’t choose based on model capability alone — choose based on whether the whole system fits the risk of the task.
| Scenario | What to focus on |
|---|---|
| Simple Q&A, code explanation | A regular LLM is enough; focus on latency and context quality |
| Complex reasoning, architecture design | Consider a reasoning model, but watch token cost and latency |
| Multi-file edits, command execution | Focus on the agent harness, tool atomicity, permissions, and rollback |
| Long-running tasks | Focus on external memory, task decomposition, resume-from-checkpoint, and log auditing |
| Enterprise production | Focus on sandboxing, data compliance, observability, and fallback on failure |
If the goal is an AI coding assistant that can actually go to production, prioritize these capabilities: a clear control loop, atomic tools, dry-run support, a context compaction strategy, a stable prompt prefix, external memory files for long tasks, and security approval plus audit logging.
5. Common Mistakes and a Troubleshooting Checklist
- Upgrading the model but not the architecture. A stronger model doesn’t mean a stronger task loop — tools, the control loop, and context matter just as much.
- Vague tool definitions. No JSON Schema and no clear boundaries lead to failed calls or wrong operations.
- Offering catch-all tools. A “do everything” function looks convenient, but it adds ambiguity, makes auditing harder, and raises security risk.
- A prompt prefix that changes often. It breaks cache hits and adds latency and cost.
- No termination condition. The agent can loop forever, so always set a max step count, a timeout, and an exit on failure.
- High-risk operations without confirmation. Deleting, overwriting, or running external commands requires sandboxing, permission control, and a second confirmation.
- No external memory for long tasks. Relying on the context window alone loses the goal — use an external memory file.
- Skipping tests and verification. After the agent changes code, run the tests, review the diff, and verify the critical paths.
- Loading the whole context. It wastes tokens and adds noise — retrieve and load on demand.
- No observability. Without logs, tool call records, and failure stacks, debugging is very hard.
6. Summary: Engineering Architecture Sets the Ceiling for Coding Agents
AI coding tools work in real development scenarios not because of the underlying model alone, but because of how the agent harness is engineered. From the observe → inspect → choose → act control loop to atomic tools wrapped behind JSON Schema; from a stable prompt prefix for better cache hits to lexical search, AST navigation, and external memory working together — every layer affects whether the agent can reliably finish complex work.
For developers building or evaluating an AI coding assistant, this checklist is a good starting point:
- Control loop: does it observe, inspect, choose, execute, and have a termination condition?
- Tool interfaces: does it have JSON Schema, atomic design, dry-run, and permission boundaries?
- Context management: does it separate fixed rules, task state, and dynamic evidence?
- Cache stability: does it avoid frequent prefix changes and verify the cache policy?
- Code navigation: does it combine directory structure, lexical search, AST, and dependency relationships?
- Memory: is there an external memory file to recover long tasks?
- Security and compliance: are high-risk tools such as Bash, Write, and Edit sandboxed, confirmed, and audited?
- Observability: does it log tool calls, errors, and task state so problems can be diagnosed?
Understanding how these modules work together is what lets you build a stable, controllable AI coding assistant that is ready for production.
