
hooks-plugin
Security and workflow hooks that block risky Bash commands, nudge toward native tools, and guard git operations.
- version
- 2.22.3
- GitHub stars
- 60
What it does
- Adds 50-plus hooks such as
bash-safety.sh,bash-antipatterns.sh,secret-protection.sh, andbranch-protection.shfor Claude Code sessions - Covers blocking dangerous shell patterns like
git add -A,git reset --hard,curl | sh, andchmod 777, plus tool-choice nudges - Enforces stash cleanup through
git-stash-reminder.shso session-created stashes are flagged before a session ends - Designed for projects that want consistent Claude Code behavior enforced through PreToolUse, SessionStart, and Stop hooks
Claude Code hooks for enforcing best practices and workflow automation
Add marketplace
/plugin marketplace add laurigates/claude-pluginsRun it inside Claude Code once, then install the plugin below.
Install
/plugin install hooks-plugin@laurigates-claude-pluginsRun it inside Claude Code after adding the marketplace.
Files
Discovered from sourceClaude Code Hooks Configuration
Expert knowledge for configuring and developing Claude Code hooks to automate workflows and enforce best practices.
When to Use This Skill
| Use this skill when... | Use something else when... |
|---|---|
| Configuring hook lifecycle events (PreToolUse, PostToolUse, etc.) | Writing general shell scripts unrelated to hooks |
| Blocking dangerous commands or enforcing patterns | Setting up CI/CD pipelines (use CI tooling) |
| Auto-formatting files after edits | Configuring Claude Code settings unrelated to hooks |
| Injecting context at session or subagent start | Writing standalone automation scripts |
| Setting up PermissionRequest auto-approve/deny | Managing project permissions via settings.json directly |
| Developing prompt or agent hooks for judgment-based decisions | Building MCP servers or custom tool integrations |
Core Concepts
What Are Hooks? Hooks are user-defined shell commands that execute at specific points in Claude Code's lifecycle. Unlike relying on Claude to "decide" to run something, hooks provide deterministic, guaranteed execution.
Why Use Hooks?
- Enforce code formatting automatically
- Block dangerous commands before execution
- Inject context at session start
- Log commands for audit trails
- Send notifications when tasks complete
Hook Lifecycle Events
| Event | When It Fires | Key Use Cases |
|---|---|---|
| SessionStart | Session begins/resumes | Environment setup, context loading |
| SessionEnd | Session terminates | Cleanup, state persistence |
| UserPromptSubmit | User submits prompt | Input validation, context injection |
| UserPromptExpansion | A typed skill/command/MCP prompt expands, before it reaches Claude | Block a command, inject skill-specific context, log invocations |
| PreToolUse | Before tool execution | Permission control, blocking dangerous ops |
| PostToolUse | After tool completes | Auto-formatting, logging, validation |
| PostToolUseFailure | After tool execution fails | Retry decisions, error handling |
| PermissionRequest | Claude requests permission for a tool | Auto approve/deny without user prompt |
| PermissionDenied | Auto mode denies a tool call | Audit denials, tell the model it may retry (retry: true) |
| PostToolBatch | A batch of parallel tool calls has resolved, before the next model call | Inject context once per batch, stop the loop |
| Stop | Main agent finishes responding | Notifications, git reminders |
| SubagentStart | Subagent (Task tool) is about to start | Input modification, context injection |
| SubagentStop | Subagent finishes | Per-task completion evaluation |
| WorktreeCreate | New git worktree created via EnterWorktree | Worktree setup, dependency install |
| WorktreeRemove | Worktree removed after session exits | Cleanup, uncommitted changes alert |
| TeammateIdle | Teammate in agent team goes idle | Assign additional tasks to teammate |
| TaskCompleted | Task in shared task list marked complete | Validation gates before task acceptance |
| PreCompact | Before context compaction | Transcript backup |
| Notification | Claude sends notification | Custom alerts |
| ConfigChange | Claude Code settings change at runtime | Audit config changes, validation |
| PreModelSwitch | Before the session model changes (/model, fallbackModel, safety-classifier fallback) | Audit or record the outgoing model |
| PostModelSwitch | After the session model has changed | Re-apply per-model settings, log the new model |
Stop vs SubagentStop:
Stopfires at the session level when the main agent finishes a response turn.SubagentStopfires when an individual subagent (spawned via the Task tool) completes. UseStopfor session-level notifications; useSubagentStopfor per-task quality gates.
For full schemas, examples, and timeout recommendations for each event, see .claude/rules/hooks-reference.md.
Configuration
File Locations
Hooks are configured in settings files:
~/.claude/settings.json- User-level (applies everywhere).claude/settings.json- Project-level (committed to repo).claude/settings.local.json- Local project (not committed)
Claude Code merges all matching hooks from all files.
Frontmatter Hooks (Skills and Commands)
Hooks can also be defined directly in skill and command frontmatter using the hooks field:
Example frontmatter: references/frontmatter-hooks.md.
Basic Structure
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{
"type": "command",
"command": "your-command-here",
"timeout": 30
}
]
}
]
}
}
Matcher Patterns
- Exact match:
"Bash"- matches exactly "Bash" tool - Regex patterns:
"Edit|Write"- matches either tool - Wildcards:
"Notebook.*"- matches tools starting with "Notebook" - All tools:
"*"- matches everything - MCP tools:
"mcp__server__tool"- targets MCP server tools
Input/Output Schema Summary
Hooks receive JSON via stdin with common fields (session_id, transcript_path, cwd, permission_mode, hook_event_name). Event-specific fields include tool_name and tool_input for PreToolUse, plus tool_response for PostToolUse, and subagent_type/subagent_prompt for SubagentStart.
Exit codes: 0 = allow, 2 = block (stderr shown to Claude), other = non-blocking error.
JSON responses vary by event: PreToolUse uses hookSpecificOutput with permissionDecision; Stop/SubagentStop use decision/reason; SubagentStart uses updatedPrompt; SessionStart uses hookSpecificOutput with additionalContext.
For detailed hook schemas and examples, see REFERENCE.md.
Common Hook Patterns
Worked scripts (block dangerous commands, auto-format after edits, tool reminders, SessionStart context): references/hook-patterns.md.
For additional patterns (subagent injection, desktop notifications, audit logging, auto-approve, worktree setup, task gating), see REFERENCE.md.
Prompt-Based and Agent-Based Hooks
Four hook types: command (shell script, exit code), http (HTTPS endpoint), prompt (single-turn LLM call), and agent (multi-turn with tool access). Use command for deterministic rules; prompt/agent for judgment-based decisions. Add async: true for fire-and-forget; once: true to run only once per session.
Prompt and agent hooks work on PreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, Stop, SubagentStop, TaskCompleted, UserPromptSubmit. All other events support command hooks only.
For hook type details, CLAUDE_ENV_FILE, and configuration examples, see REFERENCE.md and .claude/rules/prompt-agent-hooks.md.
Handling Blocked Commands
When a PreToolUse hook blocks a command:
| Situation | Action |
|---|---|
| Hook suggests alternative | Use the suggested tool/approach |
| Alternative won't work | Ask user to run command manually |
| User says "proceed" | Still blocked - explain and provide command for manual execution |
Critical: User permission does NOT bypass hooks. Retrying a blocked command will fail again.
When command is legitimately needed:
- Explain why the command is required
- Describe alternatives considered and why they won't work
- Provide exact command for user to run manually
- Let user decide
Timeout Guidelines
The default hook timeout is 600s (10 minutes) since Claude Code 2.1.50. Set explicit timeouts to document intent and prevent "Hook cancelled" errors:
| Hook Type | Recommended Timeout | Use Case |
|---|---|---|
| SessionStart | 120–300s | Tests, linters, dependency checks |
| SessionEnd | 60–120s | Logging, cleanup, state saving |
| Stop / SubagentStop | 30–60s | Git status checks, quick validations |
| PreToolUse | 10–30s | Quick validations |
| PostToolUse | 30–120s | Logging, notifications |
| PermissionRequest | 5–15s | Keep fast for good UX |
For slow work, run it in a background subshell: references/hook-patterns.md.
Best Practices
| Area | Key Points |
|---|---|
| Script | Read stdin with cat; parse with jq; quote all vars; exit 2 to block, 0 to allow; stderr for messages; keep < 5s |
| Config | $CLAUDE_PROJECT_DIR for portable paths; explicit timeouts; specific matchers over wildcards; test before enabling |
| Security | Validate all inputs; use absolute paths; avoid .env / .git/ directly; review before deploy |
Debugging
Hook cancelled, failing, or not firing: references/troubleshooting.md.
Readme
Hooks Plugin
Claude Code hooks for enforcing best practices and workflow automation.
Overview
This plugin provides pre-built hooks that can be installed in any project to enforce consistent behavior and remind Claude to use the correct tools.
Toggling behavior: every env var that turns a hook on/off or tunes it — across hooks-plugin, git-plugin, and taskwarrior-plugin — is indexed in
docs/feature-flags.md(opt-in / opt-out / tunable, with source pointers). The per-hookToggle:lines below are the deep detail.
Available Hooks
bash-antipatterns.sh
A PreToolUse hook that intercepts Bash commands and blocks those that should use built-in tools instead.
Detected Anti-patterns:
| Pattern | Reminder |
|---|---|
cat file | Use Read tool instead |
head/tail file | Use Read tool with offset/limit |
sed -i (repo files; /tmp/scratch targets exempt, #2052 — reachable via a literal path, a cd target, or a variable value, W34 §Signal C) | Use Edit tool instead |
echo/printf > file (repo files; absolute /tmp/scratch destinations exempt, W38) | Use Write tool instead |
cat > file | Use Write tool instead |
timeout cmd | Remove timeout (human approval time exceeds it); append # allow-timeout for genuinely-unbounded processes (#2041) |
| Multi-grep test parsing | Use --reporter=json instead |
The safety blocks (git add -A, git chains, reset --hard, curl | sh, fork
bombs, chmod 777, block-device writes) are in bash-safety.sh, below.
The three write rows share one scratch context: a cd into /tmp, a variable
holding a /tmp path, or a mktemp -d dir (T=$(mktemp -d),
cd "$(mktemp -d)") exempts the write (#2892). The context is decided for the
whole command, so such an assignment exempts every write in it, including a
write to a repo path that never uses the variable; sed -i has carried the
same trade-off since W34. echo/printf > file and sed -i also pass when
every destination is a literal tmp/ or ./tmp/ path (no glob) that
git -C <cwd> check-ignore reports ignored, and the command contains no
cd/pushd/popd. A tracked tmp/ still blocks (#2837). The Claude Code
harness scratchpad under $HOME/tmp/claude-<uid>/…/scratchpad/ counts as
scratch too, as a literal sed -i operand, a cd target, or a variable value;
a plain $HOME/tmp/ path does not (#3525).
echo/printf > file no longer blocks. The command runs and the hook returns
a PreToolUse additionalContext note preferring Write, because a Bash-only edit
is not restored by /rewind. sed -i still blocks, except when every file it
edits was copied with cp earlier in the same command (the mutation-probe
shape cp f tmp/snap && sed -i … f && test; cp tmp/snap f).
The read/write detectors (cat/head/tail, echo/printf/cat writes,
sed -i, task-output reads) are classified structurally via
ast-grep --lang bash — a real parse distinguishes a command from a
string/heredoc-body/pipeline/argument, retiring the regex false-positive
treadmill (#1701/#1721/#1722/#1848/#2052/#2058) and the remote-exec guard
(#1900). They are style nudges that fail open when ast-grep is absent
(no regex twin, #2008); the safety blocks in bash-safety.sh stay pure-regex
and fire in every context. The three read rules additionally require the read to be the
whole command (#2148) — cat f.md blocks, cd repo && cat f.md and
ls d/; head -20 f do not; the write rules are unscoped by that narrowing.
find (#1871), grep/rg (#1909), ls <glob> (#2036), and long pipelines
(5+ pipes from a cat/echo/printf or grep|grep head, #1873) are not
blocked — those redirects were demoted to non-blocking hints in the opt-in
teach hook (bash-antipatterns-teach.sh). See
.claude/rules/hook-block-vs-nudge.md for the block-vs-nudge litigation.
bash-safety.sh
A PreToolUse hook holding the Bash safety blocks, split out of
bash-antipatterns.sh so they can be exported to other harnesses without that
hook's Claude-Code-specific tool advice (#2788). Every detector is pure regex,
fires in every context (sandboxes and subagents included, with or without
ast-grep), and sources no library.
| Pattern | Reminder |
|---|---|
git add -A / git add --all / git add . | Stage specific files by name instead |
Two index-modifying git commands chained with && (git add a && git commit) | One git add -- A B C, then git commit as a separate call (index.lock races) |
git reset --hard | Use git pull, git restore, or git reset --soft instead |
git push -u origin main:feat/x from main | Push without -u |
curl | sh / wget | bash | Download first, review, then execute |
| Fork bombs | Blocked unconditionally |
chmod 777 | Use restrictive permissions (755, 644, 600) |
| Write to block device | Blocked unconditionally |
Heredoc bodies and trailing # comments are data, not commands, for the
line-anchored git blocks (#2106, #2431). The network-to-shell, fork-bomb,
chmod 777 and block-device checks skip a quoted heredoc body fed to
cat/tee/gh/git with no pipe (#3363). The pi export
(scripts/generate-pi-hook-extension.py) includes this hook and leaves
bash-antipatterns.sh out. Pinned by hooks/test-bash-safety.sh.
git-stash-session-init.sh
A SessionStart hook that writes two session-scoped baselines used by other hooks:
| Baseline | Path | Used by |
|---|---|---|
| Pre-existing stash hashes | <baseline-dir>/<session_id>.d/<sha256-of-git-common-dir> | git-stash-reminder.sh |
| Stash hashes already reported | <baseline-dir>/<session_id>.d/<sha256-of-git-common-dir>.reported | git-stash-reminder.sh (written by it, #2686) |
| Session start time | <baseline-dir>/<session_id>.d/.session-start (mtime) | git-stash-reminder.sh |
| HEAD commit at session start | /tmp/claude-test-baselines/<session_id> | test-verification.sh |
<baseline-dir> defaults to /tmp/claude-stash-baselines and is overridable with
CLAUDE_STASH_BASELINE_DIR. The stash baseline is keyed on the git common
dir, not the repo root, because refs/stash lives in the common dir and is
therefore shared by every linked worktree — one stash namespace, one baseline.
Both writes are write-once per session: a SessionStart re-fire on
resume/compact/clear deliberately leaves them alone, so it cannot retroactively
un-report a stash the Stop hook already flagged.
git-stash-reminder.sh
A Stop hook that checks for git stashes created during the current session. Pre-existing stashes (recorded at session start by git-stash-session-init.sh) are ignored.
| Condition | Action |
|---|---|
| Hand-made session stash | Block, recommend git stash pop |
auto-checkpoint before … session stash, CLAUDE_HOOKS_ENABLE_AUTO_CHECKPOINT=1 | Block, recommend "verify against the working tree, then git stash drop" (#2686) |
auto-checkpoint before … session stash, flag unset (default) | Silent: the reminder's checkpoint branch is opt-in with auto-checkpoint.sh (#2652) |
| Stash tree equals the working tree | Silent exit — it holds nothing the tree does not (#2686) |
Checkpoint tagged [worktree: <path>] matching that worktree, or (worktree removed) matching one branch path for path | Silent exit — judged where a worktree subagent took it (#3055) |
| Already reported earlier this session | Silent exit — reviewing and keeping a stash clears the block (#2686) |
| Only pre-existing stashes | Silent exit (no block) |
| No stashes at all | Silent exit |
| Repo first seen mid-session | Baseline captured for that namespace, then the age filter still applies — a genuine session stash is reported |
Toggle: CLAUDE_HOOKS_DISABLE_GIT_STASH_REMINDER=1 disables the hook entirely.
A repo the session enters later (a moved cwd, a linked worktree, a repo that was stash-free at SessionStart) gets its baseline captured on first observation, but only stashes older than the session start are absorbed into it — so a stash the session actually created is reported on that Stop and every Stop after.
The three #2686 filters exist to keep the block satisfiable. A Stop hook that
re-fires on the same entry for the life of the session — which is what happened
once auto-checkpoint.sh switched to git stash create + git stash store
(#2610/#2641) and every checkpoint began persisting in git stash list — teaches
the agent to ignore it, which is worse than a hook that never fires. Reported
commit hashes are remembered in a sibling <baseline>.reported file (hashes, not
stash@{N}, so the memory survives reindexing).
Redundancy is judged by comparing the stash commit against the working tree, and
a stash carrying an untracked payload — a 3rd parent, which only
git stash push -u creates — is never called redundant: git diff cannot see
that payload, and it is exactly the content #2610 was filed to protect. Both new
filters fail toward reporting, so an unreadable memory file or an errored
comparison costs a repeated nag rather than silent information loss.
Tests: bash hooks-plugin/hooks/test-git-stash-reminder.sh (hermetic — sandboxed via CLAUDE_STASH_BASELINE_DIR).
session-end-issue-hook.sh
A Stop hook that fires when the main agent finishes a response. If the session transcript contains any TodoWrite todos with status: "pending" or status: "in_progress", it blocks and surfaces the list to Claude with suggested gh issue create commands. Silent when all todos are completed. Depends on the TodoWrite tool, which is off by default on Opus 4.8, Sonnet 5, Fable 5/5.1 and newer unless CLAUDE_CODE_ENABLE_TODO_TOOLS=1 is set — without it the hook is silent on every response, which is not the same as "all todos completed" (see /hooks:session-end-issue-hook Step 1).
| Condition | Behaviour |
|---|---|
| No pending todos | Exits 0 silently — no interruption |
| Pending / in-progress todos | Blocks with list and gh issue create suggestions |
Configure via /hooks:session-end-issue-hook or see Session End Issue Hook below.
git-session-cleanup.sh
A SessionEnd hook that runs cleanup operations when the session terminates: commits any staged changes, switches to the main/master branch, and pulls the latest changes.
| Step | Behaviour |
|---|---|
| Commit | Commits staged files with chore: auto-commit staged changes (skipped if nothing staged) |
| Switch | Switches to main (or master if main doesn't exist); no-op if already on main |
| Pull | Runs git pull --ff-only to fast-forward the branch |
secret-protection.sh
A PreToolUse hook that blocks access to sensitive files and prevents credential exposure.
| Category | Blocked Patterns |
|---|---|
| Environment files | .env, .env.* (allows .env.example, .env.sample) |
| SSH credentials | .ssh/id_*, .pem, *_rsa, *_ed25519 |
| Cloud credentials | .aws/credentials, .config/gcloud/, .kube/config, .docker/config.json |
| Credential files | credentials.json, secrets.json, .api_tokens (e.g. ~/.api_tokens), *.keystore, *.key |
| Bash reader verbs | cat/head/tail/less/more/editors (any argument mentioning a protected path), plus sed/awk/grep/cut/perl/rg when the protected path is a standalone file argument — a protected name inside a quoted search pattern or sed script passes. source/. of a token file is allowed (it loads, not prints). A protected path that is only an output-redirect target is a write and passes (cat > .env, … | ssh host 'cat > /srv/app/.env'); one read anywhere in the command (cat .env > /tmp/x, ssh host 'cat /srv/app/.env', the read-write redirect cat <>.env, a substitution such as cat >/tmp/a$(cat .env)) still blocks (#3594) |
| Env var exposure | Commands that echo $API_KEY, $SECRET, $TOKEN, $PASSWORD; the verb (echo/printf/cat/env/printenv/export) must be a command word, so source .env && tool --token=$X_TOKEN and dotenv run -- … pass |
| Full env dump | Bare printenv or env commands |
The Bash checks match their patterns against the raw command, then — when ast-grep is installed — lift a block whose every matching verb sits in text no shell runs: a quoted argument or heredoc body of git commit / gh issue|pr <create|comment|edit|review|close|reopen|merge>, a $(cat <<'EOF' … EOF) body feeding one, or a comment. So git commit -m "docs: never cat .env in CI" passes, while $(cat .env) or backticks inside that text, any other program's text (echo 'cat .env' | bash, bash -c, ssh, eval), a command that rebinds git/gh (a function, alias, trap, PATH=), an allowlisted command that itself names a protected file (--body-file .env, --template .env), and double-quoted or unquoted-heredoc text that expands a secret variable ("$API_TOKEN") still block. Backslash-newline continuations are joined before matching, so cat \⏎.env is one read. Without ast-grep, or on a parse error, the regex verdict stands (#2737).
The env-var exposure check also lifts when every secret reference sits in a single-quoted script run on another host, which the local shell never expands: an argument of ssh host '…' (no ProxyCommand/LocalCommand-style option), or of kubectl … exec … -- sh -c '…' after the --. So kubectl exec redis-master-0 -- sh -c 'export REDISCLI_AUTH="$REDIS_PASSWORD"; redis-cli INFO' passes. A double-quoted or unquoted reference, bash -c/sh -c/eval (local), a remote command inside a pipeline or $(…), and any secret reference elsewhere in the command (ssh host 'cat -' <<<"$API_TOKEN") still block. Sensitive-file reads inside the remote script (ssh host 'cat .env') are not exempt (#3424).
Toggle: CLAUDE_HOOKS_DISABLE_SECRET_PROTECTION=1, honored only when a human operator exports it in their own shell environment — an inline prefix on the blocked command is intentionally not honored, so an agent cannot self-serve the bypass (see .claude/rules/handling-blocked-hooks.md).
branch-protection.sh
A PreToolUse hook that blocks write operations on protected branches (main, master).
Defers to auto mode. Under permission mode "auto", Claude Code routes the actual tool call through its own classifier with full environment context, which already covers force-push and protected-branch pushes. This hook would only double-gate that (and re-introduce blunt false positives), so it exits early when permission_mode == "auto". It still enforces in default/plan/acceptEdits and in surfaces where auto mode is unavailable (web/remote/CI, or a plan/model that does not offer it). Auto mode is the default permission mode in current Claude Code, so in an ordinary local session this hook is normally silent and the classifier owns the protected-branch decision.
| Operation | Behavior |
|---|---|
| Read-only git (status, diff, log, show) | Allowed |
| Checkout/switch to another branch | Allowed |
Push with explicit refspec (main:feature) | Allowed |
| Initial bootstrap push (single root commit) to main | Allowed (initializes an empty remote) |
| Merge (local feature branch into main) | Allowed (reversible) |
| Commit, rebase, push | Blocked with branch creation suggestion |
| Staging (git add, rm, mv) | Blocked |
| Reset | Blocked |
Toggle: export CLAUDE_HOOKS_DISABLE_BRANCH_PROTECTION=1 in your shell environment (e.g. in a personal repo, dotfiles, or main-branch-dev workflow). This is a human-operator opt-in — inline prefixes like CLAUDE_HOOKS_DISABLE_BRANCH_PROTECTION=1 git commit ... on a Bash command are intentionally not honored, so that agents cannot self-serve the bypass. When blocked on a protected branch, an agent should follow .claude/rules/handling-blocked-hooks.md and delegate to the user instead.
repo-deletion-safety.sh
A PreToolUse hook that blocks rm -rf on a git repository whose history exists nowhere else — no remote, or a remote that has never been pushed to. Such a delete destroys committed history, the working tree, every stash and every unpushed branch with a strictly empty recovery path, which is why it is a hard block rather than a nudge. The advisory counterpart is the git-plugin:git-repo-delete-check skill (/git:repo-delete-check).
Target of rm -r/-rf/--recursive | Behavior |
|---|---|
| Repo root with no remote (tier 1a) | Blocked (exit 2) |
| Repo root whose remote has never been pushed to (tier 1b) | Blocked (exit 2) |
| A plain directory holding such repos (scanned to depth 3, capped at 20) | Blocked per offending repo |
| Remote-backed repo with uncommitted / unpushed / stashed work (tier 2) | ask — opt-in, off by default |
| A path inside a repo, a linked worktree, a submodule, a symlink | Allowed — the operand must be a repo root |
Repos under /tmp, /private/tmp, /var/folders, $TMPDIR | Allowed by default |
A repo with an existing <basename>-*.tar.* in the backup dir | Allowed — this is what makes the block self-extinguishing |
The block message reports what the preflight found in that repo (commits, uncommitted changes, stashes, local branches — every probe capped so the hook finishes inside its timeout; on Claude Code 2.1.295+ a timeout blocks the deletion through onFailure: "block", but the configured timeout of 5000 is read as seconds, so it does not fire in practice — the units are tracked separately) and points at git-plugin:git-repo-delete-check for the remediation options; that skill is their single authority, so the message does not restate them (#2454). The one option it keeps verbatim is the tar backup to $CLAUDE_REPO_BACKUP_DIR, because writing that tarball is what changes the world state the hook reads, so the retried rm -rf succeeds with no override. Fails open on unresolvable operands ($VAR, $(…), globs, {}) and on remote-exec commands; sibling verbs (git clean -xdff, trash, mv, rmdir, shred, find … -delete) are out of scope. Full enumerated gap list in hooks/README.md.
Toggle: export CLAUDE_HOOKS_DISABLE_REPO_DELETION_SAFETY=1 in your shell environment. Like branch protection, a human-operator opt-in — an inline VAR=1 rm -rf … prefix is intentionally not honored (the statement parser strips leading assignments), so agents cannot self-serve the bypass. Tuning: CLAUDE_REPO_BACKUP_DIR (default $HOME/Backups), CLAUDE_HOOKS_REPO_DELETION_TMP_EXEMPT (default 1), CLAUDE_HOOKS_REPO_DELETION_WARN_DIRTY (default 0).
Tests: bash hooks-plugin/hooks/test-repo-deletion-safety.sh (hermetic — all fixtures under mktemp -d).
workflow-scale-guard.sh
A PreToolUse hook on the Workflow tool that asks the user to confirm before a multi-agent workflow spawns more agents than the configured limit. A workflow's cost is set almost entirely by its agent count, and that number is a property of the script's shape rather than of the prompt that asked for it.
Two shipped mechanisms look like they cover this and do not. workflowSizeGuideline is advisory system-prompt text that ends "This is a guideline, not a hard limit — follow it unless the user's prompt calls for a different scale", and a sweep-shaped prompt reads exactly like a call for a different scale. skipWorkflowUsageWarning is a one-time acceptance of the multi-agent usage warning; once set, auto mode stops prompting before every workflow, at every scale, permanently. Observed 2026-09-15: five workflow runs in one session spawned 496 subagents against a medium guideline of 10 and cost $528 in an afternoon — 67% of the day's spend and roughly 8x the entire GitHub Actions bill — with no prompt, because the acceptance flag had been set long before.
The rule is count or ask. The estimator parses the script and counts each agent() call site only when every loop or fan-out around it has a bound written in the text; any other site is unbounded, and one unbounded site is enough to ask.
| Script shape | Behavior |
|---|---|
Plain top-level agent() calls, parallel([() => agent(), ...]) thunks | Counted (once each) |
for...of / .map / .forEach / .flatMap / parallel(xs.map(...)) / pipeline(xs, ...) over an array literal or a .slice(a, b) with numeric literals | Counted (list length, or b - a) |
for (let i = 0; i < 5; i++) or i += step, with literals, whose body never writes i (a var counter is not counted: code outside the body can reset it) | Counted (iterations) |
Counted total within CLAUDE_HOOKS_WORKFLOW_MAX_AGENTS | Silent |
| Counted total over the limit | ask with the count |
A list the text does not bound (args.units, const DIMS = [...], const top = xs.slice(0, 6), xs.length), a while / do / for...in loop, a site inside any named function (a named function expression passed inline included: it can call itself), method, class, or function value, every workflow() child, and agent used as a value (an alias, a callback, a template tag, a property read such as ctx.agent, a destructuring rename such as const { agent: spawn } = ctx). agent.call(...) / agent.apply(...) and property calls such as ctx.agent(...) / globalThis["agent"](...) are call sites like agent(...) | ask, naming each line and why |
A script that does not parse, one the estimator fails on, one the parser crashes or times out on (twice: one retry absorbs a cold node start), or an estimator run that exits non-zero or prints no verdict | ask, saying so |
Resume (resumeFromRunId), saved workflow by name, no agent() call | Silent |
The ask says how to make a run silent: slice the list in the fan-out itself (for (const x of items.slice(0, 6)), items.slice(0, 6).map(...)) or bound a for loop by a literal (i < 6), and call agent() inline in that fan-out. A capped copy held in a variable (const top = items.slice(0, 6)) still asks, because variables are not resolved. A caller-supplied list is unbounded by design, so a template whose fan-out width comes from its arguments asks before every run; that is the intended trade.
What it deliberately does not try to do: resolve variables (a const holding a literal can still be pushed to), follow helper functions or their call sites, model mutation, recursion, getters, or any other JavaScript semantics. Each of those makes a site unbounded, so the cost of not modelling them is an extra question. Not seen at all: agent reached without being named (globalThis["age" + "nt"]). Taken on trust, and so a possible silent over-spend: parallel, pipeline, .slice, .map, .forEach and .flatMap are recognised by name, so a script that shadows or redefines one (a local parallel, a user .slice, a patched Array.prototype.map) is counted as if it had not. The pre-parser estimator this replaces grew to 3,885 lines across twelve review rounds (#2787) chasing shapes like these; asking is cheaper than modelling them.
ask, not a block, on purpose. The failure is not "this workflow is forbidden", it is "nobody was asked". A hard block would make the agent judge whether the scale is justified, which is the judgment that already went wrong; ask puts the number in front of the person paying and lets them approve in one keystroke. It is also the only enforcement point: a SubagentStart hook fires per agent but cannot stop a workflow's agents from starting.
Estimation runs in hooks/workflow-scale-estimate.py, which parses with acorn 8.18.0 (MIT, vendored unmodified under hooks/lib/vendor/acorn/, run by hooks/lib/workflow-scale-parse.cjs under node). Its rollup reports PARSER=acorn. A parser that crashes or times out twice (each attempt gets CLAUDE_HOOKS_WORKFLOW_PARSE_TIMEOUT seconds, default 2; a timeout is retried once, for a cold node start, so the worst case is about 4 s, inside the hook's 5 s budget), or an error while walking a script that parsed, is VERDICT=ANALYSIS_ERROR, and the guard asks. The guard also asks, as ANALYSIS_ERROR, when the estimator process exits non-zero or prints no verdict, with or without node; the pre-parser guard exited 0 there. Only without node does it fall back to the pre-parser regex estimator (hooks/lib/workflow-scale-estimate-fallback.py) and report PARSER=fallback: that estimator costs a runtime-length fan-out at CLAUDE_HOOKS_WORKFLOW_ASSUMED_WIDTH items and never reports unbounded, so a machine without node counts as it did before this rule, and an exception inside it is VERDICT=ERROR, which stays silent as it did then. A script file that is not valid UTF-8 is read with the bad bytes replaced, so it is still parsed, and the rollup is written as UTF-8 whatever the locale, so a latin-1 or ASCII stdout cannot crash the estimator.
Bundled workflow templates declare their agent count as **Agent budget:** in the skill's framing section; scripts/check-workflow-js-model.sh checks it against the same estimator (an integer when every site is counted, a per-item formula such as 2 + 2 x cells when some are not).
Toggle: export CLAUDE_HOOKS_DISABLE_WORKFLOW_SCALE_GUARD=1. Tuning: CLAUDE_HOOKS_WORKFLOW_MAX_AGENTS (default 10, matching the medium guideline; the guard asks when the counted total exceeds it, so a total equal to it is silent, 0 asks on any counted agent, and a value that is not all digits means 10), CLAUDE_HOOKS_WORKFLOW_ASSUMED_WIDTH (default 8, read only by the no-node fallback). CLAUDE_HOOKS_WORKFLOW_PARSE_TIMEOUT is the estimator's per-attempt parser timeout in seconds (default 2; a value that is not a positive number means 2). The hook leaves it at 2 so two attempts fit its 5 s budget: at 4, a double timeout outlasted the budget, the runtime killed the hook, and the Workflow call ran with no ask (#3093); scripts/check-workflow-js-model.sh, a CI guard with no latency budget, runs the estimator with 30 so a cold node start on a loaded runner that outlasts both 2 s attempts is not reported as estimator_error (#3005, #2975). A hook runs as its own process with the session environment, so there is no inline prefix an agent can use to reach these — raising the limit is an operator action.
Tests: bash hooks-plugin/hooks/test-workflow-scale-guard.sh (table-driven: counted shapes stay silent, each unbounded kind asks, over-limit and parse-error ask, the structural guards stay silent, the no-node fallback reproduces the pre-parser behaviour, and a crashing or cold-starting parser asks rather than falling back).
subagent-count-tripwire.sh
A SubagentStart + Stop hook that tells the user, after the fact, how many subagents the session has started. workflow-scale-guard.sh estimates a workflow before it runs; this counts what actually ran, across Workflow agents (agent_type workflow-subagent) and Agent-tool subagents alike. It exists because a SubagentStart hook cannot block or stop a subagent — it can only add context to one (additionalContext): on Claude Code 2.1.283, exit 2, {"decision":"block"}, {"continue":false} and updatedPrompt were all ignored. A trivial workflow agent still costs ~66k tokens of prompt-cache creation.
| Event | Behavior |
|---|---|
SubagentStart | Appends agent_id/agent_type to ${TMPDIR:-/tmp}/claude-subagent-count-<uid>/<session_id>.log. Silent, always exits 0. It creates the directory mode 700 and writes nothing unless the directory is owned by the current user and is not a symlink. On a session's first subagent it deletes top-level .log files idle for over 3 days, each with its .reported marker, plus .reported markers idle for over 3 days whose log is gone. Cleanup runs only in a directory the hook created, so pointing CLAUDE_HOOKS_SUBAGENT_COUNT_DIR at an existing directory never deletes anything in it. |
Stop | Counts distinct agent_ids (a resumed subagent re-fires SubagentStart). When the count reaches the next unreported threshold, prints one systemMessage, e.g. This session has started 20 subagents (14 workflow, 6 agent-tool); limit is 10. |
Thresholds are the limit, then each doubling (10, 20, 40, 80, ...), each reported once; jumping past several at once reports once. systemMessage is shown to the user and does not continue the turn — no decision: "block", no additionalContext.
A workflow's agents start after the Stop of the turn that launched it, so the count is reported at a later Stop: in an interactive session, the turn that handles the workflow's completion. A headless claude -p run can end before any Stop sees the full count.
Toggle: export CLAUDE_HOOKS_DISABLE_SUBAGENT_COUNT=1. The first threshold is CLAUDE_HOOKS_WORKFLOW_MAX_AGENTS (default 10), shared with workflow-scale-guard.sh, which reads it differently. Here a count equal to the threshold reports, and 0, or a value that is not all digits, means 10, since the thresholds double from it. The guard asks only when a script's counted total exceeds the limit, and treats 0 as asking on any counted agent.
Tests: bash hooks-plugin/hooks/test-subagent-count-tripwire.sh.
context-threshold-nudge.sh
A PostToolUse hook that tells the agent when its context has grown past a size threshold. It exists for Claude Haiku 5.5, which is priced by prompt length: a request whose prompt is over 100,000 tokens, cache reads and writes included, pays 5x the input, cache and output rates, and so does every later request until the context shrinks. A Haiku worker or a /loop session crosses that line without noticing. Measured 2026-10-15: a bare Haiku session starts at about 35.5K prompt tokens, one in this repo at about 69K, and a fresh subagent at about 24K, before any work.
No hook event carries a token count, so the hook reads the newest assistant usage record in the last 500 lines of the transcript and sums input_tokens, cache_creation_input_tokens and cache_read_input_tokens.
| Situation | Behavior |
|---|---|
Model is claude-haiku-5-5, CLAUDE_HOOKS_CONTEXT_THRESHOLDS unset | Thresholds 80,000 and 95,000 |
Any other model, CLAUDE_HOOKS_CONTEXT_THRESHOLDS unset | Silent |
CLAUDE_HOOKS_CONTEXT_THRESHOLDS has a valid entry | Those thresholds, for every model; the 100,000-token price note is added only on Haiku 5.5 |
| Prompt reaches a threshold above the last one reported | One additionalContext message, e.g. Context check: your last request sent 81,234 prompt tokens, past the 80,000-token warning threshold. ... |
Prompt drops back under the lowest threshold (after /compact) | Re-arms; the thresholds report again |
Payload carries agent_id | Reads <transcript>/subagents/agent-<id>.jsonl and keeps separate state, so each subagent is warned about its own context |
It never blocks and always exits 0. State is one small file per session (and per subagent) in ${TMPDIR:-/tmp}/claude-context-threshold-<uid>/, created mode 700 and used only when it is a real directory owned by the current user.
Lag: Claude Code writes the transcript after the request, and the file can trail the live conversation, so the warning usually arrives one or two tool calls after the crossing. The 5,000-token gap between 95,000 and the price threshold absorbs that for ordinary tool results; a single very large read can still overshoot it.
Toggle: export CLAUDE_HOOKS_DISABLE_CONTEXT_THRESHOLD=1. Tuning: CLAUDE_HOOKS_CONTEXT_THRESHOLDS (comma-separated token counts; entries that are not all digits are dropped, and a list with no valid entry means the Haiku defaults).
Tests: bash hooks-plugin/hooks/test-context-threshold-nudge.sh.
branch-base-guard.sh
A PreToolUse hook that nudges before cutting a new branch from a local default branch that is ahead of its remote — git-hazards.md trap #2: unpushed commits on local main ride into the new branch, get bundled into its PR under an unrelated title, and a squash-merge hides them everywhere except the file list.
| Aspect | Detail |
|---|---|
| Tier | Nudge (permissionDecision: "ask"), never a deny — nothing here is irreversible. Same tier as git-plugin's check-branch-sync-on-push.sh |
| Fires on | git switch -c/-C/--create/--force-create, git checkout -b/-B, git worktree add … -b/-B |
| Only when | HEAD is the resolved default branch, and no explicit start-point was given, and local <default> is ≥1 commit ahead of origin/<default> |
| Exempt | An explicit start-point (git switch -c feat/x origin/main — the hook's own suggested fix), --track/-t, feature-branch bases, in-sync defaults, no origin, detached HEAD, all git branch forms, quoted mentions, remote-exec |
| Default branch | Resolved (refs/remotes/origin/HEAD, then a probed main/master), never hardcoded |
| Dedup | At most one nudge per session+repo+default per TTL; silent when the ahead-count is 0 |
| Network | None by default — a stale origin/<default> can only overstate the count |
| Auto mode | Does not defer: auto mode's classifier has no notion of which base a branch is cut from |
Known gaps: bare git branch <name> is deliberately out of scope (listing/deleting/-vv dominate its use, so disambiguating creation costs more false positives than the coverage buys); a never-fetched origin/<default> can overstate the count; cutting from an equally-ahead feature branch is uncovered.
Toggle: export CLAUDE_HOOKS_DISABLE_BRANCH_BASE_GUARD=1 in your shell environment — the documented answer for a repo that legitimately develops on its default branch (dotfiles, personal repos). Human-operator opt-in; an inline prefix is intentionally ignored. Tuning: CLAUDE_HOOKS_BRANCH_BASE_TTL (default 300 seconds), CLAUDE_HOOKS_BRANCH_BASE_FETCH (default 0).
Tests: bash hooks-plugin/hooks/test-branch-base-guard.sh (hermetic — fixture repos under mktemp -d).
worktree-location-guard.sh
A PreToolUse hook that denies a hand-rolled git worktree add whose path lands outside the target repo's <repo>/.claude/worktrees/. Claude Code creates its own worktrees there; a sibling such as ../<repo>-wt-<task> has no cleanup lifecycle and outlives its merged PR. The hook resolves the repo from git -C <dir> first, so a session working on another repo is pointed at that repo's .claude/worktrees/.
| Aspect | Detail |
|---|---|
| Tier | Deny (permissionDecision: "deny") with the corrected command in the reason. The fix is the same command with a different path, so the agent is never dead-ended, and no permission prompt reaches the user |
| Fires on | git [-C <dir>] worktree add … <path> |
| Base directory | The hook input's cwd, moved by each literal cd <dir> earlier in the command, then by git -C <dir>. After a cd it cannot resolve ($VAR, cd -, a missing dir) it decides against the cwd as before but omits the Retry with: command |
| Allowed | <main-repo>/.claude/worktrees/<name> (resolved from --git-common-dir, so a session inside a linked worktree targets the main repo), and scratch worktrees under $TMPDIR, /tmp, /private/tmp, /var/folders |
| Denied | Any other path, including a path nested inside another linked worktree |
| Silent | Unresolvable paths ($VAR, $(…), globs), quoted mentions, other worktree subcommands, non-repo cwd, remote-exec |
| Not git-ignored | When <main-repo>/.claude/worktrees/ is not ignored, the deny message adds an echo '.claude/worktrees/' >> <info/exclude> command, and an allowed add gets the same note as non-blocking additionalContext, so the worktree does not surface as untracked files to commit |
Toggle: export CLAUDE_HOOKS_DISABLE_WORKTREE_LOCATION_GUARD=1 in your shell environment. An inline prefix is intentionally ignored.
Tests: bash hooks-plugin/hooks/test-worktree-location-guard.sh (fixture repos under $HOME/.cache, since the hook exempts temp dirs).
bare-declaration-guard.sh
A PreToolUse hook that blocks an Edit or Write which adds, to a shell file, a declaration whose arguments are all expansions. local, typeset, declare and export list parameters when they run with no arguments, so local $names with names unset prints every parameter in scope to stdout, exported secrets included. The listing lands in whatever captures the output: an agent transcript, a CI log, a redirected file.
| Aspect | Detail |
|---|---|
| Tier | Block (exit 2) for an Edit or Write. The listing exposes secrets, and the fix is a rewrite of the same line, so the agent is never dead-ended. A Bash command that runs or writes such a line gets a non-blocking additionalContext note instead (#3629): most of those run with a non-empty expansion, and a block would stop each one |
| Fires on | Edit and Write to a shell file: *.sh, *.bash, *.zsh, *.ksh, the rc files (.zshrc, .bashrc, .profile, …), the chezmoi source names for those (dot_zshrc.tmpl), or a file whose first line is a sh/bash/zsh/ksh/dash shebang. Also the shell lines of non-shell files (#3629): Makefile recipe lines (Makefile, GNUmakefile, *.mk; a leading tab, $$ read as $, an empty $(VAR) counted as an expansion), justfile recipe lines (justfile, .justfile, *.just; indented, {{x}} counted as an expansion), and run: values in .github/workflows/*.yml and action.yml. A top-level export in a Makefile or justfile is the tool's own directive and is not checked |
| Checked | Only the text the edit adds. A line that old_string or the file on disk already holds is not blocked |
| Blocked | local $names, export $(grep -v '^#' .env | xargs), export `cmd` , typeset -x $names, declare -p $name, typeset "${names[@]}", export "$@" — at the start of a line or after ;, &&, ||, {, (, then, do, else |
| Allowed | An assignment (local name=$value), a literal name among the arguments (local first $rest), a quoted single value (export "$name": empty is an error), a non-empty default (${names:-a b}), an abort form ("${names[@]:?names is empty}") |
| Escape hatch | A # allow-bare-decl comment on the line, or alone on the line above. It is meant for the agent: it records in the source that the line cannot expand to nothing |
| Not covered | Shell in Dockerfiles; readonly/integer/float, whose bare forms list only their own kind of parameter (bare readonly printed 6 lines and no exported canary in bash 5.2, so it is not a secret leak and gets no block). A match inside a string or a heredoc body is a false positive; on an Edit or Write the allow comment clears a string |
Which shells print the listing was measured with an exported canary variable (bash 5.2, zsh 5.9): typeset, declare and export in both, local in zsh only. The hook checks local in every shell file because a .sh file can be sourced by zsh. The suite runs each fixture in the real shells, so the pattern and the behaviour cannot drift apart.
Toggle: export CLAUDE_HOOKS_DISABLE_BARE_DECLARATION_GUARD=1 in your shell environment. An inline prefix does not reach the hook.
Tests: bash hooks-plugin/hooks/test-bare-declaration-guard.sh (bash always; the zsh column when zsh is installed, and the make and just rows when those tools are; the summary line says when the zsh column did not run).
external-pr-merge-guard.sh
A PreToolUse hook that refuses to let an agent merge a pull request authored by anyone other than the authenticated user or a bot.
A public repo attracts drive-by PRs, and merge tooling is built for bulk-merging your own and bots' PRs. A stranger's PR riding that bulk reflex is merged code nobody read — and a PR that adds a workflow, a hook, or a shell script executes on merge. Deciding whether an outside contribution is trustworthy is a human judgement call, so the agent path is closed and pointed at the human one.
| Author of the PR | Behavior |
|---|---|
The authenticated user (gh api user) | Allowed silently |
A bot — is_bot, an app/<name> login, or a <name>[bot] login | Allowed silently |
| Anyone else | Denied, naming the author, their author_association, and which touched paths execute |
Not determinable (no network, unresolvable $var selector, bad PR number, an argument that is not selector-shaped) | Denied — "cannot verify" is not "safe" |
| Any non-merge command | Allowed, immediately |
The author comes from gh pr view, which uses GraphQL. Where GraphQL is refused
and REST works (Claude Code cloud sessions answer GraphQL with HTTP 403), the
hook falls back to gh api repos/OWNER/REPO/pulls/N and
gh api repos/OWNER/REPO/pulls/N/files, but only for an explicit -R/--repo
(or the MCP tool's owner/repo) and a numeric PR. Without -R, gh resolves
the repository from remotes and its default setting, which the hook does not
guess, so the merge stays denied; name the repository and retry.
A lookup that fails is reported as a failed lookup, not as an authorship
verdict (issue #3602). On an HTTP error gh api prints the error body on
stdout and exits 1, so the hook keeps a lookup's output only on exit 0. When
the viewer or author lookup fails, the denial asks gh api rate_limit (which
does not count against the limit) and, if the REST or GraphQL limit is
exhausted, names it with the reset time and says to retry after the reset.
Otherwise it quotes gh's error message. A failed viewer lookup denies only a
non-bot author: a bot PR is trusted whoever the viewer is, so it is still
allowed.
Covers every merge route: gh pr merge (in any flag order, inside a compound
command, with or without --repo), gh api ... /pulls/N/merge (and curl
on the same route), GraphQL mergePullRequest / enablePullRequestAutoMerge
mutations, and the GitHub MCP merge_pull_request tool. --admin does not
bypass it. Every merge in a command is checked, not just the first
(issue #2889): gh pr merge 5 && gh pr merge 5 -R other/repo checks both,
and the command is denied if any one is external or unverifiable.
How the arguments are read. As gh's flag parser (cobra/pflag) reads them, after the shell has removed quotes:
| Spelling | Read as |
|---|---|
-R x, --repo x, --repo=x, -Rx, -R=x, -sRx, -sR x, "-R" x, '--repo' x | repository x (the last one wins, as in gh) |
gh -R x pr merge 5, gh pr -R x merge 5 | repository x — gh accepts -R before the subcommand |
-s/--squash, -m/--merge, -r/--rebase, -d/--delete-branch | booleans, so gh pr merge -s 2231 merges 2231 |
-b/--body, -F/--body-file, -t/--subject, -A/--author-email, --match-head-commit | take a value, which is never the selector |
"gh" pr merge, g\h pr merge, /usr/bin/gh pr merge, gh pr "merge" | a merge |
Denied as unverifiable (the hook cannot know what gh will receive): an
argument holding a shell variable or command substitution ($F, "$F",
$(…), backticks; a quoted value of --body/--subject is fine), an unquoted
glob, brace or zsh extglob (-? x, {-R,x}, -@(R) x), a variable command
word in front of any merge route — $GH pr merge, $GH api …/pulls/N/merge,
$CURL -X PUT …/pulls/N/merge, and any $GH api graphql call —
xargs/parallel (they add arguments at run time), a shell
reading its script from a pipe (echo '…' | bash) or a process substitution
(bash <(…), source <(…), bash < <(…), zsh =(…)), a call to a shell
function defined in the same command (f(){ "$@"; }; f gh pr merge 5, a zsh
anonymous () { … } gh pr merge 5, or a gh() function) whose arguments hold
merge, a pulls/N/merge route, GraphQL or a --prs list — its body decides
what runs, including an extra -R — nested shell text whose
quoting leaves a literal quote or a dangling -R (bash -c "… \"-R\" x",
eval "… -R" "x"), a GraphQL merge mutation (it names the PR by node id), a
GraphQL query read from @file/--input, a variable, or stdin (a pipe, a
heredoc, a <<< herestring or a < redirection other than /dev/null), and a
REST route whose owner/repo/number is not literal (repos/$R/pulls/5/merge).
A query with a value spliced in (-f query="…\"$ID\"…") is a variable query;
the refusal points at GraphQL variables instead, a literal query with the value
passed as its own field (-f query='mutation($id:ID!){…}' -f id="$ID"), which
is checked and passes unless it merges (#3298).
Command substitutions inside double quotes and inside an unquoted heredoc
(<<EOF, where markdown backticks execute) are scanned as commands; a <<<
herestring is a plain redirection, so the lines after it are still scanned.
The rest of a heredoc body is prose: a body line such as `$GH api graphql`
under cat <<'EOF' is not a command word, and the line after the closing
delimiter is scanned as a command of its own (#3355).
MCP owner/repo/pullNumber values carrying a newline or the hook's
internal \036/\037 separators are denied.
Fails closed on its own errors. A scanner failure denies, and so does any
crash after a command is recognised as a possible merge (an EXIT trap emits the
deny). Before Claude Code 2.1.295, and on any client without onFailure: "block",
a hook error is non-blocking, so dying would let the merge run; the trap keeps
that closed on every client. The hook is kept bash-3.2 clean (no mapfile, declare -A, ${v,,}, …)
because macOS /bin/bash is 3.2.
merge-chain.sh (git-plugin). The script merges a PR list with gh calls
the hook never sees, so the hook reads the list from the invocation and checks
every PR before the script runs: merge-chain.sh --repo OWNER/REPO --prs 219,220 … is checked like gh pr merge 219 -R OWNER/REPO && gh pr merge 220 -R OWNER/REPO, and one disallowed author denies the whole command, naming that
PR. It is recognised as merge-chain.sh …, ./…/merge-chain.sh …, a quoted
path built from ${CLAUDE_PLUGIN_ROOT} or $HOME, bash|sh|zsh <path>/merge-chain.sh …, source …, behind a wrapper, or inside bash -c '…'; a mention in prose, a
quoted argument or a heredoc body is not an invocation. The arguments are read
as the script reads them: separate words, --prs comma-separated with spaces
dropped and a leading # allowed. Denied as unverifiable: no --repo or
--prs, a non-integer entry, a variable or command substitution in --prs or
--repo, an unquoted expansion or glob in any word (the script path included —
quote "$HOME/…/merge-chain.sh"), an argument the script does not accept
(--repo=x included), xargs, and a script path that is a variable or glob given
a --prs list. -h/--help is allowed. Each listed PR costs one gh pr view,
run sequentially inside the hook's 20 s timeout.
Not covered: a gh alias defined before the command (gh alias set mm 'pr merge', then gh mm 5) and any other script or binary that merges
internally (merge-chain.sh under a different file name included, a copy or
symlink of gh under another name, or a merge run from another language such
as python3 -c "os.system(…)") — the hook sees only the command text, not what
it calls. merge-chain.sh keeps its own authorship check as a second layer for
this reason (issue #3262).
Which repository the PR is looked up in. With --repo/-R, that
repository. Otherwise the repository of the hook's cwd, with one exception
(issue #2872): when the command is exactly cd <dir> && gh pr merge …, the PR
is looked up in <dir>, where the merge actually runs. Any other way the
command could change the repository gh resolves before a merge without -R
is denied as unverifiable rather than looked up in the wrong place (issue
#2889 — these used to fall back to the session cwd, which checked your own PR
while gh merged someone else's).
Before a merge with no -R | Result |
|---|---|
cd /abs/path && gh pr merge 5, also ./…, ../…, ~/… — one plain literal operand, the cd first and the merge second, joined by &&, the only merge in the command | Looked up in the cd target, if it exists and resolves to the same directory logically and physically |
Any other cd shape (cd x; gh pr merge, cd x || …, cd -P x, cd "x", cd $X, pushd, (cd x && …), bash -c 'cd x && …', a cd inside a loop), env -C, sudo -D, find -execdir, GIT_DIR/GIT_WORK_TREE, git remote/config/worktree/clone/init, gh repo set-default, a gh function or alias, source/., ssh, a redirection into a .git path, or a lone backgrounding & anywhere in the command | Denied — retry with -R OWNER/REPO as its own command |
GH_REPO set inline, exported earlier, or through an environment entry whose name is a variable | Denied — gh obeys an explicit -R over GH_REPO, so name the repo with -R |
git checkout/switch or gh pr checkout, for a merge with no PR selector | Denied — the current-branch PR the hook can see is not the one gh merges |
GH_HOST, GH_CONFIG_DIR, XDG_CONFIG_HOME or HOME set (even with -R) | Denied — gh would talk to a different host or account |
When the lookup fails and no --repo was given, the denial names the directory
it resolved the repository from and suggests retrying with -R OWNER/REPO. The
hazard scan reads the command text before the merge, so a commit message that
merely says "cd" or "remote" before an un--R merge also denies; -R resolves
it.
The command word is resolved structurally, so a merge stays a merge when it is reached through:
| Position | Example |
|---|---|
| A wrapper that runs the wrapped command — including flags taking a separate value | sudo -u ci, env -C dir, timeout, xargs, find -exec, parallel, watch, script, uv run, arch -arm64, screen -dm, zsh noglob/nocorrect, time -p, /usr/bin/time |
| A shell invoker, including heredocs fed to a shell | bash -c "…", eval "…", unquoted eval gh pr merge … (its words are joined and scanned as command text), nix-shell --run, bash <<EOF, bash -s <<'EOF' |
| Command substitution | X=`gh pr merge 2231`, $(gh pr merge 2231) |
Redirections, which bash strips before gh sees argv | gh pr merge 2>/dev/null 2231, xargs -n1 gh pr merge < prs.txt |
The counterpart narrowing: a mention of the phrase, or of the
pulls/N/merge route, is not an invocation. Prose, a quoted --body value, a
$(cat <<EOF) body, a non-shell heredoc, and an rg/grep/echo of the API
route are all allowed — the api route now requires a command word that can
actually call it (gh/curl/wget/http/xh/hurl). One narrow false
positive is accepted deliberately: unquoted prose directly behind a wrapper
(sudo echo gh pr merge 5) denies, which is fail-closed; the quoted form is
unaffected.
Does not defer to auto mode, unlike branch-protection.sh. Auto mode's classifier models destructive-git and protected-branch risk; it has no notion of PR authorship trust, so deferring would leave the gap open rather than avoid a double-gate.
The human-side counterpart lives in the ghsq/ghrb zsh wrappers (dotfiles): external PRs are hidden from the merge picker by default (ghsq -x includes them, marked ⚠) and merging one requires typing merge — never a single keypress, and never swept up by a=all.
Toggle: export CLAUDE_HOOKS_DISABLE_EXTERNAL_PR_MERGE=1 in your shell environment. Like branch protection, this is a human-operator opt-in — an inline CLAUDE_HOOKS_DISABLE_EXTERNAL_PR_MERGE=1 gh pr merge ... prefix is intentionally not honored, so agents cannot self-serve the bypass.
Tests: bash hooks-plugin/hooks/test-external-pr-merge-guard.sh (hermetic — gh is stubbed).
auto-checkpoint.sh
A PreToolUse hook that creates a git stash checkpoint before destructive operations. Opt-in since #2652: it does nothing unless CLAUDE_HOOKS_ENABLE_AUTO_CHECKPOINT=1. Every recorded instance across its issues was a false-positive stash (an rm -rf target outside the repo, git-ignored, or only quoted in a command's text) and none was a recovery. repo-deletion-safety.sh still blocks deleting a repo with unpushed work, and git's reflog covers reset and checkout.
| Trigger | Checkpoint Created |
|---|---|
git reset | Named stash with timestamp |
git checkout -- <files> | Named stash with timestamp |
git restore (non-staged) | Named stash with timestamp |
rm -rf (non-build-artifact) | Named stash with timestamp |
git clean -f | Named stash with timestamp |
Destructive command whose tree matches stash@{0} (an auto-checkpoint before … entry) | Skipped — the protecting checkpoint already holds this content (#2736) |
Skips checkpointing for build artifact removal (node_modules, dist, build, .next, etc.).
Each message ends with [worktree: <toplevel>] naming the checkout that took it (#3055). refs/stash is shared by every worktree of a repo, so git-stash-reminder.sh uses the tag to judge a worktree subagent's checkpoint against that worktree instead of the parent's checkout.
Toggle: CLAUDE_HOOKS_ENABLE_AUTO_CHECKPOINT=1 enables it (only the literal 1). The former opt-out CLAUDE_HOOKS_DISABLE_AUTO_CHECKPOINT is no longer read. git-stash-reminder.sh reports auto-checkpoint before … entries only when the same flag is set.
Tests: bash hooks-plugin/hooks/test-auto-checkpoint.sh (hermetic — fixture repos under mktemp -d).
event-logger.sh
A development hook that logs all hook events to ~/.claude/hook-events.log.
| Mode | Environment Variable | Output |
|---|---|---|
| Off (default) | — | No logging |
| Summary | CLAUDE_HOOKS_ENABLE_EVENT_LOGGER=1 | One-line per event (timestamp, event, tool, session) |
| Verbose | Above + CLAUDE_HOOKS_EVENT_LOGGER_VERBOSE=1 | Full JSON input logged |
Custom log path: CLAUDE_HOOKS_EVENT_LOG=/path/to/log
permission-auto-approve.sh
A PermissionRequest hook that auto-approves safe operations and auto-denies dangerous ones.
| Decision | Patterns |
|---|---|
| Auto-deny (checked first) | Recursive rm when its target literally spells the filesystem root or home directory (rm -rf /, rm -r -f /, rm -rf -- /, rm -Rf "$HOME"); alias spellings (~+, $PWD/..) fall to the normal prompt; force push to main/master (--force, -f, --force-with-lease, a +main refspec) — anywhere in the command |
| Auto-approve | Read-only git, test runners, linters, gh CLI reads — only when every command in the line is one of them and its arguments pass that rule's argv check |
| Pass through | Everything else (user decides) |
Approval is decided on an ast-grep --lang bash parse, not the raw string
(#2733): git status && touch x,
npm test; chmod -R 777 . and a multi-line command with an unreviewed second line all pass
through. Only plain commands joined by &&, ||, ;, |, & or newlines can be approved —
a substitution, process substitution, $VAR, subshell, group, loop, conditional, function,
redirection, heredoc, assignment prefix or comment means no decision. Without ast-grep (or if
the parse errors or takes over 5 s) the hook never approves; the deny rules still fire.
Each approved command's words are de-quoted the way bash would and checked against its rule
(#2885,
#2886). The program and subcommand
must match exactly, so pytest=1 touch x, pytestx, npx jest-evil, make test-and-deploy and
git statusfoo get no decision. A command containing { } * ? [ ] gets no decision, since bash
would expand it into words the hook never saw.
Where a rule takes an allowlist of flags, a flag outside it gets no decision however it is
spelled (git remote show --eh origin), and a value flag's value (-p v or -p=v) passes the
same path gates as a positional argument: no absolute, ~, .. or @file value
(tsc --noEmit -p /tmp/x, mypy -p /tmp/x, pytest --durations /tmp/x). That includes
pattern flags such as -t and -k, whose value is a test name rather than a path; one spelled
like an absolute path goes to the prompt.
| Rule | Approved | No decision (examples) |
|---|---|---|
git status log diff show blame shortlog describe ls-files rev-parse rev-list | Any arguments but the refused ones | --output, --ext-diff, --textconv |
git branch | Listing: no arguments, -a, -r, -v, --list, --show-current, --contains, --merged, --format, … | -d -D -m -f -c -u, --set-upstream-to, a bare name (creates a branch) |
git remote | No arguments, -v, show <name>, get-url <name> | add, set-url, remove, rename, prune, … |
Test runners (npm test, npx vitest/jest, bun test, pytest, cargo test, go test, make test) | An allowlist of common flags (-x, -k, -v, --workspace, -run, -race, --nocapture, …) and paths inside the tree | -u/--updateSnapshot, pytest -p/-c/--basetemp/@file, go test -exec/-o/-toolexec, cargo test --config/-Z/--manifest-path, npm test --script-shell, make test <target>/VAR=…/-f, an absolute, ~ or .. path |
Linters (npx eslint/prettier/biome, bun run lint/check, ruff check, mypy, tsc --noEmit) | Check-mode flags only | --fix, --write/-w, --apply, --unsafe, --install-types, --config/--config-file, --outDir, bun run format, bun run lint:fix |
gh pr view/checks/list/diff, issue view/list, run view/list | Any arguments | Any other verb (gh pr listx) |
Toggle: CLAUDE_HOOKS_DISABLE_PERMISSION_AUTO=1
Tests: bash hooks-plugin/hooks/test-permission-auto-approve.sh (needs ast-grep for the parser sections; SKIPs them otherwise).
task-completeness.sh
A Stop hook that checks for obvious signs of incomplete work using deterministic heuristics. Replaces the former type: "prompt" task-completeness hook to avoid leaking the full LLM prompt in error output (see #1009).
| Check | Trigger |
|---|---|
| TODO/FIXME/HACK/XXX added in uncommitted diff | Blocks with count and message |
Merge conflict markers (<<<<<<<, >>>>>>>) in changed files | Blocks with affected filenames |
Debugging artifacts (console.log, debugger;, breakpoint(), pdb.set_trace) added in diff | Blocks with count |
stop_hook_active=true in input | Exits 0 immediately (prevents infinite loops) |
| Non-git directory | Exits 0 silently |
Documentation files (*.md, *.mdx, *.rst, *.txt) and vendor/generated paths (node_modules, vendor, dist, build, *.min.*) are excluded from all three checks — they routinely quote literal TODO/FIXME tokens, conflict markers, and console.log examples in prose.
Toggle: CLAUDE_HOOKS_DISABLE_TASK_COMPLETENESS=1
no-calendar-estimates.sh
Details
- Marketplace
- laurigates/claude-plugins
- Source
- hooks-plugin
- Author
- Lauri Gates
- Category
- Automation
- License
- MIT
- Keywords
- hooks, automation, best-practices, workflow, anti-patterns, session-start, web, prose-style
- Listed since
- Apr 7, 2026
More from laurigates/claude-plugins
All 52- kernel-pluginv1.1.1
- kitty-pluginv2.0.0
- kubernetes-pluginv1.10.4
- langchain-pluginv1.5.10
- linux-pluginv1.1.1
- macos-pluginv2.0.1
- migration-patterns-pluginv1.7.1
- networking-pluginv1.4.3
- obsidian-pluginv1.3.8
- project-pluginv1.21.17
- prompt-engineering-pluginv1.1.4
- prose-pluginv1.4.5
- python-pluginv1.5.10
- reverse-engineering-pluginv1.1.0
- rust-pluginv1.9.1
- session-pluginv1.18.3
- software-design-pluginv1.2.0
- taskwarrior-pluginv1.16.4
- terraform-pluginv1.7.13
- testing-pluginv3.27.2
- tools-pluginv2.16.2
- typescript-pluginv1.10.4
- video-pluginv2.0.2
- workflow-orchestration-pluginv1.20.0
Similar to hooks-plugin
More Security
sc-hooksPluginkylesnowschwartz/SimpleClaude116 starsSimpleClaude hooks for auto-formatting, lint checks, and tool monitoring
hooks-developmentPlugindavepoon/buildwithclaude3.8K starsDevelopment Hooks - Event-driven automation hooks
hooks-formattingPlugindavepoon/buildwithclaude3.8K starsFormatting Hooks - Event-driven automation hooks
hookifyPluginathola/claude-night-market350 starsBehavioral rules engine: create safety hooks through markdown configuration with pattern matching and zero-code rule authoring
everything-claude-codePluginxu-xiang/everything-claude-code-zh2K starsThe most comprehensive Claude Code plugin — 14+ agents, 56+ skills, 33+ commands, and production-ready hooks for TDD, security scanning, code review, and contin
Hooks AutomationSkillspencermarx/open-code-review395 starsIntelligent hook system that coordinates, formats, and learns from Claude Code operations via MCP.