Optimize Token Usage in Claude Code
Cut Claude Code token costs 30-70% with caching, compression, and subagents.
Introduction
30 Second Summary
Every message you send to Claude Code costs tokens. Some users burn through their limits 3-5x faster than others on identical tasks, purely because of how their environment is configured.
In this project, you will optimize your Claude Code setup to reduce token waste across every session. You'll configure ignore files, install compression tools, write custom skills, and tune auto-compaction so your environment compounds savings automatically.
What You'll Build
A fully optimized Claude Code token configuration stack that minimizes waste on every single interaction.
By the end of this project, you'll have:
- An optimized CLAUDE.md file with only behaviour-changing rules, staying under 500 tokens and structured for prompt caching.
- A .claudeignore file and Caveman mode installed to cut both input and output token usage with real per-prompt metrics.
- A custom context-mode skill and tuned auto-compaction settings that keep sessions lean and high-quality.
- Secret Mission: Build a Haiku-routed exploration subagent that isolates cheap research from your main context window.
Are there any prerequisites?
You need an active Claude Code subscription (Pro, Max, or API) and basic familiarity with using Claude Code for coding tasks. You should also have a macOS terminal available and a text editor like Cursor or VS Code.
Before We Start
Before optimizing anything, you need a baseline to measure against. Without knowing your current token usage, cache hit rate, and CLAUDE.md size, you won't be able to prove that your changes actually helped.
In this step, you'll confirm your tools are working, start a Claude Code session in a real project, and capture the numbers you'll compare against later.
In this step, get ready to:
- Verify Claude Code and Node.js are installed and accessible.
- Take a baseline /cost snapshot in a Claude Code session.
- Check your current CLAUDE.md line count.
Verify Claude Code and Node.js
Claude Code is the AI coding assistant you'll be optimizing. Node.js is required later to install Caveman, a token-compression tool.
- Open your terminal. Press Cmd+Space (macOS) or the Windows key (Windows) to open your search bar.
- Type Terminal and press Enter to open it.
- Confirm Claude Code is installed by running this command:
claude --version
You should see a version number printed in the terminal.
Command not found?
If claude is not recognized, install it by running:
npm install -g @anthropic-ai/claude-code
After installation completes, run claude to authenticate and follow the login prompts. Then retry claude --version.
Help me install Claude Code on my machine.
- Check your Node.js version by running this command:
node --version
✔️ I see version 18 or higher
Your Node.js version is ready. You can move on to the next substep.
ⓧ I see an older version
You have Node.js installed but it's below version 18. Upgrade it by running these commands:
brew update
brew upgrade node
After the upgrade finishes, verify by running node --version again. You should now see v18 or higher.
Still seeing the old version?
If node --version still reports an old version after upgrading, you may have multiple Node.js installations. The old one earlier in your PATH is taking priority over the Homebrew-managed version.
Try closing and reopening your terminal, then checking the version again. If the problem persists, run which node to see which binary is being used.
Help me resolve my Node.js version conflict on macOS.
ⓧ Command not found
Node.js is not installed yet. Install it by running this command:
brew install node
This installs the latest Node.js (which is well above version 18). After installation completes, verify by running:
node --version
You should see a version number starting with v18 or higher.
Brew not found either?
If brew is not recognized, you need to install Homebrew first. Visit brew.sh and follow the installation instructions for macOS. Then come back and run brew install node.
Help me install Homebrew and Node.js on my Mac.
Open a Claude Code session in a real project
To get meaningful baseline numbers, you need to measure in a project you actively work on. An empty folder would give you a zero-token baseline that tells you nothing useful.
- Navigate to a project you actively work on (one with a CLAUDE.md already, ideally) by running:
cd [[PROJECT_PATH="path/to/your/active/project"]]
- Start a Claude Code session by running:
claude
Claude Code launches and you should see its interactive prompt ready for input.
- Take a baseline cost snapshot by typing this inside your Claude Code session:
/cost
This displays your current session's token usage and cache hit rate percentage. Note down the cache hit rate. This is the number you'll improve throughout the project.
What is the cache hit rate?
Claude Code uses prompt caching to avoid re-processing your CLAUDE.md and system prompt on every message. The cache hit rate tells you what percentage of input tokens came from cache (cheap) versus being processed fresh (expensive).
A higher cache hit rate means you're paying less per message. Your target by the end of this project is above 40%.
Check your current CLAUDE.md
The CLAUDE.md file loads into every single session. Every line in it is a token tax you pay on every interaction. Knowing its current size tells you how much room there is to optimize.
- Open a new terminal tab (Cmd+T in Terminal on macOS).
- Navigate to the same project directory and check your CLAUDE.md line count by running:
wc -l CLAUDE.md
You should see a number followed by the filename. Note this number down.
What if I don't have a CLAUDE.md?
If you see an error like "No such file or directory", you don't have a CLAUDE.md yet. Switch back to your Claude Code session and run /init to generate a starter file.
Then come back to this terminal tab and run wc -l CLAUDE.md again to get the line count.
💡 Over 200 lines means big savings ahead
The official Anthropic documentation recommends keeping CLAUDE.md under 200 lines per file. Longer files consume more context and reduce adherence to your rules. If yours is above 200 lines, you'll see significant improvements in the next step.
You now have a clear baseline. Next up, you'll make the single highest-impact change: slimming down your CLAUDE.md to stop paying unnecessary token tax on every message.
Set Up Your Environment
You can't optimize what you haven't measured. Before making any changes, you need a clear picture of how your Claude Code environment is performing right now.
In this step, you'll verify your tools are ready, start a session inside a real project, and capture the baseline metrics you'll compare against at the end.
In this step, get ready to:
- Verify Claude Code and Node.js are installed and accessible.
- Open a Claude Code session and record your baseline token metrics.
- Check your current CLAUDE.md size to gauge optimization potential.
Verify Claude Code and Node.js
Both Claude Code and Node.js need to be installed before you can proceed. Node.js is required for installing Caveman later in the project.
- Confirm Claude Code is installed by running this command:
claude --version
You should see a version number printed in your terminal.
- Confirm Node.js is installed by running:
node --version
You should see a version number of v18 or higher (e.g. v22.4.0).
Command not found?
If claude is not recognized, install Claude Code by running:
npm install -g @anthropic-ai/claude-code
Then run claude and follow the login prompts to authenticate with your account.
If node is not found or shows a version below 18, install the latest version by running:
brew install node
After installing, run node --version again to confirm. Help me troubleshoot my Claude Code or Node.js installation
Get a project to optimize
The optimization techniques in this project work best when tested against a real codebase with a bloated CLAUDE.md you can trim. You can use our demo repo (a React music app with a deliberately oversized 342-line CLAUDE.md) or bring your own project.
I'll use the demo repo
- Move to your Desktop by running this command:
cd ~/Desktop
- Clone the practice project and install its dependencies by running these commands:
git clone https://github.com/nextwork-projects/nextsound2.git
cd nextsound2
npm install
You should see packages installing. This creates a node_modules/ directory with thousands of files, which is exactly what you'll learn to exclude later.
I want to use my own project
- In your terminal, navigate to a project you actively work on. A project with a CLAUDE.md file and node_modules/ is ideal.
What if I don't have a CLAUDE.md yet?
Switch back to your Claude Code session and run /init to generate a starter CLAUDE.md for your project. The /init command analyzes your project structure and creates a CLAUDE.md with inferred conventions.
- Start a Claude Code session by running:
claude
You should see the Claude Code interface appear in your terminal.
- Take a baseline cost snapshot by typing this inside your Claude Code session:
/cost
What does /cost show?
The /cost command displays your session's token usage, including a per-model breakdown and your cache hit rate.
The cache hit rate percentage is the number you'll improve throughout this project. Write it down or take a screenshot so you can compare later.
💡 Aim for a high cache hit rate
Your target by the end of this project is a cache hit rate above 40%. Whatever your current rate is, that's your starting line.
Check your current CLAUDE.md
Your CLAUDE.md file loads into every single Claude Code session. Every line is a token cost you pay on every interaction.
- Open a separate terminal tab (keep your Claude Code session running).
- Check the size of your CLAUDE.md by running this in your project root:
wc -l CLAUDE.md
Note the line count. If it's over 200 lines, there's significant room to optimize in the next step.
Your environment is ready and your baselines are recorded. Next up, you'll tackle the single highest-impact optimization: slimming down your CLAUDE.md.
Optimize Your CLAUDE.md
Your environment is confirmed and your baseline numbers are recorded. Now it's time to make the single highest-impact change to your token usage.
Your CLAUDE.md file loads into every single session. Every line in that file is a token tax you pay on every message, forever. A bloated CLAUDE.md filled with generic advice Claude already knows is wasting tokens on repeat. In this step, you'll trim it down to only the rules that actually change Claude's behaviour.
In this step, get ready to:
- Audit your CLAUDE.md and remove lines that don't prevent mistakes.
- Compress remaining rules into single-imperative bullet format.
- Structure the file for optimal prompt caching.
Audit what can be cut
Claude Code applies prompt caching to your CLAUDE.md. The first request in a session pays the full token cost, but subsequent requests within about 5 minutes read from cache at a significantly lower rate. This means a stable, lean file is cheap per-message. A bloated one wastes tokens on every cache miss.
- Open your CLAUDE.md in your text editor.
- For every line, ask yourself: "Would removing this cause Claude to make a mistake?" If the answer is no, cut it.
Here's what to remove and what to keep:
- Remove: generic coding standards Claude already knows (like "write clean code"), project descriptions that belong in a README, aspirational rules nobody follows, historical migration notes that no longer apply, git commands Claude already knows.
- Keep: project-specific patterns, critical file locations, non-obvious conventions unique to your project, hard constraints (e.g. "never modify the public API signature").
Why cut so aggressively?
Claude already knows how to write clean code, use git, and follow common conventions. Every line that restates general knowledge is a token you pay for on every single message. The goal is to keep only what Claude can't infer on its own.
Anthropic's own documentation recommends keeping CLAUDE.md under 200 lines per file. Longer files consume more context and reduce Claude's adherence to your rules.
Compress to reference format
Now that you've removed the unnecessary lines, it's time to compress the remaining rules into the most token-efficient format possible.
- Rewrite each remaining rule as a single imperative sentence. For example, write "Use TypeScript strict mode" instead of "We believe strict mode leads to better type safety and..."
- Convert any prose paragraphs into bullet lists. Claude doesn't need grammatically correct sentences. It needs the information.
- Remove filler words, hedging language, and explanations of why a rule exists. Keep only the rule itself.
What does good CLAUDE.md formatting look like?
A well-optimized CLAUDE.md reads like a checklist of constraints, not a style guide essay. Each line is one rule. Each rule is one sentence. No explanations unless the rule would be misinterpreted without one.
- Verify your file size by running this command in your project root:
wc -c CLAUDE.md
- Divide the byte count by 4 for a rough token estimate. Your target is under 2000 bytes (approximately 500 tokens).
- Also check the line count by running:
wc -l CLAUDE.md
- Your target is under 200 lines. If you're still over, look for multi-line rules that can be collapsed into single bullets.
Still over 200 lines?
Look for these common culprits: example code blocks (move to a separate reference file), lists of banned libraries (use .claudeignore instead), and duplicate rules that say the same thing differently.
help me identify which lines in my CLAUDE.md are generic knowledge that Claude already has
Structure for prompt caching
The order of your rules matters, and so does when you edit the file. Prompt caching is content-addressed. Any change to CLAUDE.md invalidates the entire cache for that file. One mid-day tweak means you pay the full token cost again on the next message.
- Place your most critical rules at the top of the file. Claude gives higher attention to content that appears early (primacy effect).
- Commit to not editing CLAUDE.md during your working sessions. Set it once, then leave it alone for the day.
- Save your optimized CLAUDE.md file.
Why not edit CLAUDE.md during the day?
Claude Code caches your CLAUDE.md after the first request. Subsequent requests within about 5 minutes read from this cache at a much lower token cost. The cache is content-addressed, so even a one-character change invalidates it completely.
Batch your edits. Make changes at the start of your day or between sessions. Never mid-conversation.
- Start a new Claude Code session in your project (or if you're still in one, your next message will use the updated file).
- After a few messages, check your cache hit rate by running:
/cost
- Compare the cache read tokens to your baseline from Step 1. Your target is a cache hit rate above 40%.
Cache improvements take a few messages
The first message in a new session always pays full price (cache write). You'll see the improvement on the second and subsequent messages when the cache starts being read. Send 3-4 messages before comparing to your baseline.
🙋♀️ Cache hit rate still low?
If your rate hasn't improved, check that you saved the file before starting the new session. Also confirm you're looking at cache read tokens specifically, not total input tokens.
why is my CLAUDE.md prompt cache hit rate still low after optimizing
✔️ Awesome, I've got everything!
Great. Double check that your CLAUDE.md is saved and you're happy with the trimmed version.
ⓧ I'd like to double check my work
Your optimized CLAUDE.md should have all of these characteristics:
- Under 200 lines (check with wc -l CLAUDE.md).
- Under ~2000 bytes / ~500 tokens (check with wc -c CLAUDE.md and divide by 4).
- Contains only project-specific patterns, critical file locations, non-obvious conventions, and hard constraints.
- Written as single-imperative bullet points (not paragraphs or essays).
- Most critical rules placed at the top of the file.
- No generic coding standards, README-style project descriptions, aspirational rules, or historical migration notes.
Your CLAUDE.md is now lean and cache-friendly. Next up, you'll tackle the other side of the equation: preventing Claude from reading files it doesn't need in the first place.
Add a .claudeignore File
Your CLAUDE.md is now lean and cache-friendly. The next optimization targets the other side of the equation: what Claude reads from your project.
In a typical Claude Code session, the vast majority of tokens are input tokens. Every file Claude reads during autonomous exploration (searching for relevant code, indexing your project) adds to that cost. A .claudeignore file tells Claude which files to skip during that exploration, cutting noise from your context window.
In this step, get ready to:
- Create a .claudeignore file that blocks unnecessary file reads.
- Understand what .claudeignore does and does not block.
- Verify reduced noise in your context window.
Create the .claudeignore file
The .claudeignore file works like a .gitignore but for Claude Code's file discovery. Any path you list here becomes invisible to Claude's automatic search and indexing.
- Create a file called .claudeignore in your project root (the same directory as your CLAUDE.md).
- Add the following content to the file:
# Dependencies
node_modules/
.pnpm-store/
# Build outputs
dist/
build/
out/
.next/
# Cache directories
.cache/
.turbo/
.eslintcache/
# Test coverage
coverage/
.nyc_output/
# Generated files
*.generated.ts
*.generated.js
# Lock files
package-lock.json
pnpm-lock.yaml
yarn.lock
# Environment files
.env.local
.env.*.local
# Large static assets
public/images/
public/videos/
*.svg
*.png
*.jpg
# Documentation (read manually when needed)
docs/*.md
!CLAUDE.md
# IDE config
.vscode/
.idea/
What does each section do?
- Dependencies and lock files prevent Claude from indexing thousands of third-party files when searching for relevant code.
- Build outputs and cache directories exclude compiled or temporary files that duplicate your source code.
- Large static assets keep binary-heavy folders out of context. Claude cannot meaningfully read image files anyway.
- The !CLAUDE.md exception ensures Claude can still read your CLAUDE.md even though docs/*.md is excluded.
- Save the .claudeignore file.
- Confirm it exists by running:
ls -a | grep claudeignore
You should see .claudeignore in the output.
Don't see the file?
- Make sure the filename starts with a dot. Files starting with . are hidden by default in most file browsers.
- Confirm you saved it in the project root directory, not in a subfolder.
- If you used a GUI editor, check it did not add a .txt extension automatically.
Help me troubleshoot why my .claudeignore file isn't appearing in my project root.
Understand what .claudeignore does and does not block
The .claudeignore file controls Claude's autonomous exploration. It does not make files completely inaccessible.
What does .claudeignore actually block?
It prevents Claude from reading listed files during automatic file discovery. This means search, grep, and indexing operations skip these paths.
It does NOT prevent Claude from reading a file if you explicitly reference it by path. For example, if you say "read package-lock.json" Claude can still open it. The savings come from Claude not indexing your entire node_modules/ when it searches for relevant code on its own.
Use this decision rule for each file or directory in your project: "Does Claude need to read this to write better code?" If yes, keep it readable (source code, type definitions, test files, key config like tsconfig.json). If no, add it to .claudeignore.
Verify the file is working
- Start a new Claude Code session by running /clear or restarting claude in your terminal.
- Ask Claude to search for usages of a function in your project. For example, type something like: "find all usages of [a function you know exists]."
Claude should search only through your source files. It should not search through node_modules/ or build output directories.
- Run /context to visualize what is currently loaded into your context window.
You should see less noise from irrelevant files compared to your earlier sessions. The context visualization shows where tokens are being spent.
What should I see?
The /context output shows what is currently loaded into your context window and where it is being spent. You should notice that large directories like node_modules/ and dist/ are absent from the listing. This means Claude is not wasting tokens reading files it does not need.
🙋♀️ Still seeing node_modules in context?
- Make sure you started a fresh session after creating .claudeignore. The file takes effect on new sessions, not mid-conversation.
- Double-check the file is named exactly .claudeignore (not claudeignore without the dot).
- Verify the file is in your project root, the same directory where you run claude.
Help me figure out why my .claudeignore isn't blocking files from context.
✔️ Awesome, I've got everything!
Great. Double check you have saved your .claudeignore file and confirmed it is working with /context.
ⓧ I'd like to double check the full code
Here is the complete .claudeignore file for comparison:
# Dependencies
node_modules/
.pnpm-store/
# Build outputs
dist/
build/
out/
.next/
# Cache directories
.cache/
.turbo/
.eslintcache/
# Test coverage
coverage/
.nyc_output/
# Generated files
*.generated.ts
*.generated.js
# Lock files
package-lock.json
pnpm-lock.yaml
yarn.lock
# Environment files
.env.local
.env.*.local
# Large static assets
public/images/
public/videos/
*.svg
*.png
*.jpg
# Documentation (read manually when needed)
docs/*.md
!CLAUDE.md
# IDE config
.vscode/
.idea/
Your project now has two layers of token optimization working together. Your CLAUDE.md is lean and stable (maximizing cache hits), and your .claudeignore prevents Claude from reading irrelevant files during exploration. Next up, you will install Caveman mode to tackle the output side of the equation.
Install and Test Caveman Mode
Your .claudeignore is now blocking Claude from reading unnecessary files. That handles the input side of token waste.
Output tokens still add up when Claude over-explains, adds pleasantries, or writes summaries you never asked for. Caveman is a community tool that compresses Claude's prose output by an average of 65%. You'll install it, test all four intensity levels, and track per-prompt savings in real time.
In this step, get ready to:
- Install Caveman via the one-liner installer.
- Test all four intensity levels with the same prompt.
- Measure lifetime token savings with /caveman-stats.
Install Caveman
Caveman uses Claude Code's hook system to automatically compress responses from the very first message of every session. The installer auto-detects Claude Code on your machine and wires everything up in about 30 seconds.
- Exit your current Claude Code session first by typing /exit or pressing Ctrl+C.
- In your regular terminal (outside Claude Code), install Caveman by running this command:
curl -fsSL https://getcaveman.dev/install.sh | bash
What does this command do?
This downloads and runs the Caveman installer script. It auto-detects Claude Code on your system, installs the plugin and hooks, and configures the statusline badge.
The SessionStart hook is the key piece. It fires once when Claude Code launches and injects the Caveman compression rules as hidden system context. Claude sees the rules, but you never see them in your chat.
- The installer may prompt you to confirm the statusline badge setup. Accept the defaults.
- After installation completes, restart Claude Code by running:
claude
- Verify the install worked by checking that the statusline at the bottom of your Claude Code session shows [CAVEMAN].
Why do I need to restart?
The SessionStart hook only fires when Claude Code starts a new session. It writes full to ~/.claude/.caveman-active and emits the compression rules. If you don't restart, the hook never fires and Caveman stays inactive.
🙋♀️ Don't see the [CAVEMAN] badge?
Run this in a separate terminal to check the flag file:
cat ~/.claude/.caveman-active
- If it outputs full, the hook fired correctly. The statusline badge may need manual configuration. Claude will offer to help set it up on your next prompt.
- If the file is missing or empty, the SessionStart hook did not fire. Re-run the installer with --force and restart Claude Code again.
- Make sure claude is on your PATH. The installer needs to detect it to wire up hooks.
Help me troubleshoot my Caveman installation. The [CAVEMAN] badge is not showing in my Claude Code statusline after running the installer and restarting.
Test the intensity levels
Caveman has four intensity levels. Each compresses output differently while keeping the technical content identical. You'll try all four with the same question so you can see the difference side by side.
- Inside your Claude Code session, type /caveman lite to switch to lite mode.
- Ask Claude a question that normally produces a verbose response. For example, type: "What causes React re-renders?"
- Now switch to full mode by typing /caveman full and ask the same question again.
- Switch to ultra mode by typing /caveman ultra and ask the same question once more.
- Finally, switch to wenyan mode by typing /caveman wenyan and ask the same question.
What are the four levels?
- lite removes filler and pleasantries but keeps full grammar.
- full (the default) drops articles, allows fragments, and uses short synonyms.
- ultra applies maximum compression with abbreviations and arrows for causality.
- wenyan uses Classical Chinese compression. Each character carries high semantic weight, making it the most token-efficient literary register.
The technical content stays identical across all levels. Only the wrapper text changes.
Compare your four responses. Notice how the core information is the same in each, but the word count drops dramatically as you move from lite to wenyan.
Measure the savings
Now that you've generated a few responses across different levels, you can see real numbers on how many tokens Caveman saved.
- Inside Claude Code, run /caveman-stats to see your session token usage, lifetime savings, and estimated USD cost.
What should I see?
The /caveman-stats output shows how many output tokens were saved across your session. The statusline badge at the bottom updates to show [CAVEMAN] ⛏ 12.4k (or your actual lifetime tokens saved) after each stats check.
- Note your lifetime tokens saved number. This is your new baseline.
How much does Caveman actually save?
The 65% reduction applies only to prose output text. In a real session, prose is roughly 25% of total output. Real overall session savings are typically 4-10%, reaching 15-25% on coding-heavy sessions.
The bigger win is fewer conversation turns. Less over-explanation means fewer corrections, which means fewer back-and-forths. Each turn costs 2,000-3,000 tokens. This compounds to meaningful savings across a working day.
Caveman only affects output tokens. Thinking and reasoning tokens are untouched.
💡 Pick your default level
Most developers settle on full for everyday work. Use ultra for mechanical refactors where you don't need explanations. Use lite when you're learning something new and want readable responses.
Caveman is now compressing every response automatically. Next up, you'll write a custom skill that takes a gentler approach to verbosity suppression.
Write a Custom Context-Mode Skill
Caveman is cutting your output tokens down. But its telegraphic style can be too aggressive for everyday coding sessions where you still want readable, complete sentences.
In this step, you'll write a custom skill that makes Claude token-conscious without the caveman compression. Skills are markdown files that Claude loads at runtime from your .claude/skills/ directory.
In this step, get ready to:
- Create a context-mode skill file with behavioural rules.
- Test the skill in a new Claude Code session.
- Decide when to use caveman vs context-mode.
Create the skill file
Skills are markdown files with YAML frontmatter and a body of instructions. Claude sees skill descriptions at session start, then loads the full content when a skill is triggered.
- Create the skills directory by running this command:
mkdir -p .claude/skills
- Confirm the directory exists by running:
ls .claude/
You should see a skills/ folder in the output.
- Create a file called context-mode.md inside .claude/skills/ and paste in this content:
---
name: context-mode
description: Keep responses terse and token-efficient
---
# Context Mode
When this skill is active:
- Do not explain what the code does unless asked
- Do not add comments describing obvious behavior
- Do not produce summaries after edits
- Do not offer next steps unless asked
- Do not re-read files you already have in context
- If unsure whether to say something, do not say it
What does this skill do?
Each rule targets a specific type of token waste that Claude produces by default:
- "Do not explain what the code does unless asked" kills the preamble paragraphs before every edit.
- "Do not produce summaries after edits" kills the "Here's what I changed" recap.
- "Do not re-read files you already have in context" prevents redundant file reads that bloat input tokens.
- "If unsure whether to say something, do not say it" is the catch-all for unsolicited commentary.
- Save context-mode.md.
- Confirm the file is in place by running:
ls .claude/skills/
You should see context-mode.md in the output.
Don't see the file?
- Double-check you created the file inside .claude/skills/ and not in the project root or inside .claude/ directly.
- Make sure the filename is exactly context-mode.md with no extra extensions.
- If you created the .claude/skills/ directory for the first time during this session, you will need to restart Claude Code for it to detect the new directory.
Help me debug my skill file setup.
✔️ Awesome, I've got everything!
Great. Make sure you have saved the file before moving on.
ⓧ I'd like to double check the full code
---
name: context-mode
description: Keep responses terse and token-efficient
---
# Context Mode
When this skill is active:
- Do not explain what the code does unless asked
- Do not add comments describing obvious behavior
- Do not produce summaries after edits
- Do not offer next steps unless asked
- Do not re-read files you already have in context
- If unsure whether to say something, do not say it
Test the skill
The skill file is in place. Now you need to confirm Claude actually picks it up and changes its behaviour.
- Restart Claude Code so it detects the new skills directory. Exit your current session and run:
claude
- Verify the skill is loaded by running:
/skills
You should see context-mode listed among your available skills.
- Ask Claude to make a small edit to a file in your project. For example, ask it to rename a variable or add a function parameter.
- Observe the response. You should see just the edit itself. No preamble, no "Here's what I did" summary, no "Let me know if you'd like me to adjust anything" sign-off.
What should I see?
With context-mode active, Claude's response to a simple edit request should be dramatically shorter. You will notice the absence of explanation paragraphs, post-edit summaries, and unsolicited follow-up suggestions. The technical content of the edit stays identical. Only the wrapper text disappears.
🙋♀️ Still seeing verbose responses?
- Run /skills and confirm context-mode appears in the list. If it does not appear, restart Claude Code.
- Check that the YAML frontmatter is between --- markers and includes both name and description fields.
- If the skill appears but Claude ignores it, try invoking it explicitly with /context-mode in your next message.
Why is my context-mode skill not affecting Claude's responses?
Decide when to use caveman vs context-mode
You now have two tools for controlling output verbosity. Each fits different situations.
When to use which?
Caveman is more aggressive. It compresses responses into telegraphic fragments, drops articles, and uses abbreviations. It is best for mechanical tasks like refactors, bulk renames, and repetitive edits where you already know what the output should look like.
Context-mode is gentler. Claude still writes in full sentences. It just stops volunteering information you did not ask for. It is best for everyday coding sessions where you want clear, readable responses without noise.
You can use both together. Set context-mode as your baseline for every session. Layer caveman on top for heavy refactor sessions when even full sentences are too much wrapper text.
The output-token savings from context-mode compound across long sessions. Every suppressed summary, every skipped explanation, and every omitted sign-off is a few dozen tokens you are not paying for. Over a full working day, this adds up.
Your skill is locked in. Next up, you will configure auto-compaction and session hygiene to keep your context window clean as conversations grow.
Configure Auto-Compaction and Session Hygiene
Your Claude Code environment now has a lean CLAUDE.md, a tight .claudeignore, Caveman compression, and a custom context-mode skill. All of those target what Claude reads and writes.
This step targets the container itself. The context window is finite, and when it fills up, Claude loses track of earlier instructions and quality degrades. You will control when Claude compacts your conversation and build habits that keep sessions clean from the start.
In this step, get ready to:
- Set the auto-compaction threshold to trigger earlier via an environment variable.
- Practice proactive compaction with preservation instructions.
- Learn session hygiene habits that compound savings across every future session.
Set CLAUDE_AUTOCOMPACT_PCT_OVERRIDE
Claude Code automatically compacts your conversation when the context window gets too full. By default, this happens at roughly 83% capacity.
That is too late. By the time the compaction fires, you have very little free context left for Claude's reasoning. Lowering the threshold to 50% keeps more room for high-quality responses.
- Open your ~/.zshrc file in your editor and add this line at the bottom:
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50
What does this line do?
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE sets the percentage of context capacity at which auto-compaction triggers.
Setting it to 50 means Claude will summarize the conversation when the window is half full, leaving the other half free for reasoning and new content. You can only lower this threshold, not raise it above the default.
- Save ~/.zshrc.
- Apply the change to your current terminal session by running this command:
source ~/.zshrc
- Verify the variable is set by running:
echo $CLAUDE_AUTOCOMPACT_PCT_OVERRIDE
You should see 50 printed in your terminal.
Seeing a blank output?
Make sure you saved ~/.zshrc before running source. If you added the line to a different shell config (like ~/.bashrc), source that file instead.
help me set CLAUDE_AUTOCOMPACT_PCT_OVERRIDE in my shell config
Practice /compact with preservation instructions
Auto-compaction is a safety net. The better habit is to compact proactively before quality degrades.
When you run /compact with custom instructions, you tell Claude exactly what to remember in the summary. Without instructions, Claude decides on its own and often drops decisions that are not explicit in the recent conversation.
- In your Claude Code session, run /context to see your current context utilization.
- When you finish a task or reach a natural breakpoint (ideally around 60% context utilization), run a compact command with preservation instructions like this:
/compact Keep: current file structure, the decision to use [X], and the unresolved error in [Y]
What do preservation instructions do?
The text after /compact is passed into the compaction prompt. It tells Claude what to anchor the summary around.
Replace [X] and [Y] with whatever is relevant to your current session. For example: "Keep: the decision to use Redis for caching, and the unresolved timeout in the auth middleware."
- After compacting, ask Claude to summarize the current state of your work. Verify that it remembers what you specified in your preservation instructions.
When to compact
Compact at around 60% context utilization (check with /context), not when you see the auto-compaction warning. The warning means you are already too late and quality may have already started dropping.
Build session hygiene habits
Configuration gets you most of the way. Habits get you the rest.
Three practices compound savings across every Claude Code session going forward.
- Keep one task per conversation. When you finish a task and need to switch topics, run /clear instead of continuing in the same session. Your CLAUDE.md carries durable context forward, so chat history does not need to.
- Reference files precisely. Use @src/path/to/file.ts to point Claude at the exact file instead of letting it explore. Each exploration reads files into context, consuming tokens you did not need to spend.
- State acceptance criteria upfront. Tell Claude what "done" looks like at the start of a task ("tests pass", "no new dependencies", "under 50 lines"). This prevents back-and-forth correction rounds that burn tokens on rework.
Why one task per conversation?
Long sessions accumulate noise. When you switch from "fix the login bug" to "refactor the billing module", all the login-bug context is still in the window, confusing Claude and reducing the quality of its responses.
Running /clear wipes the conversation history but keeps your CLAUDE.md, skills, and project configuration intact. You get a fresh, focused session every time.
- Try it now: in your Claude Code session, run /clear to start fresh.
- Then ask Claude a question about your project using a precise file reference (for example, @src/index.ts what does this file export?).
- Run /cost afterwards. Notice how a targeted question with a precise reference uses fewer input tokens than a broad "explain this project" prompt.
Not sure what to reference?
If your project does not have a src/ directory, substitute any file path that exists in your project. The key point is using the @ prefix to reference a specific file rather than asking a broad question that triggers exploration.
help me use precise file references in Claude Code
Secret mission
Build a Haiku-Routed Exploration Subagent
Every time you ask Claude to explore your codebase, dozens of file reads flood your main context window. What if that research happened in a separate, cheaper context instead? Build a custom subagent that routes exploration to the Haiku model and returns only a concise summary to your main session.
Clean Up Your Resources
Clean Up Your Resources
This project runs entirely on your existing Claude Code subscription with local configuration files. There are no ongoing costs or cloud resources to worry about.
Decide whether to keep your optimized configuration active, pause parts of it, or remove everything entirely.
Resources you used:
- Optimized CLAUDE.md file in your project root.
- .claudeignore file in your project root.
- Caveman skill installed globally (hooks, statusline badge, plugin).
- Custom skill at .claude/skills/context-mode.md.
- Custom subagent at .claude/agents/explorer.md.
- CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50 environment variable in ~/.zshrc.
Keep everything running
No action needed. Choose this if you want your optimized token configuration active across all future Claude Code sessions.
- Your CLAUDE.md, .claudeignore, skills, and agents stay in place and activate automatically.
- Caveman auto-activates on every new session via the SessionStart hook.
- Auto-compaction triggers at 50% context capacity as configured.
- Check /cost at the end of your next working day to compare your cache hit rate against today's baseline.
Pause - I'll come back to this later
Disable the most aggressive optimizations while keeping your configuration files intact for later.
- Deactivate Caveman for now by saying "normal mode" in your next Claude Code session. The skill stays installed but won't auto-compress responses.
- Comment out the auto-compaction override in your ~/.zshrc by adding a # at the start of the line:
- # export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50
- Run source ~/.zshrc to apply the change.
- Your .claudeignore, CLAUDE.md, skills, and agents remain on disk. Re-enable anytime by uncommenting the line and saying /caveman in your next session.
Delete - I don't want to use this again
Remove all project resources and restore your environment to its pre-project state.
- Delete the project-level configuration files by running:
rm .claudeignore
rm .claude/skills/context-mode.md
rm .claude/agents/explorer.md
- Uninstall Caveman by running:
npx -y github:JuliusBrussee/caveman -- --uninstall
- Remove the auto-compaction environment variable from ~/.zshrc. Open the file in your editor and delete this line:
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=50
- Apply the change by running:
source ~/.zshrc
- If you want to revert your CLAUDE.md to its pre-optimized state, restore it from version control or rewrite it with the content you had before.
That's a Wrap!
That's a Wrap!
Nice work! You've built a complete token optimization stack for Claude Code. Every future session will cost less, run faster, and stay coherent longer.
You've learned how to:
- Control what Claude reads by optimizing CLAUDE.md to under 500 tokens and adding a .claudeignore file that prevents unnecessary file indexing.
- Compress output tokens with Caveman mode and a custom context-mode skill, tracking real savings with /caveman-stats and /cost.
- Manage auto-compaction and session hygiene to keep context quality high across long working sessions.
- Built a Haiku-routed exploration subagent that isolates cheap research from your main context window (Secret Mission).
Ready to quiz yourself?