Claude Code Context Compaction

What happens when the context window fills, why it breaks overnight agent runs, and how to keep your agents alive through it automatically. Updated July 2026.

Direct Answer

Claude Code context compaction is the automatic process by which Claude Code summarizes and replaces the full conversation history when the context window approaches its token limit — allowing the agent to continue without crashing. The compaction is automatic and not configurable; it discards raw detail in favor of a high-level summary, which can cause an unattended agent to lose task state, miss the resume dialog that follows, and go off-track without any human noticing.

What Happens During Compaction

Every Claude Code session runs inside a context window — a fixed-size buffer that holds the entire conversation: your initial prompt, every tool call, every file read, every code diff, and every response. For Claude Sonnet 4 and Opus 4, this window is 200,000 tokens. That sounds large, but a real engineering session fills it fast.

A typical context-heavy session might include:

An aggressive overnight run that opens many files and executes many shell commands can hit 200k tokens in 2–4 hours. When the usage crosses a threshold (typically around 90–95% of the window), Claude Code triggers compaction automatically.

What compaction actually does:

  1. Summarization: Claude generates a condensed narrative of the entire conversation — the goals, the decisions made, the files touched, the current state of the task.
  2. Replacement: The full conversation history is discarded and replaced with the summary as a single synthetic “human” turn at the start of a fresh context.
  3. Continuation: The agent resumes from the summary, as if that summary were its entire prior history.

The net effect: the context window goes from 90%+ full to nearly empty. The agent can keep running. But the raw history is gone.

# What you see in the terminal during compaction
Context window is getting long. Compacting context...
⠸ Compacting 187,432 tokens → 12,840 tokens...
✓ Context compacted. Continuing task.

Compaction is not a configurable feature. There is no flag to disable it, increase the threshold, or change the summary strategy. It is a built-in survival mechanism, not an opt-in tool.

Why It Breaks Overnight Runs

For interactive sessions, compaction is largely invisible — you’re watching the terminal and can course-correct if the agent seems confused. For unattended overnight runs, compaction introduces three distinct failure modes.

1. The Resume Dialog

After compaction — and especially after a restart or crash — Claude Code sometimes presents an interactive resume prompt:

Would you like to resume this session?
  1. Yes (continue from last state)
  2. No (start fresh)
> _

An unattended agent cannot answer this prompt. It simply blocks. There is no timeout, no error message, no process exit. The session appears to be “running” from the outside (the process is alive, the tmux pane shows content) but it is doing nothing. If you queue tasks before bed and check in the morning, you find the agent frozen exactly where it was when the dialog appeared — which could be 30 minutes into an 8-hour window.

2. Lost Task State

Compaction is a lossy summarization. The narrative captures:

But it typically discards:

After compaction, the agent continues — but with a compressed map, not the territory. If it was halfway through a multi-step refactor that depended on a precise error message seen 50,000 tokens ago, it may regenerate a different fix, or skip the step entirely because the summary said “error was addressed” when it was only identified.

3. Context Drift

Even when the summary is accurate, the agent’s behavior can shift subtly. The summary is generated by a model interpreting what was “important” — which may not match what your task required. A constraint like “keep all changes backwards-compatible” stated at session start may be compressed into a single bullet that does not carry the same weight in the agent’s next action as it did when it was a fresh explicit instruction.

Context drift is insidious because the agent is still running, still producing output, and still looks healthy. The deviation from intent is gradual and only visible when you review the output.

How to Detect It

There are several signals that context compaction has occurred in a running session.

Terminal Output

The most direct signal is the compaction log line itself. Claude Code prints a visible message when compaction fires:

Context window is getting long. Compacting context...
✓ Context compacted. Continuing task.

In a tmux session you can scan for this by reviewing the scrollback buffer. If you’re logging session output to a file, grep -i compact will surface all compaction events with their timestamps.

Behavioral Signals

If you don’t have the terminal log, behavioral clues include:

Token Count

If you have structured (JSON) output enabled, each Claude Code message includes a usage field with input token counts. A sudden drop from 180k tokens to 12k tokens between consecutive turns is a compaction event.

# Before compaction
{"usage":{"input_tokens":183244,"output_tokens":412,...}}

# After compaction (same session, next turn)
{"usage":{"input_tokens":13108,"output_tokens":388,...}}

How amux Handles It Automatically

amux is an open-source multi-agent orchestration layer that wraps Claude Code (and Codex CLI, Gemini CLI) sessions in a self-healing watchdog. It was built specifically to make overnight, unattended runs reliable — and context compaction is one of the core failure modes it addresses.

Resume Dialog Detection (NEEDS INPUT State)

The amux watchdog continuously scans each session’s terminal output for the resume dialog pattern. When it detects the prompt, it classifies the session as NEEDS INPUT and immediately sends the confirmation keypress to continue. The session never stalls.

This detection loop runs every few seconds per session and handles multiple dialog patterns — not just the post-compaction resume prompt, but any interactive confirmation that Claude Code may surface during an unattended run.

# amux session states visible in the dashboard
running     → agent is actively working
needs_input → watchdog detected a blocking prompt, auto-answering
idle        → agent completed its task, waiting
crashed     → process exited unexpectedly, watchdog will restart

Compaction Event Logging

When amux detects a compaction event in the session output, it logs it in the session timeline with a timestamp and the before/after token counts. This gives you a precise audit trail: you can see exactly when compaction happened, how much context was lost, and correlate that with any behavioral changes in the session output immediately after.

The timeline is visible in the amux dashboard and queryable via the REST API, so you can build monitoring alerts on top of it — for example, a push notification to your phone if compaction occurs more than twice in one session (a sign that the task scope is too large for the context window).

The Hibernate Fix: Preserving Solo Overnight Runs

An earlier version of amux had an auto-stop behavior: idle sessions would be stopped to save resources. This was correct for multi-agent fleet scenarios but broke solo overnight runs — an agent that had just compacted and was briefly idle between tool calls could be incorrectly classified as “done” and stopped.

The hibernate fix (shipped in commit f727de6) changed this logic: amux now only auto-stops idle sessions when multiple sessions are running concurrently. A solo overnight run — one agent, one task — is never auto-stopped regardless of idle time. The agent can pause mid-task, sit briefly idle after compaction, and resume without interference.

amux Steering: Injecting Context Reminders Mid-Run

Because compaction can cause context drift, amux supports “steering” — injecting a message into a running session mid-task. If you notice (via the phone alert or dashboard) that an agent has drifted after compaction, you can send a correction without stopping the session:

# Send a steering message to a running session
amux send my-session "Reminder: do not modify files under /legacy/. \
  Current priority is finishing the auth migration in src/auth/."

The message is injected into the agent’s input, re-grounding it without losing the post-compaction progress already made.

Best Practices

Practice Why It Helps How
Commit early and often Compaction loses in-memory task state, but git history is permanent. If the agent commits after every logical step, you can always see what was actually done — independent of what the summary thinks was done. Instruct the agent in your initial prompt or CLAUDE.md: “Commit after completing each subtask.”
Write constraints to CLAUDE.md CLAUDE.md is read at session start and injected at the beginning of the context on every new turn. Constraints in CLAUDE.md survive compaction because they are re-injected, not summarized. Move your “do not touch X” and “always use Y pattern” instructions from the initial prompt into the project’s CLAUDE.md file.
Break large tasks into sessions A task that fits in one context window (roughly <150k tokens of history) will never compact. Decompose large multi-day tasks into smaller sessions, each with a clear handoff artifact (a git branch, a written spec, a commit message). Use amux to queue multiple sessions, each scoped to a single subtask, rather than one mega-session.
Use amux steering for post-compaction correction If you’re monitoring via the amux phone alert and notice a compaction event, a quick steering message re-grounds the agent before it drifts far. amux send <session> "After compaction reminder: ..."
Log session output to a file The terminal scrollback buffer is finite. Writing session output to a log file lets you grep for compaction events after the fact and reconstruct exactly what the agent did before and after. Configure tmux pipe-pane or redirect stdout: claude ... 2>&1 | tee session.log
Scope file reads aggressively The fastest way to fill the context window is reading entire large files when only a few functions are relevant. The longer the context, the sooner compaction fires. Instruct the agent: “Read only the specific functions you need, not entire files. Use grep to locate the relevant section first.”
amux handles context compaction automatically (304★ GitHub)
Self-healing watchdog catches the resume dialog, logs compaction events, and keeps your overnight run alive. Open source, single Python file.
View on GitHub ★

FAQ

What is Claude Code context compaction?

Context compaction is Claude Code’s automatic response to a full context window. When the running conversation — tool calls, file reads, code edits, and messages — approaches the model’s token limit, Claude Code automatically summarizes the entire conversation into a compact representation and replaces the full history with that summary. The agent then continues from the summary rather than the raw history. This happens automatically — there is no flag to disable it and no user prompt before it occurs.

Does context compaction lose data?

Compaction is a lossy summarization. The summary captures the high-level narrative — what tasks were done, what the current goal is — but discards the raw detail: exact file content that was read, precise error messages from tool calls, inline diffs, and intermediate reasoning steps. If the agent was mid-task and relied on an exact value from a prior tool call (a function signature, an error code, a file line number), that value may not survive compaction verbatim. For simple sequential tasks the summary is usually sufficient; for complex multi-file refactors the loss of detail is where context drift starts.

Why does context compaction break overnight runs?

Three reasons. First, the resume dialog: after compaction (or a restart), Claude Code sometimes presents an interactive prompt asking whether to resume the previous session. An unattended agent cannot click this — it blocks silently with no timeout. Second, task state loss: complex tasks that depended on exact tool-call results accumulated earlier in the session may go off-track once those details are summarized away. Third, context drift: the compacted summary describes what happened, but the agent’s next action is generated from that summary, not the original instructions — it can subtly shift priority or forget constraints stated early in the session.

How can I tell when context compaction happened?

In the terminal output you will see a line that reads something like: “Context window is getting long. Compacting context…” followed by a spinner, then “Compacted X tokens → Y tokens”. In amux, compaction events are logged in the session timeline with a timestamp so you can see exactly when they occurred and how much was compressed. If the agent’s behavior suddenly changes tone or seems to forget an earlier constraint, check the timeline for a compaction event near that point.

How does amux handle the resume dialog after compaction?

amux’s watchdog continuously scans each session’s terminal output for the resume dialog pattern. When it detects the dialog, it automatically sends the appropriate keypress to confirm continuation — the session never stalls. This NEEDS INPUT detection is built into the core watchdog loop and applies to all sessions, not just ones that have compacted. The watchdog fires within seconds of the dialog appearing, so overnight runs continue uninterrupted.