Long-Running Agents Need Context Budgets, Not Just Bigger Windows
Long context windows delay the problem; they do not remove it. A practical compaction design that separates pinned facts, durable state, summaries, and a recent message tail while preserving what an agent actually needs.
On this page
A long context window can make an agent feel durable right up until the history becomes expensive, repetitive, and difficult to reason about.
The failure is rarely a clean “context limit exceeded” error. More often the system gets slower first. Prompt cost grows every turn. Old tool results keep competing with newer state. The model starts paying attention to details that mattered forty steps ago and missing the one constraint that still matters now.
That is why I do not treat context compaction as an emergency operation triggered only when the prompt is nearly full. I treat it as ordinary state management.
The example here is a coding agent working on a multi-step refactor. It may inspect files, run tests, edit code, read compiler errors, and repeat that cycle for an hour. The useful state after twenty steps is not a verbatim transcript of everything that happened.
What the next model call needs is a compact working set:
- the user's current goal;
- constraints that must not be lost;
- durable decisions already made;
- a concise summary of older progress;
- a short tail of recent messages and tool observations;
- references to larger artifacts that can be fetched again if needed.
That is a different data structure from a chat log.
Separate conversation history from working state
The first design choice is to stop storing every important fact only inside messages.
I like to model the run explicitly:
type PinnedFact = { key: string; value: string; sourceId: string;};type RunState = { runId: string; goal: string; pinnedFacts: PinnedFact[]; decisions: string[]; summary: string; recentEvents: AgentEvent[]; summaryVersion: number;};type AgentEvent = { id: string; role: "user" | "assistant" | "tool"; content: string; createdAt: string;};The user's goal and pinned facts do not need to be rediscovered from a summary every turn. They are first-class state.
That matters because summaries are lossy by design. A summary can compress “use Node 22, do not change the public API, and preserve the current database schema” into “modernize the service carefully” if those constraints are not protected separately.
Python expresses the same separation:
from dataclasses import dataclass, field@dataclass(frozen=True)class PinnedFact: key: str value: str source_id: str@dataclass(frozen=True)class AgentEvent: id: str role: str content: str created_at: str@dataclassclass RunState: run_id: str goal: str pinned_facts: list[PinnedFact] = field(default_factory=list) decisions: list[str] = field(default_factory=list) summary: str = "" recent_events: list[AgentEvent] = field(default_factory=list) summary_version: int = 0This looks more like workflow state than chat history because that is what a long-running agent actually has.
Build a prompt from layers with different retention rules
I do not compact every section equally.
A useful prompt builder has layers:
- system and policy instructions — stable and never summarized by the agent;
- current goal — pinned;
- critical constraints and decisions — pinned or structured;
- older-run summary — compactable;
- recent event tail — verbatim within a budget;
- current tool/resource material — fetched on demand.
type PromptSections = { system: string; goal: string; facts: string; decisions: string; summary: string; recent: string;};function buildPromptSections(state: RunState): PromptSections { return { system: SYSTEM_PROMPT, goal: state.goal, facts: state.pinnedFacts .map((fact) => `${fact.key}: ${fact.value}`) .join("\n"), decisions: state.decisions.map((item) => `- ${item}`).join("\n"), summary: state.summary, recent: state.recentEvents .map((event) => `[${event.role}] ${event.content}`) .join("\n"), };}A single token limit can then be distributed intentionally instead of letting whichever section grew fastest take everything.
Use budgets per section, not one global panic threshold
Suppose a model supports a large input window. I still do not want to use all of it.
The request also needs room for the model's output, tool definitions, retrieved context, and provider overhead. More importantly, cost and attention quality matter before the hard limit.
I therefore define a *working input budget* below the provider maximum.
type ContextBudget = { totalInputTokens: number; reservedOutputTokens: number; recentEventTokens: number; summaryTokens: number; retrievedMaterialTokens: number;};const budget: ContextBudget = { totalInputTokens: 48_000, reservedOutputTokens: 6_000, recentEventTokens: 10_000, summaryTokens: 4_000, retrievedMaterialTokens: 16_000,};These numbers are examples, not recommendations. The right budget depends on model, workload, latency, and cost.
What matters is that a recent tool dump cannot silently consume the space intended for user constraints or the output.
Compact when the recent tail crosses its own budget
Compaction should be triggered by the part of state that actually grew.
interface TokenCounter { count(text: string): number;}interface Summarizer { summarize(input: { previousSummary: string; events: AgentEvent[]; pinnedFacts: PinnedFact[]; decisions: string[]; }): Promise<string>;}async function compactRecentEvents( state: RunState, counter: TokenCounter, summarizer: Summarizer, recentBudget: number,): Promise<RunState> { const serialized = state.recentEvents .map((event) => `${event.role}: ${event.content}`) .join("\n"); if (counter.count(serialized) <= recentBudget) { return state; } // Keep the newest events verbatim and summarize the older prefix. const keepCount = Math.max(4, Math.floor(state.recentEvents.length / 3)); const splitAt = state.recentEvents.length - keepCount; const toCompact = state.recentEvents.slice(0, splitAt); const keep = state.recentEvents.slice(splitAt); const summary = await summarizer.summarize({ previousSummary: state.summary, events: toCompact, pinnedFacts: state.pinnedFacts, decisions: state.decisions, }); return { ...state, summary, recentEvents: keep, summaryVersion: state.summaryVersion + 1, };}The summary gets the previous summary because compaction can happen repeatedly. It also receives pinned facts and decisions so it can avoid contradicting them—but those facts are still rendered separately later.
The summary is supporting context, not the canonical source of critical state.
Python version with the same semantics
from typing import Protocolclass TokenCounter(Protocol): def count(self, text: str) -> int: ...class Summarizer(Protocol): async def summarize( self, previous_summary: str, events: list[AgentEvent], pinned_facts: list[PinnedFact], decisions: list[str], ) -> str: ...async def compact_recent_events( state: RunState, counter: TokenCounter, summarizer: Summarizer, recent_budget: int,) -> RunState: serialized = "\n".join( f"{event.role}: {event.content}" for event in state.recent_events ) if counter.count(serialized) <= recent_budget: return state keep_count = max(4, len(state.recent_events) // 3) split_at = max(0, len(state.recent_events) - keep_count) to_compact = state.recent_events[:split_at] keep = state.recent_events[split_at:] summary = await summarizer.summarize( state.summary, to_compact, state.pinned_facts, state.decisions, ) state.summary = summary state.recent_events = keep state.summary_version += 1 return stateIn a durable workflow I would store each summary version rather than mutate the only copy. That gives me a trace of when information was compacted and makes debugging easier.
Compaction must preserve unresolved work
A bad summary often sounds reasonable but drops the one thing the agent still needed to do.
For a coding workflow, I want the summary format to preserve explicit categories such as:
- completed changes;
- unresolved failures;
- files currently relevant;
- decisions and their rationale;
- next intended action;
- user constraints.
I do not require the final prompt to expose these as a rigid template forever, but the summarizer benefits from a structured contract.
For example:
type CompactedSummary = { completed: string[]; unresolved: string[]; relevantResources: string[]; nextStep?: string;};This is safer than asking for “a concise summary of the conversation.” Concise is not the same as operationally useful.
Keep references to large artifacts instead of summarizing them away
Imagine the agent ran a test suite and received 20,000 lines of output. A summary may say “42 tests failed,” but later the agent needs the exact stack trace from test number 17.
The better representation is often:
Test run tr_8f12: 42 failures. Primary failure groups: auth, invoices, webhooks.Full log available through read_test_run(tr_8f12, offset, limit).The prompt keeps a small preview and a handle. The full artifact lives outside context and can be retrieved when the next step needs it.
Compaction should reduce *active context*, not destroy information that may be needed later.
Summaries can become stale too
Context compaction solves size. It does not solve freshness.
Suppose an older summary says src/auth.ts contains a synchronous token check. Three steps later the agent rewrites that file. If the old summary remains unchanged, the prompt now contains a stale description of current code.
This is why I avoid treating a running summary as a database of live resource state.
Facts about mutable resources should be keyed and refreshed separately. The next article in this series goes deeper into that problem, because freshness requires different mechanics from compression.
Do not compact security policy or authorization state through an LLM
Some data should not enter the summarizer at all.
Current actor identity, tenant ID, granted capabilities, approval status, budget limits, and security policy should remain structured application state. Reconstructing these from a generated summary creates an unnecessary trust boundary.
The model may summarize “the user appears to be an admin.” The authorization layer still uses the authenticated role object, not that sentence.
Compaction is a context optimization, not a substitute for application state.
Evaluate compaction with continuation tasks
A summary can look excellent to a human and still be poor for the next step.
I prefer tests that compact a real or synthetic run and then ask the agent to continue.
Examples:
- after compaction, can it still name the API constraint the user set ten turns ago?
- does it know which migration strategy was chosen?
- does it avoid repeating work already completed?
- can it identify an unresolved failing test?
- does it refrain from using an obsolete file observation?
The metric I care about is not summary similarity. It is task continuity after old context has been removed.
Do not compact too aggressively
Every compaction is lossy and costs another model call.
If a workflow usually ends in six turns, building an elaborate multi-stage memory hierarchy is probably unnecessary. If the model window is large and the average prompt stays comfortably small, a simple recent-tail policy may be enough.
I add compaction when traces show one of three things: context cost keeps growing, long runs approach practical input limits, or older history starts hurting behavior.
A bigger context window can postpone all three. It does not change the underlying shape of the problem.
Long-running agents need a working set, not an autobiography. Once goals, durable state, summaries, recent events, and large artifacts have separate lifecycles, context becomes something the application can budget and debug instead of a transcript that grows until somebody notices the bill.
KEEP READING
Related engineering notes
A Failover Route Is Not a Recovery Path: Proving Independence in AI Infrastructure
Two LLM providers can share the same failure domain. Build an evidence-backed recovery graph that checks cloud, networking, identity, control-plane and capacity dependencies before admitting fallback routes, then test correlated outages without weakening safety.
Read articleAn Eval Platform Sunset Can Erase Your Release Evidence: Build an Evidence-Escrow Migration Gate
When a hosted LLM evaluation platform retires, switching runners is not enough. Preserve the historical evidence, reconstruct grader semantics, validate scoring parity, and enforce a fail-closed release gate that survives the service shutdown.
Read articleWhen the Package Runs Before Your App: Quarantining AI Framework Releases
The 2026 agent-framework PyPI compromise exposed a blind spot in AI build pipelines: Python startup hooks execute before application imports. Design an artifact-quarantine gate, inspect wheels without installing them, separate credentials, and recover from suspected exposure.
Read article