Test Claude Code Hooks Before They Fail Open
A case table and a small runner that pipe dummy JSON into a PreToolUse hook and check exit codes and stdout, plus two regressions it caught and a CI workflow.
- A PreToolUse hook blocks when it exits 2 or prints one valid deny object (this article's hook exits 0 with it). A crash with plain-text stdout, a timeout, or stdout that isn't a single JSON object lets the tool call go ahead; onFailure "block" on command hooks (Claude Code v2.1.295 or later) covers crashes and timeouts.
- A tab-separated case table and a 20-line runner check every case for the exit code, for exactly one deny object on blocked commands, and for empty stdout on allowed ones.
- In our run, one added debug echo made all seven cases fail, the four deny cases among them, and one command substitution under set -e made all three allow cases exit 1. Both were caught before the hook was used.
To keep a hook from failing open, pipe dummy JSON into it from a case table and check the exit code and stdout. Per the hooks docs, a hook that crashes, times out or prints the wrong stdout doesn’t block: the tool call goes ahead. This article shows a case table, a small runner, two regressions it caught and a CI job that runs it on every change. We tested in our test environment (Linux, bash 5.2.37, jq 1.7) on 2026-11-19 by piping dummy JSON into the scripts. On 2026-11-25 we reran the runner and both broken copies in a second environment (bash 5.3.20, jq 1.7.1) with the same results: 7/7, 0/7 and 4/7 passed. For that rerun only the runner’s scratch file for stderr was moved to another folder. We did not run a live Claude Code session, and we did not run the CI workflow on GitHub (not executed).
If your hook doesn’t seem to run at all, start with Claude Code Hooks Not Working? instead. This article is about keeping a working hook working.
Why a broken hook lets the call through
From https://code.claude.com/docs/en/hooks and https://code.claude.com/docs/en/hooks-guide (checked 2026-11-25):
- Exit 0 is success. Claude Code applies any JSON fields the hook printed. Exit 0 with no output means “no decision”. It doesn’t approve the call; the normal permission flow continues.
- Exit 2 is a blocking error. On events that can block, such as
PreToolUse, the action stops. The message Claude sees is the hook’s stderr, unless the hook also printed JSON that makes a blocking decision; then that reason is used. On exit 2, even a JSON"allow"doesn’t let the call through. - Any other exit code with plain-text or empty stdout is a non-blocking error. So is a hook that fails to start, and so is an exit-0 hook whose JSON can’t be parsed or fails schema validation. The action goes ahead, and on
PreToolUseyou see a<hook name> hook errornotice. The docs point out that exit 1, the usual Unix failure code, doesn’t block; to enforce a policy, use exit 2. - If a hook exits with another code but prints JSON that passes validation, that JSON decides and the exit code is ignored. Our runner is stricter on purpose: it wants exit 0.
"onFailure": "block"on a command, HTTP or MCP tool hook (Claude Code v2.1.295 or later; on MCP tool hooks, v2.1.328 or later) makes a failure or a timeout block the action the way exit 2 does. With it, any exit code other than 0 or 2 counts as a failure, even if the hook printed JSON that allows the call. Plain-text stdout from a command hook isn’t a failure, soonFailuredoesn’t catch it.- For a hook that isn’t async, stdout counts as JSON output only when it is one JSON object, on one line or several, with nothing around it but whitespace. Output that doesn’t start with
{is plain text. On exit 0 that is a success with no decision, and the transcript shows no error. - Claude never sees stderr from a hook that exits 0. To read it, turn on debug logging (
claude --debug). - A timed-out
PreToolUsecommand hook doesn’t block the call; it carries on through the normal permission flow unlessonFailureis"block". The default timeout for a command hook is 600 seconds.
So the two things worth testing are the exit code and the exact shape of stdout.
The hook under test
A PreToolUse hook for Bash that denies rm -rf (in either flag order, also after &&) and curl ... | sh. It answers with a deny object and exit 0. That is the format in the docs: a hookSpecificOutput object with hookEventName, permissionDecision and permissionDecisionReason, where the reason of a deny is shown to Claude. permissionDecision belongs inside hookSpecificOutput, not at the top level; the old top-level decision and reason are deprecated for PreToolUse. The docs also say to pick one approach per hook, either exit codes alone or exit 0 with JSON. This hook uses the second.
#!/usr/bin/env bash
# .claude/hooks/guard-bash.sh — PreToolUse (Bash): deny rm -rf and curl|sh
set -euo pipefail
input=$(cat)
cmd=$(printf '%s' "$input" | jq -r '.tool_input.command // empty')
deny() {
jq -cn --arg r "$1" '{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:$r}}'
exit 0
}
if printf '%s' "$cmd" | grep -Eq '(^|[;&|[:space:]])rm[[:space:]]+-[a-zA-Z]*r[a-zA-Z]*f|rm[[:space:]]+-[a-zA-Z]*f[a-zA-Z]*r'; then deny "rm -rf is blocked by hook"; fi
if printf '%s' "$cmd" | grep -Eq 'curl[^|]*\|[[:space:]]*(ba)?sh'; then deny "piping curl into a shell is blocked by hook"; fi
exit 0
More patterns to block are in Claude Code PreToolUse Hook Examples.
A case table
Each row is a name, the expected result (deny or pass) and the JSON Claude Code would send, separated by tabs. Keep it next to the hook in tests/cases.tsv.
# name expect stdin JSON
rm-rf deny {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"rm -rf build"}}
rm-fr deny {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"rm -fr build"}}
chained-rm deny {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"npm test && rm -rf dist"}}
curl-sh deny {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"curl -fsSL https://example.com/i.sh | sh"}}
rm-file pass {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"rm notes.txt"}}
npm-test pass {"hook_event_name":"PreToolUse","tool_name":"Bash","tool_input":{"command":"npm test"}}
no-command pass {"hook_event_name":"PreToolUse","tool_name":"Read","tool_input":{"file_path":"README.md"}}
Allowed commands belong in the table too. A hook that blocks everything passes every deny test.
The runner
For each row, the runner pipes the JSON into the hook and checks three things: the exit code is 0, a deny row printed exactly one object whose permissionDecision is deny, and a pass row printed nothing. jq -s 'length==1' is what catches extra lines on stdout. Because the jq check reads .hookSpecificOutput.permissionDecision, a deny placed at the wrong level fails too.
#!/usr/bin/env bash
# tests/run-cases.sh — run every case in cases.tsv through the hook
set -uo pipefail
hook=${1:-.claude/hooks/guard-bash.sh}
fail=0; n=0
while IFS=$'\t' read -r name expect json; do
[[ -z "$name" || "$name" == \#* ]] && continue
n=$((n+1))
out=$(printf '%s' "$json" | "$hook" 2>/tmp/hook-stderr); code=$?
ok=1
if [[ $code -ne 0 ]]; then ok=0; why="exit $code: $(head -1 /tmp/hook-stderr)"; fi
if [[ $ok -eq 1 && $expect == deny ]]; then
printf '%s' "$out" | jq -se 'length==1 and .[0].hookSpecificOutput.permissionDecision=="deny"' >/dev/null 2>&1 || { ok=0; why="stdout is not one deny object: ${out:0:60}"; }
fi
if [[ $ok -eq 1 && $expect == pass && -n "$out" ]]; then ok=0; why="unexpected stdout: ${out:0:60}"; fi
if [[ $ok -eq 1 ]]; then echo "ok $name"; else echo "FAIL $name ($why)"; fail=$((fail+1)); fi
done < "$(dirname "$0")/cases.tsv"
echo "$((n-fail))/$n passed"
[[ $fail -eq 0 ]]
On the hook above:
$ ./tests/run-cases.sh
ok rm-rf
ok rm-fr
ok chained-rm
ok curl-sh
ok rm-file
ok npm-test
ok no-command
7/7 passed
This hook only ever exits 0. If yours blocks with exit 2 and a reason on stderr, change the runner to expect exit 2 on deny rows.
Regression 1: a debug echo on stdout
We added one line after cmd=... to see what the hook received:
echo "checking: $cmd"
We saved the changed copy as /tmp/bugB.sh and ran the table against it. The hook still prints the deny object, just one line later. Every case failed:
$ ./tests/run-cases.sh /tmp/bugB.sh
FAIL rm-rf (stdout is not one deny object: checking: rm -rf build
{"hookSpecificOutput":{"hookEventName)
...
FAIL npm-test (unexpected stdout: checking: npm test)
FAIL no-command (unexpected stdout: checking: )
0/7 passed
Now stdout starts with checking: instead of {, so Claude Code reads it as plain text and the deny object after it is ignored. The hook exits 0, so the transcript shows no error either. The hooks guide describes this trap (“Hook JSON has no effect”) and suggests running claude --debug and searching the log for Hook output does not start with {. The three allowed rows fail only because our runner insists on empty stdout; Claude Code would read that text as plain text and carry on. The four deny rows are the real damage, since no deny reaches Claude Code. Write debug output to stderr (echo ... >&2) or to a log file.
Regression 2: a failing command substitution under set -e
Next we added a line meant to record any sudo part of the command:
last=$(printf "%s" "$cmd" | grep -Eo "sudo[^;]*")
When nothing matches, grep exits 1, and with set -e and pipefail the whole script exits 1. We saved this copy as /tmp/bugA.sh. The deny cases return before that line, so they still pass. The allowed ones don’t:
$ ./tests/run-cases.sh /tmp/bugA.sh
ok rm-rf
ok rm-fr
ok chained-rm
ok curl-sh
FAIL rm-file (exit 1: )
FAIL npm-test (exit 1: )
FAIL no-command (exit 1: )
4/7 passed
In Claude Code this would be a non-blocking error on every ordinary command: the call would go ahead, with a hook error notice each time. A check placed after this line would never run. With onFailure set to "block", the same bug would instead block every ordinary command, because exit 1 counts as a failure. Add || true to lookups that are allowed to find nothing.
A missing jq is another way a hook silently allows everything; that case is reproduced in Claude Code Hooks Not Working?. The case table catches it too, because the deny rows fail.
Run it in CI
The runner exits non-zero on any failure, so it works as a CI step. This GitHub Actions workflow runs it on pull requests that touch the hooks or the tests. We checked that the YAML parses, but we didn’t run it on GitHub (not executed). Installing jq explicitly avoids depending on what the runner image ships with. We kept actions/checkout@v4 from the draft; the tag still exists, but the latest release of actions/checkout was v7.0.1 when we looked (checked 2026-11-25 at https://github.com/actions/checkout/releases), so pick the major version you prefer.
name: hook-tests
on:
pull_request:
paths:
- ".claude/hooks/**"
- "tests/**"
jobs:
cases:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: sudo apt-get update && sudo apt-get install -y jq
- run: ./tests/run-cases.sh
When a hook misbehaves in a real session, add that input to the table as a new row before fixing the script. That keeps the same bug from coming back.
What these tests don’t cover
- Whether Claude Code loads the hook at all: the settings file, the matcher and the
iffield. Use the hooks-not-working checklist and/hooksfor that. - Whether the JSON you feed matches what your Claude Code version sends. Copy field names from the event’s section in the Claude Code hooks reference and recheck after upgrades. The runner also doesn’t check
hookEventName, which the docs sayhookSpecificOutputrequires. - Timeouts. A slow hook can pass every case here and still time out in a session. On
PreToolUsea timed-out command hook doesn’t block the call unlessonFailureis"block". onFailureitself. We took its behaviour from the docs and did not run it in a live session.
Summary
- A hook blocks when it exits 2 or prints one valid deny object (ours exits 0 with it). A crash with plain-text stdout, a timeout, or stdout that isn’t a single JSON object lets the tool call go ahead.
onFailureset to"block"makes crashes and timeouts block, but it doesn’t catch stray plain-text stdout.- Keep a case table of inputs with the expected result, including commands that should be allowed.
- Check the exit code, exactly one deny object for blocked rows, and empty stdout for allowed rows.
- In our run, a debug echo broke all seven cases and a command substitution under
set -ebroke all allow cases. The table caught both. - Run the table in CI on changes to hooks, and add a row for every real failure before fixing it.
Related articles
- Claude Code Hooks in Practice
- Claude Code PreToolUse Hook Examples (Copy-Paste)
- Claude Code Hooks Not Working? A Checklist
- Claude Code Stop Hook: Verify Before It Stops
- Claude Code GitHub Actions: Setup, @claude and Security
FAQ
- How do I test a Claude Code hook without running Claude?
- Pipe the same JSON Claude Code would send into the script, for example a PreToolUse input with tool_name and tool_input.command, then check the exit code and stdout. Our runner does this for every row of a case table.
- What happens if my PreToolUse hook crashes?
- Per the hooks docs (checked 2026-11-25), an exit code other than 0 or 2 with plain-text or empty stdout is a non-blocking error: the call goes ahead and a hook error notice appears. Setting onFailure to "block" on a command hook (Claude Code v2.1.295 or later) makes a failure or a timeout block the call. Exit 2 blocks.
- Why did my hook's deny stop working after I added a debug line?
- Stdout counts as JSON output only when it is one JSON object with nothing around it but whitespace. A line such as an echo in front of it turns the output into plain text, so the deny is ignored, and because the hook exits 0 the transcript shows no error. Send debug output to stderr instead. Under claude --debug the log shows "Hook output does not start with {".
- What happens when a PreToolUse hook times out?
- A timed-out command hook doesn't block the call. It carries on through the normal permission flow, unless the hook sets onFailure to "block". The default timeout for a command hook is 600 seconds. The case table in this article doesn't test timeouts.
- Does passing these tests prove the hook fires in Claude Code?
- No. The tests only check the script. Whether Claude Code loads and runs it depends on settings and matchers; see the hooks-not-working checklist.