At 09:33 the coding agent has finished the six files for ORD-2187, and every check in its editing loop has passed. The developer asks it to commit. The agent runs git commit with the subject feat(orders): add delivery_note to the order API and the line Refs: ORD-2187.
Which checks run at that moment? Many teams would answer that the agent fires a "commit" event, so they write a commit check for the agent and expect it to cover people too, or they write a git hook and expect it to see what the agent is about to do. Both expectations are wrong. Each one puts a check where it either cannot see what it needs, or cannot stop what it should.
The confusion has a simple source. Two different programs are involved in that one command, git and the software that runs the agent, and each lets a team attach a script to moments of its own. The stages Code change and Commit chose where Acme's checks sit; what follows is the event-by-event detail behind those choices. Times on this page are illustrative.
Git firespre-commit. The coding agent firesPreToolUse. Neither program knows the other's events. Pick the event by asking who must be stopped, and when.
1. What runs when the agent commits#
Both programs work the same way at the surface. Each names fixed moments, such as "before a commit is created" or "before a tool call runs", and runs a script the team registered for that moment. The moment is a hook event, and the script that runs at it is a hook script, also called a handler. The program that owns the event decides when the script runs; the script does not.
So the question at 09:33 becomes: which program fires which event? The answer starts with a fact that surprises many people.
Claude Code has no event named commit or push. It has an event for every tool call the agent makes. A commit made by the agent is a shell command, so it arrives as a PreToolUse event for the shell tool, with the command text inside.
Here is the whole sequence, in order. The harness is the software that runs and controls the agent: it runs the tools the model asks for, applies permissions and fires the agent's hook events.
| Step | Who acts | Event | Can a script stop the commit here? |
|---|---|---|---|
| 1 | The model asks to run the shell command | none yet | |
| 2 | The harness, before it runs the command | PreToolUse (agent hook), with the tool name Bash and the full command text | Yes. Exit 2 cancels the command and the model reads the reason. |
| 3 | The harness starts the command; git begins | none | |
| 4 | Git, before it creates the commit | pre-commit (git hook) | Yes. Non-zero exit, no commit. |
| 5 | Git, after the message is written | commit-msg (git hook) | Yes. Non-zero exit, no commit. |
| 6 | Git, after the commit exists | post-commit (git hook) | No. The commit exists. |
| 7 | The harness, after the command returned | PostToolUse (agent hook), with the command output | No. It can only send feedback to the model. |
The same layers as a picture. Tap a box to see its script and its settings.
Diagram: Three layers at the commit · guide, guard, gate
Read left to right. The same checks appear three times on purpose. The first two layers give fast feedback and can be skipped. The third cannot, and is the only one to rely on.
- Guide · inside the agent
- Hook before shell command: Fires before the agent runs a matching command, such as a push. It can cancel the command and explain why.
- Deny rules: Settings that make the harness refuse an action: a force push, an edit to a gate file.
- Sandbox: Operating-system limits on files and network for the agent's shell, whatever the command text says.
- Guard · developer machine
- Git hook before commit: pre-commit runs the secret scan and the formatter; commit-msg checks the message. For people and scripts as well as the agent.
- Git hook before push: Runs the affected tests and the local review. A finding stops the push unless the developer overrides it; it never blocks when the review cannot run. Feedback, not a verdict.
- Gate · repository host
- Push protection: The host scans the commits in a push as it arrives and rejects the push if it contains a known secret format.
- Branch rules: No direct push to main. Required checks must pass. A pull_request workflow runs as the pull request wrote it, so code owners on the workflow files keep a pull request from rewriting its own judge.
- Code owners for gate files: A named owner must approve any change to the files that define the checks.
Three things follow from the table, and each one is a mistake teams make when they skip it.
- A person who commits in a terminal passes steps 4 to 6 only. No agent hook runs, so a check written only as an agent hook never sees that commit.
- The agent passes all seven. Git hooks run for the agent too, because git runs them, not the agent. A git hook is not "the human-only layer".
- The agent hook sees text. It recognizes a commit by matching the command text. A script that calls git internally, or an unusual spelling of the command, passes step 2 unseen. Step 4 still sees it, because git itself fires that event.
At Acme, step 2 starts no script at 09:33. Acme's only PreToolUse hook is the push guard, guard-push.sh, whose filter matches git push; the Commit page explains why. The commit is checked at steps 4 and 5: the pre-commit git hook passes, and a commit-msg script like the one below accepts the subject and the Refs: line.
2. Why the two families get confused#
The confusion is understandable, because the two families look alike in every way that is easy to see. Both are called hooks, and both can block. Both sit around the same moment: steps 2 and 4 above are a fraction of a second apart. And at Acme both are committed to the same repository, in .claude/ and .githooks/.
The differences are in what is harder to see: who fires the event, what the script receives, and who it covers. Those three decide whether a check can do its job.
| Git hooks | Agent hooks (here: Claude Code) | |
|---|---|---|
| Who fires the event | The git program | The agent harness |
| Example events | pre-commit, commit-msg, pre-push, post-commit | PreToolUse, PostToolUse, Stop, UserPromptSubmit, SessionStart, SubagentStop |
| Where the script is registered | An executable file named after the event, in .git/hooks/ or in the folder that core.hooksPath names | A hooks entry in a settings file, for example .claude/settings.json |
| What the script receives | Command-line arguments and sometimes standard input, different for each event | One JSON object on standard input that describes the event |
| How it blocks | Any non-zero exit code, on the events that can block | Exit code 2, or a JSON decision, on the events that can block |
| Who it covers | Everyone who uses git in that clone: people, scripts and agents | Only work done through that agent |
| Who can skip it | Anyone who adds --no-verify, or who never installed the hooks | Anyone who works outside the agent |
Read the last two rows together. A git hook covers everyone, and anyone can skip it. An agent hook sees the agent's intent before anything runs, and covers nobody else. Neither covers everyone without a way around it; that is the job of the server, and the Commit page builds the three layers from this fact.
Other coding agents have their own hook systems with other event names. The git column is the same for all of them.
3. Choosing the event: who must be stopped, and when#
With the two families apart, choosing an event becomes a short question about the check itself. What must it see: the staged files, the message, the whole batch of commits, the agent's next command, the file it just edited? And what must it stop, if anything? The table answers that for the common jobs, and says why the neighboring event is the wrong choice.
| The job | The right event | Why not the neighbor |
|---|---|---|
| Format or lint the files in this commit | pre-commit | pre-push would report it ten commits late. |
| Check the commit message format | commit-msg | pre-commit runs before the message exists. |
| Test the whole batch once before it leaves the machine | pre-push | pre-commit would run it on every commit, and people would start skipping it. |
| Log or notify after a commit | post-commit | It cannot block, so no check belongs here. |
| Stop the agent before a risky command | PreToolUse | A git hook only sees git commands. |
| Check a file right after the agent edits it | PostToolUse | pre-commit is later; the agent has built more on the mistake. |
| Keep the agent working until the tests pass | Stop | PostToolUse after every edit is too early; code is often broken mid-change. |
| Add context to a prompt, or refuse one | UserPromptSubmit | SessionStart runs once and does not see the prompt. |
| Load the state of the repository when a session starts | SessionStart | UserPromptSubmit would repeat it on every prompt. |
| Check a helper agent's report before it returns | SubagentStop | Stop is for the main agent only. |
| Anything that must never be skipped | None of these. A required check and a branch rule on the server. | Every event on this page runs on a machine its user controls. |
The last row matters most. Every event above gives fast feedback to someone who can choose to ignore it, so none of them is a control. They earn their place by catching mistakes minutes or hours before the server would.
The rest of this page is reference. Each event below opens to show its facts, one script, ten more uses, and when it is the wrong place. Before each script, one sentence says what it demonstrates and what a passing run does and does not prove.
4. Git hook events#
These are the git side of the morning: pre-commit and commit-msg at 09:33, pre-push at 09:34 when the ship skill pushes the branch. The scripts are short on purpose. Each shows the input its event provides and the one rule that event imposes, so a team can put its own checks in the same place.
Shared by a team through one folder in the repository: git config core.hooksPath .githooks, run once per clone. Git ignores a hook file that is not executable. All four scripts below were run in a scratch git repository: each blocking case and each passing case.
pre-commitGit · before each commit is created · can block
| Fires when | git commit starts, before the message editor opens |
| Receives | No arguments. The script asks git what is staged. |
| Blocks | Yes. Any non-zero exit: no commit is created. |
| Skipped by | git commit --no-verify |
| Time budget | A few seconds. It runs on every commit. |
| Check | The staged content, not the working folder. The two can differ. |
Example: stop a secret or a merge-conflict marker from entering history.
The script demonstrates the rule every pre-commit check must follow: read what is staged, because that is what the commit will hold. A pass proves that the added lines match neither of two key patterns and that no conflict marker or whitespace error is staged. It does not prove the commit is free of secrets: two patterns are not a secret scanner, and a team's real scanner belongs at this same spot.
#!/usr/bin/env bash
# .githooks/pre-commit: git runs this before it creates each commit.
# No arguments. A non-zero exit means: no commit.
set -euo pipefail
staged=$(git diff --cached --name-only --diff-filter=ACM)
[ -z "$staged" ] && exit 0 # nothing added or changed
# 1. A private key or a cloud access key in the lines being added
if git diff --cached -U0 | grep -E '^\+' \
| grep -Eq 'BEGIN [A-Z ]*PRIVATE KEY|AKIA[0-9A-Z]{16}'; then
echo "pre-commit: a secret is in the staged changes. Remove it and commit again." >&2
exit 1
fi
# 2. Conflict markers or whitespace errors left in a staged file
if ! git diff --cached --check >/dev/null; then
echo "pre-commit: conflict markers or whitespace errors. See: git diff --cached --check" >&2
exit 1
fi
exit 0
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Format staged files | Runs the formatter in check mode on the staged file list; fails with the command to fix them. |
| 2 | Lint staged files only | Passes the staged list to the linter, so the run stays short on a large repository. |
| 3 | Refuse large files | Reads each staged file's size with git cat-file -s and fails above a limit such as 5 MB. |
| 4 | No commits on the main branch | Reads the branch with git symbolic-ref --short HEAD and fails when it is main. |
| 5 | Debug leftovers | Searches the added lines for debugger, console.log( or pdb.set_trace. |
| 6 | Broken data files | Parses each staged .json and .yaml file and fails on the first one that does not parse. |
| 7 | Gate files | Prints a warning when a staged path is a gate file, such as a CI workflow or the code owners file. The owner approval itself is a server rule. |
| 8 | Lock file out of step | Fails when the dependency manifest is staged and its lock file is not. |
| 9 | Migration naming | Checks that a new file in db/migrations/ follows the timestamp name pattern. |
| 10 | Stale generated file | Runs the generator and fails when its output differs from the staged copy. |
Wrong place when: the check needs more than a few seconds (move it to pre-push), needs the commit message (commit-msg), or must not be skippable (server).
commit-msgGit · after the message is written · can block and can edit the message
| Fires when | The message is ready, before the commit is created |
| Receives | One argument: the path of a file that holds the message |
| Blocks | Yes. Non-zero exit: no commit. The script may also change the file. |
| Skipped by | git commit --no-verify |
| Time budget | Under one second. It reads one small file. |
Example: require a typed subject line and a work-item reference.
The script checks the two things the 09:33 commit carries: a typed subject, feat(orders): add delivery_note to the order API, and the line Refs: ORD-2187. A pass proves the message has that shape. It does not prove the work item exists or matches the change; only a lookup in the tracker could.
#!/usr/bin/env bash
# .githooks/commit-msg: git passes one argument, the file that holds the message.
set -euo pipefail
msg_file="$1"
subject=$(grep -v '^#' "$msg_file" | head -n 1)
# Merge and revert commits write their own subject. Let them pass.
case "$subject" in "Merge "*|"Revert "*) exit 0 ;; esac
if ! printf '%s' "$subject" \
| grep -Eq '^(feat|fix|docs|refactor|test|chore)(\([a-z0-9-]+\))?: .{1,72}$'; then
echo "commit-msg: write the subject like feat(orders): add delivery_note to the order API" >&2
exit 1
fi
if ! grep -Eq '^Refs: [A-Z]+-[0-9]+$' "$msg_file"; then
echo "commit-msg: add a work-item line, for example Refs: ORD-2187" >&2
exit 1
fi
exit 0
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Subject length | Fails when the first line is longer than 72 characters. |
| 2 | Blank second line | Fails when the body starts directly under the subject. |
| 3 | Work item from the branch name | For teams whose branch names carry the id, such as feat/ORD-2187-delivery-note, reads it and adds the line with git interpret-trailers --in-place. |
| 4 | Sign-off line | Fails when no Signed-off-by: line is present, for projects that require one. |
| 5 | Agent trailer | Adds a trailer that names the coding agent when an environment variable shows the agent made the commit, so agent volume can be measured later. |
| 6 | Secrets in the message | Searches the message for key patterns, the same way the pre-commit example searches the diff. |
| 7 | Body required for features | Fails a feat commit that has a subject and no body. |
| 8 | Breaking-change footer | Fails a subject marked with ! that has no BREAKING CHANGE: footer. |
| 9 | Internal addresses | Fails when the message contains an internal host name or a link to a private tracker, for repositories that are public. |
| 10 | Docs-only exception | Lets a docs commit pass with no work-item line, and applies the rule to every other type. |
Wrong place when: the check is about file content (pre-commit). And a different event, prepare-commit-msg, is the place to pre-fill a message before the person edits it.
pre-pushGit · once per push, however many commits · can block
| Fires when | git push has contacted the remote, before any commit is sent |
| Receives | Two arguments: remote name and remote address. Standard input: one line per branch being pushed, with the local and remote commit ids. |
| Blocks | Yes. Non-zero exit: nothing is pushed. |
| Skipped by | git push --no-verify |
| Time budget | Tens of seconds, up to a few minutes. It runs once for the whole batch. |
Example: refuse a direct push to main, then test what changed across all the commits in the push.
The script demonstrates two things: reading git's list of pushed branches from standard input, and handing the changed files to the shared selector tools/affected-tests.sh. The Stop hook and CI call the same selector, so the three layers cannot disagree about which tests a change affects. At 09:34 this step passed for #4812 with 14 tests. A pass proves the selected tests pass on the pushed commits; it does not prove the selector chose every test that matters, which is why CI's affected-tests check is not required and nightly-full runs everything.
#!/usr/bin/env bash
# .githooks/pre-push: git runs this once per push.
# Arguments: <remote name> <remote address>
# Standard input, one line per branch: <local ref> <local id> <remote ref> <remote id>
set -euo pipefail
zero=0000000000000000000000000000000000000000
while read -r local_ref local_id remote_ref remote_id; do
[ "$local_id" = "$zero" ] && continue # deleting a branch: nothing to test
if [ "$remote_ref" = "refs/heads/main" ]; then
echo "pre-push: no direct push to main. Open a pull request." >&2
exit 1
fi
if [ "$remote_id" = "$zero" ]; then # a new branch: compare with main
base=$(git merge-base origin/main "$local_id")
else # an existing branch: only the new commits
base="$remote_id"
fi
changed=$(git diff --name-only "$base" "$local_id")
[ -z "$changed" ] && continue
echo "pre-push: testing the files changed in ${base:0:8}..${local_id:0:8}" >&2
if ! ./tools/affected-tests.sh $changed </dev/null; then
echo "pre-push: affected tests failed. Nothing was pushed." >&2
exit 1
fi
done
# Acme's hook then runs the local review of the branch (use 8 below).
exit 0
The </dev/null matters: standard input still holds git's list, and the selector must not read it.
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Type check the project | Runs the type checker once, on the pushed commit. |
| 2 | Build | Runs the build and fails the push when it fails. |
| 3 | Unfinished commits | Lists the subjects in the range and fails on WIP, fixup! or squash!. |
| 4 | Forced push to a shared branch | Uses git merge-base --is-ancestor to see whether the remote commit is still in the history; fails when it is not. |
| 5 | Secrets across the whole range | Scans every commit in the push, not only the last one. A secret removed in a later commit is still in history. |
| 6 | Branch name pattern | Fails when the branch name does not match the team pattern. |
| 7 | Far behind main | Counts the commits on main that the branch lacks and warns above a limit. |
| 8 | Local agent review | Runs a headless review of the branch with --agent code-reviewer, the same reviewer CI runs, and prints the findings. When the review cannot run, it says so and lets the push go. A finding blocks the push unless the developer pushes again with an override and a reason. Feedback only: it proves nothing to the server. Acme's version is on Pull request. |
| 9 | Dependency audit | Runs the audit only when the lock file is among the changed files. |
| 10 | Oversized change | Counts changed files and lines and asks the author to split a very large push. |
Wrong place when: the check takes long enough that people add --no-verify out of habit. Then it belongs in CI, where it cannot be skipped and does not hold a person's terminal.
post-commitGit · after the commit exists · cannot block
| Fires when | The commit has been created |
| Receives | No arguments. The new commit is HEAD. |
| Blocks | No. Git ignores the exit code. |
| Skipped by | Nothing to skip; it cannot stop anything |
| Use it for | Records and notices, never checks |
Example: keep a local record of each commit and whether an agent co-wrote it.
The script demonstrates the one thing this event is for: a record written after the fact. Its exit code changes nothing, so a run proves only that the record line was written, never that the commit was good.
#!/usr/bin/env bash
# .githooks/post-commit: git runs this after the commit exists.
# Its exit code changes nothing.
id=$(git rev-parse --short HEAD)
files=$(git diff-tree --root --no-commit-id --name-only -r HEAD | wc -l | tr -d ' ')
by_agent=no
git log -1 --format=%B | grep -q '^Co-Authored-By: ' && by_agent=yes
printf '%s\t%s\t%s files\tagent=%s\n' "$(date -u +%FT%TZ)" "$id" "$files" "$by_agent" \
>> "$(git rev-parse --git-dir)/commit-record.tsv"
exit 0
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Desktop notice | Shows a notice with the commit id, useful after a long commit by an agent. |
| 2 | Reminder to push | Counts unpushed commits and prints a reminder above a limit. |
| 3 | Background test run | Starts the affected tests in the background and writes the result to a file. |
| 4 | Review lane hint | Prints a line when the commit touched a path that will need its owner's review. |
| 5 | Refresh a code index | Rebuilds the local symbol index used by the editor. |
| 6 | Drop a stale local review | Deletes a saved local review result, because the code it described has changed. |
| 7 | Change log reminder | Prints a reminder when source files changed and the change log did not. |
| 8 | Time between commits | Appends the time since the previous commit to a local file, to see the size of work steps. |
| 9 | Preview refresh | Regenerates a local documentation preview. |
| 10 | Team notice from a shared branch | Posts the subject line to a chat channel when the commit is on a release branch. |
Wrong place when: the result should stop anything. A check here reports a problem after it is already recorded.
Other git eventsFour more that teams use
| Event | Fires when | Common use | Blocks |
|---|---|---|---|
prepare-commit-msg | Before the message editor opens | Pre-fill the message, for example with the work-item id from the branch name. Not skipped by --no-verify. | Yes |
post-checkout and post-merge | After a branch switch, and after a merge or pull | Reinstall dependencies when the lock file changed | No |
pre-rebase | Before a rebase starts | Refuse to rebase a branch that is already shared | Yes |
pre-receive | On the server, before it accepts a push | A server-side hook that the person pushing cannot skip, like update. It exists on self-managed git servers. Hosted platforms offer branch rules and push rules in its place. | Yes |
5. Agent hook events (Claude Code)#
These are the agent side. Three of the six carry Acme's editing loop and push guard: PostToolUse caught the unused variable at 09:16, Stop sent the agent back at 09:29 and let it finish at 09:31, and PreToolUse ran the push guard at 09:34. Why those checks sit at those moments is the subject of Code change; this section gives the facts and the scripts.
Each script reads one JSON object from standard input. On the events that can block, exit code 2 blocks and the text on standard error becomes the reason. Exit code 0 passes. Every script below was run with sample event JSON in a scratch git repository. Claude Code lists more than thirty events; these six carry most of the work in a delivery pipeline.
PreToolUseAgent · before any tool call runs · can block
| Fires when | The model has asked for a tool call and the harness has not run it yet |
| Receives | tool_name and tool_input. For the shell tool, tool_input.command is the full command text. |
| Blocks | Yes. Exit 2 cancels the call; the model reads the reason and can correct itself. |
| Narrowed by | matcher (the tool name) and if (one permission-style pattern, checked before the script starts) |
| Limit | It matches command text. Hard rules belong in deny rules, a sandbox and the server. |
Acme's only PreToolUse hook is the push guard, guard-push.sh, filtered on git push; its settings are on Commit. The example below is a different one, a hook a team may add. Acme does not run it, which is why no agent hook script started at 09:33.
Example (a hook a team may add): before the agent commits, refuse a commit on main and a commit that includes gate files. This is the agent-side partner of the pre-commit git hook.
It demonstrates how an agent hook reads its context from the event JSON and cancels a command with exit 2, so the model reads the reason and corrects itself. A pass proves only that, at the moment the command was about to run, the branch was not main and no staged path was a gate file. It does not stop a person, and it does not see files the command stages by itself.
{
"hooks": {
"PreToolUse": [{
"matcher": "Bash",
"hooks": [{ "type": "command", "if": "Bash(git commit *)",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/guard-commit.sh",
"timeout": 30 }]
}]
}
}
#!/usr/bin/env bash
# .claude/hooks/guard-commit.sh: the harness runs this before the agent's commit command.
# Standard input: the event as JSON. Exit 2 = cancel the command; standard error goes to the model.
set -euo pipefail
input=$(cat)
cd "$(jq -r '.cwd' <<<"$input")"
# The if filter is best-effort and can start this script for other commands. Allow them.
cmd=$(jq -r '.tool_input.command // empty' <<<"$input")
case "$cmd" in *"git commit"*) ;; *) exit 0 ;; esac
branch=$(git symbolic-ref --short HEAD 2>/dev/null || echo detached)
if [ "$branch" = "main" ]; then
echo "Do not commit on main. Create a branch first: git switch -c <name>" >&2
exit 2
fi
# Gate files: they decide how other changes are judged or what an agent may do.
gate='^(\.github/|\.claude/|\.githooks/|agents/|ci/|CODEOWNERS$|CLAUDE\.md$|\.mcp\.json$)'
staged_gate=$(git diff --cached --name-only | grep -E "$gate" || true)
if [ -n "$staged_gate" ]; then
echo "These staged files are gate files and need their owner: $staged_gate" >&2
echo "Unstage them with git restore --staged <file>, then commit the rest." >&2
exit 2
fi
exit 0
The pattern lists every gate file in the series: .github/, .claude/, .githooks/, agents/, ci/, CODEOWNERS, CLAUDE.md and .mcp.json. The script reads what is staged at that moment. A commit command that stages files itself (the -a option) adds files after this check. The pre-commit git hook and the server rule cover that case.
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Skipping git hooks | Cancels any commit or push command that contains --no-verify, so the agent cannot switch off the git layer. |
| 2 | Push to a protected branch | Reads the target branch from the push command and cancels a push to main or a release branch. Acme's guard-push.sh does this. |
| 3 | Edits to secret files | With the matcher set to the edit and write tools, cancels a change to .env or a key file by checking tool_input.file_path. |
| 4 | Ask before a migration | Returns the decision ask for an edit under db/migrations/, so a person confirms it. |
| 5 | Delete outside the project | Cancels a recursive delete whose target is not inside the project folder. |
| 6 | Download and run | Cancels a command that pipes a download straight into a shell. |
| 7 | New dependency | Asks a person before an install command adds a package that is not in the lock file. |
| 8 | Production commands | Cancels infrastructure commands that change live systems when the current context is production. |
| 9 | One tool of a connected server | Cancels a single tool of a connected tool server, for example the one that merges pull requests, and leaves the read tools open. |
| 10 | Pull request before tests | Cancels the command that opens a pull request when no record of a passing test run exists for the current commit. |
Wrong place when: the rule must hold for people too (git hook, server), or must hold whatever the command text looks like (sandbox, server).
PostToolUseAgent · after a tool call succeeded · cannot undo, can send feedback
| Fires when | A tool call has finished successfully |
| Receives | tool_name, tool_input and tool_response (what the tool returned) |
| Blocks | No. The tool already ran. The script can tell the model what to fix next. |
| Narrowed by | matcher and if, the same as PreToolUse |
| Time budget | Seconds. With an edit matcher it runs after every edit. |
Example: after each edit, lint the one file that changed and tell the model about errors.
This is Acme's after-edit hook, the one that caught the unused variable at 09:16. For a Python file it runs ruff check on that one file, and for a failure it returns the same reason text the model read that morning. A pass proves the edited file is clean under the project's ruff rules; it does not prove the edit is correct, or that the files that call it still work.
{
"hooks": {
"PostToolUse": [{
"matcher": "Edit|Write",
"hooks": [{ "type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/check-changed-file.sh",
"timeout": 20 }]
}]
}
}
#!/usr/bin/env bash
# .claude/hooks/check-changed-file.sh: the harness runs this after each successful edit.
# It cannot undo the edit. It returns JSON that tells the model what to fix.
set -u
input=$(cat)
cwd=$(jq -r '.cwd' <<<"$input")
cd "$cwd" || exit 0
file=$(jq -r '.tool_input.file_path // empty' <<<"$input")
file=${file#"$cwd"/} # report the path relative to the project
[ -n "$file" ] && [ -f "$file" ] || exit 0 # nothing to check
case "$file" in
*.py) what="Lint" # one line per error, no fix hints
out=$(ruff check --output-format concise --no-unsafe-fixes "$file" 2>&1) && exit 0 ;;
*.sh) what="Syntax check"
out=$(bash -n "$file" 2>&1) && exit 0 ;;
*.json) what="JSON parse"
out=$(jq empty "$file" 2>&1) && exit 0 ;;
*) exit 0 ;;
esac
# Not clean. Exit 0 with a JSON decision, so the harness applies it.
jq -n --arg reason "$what failed on $file. Fix these lines, change nothing else:
$out" '{decision: "block", reason: $reason}'
exit 0
Run in the scratch repository against a handler with the same unused variable on line 27, it printed the decision below, the same one shown on Code change. On a clean file it prints nothing and exits 0.
{
"decision": "block",
"reason": "Lint failed on services/orders/handlers/create_order.py. Fix these lines, change nothing else:\nservices/orders/handlers/create_order.py:27:5: F841 Local variable `note` is assigned to but never used\nFound 1 error."
}
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Format after edit | Formats the changed file and says nothing, so layout never costs the model a turn. |
| 2 | Type check one file | Runs the type checker on the changed file and returns the first errors. |
| 3 | Run the matching test file | Finds the test file that belongs to the changed source file and runs only that. |
| 4 | Remember what changed | Appends the file path to a list that the Stop hook reads later. |
| 5 | Owner path notice | Adds context for the model when the edited path will need its owner's review. |
| 6 | Shorten long output | After a test command, replaces thousands of lines of output with the failures and a count. |
| 7 | Audit record | Appends every tool call, with its time, to a local record. Runs in the background. |
| 8 | Migration check | After a write under db/migrations/, runs the migration linter and returns its findings. |
| 9 | API contract check | After an edit to the API description, compares it with the main branch and reports a breaking change. |
| 10 | Secret just written | Searches the written content for key patterns and tells the model to remove them at once. |
Wrong place when: you need to prevent the action (PreToolUse), or the check is slow and only matters at the end (Stop).
StopAgent · when the agent is about to end its turn · can send it back to work
| Fires when | The model has finished and is about to hand back to the person. Not on a person's interrupt; an API error fires StopFailure instead. |
| Receives | stop_hook_active (true when the agent is already continuing because a stop hook sent it back) and last_assistant_message |
| Blocks | Yes. Exit 2 keeps the agent working, with the reason. |
| Narrowed by | Nothing. It has no matcher; it runs on every stop. |
| Limit | Guard against loops with stop_hook_active. Claude Code also ends the turn after 8 send-backs in a row; the count resets when the agent calls a tool, and CLAUDE_CODE_STOP_HOOK_BLOCK_CAP raises the cap. |
Example: the agent may not finish while the type check or the tests for its changed files fail.
This is Acme's stop hook. It runs pyright on each service the change touched, then hands the changed files to the shared selector tools/affected-tests.sh, the same one the pre-push hook calls. If either fails, it sends the agent back once. If they still fail after that one send-back in the same turn, it lets the agent stop and records why in .claude/stop-gate.log, so a flaky or wrong test cannot hold the agent in a loop and a person decides.
At 09:29 it sent the agent back with 1 failed, 13 passed; at 09:31 the 14 selected tests passed and the agent stopped. A pass proves the touched services type check and the selected tests pass. It does not prove the selector chose every test that matters, or that another service still works with the change.
{
"hooks": {
"Stop": [{
"hooks": [{ "type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/affected-tests.sh",
"timeout": 180 }]
}]
}
}
#!/usr/bin/env bash
# .claude/hooks/affected-tests.sh: the harness runs this when the agent is about to stop.
# Exit 2 = keep working; standard error becomes the reason the model reads.
set -u
input=$(cat)
cd "$(jq -r '.cwd' <<<"$input")" || exit 0
changed=$(git diff --name-only HEAD; git ls-files --others --exclude-standard)
[ -n "$changed" ] || exit 0 # nothing changed: the turn may end
services=$(printf '%s\n' $changed | grep -oE '^services/[^/]+' | sort -u)
# 1. Type check each service the change touched. 2. The shared selector runs the affected tests.
if out=$( {
for svc in $services; do
echo "affected-tests.sh: pyright $svc"
pyright "$svc" || exit 1
done
./tools/affected-tests.sh $changed </dev/null
} 2>&1 ); then
exit 0 # green: the turn may end
fi
# Already sent back once in this turn and still red: let it stop and record why,
# so a flaky or wrong test cannot hold the agent in a loop. A person decides.
if [ "$(jq -r '.stop_hook_active // false' <<<"$input")" = "true" ]; then
{ echo "$(date -u +%FT%TZ) still failing after one send-back"; tail -n 5 <<<"$out"; } \
>> .claude/stop-gate.log
exit 0
fi
echo "Type check or affected tests fail. Fix the code, not the tests, then finish." >&2
tail -n 25 <<<"$out" >&2
exit 2
The script splits file names on spaces, which is enough for a repository whose paths have none. In the scratch run, a stand-in selector played the part of tools/affected-tests.sh; the three outcomes behaved as described: exit 0 when green, exit 2 with the failure on the first red, and exit 0 with a log line when stop_hook_active was true.
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Whole-change lint | Lints every changed file once, at the end, where a per-edit lint would be too noisy. |
| 2 | Type check with dependents | Type checks the changed files and the files that import them. |
| 3 | Debug leftovers | Sends the agent back when the diff still contains debug statements. |
| 4 | Unfinished task list | Reads the task file and sends the agent back when items are still open. |
| 5 | Evidence in the final message | Reads last_assistant_message and requires the test command and its result to be named. |
| 6 | Docs follow the API | Sends the agent back when a public API file changed and its documentation did not. |
| 7 | Scope | Sends the agent back when files outside the task's folders changed. |
| 8 | Generated files | Runs the generator and sends the agent back when the output is stale. |
| 9 | Hand-over note | Writes a short summary of the session to a file. Never blocks. |
| 10 | Finished notice | Sends a desktop or chat notice that the agent is done. Never blocks. |
Wrong place when: the check should stop one specific action (PreToolUse), or the answer is needed after each edit (PostToolUse). And it is not a gate: a person can interrupt, and the agent can be run without hooks.
UserPromptSubmitAgent · when a person sends a prompt · can block it or add context
| Fires when | A prompt is submitted, before the model sees it |
| Receives | prompt (the text the person typed) |
| Blocks | Yes. Exit 2 stops the prompt; it never reaches the model. |
| Adds context | Plain text on standard output is added for the model, next to the prompt |
| Narrowed by | Nothing. It has no matcher. Keep it fast; it runs on every prompt. |
Example: refuse a prompt that contains a credential; otherwise add the state of the repository.
It demonstrates the event's two outputs: a block that keeps a prompt from the model, and plain text that becomes context. A pass proves the prompt matched neither key pattern. It does not keep a pasted secret off the disk, as the note after the script explains.
{
"hooks": {
"UserPromptSubmit": [{
"hooks": [{ "type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/screen-prompt.sh" }]
}]
}
}
#!/usr/bin/env bash
# .claude/hooks/screen-prompt.sh: the harness runs this when a person sends a prompt.
# Exit 2 = the prompt is not sent. Text on standard output is added as context.
set -u
input=$(cat)
prompt=$(jq -r '.prompt // empty' <<<"$input")
if grep -Eq 'AKIA[0-9A-Z]{16}|BEGIN [A-Z ]*PRIVATE KEY' <<<"$prompt"; then
echo "Your prompt contains what looks like a credential. It was not sent." >&2
echo "Remove it, or give the path of a file that holds it." >&2
exit 2
fi
cd "$(jq -r '.cwd' <<<"$input")" || exit 0
branch=$(git symbolic-ref --short HEAD 2>/dev/null || echo detached)
dirty=$(git status --porcelain 2>/dev/null | wc -l | tr -d ' ')
echo "Repository state: branch $branch, $dirty uncommitted files."
exit 0
The block keeps the prompt from the model, not off the disk. By default the block message, with the prompt text, is written to the local session transcript. suppressOriginalPrompt in the JSON output leaves the text out of that message; the transcript and the prompt history can still hold it.
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Work-item text | When the prompt names an id such as ORD-2187, fetches the title and acceptance criteria and adds them. |
| 2 | Path rules on mention | When the prompt mentions payments or sign-in, adds the rule that those paths need an owner. |
| 3 | Prompt record | Appends the prompt and time to a local audit record. |
| 4 | Failing build context | When the prompt says to fix the build, adds the summary of the failing CI job for the current branch. |
| 5 | Team shorthand | Expands team terms into their full meaning before the model reads them. |
| 6 | Risky instruction | Stops a prompt that says to skip tests or checks, and explains the team rule. |
| 7 | Huge paste | Stops a prompt above a size limit and asks for a file path, to keep a pasted log out of the context. |
| 8 | Date and on-call | Adds today's date and the current on-call owner for the affected service. |
| 9 | Session title | Sets the session title from the first prompt, so sessions are easy to find later. |
| 10 | Repository not approved | Stops every prompt in a repository where agent use is not permitted, with a pointer to the policy. |
Wrong place when: the context is the same for the whole session (SessionStart, or the project instruction file), or the concern is what the agent does, which a prompt check cannot see.
SessionStartAgent · when a session begins or resumes · cannot block, adds context
| Fires when | A session starts, resumes, is cleared or forked, or restarts after its context was compacted |
| Receives | source: startup, resume, clear, compact or fork |
| Blocks | No. |
| Adds context | Plain text on standard output is added before the first prompt |
| Narrowed by | matcher on the source value |
| Extra | Lines written to the file named by CLAUDE_ENV_FILE become environment variables for the agent's later shell commands |
Example: tell the agent where it is and which paths need an owner.
It demonstrates the event's two channels: text that becomes context, and CLAUDE_ENV_FILE for environment variables. It cannot fail a session; a run proves only that the agent starts with these facts in view, not that it will respect them. The red paths and gate files it lists are Acme's.
{
"hooks": {
"SessionStart": [{
"matcher": "startup|resume|compact",
"hooks": [{ "type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/session-context.sh" }]
}]
}
}
#!/usr/bin/env bash
# .claude/hooks/session-context.sh: the harness runs this when a session begins.
# It cannot block. Text on standard output becomes context for the model.
set -u
input=$(cat)
cd "$(jq -r '.cwd' <<<"$input")" || exit 0
echo "Repository state at session start:"
echo "- Branch: $(git symbolic-ref --short HEAD 2>/dev/null || echo detached)"
echo "- Last commit: $(git log -1 --format='%h %s' 2>/dev/null || echo none)"
echo "- Paths that need their owner's review: services/auth/, services/payments/, db/migrations/, api/openapi/, infra/"
echo "- Gate files: .github/, .claude/, .githooks/, agents/, ci/, CODEOWNERS, CLAUDE.md, .mcp.json"
# Make project tools available to the agent's later shell commands.
if [ -n "${CLAUDE_ENV_FILE:-}" ]; then
echo 'export PATH="$PATH:./node_modules/.bin"' >> "$CLAUDE_ENV_FILE"
fi
exit 0
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Open work item | Reads the id from the branch name and adds the work item's text. |
| 2 | Rules after compaction | With the matcher compact, adds the few rules that must survive a shortened context. |
| 3 | On the main branch | Adds a warning when the session starts on main, before any edit happens. |
| 4 | Behind main | Adds how many commits the branch is behind, so the agent rebases first. |
| 5 | Branch build status | Adds whether the last CI run on this branch passed. |
| 6 | Tool versions | Checks the language and tool versions the project needs and reports a mismatch. |
| 7 | Environment variables | Writes the variables the project needs to CLAUDE_ENV_FILE. |
| 8 | Changes since last session | Lists the files that changed since the previous session ended. |
| 9 | Session title | Sets the session title from the branch name. |
| 10 | Dependencies out of date | Compares the lock file with the installed packages and says so when they differ. |
Wrong place when: the text never changes (put it in the project instruction file), or the work is slow. This event runs on every session start.
SubagentStopAgent · when a helper agent is about to return · can send it back to work
| Fires when | A subagent (a helper agent started by the main agent for one task) is about to return its report |
| Receives | agent_type, last_assistant_message (the text of the subagent's final response) and stop_hook_active |
| Blocks | Yes. Exit 2 keeps the subagent working, with the reason. |
| Narrowed by | matcher on the agent type |
| Use it for | The shape and the evidence of a report, before the main agent builds on it |
Example: a review subagent must end its report with a verdict line that a script can read.
It demonstrates checking the shape of a report before the main agent builds on it, and asking only once (stop_hook_active). A pass proves the report ends with a readable verdict line. It says nothing about whether the verdict is right.
{
"hooks": {
"SubagentStop": [{
"hooks": [{ "type": "command",
"command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/review-verdict.sh" }]
}]
}
}
#!/usr/bin/env bash
# .claude/hooks/review-verdict.sh: the harness runs this when a subagent is about to return.
# Exit 2 = the subagent keeps working; standard error is the reason it reads.
set -u
input=$(cat)
[ "$(jq -r '.stop_hook_active // false' <<<"$input")" = "true" ] && exit 0 # asked once already
[ "$(jq -r '.agent_type // empty' <<<"$input")" = "code-reviewer" ] || exit 0 # other helpers pass
report=$(jq -r '.last_assistant_message // empty' <<<"$input")
if ! grep -Eq '^VERDICT: (pass|changes-needed)$' <<<"$report"; then
echo "End your report with one line: VERDICT: pass or VERDICT: changes-needed" >&2
exit 2
fi
exit 0
The script checks the agent type itself, so it can be registered without a matcher; a matcher of code-reviewer would do the same before the script starts. One version note: on Claude Code v2.1.271 or later, a subagent that hands back with the SubagentHandback tool, which Claude Code provides in auto mode, delivers its report through that tool, and last_assistant_message then holds only its closing text. For such a subagent, check the report on that tool call with a PreToolUse or PostToolUse hook instead.
Ten more uses for this event
| # | Scenario | What the script does |
|---|---|---|
| 1 | Findings cite a location | Sends a reviewer back when a finding has no file and line. |
| 2 | Verifier result | Requires a verifier to end with supported, refuted or inconclusive. |
| 3 | What was not checked | Requires a section that lists what the helper did not look at. |
| 4 | Empty report | Sends back a report that is empty or only says it is done. |
| 5 | Report size | Sends back a search helper that returned whole files where a summary was asked. |
| 6 | Tests were run | For a test-writing helper, runs the new tests and sends it back when they fail. |
| 7 | Stayed in its folder | Sends a helper back when it changed files outside the folder it was given. |
| 8 | Duration record | Records the helper's type and run time. Never blocks. |
| 9 | Transcript for audit | Saves the path of the helper's transcript next to the pull request record. Never blocks. |
| 10 | Severity order | Requires findings ordered by severity, most serious first. |
Wrong place when: the check is about the main agent's final result (Stop), or about a pull request on the server, where a report from a developer machine proves nothing.
Other agent eventsFive more worth knowing
| Event | Fires when | Common use | Blocks |
|---|---|---|---|
PostToolUseFailure | A tool call failed | Add a hint for a known failure, such as a missing tool | No |
PermissionRequest | The harness is about to ask a person for permission | Answer routine requests by rule, so people see fewer prompts | By a JSON decision |
Notification | The agent needs attention | Send a desktop or chat notice | No |
PreCompact | Before the context is shortened | Give instructions for the summary, or save notes that must survive | Yes |
SessionEnd | The session ends | Write a record; clean up temporary files | No |
6. Questions readers ask#
| Question | Short answer |
|---|---|
| Can the agent skip a git hook? | Yes, with --no-verify, the same as a person. Cancel that option with a PreToolUse hook and a deny rule, and rely on the server for the real check. |
| Should one check live in two places? | Often, yes. Keep one script in the repository and call it from the git hook, the agent hook and the CI job, as Acme does with tools/affected-tests.sh. Then the three layers cannot disagree. |
| Do git hooks run in CI? | Only if the job installs them (a fresh clone has none active) and then runs a git command that fires one, which is rare. In CI, call the same script as a job step. |
| A hook is slow. Now what? | Move it one layer later: pre-commit to pre-push, pre-push to CI. A slow local hook trains people to skip it. |
| Why did my hook not run? | For git: the file is not executable, has the wrong name, or core.hooksPath points elsewhere. For the agent: the matcher or the if pattern did not match, or the agent was started with hooks off. |
| Is any hook on this page a security control? | No. Each one is early feedback on a machine its user controls. The control is on the server: required checks, branch rules and owner approval. |
At 09:33 two programs had the chance to check #4812's commit, and only git checked it. The harness fired PreToolUse for the command, but Acme registers no script for a commit, and git fires its events for everyone who runs it, agent or person.
That is the model to keep: an event belongs to the program that fires it, and a script there sees only what that program sees and stops only what that program does. Pick the event by asking who must be stopped, and when. Anything that must never be skipped belongs on the server.
Next: every term used across the stages, defined in one place, in the Glossary.