Advanced (Updated: 7/22/2026)

Claude Code Context Management: A Practical Guide to /context, /compact, and /clear

Keep Claude Code focused with /context, /compact, /clear, memory, usage checks, and reliable handoffs.

Claude Code Context Management: A Practical Guide to /context, /compact, and /clear

You start a Claude Code session with a clear request. An hour later, Claude rereads files it already inspected, forgets a decision from twenty messages ago, or follows an outdated instruction instead of the correction you just gave it. For a beginner, this can look as if the model suddenly became less capable.

The more common problem is a crowded context window. The conversation, file contents, command output, project instructions, tool definitions, and Claude’s own replies all compete for a limited working area. Once that area is full of old investigation and noisy logs, the important facts are harder to keep prominent.

Context management is therefore not a trick for saving a few tokens. It is the routine of deciding what Claude needs for the current task, what should become durable project guidance, what can be summarized, and when the conversation should end. This guide gives you that routine without assuming you already understand tokens, memory files, or session storage.

Key takeaways

  • Run /context to inspect what is using the current window before guessing at the cause of a long session.
  • Use /compact when the task is still the same but the conversation is too large. Give it focus instructions when certain decisions must remain prominent.
  • Use /clear when you are moving to an unrelated task. The old conversation is saved and can be resumed; the new conversation starts with empty conversational context and reloads project memory.
  • Use /memory to inspect and edit persistent instructions and auto memory. Use /context, not /memory, to confirm which memory files actually loaded.
  • Use /usage for session cost, plan limits, and activity details. /cost is an alias, and /stats is an alias that opens the Stats tab.
  • Put durable rules in project files and leave a short verification receipt before compacting or handing work to another session.
flowchart TD
  A["The session starts to drift"] --> B["Run /context"]
  B --> C{"Continue the same task?"}
  C -->|Yes| D["Write a handoff receipt"]
  D --> E["Run /compact and continue"]
  C -->|No| F["Run /clear and start a new conversation"]

The context window is Claude’s working desk

A context window is the information Claude can consider during the current turn. Think of it as a working desk rather than permanent storage. A clean desk might contain the task, two relevant files, a short error message, and the acceptance criteria. A crowded desk might contain several abandoned approaches, complete build logs, unrelated research, duplicate file reads, and rules that contradict one another.

The desk fills from more places than the visible chat:

What uses contextHow it becomes noisyBetter operating habit
Conversation historySide questions and superseded decisions remain in viewSeparate unrelated tasks and record the current decision
File readsWhole directories or large generated files are loadedSearch first, then read only relevant files or ranges
Tool resultsRepeated test output and long logs accumulateKeep the root-cause lines and the final result
CLAUDE.md and rulesBroad, duplicated, or conflicting instructions load repeatedlyKeep always-on rules short and move narrow procedures to scoped files
Skills and tool descriptionsEnabled capabilities consume startup contextKeep only the capabilities needed for the work

Claude Code can compact automatically as the window approaches its limit. That prevents the session from simply stopping, but automatic compaction still has to decide what matters. A focused manual compaction before a major phase change gives it a better target.

What each command actually does

The commands overlap in appearance, but they solve different problems. Enter them at the start of a message in an interactive Claude Code session.

/context: inspect the current window

/context displays current context usage as a colored grid and includes optimization suggestions for heavy tools, memory bloat, and capacity warnings. Use /context all when you want the expanded per-item breakdown.

/context
/context all

Run it at the start of a long task to establish a baseline, after a large investigation to see what it added, and before /compact to decide what the summary should emphasize. It is a diagnostic view, not a cleanup command; looking at the grid does not remove anything.

/compact [instructions]: summarize and continue

/compact replaces the conversation history with a structured summary so the same conversation can continue with more room. The optional text after the command tells the summarizer which information deserves priority.

/compact preserve the accepted API contract, changed files, failing test, commands already run, and next action

Use it when the objective is unchanged: for example, the same authentication bug is still being fixed, but discovery produced a long transcript. Do not rely on the summary to preserve every sentence. Important rules should already live in CLAUDE.md, a specification, or a handoff note.

/clear [name]: start a different conversation

/clear starts a new conversation with empty conversational context. You can optionally provide a name for the previous conversation. Claude Code continues to retain project memory, and the previous conversation remains saved for /resume.

/clear auth-fix-complete

Use it when the next request has a different objective, files, or decision history. A practical rule is simple: if the next task would be clearer to a teammate who had not read the previous transcript, clear the conversation.

The prior work is not deleted. Interactive sessions are stored continuously, so you can return with /resume, claude --resume, or claude --continue for the most recent session in the directory.

/memory: inspect persistent guidance

/memory lists CLAUDE.md and CLAUDE.local.md locations, lets you open or create those files, shows auto-memory entries, and lets you toggle auto memory. It answers, “Where should this reusable information live?”

/memory

It does not prove that every listed file is active in the current context. Use /context and inspect the Memory files section for that. Project CLAUDE.md is team guidance that can be committed; auto memory is Claude-maintained, repository-specific information stored locally and shared across worktrees of that repository, not across machines.

/usage, /cost, and /stats: inspect usage rather than context

/usage shows session cost, plan usage limits, and activity statistics. On supported subscription plans, it also breaks down use by skills, subagents, plugins, and MCP servers. /cost is an alias for /usage. /stats is also an alias and opens the Stats tab.

/usage
/cost
/stats

These commands answer a different question from /context. Usage tells you about consumption and limits; context tells you what currently occupies the model’s working window. Clearing or compacting a conversation does not reverse usage already incurred.

Decide the context budget before starting

Do not begin a large task with “read the whole repository and fix it.” Give Claude a small task brief with an objective, scope, exclusions, completion criteria, and verification commands. This makes the first file reads intentional and gives compaction a stable structure later.

## Task brief
- Objective: Fix the expired-session redirect loop.
- In scope: src/auth/, tests/auth/session.test.ts
- Out of scope: UI redesign and identity-provider migration
- Done when: expired sessions redirect once to /login and the regression test passes
- Verify with: npm test -- tests/auth/session.test.ts
- Human approval required for: changing cookie lifetime or public API behavior

Search narrowly before loading files. The following commands are examples you can paste into a shell and adapt to your repository:

rg -n "expired session|redirect loop|set-cookie" src tests
git diff --stat
git status --short
npm test -- tests/auth/session.test.ts

The sequence matters. rg identifies likely files, git diff --stat and git status reveal existing work that must not be overwritten, and the focused test provides a measurable finish line. Claude then needs a few relevant artifacts instead of an entire repository snapshot.

Leave a handoff receipt before compaction

Before /compact, /clear, or a session handoff, write a short receipt. This is not a second transcript. It is the minimum state another person or agent needs to continue without repeating discovery.

## Handoff receipt
- Objective:
- Current diagnosis:
- Decisions already accepted:
- Files changed:
- Commands run and results:
- Uncommitted user changes to preserve:
- Remaining risk:
- Next action:

Save the receipt in a project document when it should be shared, or paste the completed version into the focus instruction for /compact. Include outcomes, not raw output. “Focused test fails at session.test.ts:84 because two redirects are emitted” is useful; two hundred lines of repeated stack trace are not.

What survives compaction

Compaction does not treat every type of information equally. Current Claude Code behavior depends on how an instruction entered context:

MechanismBehavior after /compact
System prompt and output styleRemain unchanged because they are not conversation history
Project-root CLAUDE.md and unscoped rulesRe-injected from disk
Auto memoryRe-injected from disk
Rules with paths: frontmatterAbsent until Claude reads a matching file again
Nested CLAUDE.md in a subdirectoryAbsent until Claude reads a file in that subdirectory again
Invoked skill bodiesRe-injected within the documented per-skill and total limits
HooksContinue to run as code; they are not conversational context

The fragile category is information stated only in chat. It may be represented in the summary, but fine detail can be dropped. If Claude must follow a rule every time, put it in the project-root CLAUDE.md or another appropriate persistent file. If a rule applies only to one directory, keep it scoped, but expect it to return only after a matching file is read.

You can also guide compaction from CLAUDE.md:

# CLAUDE.md

## Compact instructions
- Preserve the current objective, accepted decisions, and out-of-scope areas.
- Preserve changed files, verification commands, test results, and blockers.
- Keep only log lines that explain the root cause.
- Preserve uncommitted user changes and the next safe action.

Keep this section concise. CLAUDE.md itself consumes context at the start of every conversation, so turning it into a complete project manual creates the problem it is meant to solve.

Human decisions and agent responsibilities

Good context management is partly a division of responsibility. Claude can inspect, summarize, search, test, and propose. A human still owns decisions whose consequences cannot be inferred safely from the repository.

Claude Code can ownA human should own
Finding relevant files and reducing a long log to root-cause evidenceChoosing the business objective and acceptable tradeoffs
Reporting context pressure and suggesting when to compactDeciding whether two tasks are truly related
Writing a handoff receipt from observed workApproving destructive operations, credential use, or production changes
Running agreed verification commandsAccepting changes to security policy, public behavior, or data retention
Updating a documented rule after explicit approvalResolving contradictory requirements from stakeholders

Do not ask the agent to decide what must never be lost and then leave that decision only inside the same crowded conversation. The human identifies durable constraints; the agent records them in the agreed location and verifies that they load.

Four concrete use cases

Use case 1: a multi-file authentication refactor

Situation: Research touches middleware, cookie utilities, integration tests, and deployment settings. Loading every file and every failed test into one conversation makes implementation harder.

Agent scope: Use search to map the authentication path, delegate broad documentation research to a subagent, and return a short decision summary to the implementation conversation. Keep only the selected contract, target files, and focused test output in the main context.

Human checkpoint: Approve changes to cookie lifetime, logout behavior, or compatibility guarantees. Those are product and security decisions, not cleanup details.

Sequence: Start with the task brief, run /context after discovery, write the accepted design into the handoff receipt, then use /compact focus on the accepted auth contract and regression test before editing.

Use case 2: debugging a failing deployment

Situation: Several retries produce nearly identical logs. The one useful line is buried among package installation output and warnings.

Agent scope: Compare attempts, isolate the first causal error, record the environment and exact failing command, and discard duplicate output from the working summary.

Human checkpoint: Approve credential changes, provider configuration, or a rollback. The agent may diagnose these areas but should not silently broaden access or change production policy.

Sequence: Preserve the failing command and root-cause line in a receipt. Compact if the same incident continues. Clear only after the deployment is verified or when moving to an unrelated feature.

Use case 3: producing and reviewing a technical article

Situation: Source research, editorial rules, code verification, translation notes, and rendered-page checks can overwhelm the writing conversation.

Agent scope: Keep source notes in a research file, durable editorial requirements in CLAUDE.md, and the final article in MDX. Return only confirmed facts and unresolved questions from research. Verify code and links before the publishing pass.

Human checkpoint: Choose the audience, commercial promise, and primary call to action. The agent can improve wording, but it should not invent experience, benchmarks, or customer results.

Sequence: Separate research from writing, compact around the approved outline, and leave the slug, locale, changed files, checks, and deployment state in the handoff receipt.

Use case 4: switching from a bug fix to a new feature

Situation: The bug fix is complete, but the same terminal remains open and the next prompt asks for an unrelated dashboard feature.

Agent scope: Report the final diff and test result, then suggest a clean task boundary.

Human checkpoint: Confirm that no follow-up from the bug fix belongs in the next task.

Sequence: Name or record the finished session, run /clear bug-fix-complete, and start the dashboard work with a new brief. If a detail is needed later, use /resume instead of carrying the entire old conversation into the new feature.

Concrete pitfalls and fixes

Pitfall 1: treating /compact as perfect memory

A compacted summary is selective. A minor constraint mentioned once may disappear.

Fix: Put durable rules in CLAUDE.md or a specification, and include accepted decisions in the handoff receipt before compacting.

Pitfall 2: using /clear to solve a still-active task

Clearing too early removes the active conversational working set. You may spend time reconstructing the same diagnosis.

Fix: If the objective and acceptance test are unchanged, compact with focus instructions. Clear when the task boundary is real.

Pitfall 3: assuming /memory shows what loaded

/memory is an editor and browser for persistent files. Nested files and path-scoped rules may not yet be active.

Fix: Run /context and inspect Memory files. Read a matching file when a scoped rule needs to load again after compaction.

Pitfall 4: putting enforcement rules only in CLAUDE.md

CLAUDE.md is contextual guidance, not a hard security boundary. Vague or conflicting instructions may be followed inconsistently.

Fix: Use permissions and hooks for actions that must be blocked or validated. Keep CLAUDE.md for concise workflow guidance and project conventions.

Pitfall 5: using auto memory as team documentation

Auto memory is machine-local. It is shared across worktrees of the same repository, but not automatically across teammates’ machines or cloud environments.

Fix: Move shared conventions into committed project CLAUDE.md, rules, or docs. Reserve auto memory for local preferences and repeated learnings.

Pitfall 6: confusing usage with available context

/usage can show cost and limits while /context shows a crowded or clean working window. They are related operationally but are not the same measurement.

Fix: Use /context to decide whether to narrow, delegate, compact, or clear. Use /usage to monitor consumption and plan limits.

Where Obsidian and project files fit

Not every useful note belongs in Claude’s always-loaded memory. A note system such as Obsidian is better for long research, alternative ideas, meeting notes, and material you may use later. The repository is better for shared instructions, specifications, handoffs, and published work.

LocationPut this there
Project CLAUDE.mdShort rules needed in most sessions
.claude/rules/Instructions that apply to a file type or path
Project docsShared decisions, specifications, and handoff receipts
ObsidianLong research, hypotheses, source notes, and idea backlog
Auto memoryLocal preferences and recurring discoveries

This separation keeps startup context small without losing knowledge. For related workflows, see the CLAUDE.md best-practices guide, token optimization guide, and Claude Code with Obsidian guide.

A simple operating routine

Use this five-step loop until it becomes automatic:

  1. Brief: State the objective, scope, exclusions, completion test, and human approvals.
  2. Narrow: Search first and load only the files and output needed for the next decision.
  3. Inspect: Run /context after substantial discovery or when Claude begins repeating work.
  4. Record: Write the accepted decisions, changed files, verification result, and next action.
  5. Choose: Use /compact for the same task, /clear for a new task, and /resume when returning to saved work.

If you want a reusable set of prompts and operating templates for this workflow, use the Claude Code practical prompt guide.

Official references

What we verified

For this revision, we checked the command names and current alias behavior against the official commands reference: /cost and /stats both route to /usage, with /stats opening the Stats tab. We also checked the official context-window table before describing what is re-injected after compaction and what waits for a matching file read. Finally, we confirmed in the sessions documentation that /clear starts a new conversation without deleting the previous saved conversation, and that the earlier work can be reopened with the resume commands. The shell snippets and Markdown receipts above are copy-paste templates; repository-specific paths and test commands still need to be adapted to the project you are working in.

#claude-code #context management #token optimization #productivity
Free

Free PDF: Claude Code Cheatsheet

Enter your email and download the one-page Claude Code cheatsheet for commands, review habits, and safe workflows.

We handle your data with care and never send spam.

Level up your Claude Code workflow

Start with the free PDF, use Gumroad guides when you need repeatable workflows, and book consultation when rollout or revenue paths need human judgment.

Masa

About the Author

Masa

Engineer focused on practical Claude Code workflows. Runs claudecode-lab.com, a 10-language technical media site.