irfan@backend:~/portfolio
Email me
← cd ../blog

Claude Code / AI Agents / Tokens / Beginner

Claude Code Token Diet

Find where your Claude Code tokens go, measure them, then cut shell noise with RTK, repo reading with Graphify and long answers with Caveman.

On this page
  1. Three layers of waste
  2. Why the waste repeats
  3. The three layers
  4. Measure first
  5. Built-in commands in Claude Code
  6. rtk gain
  7. RTK
  8. How the hook rewrites commands
  9. Install and turn it on
  10. When not to use RTK
  11. Graphify
  12. Words you need
  13. Worked example: one query instead of many greps
  14. How Graphify builds the map
  15. Install and build it
  16. Wire it into Claude Code with a hook
  17. Measure it with graphify benchmark
  18. Caveman
  19. What Caveman changes
  20. Install it and switch modes
  21. The honest numbers
  22. Shrinking memory files with /caveman-compress
  23. When to switch them off
  24. Recap

A long Claude Code session gets slow and expensive. A big part of that is not your code. It is noise: progress bars, long git log output, files the agent reads "just to look around", and long answers.

In this post we find where that waste comes from, measure it, and cut it layer by layer.

After this post you can:

  • see where your tokens go, and measure them with /context, /usage, rtk gain and graphify benchmark
  • cut shell noise with RTK, give the agent a map of your repo with Graphify, and make its answers shorter with Caveman
  • know when to switch each tool off

RTK (Rust Token Killer) is a small program that runs a shell command, then shortens its output before the agent reads it.

This post builds on Claude Code 101. If tokens, the context window or hooks are new to you, read that first. I don't teach them again here.

Three layers of waste#

Here is a real git status from a clean repo, on my machine:

On branch develop
Your branch is up to date with 'origin/develop'.

nothing to commit, working tree clean

The agent only needs two facts: which branch, and "clean". Everything else is extra words. One command is small. But an agent runs hundreds of commands in a session, and each output stays in the chat.

Why the waste repeats#

Quick reminder from Claude Code 101: on every request, Claude Code sends the whole conversation again. So a noisy output is not paid once.

It rides along on every request after it, until you /clear or /compact.

Watch the bar fill as the chat grows:

context-window
context window10% used
system prompt + CLAUDE.mdyouclaude
Every new message sends the whole pile again. Demo sizes, not real numbers.

Words you need:

  • Prompt caching: the API remembers the start of your request. The next request that starts the same way reads that part from the cache instead of paying the full price again.
  • Cache write: the first time a part of the prompt is stored in the cache. It costs a bit more than normal input.
  • Cache read: a later request reuses the stored part. It costs much less than normal input.

There is good news. Claude Code uses prompt caching by itself (Claude Code docs).

Here are the prices for Claude Sonnet 5.5, per million tokens, from Anthropic's pricing page:

Normal inputCache write (5 minutes)Cache readOutput
$2$2.50$0.10$10

The 5 minutes is how long the cache lives. Claude Code can also use a 1-hour cache, which its docs show as "1h TTL".

A cache read costs one twentieth of normal input. Why cut noise at all, then? Three reasons:

  • Cached tokens are cheaper, but not free. A long session still counts against your usage for the whole conversation on every request (Claude Code docs).
  • After a break longer than the cache lifetime (5 minutes, or 1 hour on the 1-hour cache), the cache expires. Your next message misses the cache and pays full price for everything again.
  • Noise still takes room in the context window. The model has to read past it to find your rules and your code.

The three layers#

Token waste comes from three places. Each tool in this post fixes one:

LayerExample of wasteTool
What the agent readsit greps and opens 20 files to find one functionGraphify (Graphify chapter)
What tools printgit log, test runs, build logsRTK (RTK chapter)
What the model writeslong answers, polite fillerCaveman (Caveman chapter)

Look at the price table again: output costs 5 times normal input. So long answers are the pricey kind of token.

On a Pro or Max plan you don't pay per token, but the same tokens still count against your usage.

quick-check

Claude Code caches your prompt. Why is a noisy git log still a problem?

quick-check

Your agent opens 20 files to find one function. Which layer is that?

Measure first#

Before you install anything, look at your numbers. A tool that claims "90% savings" tells you nothing about your own sessions.

Built-in commands in Claude Code#

Type these in a Claude Code session:

  • /context shows what is using space in your context window right now (Claude Code docs).
  • /usage shows the token use of this session.

The /usage session block looks like this. This is the example from the Claude Code docs. It uses an older model, so the prices differ from the table above:

Total cost:            $0.55
Total duration (API):  6m 20s
Usage by model:
   claude-sonnet-4-6:  1.2k input, 5.3k output, 940.0k cache read, 50.0k cache write ($0.55)

Look at the last line. Most of the input in that session came from the cache (940.0k cache read against 1.2k normal input).

The docs say Claude Code v2.1.251 or later also adds a "Prompt cache (main)" line with the share of input served from the cache.

When do you use this? At the start of a session, to see what is always loaded. And after a long task, to see if the chat or the tool output is the big part.

rtk gain#

Words you need:

  • RTK (Rust Token Killer): a small program that runs a shell command, then shortens its output before the agent reads it. The RTK chapter shows how.

RTK keeps a record of every command it shortened. rtk gain prints the summary. Here is the top of mine, on my machine (RTK 0.35.0):

RTK Token Savings (Global Scope)
════════════════════════════════════════════════════════════

Total commands:    88042
Input tokens:      806.0M
Output tokens:     40.7M
Tokens saved:      766.5M (95.1%)

Read it carefully. These words don't mean the same as in /usage:

  • "Input tokens" here is the text the commands printed.
  • "Output tokens" here is the text RTK passed on to the agent.

Neither one is a Claude API token count. And 806.0M minus 40.7M is 765.3M, not 766.5M.

The current RTK source code (it may differ from 0.35.0) counts a command that made output bigger as 0 saved, not as a negative number. So the "saved" total comes out a little higher than input minus output.

The RTK README is honest about two more things. RTK counts tokens as bytes / 4, so the percentages are reliable but the token numbers are rough.

So the cut on your bill is smaller, for two reasons:

  • Shell output is only one part of your Claude input tokens.
  • Claude input tokens are only one part of your bill, which also counts output.

Here is what RTK can and can't touch:

Part of the billDoes RTK touch it?
System prompt, skills, MCP toolsNo
CLAUDE.mdAdds a little (the @RTK.md line and the short file it loads)
Files read with the built-in Read, Grep and Glob toolsNo
Your messagesNo
Output of shell commands the agent runsYes
The model's answersNo

Two more commands help:

rtk gain --history   # recent commands and what each one saved
rtk discover         # commands in your Claude Code history that ran without RTK

By default, rtk discover looks at the current project only, and at the last 30 days. rtk discover --all scans every project.

For the repo-reading layer, Graphify has its own graphify benchmark. The Graphify chapter shows it.

The rule: measure before and after any change. Check the number on your own work, and know what the number counts.

quick-check

rtk gain says 95% saved. Does your Claude bill drop by 95%?

RTK#

Same repo, three commands, raw and through RTK. I measured the sizes on my machine with wc -c, a command that counts the bytes in an output. One run for all three, on a clone of the public RTK repo:

CommandRaw outputThrough RTK
git status106 bytes55 bytes
git log -105,606 bytes, 127 lines3,275 bytes, 47 lines
find src -type f -name "*.rs"4,273 bytes694 bytes

Here is the RTK version of that git status:

* develop...origin/develop
clean — nothing to commit

And one commit from the RTK version of git log, from the same run. It keeps the hash, subject, time and author, then cuts long commit bodies:

b1701fb fix(ruff): restore a leading -- before routing (3 days ago) <Yathiskumar>
  clap's trailing_var_arg strips a `--` that leads `args`, so `rtk ruff -- check`
  reached run() as `["check"]`, was routed as the check subcommand with no path,
  and linted the whole working directory. Restore it the way golangci and dotnet
  [+2 lines omitted]

This is output, not a command to copy. The saving depends a lot on the command. find shrank by about 84%, git log by about 42%. Measure your own.

When do you use this? Any project where the agent runs a lot of shell commands: git, tests, linters, ls, find, docker.

How the hook rewrites commands#

Words you need:

  • PreToolUse hook: a Claude Code hook that runs before a tool call. It can change the tool's input (hooks in Claude Code 101).
  • Matcher: the tool names a hook runs for. The matcher Bash means "only before Bash tool calls".

RTK has its own version of many common commands: rtk git, rtk grep, rtk find, rtk ls, rtk vitest, rtk docker and more. Run rtk --help to see the list for your version.

You never type these yourself. A hook rewrites the agent's commands for you. Follow one command:

rtk-hook
  1. Claude wants to run: git status
  2. Before the Bash tool runs, the PreToolUse hook fires
  3. The hook reads the tool call as JSON and asks: rtk rewrite "git status"
  4. RTK answers: rtk git status
  5. The hook hands the new command back to Claude Code
  6. Claude Code runs rtk git status
  7. RTK runs git, shortens the output, and the short version goes into the context
step 1 / 7
The agent never knows the command was rewritten.

You can try the rewrite step by hand:

rtk rewrite "git status"   # prints: rtk git status
rtk rewrite "echo hi"      # prints nothing: RTK has no filter for echo

A command with no RTK version passes through unchanged.

Install and turn it on#

On a Mac or Linux with Homebrew, this is the simplest way, from the RTK README:

brew install rtk

The README also has an install script. Never pipe a script from the internet straight into sh. Download it, read it, then run it. Pin it to a release tag, not the moving master branch:

curl -fsSL -o rtk-install.sh https://raw.githubusercontent.com/rtk-ai/rtk/v1.0.1/install.sh
less rtk-install.sh                   # read it before you run it
RTK_VERSION=v1.0.1 sh rtk-install.sh  # RTK_VERSION pins the version it downloads

The RTK_VERSION setting comes from the script itself (install.sh at v1.0.1). v1.0.1 was the latest release when I wrote this. Check the releases page for a newer one.

Then check you got the right program. The README warns that a different project called "rtk" exists on crates.io (the package site for Rust):

rtk --version
rtk gain   # must show the savings dashboard; an error means you have the wrong rtk

The steps below were checked on RTK 0.35.0, the version on my machine. Check rtk --help on your version.

Then wire it into Claude Code and restart Claude Code:

rtk init -g      # global setup for Claude Code
rtk init --show  # check: the hook and settings.json lines should say [ok]

On my version (0.35.0), rtk init --show lists what rtk init -g sets up:

  • a hook in ~/.claude/settings.json
  • a short instructions file, ~/.claude/RTK.md
  • an @RTK.md line in your global CLAUDE.md, so Claude Code loads that file

rtk init -g --hook-only skips the RTK.md file. When rtk init -g asks to patch (edit) settings.json, answer y. Or use rtk init -g --auto-patch to skip the question.

The hook it adds is a PreToolUse hook with the matcher Bash. On my machine (RTK 0.35.0) it looks like this:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "bash /Users/you/.claude/hooks/rtk-rewrite.sh" }
        ]
      }
    ]
  }
}

On 0.35.0 the hook is a shell script. It needs jq, a small command-line tool that reads JSON.

The current RTK docs list a different hook command for Claude Code: rtk hook claude, the RTK program itself (supported agents).

Either way, rtk init -g writes the hook for you. You never run the hook command by hand.

quick-check

You installed RTK with brew, but rtk gain shows no commands after a day of work. What did you most likely skip?

When not to use RTK#

RTK cuts output on purpose. Sometimes you need the full thing.

  • Built-in tools skip it. The README says it plainly: the hook only fires on Bash tool calls. Claude Code's own Read, Grep and Glob tools don't go through it. On my machine, most saved tokens come from rtk read and rtk grep. Those records only exist because the agent ran shell commands like cat and grep, and the hook rewrote them.
  • A strange failure. When a test fails in a way you don't understand, the line you need may be one RTK cut. Run the command without filtering.
  • How to run it unfiltered. On RTK 0.35.0 that is rtk proxy <command>. The current README calls it rtk bypass <command>. Check rtk --help for your version. Or ask the agent to run it in your own terminal.
  • Commands it doesn't know. They pass through unchanged, so no saving. On my version (0.35.0), rtk rewrite "npm test" returns nothing. Don't assume every command is filtered: check with rtk rewrite.

One worry you can drop: the README says RTK does not break Claude's prompt cache. The shortened output is stored in the history once and cached like any other text.

quick-check

The agent searches your code with Claude Code's built-in Grep tool. What does RTK do?

Why it works: the agent needs the facts in an output, not the formatting. RTK keeps the facts and drops the formatting before the output enters the context. Everything in the context is re-sent on every request.

Graphify#

Shell noise is cut. Two layers are left: what the agent reads to find things, and what the model writes back. This chapter fixes reading.

On my machine, I took the git part of the RTK source code: 6 Rust files, about 770 KB of code. The biggest file is 278 KB. Then I asked one question: where does RTK make git log output shorter?

Without a map, the agent greps for "log", gets many hits, and opens big files to read around them. With a Graphify map, the agent asks the map first.

map-vs-grep
  1. Without a map, the agent greps for "log" and gets many hits.
  2. It opens big files to read around the hits.
  3. With a map, the agent asks the map first.
  4. The answer points straight at the right functions and lines.
step 1 / 4
The map says where the code is. The agent then reads only those functions.

Words you need#

  • Knowledge graph: a map of things and how they connect.
  • Node: one thing in the map, like a function, a class or a file.
  • Edge: one link between two nodes, like "calls" or "imports".
  • Tree-sitter: a parser that reads source code into a tree of its parts. It runs on your machine, with no AI.
  • Community: a group of nodes that link to each other a lot, like one module. Each one gets a number.
  • God node: a node with many more links than the rest. It is often the core of a module.

Worked example: one query instead of many greps#

graphify query "how is git log output compacted" --budget 300
NODE git_cmd.rs [src=git/git_cmd.rs loc=L1 community=2]
NODE compact_diff() [src=git/git_cmd.rs loc=L1343 community=9]
NODE git_cmd() [src=git/git_cmd.rs loc=L79 community=7]
NODE tokenize_git_log_args() [src=git/git_cmd.rs loc=L2067 community=13]
NODE filter_log_output() [src=git/git_cmd.rs loc=L2231 community=16]
NODE run_log() [src=git/git_cmd.rs loc=L1829 community=7]
...
... (truncated to ~300 token budget)

Each line is one node: its name, its file (src), its line (loc) and its community. --budget 300 caps the answer at about 300 tokens.

On my machine that answer was 938 bytes. It points straight at filter_log_output() on line 2231 and run_log() on line 1829. Now the agent reads only those functions.

When do you use this? A repo too big for the agent to read in one go, or one you are new to. Questions like "where is X?" and "what calls Y?" are where the map helps most.

How Graphify builds the map#

Everything below I checked on graphify 0.3.28, the version on my machine. Newer versions exist and change some details (releases). Run graphify --help on yours before you copy a command.

The Graphify README says the official repo is Graphify-Labs/graphify. Graphify turns a folder into a graph and writes a short report about it.

The agent then reads the report or runs a query, and a hook reminds it to. Follow the arrows from left to right:

  • Code costs no tokens. The README says code is parsed locally with tree-sitter, and nothing leaves your machine. My report for the Rust folder says Token cost: 0 input · 0 output. It also says 100% EXTRACTED: every link was read from the code, none guessed.
  • Docs, PDFs and images do cost tokens. For those, Graphify runs a semantic pass. It sends the text to your assistant's model, and the model finds the ideas and links in it.
  • The report is short. On my machine, GRAPH_REPORT.md was 10.5 KB for 770 KB of code. It listed 882 nodes, 1,708 edges, 27 communities, and the god nodes.

Install and build it#

Words you need:

  • PyPI: Python's package site.
  • uv and pipx: tools that install a Python command-line program in its own space, so it doesn't clash with your other Python packages.

Graphify is a Python package, so you install it with a Python tool.

From the Graphify README:

uv tool install graphifyy   # or: pipx install graphifyy
graphify install            # registers the /graphify skill for your assistant

The package is graphifyy with two y's. The README says other graphify packages on PyPI are not from this project. The command is still graphify.

Then build the map inside Claude Code. These are commands for the /graphify skill, typed in the Claude Code chat, not in your terminal:

/graphify .
/graphify . --update    # later: re-extract only new or changed files

Some older guides show graphify extract. In 0.3.28 that command does not exist.

Wire it into Claude Code with a hook#

A graph on disk helps only if the agent looks at it. Run this once in your project, in the terminal:

graphify claude install

In 0.3.28 it does two things. It adds a ## graphify section to the project CLAUDE.md.

It also adds a PreToolUse hook to the project's .claude/settings.json, with the matcher Glob|Grep. The | means "or": the hook runs before every Glob call and every Grep call.

When graphify-out/graph.json exists, the hook adds this note before the search:

graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files.

The hook doesn't block the search. It gives the agent a reminder at the moment it is about to grep.

To keep the map fresh after commits and branch switches:

graphify hook install   # git hooks: post-commit and post-checkout

These are git hooks, not Claude Code hooks. Git runs them after a commit or a checkout, and they rebuild the graph.

Measure it with graphify benchmark#

graphify benchmark

On my machine, one run on the Rust folder:

Corpus:          44,100 words → ~58,800 tokens (naive)
Avg query cost:  ~24,960 tokens
Reduction:       2.4x fewer tokens per query

Why ~24,960 tokens per query, when my query above was under 300? The benchmark measures something else.

In the 0.3.28 source, it runs 5 built-in sample questions, like "how does authentication work". For each one it follows links up to 3 steps away from the matching nodes, with no budget cap, and counts the whole result. Then it compares that against reading the whole folder.

It also guesses the folder size. In 0.3.28 it reads the word count from a .graphify_detect.json file in the current folder.

My code-only build didn't write that file, so it guessed 50 words per node: 44,100 words. My report counted 81,502 words. So read the result as a rough guide.

Your real saving depends on your questions and your --budget.

quick-check

You build a Graphify map for a repo that is all code. What does the build cost in tokens?

Quick check: the agent finds a function through the map. Should it still read the function's code before it edits it?

Show answer

Yes. The map says where the code is and what links to it. It doesn't hold the full code. The agent reads the few files the map points to, instead of grepping the whole repo.

Caveman#

Reading is cut. The last layer is what the model writes back.

Here is one answer, two ways. Both examples come from the Caveman README:

Normal:
The reason your React component is re-rendering is likely because you're creating
a new object reference on each render cycle. When you pass an inline object as a
prop, React's shallow comparison sees it as a different object every time, which
triggers a re-render. I'd recommend using useMemo to memoize the object.

Caveman:
New object ref each render, so React re-renders. Wrap the prop in `useMemo`.

Words you need:

  • Tokenizer: the program that cuts text into tokens.
  • tiktoken: OpenAI's tokenizer. o200k is one of its token sets.

Same fix. The README counts 63 tokens against 20. It counted with tiktoken o200k. Claude's tokenizer cuts text a bit differently, so take the counts as a guide.

Paste each version into the box and compare:

token-splitter
Claude,pleasefixtheloginbuginmydashboard.
9 words, about 13 tokens
Type anything. Rough demo: real tokenizers cut text a bit differently, but the idea is the same.

When do you use this? Daily coding work where you want the fix, the command and the reason, and nothing around them.

What Caveman changes#

Caveman is a set of skills that change how the agent writes its replies. Its rules, from the skill itself:

  • Answer first: the thing, the action, the reason, then the next step. No greeting, no recap.
  • Payload verbatim: the payload is the part you will copy or run: code, commands, paths and error messages. Verbatim means it stays exactly the same, character for character.
  • Meaning never dropped: small words like "the" can go. "not", "never", "no" and "only" never go. Numbers stay exact.
  • Full sentences when it matters: it writes plain full sentences for a security warning, an action you can't undo, or a confused user. Then it goes back to short mode.

The README also says Caveman never rewrites what you type.

Install it and switch modes#

Words you need:

  • Proxy: a program that sits between your agent and the Claude API and sees every request.

On my machine Caveman is version 4.0.1, installed as a Claude Code plugin. The README gives these commands:

# Claude Code plugin
claude plugin marketplace add JuliusBrussee/caveman && claude plugin install caveman@caveman

# or only the skill, nothing else
npx skills add JuliusBrussee/caveman -g

The README says the full installer sets up six parts. One of them is a proxy. If you want the full installer, pin the exact version:

npx @caveman-ai/cli@4.0.1

Be careful with any proxy on your API traffic. It sees your prompts, your code and the files the agent reads.

Read the Privacy section in the README before you turn it on. If you only want shorter answers, the plugin or the skill is enough.

The modes, in Claude Code:

CommandWhat you get
/cavemanthe normal Caveman voice: short, full facts
/ultracave or /caveman ultrashorter: fragments, each fact once
/megacave or /caveman wenyanreplies in Classical Chinese, code stays as is
/caveman statusshows the current mode, changes nothing

To turn it off, say stop caveman or normal mode.

Some older guides list six modes (lite, full, ultra and three wenyan levels), turned on by pasting a file into CLAUDE.md. Version 4.0.1 has the modes in the table above.

The honest numbers#

Words you need:

  • Median: the middle result when you sort all results.

The README tested ten dev questions on Claude Opus 5.5. It counted the output tokens with each instruction:

InstructionOutput tokens
none6,983
"Answer concisely."4,334
/caveman4,119
/ultracave2,693

A plain "Answer concisely." line already does most of the work. Compared with that line, /caveman wrote 4,119 tokens instead of 4,334, and /ultracave wrote 2,693.

The README's own summary uses a different number: the median saving per question, out of all ten. Per question, /caveman saved 3% more than "Answer concisely." at the median, and /ultracave 35% more.

Two warnings from the same README. These numbers were measured on the older 3.1.0 rules and not re-run yet. And the rules themselves cost about 1,160 input tokens on each request.

So "be concise" gets you a lot for free. Caveman adds strict rules on top: what to cut, and what must never be cut.

quick-check

Caveman is on. The agent shows you a shell command to run. What happens to the command?

Shrinking memory files with /caveman-compress#

Memory files are the text files Claude Code loads into every session, like CLAUDE.md. They cost input tokens on every request.

/caveman-compress <file> rewrites a memory file in the short style and keeps a backup of the original. The skill warns that it sends the file's full text to your model provider. Don't run it on a file with secrets in it.

When to switch them off#

Every tool in this post cuts something. Sometimes the cut part is the part you need.

Words you need:

  • Runtime: the moment the code actually runs, not the code as written.

Caveman already handles security warnings and actions you can't undo by itself: it writes them in full sentences (Caveman chapter). The other cases are up to you:

SituationWhat to do
A test fails in a strange wayRun the command unfiltered (rtk proxy on 0.35.0, rtk bypass on newer RTK, per the README) and say normal mode, so you see every line and the full reasoning
You are learning a new topicTurn Caveman off. Short answers skip the "why" you are trying to learn
A small repo the agent can read quicklySkip Graphify. Building and reading the map is extra work for little gain
Right after a big refactorRebuild the map (/graphify . --update) before you trust it
A bug that only shows when the code runsUse logs and tests. The map shows how code is linked, not what it does at runtime

A strange failure is the one to remember. All three tools hide detail by design.

strange-failure
  1. A command fails in a way you have never seen.
  2. Rerun it unfiltered and say normal mode.
  3. You see every line and the full reasoning, and find the cause.
  4. Turn the tools back on for every other task.
step 1 / 4
When the cause is in the detail, turn the tools off, find the cause, then turn them back on.
quick-check

A deploy script fails with an error you have never seen. What is the best first move?

Why it works: each tool removes a kind of text the agent rarely needs. When you do need it, you switch the tool off for that one task and keep the saving on all the others.

Recap#

That is the whole token diet: RTK for shell output, Graphify for reading, Caveman for writing.

You can nowWith
Name the three layers of wastewhat the agent reads, what tools print, what the model writes
Explain why noise matters even with prompt cachingcached tokens cost less, not nothing, and still fill the window
Measure, and know what each number counts/context, /usage, rtk gain, graphify benchmark
Cut shell outputrtk init -g, checked with rtk init --show
Give the agent a map of your repo/graphify ., graphify query, graphify claude install
Make answers shorter/caveman, /ultracave, off with stop caveman
Switch the tools off when detail mattersrtk proxy or rtk bypass, normal mode

Try it:

  • Run rtk gain today, work for a day, then run rtk gain --history and see which commands saved the most.
  • Try one tool at a time, and run /usage before and after each one to see what it does in your own sessions.

Read next: Claude Code 101.