AI News Daily한국어
← AI tool tips
Claude Code✓ Confirmed in official docsAdded Nov 23

How to make Claude Code finish only after tests pass with a Stop hook

Writing "run the tests before finishing" in CLAUDE.md doesn't guarantee Claude will do it at the end of a long task. A Claude Code Stop hook runs every time Claude is about to finish responding. If the hook script exits with code 2, Claude doesn't stop: it keeps working and receives whatever the script wrote to stderr as the reason to continue.

  1. Create .claude/hooks/require-tests.sh in your project. Replace npm test with your project's test command.
#!/bin/bash
if ! out=$(npm test 2>&1); then
  echo "Tests failed. Fix them before finishing." >&2
  echo "$out" | tail -n 40 >&2
  exit 2
fi
exit 0
  1. Make it executable.
chmod +x .claude/hooks/require-tests.sh
  1. Register it as a Stop hook in the project's .claude/settings.json. Stop doesn't support matchers, so leave the matcher out.
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/require-tests.sh"
          }
        ]
      }
    ]
  }
}

When tests fail, Claude reads the failure log, fixes the code and tries to finish again, which runs the hook once more. Exit code 0 means pass and 2 means block. Any other code is a non-blocking error and the turn ends.

To prevent endless loops, Claude Code overrides the next block and ends the turn after Stop hooks have blocked eight times in a row. The count resets whenever Claude calls a tool. Change the cap with the CLAUDE_CODE_STOP_HOOK_BLOCK_CAP environment variable, or set it to 0 to remove it. The hook input JSON's stop_hook_active is true when Claude is already continuing because of a Stop hook. To allow only one retry, exit 0 when it is true.

Stop hooks also run when Claude just answers a question, so only attach fast tests (the default timeout for command hooks is 600 seconds). To have a model judge whether the work is done, use /goal or a type: "prompt" hook instead.

Get notified when a new tip lands

Tip alerts only go out in the app. Install it and turn notifications on.

Get the app

All tips →