Author, register and optimize Claude Code hooks
Create and manage hooks that execute automatically in response to specific events in Claude Code, ensuring they are efficient and do not disrupt the user's workflow.
Editor's Note
Before writing a hook, read `references/performance.md` to understand the cost of different interpreters and events. Use the `if` field to gate conditions with zero process startup cost when possible. Avoid registering hooks that run on every prompt, especially blocking ones, as they can significantly impact performance.
When to Use It
- Automatically enforce coding standards on specific tool calls
- Trigger post-processing actions after a tool is used
- Implement lightweight checks that run without user intervention
SKILL.md
SkillsHunter provides this listing for informational purposes only. Review the skill’s source, license, and required permissions before use. You are responsible for deciding whether to install or run it. Terms of Use
Claude Code hook authoring
Every hook is a process spawn on somebody's critical path. This skill exists so that cost is chosen deliberately rather than discovered later.
Read references/performance.md before picking an interpreter or an event — it carries the
measured cost table. Read references/events-and-payloads.md for the event catalog, matcher
semantics, exit codes, and the stdin payload shape.
1. First decide it should be a hook
A hook is the right tool when the behaviour must happen without anyone remembering to ask for it, and the trigger is an event the harness already emits. It is the wrong tool when a guideline or an on-demand check would do.
- Never register a hook that runs on every prompt, and least of all a blocking one — see
~/.claude/memory/feedback_no_per_prompt_hooks.md. The cost is paid most often in exactly the case where the hook does nothing. - Enforcement at generation time (a
PostToolUselint hook) beats a convention that relies on remembering — but only once it is narrowed per §2. - If the work is "do X when the user asks", that is a skill or a slash command, not a hook.
2. Narrow before you spawn — the ladder
Apply the cheapest gate that expresses the condition. Each rung avoids the entire cost of the one below it.
iffield — pattern-gates on tool arguments and costs zero process startup when it does not match. It takes a permission rule, so it gates a Bash command as readily as a path:"if": "Bash(git *)","if": "Write(//**/SKILL.md)". The//root anchor is required on a path pattern; without it the rule silently matches nothing and the hook never runs. It gates rather than enforces — see the reference for what it fails open on.matcher— gates on the event's discriminator (tool name forPreToolUse/PostToolUse,notification_typeforNotification, start mode forSessionStart). Exact string unless it contains regex metacharacters. An absent matcher means every occurrence of that event.- In-script early return — the last resort. It runs after the interpreter has started, so it saves the body's work but never the startup cost. Order these cheapest-first (§4).
A matcher-less PreToolUse or PostToolUse forks on every single tool call. That is the most
expensive mistake available here.
3. Choose async deliberately
The default is async: false, i.e. blocking, as references/events-and-payloads.md states. This line
claimed the opposite until 2026-08-24; the worked example in this very tree disproves it, since
skill-tracked.py sets no async key and does deliver additionalContext, which a backgrounded hook cannot.
Set the value explicitly in any hook whose usefulness depends on it, rather than trusting either sentence — the
failure is silent, and a hook that runs and delivers nothing looks exactly like one with nothing to say.
A blocking hook sits on the user's critical path, so mark everything async: true except the cases that must
return a decision or context to the model:
- a permission decision (
hookSpecificOutput.permissionDecision) additionalContextthe model needs this turn- exit code 2 to block the action
Everything else — telemetry, state files, notifications, archiving — is fire-and-forget.
asyncRewake: true is the middle ground: background execution that wakes Claude on exit 2.
4. Order checks cheapest-first
Inside the script, put the discriminator that rejects most invocations at the top, and anything
involving IO at the bottom. Concretely, in ascending cost: a payload field comparison → an
os.environ lookup → a Path.exists() → a directory glob → reading a file → parsing the session
transcript → forking git → a network call.
Reading transcript_path means streaming the whole session JSONL to EOF. Never do it before the
cheap checks that would have returned.
5. The never-raise contract
A hook must not be able to disrupt Claude Code. Every script in this repo follows this and new ones must too:
- Wrap the stdin parse in a bare
try/exceptthat falls back to{}and exits 0. - Give every subprocess, file operation, and network call its own swallow.
- Exit 0 on every path except a deliberate block (exit 2).
- Pass
timeout=to everysubprocesscall and every HTTP request.
Errors are not surfaced, especially with async: true — a broken hook fails silently. If a
hook does anything consequential, append a JSON line per decision to a log under ~/.claude/,
through a helper that itself cannot raise. plan-archive.py is the reference implementation, and
its log is what made a misfire diagnosable after the fact.
6. Script hygiene
- Windows UTF-8 is handled globally — don't re-fix it per hook. Claude Code sends UTF-8 bytes;
Python on Windows decodes stdin with the system ANSI codepage. It does not raise — CPython
opens stdio with
errors="surrogateescape", so the payload arrives mangled into mojibake,json.loadstill succeeds (JSON punctuation is ASCII), and the hook runs on a populated but corrupted payload. Nothing reaches the never-raiseexcept, which is why it is so quiet. The damage lands wherever a mangled value is used: a non-ASCII repo path sent a whole memo backlog into a directory outside the repo, and madeskill-tracked.pyearly-return on a failed check ofos.path.isdir. Setting"PYTHONUTF8": "1"in theenvblock ofsettings.jsoncloses it for every hook at once, hooks in repos this one cannot edit included, unless the hook's command starts Python with a flag that ignores the variable; those flags are named in the learning~/.claude/learnings/python-windows-console-encoding.md, under "Turning it on changes more than output". A per-filesys.stdin.reconfigure(...)is a second mechanism for the same job, so leave it out. Keepsys.stdout.reconfigure(encoding="utf-8")where a hook already has one. Note the variable is process-wide: it also sets the default encoding foropen()andsubprocess.run(text=True), so a helper that reads codepage-encoded output can start raising where it used to mis-decode. - Derive cwd as
CLAUDE_PROJECT_DIR→payload["cwd"]→os.getcwd(). Addgit rev-parse --show-toplevelonly when the target is repo-relative. realpathbefore git when the path may be a symlink out of the worktree — everything under~/.claude/is symlinked from the dotfiles repo.- Unknown
argv[1]must be a no-op, so a stale command string insettings.jsoncannot re-arm a removed mode. - The shebang is dead text when the hook is invoked as
python script.py; it only applies if the script is executed by path, which is also the slowest form.
7. Registering it
~/.claude/settings.json is a symlink into the dotfiles repo — Write and Edit refuse to write
through symlinks, so resolve it with readlink and edit the real path.
The file stores escaped quotes as literal ", which defeats exact-string editing. Edit it
programmatically, then json.loads the result before writing it back — a syntax error here
breaks every hook at once.
A hook change takes effect without a relaunch, though not always on the very next call.
Measured 2026-09-18: a PreToolUse entry written into a project's .claude/settings.local.json
fired on the next Bash call of the same session. Measured 2026-09-28 on the user-level
settings.json: a new ^Read$ entry and a new if filter did not fire on calls made seconds
after the write, and both fired when the same calls were repeated about a minute later. So no
restart is needed, which is the same fact §8.5 rests on, that the first bad save is already in
force. But a live test run straight after the write proves nothing either way: repeat a miss
before believing it.
8. Verify
python -m py_compile <script>— it must at least parse.- Feed it each payload shape on stdin directly and assert the exit code and stdout. Redirect
HOME/USERPROFILEto a temp dir for any run that writes, so real logs and state stay clean. - Test the discard path as well as the acting path — that is the path that runs most.
- Time it:
time (for i in $(seq 20); do ... ; done)and divide. Compare againstreferences/performance.md; a hook meaningfully above the floor is doing work it could defer. - After any
settings.jsonedit, confirm the JSON parses and that every command string still runs. Parsing is not sufficient —python -Sfused to the quoted path with no separating space is valid JSON and dies withUnknown option: -/. Build the edit in a temp copy, execute each command, and only then copy it over the live file: settings hot-reloads on write, so the first bad save is already in force. - Clean up temp dirs and confirm nothing reached the real log.
9. Findings log
- 2026-11-19 —
PostModelSwitchfires after the picker's save has reached disk, and not at all for an effort-only change. Measured on Claude Code 2.1.322 in a scratchCLAUDE_CONFIG_DIRdriven through a pty: Enter in the/modelpicker had already written"model"tosettings.jsonwhen the hook's first instruction read the file. The payload carriesfrom_model,to_model,requested_modelandsource(pickerhere), with nothing saying whether the pick was saved or session-only. A hook that rewrote the file left the saving session on its pick and a second open session where it was. Changing only the effort, in/effortor with the effort control inside the/modelpicker, savedmodelSettingsand fired no hook.model-default-guard.pyis built on these results.
This section accumulates. When a hook surprises you — a cost, a silent failure, a semantic — add a dated line here rather than leaving it in a session transcript.
-
2026-11-15 — Auto mode refuses a call whose input a
PreToolUsehook changed when its classifier is what decides the call, and passes the same input sent back once, provided the hook then changes nothing. A call an allow rule admits runs rewritten, with no refusal. Measured on Claude Code 2.1.322 over the ninereview-autocallsreview-scope.pychanged in three sessions between 2026-11-13 and 2026-11-16; the transcript record of each call's tool result holds what decided it, underpermissionDecision. The five that/wrap-uplaunched in the turn that invoked it, whoseallowed-toolslists Workflow, recordedreasonType: "rule"withruleSource: "command"and ran. The four made after such a turn had ended recordedreasonType: "classifier"withreasonCode: "classifier:auto-mode:unavailable"and were refused: two relaunches by name that/wrap-upmade once a background run's task notification had opened a new turn, and tworesumeFromRunIdresumes of a/wrap-uprun after a typed prompt. Why the grant reached the five and not the four is in~/.claude/learnings/claude-code-auto-mode-permissions.md, under "A skill'sallowed-toolsgrant lasts one turn". The refusal reads "gave no verdict for Workflow: a hook changed this call's input after auto mode reviewed it", quotes the hook's output, and tells the model to issue the call once more with exactly that input, alone in its next response, and not to retry if it is refused again; it ends by noting that read-only operations do not require the classifier. The resend is reviewed as written and runs the hook again, so a hook that appends unconditionally grows the input on the resend and is refused for good. A rewriting hook has to pass its own output through unchanged, since a skill's grant does not reach a relaunch or resume it makes in a later turn: the hook inreview-scope.pykeeps a single copy of the scope text it appends and leaves alone a call that already carries everything it would write. The refusal first shows on 2.1.322. On 2.1.295, 2.1.316 and 2.1.318 the Windows machine's transcripts hold 35, 4 and 7 calls the classifier decided afterreview-scope.pyhad changed them, the last on 2026-11-08, and every one ran, as the 2026-10-12 entry's probe did. -
2026-10-16 — A Bash
tool_responsecarries the diff of every file the command edited, underbashEditDiff(files[].hunks[].lines), besidestdoutandstderr. Measured with a payload dump fromlocal-time.py: a command that only appended to a tracked file returnedstdout: "edited"and the file's hunks. The command itself is not in the response. A hook that scans Bash output for content has to drop that key, or it reacts to whatever the model just wrote into a file. -
2026-10-12 —
PreToolUseupdatedInputrewrites a call with nopermissionDecisionbeside it, so a hook can change what runs without also deciding whether it may. Measured in auto mode with a probe hook: a Bashechowas replaced by the hook's command, and a Workflow call sentargs: {"a": 1}reached the script as the hook's object. The rewrite replaces the whole input, so copy every field you are not changing. Addingallowto make it work would silently skip the user's permission prompt for that tool, and it is not needed.review-scope.pyrelies on this to widen everyreview-autoscope. The probe ran on a build before 2.1.322, the first build seen refusing a rewritten call that its classifier decides (the 2026-11-15 entry). -
2026-09-30 — Counting registrations is not counting spawns, and the arithmetic that treats them as equal overstates the cost badly.
settings.jsonregisters one^Bash$entry perifpattern, becauseiftakes a single permission rule — sowindows-link-guardappears four times (powershell *ItemType*,pwsh *ItemType*,cmd *,mklink *) andsecret-print-guardfour (*config*,*transcrypt*,*var -l*,*var --list*). Read as duplicates they look like eight spawns per Bash call, ~176 ms at the ~22 ms a guard costs standalone. They are not duplicates, and rung 1 above is why: a non-matchingifcosts zero process startup, so a typical Bash call starts none of them. The measurement that settles it is the transcript, not a stopwatch on one script — pair eachtool_usewith itstool_resultand read the floor. Across 101 Bash calls the fastest round trips were 40 ms including hooks, which no serial sum of three or more guards fits. Budget the chain as what actually matches this command, never as the registration count. +23 ms on every invocation for no behaviour change. All 18 hook commands were switched topython; measured after the change,plan-archive.py donewent 96 → 72 ms and the statusline hook 108 → 84 ms. The statusline then ran every 2 s, so that one alone returned ~0.7 s of CPU per minute; it was removed on 2026-11-19, when the spawn itself proved the cost (see the statusLine row inreferences/performance.md). Writepythonin new hook commands. Note the shim is also a shell alias, which is why it looks free interactively — aliases don't expand in the non-interactive shell that spawns hooks. -
2026-08-19 — Nothing is free: the Windows process-spawn floor is ~29 ms, and a Python hook that does nothing but parse stdin and discard costs ~61 ms. Budget per invocation, not per line of script.
-
2026-08-19 — Bash is not the lightweight option. One fork (
cat,grep) costs 62–64 ms — worse than Python doing a real JSON parse. Bash only wins with builtins and zero forks (~33 ms). -
2026-08-19 — Trimming imports is a non-fix: the whole typical set costs 2.8 ms, while
site.pyalone costs 18.4 ms. Script length is not the lever either (0.2 KB → 11.4 KB spans 6 ms). -
2026-08-19 —
Notificationfires on an idle timeout (~60 s of no user input), not a turn boundary. It is not a "the model finished" signal, and nothing about it implies work completed. -
2026-08-19 —
MessageDisplayforks per streaming chunk with a ~10 s timeout that blocks TUI rendering. Treat it as the most expensive event in the system. -
2026-08-19 — Hooks run under
CREATE_NO_WINDOWwith a fresh invisible console and no controlling TTY; Claude captures stdout and strips ESC bytes. -
2026-08-19 — A content-matching gate fires on prose, not just on commands.
doppler-guard.pytriggered while writing documentation that mentionsdoppler-guard.py. Harmless here, but it is why content matching is the last rung of the ladder: it cannot distinguish doing the thing from writing about it, and every false positive is a synchronous interpreter start. -
2026-08-19 — A hook whose trigger carries no information about the condition it is testing will misfire, however good its checks are.
plan-archive.py doneinferred "the plan is finished" from an idle timeout and archived a plan four minutes after it was written. Ask what the event actually proves before hanging an action on it. -
2026-09-18 — An
ifpattern gates a nested interpreter only by its outer command, and it fails open on anything the command parser cannot decompose. Measured with"if": "Bash(powershell *Junction*)": it matchedpowershell -NoProfile -Command "New-Item -ItemType Junction …", stayed quiet on a plain command and on;/||compounds, and fired anyway on a&&brace group wrapping a multi-linepython3 -c "…". Soifbuys a real reduction and never a guarantee — budget for occasional spawns on complex commands, and reach forpermissions.denywhen the requirement is a hard block. -
2026-09-28 —
ifpatterns match a subcommand of a compound, and a leading*works. Measured live withsecret-print-guard.py:"Bash(git *config*)"fired oncd <dir> && git config --local --list; echo after, and"Bash(*.git/config*)"onecho start; grep -n password <dir>/.git/config. A guard need not be gated on whatever command a compound happens to start with. -
2026-09-29 —
ifpatterns cannot see a heredoc, neither its body nor its<<operator. Measured live:"Bash(*doppler*)"fired onecho dopplerbut not onbash <<'EOF'whose body alone saiddoppler."Bash(*<<*)"never fired on a heredoc command, while the same guard's*config*filter refused the plain listing. So a guard that has to judge scripts fed tobashorsshon a heredoc must be registered withoutif, and pays an interpreter start on every call of that tool. -
2026-09-29 — Auto mode can refuse an edit to a
hooksentry insettings.jsonas Self-Modification, and not consistently. Of two near-identical additions of anifentry, made in the same turn, one was denied and one went through. Treat a denial as the user's decision to make, not something to retry through another route, and say which registration change is still pending. -
2026-09-28 — A guard on Bash text does not cover the other routes to the same content. The Read tool printed
.git/configwith the Bash guard in place, until a^Read$entry with"if": "Read(//**/.git/config)"refused it. A skill's!Context command runs when the skill loads, before any hook, and/transcrypt's had printed the passphrase on every load for months. So a secret guard also needs the other tools' matchers, and a commit-time check that runs every skill's Context commands through it (claude/tests/bash-guards.py). -
2026-08-21 — A malformed command in a blocking
PreToolUsehook matched on^(Bash|Write|Edit)$disables all three mutation tools at once, leaving no way to repairsettings.jsonfrom inside the session — the user has to run a shell command. The JSON-parses check does not catch it, because the file stays well-formed. Validate a candidate copy by running its commands before overwriting the live file (§8.5). -
2026-09-21 — A hook that mutates a directory acts on every file there, including ones it did not put there and does not own.
plan-archive.py doneglobbeddocs/plans/*.mdand moved whatever declared itself finished; in a third-party clone that meant deleting files the repo tracks upstream, between turns, with nothing in the transcript to explain it. Its own log settles the scale: of 41 archive moves, 20 were of files nostart_movedhad ever placed — 14 distinct documents across 7 repos, some moved repeatedly after being restored. It was retired into a/commitstep. Before a hook writes anywhere, ask what distinguishes its own artifacts from everything else in that location; if nothing does, the hook is the wrong instrument. -
2026-09-21 — A text heuristic on the last assistant message is defeated by anything appended after it.
plan-archive.py donewas guarded bylast_assistant_ends_with_question, and a session that appends a fixed marker to every reply madeendswith("?")false on every turn, so the guard never once fired there while logging 1174 correct skips elsewhere. A guard that fails silently in whole sessions reads as a working guard in the aggregate. -
2026-09-21 — Removing a hook does not stop it running. Hooks load at session start, so every live session keeps invoking the command that
settings.jsonno longer registers. Leave the entry point reachable and inert —plan-archive.pystill dispatches onargv[1] == "start"and returns on anything else, so a stale session'sdonecall is a no-op rather than a fall-through.
Out of scope
- Do NOT add a hook without narrowing it per §2 first.
- Do NOT register a hook on every prompt, or a blocking hook on a hot event.
- Do NOT edit
settings.jsonthrough the symlink, or without validating the JSON afterwards. - Do NOT restate content that
references/or a cited memory already owns — add a pointer.
View original Markdown
---
name: hooks
description: >-
Author, register and optimize Claude Code hooks.
TRIGGER when: writing or editing a hook script, changing a `hooks` entry in `settings.json`, a hook
never fires or fires too often, or deciding whether something should be a hook.
DO NOT TRIGGER when: git hooks (pre-commit, pre-push), React hooks or Win32 hooks.
---
# Claude Code hook authoring
Every hook is a process spawn on somebody's critical path. This skill exists so that cost is
chosen deliberately rather than discovered later.
Read `references/performance.md` before picking an interpreter or an event — it carries the
measured cost table. Read `references/events-and-payloads.md` for the event catalog, matcher
semantics, exit codes, and the stdin payload shape.
## 1. First decide it should be a hook
A hook is the right tool when the behaviour must happen *without anyone remembering to ask for
it*, and the trigger is an event the harness already emits. It is the wrong tool when a guideline
or an on-demand check would do.
- **Never register a hook that runs on every prompt**, and least of all a blocking one — see
`~/.claude/memory/feedback_no_per_prompt_hooks.md`. The cost is paid most often in exactly the
case where the hook does nothing.
- Enforcement at generation time (a `PostToolUse` lint hook) beats a convention that relies on
remembering — but only once it is narrowed per §2.
- If the work is "do X when the user asks", that is a skill or a slash command, not a hook.
## 2. Narrow before you spawn — the ladder
Apply the cheapest gate that expresses the condition. Each rung avoids the entire cost of the one
below it.
1. **`if` field** — pattern-gates on tool *arguments* and costs **zero process startup** when it
does not match. It takes a permission rule, so it gates a Bash command as readily as a path:
`"if": "Bash(git *)"`, `"if": "Write(//**/SKILL.md)"`. The `//` root anchor is required on a
path pattern; without it the rule silently matches nothing and the hook never runs. It gates
rather than enforces — see the reference for what it fails open on.
2. **`matcher`** — gates on the event's discriminator (tool name for `PreToolUse`/`PostToolUse`,
`notification_type` for `Notification`, start mode for `SessionStart`). Exact string unless it
contains regex metacharacters. An absent matcher means *every* occurrence of that event.
3. **In-script early return** — the last resort. It runs *after* the interpreter has started, so
it saves the body's work but never the startup cost. Order these cheapest-first (§4).
A matcher-less `PreToolUse` or `PostToolUse` forks on every single tool call. That is the most
expensive mistake available here.
## 3. Choose `async` deliberately
**The default is `async: false`, i.e. blocking**, as `references/events-and-payloads.md` states. This line
claimed the opposite until 2026-08-24; the worked example in this very tree disproves it, since
`skill-tracked.py` sets no `async` key and does deliver `additionalContext`, which a backgrounded hook cannot.
Set the value explicitly in any hook whose usefulness depends on it, rather than trusting either sentence — the
failure is silent, and a hook that runs and delivers nothing looks exactly like one with nothing to say.
A blocking hook sits on the user's critical path, so mark everything `async: true` except the cases that must
return a decision or context to the model:
- a permission decision (`hookSpecificOutput.permissionDecision`)
- `additionalContext` the model needs this turn
- exit code 2 to block the action
Everything else — telemetry, state files, notifications, archiving — is fire-and-forget.
`asyncRewake: true` is the middle ground: background execution that wakes Claude on exit 2.
## 4. Order checks cheapest-first
Inside the script, put the discriminator that rejects most invocations at the top, and anything
involving IO at the bottom. Concretely, in ascending cost: a payload field comparison → an
`os.environ` lookup → a `Path.exists()` → a directory glob → reading a file → parsing the session
transcript → forking `git` → a network call.
Reading `transcript_path` means streaming the whole session JSONL to EOF. Never do it before the
cheap checks that would have returned.
## 5. The never-raise contract
A hook must not be able to disrupt Claude Code. Every script in this repo follows this and new
ones must too:
- Wrap the stdin parse in a bare `try/except` that falls back to `{}` and exits 0.
- Give every subprocess, file operation, and network call its own swallow.
- Exit 0 on every path except a deliberate block (exit 2).
- Pass `timeout=` to every `subprocess` call and every HTTP request.
**Errors are not surfaced**, especially with `async: true` — a broken hook fails silently. If a
hook does anything consequential, append a JSON line per decision to a log under `~/.claude/`,
through a helper that itself cannot raise. `plan-archive.py` is the reference implementation, and
its log is what made a misfire diagnosable after the fact.
## 6. Script hygiene
- **Windows UTF-8 is handled globally — don't re-fix it per hook.** Claude Code sends UTF-8 bytes;
Python on Windows decodes stdin with the system ANSI codepage. **It does not raise** — CPython
opens stdio with `errors="surrogateescape"`, so the payload arrives *mangled into mojibake*,
`json.load` still succeeds (JSON punctuation is ASCII), and the hook runs on a populated but
corrupted payload. Nothing reaches the never-raise `except`, which is why it is so quiet. The
damage lands wherever a mangled *value* is used: a non-ASCII repo path sent a whole memo backlog
into a directory outside the repo, and made `skill-tracked.py` early-return on a failed check
of `os.path.isdir`. Setting `"PYTHONUTF8": "1"` in the `env` block of `settings.json` closes
it for every hook at once, hooks in repos this one cannot edit included, unless the hook's
command starts Python with a flag that ignores the variable; those flags are named in the
learning `~/.claude/learnings/python-windows-console-encoding.md`, under "Turning it on
changes more than output". A per-file
`sys.stdin.reconfigure(...)` is a second mechanism for the same job, so leave it out. Keep
`sys.stdout.reconfigure(encoding="utf-8")` where a hook already has one. Note the variable is
process-wide: it also sets the default encoding for `open()` and `subprocess.run(text=True)`,
so a helper that reads codepage-encoded output can start raising where it used to mis-decode.
- **Derive cwd** as `CLAUDE_PROJECT_DIR` → `payload["cwd"]` → `os.getcwd()`. Add
`git rev-parse --show-toplevel` only when the target is repo-relative.
- **`realpath` before git** when the path may be a symlink out of the worktree — everything under
`~/.claude/` is symlinked from the dotfiles repo.
- **Unknown `argv[1]` must be a no-op**, so a stale command string in `settings.json` cannot
re-arm a removed mode.
- The **shebang is dead text** when the hook is invoked as `python script.py`; it only applies if
the script is executed by path, which is also the slowest form.
## 7. Registering it
`~/.claude/settings.json` is a symlink into the dotfiles repo — Write and Edit refuse to write
through symlinks, so resolve it with `readlink` and edit the real path.
The file stores escaped quotes as literal `"`, which defeats exact-string editing. Edit it
programmatically, then `json.loads` the result **before** writing it back — a syntax error here
breaks every hook at once.
**A hook change takes effect without a relaunch, though not always on the very next call.**
Measured 2026-09-18: a `PreToolUse` entry written into a project's `.claude/settings.local.json`
fired on the next Bash call of the same session. Measured 2026-09-28 on the user-level
`settings.json`: a new `^Read$` entry and a new `if` filter did not fire on calls made seconds
after the write, and both fired when the same calls were repeated about a minute later. So no
restart is needed, which is the same fact §8.5 rests on, that the first bad save is already in
force. But a live test run straight after the write proves nothing either way: repeat a miss
before believing it.
## 8. Verify
1. `python -m py_compile <script>` — it must at least parse.
2. Feed it each payload shape on stdin directly and assert the exit code and stdout. Redirect
`HOME`/`USERPROFILE` to a temp dir for any run that writes, so real logs and state stay clean.
3. Test the *discard* path as well as the acting path — that is the path that runs most.
4. Time it: `time (for i in $(seq 20); do ... ; done)` and divide. Compare against
`references/performance.md`; a hook meaningfully above the floor is doing work it could defer.
5. After any `settings.json` edit, confirm the JSON parses **and that every command string still
runs**. Parsing is not sufficient — `python -S` fused to the quoted path with no separating
space is valid JSON and dies with `Unknown option: -/`. Build the edit in a temp copy, execute
each command, and only then copy it over the live file: settings hot-reloads on write, so the
first bad save is already in force.
6. Clean up temp dirs and confirm nothing reached the real log.
## 9. Findings log
- **2026-11-19** — **`PostModelSwitch` fires after the picker's save has reached disk, and not at all for an effort-only
change.** Measured on Claude Code 2.1.322 in a scratch `CLAUDE_CONFIG_DIR` driven through a pty: Enter in the
`/model` picker had already written `"model"` to `settings.json` when the hook's first instruction read the file.
The payload carries `from_model`, `to_model`, `requested_model` and `source` (`picker` here), with nothing saying
whether the pick was saved or session-only. A hook that rewrote the file left the saving session on its pick and a
second open session where it was. Changing only the effort, in `/effort` or with the effort control inside the
`/model` picker, saved `modelSettings` and fired no hook. `model-default-guard.py` is built on these results.
This section accumulates. When a hook surprises you — a cost, a silent failure, a semantic — add a
dated line here rather than leaving it in a session transcript.
- **2026-11-15** — **Auto mode refuses a call whose input a `PreToolUse` hook changed when its classifier is what
decides the call, and passes the same input sent back once, provided the hook then changes nothing. A call an
allow rule admits runs rewritten, with no refusal.** Measured on Claude Code 2.1.322 over the nine `review-auto`
calls `review-scope.py` changed in three sessions between 2026-11-13 and 2026-11-16; the transcript record of each
call's tool result holds what decided it, under `permissionDecision`. The five that `/wrap-up` launched in the turn
that invoked it, whose `allowed-tools` lists Workflow, recorded `reasonType: "rule"` with `ruleSource: "command"`
and ran. The four made after such a turn had ended recorded `reasonType: "classifier"` with
`reasonCode: "classifier:auto-mode:unavailable"` and were refused: two relaunches by name that `/wrap-up` made once
a background run's task notification had opened a new turn, and two `resumeFromRunId` resumes of a `/wrap-up` run
after a typed prompt. Why the grant reached the five and not the four is in
`~/.claude/learnings/claude-code-auto-mode-permissions.md`, under "A skill's `allowed-tools` grant lasts one turn".
The refusal reads "gave no verdict for Workflow: a hook changed this call's input after auto mode
reviewed it", quotes the hook's output, and tells the model to issue the call once more with exactly that input,
alone in its next response, and not to retry if it is refused again; it ends by noting that read-only operations
do not require the classifier. The resend is reviewed as written and runs the hook again, so a hook that appends
unconditionally grows the input on the resend and is refused for good. A rewriting hook has to pass its own output
through unchanged, since a skill's grant does not reach a relaunch or resume it makes in a later turn: the hook in
`review-scope.py` keeps a single copy of the scope text it appends and leaves alone a call that already carries
everything it would write. The refusal first shows on 2.1.322. On 2.1.295, 2.1.316 and 2.1.318 the Windows
machine's transcripts hold 35, 4 and 7 calls the classifier decided after `review-scope.py` had changed them, the
last on 2026-11-08, and every one ran, as the 2026-10-12 entry's probe did.
- **2026-10-16** — **A Bash `tool_response` carries the diff of every file the command edited**, under
`bashEditDiff` (`files[].hunks[].lines`), beside `stdout` and `stderr`. Measured with a payload dump from
`local-time.py`: a command that only appended to a tracked file returned `stdout: "edited"` and the file's hunks.
The command itself is not in the response. A hook that scans Bash output for content has to drop that key, or it
reacts to whatever the model just wrote into a file.
- **2026-10-12** — **`PreToolUse` `updatedInput` rewrites a call with no `permissionDecision` beside it**, so a
hook can change what runs without also deciding whether it may. Measured in auto mode with a probe hook: a Bash
`echo` was replaced by the hook's command, and a Workflow call sent `args: {"a": 1}` reached the script as the
hook's object. The rewrite replaces the whole input, so copy every field you are not changing. Adding `allow`
to make it work would silently skip the user's permission prompt for that tool, and it is not needed.
`review-scope.py` relies on this to widen every `review-auto` scope. The probe ran on a build before 2.1.322, the
first build seen refusing a rewritten call that its classifier decides (the 2026-11-15 entry).
- **2026-09-30** — **Counting registrations is not counting spawns, and the arithmetic that treats
them as equal overstates the cost badly.** `settings.json` registers one `^Bash$` entry per `if`
pattern, because `if` takes a single permission rule — so `windows-link-guard` appears four times
(`powershell *ItemType*`, `pwsh *ItemType*`, `cmd *`, `mklink *`) and `secret-print-guard` four
(`*config*`, `*transcrypt*`, `*var -l*`, `*var --list*`). Read as duplicates they look like eight
spawns per Bash call, ~176 ms at the ~22 ms a guard costs standalone. They are not duplicates, and
rung 1 above is why: a non-matching `if` costs **zero** process startup, so a typical Bash call
starts none of them. The measurement that settles it is the transcript, not a stopwatch on one
script — pair each `tool_use` with its `tool_result` and read the floor. Across 101 Bash calls the
fastest round trips were **40 ms including hooks**, which no serial sum of three or more guards
fits. Budget the chain as *what actually matches this command*, never as the registration count.
**+23 ms on every invocation** for no behaviour change. All 18 hook commands were switched to
`python`; measured after the change, `plan-archive.py done` went 96 → 72 ms and the statusline
hook 108 → 84 ms. The statusline then ran every 2 s, so that one alone returned ~0.7 s of CPU per
minute; it was removed on 2026-11-19, when the spawn itself proved the cost (see the statusLine
row in `references/performance.md`). Write `python` in new hook commands. Note the shim is also a shell *alias*, which is why
it looks free interactively — aliases don't expand in the non-interactive shell that spawns hooks.
- **2026-08-19** — Nothing is free: the Windows process-spawn floor is ~29 ms, and a Python hook
that does nothing but parse stdin and discard costs ~61 ms. Budget per *invocation*, not per
line of script.
- **2026-08-19** — Bash is not the lightweight option. One fork (`cat`, `grep`) costs 62–64 ms —
worse than Python doing a real JSON parse. Bash only wins with builtins and zero forks (~33 ms).
- **2026-08-19** — Trimming imports is a non-fix: the whole typical set costs 2.8 ms, while
`site.py` alone costs 18.4 ms. Script length is not the lever either (0.2 KB → 11.4 KB spans 6 ms).
- **2026-08-19** — `Notification` fires on an idle *timeout* (~60 s of no user input), not a turn
boundary. It is not a "the model finished" signal, and nothing about it implies work completed.
- **2026-08-19** — `MessageDisplay` forks **per streaming chunk** with a ~10 s timeout that blocks
TUI rendering. Treat it as the most expensive event in the system.
- **2026-08-19** — Hooks run under `CREATE_NO_WINDOW` with a fresh invisible console and no
controlling TTY; Claude captures stdout and strips ESC bytes.
- **2026-08-19** — A content-matching gate fires on prose, not just on commands. `doppler-guard.py`
triggered while writing *documentation that mentions* `doppler-guard.py`. Harmless here, but it
is why content matching is the last rung of the ladder: it cannot distinguish doing the thing
from writing about it, and every false positive is a synchronous interpreter start.
- **2026-08-19** — A hook whose trigger carries no information about the condition it is testing
will misfire, however good its checks are. `plan-archive.py done` inferred "the plan is
finished" from an idle timeout and archived a plan four minutes after it was written. Ask what
the event actually proves before hanging an action on it.
- **2026-09-18** — An `if` pattern gates a *nested* interpreter only by its outer command, and it
fails open on anything the command parser cannot decompose. Measured with
`"if": "Bash(powershell *Junction*)"`: it matched
`powershell -NoProfile -Command "New-Item -ItemType Junction …"`, stayed quiet on a plain command
and on `;`/`||` compounds, and fired anyway on a `&&` brace group wrapping a multi-line
`python3 -c "…"`. So `if` buys a real reduction and never a guarantee — budget for occasional
spawns on complex commands, and reach for `permissions.deny` when the requirement is a hard block.
- **2026-09-28** — `if` patterns match a *subcommand* of a compound, and a leading `*` works. Measured
live with `secret-print-guard.py`: `"Bash(git *config*)"` fired on `cd <dir> && git config --local
--list; echo after`, and `"Bash(*.git/config*)"` on `echo start; grep -n password <dir>/.git/config`.
A guard need not be gated on whatever command a compound happens to start with.
- **2026-09-29** — `if` patterns cannot see a heredoc, neither its body nor its `<<` operator. Measured
live: `"Bash(*doppler*)"` fired on `echo doppler` but not on `bash <<'EOF'` whose body alone said
`doppler`. `"Bash(*<<*)"` never fired on a heredoc command, while the same guard's `*config*` filter
refused the plain listing. So a guard that has to judge scripts fed to `bash` or `ssh` on a
heredoc must be registered without `if`, and pays an interpreter start on every call of that tool.
- **2026-09-29** — Auto mode can refuse an edit to a `hooks` entry in `settings.json` as
Self-Modification, and not consistently. Of two near-identical additions of an `if` entry, made in
the same turn, one was denied and one went through. Treat a denial as the user's decision to make,
not something to retry through another route, and say which registration change is still pending.
- **2026-09-28** — A guard on Bash text does not cover the other routes to the same content. The
Read tool printed `.git/config` with the Bash guard in place, until a `^Read$` entry with
`"if": "Read(//**/.git/config)"` refused it. A skill's `!` Context command runs when the skill
loads, before any hook, and `/transcrypt`'s had printed the passphrase on every load for
months. So a secret guard also needs the other tools' matchers, and a commit-time check that runs
every skill's Context commands through it (`claude/tests/bash-guards.py`).
- **2026-08-21** — A malformed command in a blocking `PreToolUse` hook matched on
`^(Bash|Write|Edit)$` disables all three mutation tools at once, leaving no way to repair
`settings.json` from inside the session — the user has to run a shell command. The JSON-parses
check does not catch it, because the file stays well-formed. Validate a candidate copy by
running its commands before overwriting the live file (§8.5).
- **2026-09-21** — A hook that mutates a directory acts on every file there, including ones it did
not put there and does not own. `plan-archive.py done` globbed `docs/plans/*.md` and moved
whatever declared itself finished; in a third-party clone that meant deleting files the repo
tracks upstream, between turns, with nothing in the transcript to explain it. Its own log settles
the scale: of 41 archive moves, 20 were of files no `start_moved` had ever placed — 14 distinct
documents across 7 repos, some moved repeatedly after being restored. It was retired into a
`/commit` step. Before a hook
writes anywhere, ask what distinguishes its own artifacts from everything else in that location;
if nothing does, the hook is the wrong instrument.
- **2026-09-21** — A text heuristic on the last assistant message is defeated by anything appended
after it. `plan-archive.py done` was guarded by `last_assistant_ends_with_question`, and a session
that appends a fixed marker to every reply made `endswith("?")` false on every turn, so the guard
never once fired there while logging 1174 correct skips elsewhere. A guard that fails silently in
whole sessions reads as a working guard in the aggregate.
- **2026-09-21** — Removing a hook does not stop it running. Hooks load at session start, so every
live session keeps invoking the command that `settings.json` no longer registers. Leave the
entry point reachable and inert — `plan-archive.py` still dispatches on `argv[1] == "start"` and
returns on anything else, so a stale session's `done` call is a no-op rather than a fall-through.
## Out of scope
- Do NOT add a hook without narrowing it per §2 first.
- Do NOT register a hook on every prompt, or a blocking hook on a hot event.
- Do NOT edit `settings.json` through the symlink, or without validating the JSON afterwards.
- Do NOT restate content that `references/` or a cited memory already owns — add a pointer.
Community Reviews & Field Notes
Tried this skill on your own project? Share the model you used and the results you got.