ai newsFr., 16. Okt.
EilmeldungMeta releases 816B-parameter Muse Spark Open for coding and agent work

Zu großes CLAUDE.md frisst den Kontext der KI-Agenten

Ungebremst wachsende CLAUDE.md-Dateien verbrauchen erhebliche Teile des verfügbaren Kontexts in Claude Code. Empfohlen wird, das Agent-Gedächtnis aktiv unter ein Token-Budget zu halten.

dev.toDonnerstag 21:48 · 15.10.DE9 Min. Lesezeit
Bild: dev.to

Claude Codes eigene Dokumentation sagt einem, wann man eine Zeile in die CLAUDE.md aufnehmen sollte: wenn Claude denselben Fehler ein zweites Mal macht oder wenn man dieselbe Korrektur eintippt wie in der letzten Sitzung (Memory-Dokumentation). Das ist ein guter Rat. Niemand sagt einem jedoch, wann man eine Zeile wieder entfernen sollte.

Deshalb wächst die Datei. Die pnpm-Regel. Die Regel zum Legacy-Billing-Ordner. Eine Release-Checkliste, die man einmal pro Quartal durchläuft. Ein eingefügtes Verzeichnisbaum-Schema aus der Zeit, bevor ein Refactor die Hälfte der Ordner verschoben hat. All das wird zu Beginn jeder Sitzung geladen, noch bevor der Agent eine einzige Datei des Codes öffnet. Subagents laden zudem ihre eigene Kopie, die auf ihren eigenen Kontext angerechnet wird (Dokumentation zum Kontextfenster). Die eingebauten Explore- und Plan-Agents überspringen sie, und ein benutzerdefinierter Subagent kann mit omitClaudeMd: true davon absehen (Subagent-Dokumentation).

Dieselbe Dokumentation setzt ein Ziel: weniger als 200 Zeilen pro CLAUDE.md, weil "längere Dateien verbrauchen mehr Kontext und verringern die Befolgung". Man bezahlt doppelt. Einmal in Token bei jeder Sitzung, und erneut in Regeln, die weniger zuverlässig befolgt werden, weil sie miteinander konkurrieren.

Beginnen Sie damit, was tatsächlich geladen wird. Führen Sie in einer Claude Code Sitzung /context aus und schauen Sie unter Memory files. Claude Code lädt CLAUDE.md und CLAUDE.local.md aus Ihrem Arbeitsverzeichnis und jedem übergeordneten Verzeichnis, dazu Ihre persönliche ~/.claude/CLAUDE.md sowie jede.claude/rules/ Datei ohne paths: Feld. Auto Memory ergänzt die ersten 200 Zeilen oder 25KB seines MEMORY.md Index. Und @path Imports helfen nicht: Die Dokumentation sagt, sie ordnen eine lange Datei "reduzieren aber nicht die Kontextkosten, weil importierte Dateien ebenfalls beim Start geladen werden".

Überschreitet eine Datei die empfohlene Länge, warnt Claude Code beim Start und bei der Ausführung von /status.

Zeilenanzahl ist nur ein grober Anhaltspunkt. Für Token nutzen Sie Anthropics Token-Counting-Endpoint. Der Aufruf ist kostenlos (ratenlimitiert je nach Nutzungsstufe) und zählt mit dem Tokenizer des jeweils angegebenen Modells. Die CLAUDE.md erreicht Claude als User-Message nach dem Systemprompt, sodass es eine faire Näherung ist, jede Datei als eine User-Message zu zählen. Dieses Skript benötigt jq und curl:

#!/usr/bin/env bash # count-context.sh: geschätzte Token pro Instruktionsdatei set -euo pipefail model = " ${ MODEL:- claude -opus-5-5 } " for f in " $@ "; do n = $( jq -Rs --arg m " $model " \ '{model: $m, messages: [{role: "user", content:.}]}' \ " $f " | curl -s https://api.anthropic.com/v1/messages/count_tokens \ -H "x-api-key: $ANTHROPIC_API_KEY " \ -H "anthropic-version: 2023-06-01" \ -H "content-type: application/json" \ -d @- | jq '.input_tokens' ) printf '%7s %s\n' " $n " " $f " done Enter fullscreen mode Exit fullscreen mode Richten Sie es auf Ihre Instruktionsdateien. Pfadbezogene Regeln zählen Sie separat: Sie kosten nur Kontext, wenn sie geladen werden.

chmod +x count-context.sh./count-context.sh ~/.claude/CLAUDE.md CLAUDE.md \.claude/rules/ *.md Enter fullscreen mode Exit fullscreen mode Gibt eine Zeile null aus, hat die API für diese Datei einen Fehler geliefert; führen Sie den curl von Hand aus, um ihn zu lesen. Setzen Sie MODEL auf das Modell, das Ihr Agent tatsächlich verwendet.

Lesen Sie die Zahlen mit einigen Vorbehalten. Die Dokumentation bezeichnet jede Zählung als Schätzung, und eine Zählung kann einige Token enthalten, die Anthropic für Systemoptimierungen hinzufügt und die nicht abgerechnet werden. Blockweise HTML-Kommentare ( <!-- so wie dieser --> ) werden aus der CLAUDE.md entfernt, bevor sie das Modell erreicht, sodass eine Datei voller Maintainer-Notizen hier höher zählt, als sie in einer Sitzung kostet. Und zählen Sie neu, wenn Sie das Modell wechseln: Claude 4.7 und neuere Versionen nutzen einen neueren Tokenizer, der für denselben Text etwa 30 Prozent mehr Token erzeugt, laut derselben Token-Counting-Seite.

Jede immer geladene Regel wird bei jeder Sitzung mitgeschleppt, und bei den meisten Subagents ebenfalls.

Jede Zeile in der CLAUDE.md sollte einen Test bestehen: Benötigt der Agent dies in jeder Sitzung? Die Memory-Dokumentation beantwortet den größten Teil des Restes. Mehrstufige Abläufe gehören in ein Skill. Regeln für einen Teil des Codebase gehören in eine pfadbezogene Regel. Alles, was an einem festen Punkt geschehen muss, etwa ein Lint vor jedem Commit, gehört in einen Hook, der als Shell-Befehl ausgeführt wird, statt im Kontext zu liegen.

Eine pfadbezogene Regel ist eine Markdown-Datei mit einer paths Liste im Frontmatter. Sie wird geladen, wenn Claude eine Datei liest, schreibt oder bearbeitet, die übereinstimmt:

--- paths: - " src/billing/**/*.ts" --- # Billing - Beträge sind ganzzahlige Cents. Niemals Floats verwenden. - Jeder Schreibvorgang läuft über LedgerService. Enter fullscreen mode Exit fullscreen mode Ein Haken dabei: Eine pfadbezogene Regel wird in den Nachrichtenverlauf geladen, sodass /compact sie zusammenfasst, bis wieder eine passende Datei berührt wird. Eine Regel, die eine Komprimierung überstehen muss, gehört in die CLAUDE.md im Projektstamm, die nach /compact erneut von der Festplatte gelesen wird.

Die quartalsweise Release-Checkliste wird ein Skill. Nur die Beschreibung liegt im Kontext, bis der Skill verwendet wird:

--- description: Schneide ein Release. Verwenden, wenn nach Release oder Tag gefragt wird. --- 1. Führe `pnpm test` aus und stoppe bei jedem Fehler. 2. Erhöhe die Version in package.json. 3. Füge die gemergten PRs zu CHANGELOG.md hinzu. 4. Tagge vX.Y.Z und pushe den Tag. Enter fullscreen mode Exit fullscreen mode Speichern Sie sie als.claude/skills/release/SKILL.md. Die Skills-Dokumentation bringt es so auf den Punkt: "der Körper eines Skills wird nur geladen, wenn er verwendet wird, sodass langes Referenzmaterial fast nichts kostet, bis man es braucht."

Die kurze Karte wird jedes Mal gelesen. Das Regal wird nur geöffnet, wenn eine Aufgabe es braucht.

Aufsplitten verschiebt die Kosten. Ausdünnen beseitigt sie, und zwei Arten von Nachweisen lassen sich günstig sammeln.

Die erste ist, wie oft jede On-Demand-Datei tatsächlich geladen wird. Claude Code löst einen InstructionsLoaded Hook aus, wann immer eine CLAUDE.md oder Regeldatei geladen wird, mit dem Dateipfad und einem load_reason von session_start, nested_traversal, path_glob_match, include oder compact. Er kann nichts blockieren; er dient der Protokollierung. Speichern Sie dies als.claude/hooks/log-load.sh:

#!/bin/sh # Eine JSON-Zeile pro lazy geladener Instruktionsdatei. jq -c '{at: (now | todate), file:.file_path, why:.load_reason, by:.trigger_file_path}' \ >> " $CLAUDE_PROJECT_DIR /.claude/instructions.log" Enter fullscreen mode Exit fullscreen mode Machen Sie es ausführbar und registrieren Sie es in.claude/settings.json nur für lazy Loads:

{ "hooks": { "InstructionsLoaded": [{ "matcher": "path_glob_match|nested_traversal", "hooks": [{ "type": "command", "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/log-load.sh" }] }] } } Enter fullscreen mode Exit fullscreen mode Enthält Ihr Projektpfad Leerzeichen, setzen Sie die Variable in escaped Quotes, wie es der Hooks-Guide tut. Fügen Sie.claude/instructions.log zu.gitignore hinzu. Nach ein paar Wochen normaler Arbeit:

jq -r.file.claude/instructions.log | sort | uniq -c | sort -rn Enter fullscreen mode Exit fullscreen mode Das obere Ende dieser Liste zeigt, wohin die Token fließen. Eine pfadbezogene Regel, die in fast jeder Sitzung geladen wird, hat ein so breites Glob, dass sie etwa so viel kostet wie eine immer geladene Zeile; verschärfen Sie das Glob also oder verschieben Sie die Regel gezielt in die CLAUDE.md. Eine pfadbezogene Regel, die nie auftaucht, kostet nichts, aber sie hat entweder ein Glob, das nichts trifft, oder sie deckt Code ab, den in diesem Zeitraum niemand berührt hat.

Korrigieren Sie das Glob, oder entscheiden Sie, ob dieser Code überhaupt noch eine Regel braucht. Regeldateien ohne paths: werden bei session_start geladen, was dieser Hook überspringt; beurteilen Sie diese anhand der zweiten Art von Nachweis.

Die zweite Art von Nachweis ist eine Begründung für jede Zeile, die immer geladen bleibt. Da blockweise HTML-Kommentare vor der Injektion entfernt werden, kostet die Begründung nichts:

- Paketmanager: pnpm. Niemals npm oder yarn. <!-- Hinzugefügt 2026-09: Agent lief npm install, Lockfile-Churn --> Enter fullscreen mode Exit fullscreen mode Eine Zeile ohne Begründung oder mit einer Begründung, die nicht mehr zutrifft, ist ein Kandidat. Verschieben Sie die fraglichen in eine Datei, die nichts importiert, arbeiten Sie eine Woche normal, und nehmen Sie jede Regel zurück, deren Fehler wiederkehrt. Der Rest war totes Gewicht.

Claude Code macht auch selbst einen ersten Durchgang. /doctor prompt-audit (v2.1.283 oder neuer) sucht nach Anweisungen, die für ältere Modelle geschrieben wurden, nach Verweisen auf Dateien oder Befehle, die nicht existieren, und nach Dateien, die sich widersprechen. Es ändert nichts, bis Sie es verlangen. Der einfache /doctor Check schlägt Kürzungen für eine eingecheckte CLAUDE.md vor und streicht, was Claude aus dem Codebase ableiten kann, etwa Verzeichnisstrukturen und Abhängigkeitslisten.

Behalten Sie die Regeln mit Begründung. Parken Sie den Rest und schauen Sie, was Ihnen fehlt.

Codex liest AGENTS.md beginnend am Projektstamm und absteigend bis zu Ihrem Arbeitsverzeichnis, höchstens eine Datei pro Verzeichnis, und verkettet sie, wobei näher liegende Dateien später kommen. Es hört auf, Dateien hinzuzufügen, sobald die kombinierte Größe project_doc_max_bytes erreicht, standardmäßig 32 KiB, und die Dokumentation listet "Instructions truncated" unter den zu behebenden Problemen. Prüfen Sie, wo Sie stehen:

find. -name AGENTS.md -not -path '*/node_modules/*' \ -exec wc -c {} + Enter fullscreen mode Exit fullscreen mode Das Token-Skript funktioniert auch auf AGENTS.md, und das ist wichtig, wenn Sie eine Datei über mehrere Agents hinweg teilen. Claude Code v2.1.277 und neuer liest AGENTS.md direkt, wenn sich keine CLAUDE.md oder CLAUDE.local.md in Ihrem Arbeitsverzeichnis oder darüber befindet. Existiert eine, liest Claude stattdessen diese, es sei denn, die CLAUDE.md importiert @AGENTS.md oder Sie ändern die Einstellung Project instructions in /config. Eine gemeinsame Datei bedeutet ein einziges Budget, das von beiden Agents gelesen wird.

Ich baue Hermes IDE, bewerten Sie diesen Absatz also vor diesem Hintergrund. Hermes betreibt Claude Code, Codex und andere CLI-Agents nebeneinander, jeweils in einem eigenen Terminal, und das Projektgedächtnis folgt der oben beschriebenen Aufteilung.

Die ableitbare Hälfte wird generiert. Hermes durchsucht jedes Projekt nach seinen Sprachen, Frameworks, Architektur und Konventionen und verweist Ihren Agent auf eine Kontextdatei mit den Ergebnissen des Scans. Diese Datei bleibt innerhalb eines Token-Budgets, das Sie pro Projekt festlegen können ( README ). Stack und Aufbau sind keine Zeilen mehr, die Sie von Hand in CLAUDE.md pflegen, und die generierte Version hat ein Limit.

Die Fakten-Hälfte wird angeheftet. Memory- und Context-Pins speichern Fakten und angeheftete Dateien für ein Projekt, und sie erreichen den Agent jeder späteren Sitzung, auch nach einem Neustart. „Die API-Tests brauchen eine lokale Redis-Instanz“ ist ein Pin: Sie sollte die Sitzung überdauern, in der Sie das herausgefunden haben.

Das README beschreibt das Budget für die gescannte Kontextdatei, nicht für die selbst geschriebene CLAUDE.md oder AGENTS.md, sodass Messen, Aufteilen und Ausdünnen weiterhin für diese Dateien gilt. Hermes kann auch mehrere Projekte an eine Sitzung anhängen, und deren Kontext erreicht den Agent gemeinsam, daher setzen Sie das Budget für jedes angehängte Projekt.

Hermes ist kostenlos, als Quellcode unter BSL 1.1 verfügbar und läuft auf macOS, Windows und Linux. Release Notes zu jeder Version finden sich auf GitHub. Es besteht keine Verbindung zu Anthropic, OpenAI, Nous Research oder einem anderen Agent-Anbieter.

Einen Coding-Agent mit Prompts zu versorgen ist heute vor allem Kontextmanagement: was geladen wird, wann, und was es pro Sitzung kostet. Mein Prompt Engineering Pocket Guide behandelt System-Prompts und Context Engineering in Kurzform. Wenn Sie mehr als einen Agent auf einem Repository betreiben, laden Sie Hermes IDE herunter, und wenn Ihnen das Projekt-Budget Tokens spart, vergeben Sie einen Stern auf GitHub.

Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.

Original (Englisch) anzeigen

Claude Code 's own docs tell you when to add a line to CLAUDE.md: when Claude makes the same mistake a second time, or when you type the same correction you typed last session ( memory docs ). It's good advice. Nobody tells you when to take a line out.

So the file grows. The pnpm rule. The rule about the legacy billing folder. A release checklist you run once a quarter. A directory tree pasted in before a refactor moved half the folders. All of it loads at the start of every session, before the agent opens a single file of your code. Subagents load their own copy too, counted against their own context ( context window docs ). The built-in Explore and Plan agents skip it, and a custom subagent can opt out with omitClaudeMd: true ( subagent docs ).

The same docs set a target: under 200 lines per CLAUDE.md file, because "longer files consume more context and reduce adherence." You pay twice. Once in tokens on every session, and again in rules followed less reliably because they compete with each other.

Start with what actually loads. In a Claude Code session, run /context and look under Memory files. Claude Code loads CLAUDE.md and CLAUDE.local.md from your working directory and every directory above it, plus your personal ~/.claude/CLAUDE.md, plus any.claude/rules/ file without a paths: field. Auto memory adds the first 200 lines or 25KB of its MEMORY.md index. And @path imports don't help: the docs say they organize a long file "but don't reduce its context cost, because imported files also load at launch."

If a file is over the recommended length, Claude Code warns you at startup and when you run /status.

Line counts are a rough proxy. For tokens, use Anthropic's token counting endpoint. It's free to call (rate-limited by usage tier) and counts with the tokenizer of whichever model you name. CLAUDE.md reaches Claude as a user message after the system prompt, so counting each file as one user message is a fair approximation. This script needs jq and curl:

#!/usr/bin/env bash # count-context.sh: estimated tokens per instruction file set -euo pipefail model = " ${ MODEL:- claude -opus-5-5 } " for f in " $@ "; do n = $( jq -Rs --arg m " $model " \ '{model: $m, messages: [{role: "user", content:.}]}' \ " $f " | curl -s https://api.anthropic.com/v1/messages/count_tokens \ -H "x-api-key: $ANTHROPIC_API_KEY " \ -H "anthropic-version: 2023-06-01" \ -H "content-type: application/json" \ -d @- | jq '.input_tokens' ) printf '%7s %s\n' " $n " " $f " done Enter fullscreen mode Exit fullscreen mode Point it at your instruction files. Count path-scoped rules separately: they only cost context when they load.

chmod +x count-context.sh./count-context.sh ~/.claude/CLAUDE.md CLAUDE.md \.claude/rules/ *.md Enter fullscreen mode Exit fullscreen mode If a row prints null, the API returned an error for that file; run the curl by hand to read it. Set MODEL to the model your agent actually runs.

Read the numbers with a few caveats. The docs call every count an estimate, and a count may include a few tokens Anthropic adds for system optimizations, which you aren't billed for. Block-level HTML comments ( <!-- like this --> ) are stripped from CLAUDE.md before it reaches the model, so a file full of maintainer notes counts higher here than it costs in a session. And recount when you switch models: Claude 4.7 and later use a newer tokenizer that produces roughly 30 percent more tokens for the same text, per the same token counting page.

Every always-loaded rule rides along on every session, and on most subagents.

Every line in CLAUDE.md should pass one test: does the agent need this in every session? The memory docs answer most of the rest. Multi-step procedures belong in a skill. Rules for one part of the codebase belong in a path-scoped rule. Anything that must happen at a fixed point, like a lint before every commit, belongs in a hook, which runs as a shell command instead of sitting in context.

A path-scoped rule is a markdown file with a paths list in its frontmatter. It loads when Claude reads, writes or edits a file that matches:

--- paths: - " src/billing/**/*.ts" --- # Billing - Amounts are integer cents. Never use floats. - Every write goes through LedgerService. Enter fullscreen mode Exit fullscreen mode One catch: a path-scoped rule loads into message history, so /compact summarizes it away until a matching file is touched again. A rule that must survive compaction belongs in the project-root CLAUDE.md, which is re-read from disk after /compact.

The quarterly release checklist becomes a skill. Only the description sits in context until the skill is used:

--- description: Cut a release. Use when asked to release or tag. --- 1. Run `pnpm test` and stop on any failure. 2. Bump the version in package.json. 3. Add the merged PRs to CHANGELOG.md. 4. Tag vX.Y.Z and push the tag. Enter fullscreen mode Exit fullscreen mode Save it as.claude/skills/release/SKILL.md. The skills docs put it this way: "a skill's body loads only when it's used, so long reference material costs almost nothing until you need it."

The short card is read every time. The shelf is opened only when a task needs it.

Splitting moves the cost around. Pruning removes it, and two kinds of evidence are cheap to collect.

The first is how often each on-demand file actually loads. Claude Code fires an InstructionsLoaded hook whenever a CLAUDE.md or rules file loads, with the file path and a load_reason of session_start, nested_traversal, path_glob_match, include or compact. It can't block anything; it exists for logging. Save this as.claude/hooks/log-load.sh:

#!/bin/sh # One JSON line per lazily loaded instruction file. jq -c '{at: (now | todate), file:.file_path, why:.load_reason, by:.trigger_file_path}' \ >> " $CLAUDE_PROJECT_DIR /.claude/instructions.log" Enter fullscreen mode Exit fullscreen mode Make it executable, then register it in.claude/settings.json for lazy loads only:

{ "hooks": { "InstructionsLoaded": [{ "matcher": "path_glob_match|nested_traversal", "hooks": [{ "type": "command", "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/log-load.sh" }] }] } } Enter fullscreen mode Exit fullscreen mode If your project path contains spaces, wrap the variable in escaped quotes the way the hooks guide does. Add.claude/instructions.log to.gitignore. After a couple of weeks of normal work:

jq -r.file.claude/instructions.log | sort | uniq -c | sort -rn Enter fullscreen mode Exit fullscreen mode The top of that list is where the tokens go. A path-scoped rule that loads in nearly every session has a glob so broad that it costs about as much as an always-loaded line, so tighten the glob or move the rule into CLAUDE.md on purpose. A path-scoped rule that never appears costs nothing, but it either has a glob that matches nothing or covers code nobody touched in that window. Fix the glob, or decide whether that code still needs a rule at all. Rules files without paths: load at session_start, which this hook skips, so judge those by the second kind of evidence.

The second kind of evidence is a reason for every line that stays always-loaded. Since block-level HTML comments are stripped before injection, the reason costs nothing:

- Package manager: pnpm. Never npm or yarn. <!-- Added 2026-09: agent ran npm install, lockfile churn --> Enter fullscreen mode Exit fullscreen mode A line with no reason, or a reason that no longer applies, is a candidate. Move the doubtful ones into a file nothing imports, work normally for a week, and put back any rule whose mistake returns. The rest were dead weight.

Claude Code will also do a first pass. /doctor prompt-audit (v2.1.283 or later) looks for instructions written for older models, references to files or commands that don't exist, and files that contradict each other. It changes nothing until you ask. The plain /doctor checkup proposes trims for a checked-in CLAUDE.md, cutting what Claude can derive from the codebase, such as directory layouts and dependency lists.

Keep the rules with a reason. Park the rest and see what you miss.

Codex reads AGENTS.md starting at the project root and walking down to your working directory, at most one file per directory, and concatenates them with nearer files later. It stops adding files once the combined size reaches project_doc_max_bytes, 32 KiB by default, and the docs list "Instructions truncated" among the problems to troubleshoot. Check where you stand:

find. -name AGENTS.md -not -path '*/node_modules/*' \ -exec wc -c {} + Enter fullscreen mode Exit fullscreen mode The token script works on AGENTS.md too, and that matters if you share one file across agents. Claude Code v2.1.277 and later reads AGENTS.md directly when no CLAUDE.md or CLAUDE.local.md sits in your working directory or above it. If one does, Claude reads that instead, unless the CLAUDE.md imports @AGENTS.md or you change the Project instructions setting in /config. One shared file means one budget to keep, read by both agents.

I build Hermes IDE, so weigh this section with that in mind. Hermes runs Claude Code, Codex and other CLI agents side by side, each in its own terminal, and its project memory follows the split above.

The derivable half is generated. Hermes scans each project for its languages, frameworks, architecture and conventions, and points your agent at a context file with what the scan found. That file is kept within a token budget you can set per project ( README ). The stack and layout stop being lines you maintain by hand in CLAUDE.md, and the generated version comes with a cap.

The facts half is pinned. Memory and context pins save facts and pinned files for a project, and they reach every later session's agent, also after a restart. "The API tests need a local Redis instance" is a pin: it should outlive the session where you found it out.

The README describes the budget for the scanned context file, not for the CLAUDE.md or AGENTS.md you wrote, so measuring, splitting and pruning still apply to those. Hermes can also attach several projects to one session, and their context reaches the agent together, so set the budget on each project you attach.

Hermes is free, source-available under BSL 1.1, and runs on macOS, Windows and Linux. Release notes for each version are on GitHub. It is not affiliated with Anthropic, OpenAI, Nous Research or any agent vendor.

Prompting a coding agent is mostly context management now: what loads, when, and what it costs per session. My Prompt Engineering Pocket Guide covers system prompts and context engineering in short form. If you run more than one agent on a repo, download Hermes IDE, and if the per-project budget saves you tokens, star it on GitHub.

Originaltitel: Your CLAUDE.md Is Eating Your Context. Keep Agent Memory Under a Token BudgetQuelle: dev.to (dev.to). Original öffnen