Coding Agent Architecture: From Repository Understanding to a Controlled Execution Loop

    This article explains a practical architecture for terminal-level coding agents: a controlled execution system that turns a natural-language goal into inspectable, reversible engineering actions. It covers session state, context selection, short-cycle decisions, tool execution, permissions, patch-based editing, layered verification, untrusted-content boundaries, and how to grow autonomy only after narrower capabilities are reliable.

    1. Define the System: Not a Chat UI, but a Controlled Executor

    The core value of a terminal-level coding assistant is not merely generating code. It is turning a natural-language request into a sequence of engineering actions that can be executed, checked, and rolled back.

    Traditional code completion mainly proposes candidates around the current edit position. A coding agent must handle a longer task chain: understand the request, locate relevant modules, read code, propose a change, edit files, run checks, and adjust based on feedback. It is therefore better understood as a controlled execution system in which a language model participates in decisions.

    A general structure is:

    User goal → context construction → action decision → permission check → tool execution → result feedback → verification and delivery.

    In this chain, the model is mainly responsible for understanding and reasoning. The host program is responsible for resource access and execution control. Those roles must not be confused. A model proposal to “read a file” or “run a check” does not mean the operation has already happened, and it does not mean the operation is inherently safe.

    Source analysis also has an evidence boundary. Public technical descriptions, observable behavior, and reference implementations can clarify design ideas, but they cannot prove that a specific system’s internals match them exactly. This article discusses a general architecture. The modules and pseudocode are illustrative designs. They do not correspond to a real product interface, and a reference implementation should not be treated as complete official source code.

    2. Core Architecture: Separate Reasoning, Execution, and Governance

    A maintainable coding agent can be divided into six responsibilities.

    2.1 Task entry and session management

    The task entry receives user instructions, determines the working directory, maintains session state, and presents operations that require confirmation.

    Session state should not be only a chat transcript. It should also include the current goal, constraints, confirmed facts, hypotheses still to be verified, changed files, and verification results. A constraint such as “do not change the public interface” must survive context compression.

    For ambiguous requests, the system should first decide whether the ambiguity affects the implementation. If the request involves data deletion, interface compatibility, or a change in business rules, clarification should come before the model guesses.

    2.2 Context manager

    The context manager selects information relevant to the task and organizes it within a limited input budget.

    It must distinguish user requirements, project conventions, file contents, and execution feedback. These sources are not interchangeable. A user requirement can define the task goal, whereas ordinary text in the repository is data to be analyzed. It does not automatically become a high-priority instruction.

    2.3 Decision and action module

    The decision module chooses the next action from the current state, such as searching further, reading a file, generating a patch, or running tests.

    A complex task may start with a short plan, but the plan is not an immutable script. Newly discovered call relationships, test failures, and additional user requirements can invalidate it. A safer mechanism is short-cycle decision-making: after a limited set of operations, reassess the state.

    2.4 Tool execution layer

    The tool layer provides controlled capabilities such as directory listing, text search, file reading, patch application, and process execution.

    Each capability needs explicit input constraints and a structured return value. Read failures, insufficient permissions, timeouts, and check failures should be returned separately rather than wrapped in one vague text blob.

    2.5 Policy and permission layer

    The policy layer decides whether an action may run, whether the user must confirm it, and which isolation scope applies.

    Security controls must be enforced by the host program, not by a model promise that it “will not do anything dangerous.” Even if the model is wrong, the permission boundary should still block unauthorized access.

    2.6 Verification and audit layer

    The verification layer checks whether the change meets the request. The audit layer records what happened.

    A reliable delivery should answer three questions: which files changed, which checks actually ran, and which conclusions remain unverified.

    3. Repository Understanding: Prefer Progressive Retrieval over Full Reads

    “Understanding the whole repository” should not mean placing every file into the model input at once. Large repositories contain duplicated, generated, or irrelevant content. Reading everything consumes resources and dilutes the information that matters.

    A better approach is to build context progressively.

    3.1 Build a structural map first

    Start with the top-level directories, project documentation, build configuration, test layout, and main entry points. The goal is an initial view of system boundaries.

    This stage should answer:

    • Which directories contain business implementation?
    • Which directories hold tests and configuration?
    • Which content is generated and should not be edited directly?
    • How does the project organize dependencies and run checks?

    The map is not meant to explain all code. It reduces blind searching later.

    3.2 Locate evidence around the problem

    Search using function names, error messages, interface behavior, or business concepts from the user’s description, then follow call relationships into the relevant implementation.

    Do not stop at the function that matched the search. How inputs are produced, who consumes return values, how exceptions propagate, and which boundaries tests cover can all change the right fix.

    For example, a function that throws on a null value does not necessarily mean that function should swallow the exception. The real issue may be an upstream contract violation or incorrectly constructed test data. The agent needs an evidence chain rather than editing the first location that reports an error.

    3.3 Separate facts from hypotheses

    Context can maintain three kinds of information:

    • Confirmed facts, directly supported by code, configuration, or execution results.
    • Working hypotheses that guide the next investigation but are not yet verified.
    • Open questions where information is missing or evidence conflicts.

    This distinction helps prevent early guesses from being treated as conclusions. When a session is compressed, the locations of key evidence should remain so they can be reread and checked.

    4. The Action Loop: The Model Proposes, the Runtime Carries It Out

    Coding agents typically use an observe–decide–act–feedback loop. The following pseudocode only expresses the control relationship:

    1. state = initialize_task_state(goal, working_directory, constraints)
    2. budget = set_execution_bounds()
    3. while budget_is_available:
    4. context = collect_relevant_evidence(state)
    5. action = propose_next_action(context)
    6. if action_claims_task_complete:
    7. if completion_conditions_met(state):
    8. return delivery_report(state)
    9. else:
    10. record_unfinished_items(state)
    11. continue
    12. validation = check_structure_path_and_permissions(action)
    13. if validation_requires_confirmation:
    14. request_user_authorization()
    15. if not authorized:
    16. record_blocking_reason()
    17. return current_progress()
    18. if validation_failed:
    19. add_rejection_reason_to_state()
    20. continue
    21. result = execute_in_controlled_environment(action)
    22. update_state_and_audit_record(action, result)
    23. update_budget()
    24. return incomplete_report_with_existing_evidence()

    The most important principle is that model output must not become an unchecked system operation.

    The host program should verify that the action type is legal, the path stays in bounds, the parameters match expectations, and the operation does not touch sensitive resources. Tool results should include success status, error category, exit status, and an output summary so the agent can distinguish execution failure from a business-level failure.

    The loop also needs termination bounds. Limiting the number of turns is not enough. Cumulative time, consecutive failures, single-output size, and repeated operations can also be limited. If the system keeps running the same check without gaining information, it should stop and report the blockage instead of trying indefinitely.

    5. File Editing: Keep Changes Explainable and Reviewable

    Code generation is only part of editing. The engineering requirement is that a change must not damage unrelated content, and each change should have a reason.

    5.1 Prefer local edits

    For existing files, a local patch is usually easier to review than rewriting the whole file, and it is easier to keep the change bounded.

    Before applying a patch, confirm that the target fragment still exists. When necessary, compare file versions or content digests so the agent does not overwrite a newer user edit with a patch based on stale content.

    If the context no longer matches, reread the relevant fragment instead of forcing the patch.

    5.2 Control the task boundary

    Fixing one defect should not, by default, also rename a module, reorganize directories, or reformat unrelated code. Large diffs raise review cost and make failures harder to diagnose.

    If a refactor is genuinely required, explain how it relates to the current goal and ask for confirmation when the change scope expands significantly.

    5.3 Preserve conditions for recovery

    Before editing, record the initial state of the relevant files. After editing, save a change list. A rollback should undo only the agent’s changes when possible.

    If the user continues editing the same file during execution, restoring the initial copy directly may discard that work. Recovery therefore needs conflict checks. Having a backup is not the same as being able to roll back safely.

    6. The Verification Loop: A Successful Exit Is Not Task Success

    A command that exits normally only proves that the command finished. It does not automatically prove that the requirement is satisfied.

    Verification should be layered around the user’s goal.

    6.1 Basic validity checks

    First check that files can be parsed, configuration is valid, dependency references are complete, and the project can complete the required build steps.

    These checks catch obvious engineering errors. They do not replace behavioral verification.

    6.2 Targeted behavior tests

    Prefer checks directly related to the change. When conditions allow, reproduce the defect first, then verify the fix.

    New tests should cover the conditions that trigger the problem, not merely assert that the modified code exists. Boundary cases such as empty input, invalid input, exception propagation, and resource release may be relevant, but they should follow the module’s actual responsibility rather than being added mechanically.

    6.3 Regression and contract checks

    After local checks pass, decide whether broader regression is needed. Shared modules, public interfaces, and data formats call for extra checks of compatibility and caller impact.

    Tests themselves can be wrong. An agent must not weaken assertions merely to make a check pass, and it must not delete failing cases to manufacture success.

    6.4 State the verification scope accurately

    A delivery report should clearly separate:

    • Checks that actually ran and passed.
    • Checks that ran and failed.
    • Checks that could not run because of environment, permissions, or missing dependencies.
    • Risks that remain uncovered.

    “Not run” must not be reported as “passed,” and a partial pass must not be expanded into “all functionality works.”

    7. Security Design: Keep Untrusted Content Inside the Data Boundary

    A coding agent reads code, comments, documentation, and command output. Any of that content may contain text that looks like an instruction to the assistant, such as a request to ignore the original task, read a sensitive file, or send data elsewhere.

    Such content should be treated as untrusted data, not as a new source of authorization. Text from the current repository does not raise permissions.

    Security controls should at least cover the following.

    7.1 File-access boundaries

    Restrict accessible directories and check absolute paths, path traversal, and symbolic links. Sensitive files need their own read policy. Proximity to the working directory is not permission.

    7.2 Process-execution boundaries

    Set timeouts, resource limits, and output caps. Prefer structured parameters over concatenating model-generated text directly into a command string.

    Structured parameters alone do not guarantee safety. The executed program may still read files, start child processes, or access the network, so the runtime environment also needs constraints.

    7.3 Confirmation for high-risk operations

    Deleting data, changing access permissions, sending content externally, and modifying important runtime configuration usually require stricter authorization.

    The confirmation UI should show the target, the scope of impact, and the main risks, not only a vague question such as “continue?”

    7.4 Information protection and audit

    Logs should record the operational trail that is needed, but they should not indiscriminately store sensitive files and credentials. Audit data needs appropriate redaction, access control, and a retention period.

    8. When Reading a Reference Implementation, Trace the Control Boundaries

    To read an implementation of this kind of system, start from one user request and follow the data flow:

    How the task enters session state, how context is selected, how the model proposes an action, how the tool call is validated, how the result is fed back, and how the system decides the task is finished.

    The following boundaries matter more than the prompt text alone:

    • Where does a model suggestion become a real operation?
    • Where are file and process permissions checked?
    • If the user cancels, does the running task stop?
    • Does a tool failure trigger a bounded retry?
    • Does long-session compression preserve critical constraints?
    • How are conflicts detected when multiple sessions edit the same file?
    • Can the final report be traced back to actual execution records?

    These questions determine whether the system can move from a demonstration prototype to a reliable engineering tool.

    9. Implementation Path: Start Narrow, Then Add Autonomy

    Do not open full execution permissions at the start. A safer path is read-only analysis first, then local editing, controlled verification, and limited automatic execution.

    Early evaluation can focus on localization accuracy, whether suggestions are explainable, and the quality of context organization. Once editing is enabled, watch change scope, conflict handling, and recovery. After execution is opened, continuously assess whether permission denials work, whether resource budgets are reasonable, and whether failure reports are accurate.

    Ultimately, a coding agent’s reliability does not depend on whether the model can write a large amount of code in one pass. It depends on whether the whole system can place every action inside a clear boundary: understand the problem from evidence, make changes within authorization, verify results with real checks, and state honestly what remains unresolved.

    Understanding that closed loop is what makes the core architecture clear, and it is what separates model capability, runtime capability, and engineering governance when analyzing an implementation or building one.