Claude Code Stop Hook: Block Early Exit Without Loops
说明与用途
命令 Stop Hook 在 Claude Code 中运行测试(如 npm test),在测试失败时以特定原因阻止提前退出,并在测试通过时退出 0,从而让无人值守的运行持续工作直到真正的检查通过。
问题
How to keep an unattended Claude Code run working until a real check passes, without relying on Claude's own judgment of completion.
结果
A command Stop hook runs npm test, blocks with a specific reason while the test fails, and stops blocking after a fixed number of retries, allowing the unattended run to continue until the real check passes.
工作流
- Add a command Stop hook to .claude/settings.json pointing to a script that runs the real check and blocks with a reason until it passes
- Write the script to read stdin JSON fields (session_id, stop_hook_active), reset the retry counter on a fresh stop, run the check, block with a reason while failing, and exit 0 once the check passes
- Set a max retry cap so the run cannot loop forever
- Run the unattended Claude Code session and verify the run keeps working until the check passes
证据
If the command prints {"decision": "block", "reason": "..."}, Claude keeps working and treats the reason as its next instruction.
Add this to .claude/settings.json in your project. Use .claude/settings.local.json if you don't want to commit it.
There is no "matcher", because Stop doesn't support one.
A command hook has a 600-second default timeout. A slow test suite needs a larger timeout value.
- 记录日期: 2026-11-02T17:29:25.311Z