Context compression: what Headroom does and why it matters

An open-source tool called Headroom hit 40,000 stars this week for compressing LLM context by 60-95%. A live demo of the underlying techniques \u2014 paste your own code or text, watch tokens disappear.

An open-source tool called Headroom went viral on GitHub this week, crossing 40,000 stars in days. The pitch is compelling and, if you have used Cursor or Claude Code seriously, immediately intuitive: sit between your coding tool and the model, compress the context before it enters the LLM, get the same result for 60-95% fewer tokens.

The 40,000 stars are not because 40,000 developers suddenly discovered token pricing. They are because everyone shipping with agentic coding tools has watched their monthly bill triple and asked the same question: how much of what I am sending to the model is actually necessary?

The answer, it turns out, is not that much. This post walks through four of the compression techniques Headroom-style tools use, with a live demo you can paste your own code or prose into. Watch tokens disappear. Then use the meaning-preserved check at the end to confirm the compressed version still says what the original did.

Note: This demo uses rules-based heuristics inspired by Headroom’s approach. Real production compression uses learned models and achieves 40-70% on real code. This demo achieves 25-50%.

Paste code or text

Loading tokenizer…

The four passes explained

The demo above applies four compression passes in sequence, each removing something different. Here is what each one does and why it matters.

Pass 1 \u2014 Whitespace and comments

The cheapest compression, and often the largest single win. Every empty line, every trailing space, every # or // comment costs tokens. In a well-commented Python file the comments alone can be 20% of tokens. In JavaScript with a full license header at the top, the header can be 5% of the file before any code even starts.

The trade-off: comments contain intent. A function that was clear to write becomes opaque when its explanatory comments disappear. For coding agents that only need to understand behavior (edit this function, fix this bug), comments are usually redundant with the code. For agents doing higher-level design work (should this file even exist?), stripping comments is a bad idea. Real production compressors weight this decision based on the task.

# Calculate the fibonacci number# using dynamic programmingdef fib(n): # Base cases if n <= 1: return n # Build up from bottom a, b = 0, 145 tokens\u2192def fib(n): if n <= 1: return n a, b = 0, 128 tokens (\u221238%)

Pass 2 \u2014 Boilerplate elimination

Every codebase has patterns the LLM does not need to see repeated to understand. Long import blocks. License headers. try/catch scaffolding that catches every error the same way. Log statements that describe what the function is doing at every step.

The insight: an LLM that has seen ten thousand Python files does not need to see import os and import json at the top of yours to know they exist. It can infer them from usage. Similarly, a try/except: log.error(...); raise pattern used identically in five places can be compressed to one instance plus references.

The tradeoff: you lose the ability to check whether imports are correct. If the agent is debugging import errors, stripping the imports is exactly wrong. Task-awareness matters.

Pass 3 \u2014 Semantic chunking

The move from mechanical compression (removing characters) to selective compression (removing whole ideas). Split the input into semantic blocks \u2014 functions in code, paragraphs in prose \u2014 then keep only the blocks relevant to the task at hand.

Full inputfn_a()fn_b()fn_c()fn_d()fn_e()2,400 tokScore by relevanceto task queryfn_a() \u2192 0.82 \u2713fn_b() \u2192 0.31fn_c() \u2192 0.89 \u2713fn_d() \u2192 0.15fn_e() \u2192 0.28Kept onlyfn_a()fn_c()1,050 tok(\u221256%)The scoring step ideally uses an embedding model; this demo uses a keyword heuristic.

The demo above uses a heuristic proxy \u2014 keyword frequency matching against the top few important terms. Real production compressors embed each chunk with a proper model, embed the task query, and score by cosine similarity. That is a much better ranking, but it requires an inference call at compress-time, which is why it is usually done once per file rather than per turn.

Pass 4 \u2014 Reference substitution

The most aggressive compression, and the one that most obviously requires the model to be cooperating. Repeated long strings get replaced with short reference tokens like <REF_1>, and the mapping is included once at the top of the context. The model reads the mapping, then processes the compressed body, substituting mentally as it goes.

This is real. Anthropic’s cache-optimized context format uses similar ideas at the API level. Prompt caching itself is a form of reference substitution \u2014 the cached prefix is served by an ID rather than re-transmitted.

The tradeoff: the model has to actually resolve the references correctly. Weaker models get confused. Stronger models handle it well but may hallucinate a reference that was not defined. This is the most compressor-model-brittle of the four techniques.

The meaning-preserved test

The whole point of compression is to reduce tokens without changing what the input means. The demo above includes a meaning-preserved check at the bottom: it takes your original input and the compressed version, sends both to the site’s embedding endpoint, and computes cosine similarity between the two vectors.

Values above 0.9 indicate the compressed version is semantically nearly identical to the original. Values between 0.75 and 0.9 mean significant compression happened but the core meaning is retained \u2014 usually acceptable. Below 0.75 means the compression was too aggressive; ideas were lost, not just noise.

This is not a perfect signal. Two documents can have similar embeddings while differing in a critical detail (a negation, a specific number). But it is a fast, cheap sanity check that catches obvious cases of over-compression.

When you should not compress

Not every task tolerates context compression. A few cases where the honest answer is: leave it uncompressed.

Exact-syntax tasks. If you are asking the LLM to output a diff, patch a specific line, or match indentation exactly, compression that strips whitespace destroys the signal. The model needs to see the file as it will be modified.

Security review. A compressed version of a security-sensitive file may hide the exact vulnerability you are trying to find. If the pass removes comments, log statements, or “unused” imports, it may remove the very code path the vulnerability lives in.

Debug context. When debugging, the surrounding code matters even when it looks irrelevant. A stripped try/except block may hide the fact that the error you are chasing is being swallowed silently by the caller.

High-precision retrieval. If your RAG system needs to retrieve exact text (regulations, contracts, statutes), compressing before storage means the retrieval will find a summary, not the source. Compress the query, not the corpus.

Why this is happening now

Context compression was possible a year ago and nobody built a tool that hit 40k stars. Why is it hot this month?

Three things converged:

Agentic coding tools got popular. Cursor, Claude Code, Windsurf, and the rest fan out any user prompt into 20-50 sub-calls. Each sub-call includes surrounding context. The total tokens sent per session went from thousands to hundreds of thousands. The bill went up accordingly.

Model pricing did not track that increase. GPT-4o and Claude Opus cost the same per token whether you send 1,000 or 100,000. So the total cost scaled linearly with context, and users started noticing five-figure bills for tasks that used to cost cents.

Vibe coding cost bombs made the news. The $81,267 vibe coding bill at Slash was the story that broke it into the mainstream this week. Every team building on top of coding agents suddenly needed a story for their finance team about how they were controlling this.

Context compression is not the only answer to that pressure. Better prompting helps. Better retrieval helps. Cheaper models help. Rate limiting helps. But compression is the answer that requires no changes to your agent code, no changes to your prompts, and no changes to the model you use. It sits in the middle and just does its thing. That is why it hit 40k stars in a week.

What I would build next

A follow-up post on reference substitution done right \u2014 building a small end-to-end demo where a compression layer sends compressed context to a real Claude endpoint, includes a reference table, and shows that the model still produces the same answer as it would from the uncompressed original. That is the interesting engineering challenge, and it is where the real 60-95% numbers come from.

// discussion

Comments

Replies use GitHub Discussions. You'll need a GitHub account to post.