Skip to main content
Jeremy Cleland.
WorkAboutResumeWritingLearnContact
Jeremy Cleland.

Director - Senior Software Engineer
Gray Matter Resources
Michigan, USA.

WorkAboutResumeContactWritingLearn
jeremy@clelandco.comGitHubLinkedIn© 2026 Jeremy Cleland
  1. Home
  2. Writing
  3. Context Engineering for Long-Running AI Agents
Artificial IntelligencePublished November 12, 2026 · 5 min read

Context Engineering for Long-Running AI Agents

A worked context budget shows what to retain, remove, and recover when an agent compacts history: durable decisions, failed attempts, versioned evidence, and a testable continuation.

By Jeremy ClelandPublished November 12, 2026
  • Context Engineering
  • Agentic AI
  • Long-Running Agents
  • Context Rot
  • Compaction
  • Agent Memory
  • Sub-Agents
  • Prompt Caching
  • Tool Design
  • Agent Reliability
Context Engineering for Long-Running AI AgentsContext Engineering for Long-Running AI Agents
Conceptual illustration: a fixed rectangular working frame holding a few ordered blocks, with a large cabinet of indexed drawers outside it and a single block being carried in.

On this page

    Long-running agents need more than a large context window. They need a deliberate choice about which instructions, observations, decisions, and unresolved failures are available at each step.

    Context engineering is the work of assembling that view from a larger durable record. A useful system keeps enough information to continue correctly, makes omitted evidence recoverable, and distinguishes a remembered observation from a current one.

    Capacity and useful context are different properties

    Lost in the Middle showed that relevant information's position affected performance on the retrieval and question-answering tasks studied. Its older models do not establish a universal curve for current agents. The result does establish that fitting information into a window and using it reliably are different capabilities.

    Chroma's Context Rot report evaluates a later collection of models on controlled tasks and reports inconsistent performance as input length grows. LOCA-bench tests agents while scaling environment state. These are reasons to evaluate a system under realistic context growth, not proof that every extra token harms every task.

    Cutting history arbitrarily can also discard the information needed to succeed. The goal is neither the largest possible prompt nor the smallest possible prompt. It is a prompt that preserves the current decision's dependencies.

    A concrete 32,000-token budget

    Consider an illustrative incident-investigation agent with a 32,000-token window and 4,000 tokens reserved for output. The figures below are planning allocations, not tokenizer measurements or a reported performance experiment.

    Input categoryBefore compactionAfter compaction
    Instructions2,0002,000
    Current task1,0001,000
    Conversation history18,000Replaced by checkpoint and recent turns
    Tool results7,000Replaced by selected evidence and references
    Durable checkpoint—2,000
    Recent turns—3,000
    Selected evidence—3,000
    Total input28,00011,000
    Unallocated capacity after output reserve017,000

    The arithmetic can be reproduced with the standalone context-budget example. Save it and run node context-budget.mjs. It uses only Node's standard library and asserts the totals and checkpoint invariants. It does not call a model or demonstrate that compaction improves accuracy.

    In a real integration, measure the serialized request with the provider's supported tokenizer or counting interface. Include system instructions, tool definitions, message framing, images, and any provider-specific overhead. A word-count estimate is not a hard limit.

    Write the checkpoint before discarding history

    The example preserves six things:

    {
      "goal": "Diagnose a synthetic incident; propose only, do not execute.",
      "decisions": ["No write authorization; preserve missing evidence as missing."],
      "state": { "revision": 7, "status": "investigating" },
      "failedAttempts": [
        { "operation": "metrics query", "outcome": "timeout; not evidence of health" }
      ],
      "references": [{ "id": "log-17", "artifact": "artifacts/logs.json", "observedRevision": 6 }],
      "next": "Refresh metrics and logs at revision 7 before proposing an action."
    }
    

    The goal preserves the boundary between proposing and executing. The decision records a constraint and its meaning. The state identifies the current revision. The failed attempt prevents a later session from interpreting a timeout as a healthy service. The reference makes discarded logs recoverable while showing that they are stale. The next action names the evidence that must be refreshed.

    Raw repeated logs, redundant explanations, and superseded plans can leave the working prompt once the durable record preserves the relevant facts and references. Keep original artifacts when a later step may need to inspect their exact contents. A summary should not be the only surviving copy of evidence.

    A durable notebook is preserved separately while a long conversation is compressed.
    Conceptual illustration: preserve goals, decisions, current state, failures, and next steps before compacting conversation history.

    Recover evidence instead of trusting the summary

    After compaction, the agent should read the checkpoint, confirm the task and authorization, inspect current state, and retrieve only the evidence required for its next decision. The checkpoint's revision-6 log is a lead, not proof about revision 7.

    References need their own contract: an identifier, location, source version or hash, observation time, and access boundary. A URL alone may return different content tomorrow. A file path alone may point to an edited file. If exact historical evidence matters, retain an immutable snapshot or a versioned artifact.

    Recovery must also preserve uncertainty. A summary that changes “metrics unavailable” into “no metric anomaly” has invented evidence. A checkpoint that omits a denied action can invite a repeated request. Test these losses with cases where the omitted detail changes the correct next step.

    Retrieval earns its complexity when the corpus is larger than the task

    Anthropic's context-engineering guidance recommends lightweight identifiers and just-in-time retrieval. MemGPT develops the broader idea of moving information between working context and external storage. These are useful design patterns, not guarantees that agent-selected retrieval beats a fixed packet.

    When all relevant evidence is small and known, supplying it directly may be simpler. The synthetic comparison in how I evaluate production AI agents is a concrete counterexample to assuming agency helps. Its full benchmark and limitations belong there.

    For a large corpus, bound search results, preserve source references, and provide a way to request details. Truncation should be explicit. An agent should be able to distinguish “nothing matched” from “the response was cut off.”

    Isolate investigation without fragmenting ownership

    Separate investigators can search different sources and return findings with evidence references. That can keep irrelevant exploration out of a coordinator's context. It also creates communication costs: missing assumptions, conflicting decisions, and findings whose provenance is hard to recover.

    Use isolation where work is independent. Keep consequential decisions and artifact ownership explicit. A concise handoff should include the conclusion, evidence, uncertainty, failed approaches, and dependencies. A short answer that drops the reason for a decision can be more damaging than a longer one.

    The workflow-level version of that problem is covered in cutting the coordination tax. More agents do not remove dependencies between tasks.

    Evaluate what survives compaction

    Build a small continuation suite. Stop runs at a checkpoint and ask the resumed system to continue on cases involving a stale observation, an unresolved failure, a denied action, conflicting evidence, and a changed goal. Compare decisions and outcomes against the uncompressed record.

    Measure recovered facts, unsupported assertions, repeated failed work, retrieval calls, token use, and final task success. Keep compaction cost and latency in the accounting. A smaller prompt is useful only if the continuation remains correct enough for the task.

    Prompt caching adds another tradeoff: editing an early prefix can reduce cache reuse. Keep stable instructions and tool definitions stable where the provider's caching contract permits it, and measure total cost rather than optimizing cache hits alone. A cheap cached prompt carrying obsolete instructions is still wrong.

    The durable record is the source of continuity. The prompt is a selected working view of it, and every selection should preserve enough evidence to make the next decision defensible.

    Previous PostDoD Directive 3000.09 Explained: What the Autonomous Weapons Policy Actually Says
    Next PostApproval Fatigue: An Approve Button Is Not AI Agent Oversight
    With focus in the article, press J for previous post or K for next post

    Share this article

    Post Share

    Related writing.

    • Artificial Intelligence

      Approval Fatigue: An Approve Button Is Not AI Agent Oversight

      An approve button in front of an AI agent is not oversight on its own. Approval fatigue turns it into a rubber stamp unless the action is bounded, the reviewer sees the evidence and blast radius, and the result is verified afterwards.

      Jeremy Cleland
    • Artificial Intelligence

      MCP Tool Poisoning Is a Supply-Chain Problem, Not a Prompt Problem

      Tool descriptions and tool results are untrusted input that a model reads as instructions. MCP tool poisoning is defended with supply-chain controls and least privilege, not with better prompt wording.

      Jeremy Cleland
    • Artificial Intelligence

      OpenTelemetry GenAI: A Reproducible Agent Trace

      Build and inspect a synthetic agent-style trace with pinned OpenTelemetry versions, a failed tool span, parentage assertions, and a content-free export policy.

      Jeremy Cleland
    View all articles

    Let’s connect

    Useful AI starts with
    a real problem.

    Based in Michigan. Connect about agentic AI, software engineering, and the people using what we build.

    Get in touch