Claude Code hooks

Claude Code Stop hook: block, continue and save what was learned

A Stop hook runs when Claude has finished its answer. It can read that answer, keep Claude working, or write something down while the turn is fresh.

This page covers when the hook fires, how it blocks or continues a turn, the stop_hook_active loop guard, and a hook that saves lessons. Every statement about Claude Code comes from the official hooks reference and guide, linked at the end.

When the hook runs

Stop runs when the main Claude Code agent has finished responding. It does not run if the stoppage came from a user interrupt. An API error fires StopFailure instead.

The event has no matcher. Every Stop hook you register runs each time.

The reference also notes that the /goal command is a built-in shortcut for a session-scoped prompt-based Stop hook. Use it when you want Claude to keep working toward a condition without writing hook configuration.

What arrives on stdin

Next to the common input fields, a Stop hook receives these:

stop_hook_active
True when Claude Code is already continuing as a result of a stop hook.
last_assistant_message
The text content of Claude's final response, so a hook does not have to parse the transcript file.
background_tasks
The tasks still in flight, such as shell commands or subagents. Empty when nothing is running.
session_crons
The session-scoped scheduled wakeups, from CronCreate, ScheduleWakeup and /loop. Empty when nothing is scheduled.

For hooks that act on the turn that just ended, such as notification hooks, the reference recommends last_assistant_message over reading transcript_path. The transcript file is not guaranteed to include the final message at Stop time on all versions.

The two arrays let a hook tell "the session is done" from "the session is paused, waiting for background work to wake it up".

Block or continue

Stop and SubagentStop hooks can control whether Claude continues. A hook returns these fields:

decision
"block" prevents Claude from stopping. Omit it to let Claude stop.
reason
Required when decision is "block". Tells Claude why it should continue.
hookSpecificOutput.additionalContext
Non-error feedback for Claude. The conversation continues so Claude can act on it. Unlike decision: "block" it shows in the transcript as hook feedback, not as a hook error.
  • Exit code 2 also prevents Claude from stopping. Claude receives your stderr message as the reason to continue, the same way as reason.
  • additionalContext keeps the conversation going through the same loop protections as a block: the stop_hook_active input and the cap described below.
  • Claude Code places additionalContext from a Stop hook at the end of the turn.
stdout
{
  "decision": "block",
  "reason": "Run the test suite and report the result before you finish."
}

Use additionalContext when the hook works as designed and gives guidance, such as "run the test suite before finishing". Use decision: "block" when Claude must not stop yet.

The stop_hook_active loop guard

A hook that blocks on a condition can block forever when Claude cannot meet it. Two protections exist.

  1. stop_hook_active is true when Claude Code is already continuing as a result of a stop hook. The reference tells you to check it, or to process the transcript, to avoid blocking on a condition that will never resolve.
  2. Claude Code applies a cap of 8 consecutive continuations. After stop hooks have continued the turn eight times in a row, it overrides the next block and ends the turn. The count resets each time Claude calls a tool. To raise the cap, set CLAUDE_CODE_STOP_HOOK_BLOCK_CAP.

Do not rely on the cap alone. A hook that blocks for a reason that never goes away makes Claude run through all eight continuations, and the turn ends with a warning that the Stop hook blocked too many consecutive times.

The hooks guide shows the check as a shell script: parse stop_hook_active from the JSON input and exit early with code 0 when it is true. The same check in Node:

.claude/hooks/require-tests.mjs
import { readFileSync } from "node:fs";

const input = JSON.parse(readFileSync(0, "utf8"));

// Loop guard: if a stop hook already continued this turn, let Claude stop.
if (input.stop_hook_active) process.exit(0);

const text = input.last_assistant_message ?? "";
if (!/tests? pass/i.test(text)) {
  console.log(
    JSON.stringify({
      decision: "block",
      reason: "Run the test suite and report the result before you finish.",
    }),
  );
}

The first Stop blocks once and tells Claude to run the tests. On the next Stop, stop_hook_active is true, so the hook exits 0 and Claude may stop.

Example: save what was learned

A Stop hook sees last_assistant_message. That makes it a good place to write down a lesson while the turn is fresh. The hook below collects every line that starts with LESSON: from Claude's last answer and appends it to .claude/memory.md. A test in our repository runs this exact code.

1. Ask for the lines

Put a rule in your CLAUDE.md, for example: "When you fix a bug, end your answer with one line that starts with LESSON: and states the cause as a fact." The LESSON: convention is ours, not a Claude Code feature.

2. Add the hook

.claude/hooks/save-lesson.mjs
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";

const input = JSON.parse(readFileSync(0, "utf8"));

// Loop guard: a stop hook already continued this turn.
if (input.stop_hook_active) process.exit(0);

const text = input.last_assistant_message ?? "";
const lessons = text.split("\n").filter((line) => line.startsWith("LESSON:"));
if (lessons.length === 0) process.exit(0);

const dir = join(input.cwd, ".claude");
mkdirSync(dir, { recursive: true });
const day = new Date().toISOString().slice(0, 10);
const lines = lessons.map((line) => "- " + day + " " + line.slice(7).trim());
appendFileSync(join(dir, "memory.md"), lines.join("\n") + "\n");

The hook prints nothing and exits 0, so Claude stops as usual. It checks stop_hook_active first, so a continuation caused by another stop hook does not save the same lesson twice.

3. Register it

.claude/settings.json
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "node",
            "args": [
              "${CLAUDE_PROJECT_DIR}/.claude/hooks/save-lesson.mjs"
            ],
            "timeout": 10
          }
        ]
      }
    ]
  }
}

Load the file at the start of the next session with a SessionStart hook.

Ready-made: cachly

The cachly plugin ships a Stop hook with a timeout of 60 seconds. It does two things:

  • It learns. After a turn whose final message carries a clear fix signal, it sends one observation to your cachly instance.
  • It checks claims of saving. When the answer says something was saved to the brain but no write call ran in that turn, the hook blocks once with a reason and sends Claude back. It reads stop_hook_active and never blocks a second time.

The plugin also ships a SessionStart and a UserPromptSubmit hook.

Claude Code
/plugin marketplace add cachly-dev/cachly-mcp
/plugin install cachly-brain@cachly

Then turn on auto-update once: /plugin → Marketplaces → cachly → Enable auto-update. Claude Code leaves it off for marketplaces outside Anthropic's own, and the hooks update only with the plugin.

More on the other events: SessionStart hook, PreCompact hook and UserPromptSubmit hook. How to write a lesson Claude can use: Lessons learned for coding agents.

Sources

Checked against the hooks reference on .

More: All Claude Code hook events · AI memory in three layers · MCP integration · All docs