Evaluating Coding Agents and Using Long Context Effectively

    This article explains how to evaluate coding agents beyond single-function code generation. It covers four core capabilities—repository understanding, cross-file modification, error recovery, and toolchain stability—and then examines the practical limits of long-context models, including key evidence extraction, logical consistency, and cost and latency. It presents three implementation approaches: retrieval augmentation and code indexing, task decomposition with staged execution, and secure toolchain integration. The article closes with applicable boundaries and risk controls for adopting coding agents in real repositories.

    1. The Evaluation Target Has Changed

    In the past, code generation models were often evaluated by whether they could write a correct function from a function signature. Real software development is different. An agent needs to read requirements in a terminal, call file and command tools, run tests, handle errors, and finally deliver a change that can be reviewed and merged. Evaluation criteria must change accordingly. Checking whether a single code snippet is correct is no longer enough.

    Benchmark results can serve as a reference, but they cannot replace actual performance in a project. Benchmark tasks usually have a fixed scope and clean context, whereas real repositories contain legacy code, incomplete documentation, and unstable test environments. A more reliable approach is to select a set of tasks from problems the team has already solved, form a private evaluation set, and repeatedly test candidate models under the same conditions.

    2. Four Core Capabilities of Coding Agents

    The following four dimensions can be scored individually. Each should have observable metrics and a clear acceptance method.

    Capability Observable metric Acceptance method Common failure
    Repository understanding Accuracy in locating target modules and dependencies without being given file paths Ask “Which layer contains the authentication logic for this interface?” and verify the referenced location Guessing location from naming and missing indirect calls
    Cross-file modification Recall of files that need changes, compile and test pass rate after changes, number of unrelated files modified Compare file by file against a manually annotated change list Changing only the interface definition and missing callers
    Error recovery Number of rounds required to fix a given failing test Check whether the original test passes after the fix without modifying the test itself Deleting assertions to make the test pass
    Toolchain stability Whether working directory, environment variables, and branch state remain correct after repeated command calls Run a task with more than twenty consecutive steps and check state at each step Repeating destructive commands after a timeout

    Error recovery requires special inspection. Models sometimes modify test cases or relax assertions so that tests appear to pass. During evaluation, test files should be fixed. Any change to a test file should be flagged separately and confirmed by a human.

    3. Long Context: Capabilities and Boundaries

    Some current flagship models support million-token context windows; specific capabilities depend on the model and deployment conditions. This capability is attractive for large projects. Developers can feed the entire source code of a microservice into the model, and analysts can process dozens of financial reports and industry documents at the same time, reducing manual splitting and summarization work.

    However, fitting information into the input window does not mean the model can use every piece of it accurately. In practice, there are three main problems.

    The first is key evidence extraction. In very long inputs, the model may pay insufficient attention to information located in the middle, a phenomenon often called “lost in the middle.” To verify this, insert several verifiable facts at different positions in a long document, ask questions, and record the curve of answer accuracy as position changes.

    The second is logical consistency. The longer a conversation or task, the more easily constraints established at the beginning are violated in later steps. For example, if the opening states “do not modify public interfaces,” the model may still change them by the tenth round. To verify this, state the rules at the beginning and check compliance item by item across multiple subsequent rounds.

    The third is computational cost and latency. Attention computation grows quadratically with context length (O(n²)), and KV cache usage grows approximately linearly with length. Actual latency is also affected by batching strategy, hardware, and inference implementation, so cost cannot be estimated from token unit price alone. Time and cost should be measured on your own tasks.

    Therefore, putting all code into the context at once is not necessarily the easiest or best option. When comparing approaches, control the variables: use the same model, the same task set, and the same scoring standard; test full-context input and retrieved-context input separately; and record accuracy, latency, and cost.

    4. Three Practical Implementation Approaches

    4.1 Retrieval Augmentation and Code Indexing

    Do not put the entire project directly into the context. First use vector retrieval or AST (abstract syntax tree) analysis to extract code snippets, function definitions, and dependencies relevant to the current task, then pass this content to the model. Relevant information is more concentrated, token consumption is lower, and answers are easier to verify.

    The index needs regular updates. Code repositories change quickly, and a stale index can cause the model to reference functions that have already been deleted. It is recommended to trigger incremental indexing after each merge to the main branch and to include file paths and version numbers in retrieval results so that humans can verify them.

    4.2 Task Decomposition and Staged Execution

    Complex requirements should be decomposed first and then executed step by step. Take “refactor the user authentication module” as an example. It can be split into four subtasks: “review the existing authentication logic,” “design a new token refresh mechanism,” “modify the core authentication classes,” and “update related unit tests.”

    Each subtask needs clear boundaries. The recommended granularity is within one module and a small number of files, and acceptance commands should be written for each subtask, such as unit tests passing and static checks reporting no new warnings. Create a checkpoint before each subtask so that failures can be rolled back to the previous checkpoint.

    Logs should record the following fields: task ID, execution step, list of files in the input context, executed commands, exit code, duration, whether a rollback occurred, and whether the task was escalated to a human. These fields help the team identify the types of tasks on which the model repeatedly fails.

    The pseudocode below illustrates the control flow. It is for illustration only and must not be used directly in production.

    1. # Pseudocode: control flow for staged execution. For illustration only; not for direct production use.
    2. MAX_RETRIES = 2
    3. def execute_complex_task(user_requirement, sandbox, policy, audit_log):
    4. sub_tasks = llm_agent.decompose(user_requirement)
    5. for task in sub_tasks:
    6. checkpoint = sandbox.create_checkpoint()
    7. context = codebase_retriever.search(task.keywords, max_files=10)
    8. succeeded = False
    9. for _ in range(MAX_RETRIES + 1):
    10. action = llm_agent.generate_action(task, context)
    11. # Whitelist validation: only allow pre-approved commands and paths
    12. if not policy.is_allowed(action):
    13. audit_log.record(task.id, action, status="rejected")
    14. break
    15. # Execute in the sandbox with a timeout
    16. result = sandbox.run(action, timeout=120)
    17. audit_log.record(task.id, action,
    18. exit_code=result.exit_code,
    19. duration=result.duration)
    20. if result.is_success:
    21. succeeded = True
    22. break
    23. context.append(result.error)
    24. if not succeeded:
    25. # Roll back and escalate to human review when retries are exhausted or policy rejects the action
    26. sandbox.rollback(checkpoint)
    27. human_review.request(task)
    28. return

    The retry count, timeout, and whitelist in the example need to be adjusted for each project. Fixes generated by the model should also be delivered to human reviewers as code diffs and should not be merged directly.

    4.3 Secure Toolchain Integration

    Letting the model call a terminal and execute scripts must be done in a sandbox environment and follow the principle of least privilege. The sandbox should not contain production credentials, and network egress should be restricted to the necessary destinations.

    Sensitive data should preferably not enter the model context. Secrets in configuration files, user personal information, and similar content should be redacted during retrieval, or stored in independent object storage and read on demand by a dedicated service. Long-running builds and test tasks are suitable for asynchronous processing through a message queue, avoiding the agent occupying a session for a long time and producing duplicate executions.

    5. Applicable Boundaries and Risk Warnings

    Evaluation conclusions apply only to the task types and repository sizes that were tested. If the language, framework, or codebase size changes, the conclusions need to be validated again.

    Agent changes should not be merged directly into the main branch, and certainly should not be deployed directly to production. Before merging, a human needs to review the diff and confirm that test results are trustworthy.

    Cost and latency need upper limits. You can set a maximum number of tokens, maximum retries, and maximum runtime per task; when a limit is exceeded, stop and prompt for human intervention.

    Performance improvements need support from actual data. It is recommended to start with a two-to-four-week pilot, compare task completion rate, rework rate, and average duration, and then decide on the scope of rollout. If the data does not show clear improvement, the scope of agent use should be reduced rather than expanding permissions.

    Coding agents can take on more and more engineering tasks, but their reliability depends on whether task decomposition is reasonable, whether context is filtered, and whether the execution environment is controlled. Only by doing these three things well can a team judge what the model can and cannot do in its own projects.