skip to content

How would you build a Claude Code Stop hook that makes Claude run the tests and fix failures before it finishes?

level: seniorimportance: should knowfreq 17%

answer

  1. check the repository, not Claude's word
  2. Stop fires after every response
  3. decision block with a reason
  4. a loop guard and an eight-block cap
  5. /goal as the session-only shortcut

basics

~20 s

A Stop command hook runs the tests and, on failure, prints {"decision": "block", "reason": ...} so Claude keeps working with that reason; it exits early when stop_hook_active is true. An experimental agent hook can verify instead.

solid answer

~40 s

`Stop` fires whenever Claude finishes responding, not only when a task is done, so I write a `command` hook that is cheap when nothing changed: it reads stdin, exits 0 if `stop_hook_active` is already true, skips the run if `git status --porcelain` is empty, and otherwise runs the tests. On green it exits 0; on red it prints `{"decision": "block", "reason": "..."}` with the tail of the failure output, and Claude continues with that reason as its next instruction. The loop guard gives Claude one fix attempt per stop, and Claude Code also overrides a Stop hook after eight consecutive blocks (`CLAUDE_CODE_STOP_HOOK_BLOCK_CAP`). A `prompt` hook cannot run tests, so it only judges Claude's claim; an `agent` hook can run them but is experimental. For a one-off session condition, `/goal` is the built-in shortcut.

code

bash · 15 lines
bash
#!/bin/bash
# .claude/hooks/stop-test-gate.sh: Stop hook, no finishing on red tests
input=$(cat)
if [ "$(jq -r '.stop_hook_active' <<<"$input")" = "true" ]; then
  exit 0                       # already sent back once; let Claude stop
fi
cd "$CLAUDE_PROJECT_DIR" || exit 0
if [ -z "$(git status --porcelain)" ]; then
  exit 0                       # nothing changed in the tree: skip the run
fi
if output=$(npm test 2>&1); then
  exit 0                       # green: allow the stop
fi
jq -nc --arg r "Tests are failing. Fix them before you finish:
$(tail -n 40 <<<"$output")" '{decision: "block", reason: $r}'

go deeper

for a junior

Recall that a Stop hook runs when Claude finishes responding and can send Claude back to work with a reason.

for a middle

Explain the decision block with reason output, why the script must stay cheap on turns with no changes, and what stop_hook_active tells it.

for a senior

Design the gate: deterministic command hook over an agent or prompt hook, the eight-block cap and its variable, timeouts sized to the suite, and the additionalContext alternative for softer feedback.

for a principal

Place the gate in the enforcement stack: a fast local loop that saves review cycles, never a substitute for the pipeline, and tuned so developers do not disable it out of frustration.

## The goal A **Stop gate** stops Claude from declaring victory on red tests. Claude Code fires the `Stop` event when the main agent finishes responding. A hook on that event can **block the stop**: Claude Code then keeps the turn going and gives Claude the hook's reason as its next instruction. It does not fire on a user interrupt, and a turn that ends on an API error fires `StopFailure` instead. ## Building it as a command hook `Stop` has no matcher, so the handler goes straight under the event in `.claude/settings.json`, pointing at a script such as `"$CLAUDE_PROJECT_DIR"/.claude/hooks/stop-test-gate.sh`. The script: 1. **Reads stdin once.** The input carries the common fields plus `stop_hook_active`, `last_assistant_message`, `background_tasks` and `session_crons`. 2. **Respects the loop guard.** `stop_hook_active` is `true` when Claude is already continuing because of a stop hook. Exiting 0 then gives Claude exactly one fix attempt per stop; the event-contract details live with the input/output rules. 3. **Stays cheap when nothing changed.** `Stop` fires after every response, including a one-line answer to a question. Checking `git status --porcelain` first avoids a full test run per reply. 4. **Runs the tests and decides.** On success, exit 0. On failure, print `{"decision": "block", "reason": "..."}` with the useful tail of the output. Exiting 2 with the message on stderr routes the same way. ## Choosing the handler | Handler | What it can check | Trade-off | |---|---|---| | `command` | runs the real test command and reads its exit status | deterministic; you own the script | | `agent` | a subagent runs tests and reads files before answering `ok` | experimental; default timeout 60 s, so raise `timeout` for slow suites | | `prompt` | one model call over the hook input, such as `last_assistant_message` | judges Claude's claim, not the repository | | `/goal` | a model checks your condition after every turn | session-scoped and typed, not configured | `/goal` is documented as a built-in shortcut for a session-scoped, prompt-based Stop hook: useful when one developer wants Claude to keep going until "all call sites compile and tests pass", without editing settings. ## Production details - **The cap.** Claude Code overrides a Stop hook after it blocks **eight times in a row** and ends the turn with a warning. `CLAUDE_CODE_STOP_HOOK_BLOCK_CAP` raises it (or `0` disables it); raise it only when convergence genuinely needs more rounds. - **Feedback without an error label.** Returning `hookSpecificOutput.additionalContext` on `Stop` also keeps the conversation going, under the same loop protections, but the transcript labels it `Stop hook feedback` rather than a hook error. It suits a gentle "run the tests before finishing" nudge. - **Timeouts.** A command hook defaults to 600 seconds; set `timeout` to match the suite. A slow suite on every stop is a real cost to the developer's loop. - **Subagents.** A `Stop` hook declared in a subagent's frontmatter is converted to `SubagentStop`, which uses the same decision fields. - **Scope.** This is a local, in-session gate. It shortens the feedback loop; the pipeline that runs on every push is still the boundary nobody can skip. ## Common mistakes - **Exiting 1 on failure.** Exit 1 is a non-blocking error, so Claude simply stops; block with exit 2 or a JSON `decision: "block"` instead. - **Parsing the transcript for the final answer.** Use `last_assistant_message`; the transcript file is not guaranteed to hold the final message at `Stop` time. - **Ignoring background work.** The `background_tasks` and `session_crons` arrays tell a "finished" session from one paused for a running build or a scheduled wakeup, so a gate can wait instead of failing a half-done change. - **Blocking forever on the impossible.** A missing database or a broken toolchain cannot be fixed by Claude; detect such failures and let the stop through with a `systemMessage` for the user. ## Why not trust the model alone? Instructions in `CLAUDE.md` saying "always run tests before finishing" are guidance the model usually follows. The Stop hook is enforcement: it inspects the repository's real state on every stop, whatever the model believes.

  • Why not make the gate a prompt hook that asks a model whether the tests pass?
    A prompt hook makes one model call over the hook input, such as `last_assistant_message`. It cannot run the suite, so it judges Claude's claim rather than the repository. An agent hook can run tests, but it is experimental and slower; a command hook gives a deterministic answer from the real exit status.
  • Claude keeps working, then ends with a warning that the Stop hook blocked too many times. What happened?
    Claude Code overrides a Stop hook after eight consecutive blocks and ends the turn. Either the script never honours `stop_hook_active`, or the condition cannot be met in this session, such as an environment failure. Fix the guard or the condition; raise `CLAUDE_CODE_STOP_HOOK_BLOCK_CAP` only if convergence genuinely needs more rounds.
  • When would you use /goal instead of a Stop hook in settings?
    `/goal` sets a completion condition for the current session only, and a model checks it after every turn. It suits one developer's one-off task. A Stop hook in settings applies to every session in its scope and can run a deterministic script, so it is the choice for a team-wide rule.

  • A Stop hook fires only once Claude has completed the user's whole task.
  • A Stop gate exiting 1 on failing tests is enough to keep Claude working.
  • Asking a model whether the tests pass is as good as running them.
  • Without a loop guard the session spins forever; nothing ever ends the turn.
  • The Stop hook also fires when the user presses Esc to interrupt Claude.