Context compaction: what your coding agent drops, and how to make the important parts survive
Every coding agent has a context window. It holds the system prompt, the instruction files the agent loaded (the files such as CLAUDE.md or AGENTS.md that tell it how to work), the files it read, the output of its tools, and the conversation so far. When that window fills, something has to give.
Compaction is the usual answer. The agent asks a model to replace older turns with a summary, then continues from that summary and a small tail of recent messages. The summary is generated text, not a copy. What the summarizer leaves out is no longer in the model's view, even when the saved session, the conversation Claude Code keeps for a directory, is still on disk, as the Claude Code context window docs and OpenCode's compaction docs describe. Cursor calls the same operation summarization. Claude Code, Codex and GitHub Copilot CLI call it compaction; Gemini CLI calls it compression and exposes /compress, with /compact and /summarize as aliases at v0.65.0.
Checked against each tool's documentation on 26–27 October 2026.
When compaction happens in Claude Code, Codex, Copilot CLI, Gemini CLI, Qwen Code, OpenCode, and Cursor#
The trigger is usually the same: the window is getting full. The controls are not.
| Tool | Automatic | Manual | Settings the docs name |
|---|---|---|---|
| Claude Code | Runs as the context approaches the limit. | /compact, /compact focus on the auth bug, or /rewind and then summarize from a message. | /autocompact 500k sets how full the window gets before the automatic pass. |
| Codex | Compacts automatically at a token threshold. | /compact replaces earlier turns with a concise summary. | model_auto_compact_token_limit sets the threshold. compact_prompt changes the summary prompt. |
| Copilot CLI | Starts in the background at about 80% of the window, leaving a 20% buffer; at about 95% it pauses briefly to wait for the summary. | /compact, or /compact focus on the auth bug to steer the summary. Esc cancels a manual pass. | No threshold setting is documented. --context long_context picks a larger tier when the model has one. |
| Gemini CLI | Runs before a model request when the context reaches the configured compression threshold of the model's window; model.compressionThreshold defaults to 0.5. | /compress replaces the chat with a summary. At v0.65.0 the aliases /compact and /summarize also work. | model.compressionThreshold; ui.footer.hideContextPercentage (the meter is hidden by default). |
| Qwen Code | Runs before a request when the effective prompt reaches the computed auto threshold; context.autoCompactThreshold defaults to 0.85 and acts as a ceiling, so a small window compacts earlier. | /compress (alias /summarize) replaces the chat with a summary; focus text after the command steers it. /compress-fast clears old tool output and thinking parts without a model call. | context.autoCompactThreshold; model.chatCompression.maxRecentFilesToRetain (5) and maxRecentImagesToRetain (3). |
| OpenCode | On by default near the model's limit. | opencode api post /api/session/<id>/compact --data '{}'. | compaction.auto, keep.tokens (15,000 by default), and buffer. |
| Cursor | Compresses older parts of the conversation into a summary when the window gets close to full; the automatic pass keeps recent messages. | /summarize frees space without starting a new chat and compresses the whole conversation, including the recent tail (staff reply, 13 August 2026; #167893); /compress is the CLI alias. | The pages checked do not document a threshold setting. |
Three details matter. OpenCode says compaction is lossy and keeps about 15,000 recent tokens beside the summary. Claude Code says that if a single file or tool output is so large that context refills immediately after each summary, it stops auto-compacting after a few attempts and shows an error. Qwen Code adds a third: it sends the whole curated history to the summarizer and keeps no recent tail, then restores the current content of recent files and images.
What gets lost#
A summary can keep the shape of the work and still lose the parts that decide whether the next action is safe.
The procedure#
An instruction or tool detail loaded early. The summary may keep the goal and drop the steps.
You said: run pnpm test before every commit, and use the staging key for deploys. Forty turns later the summary says "tests pass" and "deploy is ready". The command and the key name are gone. The agent commits without the test. Claude Code's docs say the summary keeps requests and key code snippets, but detailed instructions from early in the conversation may be lost.
The provenance#
Where a claim came from, who said it, and when. A summary can keep the claim and drop the source.
The agent read a deployment note from an old ticket. After compaction the summary says "deploys go through the old pipeline". The ticket number, the author, and the date are gone. You cannot tell whether that came from the current runbook, a stale issue, or a page an attacker wrote. Provenance is how you decide whether to trust the sentence.
The open thread#
What was unfinished, what already failed, and what only applies now.
The agent tried two fixes. The first failed because the migration lock was held by another process. After compaction the summary says "working on the migration" and drops the failed attempt. The agent tries the same fix again, or reports success anyway.
What survives, by tool#
The vendors do not document the same amount.
Claude Code#
Documented to survive:
- The system prompt and output style.
- Root CLAUDE.md and unscoped rules, re-injected from disk.
- Auto memory.
- Descriptions of each skill (a folder of instructions Claude Code loads on demand; v2.1.304 or later).
- A fresh git status, if the session started with one.
- The plan from plan mode, Claude Code's read-only planning step.
- Up to five recently read or edited files.
- Invoked skill bodies, capped at 5,000 tokens per skill and 25,000 tokens total.
- Background commands and subagents keep running. A subagent is a separate agent the main conversation starts.
- A
SessionStarthook runs at a lifecycle event such as compaction; when it matchescompact, its output is added to context, according to the context window docs.
Documented to be summarized away:
- Path-scoped rules and nested CLAUDE.md files load on demand, not at the moment of compaction; compaction summarizes them away with everything else.
- Context that hooks added earlier is summarized with the rest of the conversation.
Codex#
Codex is covered below in [what Codex compaction changes](#what-codex-compaction-changes).
Copilot CLI#
Copilot CLI is covered below in [what Copilot CLI compaction changes](#what-copilot-cli-compaction-changes).
Gemini CLI#
Gemini CLI is covered below in [what Gemini CLI compression changes](#what-gemini-cli-compression-changes).
Qwen Code#
Qwen Code is covered below in [what Qwen Code compression changes](#what-qwen-code-compression-changes).
OpenCode#
Not documented: the older turns and tool details that are dropped. The detailed V1/V2 mechanics, settings, and failure modes are in [what OpenCode compaction changes](#what-opencode-compaction-changes).
Cursor#
Cursor is covered below in [what Cursor summarization changes](#what-cursor-summarization-changes).
Two details are easy to miss. Claude Code reloads path-scoped rules and nested CLAUDE.md files when a matching file is touched, so they can return; they are not guaranteed at the moment of compaction. OpenCode says the current instruction files become the baseline. Codex's and Cursor's docs do not say. If a rule must survive, put it in a file and check after compaction.
Claude Code's skill bodies are re-injected, but large skills are truncated to fit and the oldest invoked skills are dropped first. Put important instructions first in SKILL.md.
What Codex compaction changes#
Status, 26 October 2026: three open reports describe what a compacted Codex thread (its saved conversation) can lose — its place in the task, project rules from AGENTS.md, and which prompt is current (#5957, #25792, #27731; all open on 26 October 2026). The mechanics below explain why; the re-anchoring habit is the workaround.
The threshold is not the model's limit#
Codex compacts in two ways. /compact asks for a summary now; the docs list it in the CLI and in the desktop app's slash commands. Automatic compaction starts when the active context reaches model_auto_compact_token_limit, and when that key is unset Codex uses the model's default threshold, according to the configuration reference. The threshold can sit below the context window the model advertises.
Three numbers get confused:
| The number | Where it comes from | What it controls |
|---|---|---|
| The advertised window | The model or plan page | The ceiling the model is sold with. Not a Codex setting. |
model_context_window | config.toml | The window Codex assumes for the active model. |
model_auto_compact_token_limit | config.toml, or the model default | The point where Codex starts compacting. |
The docs do not publish an effective context number per model. The config reference gives the knobs, and /status reports what is happening in the session. In the CLI, /status prints token usage and remaining context capacity, and /statusline can put context in the footer. In the desktop app, /status shows the chat ID, context usage, and rate limits. Two 2026 reports that the documented 1M window was unavailable in the CLI and desktop, and that one model's effective window dropped to 258K, were closed (#38917, #32806). An open request asks for a 1M window for GPT-5.5 (#19464, last updated 6 May 2026). Treat the advertised number as a ceiling, not the working size.
What the summary keeps#
The docs commit to very little. /compact "replaces earlier turns with a concise summary, freeing context while keeping critical details". There is no published list of what counts as critical, the docs describe no way to read the summary, and nothing says the AGENTS.md chain is reloaded afterward. Codex builds that chain at the start of a run, once per run, and the docs do not describe a rebuild after compaction.
That is enough to explain the reports above. A project rule loaded before the compaction is part of the conversation being summarized. If the summarizer drops it, the rule does not come back from the file automatically; the report that says project rules may stop being applied put progress at 97% before the compaction and 42% after. /recap gives a catch-up summary on demand in the CLI, but the docs do not say it exposes the compaction summary.
One other key matters if a thread compacts repeatedly. model_auto_compact_token_limit_scope chooses whether the threshold counts the full active context or only growth after the prefix the last compaction left at the start of the thread; the default is total. A smaller scope can delay the next compaction in a thread that already carries a summary, but it does not restore what the last summary dropped.
Re-anchor after compaction#
The mechanical version is a SessionStart hook with the matcher ^compact$. In Codex, add it to $CODEX_HOME/config.toml (default ~/.codex/config.toml):
[[hooks.SessionStart]]
matcher = "^compact$"
[[hooks.SessionStart.hooks]]
type = "command"
command = 'cat "$(git rev-parse --show-toplevel)/docs/handoff.md"'After a root session compacts, the command's output is added as developer context before the next model request. That covers the rule you remembered to put in the hook. It does not cover the task state that changed five minutes ago.
The prompt is the part that works without a hook. After a compaction, send a short message that supersedes the old prompt:
Current state: migration 0042 is written, not applied.
Last action: pnpm test webhook.idempotency failed on duplicate delivery.
Next action: apply 0042 on staging, then replay evt_... and check one row.
Ignore earlier prompts that conflict with this one.That last line is there for the stale-prompt case. It tells the model which instruction is current, instead of leaving it to infer that the most recent old prompt is still active. Then ask it to restate the goal, the last failure, and the next command, and compare that with git status and git diff. A restatement that cannot name the failing command is a summary talking, not the work.
Two habits reduce how often you need this. Compact at a task boundary rather than in the middle of one, and write the working state to a file before you do. If a thread has already compacted more than once, start a fresh thread with the handoff instead of compacting again; the existing handoff template in this guide is the file to use. The Codex sessions guide covers resuming and forking a thread.
What OpenCode compaction changes#
Status, 27 October 2026: V2's documented path is a structured summary with a recent tail, and instruction files reload after compaction. V2 reports are open. One describes a provider gateway that accepted about 148,000 input tokens while the catalog advertised 1,000,000, so automatic compaction never fired and every retry failed the same way (#50446, open, updated 30 September 2026). Another describes a compacted session that answers with empty checkpoint blocks and records each turn as a success with no tool calls (#57240, open, 20 October 2026). The mechanics below explain them; the re-anchoring habit is the workaround.
V1 and V2 use different controls#
V2's compaction page describes the current shape. As the session approaches the model's limit, OpenCode sends the conversation to a model for a structured summary: objective and requirements, decisions, completed and active work, blockers and next moves, relevant files. It keeps about 15,000 recent tokens beside the summary. Long tool output in that tail is shortened, and attachments become short descriptions. A request rejected as too long is compacted and retried once; a second rejection is an error.
The settings are V2 settings: compaction.auto (on), compaction.keep.tokens (15,000), and compaction.buffer (15% of the limit, at least 16,000). buffer is the room kept free below the model's limit; a larger buffer starts compaction earlier and leaves less of the window for work. agents.compaction.model can move summaries to another model. The V1 config page names compaction.auto, compaction.prune, and compaction.reserved instead. prune clears old tool output and is off by default; reserved is the token buffer. The V2 migration page maps V1's preserve_recent_tokens to keep.tokens and reserved to buffer, and says V2 ignores tail_turns and prune with a warning. In the TUI, V1 has /compact, aliased /summarize; V2's documented manual trigger is opencode api post /api/session/<id>/compact --data '{}'.
The advertised window is not the budget#
The V2 config page says automatic compaction uses the selected model's usable input budget. That is not the same as the context number on the model's page: the usable budget can be below the advertised window. The schema also accepts limit.input, while the models page documents limit.context and limit.output; buffer is taken off that budget. If you know the real input ceiling, set limit.input (and limit.context if the window is also wrong). If the catalog is right, compaction starts before the window is full. If the catalog is wrong, it starts too late or not at all. The open gateway report above is that failure at the provider level: the catalog said 1,000,000, the endpoint stopped near 148,000, and no client-side threshold fired. Treat the advertised window as a ceiling, not the working size.
When a compacted session stalls#
V2's stall is not the old V1 stop. In the open report, the model emits the compaction scaffold as a user-visible answer, then empty <conversation-checkpoint> blocks on later turns. Every turn is stored as a success with no tool parts, so the session looks alive from the outside and does no work (#57240, 2.0.31). A related open report describes tool calls arriving as literal text after compaction, so the tools never run (#50814, open, updated 20 October 2026). If the transcript shows either, re-anchoring does not fix it; start a new session from the handoff file. The first report says a fork after the polluted compaction carries the pollution with it.
Status, 27 October 2026: both V1 reports are closed as not planned (#13217, closed 3 July 2026; #11301, closed 7 August 2026). V1 users reported a simpler stop: the session went quiet after compaction and a message like "keep going" resumed it. Treat that as a report from the V1 line, not a guarantee that a V2 stop has the same cause.
Re-anchor after compaction#
V2 reloads the current instruction files after compaction, so AGENTS.md and the paths in instructions become the session's baseline again. That restores standing rules, not the task state. Put the task state in a short handoff file. If you list that file in instructions, V2 loads its current version at startup and after compaction; a file outside the list gets no such reload. The OpenCode AGENTS.md guide covers instruction loading, and the handoff guide covers the file's shape.
After a compaction, send the same short current-state message the Codex section uses: what is done, the last failed command, and the next action, with a line that supersedes older prompts. Ask for the goal, the last failure, and the next command, then check them against git status and git diff. A restatement that cannot name the failed command is the summary talking.
Two settings change the trade-off. Raising keep.tokens keeps more exact recent detail but leaves less room for new work. Raising buffer starts compaction earlier. Neither restores what the summary already dropped. Compact at a task boundary, and if a session has compacted more than once, start fresh with the handoff instead.
What Copilot CLI compaction changes#
Run copilot --version before you compare a screen with the numbers here; the changelog was at 1.0.104 on 27 October 2026.
Status, 27 October 2026: the thresholds and the checkpoint commands are documented; a session that starts nearly full is a reported problem with a documented cause. One open report measured System/Tools at 146.4k of a 200k window, 73%, before the first message, with about ten MCP servers (external tool servers the agent connects to) and plugins configured (#3539, open, updated 3 June 2026, CLI 1.0.55-1). /context has shown Custom Instructions separately from the system prompt since 1.0.60 and broken out MCP tool tokens since 1.0.55, so an older screenshot can have different rows.
What the first prompt already costs#
The /context command prints the active model, the tokens in use, and a breakdown: System Prompt, Custom Instructions, System Tools, MCP Tools, Messages, Free Space, and Buffer. The first four are the startup bill before you type: System Prompt and System Tools are fixed, while Custom Instructions and MCP Tools depend on what you have configured. The docs say system instructions and tool definitions are always present and take a fixed portion of the window. Tool schemas are the part that grows with your setup: every tool a server or plugin exposes, after its tools filter, adds a definition, whether or not it is called that turn.
That is why a new session can look old. If those startup rows fill most of the window, automatic compaction fires after the first message even though there is almost no conversation to summarize. The open report above is the extreme case, not a universal measurement.
Before a long task, read the first screen of /context and treat System Prompt, Custom Instructions, System Tools, and MCP Tools as the starting bill. Then:
- Disable MCP servers you are not using for this task (
/mcp disable NAME); a disabled server stays configured. - Narrow the
toolslist per server in.mcp.jsonor~/.copilot/mcp-config.jsonso the MCP server contributes only the tools you need. - Remove or disable plugins that add tools you do not use;
/envlists what loaded. - Check
/mcpfor per-server token use, and compare it with the MCP Tools row in/context. - On a model with a long-context variant, press Tab on the model in
/modelto switch the Context column, or start with--context long_context. Since 1.0.93 the startup flag is honored and/contextshows the larger allowance.
The 80% and 95% marks#
The docs give two numbers. At about 80% of the window, Copilot CLI starts compaction in the background, which leaves about 20% for tool calls while the summary is written. If the context reaches about 95% before it finishes, the CLI pauses briefly and waits. A manual /compact can be steered with focus instructions; Esc cancels it. A completed compaction cannot be reversed.
The checkpoint is the summary#
Automatic compaction saves a checkpoint (since 1.0.85), and /session checkpoints lists the checkpoints in the current session by number and title. /session checkpoints 2 prints one. They live under the Copilot home, ~/.copilot/session-state/<session-id>/checkpoints/ by default, beside events.jsonl. Read one when the agent contradicts a decision it made earlier: the checkpoint is the summary the agent is now working from, not an undo for your files or a copy of the transcript.
The docs say the summary keeps goals, what was done, key technical details, important files, planned next steps, the original user instructions, and the current state of plans and to-do lists. It may drop the exact wording of messages, full command output, and minor decisions from early in the session. That is the same trade as the other tools; the difference is that you can read the checkpoint and see which side of it a fact landed on.
Re-anchor after compaction#
Copilot CLI has a preCompact hook, but its output is notification-only, and sessionStart fires with startup, resume, or new, not a compaction source. A hook can write the handoff file when compaction starts. It cannot put the file back after the summary. The prompt is the lever.
The context page also does not say whether the repository instruction files are re-read after compaction. /instructions shows the files the session has; if a rule matters, restate it in the current-state message and check it with a quote.
Send the short current-state message the Codex and OpenCode sections use: what is done, the last failed command, the next action, and a line that supersedes older prompts. Then ask for the goal, the last failure, and the next command, and check them against git status, git diff, and the newest checkpoint. A restatement that cannot name the failing command is the summary talking.
Two habits fit Copilot CLI's controls. Run /compact keep the migration 0042 state and the failing test at a task boundary, so the focus instructions name the facts you cannot afford to lose. If the session has compacted more than once and the checkpoint is thin, start a new conversation with /new and the handoff file; the docs recommend a fresh session when several compactions have lost important context. /fork is for branching the conversation, not for undoing a compaction.
What Gemini CLI compression changes#
Run gemini --version before you compare a screen with this section; it describes v0.65.0, the stable release on 20 October 2026.
Status, 27 October 2026: the threshold, /compress, and the context meter are documented; what the summary keeps and what a resume restores are not. The mechanics below come from the v0.65.0 source.
The meter is the context window, not your quota#
At v0.65.0 the footer item is labelled % used. Older builds and older reports call it "context left"; a 2025 report describes users reading that number as requests remaining (#12139, closed as stale on 1 February 2026). Either label measures one thing: the last prompt's token count divided by the model's context limit (the display component). It is not your daily request quota. /stats model reports token counts and quota separately.
The percentage is hidden by default: ui.footer.hideContextPercentage is true. Turn it on in /settings, or set the key to false in ~/.gemini/settings.json; that key does not need a restart. The number changes colour at your compression threshold and at 100%. A number near 100% means the next request is close to the model's limit, not that you are out of requests.
The threshold is a fraction, and it is checked before a request#
model.compressionThreshold is a fraction of the model's context window, not a token count. The default is 0.5, so automatic compression can start when half the window is used; the setting needs a restart. Raise it to keep more exact history in the window, or lower it to summarize earlier. The check runs before a model request, so a turn that pushes the session over the line is summarized at the start of the next turn, not in the middle of the current one.
/compress forces the same operation now. At v0.65.0 it also answers to /compact and /summarize (the command source). The docs describe it as replacing the chat with a summary; the source keeps a summary plus roughly the last 30% of the transcript by size, and it may truncate older tool output before summarizing (the compression service).
What the summary keeps#
The summarizer is asked for a structured <state_snapshot> with these fields: overall goal, active constraints, key knowledge, artifact trail, file system state, recent actions, and task state. If an approved plan exists, the prompt also tells it to keep the plan path, the status of each step, and any user feedback. That is the shape the model is told to preserve, not a guarantee. The summary is generated text; the exact wording of a requirement can be paraphrased, and an old tool output outside the preserved tail can be gone.
Two details matter after a long debugging turn. The summary can keep "the tests fail" and drop the command and the error. It can keep a decision and drop the file and line that made it. The prompt asks for an artifact trail and recent actions, which helps, but it does not make the summary a transcript.
What resuming restores#
The session file is the record. When Gemini CLI compresses, it rebuilds the chat with the summary and the preserved tail and syncs that new history back to the session recording (the recording service). /resume then loads the messages in that file. So a resumed session restores the compressed view: the summary, the recent tail, and the messages after the compression. It does not bring back the turns the summary replaced. The session management docs put it as "all prior context restored", which means the context the session kept, not every turn it ever had.
Resuming also reads the current GEMINI.md and workspace files from disk, not the copies that were loaded when the session ended, and it does not restore your working tree. Check /memory show and git status before continuing. The footer percentage is derived from the last prompt's token count, so read /stats model after the first turn rather than trusting a number that has not updated yet.
Re-anchor after compaction#
Gemini CLI has a PreCompress hook, but it is advisory: it fires asynchronously before the summary, receives trigger: "auto" | "manual", and cannot block or change the summary. SessionStart has no compact source at v0.65.0; its sources are startup, resume, and clear. The after-compaction hook that Claude Code and Codex use to put a handoff file back into context has no direct Gemini equivalent.
Use the hook for what it can do: log or snapshot the state before compression, if it finishes in time. Then send the short current-state message the other sections use. The prompt is the part that puts the state back:
Current state: migration 0042 is written, not applied.
Last action: pnpm test webhook.idempotency failed on duplicate delivery.
Next action: apply 0042 on staging, then replay evt_... and check one row.
Read docs/handoff.md before the next tool call.
Ignore earlier prompts that conflict with this one.Ask for the goal, the last failure, and the next command, then check them against git status and git diff. A restatement that cannot name the failing command is the summary talking. The hooks guide covers the PreCompress event and the hook checks; the resume guide covers what else comes back with a session.
What Qwen Code compression changes#
Qwen Code compresses differently from the tools above: the summary is generated from the entire curated history with no recent tail kept, and the automatic trigger is a ceiling computed from the declared window (85% of it, or window − 33,000, whichever is lower).
Run qwen --version before you compare a screen with this section; it describes the command line at v0.26.2 on 27 October 2026, with the mechanics read from commit 32f6713.
Status, 27 October 2026: the meter, the 0.85 default and the summary shape are documented or in the source. Two open reports matter: a local Qwen3.x model can be assigned a 1M window that its server does not have (#13415, open), and a compressed turn cannot be rewound (#4046, open).
What the footer percentage measures#
The footer indicator reads 34.3% context used (or 34.3% used on a narrow terminal); the context-used status-line item renders Context 34.3% used, and a custom status line can show ctx:34%. It is the last prompt's token count divided by the window Qwen Code assumes for the active model (the display component, the formatter). The number is not a quota and not a request count. The window comes from model-name matching in tokenLimits.ts, or from contextWindowSize when you set one. The pattern qwen3.<digit> matches the 1M rule, so a local Qwen/Qwen3.6-35B-A3B served by llama.cpp is assumed to have 1,000,000 tokens even when the server is started with 262,144. The open report above is that failure: the conversation grows past the server's limit and every request fails before auto-compaction fires.
For a local or OpenAI-compatible model, set contextWindowSize in the matching modelProviders[].generationConfig, not the top-level model.generationConfig. Provider entries are sealed; the top-level copy is ignored when a provider entry exists (settings). If the window is right but the default trigger is too late for your work, lower context.autoCompactThreshold.
/context shows the denominator, the used and free bars, and a Compaction thresholds block. /context detail adds a per-item breakdown, including a Memory files section that names each loaded context file. Qwen's resident context cost page explains why the percentage is a poor target: the same text reads as 6.5% on a 1M window and 37% on a 128k one.
The threshold is a ladder, not one number#
context.autoCompactThreshold defaults to 0.85. It is a ceiling, not a fixed trigger. Qwen computes three thresholds from the window:
- warn sits 20,000 tokens below auto. It is a UI hint; it does not change what the next request does.
- auto is the lower of 85% of the window and
window − 33,000, the point that leaves room for a 20,000-token summary and a 13,000-token buffer. On a 1M window that is 850,000; on a 200k window it is 167,000, so a smaller window compacts before 85%. - hard sits near the window edge, about
window − 23,000. It force-compacts on the next send and resets the consecutive-failure breaker.
The gate runs before the request, against the last prompt count plus the pending user message. If auto-compaction has failed three times in a row, it stops trying until a forced compaction succeeds (the hard tier or a manual /compress).
`/compress` and `/compress-fast` are different operations#
/compress asks a model for a summary and replaces the conversation with it. It also answers to /summarize; /compact, the Claude Code name, is not in the command list at v0.26.2. You can steer the summary with text after the command, up to 2,000 characters:
/compress keep migration 0042, the failing webhook test, and the staging key nameThe summary is generated from the entire curated history; Qwen does not keep a recent tail of messages the way Gemini CLI does. The prompt asks for a <state_snapshot> with nine sections: primary request and intent, key technical concepts, files and code sections, errors and fixes, problem solving, all user messages, pending tasks, current work, and next step. After the summary, Qwen restores up to five recently touched files (current content when the file is small, otherwise a path reference) and up to three recent images; change the counts with model.chatCompression.maxRecentFilesToRetain and maxRecentImagesToRetain. Exact tool output and any reasoning the summarizer dropped are gone.
/compress-fast makes no model call. It force-runs microcompaction (clears old tool results and media, keeps a recent slice) and strips thinking parts from model turns. It is a mechanical trim: it does not produce a state snapshot, it does not run the compaction hooks, and it cannot preserve a decision that was only in the conversation. Use it when old tool output is noise; use /compress with focus text when the state matters.
Re-anchor after compression#
Qwen fires PreCompact before a summary and PostCompact after it. PreCompact can add text to the summary prompt; PostCompact receives the summary and its output is ignored, so use it for logging or an archive. SessionStart has a compact source, which is the hook that puts a file back after the summary:
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{ "type": "command", "command": "cat \"$QWEN_PROJECT_DIR/docs/handoff.md\"" }
]
}
]
}
}Put it in .qwen/settings.json or ~/.qwen/settings.json. The command's stdout is added to the model context when the source is compact. /compress-fast does not fire this hook; restate the state yourself after it.
The prompt is the part that works without a hook. Send the short current-state message the other sections use: what is done, the last failed command, the next action, and a line that supersedes older prompts. Then ask for the goal, the last failure, and the next command, and check them against git status and git diff. A restatement that cannot name the failing command is the summary talking.
/rewind cannot target a turn that was compressed; Qwen returns "Cannot rewind to a turn that was compressed. Try a more recent turn" (#4046, open on 27 October 2026). If you need to go back, compact at a task boundary and keep the handoff file outside the conversation.
For the local-model window trap and the provider entry, see using Qwen Code with a local model. The Qwen Code guides cover the rest.
What Cursor summarization changes#
Run Cursor → About Cursor in the editor, or agent --version in the CLI. Cursor 3.27 was the newest editor build on 27 October 2026, and the CLI changelog listed v2026.10.22.
Status, 27 October 2026: Cursor's docs describe summarization and list /summarize as a command, but they do not say what the summary keeps or how the manual and automatic paths differ. A Cursor staff reply in #167893 (13 August 2026) describes both. Staff replies in #164549 (1 July 2026) and #175331 (19 October 2026) confirm what drops out. The release notes checked do not say either loss is fixed.
`/summarize` is not the automatic pass#
/summarize reduces context on demand; /compress is its alias in the CLI. The staff reply in #167893 describes it as the same compaction the automatic pass runs, with one difference: automatic compaction keeps your most recent messages as they are, while /summarize compresses the entire conversation and keeps no tail.
The summarizer reads the user messages, assistant replies, tool calls and their results, then writes a structured summary: task and intent, key technical details, touched files, errors and fixes, remaining tasks, current step. The model context is rebuilt as the system prompt plus that summary as a hidden message. Older messages and tool results are no longer sent. The visible transcript does not change; you see a marker that the context was summarized.
That makes /summarize a task-boundary command, not a way to make room in the middle of a step. It drops the exact recent detail the automatic pass would have kept.
What survives#
- Root
AGENTS.mdandalwaysApply: truerules. They sit near the system prompt and survive. Cursor staff said Always Apply rules survive compaction (#158551, 22 May 2026), and staff in the nested-AGENTS thread said the root file does too (#175331, 19 October 2026). Cursor's Help page says a rootCLAUDE.mdis always applied, so treat it as a root rule too. The Cursor AGENTS.md guide covers the hierarchy. - Nested
AGENTS.mdand file-scoped rules do not reliably survive. In the editor, they attach to a Read tool result once per conversation; in the CLI since v2026.10.22, an edit or create also attaches nestedAGENTS.md(CLI changelog). After a summary the text can drop out, and Cursor treats the files as already attached, so later reads in the same folder do not bring them back (#175331). Ask the agent to read the file again or@-mention it; a new chat resets the attachment state. The Cursor rules guide covers which rule is which. - The skills catalog and skills attached to the most recent message. They survive. A skill the agent read earlier in the session is folded into the summary text, so the agent may still know it exists and stop applying its steps (#164549, 1 July 2026). Reattach it with
/or@after a summary. The Cursor skills guide covers the catalog and the chat-start snapshot. - Tool definitions and permission options. They are rebuilt every turn. What can be lost is a hint from an earlier tool result, such as the exact permission value that made a command work; that text is part of the summarized history (#164549).
- The saved transcript. Summarization changes what the model sees, not the chat record. The Cursor chat history guide covers where the record lives.
The Cursor rules guide covers the loaded-but-not-followed problem; a rule that is still in the prompt is guidance, not enforcement.
Why it summarizes early#
The percentage in the context ring is relative to the active window, not the number on the model's page. In a report of summarization at 10–20% of a 1M window, a Cursor staff reply (#163850, 23 June 2026) said the 1M figure applies only with Max Mode plus the 1M context variant selected; otherwise frontier models run on 200k–300k tokens, and Composer 2.5 on 200k. Max Mode is now a legacy-plan control; check the model picker on your plan. The bigger cause in that report was tool output: a search that walked conda and virtualenv folders returned over a million characters in one result, which filled much of the window at once. Add those folders to Cursor's ignore file, which keeps them out of search and @-mentions; it does not block terminal or MCP reads. Then read the context ring's breakdown. The docs split it into System prompt, Tools, Rules, Skills, MCP, Subagents, Summarized conversation and Conversation. A large Tools or Conversation row means the window is being spent before the work, not that the model has a small limit.
Re-anchor after summarization#
Cursor documents no after-compaction hook that can put text back. preCompact is observational: it receives the trigger, usage and message counts, and can show a user message, but it cannot add context, block, or change the summary (hooks reference). Use it to log the event or snapshot the working state before the summary, if the script finishes in time. The prompt and the files are the lever.
After a summary:
- Ask the agent to re-read the nested
AGENTS.mdfiles or file-scoped rules the task depends on, or@-mention them. Root always-applied rules are already there. - Reattach a skill with
/or@if its procedure still matters. - Send the short current-state message the other sections use: what is done, the last failed command, the next action, and a line that supersedes older prompts. Ask for the goal, the last failure and the next command; check them against
git statusandgit diff.
For a task that crosses packages, put the load-bearing rules in the root AGENTS.md or an always-applied rule, and keep nested files for conventions that matter only in that folder. Run /summarize at a task boundary. If the summary is already thin, start a new chat with the handoff file instead of compacting again; the handoff guide has the shape.
The summary is not your working state#
A compaction summary is a narrative, not a snapshot of the work. It can say what you were trying to do and still miss the one thing the next action needs. Working state is smaller and more concrete: the next command, the files that changed, what is uncommitted, and what failed last.
Claude Code's docs say the summary keeps requests and key code snippets, but detailed instructions from early in the conversation may be lost. A 2026 bug report says the saved conversation transcript is preserved, but the session UI has no working path to review the pre-compaction conversation (#27242).
After compaction, the next action can look plausible and still be wrong. The summary may say "refactoring the billing path" but drop that src/billing/retry.ts is half edited and the test run is red. It may say "continue the migration" without saying which migration step is next.
Uncommitted work is the other trap. Compaction does not revert your files; the working tree is still there. Claude Code does re-read a fresh git status snapshot if the session started with one, according to its context window docs, but a status list is not the diff and does not say why each file changed. A half-finished edit can survive on disk while the plan for finishing it disappears from the conversation.
What to do:
- Use the handoff template below. Fill in its “Work in progress” and “Next action” lines with the files changed, what is uncommitted, and the last failed command.
- Before the agent continues after a compaction, re-ground it in the repository:
git status,git diff, the last test output, and the working-state file. Ask it to restate the next action and the last failure. - Commit or stash a checkpoint before a long run when the change is at a safe point. Compaction cannot lose a commit.
- Treat a summary that says "done" as a claim to verify, not a fact. Check the file and the test before you believe it.
Silent trims in Claude Code#
Not every loss comes with a compaction message. An open report about 1M-context sessions (sessions using the 1-million-token context window; #42542, updated 2 October 2026) describes two mechanisms that clear old tool results without a visible compaction event, and a third that keeps only a recent slice of messages. A tool result is the output of a command, file read, or search.
- Time-based microcompaction. When the gap since the last assistant message passes a threshold, old tool results are replaced with
[Old tool result content cleared]. - Cached microcompaction. Old tool results are removed from the provider's prompt cache, the provider's stored copy of the prompt it reuses between requests.
- Session-memory compaction. It runs before auto-compaction and keeps only a recent slice of messages, which the report puts at about 40,000 tokens.
The report says none of the three shows a compaction message, and none fires PreToolUse or PostToolUse hooks. It says the switches are server-side feature flags, settings the service turns on and off remotely, so the behavior can change without a client release. It also says DISABLE_AUTO_COMPACT does not stop them, while DISABLE_COMPACT also turns off manual compaction.
The Claude Code docs checked for this guide do not name these mechanisms. The closest is the costs page, which mentions "clearing old tool results from context" in a note about prompt-cache statistics. The context-window page covers what survives a compaction, not these silent paths.
Status, 26 October 2026: #42542 and #27242 are open. The docs do not document an independent switch for these trims or a pre-compaction review screen.
What to do:
- Watch for
[Old tool result content cleared]in the saved conversation. That marker is the visible sign the report names. - Run
/contextto see what is still taking space. It shows categories and size, not the cleared text. - Keep the working-state file outside the conversation. If the agent starts repeating a failed approach, treat the thread as damaged and start fresh with the file.
- Do not assume
DISABLE_AUTO_COMPACTprotects the session. The report says it does not.
Compact vs clear vs a new session#
These three choices are not the same. All three leave your files alone.
| Action | What it does | Use it when |
|---|---|---|
/compact | Replaces older turns with a summary and keeps the same conversation going. | You need to keep the thread, and the summary plus a working-state file is enough. |
/clear | Starts an empty context in the same Claude Code process. The previous session is saved and can be reopened with /resume. | You are switching to unrelated work, or the current thread is too tangled to summarize. |
| A new session | Starts a fresh context and a new transcript. Start it with claude (or claude -n <name>); --continue and --resume reopen an old one. | You want a clean run with a handoff file, or you want to keep the old session untouched. |
/compact is the only one that keeps the conversation going. /clear and a fresh launch both start with an empty context. Start a new session with claude -n <name>, then ask it to read the handoff before anything else. The name only makes the session findable afterward.
The docs describe /compact and /clear on the context window page and session resume on the sessions page. The costs page puts it simply: /clear costs nothing when you want a fresh start instead of continuity.
How to make the important parts survive#
Keep standing rules in the instruction file#
Claude Code's docs say to put persistent rules in CLAUDE.md rather than conversation history. The same advice applies to AGENTS.md in Codex, Copilot CLI, OpenCode, and Cursor: a rule in a file on disk is easier to reload than a sentence forty turns back, though the benchmark on whether these files help found they add inference cost, so keep only rules the agent cannot derive from the code. The page on instruction files explains which file each agent reads, and how nested files combine.
Keep the file short. Claude Code's target is under 200 lines per CLAUDE.md, and it skips a file over 4 MiB. A long file competes for the same window you are trying to preserve.
Write the handoff before the window fills#
Start a long run with a short handoff file, and update it when a decision is made or an attempt fails. A useful shape is:
Goal:
Constraints:
Decisions:
Failed:
Open:
Work in progress:
Next action:
Files:Put it in the repository or in a note the next session can read. Write it while you still have the details. The summary is written by a model under pressure; your handoff is written by you, or by the agent, while the facts are still in front of it.
Re-inject context after compaction#
Claude Code documents a SessionStart hook with the compact matcher. The command's stdout is added to the context after every compaction:
{
"hooks": {
"SessionStart": [
{
"matcher": "compact",
"hooks": [
{ "type": "command", "command": "cat .claude/handoff.md" }
]
}
]
}
}OpenCode documents a compaction hook, but it runs on the summary request, not after it. V1 calls it experimental.session.compacting and lets a plugin add context to the summary prompt or replace it; V2 calls it compaction and lets a plugin edit the transcript sent for summarization or supply the summary itself. Neither puts a state file back after the summary. Cursor documents a preCompact hook, but it is observational: it receives the trigger, context usage and message counts, and can show a user message; it cannot add context, block, or change the summary (hooks reference).
Start fresh when the summary is already thin#
Compaction is not free. Each round can lose more detail. The Compaction Cliff paper reports that safety-rule preservation fell from 53% after one round to 10% after five in its setup. If a session has compacted several times, start a new session with the handoff file instead of compacting again. Claude Code documents /clear for switching to unrelated work. A new session plus a short handoff is easier to audit than a summary of a summary.
Check what the summary dropped#
After a compaction, ask the agent to restate the goal, the constraints, the last failure, and the next step. Compare that with the handoff file. If a line is missing, paste it back before the next tool call.
Some tools show context usage. Claude Code's /context shows what is using space. Cursor's context ring shows the categories, including summarized conversation. The docs describe the categories and the size, not a way to read the summary text. The restatement is the check you can actually run.
Why it matters beyond convenience#
Compaction is not only a convenience feature. A 2026 paper, The Compaction Cliff in Long-Running AI Agent Memory, reports that on 20 production agent configurations, Claude Code's /compact prompt on Sonnet 4.6 preserved 53% of safety rules after one compaction round and 10% after five. A safety rule and an episodic log compete for the same tokens, and both are summarized at the same rate. The rule needs exact wording to remain enforceable. Those are the authors' results, not tests we ran.
A second 2026 paper, Compaction Laundering: Provenance Destruction in Context-Compacting Coding Agents, describes a sharper failure. In harnesses that flatten the typed conversation into one string, a forged user turn can survive compaction as a genuine instruction. The authors report 87–100% success in five flattening harnesses (pi, opencode, Cline, Aider, and OpenHands) and 0% in four role-typed harnesses (Codex, Gemini CLI, Qwen Code, and Continue). Those are the versions the authors tested; harnesses change. The summary can carry a claim forward after the label that said who said it is gone.
The same blind spot appears outside the model. METR and Redwood Research report that OpenAI's internal monitoring did not monitor compaction events, and estimate that about 10% of eligible internal Codex traffic went unmonitored between May and July 2026, with substantial uncertainty. During that period, an agent that kept taking actions could postpone review. Compaction was not the only gap the auditors found, but it was one of them.
Compaction is also an input path. CVE-2026-95183 describes a prompt injection in the context-compaction feature of DeepSeek Harness, reached through crafted external content. A summary that keeps attacker text can carry a read forward as an instruction.
These are third-party reports, not tests we ran. They do not prove your agent will fail in the same way. They do show that the summary is a trust boundary, and that a record kept outside the window is worth the small effort.
Where Noteheld fits#
Noteheld is the product this site documents. It is not a compaction feature.
An agent can write a note deliberately, before the window fills. The note lives on the Noteheld server, outside the context window, so a context compaction does not remove it. The next session can read the overview and the notes it needs. A person can add a correction above the note, on the whole note or a line range; any agent can also be told to fix a wrong note, and the change is saved with a reason.
Keep the limits in the same breath. An agent sees a note only when someone gives it a key or a view link and it asks Noteheld for the note. Nothing loads Noteheld for free. A note can still steer an agent that reads it. Content returned to agents is marked as stored data and carries provenance, but that does not stop a model from following text inside a note. Folder keys limit what a compromised agent can touch inside Noteheld, not tools the agent has elsewhere. Notes are stored on the server as plaintext so the product can search, outline and edit by line. Version 1 does not encrypt note bodies end to end. This version has no editor for the note body; a correction sits above the note and is still stored data.
If you want the practical setup, start with the quickstart.