Context window full in Claude Code, Cursor and Codex: what to do
In short: all three tools summarize the conversation on their own when the
context window gets close to full, so a full window rarely ends a session. What you control is when that
happens and what survives. Run /compact (Claude Code, Codex) or /summarize
(Cursor) yourself at a clean break, with a focus if the tool takes one. Start fresh with /clear or a new
chat when the next task is unrelated. Keep standing rules in instruction files, not chat messages, and use a hook to
put a short handoff note back after compaction.
Side by side
| Claude Code | Cursor | Codex | |
|---|---|---|---|
| Compacts automatically? | Yes, on by default (autoCompactEnabled) | Yes, when the window gets close to full | Yes, at a threshold the model sets unless you override it |
| Change when | /autocompact 500k, autoCompactWindow, --autocompact, CLAUDE_CODE_AUTO_COMPACT_WINDOW | No setting (staff: roughly 90%, fixed server-side) | model_auto_compact_token_limit in config.toml |
| Compact by hand | /compact [focus]; /rewind > Summarize from/up to here | /summarize (CLI alias /compress) | /compact (CLI asks you to confirm) |
| Start fresh | /clear (also /new, /reset) | New chat; CLI /clear or /new | /new, or /clear to also wipe the screen |
| See usage | /context, status line context_window fields | Context ring next to the prompt | /status |
| Steer the summary | /compact focus, “Compact Instructions” in CLAUDE.md, PreCompact hook stdout | No documented way | compact_prompt or experimental_compact_prompt_file |
| Hook after compaction | SessionStart matcher compact | None (preCompact only observes) | SessionStart matcher compact; PostCompact |
Compact, clear or new chat?
- Same task, long history: compact. You keep the thread; old tool output and file dumps shrink to a summary. Do it at a break (tests just passed, plan just agreed), not halfway through a failing edit.
- New, unrelated task: clear. Claude Code's docs put it plainly: old conversation crowds out the files you need next and costs tokens on every message.
- The agent is going in circles or “forgot” a decision: have it write a handoff note (goal, decisions, done, next), then clear and start from the note. A summary of a confused session is still confused.
- The window refills right after compacting: one huge file or tool output is the problem, not history. Read it in pieces or hand it to a subagent.
Claude Code
When it compacts
With no window set, Claude Code compacts when the conversation reaches the model's context limit. Models running a
native 1M window (the docs list the Fable models, Sonnet 5 and later, Haiku 5.5, and Opus 4.7 and later) compact at
about 967K tokens. Sonnet 4.6 and Opus 4.6 without extended context, and any model when you set
CLAUDE_CODE_DISABLE_1M_CONTEXT=1, compact at the 200K boundary. Subagents compact on their own as their
own window fills.
To compact earlier, set an auto-compact window from 100K to 1M tokens. Claude Code caps it at the model's window:
/autocompact 500ksaves the value for the current model in your user settings and applies it now;/autocompact autogoes back to the default."autoCompactWindow": 500000in a settings file sets it for every model.claude --autocompact 500kapplies to one launch without saving.CLAUDE_CODE_AUTO_COMPACT_WINDOW=200000beats all of the above. Watch the units: for the command and the flag a bare200means 200,000, but the variable reads200as 200 tokens (raised to the 100K minimum with a warning). Use200000or, on v2.1.304 or later,200k.
Claude Code also compacts a long conversation you walked away from (idleCompaction, on by default):
roughly an hour idle, at least 200,000 tokens, on the one-hour prompt cache. You'll see a line starting
Compacted while idle. Set "idleCompaction": false to stop it.
Compact with a focus
Run /compact with instructions before a long new step, for example
/compact keep the plan, the files we changed and the failing test. You can also add a section to the
project's CLAUDE.md that every compaction follows:
# Compact instructions
When you are using compact, please focus on test output and code changes
To shrink only part of the history, run /rewind, pick a message and choose Summarize from
here or Summarize up to here. That keeps the rest word for word and doesn't touch files (more
in undoing agent changes).
What survives compaction
| Kept or reloaded | Lost or cut down |
|---|---|
| System prompt and output style | Rules with paths: frontmatter and nested CLAUDE.md files (summarized away; they reload only when Claude touches a matching file again) |
| Project-root CLAUDE.md and unscoped rules, re-read from disk | Invoked skill bodies beyond 5,000 tokens each or 25,000 in total (oldest dropped first) |
| Auto memory, re-read from disk | Files Claude read beyond the five most recently modified; a file over 5,000 tokens comes back as a path only |
| The plan from plan mode, re-read from disk | Context that hooks added earlier (summarized with everything else) |
| Skill descriptions (v2.1.304 or later); background commands and subagents keep running | Details and instructions you gave early in the chat |
So a rule that must hold after compaction belongs in the root CLAUDE.md without paths:, and a long CLAUDE.md
has its own cost (see why a long CLAUDE.md gets ignored). Skills
that must survive should put their key instructions at the top of SKILL.md, since truncation keeps the start.
The errors you might see
Context limit reached · /compact or /clear to continue: the request didn't fit. Run one of the two. If the line addsauto-compact is off · /config to turn it on, that's why it happened.Not enough messages to compact.: there's only one exchange, so the space is taken by that prompt plus what loads every time (system prompt, tools, memory files). Run/clearand resend with less pasted text, or trim skills, MCP servers (/mcp disable <name>) and CLAUDE.md.Autocompact is thrashing: the context refilled to the limit...: compaction worked but a file or tool output filled the window again several times, so Claude Code stopped retrying. Ask for the file in smaller pieces, run/compact keep only the plan and the diff, move the big read to a subagent, or/clear.
To turn automatic compaction off, toggle Auto-compact in /config (writes
autoCompactEnabled) or set DISABLE_AUTO_COMPACT=1; /compact still works.
DISABLE_COMPACT=1 turns off manual compaction too. With either set, you have to watch /context
yourself.
Cursor
Cursor's docs say every chat shares a fixed context window, and when it gets close to full, Cursor compresses older parts of the conversation into a summary. The context ring next to the prompt shows how full it is; click it for a breakdown by system prompt, tools, rules, skills, MCP, subagents, summarized conversation and conversation.
The docs don't give a threshold. On the Cursor forum, Cursor staff said background compaction starts at roughly 90% of the window, that the threshold is fixed and set server-side, and (in August 2026) that a user setting or an earlier trigger is not on the roadmap. So the levers are manual:
/summarizecompacts now. It's in the Cursor CLI docs (alias/compress), and staff call it the manual checkpoint in the editor too. Staff also said running it while the agent is working interrupts the work instead of queuing, so run it between turns.- A new chat. In the CLI that's
/clear(aliases/new,/new-chat,/newchat). Bring the useful parts along with@Chats, which references a previous conversation, instead of pasting it. - Side questions in a side chat.
/sideopens a side chat that reads the parent conversation as reference context, so a quick question doesn't add to the main thread. - Standing instructions in rules. Rules have their own slice of the breakdown, apart from the summarized conversation. An instruction typed in message three is exactly what a summary can drop. If your rules aren't loading, see why Cursor rules don't apply.
Cursor's preCompact hook runs before summarizing. It can't block or change the summary, but it gets
trigger, context_usage_percent, context_tokens, context_window_size
and messages_to_compact, and can show you a user_message. That's enough to warn you that this
is a good moment for a handoff note and a new chat. sessionStart can add additional_context to a
new chat, which is how the script below carries the note over.
Codex
Codex compacts history automatically at a token threshold. The configuration reference describes
model_auto_compact_token_limit as the token count that triggers it, using the model's default when unset.
Related keys in config.toml:
model_auto_compact_token_limit_scope:total(default) counts the whole active context;body_after_prefixcounts only growth after the carried compaction prefix.model_post_turn_compact_threshold_percent(0–100, off by default): also compact after a final answer once context reaches that share of the usable window, so the next turn starts lean.compact_prompt(inline) orexperimental_compact_prompt_file(a file) replaces the prompt Codex uses to write the summary.model_context_windowtells Codex the window size of the active model, for models it doesn't know.
In the CLI, /status shows token usage and how much context is left. /compact asks you to confirm,
then replaces earlier turns with a concise summary; it's also in the IDE extension and desktop app. /recap
only writes a summary for you and doesn't free context. To start over, /new starts a fresh chat in the
same CLI session, /clear does that and wipes the screen, and Ctrl+L only clears the
screen and keeps the chat.
Codex hooks cover compaction too. PreCompact and PostCompact match manual or
auto, ignore plain stdout, and can stop the turn with continue: false. The useful one is
SessionStart with source compact: it runs after Codex compacts, before the next model request,
even when compaction happened mid-turn, and its plain stdout is added as developer context. Codex skips new or changed
hooks until you trust them in /hooks. Your AGENTS.md is still the place for rules every session needs (see
an AGENTS.md template for Codex).
Carry a handoff note across compaction
A summary decides for you what mattered. A handoff note is the part you decide: a few lines in
.agent/HANDOFF.md with the goal, decisions, what's done and what's next. Ask the agent to update it at each
break (“update .agent/HANDOFF.md with where we are”), and let a hook put it back after compaction or
/clear. Keep it short; it's added to context every time, and it shouldn't hold secrets (see
keeping agents away from .env).
# Handoff
Goal: move session storage from cookies to Redis (branch feat/redis-sessions)
Decisions: keep the cookie name `sid`; TTL 14 days; no migration of old sessions
Done: RedisStore in src/session/redis.ts, unit tests pass
Next: wire RedisStore into src/server.ts; fix failing test "logout clears session"
Don't: touch src/billing/ or change the public API of SessionStore
handoff.py reads that file from the repo root and has one mode per hook. It never blocks: if anything is
wrong it prints nothing and exits 0. It cuts the note at 8,000 characters, under Claude Code's 10,000-character cap on
hook output. Python 3.8+, standard library only. Save it as .agent/handoff.py:
#!/usr/bin/env python3
"""Carry a short handoff note across compaction, /clear and new chats.
The note lives in .agent/HANDOFF.md at the repo root (goal, decisions, done, next).
One script, four hook modes:
inject Claude Code / Codex SessionStart (matcher compact|clear): print the note
precompact Claude Code PreCompact: print summary instructions that keep the note's items
cursor-start Cursor sessionStart: JSON {"additional_context": note}
cursor-precompact Cursor preCompact: JSON {"user_message": "..."} (Cursor can't block or steer it)
Reads the hook's JSON from stdin when there is one. Never blocks: on any problem it
prints nothing (or {} for Cursor) and exits 0. Python 3.8+, standard library only.
"""
import json, os, pathlib, subprocess, sys
NOTE = pathlib.Path(".agent") / "HANDOFF.md"
CAP = 8000 # Claude Code caps hook stdout at 10,000 chars; stay well under it
def read_stdin():
if sys.stdin is None or sys.stdin.isatty():
return {}
try:
data = sys.stdin.read()
return json.loads(data) if data.strip() else {}
except (ValueError, OSError):
return {}
def repo_root(event):
roots = event.get("workspace_roots") or []
start = event.get("cwd") or (roots[0] if roots else None) or os.getcwd()
try:
out = subprocess.run(["git", "-C", start, "rev-parse", "--show-toplevel"],
capture_output=True, text=True, timeout=5)
if out.returncode == 0 and out.stdout.strip():
return pathlib.Path(out.stdout.strip())
except (OSError, subprocess.SubprocessError):
pass
return pathlib.Path(start)
def read_note(root):
p = root / NOTE
try:
text = p.read_text(encoding="utf-8").strip()
except (OSError, UnicodeDecodeError):
return ""
if len(text) > CAP:
text = text[:CAP].rstrip() + f"\n[... cut at {CAP} characters; read {NOTE} for the rest]"
return text
def main():
mode = sys.argv[1] if len(sys.argv) > 1 else ""
event = read_stdin()
note = read_note(repo_root(event))
if mode == "inject":
if note:
print(f"Handoff note from {NOTE} (re-read after compaction or /clear):\n\n{note}")
elif mode == "precompact":
if note:
print("When you summarize, keep every decision and open item in the handoff note below, "
"the exact file paths being edited, and the last failing test or error message. "
f"Drop long tool output and file contents that can be re-read.\n\n{note}")
elif mode == "cursor-start":
print(json.dumps({"additional_context": f"Handoff note from {NOTE}:\n\n{note}"} if note else {}))
elif mode == "cursor-precompact":
pct = event.get("context_usage_percent")
msgs = event.get("messages_to_compact")
bits = ["Cursor is summarizing this chat"]
if isinstance(pct, (int, float)):
bits.append(f"at {pct:.0f}% of the context window")
if isinstance(msgs, int):
bits.append(f"({msgs} messages)")
tip = f" Ask the agent to update {NOTE}, then start a new chat." if note else \
f" Consider asking the agent to write {NOTE} and starting a new chat."
print(json.dumps({"user_message": " ".join(bits) + "." + tip}))
else:
print(__doc__, file=sys.stderr)
return 0
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except Exception: # a broken hook must never break the session
sys.exit(0)
Claude Code (.claude/settings.json): re-inject after compaction and /clear, and
pass the note to the summarizer as PreCompact instructions.
{
"hooks": {
"SessionStart": [
{
"matcher": "compact|clear",
"hooks": [
{ "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.agent/handoff.py\" inject" }
]
}
],
"PreCompact": [
{
"hooks": [
{ "type": "command", "command": "python3 \"$CLAUDE_PROJECT_DIR/.agent/handoff.py\" precompact" }
]
}
]
}
}
Codex (.codex/config.toml, then trust the hook in /hooks). Codex ignores plain
PreCompact stdout, so only the SessionStart part applies:
# .codex/config.toml (project) or ~/.codex/config.toml
# Optional: compact earlier than the model default (tokens). Unset = model default.
# model_auto_compact_token_limit = 150000
[[hooks.SessionStart]]
matcher = "^(compact|clear)$"
[[hooks.SessionStart.hooks]]
type = "command"
command = 'python3 "$(git rev-parse --show-toplevel)/.agent/handoff.py" inject'
statusMessage = "Loading handoff note"
Cursor (.cursor/hooks.json; project hooks run from the project root): add the note to new
chats and tell you when Cursor starts summarizing.
{
"version": 1,
"hooks": {
"sessionStart": [
{ "command": "python3 .agent/handoff.py cursor-start" }
],
"preCompact": [
{ "command": "python3 .agent/handoff.py cursor-precompact" }
]
}
}
What it printed on our test repo:
$ echo '{"source":"compact","cwd":"/work/app/src"}' | python3 .agent/handoff.py inject
Handoff note from .agent/HANDOFF.md (re-read after compaction or /clear):
# Handoff
Goal: move session storage from cookies to Redis (branch feat/redis-sessions)
Decisions: keep the cookie name `sid`; TTL 14 days; no migration of old sessions
Done: RedisStore in src/session/redis.ts, unit tests pass
Next: wire RedisStore into src/server.ts; fix failing test "logout clears session"
Don't: touch src/billing/ or change the public API of SessionStore
$ echo '{"trigger":"auto","context_usage_percent":85,"messages_to_compact":30}' | python3 .agent/handoff.py cursor-precompact
{"user_message": "Cursor is summarizing this chat at 85% of the context window (30 messages). Ask the agent to update .agent/HANDOFF.md, then start a new chat."}
More on hook formats, exit codes and trust in hooks in Claude Code, Cursor and Codex. A handoff note is not the same as agent memory, which the tool writes for itself (see memory in Claude Code, Cursor and Codex).
Keep the window from filling so fast
- Check what loads before you type:
/contextin Claude Code, the context ring in Cursor,/statusin Codex. Big fixed slices (tools, MCP, skills, instruction files) shrink every session's working room. - Turn off MCP servers you aren't using in this project; see one MCP server, three configs for where each tool keeps them.
- Send big reads (logs, a whole module, test output) to a subagent so only its summary comes back.
- Plan first, then implement in a fresh or compacted context; Claude Code re-reads the plan from disk after compaction (see plan mode).
- One task per conversation. Clearing is cheaper than carrying an old task's history into every request.
FAQ
What should I do when Claude Code says the context window is full?
Usually nothing: auto-compact is on by default and summarizes the conversation before the limit. If you see "Context limit reached · /compact or /clear to continue", run /compact (optionally with a focus, like /compact keep the plan and the failing test) to keep going, or /clear to start a new conversation. If it says auto-compact is off, turn it back on in /config. Run /context to see what is filling the window.
What is the difference between /compact and /clear?
/compact replaces the conversation so far with a summary and keeps you in the same conversation, so the agent still knows roughly what happened. /clear (also /new) starts a new conversation with empty context; project instruction files such as CLAUDE.md or AGENTS.md load again, but nothing from the chat carries over. Codex and the Cursor CLI use the same idea: /compact or /summarize to shrink, /new or /clear to start fresh.
Can I make Cursor summarize earlier?
Not automatically. Cursor's docs say it compresses older parts of the chat when the window gets close to full, and Cursor staff said on the Cursor forum (August 2026) that background compaction starts at roughly 90%, set server-side, with no user setting and none on the roadmap. Run /summarize yourself before quality drops, or start a new chat and reference the old one with @Chats.
How do I change when Codex compacts automatically?
Set model_auto_compact_token_limit in config.toml to a token count; when it is unset Codex uses the model's default. model_post_turn_compact_threshold_percent (0 to 100, default off) adds a compaction after a final answer once context reaches that share of the usable window. Run /status to see how much context is left, and /compact to summarize by hand.
Why does the agent forget my instructions after compaction?
Compaction is a summary, so details from early messages can drop out. In Claude Code, project-root CLAUDE.md, unscoped rules and auto memory are re-read from disk, but rules with paths: frontmatter and nested CLAUDE.md files are summarized away until a matching file is read again. Put standing rules in CLAUDE.md, AGENTS.md or a Cursor rule rather than a chat message, and use a SessionStart hook with the compact matcher to re-inject a short handoff note.
Sources
- Claude Code docs: Explore the context window (what survives compaction)
- Claude Code docs: Model configuration (auto-compact window and defaults)
- Claude Code docs: Commands (/compact, /clear, /context, /autocompact)
- Claude Code docs: All settings (autoCompactEnabled, autoCompactWindow, idleCompaction)
- Claude Code docs: Error reference (Prompt is too long, Context limit reached)
- Claude Code docs: Troubleshooting (Autocompact is thrashing)
- Claude Code docs: Hooks reference (PreCompact, PostCompact, SessionStart)
- Cursor docs: Prompting agents (Context usage)
- Cursor docs: CLI slash commands (/summarize, /clear)
- Cursor docs: Hooks (preCompact, sessionStart)
- Cursor forum: staff replies on when auto-summarization runs (2026-07-20, 08-11, 09-21)
- Codex docs (ChatGPT Learn): Developer commands (/compact, /new, /clear, /status)
- Codex docs (ChatGPT Learn): Configuration reference (auto-compaction keys, compact_prompt)
- Codex docs (ChatGPT Learn): Hooks (PreCompact, PostCompact, SessionStart)