How Coding Agents Work: From the Core Loop to Production Engineering

    This article explains the internal mechanics of coding agents from a systems perspective. It covers the four core components, the perception-planning-action-observation loop, strategies for organizing repository context, tool design and permission rules, prompt caching and memory management, and an evaluation checklist for engineering deployment. Numerical values in the examples are illustrative and should be tuned to your model, task scale, and budget.

    1. Introduction: Outcomes Are Determined by the System

    A coding agent is a program that can autonomously read code, invoke tools, modify files, and verify results around software development tasks. These agents typically use a large language model as their reasoning core, but the effectiveness users actually experience depends heavily on the application layer wrapped around the model—the agent harness. The same model placed in different harnesses can show markedly different task success rates, stability, and cost. This article therefore dissects the operating logic of coding agents from a systems viewpoint and provides actionable checkpoints. All numeric examples illustrate design approaches; actual values should be adjusted based on the model, task scale, and budget.

    2. Basic Components and the Core Loop

    A typical coding agent consists of four parts:

    • Reasoning core: a large language model that understands intent, forms plans, and generates code or tool-call requests.
    • Orchestration layer: manages conversation state, assembles prompts, parses model output, dispatches tools, and records logs.
    • Tool set: capabilities such as reading files, searching code, executing commands, editing files, and running tests.
    • Runtime environment: a local working directory or isolated container, with permission boundaries and operation logs.

    The agent operates in a loop of perception, planning, action, and observation. Pseudocode:

    1. state = initialize(user_task, repo_summary)
    2. steps = 0
    3. while not state.done:
    4. if steps >= MAX_STEPS: # example value, e.g. 50
    5. abort("step budget exhausted", save_checkpoint)
    6. prompt = assemble(system_instructions, tool_definitions, memory, state.history)
    7. reply = model.generate(prompt)
    8. if reply contains tool calls:
    9. for call in parse_tool_calls(reply):
    10. if not check_permission(call):
    11. state.history.append(call, "permission denied")
    12. continue
    13. if is_high_risk(call) and not user_confirm(call):
    14. state.history.append(call, "awaiting user confirmation")
    15. continue
    16. result = execute_tool(call, timeout=TOOL_TIMEOUT)
    17. state.history.append(call, truncate(result))
    18. else:
    19. state.done = check_completion(reply)
    20. steps += 1

    The critical part of the loop is observation. The result of every tool execution returns to the context, and the model uses it to correct its next action. If command output is silently dropped or error messages never come back, the agent keeps moving forward on wrong assumptions. The orchestration layer must therefore guarantee that every action produces visible, traceable feedback, including exit codes, error messages, and timeout flags.

    A single question-answer exchange can only offer suggestions. The value of a coding agent comes from the multi-step closed loop: modify code, run tests, then roll back or revise based on failure output. The loop is also where risk concentrates. Without a step limit and checkpoints, one wrong assumption can cause the agent to repeatedly corrupt the same set of files, so the loop must be bounded.

    3. Organizing Repository Context

    A repository usually contains many files, while the model’s context window is limited. The orchestration layer cannot put the entire repository into the prompt; it must fetch context on demand. Four common approaches:

    1. Retrieval-based context: use keyword search (e.g., grep) or semantic retrieval to find relevant files and code snippets. Suitable for medium-to-large repositories; low cost and simple to implement. The main failure modes are missed recall due to keyword mismatch and false recall from identically named symbols. Boundary condition: cap the number of returned matches—for example, at most 20 per query, ranked by relevance.

    2. Summaries and compression: generate short descriptions of directories or modules and place them in the prompt as a structural map. Suitable for tasks requiring a global understanding, such as cross-module refactoring. The main risk is stale summaries that no longer match the code. Boundary condition: each summary must record the commit hash at generation time and be regenerated after code changes.

    3. Symbol index: records where functions, classes, and interfaces are defined and referenced, answering questions like “where is this function called?” Suitable for statically typed languages or codebases with explicit dependencies. The main risk is that dynamic dispatch, reflection, and string-constructed calls are easily missed. Boundary condition: index results must be cross-validated with search or direct source reads.

    4. Incremental reading: read file headers, function signatures, or specified line ranges first, expanding only when needed. Suitable for very large files and long logs. The main risk is missing context—for example, a type defined elsewhere. Boundary condition: every read carries a line-number range, and truncation points are marked in the output.

    Method Per-call cost Suitable repo size Main risk
    Retrieval-based context Low Medium to large Missed or false recall
    Summaries and compression Medium; requires generation and maintenance Any; good for structural understanding Stale summaries
    Symbol index Medium; requires indexing Medium to large; more effective for static languages Missed dynamic calls
    Incremental reading Low to medium Any; good for large files Missing context

    Here is a minimal example. The task is to fix a null-pointer exception in the login endpoint:

    1. Use retrieval-based search to find login-related routes and locate the login function in the auth module.
    2. Use incremental reading to inspect that function and the user model definition it depends on.
    3. Create a checkpoint before modifying, so rollback is possible.
    4. Run the relevant tests after modifying.
    5. If tests fail, read the failure output, narrow the change scope, or roll back to the checkpoint.

    4. Tool-Call Design and Permissions

    Every tool needs a clear name, purpose, parameter schema, return format, and error format. Tools should be narrow. Reading files, searching, editing files, and running tests should each be separate. A general-purpose shell tool that can execute arbitrary commands is the most powerful and the most dangerous; it should only be exposed inside a sandbox.

    Recommended permission rules:

    • Read-only by default. Reading paths outside the working directory requires explicit user authorization.
    • Writes are confined to the task working directory, validated against a path whitelist to prevent traversal such as ../.
    • The following high-risk operations require user confirmation: deleting files, force-pushing code, changing file permissions, accessing external networks, performing database writes, and installing dependencies.
    • Commands execute inside a container or sandbox with timeouts and resource limits.
    • Create a checkpoint before batch modifications. The orchestration layer must not automatically run destructive commands such as git reset --hard; rollback operations also require user confirmation.

    Tool output can be very long, and placing it directly into the prompt crowds out context. A common approach keeps the head and tail—for example, the first 200 and last 100 lines—replacing the middle with “N lines omitted,” while writing the full output to a file for later reading. Whatever truncation strategy you use, the fact of truncation must be stated; output must never be silently discarded.

    Recommended failure handling:

    • Tool timeout: return timeout information; retry the same call at most 2 times.
    • The same class of failure 3 times in a row: pause execution and request user intervention.
    • Step limit reached: save state and a checkpoint, then abort.
    • Tests fail after changes have taken effect: roll back to the most recent checkpoint, or continue modifying with user confirmation.
    • The same call with the same parameters repeats consecutively: treat it as a loop and abort execution.

    5. Prompt Caching, Memory, and Long-Session Continuity

    Many model services support prompt-prefix caching. To benefit, place stable content at the beginning of the prompt: system instructions, tool definitions, and project rules. Dynamic content—such as the current task and the latest tool outputs—goes at the end. The prefix must not contain timestamps, random IDs, or tool lists whose order changes between calls, as these break cache hits. Whether caching actually pays off should be judged by the usage fields returned by the service and verified through hit rates; never assume savings based on intuition.

    Memory falls into two categories:

    • Short-term memory: the conversation history. When it exceeds the context budget, compress earlier turns into a summary that preserves key decisions, the list of modified files, and outstanding items, while keeping the most recent turns in full.
    • Long-term memory: project rule files, such as a project description document. Writes require user review to prevent the model from cementing wrong assumptions. Secrets, tokens, and personal data must never be written to any memory.

    Long-session continuity relies on an external state file, not the model’s memory. The state file should record the goal, the plan checklist, completed steps, modified files, items pending verification, and the most recent checkpoint. At the end of each phase, create a new checkpoint recording the commit hash and test results. When resuming a session, first read the state file, then verify that the repository’s current state matches the records. If the two disagree, treat the actual repository state as authoritative and ask the user how to proceed.

    6. Evaluation and Engineering Deployment

    When evaluating an agent system, you can use the following checklist.

    Dimension Metric Measurement method
    Success rate Proportion of tasks passing acceptance Run a fixed task set multiple times and aggregate
    Cost Tokens and tool calls per task Read the usage fields returned by the service
    Stability Variance in results across repeated runs of the same task Run the same task N times and compare outcomes