Stability Practices for Long-Context AI Agent Tasks

    This article explains why the bottleneck in long-running agent tasks is not the context window size, but how the execution framework resumes after context compaction. It covers a state-layering approach that moves critical information into process files, three requirements for compaction recovery in the harness, context budgeting strategies, and a checklist of common pitfalls. Readers will learn how to keep long-horizon tasks stable across hundreds of thousands of tokens and multi-hour runs.

    1. Reframing the Problem: The Bottleneck Is Not Window Size

    Two misconceptions are common when discussing long-context capabilities. One assumes that a large enough window removes the need for any engineering effort. The other assumes that tasks inevitably fail once the window is exceeded. In engineering practice, the more accurate conclusion is that mainstream models typically show no noticeable degradation in instruction following or reasoning quality within a context range of roughly 100K to 200K tokens. What really determines the success or failure of a long-horizon task is whether the execution framework can resume seamlessly after context compaction is triggered.

    It is worth stressing that the very definition of a long-horizon task implies that compaction will happen. A task that runs for hours and consumes hundreds of millions of tokens in total, yet never triggers compaction, has not truly entered a long-horizon state. Setting the design goal as “avoiding compaction” is therefore the wrong direction. The correct goal is to make compaction a lossless state transition.

    2. Core Principle: Move State Out of the Context and Into Process Files

    Context is volatile, limited, and subject to trimming. The file system is persistent, addressable, and verifiable. The stability of long-horizon tasks comes from a simple principle: any information that is still required after compaction must not exist only in the conversation history.

    State should be explicitly layered:

    • Task definition layer: the goal, acceptance criteria, and inviolable constraints. Small in size, but must remain resident at all times.
    • Plan layer: the decomposed step list and a current progress pointer, used to answer “which step am I on”.
    • Evidence layer: retrieved material, API responses, and log fragments. The largest in volume, loaded on demand.
    • Decision layer: rejected options and the reasons for rejecting them, preventing the same mistakes from being repeated after compaction.
    • Artifact layer: final deliverables and intermediate versions, stored independently and versioned.

    In practice, a structured checklist file can carry the plan and progress, as illustrated below:

    1. {
    2. "goal": "Complete the data pipeline refactor and pass regression validation",
    3. "constraints": ["Do not change public interface signatures", "Keep each change under 300 lines"],
    4. "steps": [
    5. {"id": 1, "desc": "Map existing dependencies", "status": "done", "artifact": "/work/notes/deps.md"},
    6. {"id": 2, "desc": "Implement the new write path", "status": "running", "checkpoint": "/work/ckpt/2.json"},
    7. {"id": 3, "desc": "Regression and load testing", "status": "pending"}
    8. ],
    9. "rejected": [{"option": "Full rewrite", "why": "Regression cost is uncontrollable"}]
    10. }

    The key is to persist every state change immediately, rather than saving everything at the end of the task. The persistence frequency determines how much work can be lost at most when compaction occurs.

    3. Resuming After Compaction: Three Things the Harness Must Do

    The first is re-orientation after compaction. Once compaction completes, the execution framework should proactively re-read the plan file and the most recent checkpoint, and reconstruct a one-sentence statement of “goal, current step, next action”, instead of relying on the model’s vague memory of history.

    The second is idempotent design. Write operations, external calls, and file generation in long-horizon tasks may all be executed repeatedly due to retries. Generating a deterministic key for each step and checking whether it has already been completed before execution is the lowest-cost way to avoid duplicate side effects:

    1. def run_step(step_id: str, fn):
    2. key = f"done:{step_id}"
    3. if store.exists(key):
    4. return store.read(f"out:{step_id}")
    5. result = fn()
    6. store.write(f"out:{step_id}", result)
    7. store.write(key, "1") # write the artifact first, then the marker
    8. return result

    The third is checkpoint resume and timeout isolation. Split the task into segments that can be replayed independently, each with a clear input/output contract. Combined with logging services and monitoring alerts, failures can be located to a specific segment without rerunning everything. For runs spanning hours, also pay attention to the platform-side task duration quota: the quota limits the duration of a single session, not the cumulative scale of the task itself. Resuming across quotas should be treated as normal rather than exceptional.

    4. Context Budget: Treat the Window as a Cache, Not a Warehouse

    Even with a window capacity of hundreds of thousands of tokens, context should be managed proactively. Viable strategies include: retrieving evidence on demand rather than injecting everything; keeping only a summary and an addressing path for large artifacts; applying rolling trimming to historical tool outputs; and injecting a fixed-length “task constitution” (goal and constraints) at the start of each round, ensuring a stable anchor remains after compaction.

    A practical rule of thumb: if a piece of information has not been referenced in the last three rounds of reasoning, it can most likely be moved out of the context and carried by files instead.

    5. Common Pitfalls

    • Storing only the final artifacts and not the process state, making progress impossible to determine after compaction.
    • The plan file falling out of sync with actual execution, resulting in steps “marked done but not actually done”.
    • Writing checkpoints in the wrong order, writing the completion marker first and losing the artifact.
    • Ignoring external side effects, so retries cause duplicate writes or duplicate orders.
    • Cramming a long task into a single session to tough out the duration quota, instead of designing for resume.
    • Not persisting decision rationale, leading to conclusions being repeatedly overturned after compaction.

    6. Conclusion

    The value of long context lies not in “holding more”, but in pairing with reliable external state management so that compaction becomes a cheap and verifiable transition. With process-file writes as the backbone, plus idempotency, checkpoints, and resume validation, long-horizon tasks can run stably for dozens of hours within a window of hundreds of thousands of tokens. If stronger support is needed on the enterprise side, general cloud capabilities such as object storage, message queues, container platforms, and log monitoring can be combined to build an observable and recoverable execution foundation.