clawdbod ~ $ cat hooks/stop-fitness-check.mjs

A real Claude Code Stop hook example, line by line

Updated , 6 min read

Most Stop hook examples are three lines that echo a message. That is enough to see the shape, and not enough to ship. A hook that runs after every single reply has to keep state, avoid looping forever, cope with parallel sessions, and never break the session it is attached to.

This is a walkthrough of a Stop hook that does all of that in production. It comes from ClawdBod, an open-source Claude Code plugin that counts your prompts and, every so often, asks Claude to offer you an exercise break. The fitness part is incidental. The pattern, "after N turns and M minutes, make Claude do something", applies to plenty of other ideas. The full source is in the hooks folder on GitHub, and the official reference is the Claude Code hooks documentation.

What a Stop hook is

A Stop hook is a command Claude Code runs each time Claude finishes responding. The command receives a JSON object on standard input describing the session, and it can reply on standard output.

If it prints nothing and exits cleanly, Claude stops as normal. If it prints a decision to block, Claude does not stop. Instead, the reason you supply is fed back to Claude as context, and Claude carries on with that instruction in hand. That is the whole trick: a Stop hook lets you inject a new instruction at the exact moment a turn ends.

Registering the hook

A plugin declares its hooks in hooks/hooks.json:

hooks/hooks.json
{
  "hooks": {
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "node \"${CLAUDE_PLUGIN_ROOT}/hooks/stop-fitness-check.mjs\"",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

Two details are worth copying.

Use double quotes around ${CLAUDE_PLUGIN_ROOT}. The variable points at the plugin's install directory and is expanded by the shell. An earlier ClawdBod release wrapped it in single quotes, the shell left it unexpanded, and the hook crashed on every run. The symptom was simply that breaks and onboarding stopped happening. There is now a test that guards the quoting.

Set a short timeout. This command runs after every reply. Five seconds is generous for something that reads two small files, and it caps the damage if anything hangs.

Reading the input

The hook reads standard input, parses it, and bails out quietly if anything is off:

stop-fitness-check.mjs (trimmed)
let input;
try {
  input = JSON.parse(readFileSync(0, "utf-8"));
} catch {
  process.exit(0);
}
if (!input || typeof input !== "object" || input.stop_hook_active) process.exit(0);

const sessionId = input.session_id;

readFileSync(0) reads file descriptor 0, which is standard input, and works the same on macOS, Linux and Windows.

The stop_hook_active check is the most important line in the file. That field is true when Claude is already continuing because a Stop hook blocked it. Without the check, the hook would block, Claude would respond, the hook would run again and block again, and you would have built an infinite loop. Any Stop hook that can block needs this guard.

Deciding when to act

The decision needs two numbers per session: how many prompts have gone by, and when the last break was.

stop-fitness-check.mjs (trimmed)
const session = readSession(dir, sessionId);
const now = Date.now();

const hadBreak = session.lastBreakAt > 0;
const minutesSince =
  (now - (hadBreak ? session.lastBreakAt : session.startedAt)) / 60000;

session.promptCount += 1;
const shouldBreak =
  session.promptCount >= config.promptsBetweenBreaks &&
  minutesSince >= config.minMinutesBetweenBreaks;

if (shouldBreak) {
  session.promptCount = 0;
  session.lastBreakAt = now;
}
writeSession(dir, sessionId, session);

if (!shouldBreak) process.exit(0);

Requiring both conditions is deliberate. A count alone fires too often during rapid exchanges, and a timer alone fires during long agent runs nobody is watching.

Two smaller decisions here came from real bugs:

  • The first break waits for the cooldown too, measured from the start of the session. Before that fix, the first break fired on prompt count alone.
  • Timestamps in the future are clamped to now. If the system clock jumps backwards after sleep or a time sync, a stored "last break" can end up ahead of the current time, which would suppress breaks until the clock caught up.

Keeping state per session

State lives in one small JSON file per session, named after the session_id from the input:

terminal
~/.claude/clawdbod/
  config.json                 cadence and optional profile
  state.json                  onboarding flag and pause state
  sessions/<session_id>.json  promptCount, lastBreakAt, startedAt

The first version of this hook kept one shared counter in the system temp directory. Two terminals open at once meant two sessions incrementing the same number, so breaks arrived in whichever window happened to cross the line. Keying the file on the session id fixed that. Files are written atomically, to a temporary file that is then renamed, so a crash mid-write cannot leave a half-written counter. Session files untouched for seven days are pruned.

Settings that should apply everywhere, such as "pause all breaks for two hours", live in the global state.json instead.

Blocking with a reason

When a break is due, the hook prints a single JSON object:

stop-fitness-check.mjs (trimmed)
const emit = (reason) =>
  process.stdout.write(JSON.stringify({ decision: "block", reason }));

emit([
  "🏋️ FITNESS BREAK TIME!",
  "",
  "IMPORTANT: If the user is mid-deploy, debugging an error, resolving a",
  "conflict, or in a critical multi-step flow, skip this break — just say",
  "nothing and continue with their task.",
  "",
  "Otherwise, use the clawdbod skill to give the user a quick exercise challenge.",
].join("\n"));

The reason is a prompt, and it should be written like one. Notice that the hook does not try to work out whether you are busy. It cannot see that from a counter. Instead it hands the judgment to Claude, which can see the whole conversation, and tells it explicitly that skipping is allowed. The hook decides when a break is possible, and the model decides whether it is appropriate.

The detailed instructions for running a break live in a skill rather than in the hook, so the reason stays short and only names the skill to use.

Never break the session

The entire script is wrapped in one try block whose catch exits with code 0. A missing file, corrupt JSON or an unwritable disk all end the same way: the hook does nothing and Claude stops normally. The comment at the top of the file states the rule: it must never exit non-zero and never print anything but a decision.

That is the right default for any hook that is a nice-to-have. A failed fitness break is invisible. A hook that throws after every reply is a reason to uninstall the plugin.

The companion hook: avoiding permission prompts

A break ends with Claude running a script to log your set. Normally a Bash call would raise a permission prompt, which is a poor way to end something meant to take ten seconds. So the plugin registers a second hook on PreToolUse with a Bash matcher. It inspects the command and approves it only when it is exactly node running one of three known scripts in the plugin's own folder:

approve-plugin-scripts.mjs (trimmed)
// No operators, substitutions, redirects, escapes, globs, or newlines anywhere.
if (/[;&|`$<>\\(){}*?\n\r]/.test(command)) return false;

// ...the command must be `node <plugin>/scripts/<known script>.mjs`...

process.stdout.write(JSON.stringify({
  hookSpecificOutput: {
    hookEventName: "PreToolUse",
    permissionDecision: "allow",
    permissionDecisionReason: "ClawdBod: running its own local script",
  },
}));

For anything else it prints nothing, which leaves the normal permission flow untouched. The export script is left off the list on purpose, because it writes a file wherever you point it and should still ask.

An auto-approve hook is a security boundary, so keep the allow-list narrow, reject anything containing shell metacharacters, and test the rejections as carefully as the approvals.

A checklist for your own Stop hook

  • Exit immediately when stop_hook_active is true.
  • Key state on session_id, not on a shared file.
  • Wrap everything in a try and exit 0 on any failure.
  • Print nothing except the decision.
  • Double-quote ${CLAUDE_PLUGIN_ROOT} in hooks.json.
  • Keep the timeout short.
  • Write the reason as an instruction, and tell Claude when it may ignore it.
  • Give users a way to pause it.

To see the result from the user's side, install the plugin and send a few prompts. The files it writes are described in the workout log guide.

FAQ

What is a Stop hook in Claude Code?

A Stop hook is a command that Claude Code runs every time Claude finishes responding. It receives session details as JSON on standard input and can either let Claude stop or block the stop and supply a reason, which Claude then acts on.

How do I stop a Stop hook from looping forever?

Check the stop_hook_active field in the hook input and exit without output when it is true. That field indicates Claude is already continuing because of a Stop hook, so blocking again would repeat indefinitely.

How does a Stop hook make Claude keep going?

It prints a JSON object with decision set to block and a reason string. Claude does not stop, and the reason is passed to it as context for its next step.

Where should a plugin hook store its state?

Outside the plugin directory, so data survives plugin updates. ClawdBod uses ~/.claude/clawdbod, with one file per session id for counters and a separate file for global settings.

Can a hook approve tool calls automatically?

Yes. A PreToolUse hook can return a permissionDecision of allow. Restrict it to an exact allow-list of commands and reject anything with shell operators, because it bypasses the normal permission prompt.

Install ClawdBod

ClawdBod is a free, open-source Claude Code plugin that turns these breaks into a habit. Run this inside Claude Code:

install
$ /plugin install clawdbod --marketplace khur/clawdbod
$ /reload-plugins

No account, no telemetry, MIT licensed. Update and uninstall commands are on the home page, and the source is on GitHub.