Stability Practices for Long-Context AI Agent Tasks
This article addresses a common misconception in long-context AI agents: a large context window alone does not guarantee that long-running tasks will complete reliably. It explains why context compaction is inevitable, lists common failure patterns, and presents a practical framework for building resumable long-horizon execution. Key topics include process files for persistence, a state.json recovery schema, harness compaction-and-continue loops, idempotency, validation, and rollback checkpoints. The article also offers context budgeting tips and notes how general cloud capabilities can improve reliability. It is intended for engineers building AI coding agents that must run for hours across many tool calls.
1. The Problem: Long Context Is Not Just About “Fitting It In”
A common misconception in discussions of long-context capabilities is treating “a big enough window” as a sufficient condition for completing long-horizon tasks. Engineering experience suggests the opposite: window capacity only determines how much information a single inference pass can carry. Whether a task progresses reliably depends on whether information is durably persisted outside the window, and whether the execution chain can resume without loss after compaction occurs.
This article therefore frames the topic as a general technical problem: how to build a recoverable long-horizon execution framework for AI coding tools with limited context windows. Here, “long-horizon tasks” refers to engineering tasks that require multiple iterations, span many tool calls, and run for hours—for example, large-scale codebase refactoring, batch data cleaning and validation, and long-chain automated test repair.
2. Key Conclusions Up Front
- For long-horizon tasks, context compaction is not an exception but an inevitable event. If a task runs long enough, compaction will eventually trigger. Treating compaction as an error is the primary cause of long-horizon task failure.
- What really determines success or failure is whether the harness (the execution framework) can correctly continue after compaction triggers—not the nominal window capacity.
- Writing process files is the foundation of stability: all intermediate conclusions, decision rationale, pending work, and rollback points must be persisted to durable storage outside the window.
- Within the mid-sized context range commonly available in the industry (roughly on the order of 100,000 to 200,000 tokens), models typically do not show noticeable capability degradation. Focusing on process orchestration yields far greater returns than repeatedly switching models.
3. Why Compaction Is Inevitable
Context growth in long-horizon tasks is roughly linear or even super-linear: each round of tool calls appends instructions, outputs, logs, and error stacks; a single directory traversal can bring in tens of thousands of tokens. Let the average consumption per round be c and the task run for n rounds; cumulative consumption grows to roughly n×c, increasing independently of window capacity W.
Cumulative context ≈ Σ(system prompt + conversation history + tool output + retrieved snippets)When cumulative context > W × threshold (e.g., 0.8), compaction triggers
The conclusion is straightforward: as long as n is large enough, compaction is only a matter of time. The mature approach is not to avoid compaction, but to design it as a “state solidification and handoff” step within the workflow.
4. Common Pitfalls
- Pitfall 1: Keeping state only in the conversation. After compaction, conversation history is replaced by a summary, and conclusions that were not persisted are lost. The task starts repeating work or even contradicting itself.
- Pitfall 2: No recovery entry point after compaction. The summary lacks a structured field for “what to do next,” so the model can only feel its way forward again.
- Pitfall 3: Long outputs are not persisted. Large generated results exist only in the context and get truncated during compaction, producing half-finished files.
- Pitfall 4: Missing idempotency and validation. Re-runs repeatedly append content or repeatedly create tables, producing dirty data.
- Pitfall 5: Misjudging rate-limit windows as capability problems. When a task has already started before a rate-limit boundary, mid-run errors are often quota or concurrency limits rather than insufficient context, and should be handled with backoff retries and task segmentation.
- Pitfall 6: No rollback points. After an error, there is no way to return to the last stable state, so the whole task must start over.
5. Process File Design: The Foundation of Stability
It is recommended to create a dedicated working directory for each task and place everything needed for recovery inside it:
/task/{task_id}/state.json # Task state machine: stage, progress, next stepplan.md # Goals, constraints, acceptance criteriadecisions.md # Key decisions and rationale (a "memory proxy" after compaction)artifacts/ # Intermediate and final artifactslogs/ # Sharded logs, rolled over by sequence numbercheckpoints/ # Periodic snapshots for rollback
state.json should explicitly include the fields needed for recovery:
{"task_id": "refactor-001","stage": "apply_patch","completed_units": [1, 2, 3],"pending_units": [4, 5, 6],"next_action": "Apply the replacement to module D and run the unit tests","checksum": "sha256:...","updated_at": "2026-01-01T00:00:00Z"}
The key point is: next_action must be a single-step instruction executable in natural language, so that even if history is compressed into a summary, the model can precisely resume from state.json.
6. The Harness Compaction-and-Continue Mechanism
A reliable execution loop can be abstracted as:
def run_long_task(task_id, step_fn, max_steps=10000):ctx = load_state(task_id) # Restore from disk, not from conversation historyfor i in range(max_steps):if ctx.needs_compaction(): # Triggered by the framework or a thresholdctx = compact_and_continue(ctx) # Summarize + persist + rebuild promptresult = step_fn(ctx) # Single-step execution with idempotent side effectspersist(ctx, result) # Key: persist first, then continueif ctx.is_done():return ctx.summary()raise RuntimeError("step budget exhausted")
The responsibility of compact_and_continue is to compress the current conversation into a structured summary, merge the summary with state.json and decisions.md into a new system prompt, and then continue execution within the same loop—rather than throwing compaction as an error. This makes compaction transparent to the upper-level task.
7. Idempotency, Validation, and Rollback
- Idempotent writes: Name artifacts by
unit_id; repeated executions overwrite rather than append; for database-type operations, use “skip if exists.” - Staged validation: At the end of each stage, compute a checksum and write it to checkpoints; on recovery, validate before resuming.
- Rolling logs: Shard logs by size to avoid a single oversized file that would overflow the window again when read.
- Rollback strategy: Keep the most recent k checkpoints, and on failure roll back to the last stable point rather than starting from scratch.
8. Practical Advice on Context Budgeting
- Truncate and summarize single-round tool output; write only the conclusion into decisions.md, and keep the raw content in artifacts.
- Pull retrieval-type information on demand, avoiding stuffing large blocks of material into the window all at once.
- Within the mid-sized context range common in the industry, model behavior is typically stable; if anomalies appear, prioritize investigating process defects, dirty state, and quota limits rather than first attributing them to “not enough context.”
9. Leveraging General Cloud Capabilities
If a task runs in a cloud environment, general-purpose capabilities can enhance reliability: use object storage to hold checkpoints and artifacts, use a message queue for task segmentation and peak shaving, and use a container platform to host re-entrant workloads.
