Coding Agent Architecture Breakdown: Harness Engineering and Two-Layer State Machines

    This article describes common engineering practices behind coding agents without relying on any specific product's internal code. It covers input and output constraints, prompt management, and context control, along with a loop of gathering context, deciding actions, calling tools, and verifying results. It also explains how a two-layer state machine separates planning from execution, how to handle errors and define termination conditions, and which security boundaries and infrastructure choices matter. Readers can use it to judge where a coding agent is stable or fragile and to guide the design of their own tools.

    This article does not depend on the internal code of any specific product. It discusses engineering approaches that these systems commonly use. The approaches come from publicly shared design practices, and they can help you judge where a coding agent is stable and where it is fragile, as well as guide the construction of your own tools.

    1. Capability Gaps Often Come from External Constraints

    Two systems built on the same base model can perform very differently depending on the engineering around the model. Models hallucinate, overlook detailed instructions, and forget earlier agreements in long contexts. An engineering system keeps these instabilities within a controllable range.

    The industry often calls this work Harness Engineering, which can be translated as “constraint engineering.” Its core practices fall into three categories:

    1. Input and output constraints: Tool calls use structured parameter definitions. Model output is validated before execution, and malformed output is sent back for a retry.
    2. Prompt management: System prompts are versioned, and templates switch by task type. A single prompt does not carry every responsibility.
    3. Context control: Each step has an explicit limit on how much history it can include. When the budget is exceeded, the context is summarized or trimmed.

    The key idea is to treat the model as a reasoning component that must be steered, rather than as a black box that delivers finished results on its own.

    2. The Closed-Loop Execution Flow

    A usable coding agent typically runs through four stages. Each stage should have clear inputs, outputs, and failure handling.

    Stage Input Output Failure Handling
    Gather context User instructions, codebase index, session memory, current file state Context fragments relevant to the task If retrieval returns nothing, widen the search or ask the user a follow-up question
    Decide action Context fragments, list of available tools Next action and its parameters If parameters are invalid, ask the model to regenerate them
    Call tool Action and parameters Tool result or error message Timeouts and permission errors enter the recovery flow
    Verify result Tool result, task goal Decision to continue, complete, or stop If the outcome is unclear, preserve the current state and request human confirmation

    The value of this loop is that every step can be logged and reviewed. When something goes wrong, developers can identify the stage where the error occurred.

    3. The Two-Layer State Machine

    A simple while loop struggles to support multi-step development tasks. As the context grows, the model becomes easily distracted. A more reliable approach splits the loop into two layers.

    The outer loop handles planning. It receives the user’s high-level goal, breaks it into subtasks, and maintains the global goal and key memory. Its states typically include: planning, executing a subtask, summarizing progress, and completing or abandoning the task.

    The inner loop executes a single subtask. It selects a tool, fills in parameters, executes the call, parses the result, and decides whether to continue. Its states typically include: selecting a tool, filling parameters, executing, parsing results, subtask completed, and subtask failed.

    The division of labor is clear. The outer loop tracks only “how far have we got,” and the inner loop handles only “how to do this step.” When the inner loop finishes, it returns only a compressed conclusion to the outer loop, so execution details do not fill up the global context.

    4. Fault Tolerance and Recovery

    Failures are normal in real development. Network fluctuations, tool timeouts, insufficient file permissions, and missing dependencies all happen. A fault-tolerance design needs to answer two questions: who handles an error after it occurs, and how the system wraps up when it cannot handle the error.

    Common recovery methods include:

    • Passing the original error message back to the model so it can correct the parameters or switch to a different tool.
    • Retrying temporary failures, such as network timeouts, with backoff and a maximum retry count.
    • Triggering summary compression when the context overflows. Keep the goal, constraints, and unfinished items, and discard process details.
    • For permission failures, do not bypass them automatically. Hand them to the user.

    The number of recovery paths depends on how many failure types the system covers. What matters is not the count of paths but whether each failure type has a clear owner and a defined way to handle it.

    5. Termination Conditions and Preventing Idle Loops

    One of the most common problems in coding agents is going in circles. The agent repeats the same action or switches back and forth between two states, consuming many tokens without making progress. Termination conditions should therefore be defined early in the design.

    Common termination conditions include:

    • The task goal is reached and verified.
    • An unrecoverable error occurs.
    • The maximum step limit is reached.
    • The token or cost budget limit is reached.
    • The same action is executed several times in a row. For example, compute a hash of the action name and its parameters. If the same hash appears three times in a row, treat the run as idle.
    • The user interrupts the task.

    A few guidelines apply to these settings. Set the step limit based on an estimate of the task’s size rather than an arbitrarily large number. Tie the budget limit to the cost that is acceptable for a single task. Set the idle detection threshold carefully, because a threshold that is too low will flag legitimate repeated reads as loops.

    6. Common Mistakes and Considerations

    When building this kind of system, the following problems appear often:

    1. No termination conditions are set, which leads to infinite loops and uncontrolled costs.
    2. The context only grows and is never trimmed, so the model frequently forgets key early constraints later on.
    3. Tool permissions are too broad, so the agent can delete or modify files outside the task scope.
    4. Keys, tokens, or private user data end up in logs.
    5. Verification only checks whether a tool returned success, without checking whether the result actually meets the goal.

    7. Infrastructure and Security Boundaries

    Coding agents usually need a code index, log collection, and containerized execution environments. General-purpose cloud services can provide these capabilities, including elastic container platforms, object storage, and monitoring and alerting services. When choosing a platform, focus on the following points:

    • Sandbox isolation strength: Whether the code execution environment is isolated from the host system and the production network.
    • Least privilege: The credentials the agent uses are granted only the minimum permissions needed to complete the task.
    • Log redaction: Tool call logs filter out keys and personal information.
    • Cost monitoring: Alert thresholds are set for token consumption and compute resources.
    • Observable state: The transitions of the state machine are recorded, which makes it easier to find bottlenecks in recovery paths.

    Infrastructure amplifies whatever design it runs on. On a system without constraints and state design, more computing power only produces errors faster.