Inside Coding Agents: From Context to Controlled Execution
This article breaks down the architecture of intelligent coding agents, explaining how they go beyond code completion to complete full tasks such as locating bugs, fixing them, and verifying tests. It covers session state, dynamic context building, tool protocols, security and permission controls, validation strategy, and observability, and concludes with a minimal reference implementation and engineering practices for building reliable, auditable agent systems.
1. From Code Completion to Task Execution: What a Coding Agent Really Is
Traditional code completion solves local problems: based on the current file and the text near the cursor, it predicts what should be written next. A terminal-level intelligent coding agent faces complete tasks instead, such as “locate the cause of an exception in a specific interface, fix the problem, and verify the related tests.”
Completing such a task requires crossing several stages:
- Understand the user’s goal and acceptance criteria.
- Find the files, symbols, and configuration related to the problem.
- Decide whether further searching or checks are needed.
- Form a modification plan and implement the changes.
- Verify the results, and continue fixing if necessary.
- Summarize the changes made, verification evidence, and remaining risks.
Therefore, an intelligent coding agent can be understood as a model-driven controlled execution system. The model proposes the next action; the runtime checks whether the action is legal, executes tools, and returns results. The two cooperate, but their responsibilities must not be blurred.
In particular, it is important to be clear: being able to invoke a tool does not mean unrestricted access to the environment; being able to read project files does not mean the entire repository has been understood. Reliability comes from gradually collecting evidence, limiting the scope of actions, and continuously verifying — not from providing as much text as possible in one shot.
This article discusses general architecture and illustrative implementations. It does not correspond to any specific product’s internal source code, nor should community reproductions or public descriptions be treated as official implementations.
2. Overall Architecture: Building an Evidence-Driven Execution Loop
A practical coding agent can typically be broken into six parts:
User task↓Session and task state↓Context selection and budget control↓Model inference and action generation↓Parameter validation and permission decisions↓Tool execution and result normalization↓Verify, continue, or finish
Tool results re-enter the session and become the basis for the next round of decisions. This feedback loop is what distinguishes an agent from a single-turn Q&A interaction.
2.1 Session Management: Save Task Facts, Not the Entire History
The session layer should at minimum maintain the user goal, repository root directory, message history, executed actions, pending approvals, and resource budgets.
It should also keep “model speculation” separate from “facts confirmed by tools.” For example, “the configuration might be missing” is a hypothesis; “after reading the config file, the target field does not exist” is evidence. If the two are mixed together, later summaries can solidify guesses into facts.
Task state can be designed as:
Waiting for input → Collecting information → Waiting for approval → Executing actions → Verifying results → Completed↘ Failed or canceled
Long-running tasks should not rely solely on natural-language conversation history to preserve state. Structured state makes recovery, auditing, and avoiding repeated operations easier.
2.2 Context Building: Show the Model What the Current Decision Needs
The context layer selects relevant files, search results, error messages, and historical conclusions, while controlling input size. It should not read the entire repository into context by default.
2.3 Model Adaptation: Isolate the Inference Interface from Business Logic
The model adaptation layer sends messages, declares tools, and receives text or structured actions. Upper layers should use a unified internal protocol, avoiding propagation of service-specific message formats into the file system and permission modules.
2.4 Tool Execution: Turn Suggestions into Controlled Operations
The tool layer provides limited capabilities, such as reading files, searching text, previewing changes, applying modifications, and running tests. Each tool should have explicit parameter constraints, output structures, and error semantics.
2.5 Security Control: Make Permission Decisions Before Execution
Security checks must be enforced by the runtime, not merely requested in prompt text telling the model to “be careful.” Paths, parameters, and commands generated by the model should all be treated as unverified input.
2.6 Verification and Reporting: Distinguish Completing an Action from Completing the Task
A file being written successfully only proves that an action completed; it does not prove the task is solved. The final result should be judged against change checks, test feedback, and acceptance criteria.
3. Dynamic Context: From Repository Overview to Evidence Retrieval
The main challenge of large repositories is not a lack of information but sparse relevance and high noise. Context construction should use a progressively narrowing strategy.
3.1 Layer 1: Build a Low-Cost Project Overview
The initial context can include:
- The user’s goal and constraints.
- The main files and directories under the repository root.
- Summaries of the project description, build configuration, and test entry points.
- An overview of currently uncommitted changes.
- Error logs or target files explicitly pointed out by the user.
Directory enumeration must enforce limits on depth, entry count, and output length. Generated directories, dependency caches, large binaries, and sensitive files should be excluded first.
Illustrative logic:
function build_directory_overview(root, depth_limit, entry_limit):result = []traverse directories in stable order:if exclusion rule matches:skipif entry count reaches limit:append "remaining entries omitted"stoprecord relative path and entry typeif directory and remaining depth > 0:recursively collect subdirectoriesreturn result
Stable ordering aids reproducibility and caching. Truncation markers remind the model that what it sees is only a partial overview and it cannot conclude that a file does not exist based on absence.
3.2 Layer 2: Search for Candidate Locations Around the Problem
The model selects search conditions based on task clues — for example, error text, function names, configuration fields, or interface paths.
Search results should return file location, the matched content, and a limited amount of surrounding context rather than the entire file. For queries with too many hits, further narrow the directory, file type, or keywords.
It must be emphasized that text search is not the same as call-graph analysis. Dependency graphs and call chains usually require additional syntactic or semantic analysis; dynamic calls and runtime loading can also cause omissions. Implementations without these capabilities should clearly state their boundaries.
3.3 Layer 3: Read the Complete Logic Relevant to the Modification
After candidate files are confirmed, read the target function and its necessary context. Looking only at matched lines makes it easy to miss parameter validation, exception handling, and call preconditions.
When modifying an interface, also check its callers and related tests; when modifying configuration, confirm defaults, load order, and override rules. The context scope should be determined by actual dependencies, not mechanically fixed to a certain number of lines.
3.4 Controlling Context Budget and Freshness
The context budget can be allocated across task instructions, key evidence, tool protocols, recent actions, and historical summaries. Ratios should be adjusted per task rather than relying on unverified fixed parameters.
When compressing history, preserve at minimum:
- Confirmed causes of the problem.
- Modified files and the purpose of each modification.
- Verification results and failure information.
- Unresolved issues.
- Operations the user has authorized.
Once a file is modified, its old content may be stale. Caches should be validated against file version information or content hashes; before applying a change, the runtime should also re-check whether the target file has changed externally.
4. Tool Protocol: Make Every Operation Verifiable and Traceable
Tools are not a loose collection of functions; they are a capability contract between the model and the runtime.
4.1 Input Must Be Explicit and Restricted
Taking file reading as an example, a tool can require a relative path, start position, and read range. The runtime needs to check:
- Whether the path falls inside the authorized workspace.
- Whether path traversal or symlinks reach outside locations.
- Whether the file type and size are allowed.
- Whether secrets, credentials, or other sensitive content are involved.
- Whether the read range exceeds the budget.
Path checks cannot rely solely on string prefixes. Resolve the actual path first, then determine its containment relationship with the authorized root, and account for path race conditions based on the execution environment.
4.2 Output Should Be Structured, Not Just a Blob of Text
Tool results should include an action identifier, success status, content, error category, execution duration, and truncation information. When running tests, also provide the exit status and a necessary output summary.
Structured results avoid misjudgment. For example, the word “failed” appearing in output may just be part of a test name; whether execution failed must be determined from the tool status.
Tool output is also untrusted data. Even if file comments or logs contain text such as “ignore previous restrictions,” it can only be treated as read content and must not be promoted to system instructions.
4.3 Modifications Should Use Constrained Patches
Directly overwriting an entire file can easily delete unrelated code. A safer approach is to submit an explicit replacement snippet or patch with preconditions:
Modification request:target fileexpected original contentreplacement contentexpected match countoptional file version check
If the expected original content is absent, the match count differs, or the file has changed, reject the application rather than guessing where to apply it.
Show a diff before execution and re-read key regions after execution to form a more complete chain of evidence for the change.
5. Security Mechanism: Approval Is Not the Only Defense
Security design should follow the principle of least privilege and distinguish read, write, execute, and external communication capabilities.
5.1 Classify Risk by Impact Scope
Read-only operations are usually low risk but can still leak sensitive information. Local modifications affect the workspace and should present a clear diff. Operations that delete data, change permissions, install dependencies, upload externally, or modify the execution environment should trigger stricter controls.
Risk assessment must not rely only on action names. An innocuous-looking test entry point can execute arbitrary project code. For tasks on untrusted repositories, prioritize isolated environments, and restrict network access, credentials, and writable directories.
5.2 Approval Must Correspond to a Specific Operation
The approval interface should show the action to be executed, working directory, affected files, network access needs, and main risks.
What the user approves is one concrete operation, not a vague class of actions the model might generate in the future. If parameters, targets, or scope of impact change, permissions must be re-evaluated. A rejected approval must not be interpreted as permission for the agent to achieve the same high-risk effect in a different way.
5.3 Use Technical Isolation to Supplement Human Confirmation
Manual confirmation only improves visibility; it cannot replace isolation. Real systems should also enforce execution timeouts, resource limits, output caps, network restrictions, and process cleanup.
For tasks that do not require general-purpose command execution, prefer dedicated tools. For example, designing “run a specified test scope” as a constrained capability is generally easier to audit than opening up an arbitrary command string.
6. Minimal Reproducible Implementation: Get a Limited Loop Working First
A minimal implementation need not immediately support all terminal capabilities. It can start with four tool types:
- Read files within an authorized scope.
- Search repository text.
- Preview and apply constrained modifications.
- Execute preconfigured verification tasks.
The pseudocode below illustrates the architecture; names are for explanation only and do not represent a specific product interface:
function execute_task(user_goal, workspace):session = initialize_session(user_goal, workspace)remaining_rounds = task_round_limitwhile remaining_rounds > 0:context = select_context(session)response = request_model_decision(context, tool_definitions)if response contains tool actions:for each action:validate tool name and parametersvalidate paths, resource budget, and task staterisk = assess_operation_risk(action)if approval required and not granted:record rejection resultcontinueresult = controlled_execute(action)record action and resultupdate file state and verification stateelse:if acceptance criteria are met:return final reportif user information is missing:return clarification requestrecord "task not yet verified" stateremaining_rounds = remaining_rounds - 1return staged report with reasons for incompletion
This loop must have an explicit upper bound — rounds, duration, model call count, and tool output volume. Otherwise the agent may repeatedly retry the same error.
Write operations should not automatically retry by default. If execution times out, actual modifications may already have taken place; check the current state first before deciding whether to retry. Operations that need retrying should be idempotent or have duplicate-execution detection.
7. Verification Strategy: Prove the Modification Works Layer by Layer
Verification can proceed from lowest to highest cost.
The first layer is change checking: confirm there are no accidental deletions, out-of-bounds modifications, or obvious formatting problems.
The second layer is static checking, which catches syntax, type, or rule-level errors. It raises confidence but does not prove runtime behavior is correct.
The third layer is targeted testing, prioritizing the modified logic and its boundary conditions. When fixing a defect, add a test that reproduces the original problem where possible, then confirm it passes after the fix.
The fourth layer is expanded regression, checking adjacent modules or broader behavior. Whether to run the full suite should be decided based on task risk, resource cost, and environmental conditions.
The final report must distinguish three states:
- Verifications executed and passed.
- Verifications executed and failed.
- Verifications not executed due to environment, permission, or time constraints.
Do not write “no failure observed” as “proven correct,” and do not treat passing tests as the absence of all other defects.
8. Engineering for Production: From Demo to Trusted System
8.1 Observability and Audit
Every tool call should be logged with time, parameter summary, permission decision, execution status, and associated changes. Logs must be sanitized to avoid persisting complete copies of sensitive file contents and credentials.
Observability serves not only troubleshooting but also explaining why the agent took an action. Users should be able to trace the basis for a modification rather than seeing only the final generated code.
8.2 Failure Recovery and Concurrency Control
Sessions should support interruption and recovery, preserving pending actions and confirmed results. After recovery, first inspect the workspace state to avoid re-applying patches.
When multiple writers touch the same file, conflict detection is required. The file version the model saw when generating its plan may differ from what exists at actual execution time; the runtime must detect this discrepancy.
8.3 Evaluation Metrics and Task Samples
Evaluation should not merely measure whether model replies are fluent. Focus on task completion rate, proportion of unrelated modifications, verification coverage, approval accuracy, execution cost, and failure-recovery performance.
Test tasks should include normal fixes as well as insufficient information, permission denial, tool timeout, malicious file content, and concurrent external modification. Only by covering abnormal paths can you determine whether the system has reliable control capabilities.
9. Conclusion: The Core Is Controlled Action, Not Unlimited Automation
To understand intelligent coding agents, follow this analytical thread: how state is preserved, how evidence enters context, how actions are constrained, and how results are verified.
Truly reliable systems do not give the model the most permissions; they give it capabilities sufficient to complete the task while remaining limitable and auditable. Dynamic context improves decision quality, structured tools reduce execution ambiguity, permissions and isolation control risk, and the verification loop turns code changes into explainable task outcomes.
Starting with limited tools, explicit state, and strict verification is a better path to a maintainable engineering implementation than opening full terminal access first and adding safety measures afterwards.
