The problem: at some point Claude forgets the rules
You have been working for two hours on a big repository, Claude Code follows to the letter the convention on amounts in cents and then, suddenly, writes a decimal number. It is not random distraction: in the meantime the session has been compacted, that is the conversation has been replaced by a summary, and the rule existed only in a message that you had written. A window of one million tokens moves the moment when this happens, it does not eliminate it.
The short answer is what comes back and what does not. After compaction three things return, re-read from
disk: the CLAUDE.md in the project root, the rules in .claude/rules/ without a
paths filter, and the auto memory. What you said in the chat does not return, and the
CLAUDE.md files of subfolders and the rules with paths return only "on demand". So the
instructions that must hold for the whole session go on disk, in the right place, and their state can be
checked with a command before anything goes wrong.
The article explains the official table of what survives, translates it into a small script that classifies a
project's instruction files, and shows how to choose the compaction threshold. To write a good
CLAUDE.md start from Context and Project Setup with
Claude; for the snapshot of a model with a 1M context, by now historical, there is
Claude Opus 4.7 and 1M Context: Workflow on Real
Monorepos.
Why a bigger context is not a better memory
The context window is everything the model can consult while it answers: the system prompt, the messages, the tool results, the tool definitions and even the reasoning it produces. The API page on context windows adds a warning that is worth more than the capacity: more context is not automatically better, because as tokens grow accuracy and recall degrade, a phenomenon that the documentation calls context rot. Curating what sits in the context matters as much as the space available.
Claude Code does not wait for the limit to step in. On models with a native 1M window, automatic compaction starts shortly before the window fills. When it starts, the conversation is replaced by a structured summary and much of the initial content is reloaded. The practical point is that compaction is a normal event of the session, not a fault: it must be planned for as the restart of a service is planned for, deciding in advance which information has to reappear by itself.
What comes back after compaction
The "Explore the context window" page reports a table with one mechanism per row. Here I reorder it into four fates, because it is the criterion you need when you must decide where to write a rule.
| Fate | What | How it comes back |
|---|---|---|
| Always comes back | CLAUDE.md in the root and rules without paths; auto memory; plan written in plan mode; system prompt and output style | Re-read from disk |
| Comes back on demand | CLAUDE.md in subfolders and rules with paths | They reload when Claude reads or edits a related file again; until then they are in the summary |
| Comes back with a cap | Files read or edited; body of invoked skills | Up to five files, the most recent, and long files only as a path reference; skills with a maximum per skill and one in total |
| Does not come back as text | Instructions given only in chat; context previously added by hooks | It goes into the summary with everything else |
The row that does damage is the second. A folder rule (for example a CLAUDE.md inside
services/payments/) loads when Claude touches a file of that folder and ends up in the message
history; compaction summarizes it like everything else, and the documentation warns that if a rule must survive
compaction it is better to remove the paths filter or move it into the root
CLAUDE.md. The price is a longer root file, and the guide recommends staying under 200 lines per
file: often the right solution is to move into the root only the three or four truly cross-cutting rules.
There is also a distinction of nature. The same documentation specifies that Claude treats instruction files as context, not as enforced configuration: no guarantee of strict compliance, especially with vague or conflicting instructions. For what must always happen at a precise point, such as running the tests before every commit, the tool is a hook, which runs a command regardless of what Claude decides to remember.
A check you can run: where does each rule live?
To avoid trusting memory I turned the table into a script. To try it I created a small test project, an
invoice manager, with seven files (six in Markdown and one TypeScript file in src/api): a
seven-line CLAUDE.md in the root, a CLAUDE.local.md, two rules (one without a filter,
one limited to src/api), a release skill and a CLAUDE.md in
services/payments full of refusal codes of the payment network, generated by me and deliberately
long. The command below shows its structure.
find repo-prova -type f | sort
# Output:
# repo-prova/CLAUDE.local.md
# repo-prova/CLAUDE.md
# repo-prova/.claude/rules/api.md
# repo-prova/.claude/rules/style.md
# repo-prova/.claude/skills/release/SKILL.md
# repo-prova/services/payments/CLAUDE.md
# repo-prova/src/api/status.ts
The script that follows reads all the .md files of the project and for each one prints lines,
characters and fate. The classifica function is the official table in code form: root and rules
without paths are "re-read from disk", subfolder files and rules with paths are "on
demand". ha_paths looks only at the initial YAML frontmatter, because the documentation says that
paths is the only field Claude Code reads in a rule. The constants at the top are the limits
declared by today's documentation and must be updated if they change.
"""Tell, for each instruction file of a project, what happens to it at compaction."""
import sys
from pathlib import Path
RIGHE_CONSIGLIATE = 200
LIMITE_A_DEMANDA = {"200K window": 40_000, "1M window (recent models)": 150_000}
SALTATO_OLTRE_BYTE = 4 * 1024 * 1024
def ha_paths(testo):
"""True if the file starts with a YAML frontmatter that contains `paths:`."""
if not testo.startswith("---"):
return False
intestazione = testo.split("---", 2)[1] if testo.count("---") >= 2 else ""
return any(r.strip().startswith("paths:") for r in intestazione.splitlines())
def classifica(percorso, radice):
rel = percorso.relative_to(radice)
testo = percorso.read_text(encoding="utf-8")
if rel.as_posix() in ("CLAUDE.md", ".claude/CLAUDE.md"):
return "re-read from disk after compaction", False
if rel.as_posix() == "CLAUDE.local.md":
return "the official table does not list it: to be verified", False
if rel.parts[:2] == (".claude", "rules"):
if ha_paths(testo):
return "summarized; returns only if you touch a matching file again", True
return "re-read from disk after compaction", False
if rel.name == "CLAUDE.md":
return "summarized; returns only if Claude re-reads a file in that folder", True
if rel.name == "SKILL.md":
return "only if invoked: body re-inserted, at most 5,000 tokens (the beginning is kept)", False
return None, False
def main(radice):
radice = Path(radice)
for percorso in sorted(radice.rglob("*.md")):
esito, a_demanda = classifica(percorso, radice)
if esito is None:
continue
testo = percorso.read_text(encoding="utf-8")
righe, caratteri = len(testo.splitlines()), len(testo)
print(f"{percorso.relative_to(radice).as_posix():34} {righe:5} lines {caratteri:7} chars {esito}")
if percorso.name != "SKILL.md" and righe > RIGHE_CONSIGLIATE:
print(f" ! over {RIGHE_CONSIGLIATE} lines: more context spent, less adherence")
if a_demanda:
for nome, limite in LIMITE_A_DEMANDA.items():
if caratteri > limite:
print(f" ! over {limite} characters ({nome}): Claude receives only the beginning")
if percorso.stat().st_size > SALTATO_OLTRE_BYTE:
print(" ! over 4 MiB: Claude Code skips it")
if __name__ == "__main__":
main(sys.argv[1])
# Output:
# .claude/rules/api.md 6 lines 185 chars summarized; returns only if you touch a matching file again
# .claude/rules/style.md 2 lines 118 chars re-read from disk after compaction
# .claude/skills/release/SKILL.md 8 lines 298 chars only if invoked: body re-inserted, at most 5,000 tokens (the beginning is kept)
# CLAUDE.local.md 1 lines 40 chars the official table does not list it: to be verified
# CLAUDE.md 7 lines 307 chars re-read from disk after compaction
# services/payments/CLAUDE.md 902 lines 79465 chars summarized; returns only if Claude re-reads a file in that folder
# ! over 200 lines: more context spent, less adherence
# ! over 40000 characters (200K window): Claude receives only the beginning
The six lines say what you expect: the root CLAUDE.md and style.md come back by
themselves; api.md comes back only if Claude touches a file of src/api again. The
skill release comes back only if it
was invoked, and its body has a cap of 5,000 tokens per skill with the tail cut. The CLAUDE.local.md
row is honest: the official table does not list it, so the script does not invent a fate. The two warnings
under the payments CLAUDE.md are the most useful: 902 lines are above the recommended
200, and 79,465 characters exceed the 40,000 that the documentation indicates as the limit for an "on demand"
file when the window is 200K. In that case Claude receives only the beginning of the file, with a note telling it
to read the rest with the Read tool.
Characters are counted with wc -m, as the memory page suggests. The number must be compared with the
limit of your window: the script prints a warning for each limit exceeded, so you see at once that the file would
be truncated at 200K but not at 1M (150,000 characters on recent models). I cannot tell you which of the two
windows your session is using without looking at it: this is why the checkpoint remains
/context.
Choosing when to compact
The default threshold is not sacred. Claude Code lets you move it in four ways: the /autocompact
command with a value (which saves the choice for the model in use), the --autocompact flag for a
single launch, the autoCompactWindow key in the settings, and the
CLAUDE_CODE_AUTO_COMPACT_WINDOW variable for scripts and cloud environments. The order of
precedence is written explicitly: the variable beats command, flag and setting, and when it is present the
status line percentage stops indicating the moment of compaction. Compacting earlier means more frequent
summaries and a less full window at every request; compacting late leaves more literal details but more "noise"
in the context. I did not measure which of the two choices costs less on real work.
There is a trap here, written in the documentation, and the flag is a convenient way to see half of it. The
accepted values go from 100K to 1M, in the forms 200000, 500k, 1M or a
bare number between 100 and 1000 that counts as thousands. With the environment variable, however, a number
without a suffix is read as that number of tokens: 200 is 200 tokens. The block below tries the flag
with a subcommand that starts no conversations; the CLI validates the value immediately, before any request.
# Same technique: the value of --autocompact is validated immediately, before any request
for valore in auto 200k 50 5000k; do
claude --autocompact $valore auth status >/dev/null 2>errore.txt
echo "--autocompact $valore -> exit $? | $(head -c 200 errore.txt)"
done
# Output:
# --autocompact auto -> exit 0 |
# --autocompact 200k -> exit 0 |
# --autocompact 50 -> exit 1 | error: option '--autocompact <auto|tokens>' argument '50' is invalid. It must be 'auto', or between 100k and 1M (e.g. 500k, 200000, or 200 as shorthand)
# --autocompact 5000k -> exit 1 | error: option '--autocompact <auto|tokens>' argument '5000k' is invalid. It must be 'auto', or between 100k and 1M (e.g. 500k, 200000, or 200 as shorthand)
The behavior is the one described: auto and 200k pass with code 0, while
50 and 5000k fail with code 1 and the message that reports the valid range. Note that
50 is rejected because the shorthand applies only to bare numbers from 100 to 1000: below 100 it is
not a shorthand, it is an error. This check concerns only the acceptance of the flag; it says nothing about when
compaction starts in a real session, because to see that you need a long conversation.
How to verify it in your session
The test that counts is done in your session, and the documentation indicates the tools. Before compacting,
/context all shows consumption by category and the list of "Memory files" loaded at startup: if a
rule is not there, Claude does not see it. Then /compact accepts instructions, and it is worth
telling it what to keep instead of letting it guess. Finally a second /context all shows what is
left. Remember that a subfolder CLAUDE.md does not appear among the "Memory files" because it loads
on demand: a "Loaded" line appears instead in the terminal when it happens.
# Run in a Claude Code session (not executed: it needs a model)
/context all
/compact focus on the file being edited and on the invoicing rules
/context all
I did not run this sequence and I report no consumption numbers: it requires an interactive session with a model
and an account with credit. The way to turn it into a real test is to put one recognizable rule only in the chat
and another only in the root CLAUDE.md, compact, and ask Claude to apply both. If the first
disappears and the second does not, you have reproduced the table with your own eyes.
Status as of 2026-11-12: thresholds and limits
These are the values that change with versions, read on 2026-11-12 on the pages indicated at the bottom. If you reread the article in a few months, start from here.
- The models with a native 1M window (Fable family, Sonnet 5 and later, Haiku 5.5, Opus 4.7 and later) compact at about 967K tokens by default.
- Opus 4.6 and Sonnet 4.6 without the
[1m]variant compact at 200K; withCLAUDE_CODE_DISABLE_1M_CONTEXT=1even the native 1M models stop at 200K. - Limit for "on demand" files: 40,000 characters with the 200K window; with 1M, 200,000 on Opus 4.6 and Sonnet 4.6 and 150,000 on later models.
- After compaction up to five files come back; files over 5,000 tokens come back as a path reference. Invoked skills: 5,000 tokens each, 25,000 in total.
- Skill descriptions are rebuilt from Claude Code version 2.1.304;
/autocompactsaves the choice per model from 2.1.288.
The first item explains the word "about": the documentation does not offer an exact threshold in tokens, and I do
not turn it into a percentage. The other four are caps, and a cap serves to decide where to write: if you have a
skill with the important instructions at the bottom, the tail can be cut; if you have a folder
CLAUDE.md of 150,000 characters, the last pages never reach Claude without an explicit read.
What stays true with the next generation
The numbers will change, the structure will not. The context always fills up, sooner or later, and compaction is
how Claude Code responds. What must hold for the whole session is written in a file re-read from disk, what holds
for a part of the code sits in a folder rule with the awareness that it comes back on demand, what must always
happen is a hook. And you look at /context instead of guessing: these are three habits that survive
any window of 1M, 2M or 10M.
What I did not verify
I did not run any session with a model. So I did not observe compaction, I did not read what a summary contains,
and I did not compare consumption before and after. The fate of CLAUDE.local.md is not in the
official table and the script declares it as such. The effect of context rot is a statement of the API
documentation: I did not measure it, nor can I tell you from which length it becomes visible. I did not read the
pages on idleCompaction or those on server-side compaction, so I do not describe them.
What you can do now
You can predict what survives a compaction and why a 1M window does not change the answer. You can choose where to write a rule (root, folder, hook, memory), you can recognize an instruction file that is too long, and you can adjust the compaction threshold with a value that the CLI accepts. The step left to you is the test in a session, with one rule put in the chat and one put on disk.
In this series. Previous article: Claude Effort and Adaptive Thinking: Measure the Right Level Instead of Guessing It. Next article: What a Claude Session Costs: Measure It Before the Invoice.
Sources
- Claude Code Docs: Explore the context window - "What survives compaction" table, what to do before the context fills,
/context, accessed 2026-11-12 - Claude Code Docs: How Claude remembers your project - locations of
CLAUDE.mdfiles, rules withpaths, 200-line limit and limits for on-demand files, "Instructions seem lost after /compact" section, accessed 2026-11-12 - Claude Code Docs: Model configuration - compaction window, accepted values, precedence of
CLAUDE_CODE_AUTO_COMPACT_WINDOW, default threshold of about 967K, accessed 2026-11-12 - Claude Docs: Context windows - what counts in the window and the warning about context rot, accessed 2026-11-12
- Claude Docs: Models overview - equivalence between 1M tokens and words on the current tokenizer, accessed 2026-11-12
The survives.py script, the find command and the tests of the --autocompact flag were run on 2026-11-12 (Claude Code 2.1.322, Python 3), in their English versions; the procedure with /context and /compact was not run.
Commenti
Caricamento commenti...
Sign in to comment