Claude Code Stop Hook: Run Tests Without an Infinite Loop
Prepared and checked using AI. Sources are linked in the article.
To make a Claude Code Stop hook run tests without an infinite loop, run tests from the event’s working directory and exit immediately when stop_hook_active is true. On the initial stop, check the tests and return useful failure details with a request to continue. On the hook-triggered continuation, allow Claude to stop—even if the underlying problem remains unresolved.
That policy gives Claude a bounded opportunity to repair failures. It does not guarantee passing tests before the turn ends.
Select the active worktree
The hook’s JSON cwd follows Claude into a worktree, while CLAUDE_PROJECT_DIR can remain at the original project root. Use the latter to locate the hook script and the former to select the code being checked.
Resolve cwd through git rev-parse --show-toplevel, which returns the working tree’s top-level directory. This also handles Claude stopping while its current directory is inside a subdirectory. If it is inside a submodule, the selected root belongs to that repository; adjust the policy if your tests belong to the superproject.
If the selected checkout is unexpected, first verify the agent’s worktree and branch.
Register a synchronous Stop hook
The following example uses a Python project with pytest, a script at .claude/hooks/stop-tests.py, and a 90-second test budget inside a 120-second hook timeout. These are sample choices; adjust them for your suite.
Prerequisites:
- Git and Python 3 are available to the hook process.
- The selected Python environment contains pytest and the project’s dependencies.
- The test command finishes without watch mode or interactive input.
Add this configuration to .claude/settings.json for project settings, merging it into any existing hooks object:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "python3",
"args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/stop-tests.py"],
"timeout": 120
}
]
}
]
}
}
Keep this check synchronous: async: true hooks cannot block stopping. The args array passes the script path as one argument without shell quoting.
The script runs python -m pytest to invoke pytest through Python. It uses sys.executable to select the interpreter running the hook, so configure command with your environment’s Python path if python3 selects the wrong interpreter.
Return a bounded failure report
Save this script at the configured path:
import json
import subprocess
import sys
TEST_COMMAND = [sys.executable, "-m", "pytest"]
TEST_TIMEOUT = 90
FEEDBACK_LIMIT = 6000
def block(reason):
print(json.dumps({"decision": "block", "reason": reason}))
return 0
def main():
try:
event = json.load(sys.stdin)
# Check before resolving paths or starting tests.
if event.get("stop_hook_active") is True:
return 0
root = subprocess.run(
["git", "rev-parse", "--show-toplevel"],
cwd=event["cwd"],
capture_output=True,
text=True,
check=True,
timeout=5,
).stdout.strip()
try:
result = subprocess.run(
TEST_COMMAND,
cwd=root,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
errors="replace",
timeout=TEST_TIMEOUT,
)
if result.returncode == 0:
return 0
status = f"Test command exited with status {result.returncode}."
output = result.stdout or ""
except subprocess.TimeoutExpired as error:
status = f"Test command exceeded {TEST_TIMEOUT} seconds."
output = error.stdout or b""
if isinstance(output, bytes):
output = output.decode("utf-8", errors="replace")
return block(
f"{status}\n"
f"Working tree: {root}\n"
f"Command arguments: {json.dumps(TEST_COMMAND)}\n"
f"Output tail:\n{output[-FEEDBACK_LIMIT:]}\n\n"
"Investigate the reported failure. Fix it if appropriate and "
"rerun the test command before finishing. If it remains blocked "
"by dependencies, infrastructure, or an unrelated failure, "
"report that explicitly. Do not claim the tests passed."
)
except (OSError, ValueError, KeyError, TypeError,
subprocess.SubprocessError) as error:
print(f"Stop test hook could not complete: {error}", file=sys.stderr)
return 1
sys.exit(main())
Python’s subprocess.run supports an explicit working directory, combined output capture, and a timeout that kills and waits for the child process. That timeout is not a process-tree cleanup policy; suites that launch servers or other descendants need their own teardown.
The script deliberately separates these outcomes:
| Outcome | Hook response |
|---|---|
| Tests pass | Exit 0 without a blocking decision |
| Tests return a nonzero status | Exit 0 with JSON decision: "block" and failure details |
| Tests exceed the sample time budget | Return a blocking decision with captured output |
| Input, repository lookup, or process startup fails | Exit 1 with a hook diagnostic |
stop_hook_active is true | Exit 0 before running tests |
For Stop, decision: "block" requires a reason and asks Claude to continue. This uses structured JSON with exit 0; another supported approach is exit 2 with feedback on stderr. Do not simply pass through the test runner’s exit status: pytest uses 1 for failed tests and 5 when no tests are collected, whereas a hook exit of 1 is nonblocking.
The output tail limits feedback to the sample 6,000 characters. The script still captures the complete command output in memory, so use a focused suite or adapt output handling for very noisy tests.
Verify the guard and accept its trade-off
From the project root containing .claude/hooks/stop-tests.py, run the script using its relative path to check the continuation path without running tests:
printf '%s\n' '{"stop_hook_active":true}' | python3 .claude/hooks/stop-tests.py
The script should exit 0 without output. It deliberately needs no cwd on this path because the guard runs first.
From the intended worktree root, exercise the initial-stop path:
python3 -c 'import json, os; print(json.dumps({"cwd": os.getcwd(), "stop_hook_active": False}))' | python3 .claude/hooks/stop-tests.py
A passing suite should produce no output. A failing suite should produce one JSON object containing the selected root, command, status, output tail, and repair instruction. Confirm the registration through /hooks in Claude Code as well.
The guard permits stopping after the repair continuation without another automatic test check. Ask Claude to rerun tests in the failure message, and require a separate passing check before accepting the change. Removing the guard to enforce eventual success reintroduces repeated continuations when failures cannot be repaired.
Keep the guard in every blocking Stop hook you control: this script cannot prevent another hook from requesting more work. For suites using shared services, also plan test database isolation between agents.
Where Parallel Code fits
Parallel Code is our free, open-source desktop app for macOS and Linux. It runs several AI coding agents in parallel, each isolated in its own git worktree, with a diff-first review surface. This hook pattern helps check the working tree belonging to the agent whose turn is ending.