Long-Running Agents: From Loop-Driven Execution to a Handoff-Ready Framework
This article examines why long-running AI agents fail not from stopping too soon but from drifting while they keep running. It shows how naive loop-driven execution solves continuity but not correctness, catalogs three compounding forms of drift (goal, context, and quality), and presents a practical framework: a front-loaded Spec, external state files that serve as handoff evidence, layered context engineering, contract-based sub-agents, and a tiered verification and audit chain. It also offers guidance on when multi-agent setups are worth their cost and a four-step rollout path. Readers will learn how to make long-horizon agent output verifiable, auditable, and easy for the next agent or engineer to take over.
1. Redefining the Problem: The Real Tension in Long-Running Agents
An agent runs for hours, crosses multiple context windows, and delegates subtasks to several sub-agents along the way. The core question for long-horizon tasks is whether the final system can be verified, audited, and taken over by someone else.
In the past, the worry was “giving up halfway”: the work is not done, the agent stops, a human says “continue,” and it has to warm up again and re-derive all its earlier judgments. But the failure that actually hurts is a different one: the agent keeps running, keeps working hard, and eventually delivers something that looks polished on the surface but has drifted off course.
The longer it runs, the higher the cost of diligent drift. If you cannot take over the scene, risk compounds over time.
2. Loop-Driven Mode: Solves Continuity, Not Correctness
The common industry approach is to give the agent a persistent goal so it does not have to stop every few minutes and ask “should I keep going?” This “persistent goal + automatic continuation” loop-driven mode has clear engineering value:
- It eliminates idle spinning and repeated warm-up caused by manual confirmation;
- It keeps long tasks moving during unattended hours;
- It hands more of the “what to do next” decision to the model itself.
But it covers only one dimension: can it keep going? It does not answer: is each round’s judgment still aligned with the original goal? Are key constraints lost after context compression? Can the output be independently verified? Mistaking continuity for correctness is the most common cognitive bias in long-horizon projects.
3. Three Kinds of Drift: The Compounding Degradation of Naive Loops
The problem with a naive loop is not the number of iterations but the fact that each round quietly accumulates three kinds of drift.
Goal drift. Each round, to make the task “look like it is making progress,” the model tends to pick the easiest sub-goal to execute, and the original constraints get diluted through repeated restatement. After ten rounds, the agent is optimizing a metric the user no longer cares about.
Context drift. Context windows are finite, and compression and summarization are inherently lossy. Architectural decisions, prohibited items, and boundary conditions set early on are reduced to a vague impression after several compressions, or are even overwritten by later inferences.
Quality drift. Without an external standard as an anchor, the definition of “done” is supplied by the model itself. It validates its own output through self-confirmation: it writes, it reads, it passes itself.
The combined effect is compounding: a small goal deviation leads to a small context-selection deviation, which leads to a small acceptance-criteria deviation, and the next round continues from an even more deviated position. Illustrated:
state at round n = previous state + this round's increment + this round's driftdrift never enters the rollback path -> monotonic accumulation -> drifts further the longer it runs
Conclusion: what long-running agents need is not stronger looping, but external anchors that can cut the drift path.
4. Front-Loaded Spec: Cutting Off Wrong Branches Early
The value of a front-loaded Spec is to cut off wrong decision branches before they happen, so later tokens do not keep running further down the wrong path. It is not an extended requirements document; it is a judgment baseline that both machines and humans can read.
A usable Spec contains at least four parts:
- Goal and success criteria: measurable acceptance conditions, not “implement some feature.”
- Hard constraints and prohibitions: tech-stack boundaries, interfaces that must not change, and performance and security red lines.
- Decision log: choices made at resolved branches, with reasons, to prevent repeated discussion or retroactive reversal.
- Unknowns list: open questions listed explicitly, with a prohibition on the model treating its own “reasonable assumptions” as established fact.
## Success Criteria- Core path end-to-end test pass rate: 100%- Key interfaces under load test: P99 latency within the agreed threshold## Hard Constraints- Do not introduce new persistence components- External interface signatures are frozen; changes require human confirmation## Decisions Made- Adopt a single-write, multi-read data access model (rationale: consistency first)## Unknowns (do not assume)- Data retention period
5. External State Files: Handoff Evidence for “the Next Owner”
External state files are more reliable than chat logs. Chat logs are process noise; state files are handoff evidence. A minimal viable skeleton uses four files:
GOAL.md: goals and acceptance criteria, read-only throughout, changes require human confirmation;PLAN.md: task breakdown, dependencies, and current stage;STANDARDS.md: coding conventions, testing requirements, and directory and naming conventions;PROGRESS.md: completed items, unfinished items, abandoned approaches and reasons, and current blockers.
Key engineering details:
- Write timing: persist each verifiable unit as soon as it completes, not at the end of the task;
- Atomicity: write to a temp file, then rename, to avoid half-written files on interruption;
- Append-only:
PROGRESS.mdis append-only and never rewritten, preserving the evolution of decisions; - Brevity first: keep each file readable in a single pass; if it grows too long, archive by stage, and keep archived files in the version control repository.
Directory layout:
project/GOAL.mdPLAN.mdSTANDARDS.mdPROGRESS.mdstate/ # machine-readable breakpoints and checkpointslogs/ # run and verification logs, shippable to a logging service
6. Context Engineering: Compression, Retrieval, Re-Injection
Long-running operation inevitably compresses context repeatedly. A workable strategy is “layered memory”: the resident layer holds only the Spec and hard constraints; the working layer holds the relevant fragments of the current subtask; the archive layer holds historical detail, retrieved and re-injected on demand. When compressing, prioritize keeping constraints, criteria, and open questions, and discard process chatter. The test is simple: after compression, replay the round—can the agent still arrive at the same next step?
7. Sub-Agents: The First-Order Value of Independent Context Is Not Role-Play
The first-order value of a sub-agent is not playing a role; it is providing independent context, which serves three kinds of work:
- Implementation: split a large task into non-interfering units that proceed in parallel;
- Exploration: research approaches, read code, and evaluate trade-offs without polluting the main context;
- Review: have a context that did not participate in implementation find faults, reducing self-confirmation.
The return path must follow a contract: a structured summary + change list + verification results + open questions, rather than dumping the entire process back into the main context. The main context keeps only what is needed for decisions, which also mitigates context drift.
8. Verifiability and Auditing: A Layered Verification Chain Before Delivery
Long-horizon output must be independently verifiable. A four-tier ladder is recommended; failure at any tier blocks the pipeline and writes back to PROGRESS.md:
- Static checks and convention validation (format, types, dependency boundaries);
- Unit and integration tests;
- End-to-end scenario validation covering the Spec’s success criteria;
- Human spot-check review of high-risk changes.
The audit side requires “three-ables”: traceable (every state change is recorded), replayable (inputs, versions, and configuration can be restored), and observable (run and verification logs are shipped to a logging service, key metrics feed monitoring and alerting, and large objects and archives live in object storage). These are all categories of general cloud capability; choose based on the team’s existing infrastructure.
9. Cost Judgment: Multi-Agent Is a Quality-Governance Tool, Not a Default
Multi-agent is not cheap: repeated context, result aggregation, and conflict merging all add overhead. It is better treated as a quality-governance tool and is worth it only when:
- The task can be split cleanly and subtask coupling is low;
- The payoff is high enough (parallelism meaningfully shortens the cycle, or review meaningfully reduces rework);
- The verification chain is clear (output can be judged automatically rather than relying on subjective evaluation).
When those do not hold, a single agent + a strong Spec + state files is often the more stable choice.
10. Rollout Path
- Add the Spec and the four state files first, leave the loop mechanism unchanged, and observe whether drift decreases;
- Wire in layered verification and log retention so “done” has an objective definition;
- Introduce read-only review sub-agents and validate the benefit of independent context;
- Only then consider parallel implementation sub-agents and more complex orchestration.
Core judgment: the next hurdle for long-running agents is not whether they can finish, but whether the scene they leave behind is clear enough after they do. Whether the next model, the next agent, or the next person can pick up directly and keep going—that is the real threshold for long-horizon engineering.
