Claude-Code-Formatierungshook war korrekt konfiguriert, lief aber nie
Ein Entwickler richtet einen Hook ein, der nach jeder Dateibearbeitung durch Claude Code automatisch den Projekt-Formatter ausführt. Obwohl die Konfiguration korrekt ist, wird der Hook nie ausgeführt, und Pull Requests enthalten unnötige Änderungen an Anführungszeichen und Kommas.

Veröffentlicht am 3. Dezember, ursprünglich erschienen auf runio.dev
Claude Code schreibt korrekten Code in seinem eigenen Stil. Meine Projekte haben einen Formatter, und ich möchte keine Pull Requests, in denen die Hälfte der geänderten Zeilen aus Anführungszeichen und Kommas besteht. Die übliche Antwort ist ein Hook: Nach jeder Dateibearbeitung wird der Formatter auf dieser Datei ausgeführt.
Das ist die Konfiguration in.claude/settings.json:
{ "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-file.sh", "timeout": 30, "statusMessage": "Formatting" } ] } ] } } Der Vollbildmodus wird aktiviert bzw. beendet. Das dahinterliegende Skript liest den Dateipfad aus dem JSON, das Claude Code über die Standardeingabe sendet, wählt anhand der Dateiendung einen Formatter aus und führt ihn aus. Das vollständige Skript, mit Prettier, Pint, PHP-CS-Fixer, Ruff und gofmt, liegt im Repository. Der Teil, der hier relevant ist, ist kurz:
input = $( cat ) file = $( jq -r '.tool_input.file_path // empty' <<< "$input" ) [ -n "$file" ] && [ -f "$file" ] || exit 0 Der Vollbildmodus wird aktiviert bzw. beendet. Das JSON war gültig. Das Skript war ausführbar. /hooks listete den Hook unter PostToolUse auf. Alles sah korrekt aus.
Ich testete es mit der kleinsten Aufgabe, die mir einfiel. Ich bat Claude um eine Datei mit einer Zeile, die kein Formatter unangetastet lassen würde:
export const sum = ( a, b ) => { return a + b } Der Vollbildmodus wird aktiviert bzw. beendet. Claude erstellte die Datei. Ich öffnete sie, und sie enthielt genau diese Zeile. Keine Leerzeichen, keine Zeilenumbrüche, kein Semikolon. Der Formatter hatte sie nicht angefasst.
Meine erste Vermutung war ein fehlerhaftes Skript, also führte ich die Sitzung erneut mit einem Debug-Log aus:
claude --debug-file /tmp/claude.log Der Vollbildmodus wird aktiviert bzw. beendet. Das Log ist der schnellste Weg zu sehen, was Claude Code tatsächlich getan hat. Ich erwartete eine Fehlermeldung meines Skripts. Ich fand etwas anderes: Im Log tauchte kein Hook auf. Claude Code hatte nicht einmal versucht, ihn auszuführen.
Das Log zeigte den Tool-Aufruf, der die Datei erstellt hatte. Es war nicht Write, sondern Bash. Das Modell hatte entschieden, dass sich eine einzeilige Datei am schnellsten mit einem Shell-Befehl erstellen lässt, etwa so:
echo 'export const sum=(a,b)=>{return a+b}' > sum.js Der Vollbildmodus wird aktiviert bzw. beendet. Mein Matcher war Edit|Write. Ein Bash-Aufruf passt nicht darauf, also kam der Hook nie in Frage. Aus der Sicht von Claude Code war nichts schiefgelaufen.
Als ich im Prompt ausdrücklich nach dem Write-Tool fragte, lief der Hook, benötigte 452 Millisekunden, und die Datei wurde zu:
export const sum = ( a, b ) => { return a + b; }; Der Vollbildmodus wird aktiviert bzw. beendet. Der Hook funktionierte also. Er deckte nur nicht jede Art ab, wie eine Datei entstehen kann.
Ein Hook auf ein Tool ist eine Regel über dieses Tool. Sie ist keine Regel über das Ergebnis. "Jede Datei, die Claude schreibt, ist formatiert" und "auf jeden Aufruf von Edit oder Write folgt der Formatter" klingen wie derselbe Satz, und sie sind es nicht.
Das Modell wählt seine Tools frei. Meistens bearbeitet es Dateien mit Edit und Write. Für eine kleine neue Datei, für eine per Befehl erzeugte Datei oder für ein Suchen-und-Ersetzen über viele Dateien mit sed kann es die Shell nutzen. Jeder dieser Wege umgeht einen Matcher auf Edit|Write.
Für andere Hooks ist das wichtiger als für einen Formatter. Wenn derselbe Matcher Dateien davor schützen soll, verändert zu werden, ist die Lücke ein Sicherheitsproblem und kein Stilproblem. Aber beim Formatter habe ich sie zuerst gesehen.
1. Claude sagen, welches Tool es nutzen soll. Eine Zeile in CLAUDE.md wie "Erstelle und ändere Dateien mit den Tools Write und Edit, nicht mit Shell-Befehlen" macht den Shell-Weg selten. Es ist eine Bitte an das Modell, und das Modell folgt ihr meistens. Für die Formatierung reicht das. Es ist keine Garantie.
2. Am Ende des Zuges formatieren, egal welches Tool verwendet wurde. Ein Stop-Hook läuft, wenn Claude kurz davor ist, fertig zu werden. Zu diesem Zeitpunkt weiß git jede geänderte Datei, und es ist egal, wie sie geändert wurde. Dieses Skript übergibt jede geänderte Datei an das oben genannte Formatierungsskript:
#!/usr/bin/env bash # Stop-Hook: jede Datei formatieren, die git als geändert oder neu meldet, # indem sie an das PostToolUse-Skript übergeben wird. cd "${CLAUDE_PROJECT_DIR:-$PWD}" || exit 0 git status --porcelain --untracked-files=all -z | while IFS = read -r -d '' entry; do file = ${entry:3} [ -f "$file" ] || continue jq -n --arg f "$PWD/$file" '{tool_input: {file_path: $f}}' |.claude/hooks/format-file.sh > /dev/null done exit 0 Der Vollbildmodus wird aktiviert bzw. beendet. Registriere es neben dem ersten Hook:
"Stop": [ { "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-changed.sh", "timeout": 60 } ] } ] Der Vollbildmodus wird aktiviert bzw. beendet. Um genau zu sein, was ich getestet habe: Ich führte dieses zweite Skript von Hand in einem Projekt mit unformatierten Dateien aus, darunter eine Datei in einem Unterordner und eine Datei mit einem Leerzeichen im Namen, und es formatierte sie. Als Stop-Hook innerhalb einer Sitzung habe ich es noch nicht ausgeführt. Den ersten Hook, den vom Anfang dieses Artikels, habe ich in echten Sitzungen ausgeführt.
Behalte beide Hooks. Der erste formatiert eine Datei sofort, sodass Claude die formatierte Version sieht, wenn es die Datei erneut bearbeitet. Der zweite fängt, was der erste nicht sehen kann.
Drei Schritte, und sie dauern fünf Minuten:
Die allgemeine Lektion ist die, die ich inzwischen auf jeden Hook anwende, den ich schreibe: Teste ihn, indem du Claude eine Aufgabe gibst, nicht indem du die Konfiguration liest. Eine Konfiguration, die korrekt aussieht, sagt dir nichts darüber, welches Tool das Modell wählen wird.
Das ist eines der Ergebnisse aus dem Testen der Rezepte meines Buchs, The Claude Code Automation Cookbook: 40 Rezepte für Hooks, Subagents, Skills, MCP und CI-Workflows, jedes davon in einer echten Sitzung ausgeführt, bevor es niedergeschrieben wurde. Der Code für alle liegt im GitHub-Repository, mit einem Test für jedes Skript. Das Buch ist auf Amazon als Taschenbuch und für Kindle erhältlich.
Dieser Artikel wurde mit Hilfe von Claude Code geschrieben, auf Grundlage meiner eigenen Testsitzungen. Die Befehle und die Ausgabe habe ich selbst überprüft.
Automatisch übersetzt. Das Original auf Englisch ist unten aufklappbar.
Original (Englisch) anzeigen
Posted on Dec 3 • Originally published at runio.dev
Claude Code writes correct code in its own style. My projects have a formatter, and I do not want pull requests where half of the changed lines are quotes and commas. The usual answer is a hook: after every file edit, run the formatter on that file.
This is the configuration, in.claude/settings.json:
{ "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-file.sh", "timeout": 30, "statusMessage": "Formatting" } ] } ] } } Enter fullscreen mode Exit fullscreen mode The script behind it reads the file path from the JSON that Claude Code sends on standard input, picks a formatter by file extension, and runs it. The full script, with Prettier, Pint, PHP-CS-Fixer, Ruff and gofmt, is in the repository. The part that matters here is short:
input = $( cat ) file = $( jq -r '.tool_input.file_path // empty' <<< "$input" ) [ -n "$file" ] && [ -f "$file" ] || exit 0 Enter fullscreen mode Exit fullscreen mode The JSON was valid. The script was executable. /hooks listed the hook under PostToolUse. Everything looked right.
I tested it with the smallest task I could think of. I asked Claude for a file with one line that no formatter would leave alone:
export const sum = ( a, b ) => { return a + b } Enter fullscreen mode Exit fullscreen mode Claude created the file. I opened it, and it contained exactly that line. No spaces, no line breaks, no semicolon. The formatter had not touched it.
My first guess was a broken script, so I ran the session again with a debug log:
claude --debug-file /tmp/claude.log Enter fullscreen mode Exit fullscreen mode The log is the fastest way to see what Claude Code really did. I expected an error from my script. I found something else: there was no hook in the log at all. Claude Code had not even tried to run it.
The log showed the tool call that created the file. It was not Write. It was Bash. The model had decided that a one-line file is quickest to create with a shell command, something like:
echo 'export const sum=(a,b)=>{return a+b}' > sum.js Enter fullscreen mode Exit fullscreen mode My matcher was Edit|Write. A Bash call does not match it, so the hook was never a candidate. From the point of view of Claude Code, nothing had gone wrong.
When I asked for the Write tool by name in the prompt, the hook ran, took 452 milliseconds, and the file became:
export const sum = ( a, b ) => { return a + b; }; Enter fullscreen mode Exit fullscreen mode So the hook worked. It only did not cover every way in which a file can appear.
A hook on a tool is a rule about that tool. It is not a rule about the result. "Every file that Claude writes is formatted" and "every call of Edit or Write is followed by the formatter" sound like the same sentence, and they are not.
The model chooses its tools freely. Most of the time it edits files with Edit and Write. For a small new file, for a file generated by a command, or for a search-and-replace over many files with sed, it can use the shell. Each of those goes past a matcher on Edit|Write.
This matters more for other hooks than for a formatter. If the same matcher protects files from being changed, the gap is a security problem and not a style problem. But the formatter is where I saw it first.
1. Tell Claude which tool to use. A line in CLAUDE.md such as "Create and change files with the Write and Edit tools, not with shell commands" makes the shell route rare. It is a request to the model, and the model follows it most of the time. That is good enough for formatting. It is not a guarantee.
2. Format at the end of the turn, whatever tool was used. A Stop hook runs when Claude is about to finish. At that point git knows every file that changed, and it does not care how. This script hands each changed file to the formatting script from above:
#!/usr/bin/env bash # Stop hook: format every file that git reports as changed or new, # by handing each one to the PostToolUse script. cd "${CLAUDE_PROJECT_DIR:-$PWD}" || exit 0 git status --porcelain --untracked-files=all -z | while IFS = read -r -d '' entry; do file = ${entry:3} [ -f "$file" ] || continue jq -n --arg f "$PWD/$file" '{tool_input: {file_path: $f}}' |.claude/hooks/format-file.sh > /dev/null done exit 0 Enter fullscreen mode Exit fullscreen mode Register it next to the first hook:
"Stop": [ { "hooks": [ { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/format-changed.sh", "timeout": 60 } ] } ] Enter fullscreen mode Exit fullscreen mode To be exact about what I tested: I ran this second script by hand in a project with unformatted files, including a file in a subfolder and a file with a space in its name, and it formatted them. I have not yet run it as a Stop hook inside a session. The first hook, the one from the beginning of this article, I ran in real sessions.
Keep both hooks. The first one formats a file at once, so Claude sees the formatted version when it edits the file again. The second one catches what the first one cannot see.
Three steps, and they take five minutes:
The general lesson is the one I now apply to every hook that I write: test it by giving Claude a task, not by reading the configuration. Configuration that looks correct tells you nothing about which tool the model will choose.
This is one of the findings from testing the recipes of my book, The Claude Code Automation Cookbook: 40 recipes for hooks, subagents, skills, MCP and CI workflows, each one run in a real session before it was written down. The code for all of them is in the GitHub repository, with a test for every script. The book is available on Amazon as paperback and for Kindle.
This article was written with the help of Claude Code, based on my own test sessions. I checked the commands and the output myself.