Long-Horizon Coding Agent Evaluation: A Practical Guide to Terminal Sandboxes

    This article examines how the evaluation of coding agents is shifting from single-point code completion toward end-to-end task completion, and why long-horizon tasks demand a more rigorous approach. It breaks down the core challenges of long-horizon work—error accumulation, context drift, implicit constraints, and non-repeatability—and explains why real, resource-constrained terminal sandboxes are the most credible testing ground. It then walks through engineering practices for building more reliable agents (planning and replanning, parsing tool output, layered memory, self-verification, and termination control), a multi-dimensional metric system, failure attribution, and how enterprises can operationalize long-horizon coding agents. Readers will find practical guidance, configuration examples, and code snippets for designing evaluations that reflect real production conditions.

    Introduction: The Focus Shifts from “Correct Completion” to “Task Completion”

    On mainstream terminal-oriented coding benchmarks, the scores of top models are converging, and the gaps between them have often narrowed to a small range. In internal tests that emphasize long-horizon tasks, however, the improvements across generations tend to be more pronounced. This contrast suggests that the capability structure of code agents is changing—and that the way we evaluate them needs to evolve accordingly.

    Early code model evaluations mostly centered on function-level completion, typically in the form of “given a function signature and docstring, complete the function body,” measured by a single-point pass rate. With the rise of code agents, the question changed: given a repository and a requirement, can the agent autonomously read code, invoke the terminal, run tests, locate defects, and complete the fix? The standard of measurement shifted as well—from “writing it correctly the first time” to “delivering the task in full.” For long-horizon capability, the real terminal sandbox is the most convincing testing ground.

    1. From Completion to Autonomy: Why Long-Horizon Tasks Are Harder

    1.1 The Essential Differences Among Three Task Forms

    Task form Typical input Interaction Main difficulty Common evaluation method
    Completion-style Local code context Single generation Local semantic understanding Hidden unit tests
    Conversational Natural-language requirement Multi-turn dialogue Intent understanding, context retention Automated scoring, human review
    Long-horizon autonomous Requirement description, code repository, terminal environment Dozens of tool calls Coordinating the full chain of planning, execution, debugging, and verification End-to-end testing in a terminal sandbox

    Long-horizon tasks require the model to continuously observe environmental feedback, dynamically adjust its strategy, and converge within a limited budget of steps and resources. What they test is no longer a single capability but the coordination of many capabilities.

    1.2 The Four Core Challenges of Long-Horizon Tasks

    First, error accumulation. A long-horizon task is a chain of multiple decision steps. Suppose the probability of “making the correct decision” at each step is p, and the task consists of n critical steps; under ideal conditions, the overall success rate is roughly p raised to the power of n. When p is 0.95 and n is 20, the overall success rate is about 36%; when p rises to 0.98 and n is 50, the overall success rate is again about 36%. This illustrates two points: in long-horizon settings, small improvements in single-step reliability are amplified exponentially; and optimizing a single point of capability alone cannot solve the long-horizon reliability problem.

    Second, context drift. Every command the agent executes produces output: compilation logs can run to tens of thousands of characters, and a full test report may contain hundreds or thousands of results. Keeping all raw content quickly fills the context window, drives up cost, and dilutes attention; over-compressing, however, may lose critical clues—for example, an ignored warning that turns out to be the root cause of a defect. Information triage and state management are therefore core engineering problems for long-horizon agents.

    Third, the implicit nature of goals and constraints. Real development tasks often carry implicit constraints: fixing a defect must not break existing functionality, changes should follow the project’s established style, and no new dependency conflicts should be introduced. These constraints are usually not written into the requirement and must be inferred by the agent proactively reading configuration, tests, and commit history.

    Fourth, non-repeatability and irreversibility. Large model output is stochastic, so the trajectory of the same task may differ across runs. Terminal commands can produce irreversible side effects, and a single mistaken deletion or edit can damage the entire working environment. Evaluation must therefore guarantee both reproducibility and safety at the same time.

    2. Evaluation Infrastructure: Real Terminals and Resource Constraints

    2.1 Why Evaluation Must Happen in a Real Terminal

    Code reasoned out “in the head” and code verified “in the environment” are not equally reliable. A real terminal provides at least three kinds of value:

    • Execution feedback: Compilation errors, runtime errors, and test results are objective signals that are hard to fake, and they can drive the agent into a “hypothesize—verify—correct” loop.
    • Engineering constraints: Real constraints such as dependency management, environment variables, directory structure, and permission settings expose solutions that merely “look correct.”
    • Alignment with the developer workflow: Developers use the terminal to complete tasks, so when the agent being evaluated uses the same set of tools, the results carry genuine engineering reference value.

    2.2 Why Resource Constraints Cannot Be Omitted

    In an unconstrained environment, an agent can try and fail repeatedly and install any dependency until it passes a test by chance, and a high score may mask its true capability. Once CPU, memory, disk, per-step execution time, and overall runtime are bounded, the agent must make tradeoffs within a limited budget: read the code first or search first? A full build or an incremental compile? Install the complete dependency set or perform static analysis? This “decision-making under constraints” is precisely what makes long-horizon tasks relevant to production reality.

    2.3 Per-Task Isolated Verification and Anti-Cheating Design

    An ideal evaluation framework should build an isolated environment for each task with an identical initial state, and follow these principles:

    • Separate the goal from the verification: The agent can only see the requirement description and the code repository; the verification cases are injected only after the task ends, preventing “writing code to the tests.”
    • Protect the verification logic: Prohibit modifying or skipping tests, and prohibit hard-coding expected outputs to bypass checks.
    • Control external dependencies: Disable external network access by default, and pre-install dependencies into the image to avoid version drift and to prevent retrieving ready-made answers directly.
    • Record the full trajectory: Save each command, output, elapsed time, and resource usage for failure attribution and manual review.

    A representative configuration looks like this:

    1. sandbox:
    2. base_image: repo-dev-20250901 # Fixed image containing a pinned compiler, dependencies, and test tools
    3. resources:
    4. cpu: 2
    5. memory: "4Gi"
    6. disk: "10Gi"
    7. wall_clock: "900s" # Maximum wall-clock time per task
    8. tool_timeout: "60s" # Timeout for a single command
    9. network: none # External network disabled by default; dependencies come from local sources in the image
    10. filesystem:
    11. root: readonly
    12. workdir: /workspace # The only writable directory
    13. verifier:
    14. command: "./run_all_tests.sh"
    15. hidden_tests: true # Hidden tests are injected after the session ends
    16. allow_modify_tests: false # Disallow modifying tests
    17. allow_skip_tests: false # Disallow skipping tests

    3. Engineering Practices for Long-Horizon Agents: Making Every Step More Reliable

    The endpoint of evaluation is not a ranking but finding the engineering steps that can be improved. A typical long-horizon coding agent usually consists of five modules: planning, tool invocation, context governance, self-verification, and termination and convergence.

    3.1 Planning and Replanning

    Effective planning should have three characteristics: verifiable goals, traceable steps, and correctable failures. A task can be represented as a stateful task tree, where each node records its goal, current state, and dependencies, and updates its state upon completion—rather than generating a one-time linear checklist. The key lies in “replanning”: when a new test result contradicts the original hypothesis, the agent should revise its plan based on evidence instead of mechanically continuing.

    3.2 Tool Invocation and Observation Parsing

    The terminal is the most general-purpose tool, but raw output must be processed before it becomes a reliable observation:

    • Structured parsing: Focus on fields such as exit code, standard output, error output, and elapsed time, rather than dumping raw text to the model.
    • Output truncation: Keep the head error summary and the tail call stack while eliding the middle, so that logs do not drown out critical signals.
    • Timeouts and retries: Set timeouts and standardize retries for commands that may hang (such as interactive prompts or long-running tasks), preventing a single blocked step from draining the overall budget.
    1. def truncate_output(raw: str, head: int = 3000, tail: int = 1000,
    2. limit: int = 4000) -> str:
    3. if len(raw) <= limit:
    4. return raw
    5. return f"{raw[:head]}\n...[truncated]...\n{raw[-tail:]}"

    3.3 Context Governance: Layered Memory

    The context of a long-horizon agent can be divided into three layers by time scale:

    1. Working memory: The most recent several rounds of commands and outputs, kept in raw form;
    2. Episodic memory: Key completed operations and conclusions—for example, “confirmed that the defect stems from a cache key that does not include the user identifier”—stored as structured summaries;
    3. Semantic memory: Project conventions, module responsibilities, and common pitfalls, which can be written into a separate task-notes file or loaded on demand via retrieval.
    1. def compress_history(history, keep_recent: int = 8):
    2. recent = history[-keep_recent:] if len(history) > keep_recent else history
    3. older = history[:-keep_recent] if len(history) > keep_recent else []
    4. summary = older and summarize(older, keys=[
    5. "Goal", "Approaches tried", "Failure reasons",
    6. "Confirmed facts", "Unresolved issues"
    7. ]) or ""
    8. return summary, recent

    The core principle can be summarized as: keep raw detail for the recent past, and keep conclusions with links to evidence for the distant past.

    3.4 Self-Verification

    A long-horizon agent should treat verification as a default action rather than relying on extra prompting from the user. After each code change, it should automatically run a three-tier check: static analysis, unit tests, and regression tests. When tests fail, it should first minimize the reproduction path (bisection, constructing a minimal case) and then fix the root cause. Implicit constraints not explicitly stated in the task description can be discovered and honored by reading configuration files and test cases.

    3.5 Termination and Convergence

    An agent without a termination condition will fall into infinite loops or unproductive exploration. Common practices include:

    • Setting a maximum number of steps, maximum duration, and maximum number of tool calls;
    • Detecting repeated actions—for example, judging an invalid loop when the same command is executed multiple times in a row with identical output;
    • Distinguishing “solved” from “honestly reported”: when a task cannot be completed, the agent should output confirmed facts, root-cause hypotheses, and suggested approaches, rather than claiming success.
    1. function run_task(task, budget):
    2. plan = build_plan(task)
    3. seen = {} # action signature -> repeat count, used to detect dead loops
    4. while budget.remaining() and not done(plan):
    5. action = plan.next()
    6. signature = hash(action)
    7. if seen[signature] >= 3:
    8. return report(plan, reason="Repeated action, suspected unproductive loop")
    9. seen[signature] += 1
    10. result = sandbox.exec(action, timeout=budget.tool_timeout)
    11. budget.consume(result.duration)
    12. history.append(result.as_observation())
    13. if is_test_command(action) and result.passed:
    14. if verify_regression(plan):
    15. return report(plan, status="resolved")
    16. plan.replan(result.summary()) # Revise the plan based on the latest observation
    17. return report(plan, reason="Budget exhausted")

    4. Evaluation Metrics: From a Single Pass Rate to a Multi-Dimensional Profile

    Looking at a single pass rate alone makes it easy to overlook shortcomings in the capability structure. A more complete metric system usually consists of four layers:

    Layer Representative metrics Meaning
    Effectiveness End-to-end pass rate (pass@1, pass@k) Whether the task is actually completed
    Efficiency Average steps, average elapsed time, average token consumption, resource usage The cost of completing the task
    Quality Whether changes are minimal, whether regressions are introduced, static-check pass rate The engineering usability of the delivery
    Reliability Variance across runs, timeout rate, budget-exhaustion rate The stability of the results

    Statistical methodology matters just as much. Because large models are stochastic, a single run is not enough to draw conclusions; tasks should be run multiple times under identical conditions, reporting the mean and the range of variation. Comparisons across different models and different configurations (temperature, toolset, budget) are only meaningful when the methodology is consistent. The magnitude of improvement over a baseline often says more about capability change than the absolute score does.

    From an engineering perspective, evaluation should also attend to three points:

    1. Task stratification: Divide tasks into difficulty levels by the number of files involved, dependency depth, and number of steps required, to avoid “simple tasks dominating the overall score.”
    2. Guarding against data contamination: Prefer real tasks published after the model’s training cutoff date, reducing inflation caused by the model having seen the original problem.
    3. Continuous updates: As tools and environment versions change, periodically refresh the benchmark to keep the evaluation relevant to reality.

    5. Failure Attribution: More Valuable Than the Score

    Classifying failed trajectories often points directly to directions for improvement:

    Failure type Typical manifestation Observed signal Improvement direction
    Planning deviation Modified unrelated files, drifted away from the requirement Change scope does not match the goal Strengthen task decomposition and constraint identification
    Tool misuse Command syntax errors, missing arguments Frequent non-zero exit codes Provide tool descriptions, argument validation, and examples
    Context loss Forgot confirmed facts, repeated an erroneous approach The same failure recurs Introduce task notes and layered memory
    Insufficient verification Claimed completion without running tests No verification step in the trajectory Make self-verification the default flow
    Loop stagnation Repeatedly executing the same command Highly repetitive action sequences Add repetition detection and budget caps
    Lack of honesty Reported success while tests failed Output contradicts the trajectory Emit structured status distinguishing success, failure, and partial completion

    The value of attribution analysis is that it turns a vague judgment like “the model isn’t good enough” into actionable product and engineering improvements—for example, optimizing prompts, adding tools, adjusting the context strategy, or tightening the sandbox budget.

    6. From Evaluation to Deployment: How Enterprises Build Long-Horizon Coding Agents

    When enterprises adopt long-horizon coding agents, they usually need to build the following engineering capabilities beyond the evaluation system:

    1. Knowledge access: Through code retrieval and document indexing, let the agent quickly locate relevant modules and past decisions, reducing blind exploration.
    2. Security isolation: Use containers to isolate the execution environment, restrict network egress, redact keys and sensitive data, and require approval for high-risk commands.
    3. Observability: Use logging services to record each execution step in the trajectory, and combine monitoring and alerting to promptly detect timeouts, abnormal exits, and cost spikes.
    4. Cost governance: Set budget caps per task, use models in tiers, delegate simple routing and summary compression to lighter models, and reserve reasoning capability for key decisions.
    5. Human-machine collaboration: Results of long-horizon tasks should enter the code review process, with developers acting as gatekeepers before changes are merged into the main branch.

    To build this system in the cloud, you can combine general categories of cloud products, for example:

    • Container platforms: Host isolated sandboxes and elastic scaling;
    • Object storage: Store evaluation datasets, image artifacts, and run trajectories;
    • Message queues: Decouple task scheduling from result collection;
    • Logging services and monitoring/alerting: Ensure runtime observability.

    Mainstream cloud providers such as Baidu AI Cloud offer cloud products in all of the categories above, and enterprises can select them as needed.

    Conclusion

    The evaluation of long-horizon coding agents is, at its core, an attempt to answer one question under real constraints: can an agent, like an engineer, understand a goal, invoke tools, correct itself based on feedback, and make sensible tradeoffs when resources are limited? Real terminals and resource-constrained environments provide the proving ground closest to production; engineering methods such as layered memory, self-verification, and failure attribution determine whether capability can be released reliably; and multi-dimensional metrics with a consistent methodology make comparisons between different approaches meaningful. Turning evaluation into a continuously iterated engineering loop—rather than a one-time leaderboard—is the prerequisite for long-horizon agents to truly move into production.