# Context windows and token limits for coding agents

URL: https://developertoolkit.ai/en/workflows/context/context-windows/
Description: How a coding agent's context window fills, how to measure it in Claude Code, Codex and Cursor, and when to compact, clear or delegate before quality drops.

A coding agent's context window is the token budget the model rereads every turn: system prompt, `CLAUDE.md` or `AGENTS.md`, tool definitions, file reads, command output and conversation. When it fills, the agent compacts older material, and instructions it was following can quietly disappear. Measuring usage and deciding when to compact, clear or delegate keeps the output trustworthy.

You are forty minutes into a debugging session. The agent has read twelve files, run the test suite six times, and found the bug. You ask for the fix, and it edits the wrong module, reintroduces the approach you rejected twenty minutes ago, and skips the regression test your project rules require. Nothing crashed; the session compacted, and the constraints you stated early did not survive the summary. This page is for developers who drive agents for long sessions and for tech leads who write the shared rules those sessions depend on.

## What you get from managing the context window deliberately

- A way to see what is in the window right now, in each tool, instead of guessing.
- A decision rule for when to compact, clear, fork or hand work to a subagent.
- Two copy-paste prompts: a scoped exploration and a handoff note that survives any reset.
- A compaction hook that re-injects your non-negotiable rules automatically.
- A check that proves the agent still holds your constraints after a reset, without re-reading its whole transcript.

## What fills a coding agent's context window?

The window is not only your conversation. Every turn resends everything the agent currently holds, so the largest consumers are the ones you do not see in the terminal:

| Consumer | Loaded when | How to shrink it |
| --- | --- | --- |
| System prompt, environment info | Always, first | You cannot; it is fixed overhead |
| `CLAUDE.md` / `AGENTS.md` and rules | At session start, and again after compaction | [Prune the file](/en/workflows/context/pruning-context-files/); move reference material into skills or path-scoped rules |
| MCP tool definitions | At start or on demand, depending on the tool | Remove servers you do not use; see [reducing MCP token cost](/en/ecosystem/mcp/reducing-mcp-token-cost/) |
| File reads | Each time the agent opens a file | Name the exact files; ask for the one function, not the whole file |
| Command output | Each test, build or grep run | Filter output (`--silent`, pipe logs through `tail -50`); fail fast |
| Conversation history | Grows every turn | Compact with a focus, or clear between tasks |

Claude Code's own context documentation names file reads as the largest consumer in a typical session (code.claude.com, `context-window`, checked 2026-09-26). That matches what you will see in `/context` on a real repository: the agent's exploration, not your prompts, fills the window.

### How big is the window, and why is "bigger" not the fix?

Window sizes depend on the model and the host, and they change with every release. The [models hub](/en/ecosystem/models/) holds the current figures; two host details matter for this page:

- **Claude Code**: from v2.1.280 (both release channels on 2026-10-12), Claude Code defaults to Claude Opus 5.5, with a 1M-token window on the Anthropic API. On Bedrock, Google Cloud's Agent Platform and Foundry, Opus 4.7 and later and the Fable models also default to a 1M window, with no `[1m]` suffix (v2.1.287; `CLAUDE_CODE_DISABLE_1M_CONTEXT=1` keeps 200K). By default, a session on a 1M-window model auto-compacts at about 967K tokens (Claude Code `model-config` docs, checked 2026-09-26).
- **Codex** gives its default model a working window that is smaller than the model's maximum. You can raise it with `model_context_window` in `~/.codex/config.toml`, up to the ceiling the model allows; see the models hub for the current figures (Codex model catalog, checked 2026-09-26).

A larger window postpones compaction; it does not make the model attend equally well to everything in it. Instructions from early in a very long session compete with hundreds of thousands of tokens of file contents and logs, and the model's adherence to them can degrade well before any limit. Treat the window as a budget you spend on the task, not as storage.

## How do you see context usage in Claude Code, Codex and Cursor?

Measure before you manage. Each tool exposes usage differently.

**Claude Code**

    Run `/context` at any point. It draws current usage as a colored grid, broken down by category (system prompt, memory files, tools, messages), and lists optimization suggestions such as context-heavy MCP tools or an oversized `CLAUDE.md`.

    To keep the number on screen, add a status line to `.claude/settings.json` (or `~/.claude/settings.json` for all projects). Claude Code pipes session JSON to the command, including `context_window.used_percentage`:

    ```json
    {
      "statusLine": {
        "type": "command",
        "command": "jq -r '\"[\\(.model.display_name)] \\(.context_window.used_percentage // 0)% context\"'"
      }
    }
    ```

    The command needs `jq` on your `PATH`.

    If you would rather see cost next to context, [ccusage](/en/ecosystem/observability/agent-cost-tracking/) (npm `ccusage`) ships a ready-made status line:

    ```json
    { "statusLine": { "type": "command", "command": "npx -y ccusage statusline" } }
    ```

    The status line runs outside the model, so it adds no tokens to the context window; `npx -y` downloads the package the first time it runs.

**Codex**

    Run `/status` in the Codex TUI. It shows the current session configuration and token usage. Run `/statusline` to choose which items the TUI keeps in its status line.

    To change the window or the compaction point for one run, pass config overrides on the command line:

    ```bash
    # terminal: raise the working window and compact earlier, for this session only
    codex -c model_context_window=400000 -c model_auto_compact_token_limit=300000
    ```

    Put the same keys in `~/.codex/config.toml` to make them permanent. Checked against Codex CLI 0.157.1 and its config schema.

**Cursor**

    This page does not name Cursor's context indicator or summarization thresholds, because they change by model; check the model picker for the current window.

    The techniques on the rest of this page work the same way in Cursor: one chat per task, the exact files named in the prompt, a handoff note on disk, and a fresh chat when the current one has drifted. Cursor's agent can also delegate to subagents (Cursor docs, checked 2026-08-28), which keeps large exploratory reads out of the main chat.

## When should you compact, clear, fork or delegate?

Decide by what you still need, not by how full the meter is:

| Situation | Action | Claude Code | Codex | Cursor |
| --- | --- | --- | --- | --- |
| Same task, long history, decisions still matter | Compact with a focus | `/compact <what to keep>` | `/compact` | Write the handoff note, then start a new chat |
| Only part of the history is noise | Summarize a slice | `/rewind` → **Summarize from here** or **Summarize up to here** | No slice summarize in Codex CLI 0.157.1: write the handoff note, then `/compact` or `/new` | Write the handoff note, then start a new chat |
| Next task is unrelated | Clear | `/clear` | `/new` | New chat |
| You want to try another approach without losing this one | Branch | `/branch` | `/fork` | Start a new chat from the handoff note |
| A side task would flood the window with reads or logs | Delegate | A [subagent](/en/developer-scorecard-guide/custom-subagents/): its reads stay in its own window and only the summary returns | Subagents (`/subagents` switches between them) | Subagent (Cursor docs, checked 2026-08-28) |
| A quick question about the session | Ask on the side | `/btw <question>`, which does not add to the conversation | `/btw <question>` (a side conversation in an ephemeral fork; Ctrl+C returns to the main thread) | Ask in a separate chat |

Two rules make this table work in practice:

1. **Compact before a phase change, not when the meter forces you.** Auto-compaction guesses what matters; a focused `/compact` after "diagnosis done, starting the fix" keeps what you choose. To compact earlier by default, lower the auto-compact window in Claude Code with `/autocompact 500k`, or set `model_auto_compact_token_limit` in Codex. `/autocompact` is saved to your user settings, so it applies to every project; `/autocompact auto` restores the default. Use `claude --autocompact 500000` for a single session.
2. **Anything that must outlive a reset lives on disk.** Plans, acceptance criteria and progress notes in files survive compaction, `/clear` and a new session. Conversation-only decisions do not.

## Run a long task without losing the plot

This is the workflow for a task that will outgrow one window: a multi-file fix, a migration, a feature with several phases.

1. **Scope the session to one outcome.** Write the outcome and its acceptance criteria into a file the agent can re-read, for example `.agent/handoff.md` (add the directory to `.gitignore` if you do not want it committed). One session, one outcome; the next outcome gets a fresh session.

2. **Explore cheaply.** Ask for targeted reads and a short written summary instead of letting the agent open whole directories. The first prompt below does this. For a broad investigation, hand it to a subagent so the file contents never enter your main window.

   **Copy-paste prompt: context-cheap exploration**

   ```text
   I need to understand how subscription cancellation works in this repo before changing it.

   Rules for this exploration:
   - Search first (ripgrep or your search tool); do not open whole directories.
   - Read only the functions on the cancellation path, not entire files.
   - Follow the path through at most four files. Ignore generated clients and anything under legacy/ or v1/.
   - Skip test output unless a test fails.

   Then write a summary of no more than 15 lines to .agent/handoff.md under "## Cancellation flow":
   entry point, the functions called in order (file:line), where state is persisted, and open questions.
   Do not change any code yet.
   ```

3. **Checkpoint at each phase boundary.** When diagnosis is done, have the agent update the handoff note, then compact with a focus on it:

   ```text
   /compact Keep the acceptance criteria, the files changed so far, the rejected approaches and why, and the exact test command. Drop exploration output and old test logs.
   ```

   **Copy-paste prompt: handoff note that survives any reset**

   ```text
   Update .agent/handoff.md so a fresh session with no memory of this conversation can continue the work. Use exactly these sections:

   ## Goal and acceptance criteria
   (copy them verbatim from the top of this file; do not reword)
   ## Done
   (files changed, one line each, with the reason)
   ## Decisions and rejected approaches
   (what we chose, what we ruled out, and why)
   ## Current state
   (the exact test command, and which tests pass and fail right now)
   ## Next step
   (one concrete action)

   Keep it under 60 lines. Do not include code blocks longer than 5 lines; reference file:line instead.
   ```

4. **Make your rules survive compaction automatically.** In Claude Code, the project-root `CLAUDE.md` is re-injected after compaction, but path-scoped rules and nested `CLAUDE.md` files are summarized away until the agent reads a matching file again (Claude Code `context-window` docs, checked 2026-09-26). For rules that must hold for the whole task, add a `SessionStart` hook with the `compact` matcher to `.claude/settings.json`; Claude Code adds the command's output to the compacted context:

   ```json
   {
     "hooks": {
       "SessionStart": [
         {
           "matcher": "compact",
           "hooks": [
             { "type": "command", "command": "cat .agent/handoff.md 2>/dev/null || true" }
           ]
         }
       ]
     }
   }
   ```

   In Codex, re-inject the file by hand: after `/compact`, send "Read `.agent/handoff.md` before continuing." Codex CLI 0.157.1 also has `PreCompact` and `PostCompact` hook events, which run only after you trust them in `/hooks`; [hooks as deterministic guardrails](/en/developer-scorecard-guide/agent-hooks/) covers the Codex hook format. In Cursor, start the next chat by pointing it at the handoff file.

5. **Clear when the task changes.** Start the next outcome with `/clear` (Claude Code), `/new` (Codex) or a new chat (Cursor), and a first prompt of: "Read `.agent/handoff.md` and continue from Next step."

## How do you prove the agent still holds your constraints after a reset?

You should not have to re-read the transcript to know whether compaction dropped something. Use checks whose result you can read in seconds:

- **Restate-and-diff.** Right after a compaction or a new session, ask: "List the acceptance criteria and the rejected approaches you are working under, verbatim." Compare the answer with the `## Goal and acceptance criteria` and `## Decisions` sections of the handoff file. Any missing or reworded item means the context was lost; point the agent at the file before it writes more code.
- **Tests as the oracle, not the summary.** The acceptance criteria in the handoff file should map to tests that fail before the change. Whether the agent "remembers" is then irrelevant: the test run says whether the behavior exists. See [how strong your oracle is](/en/workflows/test/oracle-strength/) for making those tests worth trusting.
- **The diff against the "Done" list.** `git diff --stat` should touch the files the handoff note lists and nothing else. An unlisted file is a scope leak and a typical sign that the agent lost its instructions.
- **The meter in the review.** For long or unattended runs, record the context usage and the number of compactions next to the result. A task that compacted repeatedly deserves a closer review of its decisions, not just its green tests.

The developer who ran the session signs off on the restate-and-diff check; the reviewer signs off on tests and diff scope, as they would for any change.

## When the context window works against you

**The agent ignores a rule it followed an hour ago.** The rule was in the conversation or in a path-scoped rule that compaction summarized away. Recovery: put the rule in the project-root `CLAUDE.md` or `AGENTS.md`, or in the handoff file re-injected by the compaction hook, then ask the agent to restate its constraints before continuing.

**Compaction keeps firing and each summary is worse.** The window is full of tool output, not decisions. Recovery: write the handoff note, `/clear` or `/new`, and restart from the file. Filter noisy commands (run one test file, not the suite; pipe build logs through `tail`) so the new session does not refill with logs.

**The agent reads 20 files to answer a narrow question.** Broad exploration in the main session. Recovery: interrupt, name the entry point and the files yourself, or send the question to a subagent that returns a summary.

**`/context` shows the window half full before you type.** Fixed overhead: a long `CLAUDE.md`, many MCP servers, many skills. Recovery: run the [ablation protocol for context files](/en/workflows/context/pruning-context-files/), and remove MCP servers the project does not use.

**Claude Code compacts far too early or too late on a gateway model.** Claude Code assumes a window for model IDs it does not recognise, such as an LLM gateway alias. Recovery: for a gateway alias Claude Code does not recognise (and that has no `[1m]` suffix), set `CLAUDE_CODE_MAX_CONTEXT_TOKENS` to the model's real window. For an unrecognised alias that contains `[1m]`, also set `CLAUDE_CODE_DISABLE_1M_CONTEXT=1`. For an ID Claude Code recognises, the variable takes effect only together with `DISABLE_COMPACT`, which turns off all compaction, so prefer `/autocompact` there: if a gateway stops at 200K, run `/autocompact 200k` (Claude Code `model-config` docs and 2.1.286 changelog, checked 2026-09-26).

**You raised the Codex window and the bill rose with it.** Every turn resends the whole window, so a 600K session costs far more per turn than a 150K one, and some providers price long-context input higher. Recovery: keep the default window for routine work and raise it only for a task that needs it; see [context cost optimization](/en/workflows/context/cost-per-context/).

Disabling auto-compaction (`DISABLE_AUTO_COMPACT=1` in Claude Code) does not give the model more room. When the conversation exceeds the window, Claude Code reports that it is over the token limit and you have to compact or clear anyway. Use it only when you compact manually at every phase boundary.

## Where to go next with context management

Start with the [context management overview](/en/workflows/context/) if you have not set up `CLAUDE.md` or `AGENTS.md` yet. Then:

- [Pruning CLAUDE.md and AGENTS.md](/en/workflows/context/pruning-context-files/) — Cut the fixed overhead every turn pays for, and prove each line earns its place.
- [Long-term context retention](/en/workflows/context/memory-patterns/) — Keep decisions and progress across sessions with files, memory and handoffs.
- [Code search and indexing](/en/workflows/context/codebase-indexing/) — Make the agent find the right code with fewer, cheaper reads.
- [Context cost optimization](/en/workflows/context/cost-per-context/) — Turn context usage into a number you can budget and reduce.
