Home › Articles

Context window full in Claude Code, Cursor and Codex: what to do

Updated 2026-11-15

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.

Checked against each vendor's docs on 15 November 2026. We tested the handoff script and the three config snippets below with the hook input each tool documents; we did not run them inside a live Claude Code, Codex or Cursor session.

Side by side

Claude CodeCursorCodex
Compacts automatically?Yes, on by default (autoCompactEnabled)Yes, when the window gets close to fullYes, at a threshold the model sets unless you override it
Change when/autocompact 500k, autoCompactWindow, --autocompact, CLAUDE_CODE_AUTO_COMPACT_WINDOWNo 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 fieldsContext ring next to the prompt/status
Steer the summary/compact focus, “Compact Instructions” in CLAUDE.md, PreCompact hook stdoutNo documented waycompact_prompt or experimental_compact_prompt_file
Hook after compactionSessionStart matcher compactNone (preCompact only observes)SessionStart matcher compact; PostCompact

Compact, clear or new chat?

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:

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 reloadedLost or cut down
System prompt and output styleRules 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 diskInvoked skill bodies beyond 5,000 tokens each or 25,000 in total (oldest dropped first)
Auto memory, re-read from diskFiles 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 diskContext that hooks added earlier (summarized with everything else)
Skill descriptions (v2.1.304 or later); background commands and subagents keep runningDetails 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

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:

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:

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

  1. Check what loads before you type: /context in Claude Code, the context ring in Cursor, /status in Codex. Big fixed slices (tools, MCP, skills, instruction files) shrink every session's working room.
  2. Turn off MCP servers you aren't using in this project; see one MCP server, three configs for where each tool keeps them.
  3. Send big reads (logs, a whole module, test output) to a subagent so only its summary comes back.
  4. Plan first, then implement in a fresh or compacted context; Claude Code re-reads the plan from disk after compaction (see plan mode).
  5. 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

Official docs, checked 2026-11-15.

Get the free rules sampler + new tips by email

Confirm your email and we'll send you straight to the sampler download. Then one short email every two weeks covering tool format changes (Cursor, Claude Code, Codex, Windsurf, Copilot), new rules and kit updates. No spam.

We store only your email, with our email provider Resend. See the privacy policy.

Unsubscribe anytime from any email. Rather skip email? Get the sampler on GitHub or download the zip directly.