AY Automate
Services
Case Studies
Industries
Contact
n8n logo
Claude logo
Cursor logo
Make logo
OpenAI logo
AUTOMATION GATEWAY

DEPLOYAUTOMATION

> System status: READY_FOR_DEPLOYMENT
Transform your business operations today.

Company
AY Automate
Connect with us
LinkedInXXYouTube
Explore AI Summary
ChatGPTClaude wrapperPerplexityGoogle AIGrokCopilot
Free Tools
  • ROI Calculator
  • AI Readiness Assessment
  • AI Budget Planner
  • Workflow Audit
  • AI Maturity Quiz
  • AI Use Case Generator
  • AI Tool Selector
  • Digital Transformation Scorecard
  • AI Job Description Generator
+ 5 more free tools
Our Builds
  • Ayn8nn8n Library
  • AyclaudeClaude Library
  • AyDesignMake your vibecoded app look like a $10M company
  • AyRankBe the solution cited by AI
  • LiwalaOpen Source
  • AY SkillsOur best skills
  • n8n × Claude CodeWorkflow builder
  • AY FrameworkOpen Source
Services
  • All Services
  • AI Strategy Consulting
  • AI Agent Development
  • Workflow Automation
  • Custom Automation
  • RAG Pipeline Development
  • SaaS MVP Development
  • AI Workshops
  • Engineer Placement
  • Custom Training
  • Maintenance & Support
  • OpenClaw & NemoClaw Setup
Industries
  • All Industries
  • Marketing Agencies
  • Ecommerce
  • Consulting Firms
  • Revenue Operations
  • Law Firms
  • SaaS Startups
  • Logistics
  • Finance
  • Professional Services
Resources
  • Blog
  • Case Studies
  • Playbooks
  • Courses
  • FAQ
  • Contact Us
  • Careers
Stay Updated

Stay tuned

Get the latest automation insights, playbooks, and case studies delivered to your inbox. No spam, ever.

Join 4,500+ operators · Weekly · Unsubscribe anytime

Featured
Claude

30 Days of Claude Code

Daily challenges + agents

n8n

AI Automation Playbook

Free guide · 1,000+ hours saved

Golden Offer

Scale your company without hiring more staff

Get in touch
Walid Boulanouar
Walid BoulanouarCo-Founder · CEO
Adel Dahani
Adel DahaniCo-Founder · CTO
contact@ayautomate.com

Operating Globally

Serving clients worldwide - across North America, Europe, MENA, Asia & beyond.

© 2026 AY Automate. All rights reserved.
Terms of UsePrivacy Policy
Blog
12 June 2026/16 min read

15 Best Claude Code Hook Examples (Copy-Paste Ready) in 2026

Claude Code hooks turn the agent loop into a programmable pipeline. The 15 examples below cover every event type Claude Code exposes in 2026: auto-format, block-dangerous-bash, lint-on-save, auto-commit, secret-scan, cost tracking, Slack pings, and more — each one copy-paste ready with the exact JSON matcher and shell command.

Taha
Author:Taha,AI Engineer
15 Best Claude Code Hook Examples (Copy-Paste Ready) in 2026

Book a Free Strategy Call

Skip the read — talk to Walid in 30 min.

Free strategy call. We map your AI engineering team, you keep the notes.

Or send us a brief →

Claude Code changed shape in 2025. The CLI started as a coding assistant, but by 2026 most serious teams use it as an orchestration runtime — and the runtime is only as good as the hooks wrapping it. Hooks are the deterministic layer underneath a probabilistic agent: shell commands that fire on specific lifecycle events, gate dangerous behavior, and bolt the model into your real workflow.

The hard part is that "hook examples" on the open web are usually either trivial (one echo line) or unsafe (no exit-code gating, no path scoping, no cost ceiling). What teams actually need is a set of production-tested patterns: matchers tuned to real tool calls, commands that exit cleanly, and JSON that drops into .claude/settings.json without a rewrite.

This guide collects the 15 best Claude Code hook examples for 2026. Each entry shows the hook event, what triggers it, what it does, the exact JSON to paste, and the trade-offs you should know before shipping it to your team. If you want a deeper map of the hook system itself, read our companion guide on the best Claude Code hooks. If you want hooks built and operated for you, that is what our Claude Code agency team does.

Best Claude Code hooks: a brief overview

  • Auto-format on save: Best for code consistency: runs Prettier or Black after every Edit.
  • Block dangerous bash: Best for safety: exits non-zero on rm -rf, sudo, force-push.
  • Long-task notifier: Best for async work: macOS notification when Claude is idle for input.
  • Auto-test after edit: Best for TDD: runs the matching test file the moment a source file changes.
  • Tool-call logger: Best for observability: writes every PostToolUse event to JSONL.
  • Auto-commit on Stop: Best for solo builders: snapshots a WIP commit at the end of each turn.
  • Lint-on-save: Best for catching errors early: runs ESLint or Ruff after each Edit.
  • Auto secret scan: Best for security: blocks Edits that introduce sk-, AKIA, or BEGIN PRIVATE KEY.
  • Cost tracker: Best for budget control: appends per-session token spend to a CSV on Stop.
  • Auto-link issue IDs: Best for ticket hygiene: rewrites commit messages to include the branch issue ID.
  • PR description generator: Best for review velocity: drafts a PR body from the session transcript.
  • Custom statusline: Best for context: shows model, branch, cost, and token usage in the CLI footer.
  • Sub-agent ROI tracker: Best for parallel teams: logs duration + tokens of every SubagentStop.
  • Slack ping on completion: Best for handoffs: posts to a channel when a long task ends.
  • Auto-add to TODO file: Best for memory: captures every "TODO:" comment Claude writes into a backlog.
Hook exampleEventMatcherPricing
Auto-format on savePostToolUseEdit|WriteFree
Block dangerous bashPreToolUseBashFree
Long-task notifierNotificationn/aFree
Auto-test after editPostToolUseEdit|WriteFree
Tool-call loggerPostToolUse*Free
Auto-commit on StopStopn/aFree
Lint-on-savePostToolUseEdit|WriteFree
Auto secret scanPreToolUseEdit|WriteFree
Cost trackerStopn/aFree
Auto-link issue IDsPostToolUseBashFree
PR description generatorStopn/aFree
Custom statuslinestatusLinen/aFree
Sub-agent ROI trackerSubagentStopn/aFree
Slack ping on completionStopn/aFree
Auto-add to TODO filePostToolUseEdit|WriteFree

1. Auto-format on save, best for code consistency

The single highest-ROI hook in any Claude Code setup. The moment Claude edits or writes a file, Prettier (JS/TS), Black (Python), or gofmt (Go) reformats it in place. You stop seeing diff noise from inconsistent spacing, and the model learns the project's style implicitly because every file it reads is already formatted.

Hook event

  • PostToolUse — fires after the tool succeeds, before the next model turn.

Key features

  • Triggers only on Edit and Write (not Read or Bash).
  • Reads the modified file path from $CLAUDE_TOOL_INPUT_file_path.
  • Exits 0 silently on success; non-zero output appears in transcript.

Best for

  • Teams with mixed contributors and a strict formatter config.
  • Monorepos where each package has its own formatter.
  • Anyone tired of post-commit "format" PRs.

Pricing

  • Free. Uses your existing formatter binary.
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "npx prettier --write \"$CLAUDE_TOOL_INPUT_file_path\" 2>/dev/null || true" }
        ]
      }
    ]
  }
}

Pros

  • Zero diff noise across PRs.
  • Works with any language-specific formatter swap.
  • No latency cost — runs in milliseconds.

Cons

  • Silent failures if the formatter binary is missing.
  • Can mask real syntax errors if || true swallows them — drop it in CI.

2. Block dangerous bash, best for safety

The hook that earns its keep the first time someone tries rm -rf / in a Claude session. A PreToolUse hook on Bash inspects $CLAUDE_TOOL_INPUT_command and exits non-zero on a blocklist of patterns. Claude sees the non-zero exit and refuses to execute. No prompt injection bypasses this — it runs in your shell, not the model's context.

Hook event

  • PreToolUse — fires before the tool executes, can veto it.

Key features

  • Pattern matches on rm -rf, sudo, git push --force, chmod 777, curl ... | sh.
  • Exit code 2 cancels the tool call and feeds reason back to Claude.
  • Configurable allowlist per-project via env var.

Best for

  • Any team running Claude with --dangerously-skip-permissions.
  • CI runners and sandboxed agents.
  • Solo devs who do not want to babysit every Bash call.

Pricing

  • Free.
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "echo \"$CLAUDE_TOOL_INPUT_command\" | grep -E 'rm -rf|sudo |--force|chmod 777|curl.*\\| ?sh' && { echo 'Blocked: dangerous command'; exit 2; } || exit 0" }
        ]
      }
    ]
  }
}

Pros

  • Deterministic — runs every time, no model judgment involved.
  • Patterns are auditable in git.
  • Cheap to extend with new blocklist entries.

Cons

  • False positives on legitimate rm -rf node_modules — keep an allowlist.
  • Grep-based matching can be fooled by creative quoting; for high-stakes envs, parse properly.

3. Long-task notifier, best for async work

Claude Code emits a Notification event when it is waiting on user input or has been idle for a stretch. Wire that to osascript (macOS), notify-send (Linux), or a Pushover/ntfy webhook and you can walk away from a long agent run and get pinged the moment it stalls.

Hook event

  • Notification — fires when Claude needs attention.

Key features

  • Triggers on idle, permission requests, and Plan-mode prompts.
  • Receives $CLAUDE_NOTIFICATION_message with context.
  • Cross-platform with a one-line adapter.

Best for

  • Long-running refactors and multi-hour migrations.
  • Remote work where you switch contexts often.
  • Teams running Claude on a remote VM with web access.

Pricing

  • Free.
{
  "hooks": {
    "Notification": [
      {
        "hooks": [
          { "type": "command", "command": "osascript -e \"display notification \\\"$CLAUDE_NOTIFICATION_message\\\" with title \\\"Claude Code\\\"\"" }
        ]
      }
    ]
  }
}

Pros

  • Reclaims hours of context-switch overhead.
  • Works with any notification backend.
  • No tokens consumed.

Cons

  • macOS-specific without an adapter.
  • Easy to over-notify; tune which Notification messages matter.

4. Auto-test after edit, best for TDD

Tight feedback loops are what make agentic coding viable. After every Edit or Write to src/foo.ts, run the matching tests/foo.test.ts. The test output is fed back to Claude as the next signal, so it self-corrects without you intervening.

Hook event

  • PostToolUse — fires after Edit/Write completes.

Key features

  • Maps src/x.ts to tests/x.test.ts via a small shell snippet.
  • Streams test output back through stdout.
  • Optional: only triggers if the edited file is under src/.

Best for

  • TDD-heavy codebases.
  • Library packages with deterministic unit tests.
  • Anyone using Vitest, Jest, or Pytest.

Pricing

  • Free.
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "FILE=\"$CLAUDE_TOOL_INPUT_file_path\"; TEST=$(echo \"$FILE\" | sed 's|src/|tests/|; s|\\.ts$|.test.ts|'); [ -f \"$TEST\" ] && npx vitest run \"$TEST\" || true" }
        ]
      }
    ]
  }
}

Pros

  • Catches regressions inside the same turn.
  • Lets Claude fix its own breakage automatically.
  • Encourages real test discipline.

Cons

  • Slow if your test suite is heavy — scope it to the matching file.
  • Flaky tests will derail otherwise-good sessions.

5. Tool-call logger, best for observability

You cannot improve what you do not measure. A wildcard PostToolUse hook that appends {tool, input, ts} to a JSONL file gives you the raw material to answer: which tools does Claude actually use? Where does it loop? Which sub-agents are worth their tokens?

Hook event

  • PostToolUse with "matcher": "*" — fires after every tool call.

Key features

  • Append-only JSONL — cheap to parse later with jq.
  • Captures tool name, file path, command, and timestamp.
  • Zero impact on session latency.

Best for

  • Platform teams running Claude across many engineers.
  • Anyone debugging "why did Claude do that?"
  • Building usage dashboards downstream.

Pricing

  • Free.
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "*",
        "hooks": [
          { "type": "command", "command": "echo \"{\\\"ts\\\":\\\"$(date -u +%FT%TZ)\\\",\\\"tool\\\":\\\"$CLAUDE_TOOL_NAME\\\",\\\"file\\\":\\\"$CLAUDE_TOOL_INPUT_file_path\\\"}\" >> ~/.claude/tool-calls.jsonl" }
        ]
      }
    ]
  }
}

Pros

  • Unlocks honest analytics on agent behavior.
  • Pairs well with Claude Code skills usage tracking.
  • Replayable for incident review.

Cons

  • File grows fast — rotate it weekly.
  • Sensitive paths/commands end up in the log; protect the file.

6. Auto-commit on Stop, best for solo builders

Claude finished a turn. Before you forget, snapshot the state. A Stop hook that runs git add -A && git commit -m "wip: claude turn" gives you a reflexive checkpoint. If the next turn goes sideways, git reset returns you to known-good.

Hook event

  • Stop — fires when the agent stops (turn complete or user interrupt).

Key features

  • Commits everything in the working tree.
  • Skips silently if there is nothing to commit.
  • Tag commits with [skip ci] to avoid burning CI minutes.

Best for

  • Solo developers iterating fast.
  • Branch-per-feature workflows.
  • Anyone who has ever lost work to an over-eager refactor.

Pricing

  • Free.
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "git add -A && git diff --cached --quiet || git commit -m \"wip: claude turn [skip ci]\" --no-verify" }
        ]
      }
    ]
  }
}

Pros

  • Frictionless rollback.
  • Visible history of what Claude actually did.
  • Pairs well with git rebase -i to squash later.

Cons

  • Pollutes history if you forget to squash before merge.
  • --no-verify bypasses pre-commit hooks — only use on personal branches.

7. Lint-on-save, best for catching errors early

Formatting handles style; linting handles bugs. A PostToolUse hook running ESLint, Ruff, or cargo clippy on the edited file surfaces unused vars, missing awaits, and type mismatches the moment Claude writes them. The non-zero exit feeds back into the next turn.

Hook event

  • PostToolUse on Edit/Write.

Key features

  • Runs language-appropriate linter per file extension.
  • Outputs errors via stdout so Claude sees them.
  • Optional --fix to auto-correct mechanical issues.

Best for

  • TypeScript and Python codebases.
  • Teams with strict lint rules in CI.
  • Anyone tired of "missing await" bugs.

Pricing

  • Free.
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "FILE=\"$CLAUDE_TOOL_INPUT_file_path\"; case \"$FILE\" in *.ts|*.tsx) npx eslint --fix \"$FILE\" ;; *.py) ruff check --fix \"$FILE\" ;; esac" }
        ]
      }
    ]
  }
}

Pros

  • Catches bugs Claude would otherwise ship.
  • Auto-fix reduces back-and-forth.
  • Works alongside the formatter hook.

Cons

  • Strict configs can flood the transcript.
  • Slow linters (full-program TypeScript) should be moved to CI instead.

8. Auto secret scan, best for security

Models leak secrets sometimes — pasted env vars, accidentally inlined API keys, JWTs that should have been env-loaded. A PreToolUse hook on Edit/Write that scans the new content for high-confidence secret patterns can hard-block the write before the file ever touches disk.

Hook event

  • PreToolUse on Edit/Write — vetoes the tool call.

Key features

  • Patterns for sk-, AKIA, ghp_, BEGIN PRIVATE KEY, JWT structure.
  • Exit code 2 blocks and tells Claude why.
  • Pairs with trufflehog or gitleaks if installed.

Best for

  • Teams handling customer credentials.
  • Anyone running Claude with broad file write permissions.
  • Pre-prod environments.

Pricing

  • Free.
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "echo \"$CLAUDE_TOOL_INPUT_content\" | grep -E 'sk-[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|ghp_[a-zA-Z0-9]{36}|BEGIN [A-Z ]*PRIVATE KEY' && { echo 'Blocked: secret detected'; exit 2; } || exit 0" }
        ]
      }
    ]
  }
}

Pros

  • Stops the most common leak vectors.
  • Cheap to extend with org-specific patterns.
  • Auditable via the hook log.

Cons

  • Regex matching has false positives on test fixtures.
  • Does not catch obfuscated or split secrets — layer with gitleaks for depth.

9. Cost tracker, best for budget control

Anthropic's billing dashboard shows the bill after the fact. A Stop hook that pulls cost_usd and total_tokens from the session transcript and appends them to a CSV gives you a live per-session budget. Pair it with a daily cron that emails the rollup.

Hook event

  • Stop — fires when the agent stops.

Key features

  • Reads $CLAUDE_TRANSCRIPT_PATH for usage data.
  • Appends {date, session_id, cost, tokens} to ~/.claude/costs.csv.
  • Pairs with a weekly rollup script.

Best for

  • Agencies billing clients per project.
  • Teams with monthly Anthropic budgets.
  • Cost-curious solo devs.

Pricing

  • Free.
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "jq -r '[.session_id, .cost_usd, .total_tokens] | @csv' \"$CLAUDE_TRANSCRIPT_PATH\" >> ~/.claude/costs.csv 2>/dev/null || true" }
        ]
      }
    ]
  }
}

Pros

  • Catches runaway sessions in near real-time.
  • CSV plugs into any BI tool.
  • Useful input for client invoicing.

Cons

  • Transcript schema can shift across Claude Code versions — re-verify after upgrades.
  • Does not include sub-agent cost separately (see hook #13).

10. Auto-link issue IDs, best for ticket hygiene

If your branch names follow JIRA-123-foo or eng/123-bar, every commit on that branch should reference the ID. A PostToolUse hook on git commit Bash calls rewrites the last commit message to prepend the ID if it is missing.

Hook event

  • PostToolUse on Bash — fires after the commit executes.

Key features

  • Extracts issue ID from current branch name.
  • Amends the last commit to include the ID prefix.
  • Skips silently if the ID is already in the message.

Best for

  • Teams enforcing trace-back from commits to tickets.
  • Squash-merge workflows.
  • Anyone tired of writing "JIRA-123: " manually.

Pricing

  • Free.
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          { "type": "command", "command": "echo \"$CLAUDE_TOOL_INPUT_command\" | grep -q 'git commit' && { ID=$(git rev-parse --abbrev-ref HEAD | grep -oE '[A-Z]+-[0-9]+' | head -1); MSG=$(git log -1 --pretty=%B); echo \"$MSG\" | grep -q \"$ID\" || git commit --amend -m \"$ID: $MSG\" --no-verify; } || true" }
        ]
      }
    ]
  }
}

Pros

  • Consistent ticket linkage with zero manual effort.
  • Plays nicely with PR templates.
  • Auditable.

Cons

  • Amending commits breaks shared branches — only run locally.
  • Branch names without IDs are silently skipped.

11. PR description generator, best for review velocity

A Stop hook that reads the session transcript and asks Claude (one more time, headless) to draft a PR title and body saves 10–15 minutes per PR. Pipe the output to gh pr create --body-file -.

Hook event

  • Stop — fires at end of session.

Key features

  • Reads the transcript file path.
  • Pipes a summary prompt through claude --print.
  • Saves the draft to .git/PR_DRAFT.md for review before pushing.

Best for

  • Teams doing many small PRs per day.
  • Async review cultures.
  • Solo devs who hate writing PR descriptions.

Pricing

  • Free (uses your existing Claude usage).
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "cat \"$CLAUDE_TRANSCRIPT_PATH\" | claude --print 'Summarize this session as a PR description with Title, Summary, Changes, and Test Plan sections' > .git/PR_DRAFT.md 2>/dev/null || true" }
        ]
      }
    ]
  }
}

Pros

  • Pre-fills the hardest part of a PR.
  • Consistent format across the team.
  • Easy to wire into gh pr create.

Cons

  • Costs extra tokens per session.
  • Quality depends on transcript clarity — short sessions produce short drafts.

12. Custom statusline, best for context

The statusLine hook is a different beast — it does not fire on events but instead renders the bottom-of-CLI footer. A good statusline shows model, branch, last cost, and tokens-this-session. It is what makes Claude Code feel like a proper IDE rather than a terminal.

Hook event

  • statusLine config block — runs on every render.

Key features

  • Receives session state via stdin as JSON.
  • Outputs a single line of text.
  • Updated on every model turn and tool call.

Best for

  • Power users who run multi-hour sessions.
  • Teams standardizing on a shared CLI feel.
  • Cost-conscious developers.

Pricing

  • Free.
{
  "statusLine": {
    "type": "command",
    "command": "jq -r '\"[\\(.model.display_name)] \\(.workspace.current_dir | split(\"/\") | last) | $\\(.cost.total_cost_usd) | \\(.cost.total_input_tokens + .cost.total_output_tokens) tok\"'"
  }
}

Pros

  • Instant visibility into what is happening.
  • No tokens used.
  • Easy to extend with branch, git status, or weather.

Cons

  • One-line constraint — keep it tight.
  • Some terminal widths truncate; design for 80 cols.

13. Sub-agent ROI tracker, best for parallel teams

Sub-agents are powerful but easy to misuse — spawning four parallel Task agents that each burn 50k tokens for a one-line answer. A SubagentStop hook logs every sub-agent run with its duration and token cost so you can spot the freeloaders.

Hook event

  • SubagentStop — fires when a Task sub-agent completes.

Key features

  • Captures sub-agent name, duration, and tokens used.
  • Appends to ~/.claude/subagent-roi.jsonl.
  • Pairs with a weekly review to prune low-ROI agents.

Best for

  • Teams using multiple specialized sub-agents.
  • Anyone optimizing token budget.
  • Building internal "sub-agent leaderboards".

Pricing

  • Free.
{
  "hooks": {
    "SubagentStop": [
      {
        "hooks": [
          { "type": "command", "command": "echo \"{\\\"ts\\\":\\\"$(date -u +%FT%TZ)\\\",\\\"agent\\\":\\\"$CLAUDE_SUBAGENT_NAME\\\",\\\"duration_s\\\":$CLAUDE_SUBAGENT_DURATION,\\\"tokens\\\":$CLAUDE_SUBAGENT_TOKENS}\" >> ~/.claude/subagent-roi.jsonl" }
        ]
      }
    ]
  }
}

Pros

  • Data-driven sub-agent pruning.
  • Spots runaway delegations.
  • Replayable across weeks.

Cons

  • Schema for sub-agent env vars may evolve.
  • Requires discipline to actually review the log.

14. Slack ping on completion, best for handoffs

A Stop hook that posts to a Slack incoming webhook turns Claude into a teammate that announces "done" in the channel. The message can include the branch, PR draft path, and a one-line summary pulled from the transcript.

Hook event

  • Stop — fires when the agent stops.

Key features

  • POSTs to a Slack incoming webhook URL.
  • Includes branch name, working dir, and last commit message.
  • Skips silently if SLACK_WEBHOOK_URL is unset.

Best for

  • Distributed teams where Claude runs unattended.
  • Long-running migrations.
  • Build-it-and-walk-away workflows.

Pricing

  • Free.
{
  "hooks": {
    "Stop": [
      {
        "hooks": [
          { "type": "command", "command": "[ -n \"$SLACK_WEBHOOK_URL\" ] && curl -s -X POST -H 'Content-Type: application/json' -d \"{\\\"text\\\":\\\"Claude done in $(basename $PWD) on $(git rev-parse --abbrev-ref HEAD)\\\"}\" \"$SLACK_WEBHOOK_URL\" >/dev/null || true" }
        ]
      }
    ]
  }
}

Pros

  • Real async handoff without polling.
  • Webhook-based — works with Slack, Discord, Teams, ntfy.
  • One env var to toggle.

Cons

  • Webhook URLs are secrets — keep them out of repo configs.
  • Easy to over-notify if every short session pings the channel.

15. Auto-add to TODO file, best for memory

Claude leaves // TODO: comments mid-session and forgets them. A PostToolUse hook that grep's new edits for TODO lines and appends them (with file + line number) to a project-level TODO.md turns those scattered notes into a real backlog.

Hook event

  • PostToolUse on Edit/Write.

Key features

  • Scans the edited file for TODO: lines added in the last diff.
  • Appends each one to TODO.md with file:line context.
  • Deduplicates against existing entries.

Best for

  • Long migration projects.
  • Codebases where TODOs disappear into the void.
  • Teams maintaining a single source of truth for pending work.

Pricing

  • Free.
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          { "type": "command", "command": "FILE=\"$CLAUDE_TOOL_INPUT_file_path\"; grep -nE 'TODO:' \"$FILE\" 2>/dev/null | awk -v f=\"$FILE\" -F: '{print \"- \" f \":\" $1 \" — \" substr($0, index($0,$3))}' >> TODO.md; sort -u -o TODO.md TODO.md" }
        ]
      }
    ]
  }
}

Pros

  • TODOs stop falling through the cracks.
  • Replaces a flaky human habit with a deterministic one.
  • Sortable, greppable, version-controlled.

Cons

  • Can grow noisy on large codebases — scope to a subdir.
  • Does not auto-remove TODOs once resolved.

How to choose the best Claude Code hook for your team

1) Should you start with PreToolUse or PostToolUse hooks?

Start with PostToolUse. Auto-format, lint-on-save, and tool-call logger are non-blocking — they fire after the action and either succeed silently or feed signal back to Claude. Once your PostToolUse layer is stable, layer in PreToolUse hooks for the high-risk paths: Bash and Edit/Write. PreToolUse hooks veto execution, so a buggy matcher blocks legitimate work. Treat them like firewall rules — test thoroughly, ship narrowly. Our deeper map of Claude Code hooks walks through the event lifecycle in order.

2) How do you decide what belongs in a hook vs in CLAUDE.md?

CLAUDE.md is for guidance the model should consider; hooks are for behavior the system must guarantee. "Prefer functional patterns" belongs in CLAUDE.md. "Never rm -rf outside the project root" belongs in a PreToolUse hook. The rule of thumb: if the consequence of the model ignoring it is "minor annoyance", put it in CLAUDE.md; if the consequence is "production incident or data loss", put it in a hook.

3) How do you keep hooks fast?

Hooks run synchronously between turns. A slow hook (full test suite, full type-check) makes the agent feel sluggish and burns wall-clock time. Three rules: scope by file path (only run the test for the edited file, not the whole suite), background heavy work with & when you do not need the result, and use || true to prevent transient failures from aborting the chain. If a hook takes more than 2–3 seconds, move it to CI instead.

4) When should you outsource hook engineering?

When your hook config crosses ~10 entries, when you start running Claude Code unattended in CI, or when you need org-wide standardization across many engineers. That is the point where a specialized team — our Claude Code agency and broader AI agent development agency practices — pays for itself in saved hours and prevented incidents. We also wire hooks into LangGraph and Claude Agent SDK deployments through our LangGraph development agency team.


Build Claude Code into a real engineering platform with AY Automate

The 15 hooks above are the starting kit. The real lift comes from composing them with project-specific guardrails, sub-agent orchestration, and continuous evaluation. AY Automate ships production Claude Code setups for B2B and enterprise teams — hook libraries, custom statuslines, sub-agent fleets, CI integration, and cost dashboards. If you want this engineered for you instead of pieced together from blog posts, talk to our Claude Code agency, our AI agent development agency, or our n8n agency for the workflow side. Book a free consultation and we will scope a hook architecture that fits your codebase.


FAQ

What are Claude Code hooks?

Hooks are shell commands declared in .claude/settings.json that fire on specific lifecycle events — PreToolUse, PostToolUse, Stop, Notification, SubagentStop, and statusLine. They run in your shell with the session context exposed as environment variables, which lets you gate, log, transform, or react to anything Claude does. They are the deterministic layer beneath an otherwise probabilistic agent.

How are hooks different from MCP servers or skills?

MCP servers add capabilities (tools, resources) Claude can choose to use. Skills add domain knowledge and procedures Claude reads when triggered. Hooks add deterministic guarantees that run regardless of what Claude decides — they execute whether or not the model "wants" them to. For the full picture, compare with our best Claude Code hooks and best Claude Code skills write-ups.

How do you verify a hook is actually running?

Add echo "hook fired: $(date)" >> ~/.claude/hook-debug.log to the command and trigger the event. If the log line appears, the hook fired. If not, check that the matcher pattern matches the tool name exactly (case-sensitive), that .claude/settings.json is valid JSON, and that you restarted the Claude Code session after editing it.

How much do Claude Code hooks cost?

Hooks themselves are free — they are just shell commands. The cost comes from what the command does: an extra claude --print call (PR description generator) burns tokens, a git commit does not. Track session cost with the cost-tracker hook from this list.

How long does it take to set up a hook library?

A first PostToolUse hook takes 5 minutes. A production-grade library of 10–15 hooks with proper matchers, exit-code handling, and error logs takes 1–2 days. A team-wide standardized config with CI integration and per-project overrides is closer to a week of focused work.

Are hooks safe to run with --dangerously-skip-permissions?

Hooks are exactly the right tool for that mode. The block-dangerous-bash and auto-secret-scan hooks (entries #2 and #8 above) replace the per-prompt permission checks with deterministic policy. Run them at the user-settings level so they apply across every project.

Should we use hooks or sub-agents for code review?

Use both. A Stop hook can kick off a code-review sub-agent automatically — the hook is the trigger, the sub-agent is the reviewer. For a deeper look at sub-agents, see our best Claude Code sub-agents breakdown and the best Claude Code workflows catalog.

Can hooks train my internal team?

Hooks are the cheapest training mechanism we have found: they encode "the way we do things" in executable form, so new engineers absorb the conventions by observing the agent. We help teams build internal hook libraries as part of our Claude Code agency onboarding engagements — book a free consultation if you want a hand.

Book a Free Strategy Call

Building this in production?

Walid runs a 30-min call to map your AI engineering team. Free, no slides.

Or send us a brief →
Share this article
About the Author
Taha
Taha
AI Engineer

Taha builds and ships custom AI agents and workflow automations for AY Automate clients across SaaS, finance, and professional services.