AI Agent Engineering for Long-Horizon Tasks: From Answering Questions to Delivering Results

    This article explores the engineering practices behind AI agents designed for long-running tasks. It covers the shift from single-turn chat to execution engines, the three-layer architecture of orchestration, sandbox runtime, and memory, and the core constraints of long-horizon coding such as specifications, small commits, test-based verification, and failure budgets. It also details multi-agent topologies, coordination and conflict handling, hosting and supervision for autonomous runs, cost modeling under open-weight and managed dual tracks, capacity and stability under launch traffic spikes, evaluation and selection beyond public benchmarks, and a staged adoption roadmap.

    1. Paradigm Shift: From Answering Questions to Delivering Results

    Over the past two years, the dominant form of large models in the application layer has been the “information container”: users ask questions, the model answers, and the interaction ends within a single turn or a few turns. In long-horizon task scenarios, this form quickly exposes three structural weaknesses. First, the context window is limited, so information compression and detail loss become inevitable as tasks grow longer. Second, there is no persistent state, so an interrupted process starts from scratch. Third, there is no execution feedback loop, so the model cannot perceive the real result of its previous action.

    An “execution engine” puts the model into a continuously running, tool-calling, observable, and rollback-capable execution environment, and lets it advance the task on its own until acceptance criteria are met. In engineering practice, it is usually split into three layers:

    1. ┌─────────────────────────────────────┐
    2. │ Orchestration Layer │ Task decomposition / scheduling / retries / budget
    3. ├─────────────────────────────────────┤
    4. │ Sandbox Runtime (Execution Layer) │ Code execution / file system / network egress
    5. ├─────────────────────────────────────┤
    6. │ Memory & State Layer │ Short-term context / long-term vector store / checkpoints
    7. └─────────────────────────────────────┘

    Decoupling the three layers is the prerequisite for all subsequent stability design: the orchestration layer should not care how code runs, and the execution layer should not care why the task was decomposed this way.

    2. Capability One: Engineering Constraints for Long-Horizon Coding

    Phrases like “coding continuously for more than ten hours” do not mean the model generates without interruption. In engineering terms, it means that once task durations are extended, the system must solve the drift problem. Four points matter in practice:

    1. Specification first. Turn requirements into machine-readable specification files (interface definitions, data models, acceptance cases) so the model can re-read the original constraints at every step instead of relying on conversational memory.
    2. Small commits. Commit an increment as soon as it compiles and passes tests, forming a traceable change chain. This is both a rollback mechanism and an “external memory” during context compression.
    3. Tests as the judge. Give acceptance authority to tests and static checks rather than model self-assessment. Self-assessment confidence decays as step count grows in long-horizon tasks.
    4. Failure budget. Set a maximum step count, maximum token consumption, and maximum wall-clock time per task. When exceeded, abort and produce a diagnostic report to avoid infinite loops that burn money.

    A minimal loop skeleton:

    1. for step in range(MAX_STEPS):
    2. ctx = memory.build(goal, spec, recent_events, repo_state)
    3. action = model.plan(ctx) # structured output: tool name + arguments
    4. result = runtime.invoke(action) # executed inside the sandbox
    5. memory.append(action, result)
    6. if verifier.passed(result):
    7. return commit(result)
    8. if budget.exhausted():
    9. return diagnose(memory)

    3. Capability Two: Multi-Agent Clusters and Collaboration Topologies

    When the number of sub-agents scales from single digits to hundreds, the bottleneck is no longer model capability but coordination overhead and conflict probability. Actionable design principles:

    • Topology selection: The fan-out topology (the main agent splits work, sub-agents execute independently, the main agent merges results) suits parallel retrieval and batch modifications; the pipeline topology suits build and release with strict sequential dependencies; the hierarchical topology suits domain-based governance of very large tasks. Choosing the wrong topology makes communication volume grow quadratically.
    • Write conflicts on shared state: When all sub-agents write to the same codebase, introduce leases or partition by directory; otherwise merge conflicts will swallow the gains from parallelism.
    • Heterogeneous role division: Splitting “planner, executor, reviewer, retriever” into roles with different prompts and different permissions is more stable than letting one role do everything, and makes least-privilege enforcement easier.
    • Consensus and arbitration: When results conflict, apply the order “majority vote + authoritative judge + verifiable signals first”. Verifiable signals (compilation passes, tests pass) always outweigh persuasion at the language level.

    4. Capability Three: Hosting and Supervision for Autonomous Runs

    Running an agent autonomously for several days is essentially a high-availability system problem, not a model problem:

    • State persistence: Write checkpoints to external storage so processes can be replaced at any time; separate context from execution state and rebuild from checkpoints after restart.
    • Idempotency and deduplication: All operations with external side effects (writing files, sending messages, changing configurations) must carry an idempotency key to prevent duplicate execution from retries.
    • Sandbox and least privilege: Run code in isolated containers, restrict network egress to a whitelist, and issue credentials on demand for short durations. This is the security baseline for allowing autonomous operation.
    • Observability: Structured logs, metrics, and distributed tracing. Focus on step-count distribution, tool failure rate, per-task cost, and human takeover rate.
    • Human gates: Force human confirmation for high-risk actions (deleting data, external release, anything involving funds) and auto-approve the rest.

    5. Commercialization and Cost: Dual-Track Logic Under Open Weights

    Open weights alongside managed services is a common commercial structure at this stage: open weights lower the adoption barrier and accelerate ecosystem growth, while managed and on-premises deployment serve enterprise customers with compliance, scale, and stability requirements. For users, the key is to build a cost model rather than look only at unit price:

    1. Cost per task ≈ steps × (input tokens × input price + output tokens × output price)
    2. + sandbox runtime × resource price
    3. + human takeover rate × labor cost

    In long-horizon tasks, accumulated input history often becomes the main cost item, so context trimming, summary compression, and retrieval instead of full injection are the first lever for cost reduction; caching reuse and batching come next. When pricing structures change, move budget control, quota alerts, and degradation strategies into the architecture up front rather than patching them afterward.

    6. Capacity and Stability: Treat Launch as a Load Test

    Opening a new version for trial often brings an instant traffic spike, so the engineering side should design for “ten times beyond expectations” by default: rate limiting and queuing at the entry point, per-tenant quota isolation, degradation switches on core paths, asynchronous non-critical paths, and monitoring-driven auto-scaling. Load tests must cover long-connection and long-task scenarios, because long tasks occupy sessions and sandbox resources for extended periods and are easily missed by conventional load-test models. General-purpose capabilities such as the container platform, message queue, object storage, log service, and monitoring and alerting offered by Baidu AI Cloud can be assembled into this elastic and observable foundation.

    7. Evaluation and Selection: Don’t Look Only at Leaderboards

    Public benchmarks are suitable for coarse screening, but long-horizon capability must be validated with a self-built evaluation set covering four sample types: cross-file refactoring, troubleshooting with unclear dependencies, builds that require external toolchain collaboration, and batch processing that needs long-term supervision. Beyond success rate, record average steps, human takeover rate, cost per task, and the distribution of failure modes. Selection conclusions should be written as reproducible reports, not one-off impressions.

    8. Adoption Roadmap

    1. Start with a read-only assistant to validate the reliability of retrieval and tool calls;
    2. Then open write permissions inside the sandbox and get the “specification–execution–test–commit” loop working;
    3. Introduce multi-agent parallelism, starting with two or three roles and scaling up gradually;
    4. Finally open long-duration hosting, with supervision, gates, and cost budgets in place.

    Following this order, teams gain measurable benefits at each stage while keeping risk within a rollback-able range. This is the fundamental difference between an “execution engine” and a “demo script”.