Claude Code hooks. Small scripts, useful checks.

Build small SessionStart, Stop, Notification and PreToolUse hooks, test their JSON contracts, and recover safely when a hook times out.

A useful hook performs one small action at a predictable moment: restore a short reminder, record that a turn stopped, bring a waiting session to your attention, or block a particular edit. Start with one local script you can inspect and test without a model. Adding a hook to every lifecycle event before understanding failures makes a difficult problem harder to debug.

Official documentation checked October 15, 2026. Examples below are illustrative; inspect your installed CLI’s help and existing project settings before applying them.

Pick an event and a small responsibility

SessionStart is useful for brief startup context. Stop observes a turn ending. Notification can surface an attention signal. PreToolUse runs before a tool action and can influence its permission decision. The official hooks walkthrough introduces the event configuration; the reference defines each input and output.

Keep the result proportional to the event. A startup reminder should not install dependencies. A notification should not deploy a branch. A Stop handler should not claim the requested feature passed its checks. Write the intended effect in a comment beside your own configuration, then ask whether running it twice would still be safe.

Start with a SessionStart reminder

Create .claude/hooks/session-note.py with this original example. It consumes the event JSON and supplies a fixed, short reminder:

import json
import sys

json.load(sys.stdin)
print("Before editing, confirm the task branch and its test command.")

Merge this fragment into .claude/settings.json. Preserve existing hooks and permissions. The explicit Python invocation means the script needs no executable bit; it does require python3 on the launch environment’s PATH.

{
  "hooks": {
    "SessionStart": [
      {
        "matcher": "startup|resume|compact",
        "hooks": [
          {
            "type": "command",
            "command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/session-note.py\"",
            "timeout": 5
          }
        ]
      }
    ]
  }
}

SessionStart can add context through stdout. Keep that context stable and relevant; dumping a build log at startup recreates the context problem you wanted to solve. Do not put credentials in the reminder or copy an entire environment into it. See the cost guide for deciding what deserves standing context.

Record Stop as a review signal

Here is a local status writer for .claude/hooks/record-stop.py. Register it under Stop using the same command-hook shape and a five-second timeout, without a matcher. It records only a hashed session identifier and a fixed state, with an atomic replacement so a partial write does not become the visible record.

import hashlib
import json
import os
from pathlib import Path
import sys
import tempfile

item = json.load(sys.stdin)
if item.get("stop_hook_active"):
    sys.exit(0)
session = item.get("session_id")
if not isinstance(session, str) or not session:
    sys.exit(1)
key = hashlib.sha256(session.encode()).hexdigest()
root = Path.home() / ".local/state/claude-hook-demo"
root.mkdir(parents=True, exist_ok=True, mode=0o700)
with tempfile.NamedTemporaryFile(mode="w", dir=root, delete=False) as f:
    json.dump({"state": "awaiting-review"}, f)
os.replace(f.name, root / (key + ".json"))

The record says “awaiting review,” not “successful.” Replaying this event overwrites the same session record instead of adding duplicate tasks. It deliberately stores neither the transcript nor the final message. This is a small demonstration, not a complete status service: a real dashboard also needs to clear stale state when work resumes and distinguish concurrent turns.

Keep a Notification hook simple

For macOS, a fixed notification avoids interpolating agent text into AppleScript. Save this as .claude/hooks/notify.sh, then register it under Notification with matcher permission_prompt and command sh "$CLAUDE_PROJECT_DIR/.claude/hooks/notify.sh":

#!/bin/sh
osascript -e 'display notification "A session needs your attention." with title "Claude Code"'

This is an operating-system notification, not an email or chat message. It depends on macOS notification permissions and focus settings. On another operating system, use a notifier you already understand. Keep the text generic so a screen share cannot expose a task. Test delivery separately from the hook matcher; a working script and a correctly triggered event are two different checks.

Use PreToolUse for a narrow guard

This example for .claude/hooks/guard-env.py rejects Edit or Write calls targeting a file named exactly .env. It parses JSON as data and never executes the supplied path:

import json
from pathlib import Path
import sys

event = json.load(sys.stdin)
if event.get("tool_name") in {"Edit", "Write"}:
    path = event.get("tool_input", {}).get("file_path", "")
    if Path(path).name == ".env":
        print("Direct edits to .env require a separate review.", file=sys.stderr)
        sys.exit(2)

Register it under PreToolUse with matcher Edit|Write, the same Python command pattern and an explicit timeout. This is intentionally a narrow demonstration: it does not cover Bash writes, alternate tools, symlinks or files such as .env.production. It is not a secrets boundary. Use appropriate permissions and filesystem isolation for that broader goal; see the permissions guide.

Design timeout recovery before relying on a hook

A loaded machine may not finish a hook within its budget. Keep network calls and full test suites out of the critical path. The timeout field is in seconds; use an explicit value suited to the operation. On supported command hooks, onFailure: "block" can make failures block the action; it requires version 2.1.295 or later. Verify the event-specific behavior in the reference rather than assuming every failure stops execution.

For state writes, use a stable identity and replace or reconcile an existing record. If the handler times out after its write, rerunning should converge on the same state. For remote operations, a timeout may mean the operation completed but the reply was lost; read back before retrying. Never infer approval from a missing response. Keep logs to event type, duration and outcome where possible.

Test the script and the live event separately

For the guard, run synthetic input in a disposable folder:

printf '%s' '{"tool_name":"Write","tool_input":{"file_path":"/tmp/demo/.env"}}' | python3 .claude/hooks/guard-env.py
echo $?

Expect exit status 2 and no file write. Repeat with a harmless filename and expect 0. Test malformed JSON, a missing executable and a deliberate delay in a disposable handler. For Stop, replay the same input twice and verify one final status file. Then trigger each event in Claude Code and inspect its actual output before relying on it.

Review hook code as executable project configuration, especially after pulling changes from others. Keep a known working version so rollback is simple. XAgents can help you find the session that needs attention; its help center covers that workflow. Your hook still needs its own evidence that the intended event ran and the intended effect occurred.

Common questions

Does a Stop hook prove the task succeeded?

No. It observes a lifecycle event. Verify the changed files, exact test results and requested behavior before calling the task complete.

What happens if a policy hook times out?

Failure behavior depends on the event and configuration. Current command hooks can use onFailure: block on supported events; that option requires Claude Code 2.1.295 or later. Test the failure path on your installed version.

Keep reading

The XAgents team