Skip to content

Context window management

You’ve been pairing with the agent for two hours on a gnarly migration. It was sharp at the start. Now it’s started re-suggesting a fix it already tried and you already rejected, it’s “forgotten” the constraint you stated forty messages ago, and its edits are getting vaguer. Nothing is broken. The window is just full - mostly of stale file reads, greps that didn’t pan out, and abandoned attempts - and the signal you actually need is buried under noise it can no longer tell apart from signal.

How agents work establishes the substrate: the agent runs a loop, everything it can see lives in a finite context window, and that window both fills up and loses fidelity as a session grows. This chapter is the set of levers for operating within that limit over a long session - the management layer on top of the substrate.

There are three of them:

  • Inspect - see what’s currently eating the window, before it bites.
  • Compact - squeeze the dead weight out without losing the thread: replace a long, noisy history with a short summary so the session can keep going.
  • Carry state across the boundary - resume, fork, or otherwise pick up a window instead of starting from an empty one, so you never pay to rebuild context you already had.

None of these change what the agent can do. They change what it can still see clearly after an hour of work. The window has a hard size limit and a softer coherence limit, and a long session walks into both.

The concrete moves teams make:

  • Compact at phase boundaries - finished the migration, about to start the tests? Compact first, so the test work starts on a lean window instead of dragging the migration trail behind it.
  • Clear, don’t compact, for unrelated work - switching to a different bug entirely? Start clean. Compaction summarises the old work; clearing drops it, which is what you want when none of it is relevant.
  • Watch the gauge - check what’s consuming the window (tool schemas, a giant file read, an over-long rules file) instead of waiting for degradation to tell you.
  • Delegate the noise instead of compacting after - if a sub-task will generate a lot of throwaway context, hand it to a subagent so it never enters your window in the first place.
  • Resume instead of re-explaining - pick up yesterday’s session with its context intact rather than opening a fresh window and re-establishing everything.

The test: if the agent is getting less sharp the longer you work - not wrong, just hazier - you have a context-management problem, not a model problem.

A whole session compressed into eleven steps. Walk through it and watch the window fill: the fixed overhead you pay before typing, the exploration spikes, a subagent detour that keeps 45k of noise out entirely, the auto-compact threshold - and what /compact actually keeps. Token counts are illustrative; the shape is the point.

Step 1 / 11Session start
17k / 200k tokens (9%)
Click any segment of the bar - or a legend chip below - to see what it is.

Before you type a word, 17k tokens are spent: the system prompt, the built-in tool definitions, and your rules file. This fixed overhead reloads on every turn - which is also why it’s the one part of the window you fully control.

A lean rules file pays rent every single turn.

That’s the failure context management addresses, and the rest of this chapter is what each lever does about it.

Compaction is lossy by definition: it trades a faithful, expensive transcript for a cheap, approximate summary. Knowing what survives the trade is the difference between compacting safely and compacting away the thing you needed.

Before compaction · window ~90% full
system prompt ← always kept
rules (AGENTS.md / CLAUDE.md) ← always kept
tool definitions ← always kept
~40 turns of work
  • 17 file reads (full contents)
  • 9 greps, 6 test runs
  • 4 abandoned hypotheses
  • exact error/command output
most recent turns ← kept
After compaction · ~35%
system prompt
rules
tool definitions
summary (lossy)
  • goal · key decisions · files touched · next steps
most recent turns
the middle is what gets compressed

Most items on one side have a shadow on the other. The summary keeps the label and drops the body:

Reliably keptReliably lost
Which files matter, by nameThe full contents of the files read - they become a name, not a body
The decisions made, and whyExact error and command output, summarised to prose
The state of the in-progress taskThe precise sequence of steps taken
The high-level goal-
The most recent turns, verbatim-

The practical consequence: write unsaved work to disk before compacting. A diff that exists only in the conversation gets flattened into “edited auth.ts,” and after compaction the agent may need to re-read the file to see its own change.

This is also the cleanest restatement of the rules argument: a constraint stated in conversation can be summarised away, but a constraint in the rules file is reloaded every turn and survives every compaction. Durable facts belong in always-loaded context, not in the chat.

Knowing that cost is what turns compact-or-clear from a guess into a call you can rehearse. The session below plays until the window is three-quarters full, then hands you the keyboard: keep going, /compact, or /clear. Play all three and watch what each one carries across.

One session, played back with its context window x-rayed. Watch what the work costs on the right; when the playback pauses, you decide what the session does next - then replay the other choices.

0k / 200k
Fixed overheadRulesConversationFile readsTool outputSummaries
agent session - billing-app
agent cli · new session · repo: billing-app
the window, x-rayed

    Every number is an illustrative order of magnitude, and the commands answer to different names across tools - /compact, /compress, or /summarize; /clear, /new, or a fresh chat. The trade is the same everywhere: a reset is coming, and choosing its moment - and what survives it - is yours to keep.

    The vocabulary differs; the broad goal is shared, but the implementation is not. Tools may summarize, truncate, or otherwise transform older context when a window fills. Do not assume that every tool uses one summarization call or a portable structured Markdown summary. A useful summary, when a tool exposes one, usually preserves:

    • Goal - what the session set out to do.
    • What was done - the work already completed.
    • Key decisions - what was chosen, and why.
    • Important files - which paths matter, by name.
    • Next steps - where the thread picks back up.

    Several tools expose a manual /compact that takes optional instructions (/compact focus on the API changes) so you can bias what the summary preserves. The operational idea transfers, but the exact trigger, format, and controls remain tool-specific - that is the comparison below.

    You want to…Reach forNot
    Free up a full / degrading window mid-taskCompactClear (drops everything, including what you still need)
    Start unrelated work on a clean slateClear / new sessionCompact (keeps a summary you don’t want)
    Keep a noisy side-quest out of the main window entirelySubagentCompacting after the noise already landed
    Make a fact survive every turn and every compactionRulesRestating it in chat
    See what’s actually consuming the windowInspect (/context, /status, usage gauge)Waiting for coherence to drop
    Pick up a previous session with context intactResume / continueNew window + re-explaining
    Explore a risky branch without losing the current threadFork / branch (where supported)Compacting, then regretting it

    Compaction is a recovery tool - it salvages a window that’s already heavy. The cheaper move is usually to keep the window light in the first place: delegate noise to subagents, keep rules lean, and lean on MCP tool-schema deferral so unused tool definitions don’t sit in the window as permanent weight.

    Inspect. /context shows what’s currently occupying the window (system prompt, rules, tool definitions, MCP schemas, conversation). /usage shows token usage for the session with a breakdown attributed to skills, subagents, plugins, and individual MCP servers. You can also surface live window usage in the status line.

    Compact. Auto-compaction summarises conversation history automatically as you approach the limit. Trigger it yourself with /compact, and steer it with inline instructions:

    /compact Focus on the API changes and the failing test

    You can also set standing compaction guidance in CLAUDE.md:

    # Compact instructions
    When compacting, preserve test output and code changes.

    Clear vs rewind. /clear starts fresh for unrelated work (use /rename first so you can find the session later). /rewind (or double-tap Escape) restores both the conversation and the code to an earlier checkpoint - distinct from compaction; it’s an undo, not a summary.

    Carry across. /resume reopens a prior session; claude --continue / -c continues the most recent one. A background job summarises past conversations so resume is fast.

    Keep the window light upstream: MCP tool definitions are deferred by default (only names enter context until a tool is used), and moving rarely-needed instructions out of CLAUDE.md into skills keeps base context small.

    AspectClaude CodeCodexOpenCodeCursorCopilotPi
    Inspect usage/context, /usage, status line/statusStatus display is surface-dependentinput-box gaugechat input context controlNot listed in this comparison
    Manual compaction/compact [instructions]/compactagent-/auto-driven/summarize/compact [instructions]Auto compaction, extensible
    Automatic compactionYes, near limitYes (model_auto_compact_token_limit)Yes, on overflowYes, near limit (uses a faster model)Yes (~80% of window)Yes (built-in, extension-adjustable)
    Custom compact instructionsYes (inline + CLAUDE.md)Yes - compact_prompt (inline string) or experimental_compact_prompt_file (file path, experimental) 1Fixed structured templateNot listed in the public comparison docsYes (inline)Via extension
    Disable auto-compactionCheck current Claude Code settingsn/acompaction.auto=false / OPENCODE_DISABLE_AUTOCOMPACTNot listed in the public comparison docsgithub.copilot.chat.summarizeAgentConversationHistory.enabled=falseVia extension
    Fresh window (same app)/clear/new, /clearnew sessionNew ChatNew ChatNew tree session
    Resume prior session/resume, claude --continue/-c/resume, codex resumeopencode --continue/-c, --session/-sChat historyChat history/tree session picker
    Fork / branch a session--fork-session, /branch (verify current command)/fork, /sideopencode --fork/fork (CLI)-Yes - native tree-of-sessions (/tree)

    1 Codex’s custom prompt only governs its local compaction path. Providers that support remote compaction skip the local path entirely, and compact_prompt isn’t read on that path either, per the Codex source (as of 2026-07).

    Three rows carry the real difference: Inspect usage, Custom compact instructions, and Disable auto-compaction. Auto-compaction is now the default everywhere it’s offered, so the axis that still separates the tools is control - whether you can see the window filling, steer what the summary keeps, and turn the automation off. The terminal CLIs expose the most knobs; the IDE tools manage it for you with the fewest.

    Verify tool-specific flags against the upstream docs below before relying on them - these settings move between releases.

    • Compact vs clear vs new. “Compact” summarises and keeps a thread going; “clear” / “new” abandons the thread for a fresh window. In Codex, /new starts a fresh conversation inside the same CLI process while /clear resets both the view and the conversation - neither is /compact.
    • “Summarize” vs “compact”. Cursor and Copilot surface the behaviour as “summarising conversation history”; the terminal tools call the same operation “compaction.” Same mechanism, different label.
    • “Session” is overloaded. In how agents work a session is one run of the loop with one window. OpenCode also has an opencode session CLI noun and /share-able sessions; don’t read the CLI sense as a different concept.
    • Compaction vs memory. Compaction works within a session to fit the window. Agent-managed memory persists facts across sessions and is a separate primitive (deferred; distinct from rules). Resuming a session is not the same as the agent remembering it.
    • Claude Code’s /branch vs /fork. Current Claude Code documents /fork as an alias for /branch by default; a separate environment setting can opt into forked-subagent behavior. Verify the active version and environment before relying on either meaning.

    Next session, run your tool’s inspect command from the table above before the agent starts getting hazy, not after. If the weight turns out to be a bloated rules file or a giant file read rather than the conversation itself, compaction only buys it back for another hour - move the weight out instead.