All chapters
  1. Start hereOne change, from diff to production
  2. Before stage 1The team setup: what changes when you are not alone
  3. Stage 1Code change: catch it while the agent is still editing
  4. Stage 2Commit: what must be true before a commit exists
  5. Stage 3Pull request: arrive already reviewed, with evidence
  6. Stage 4Review: who reviews what, at hundreds a day
  7. Stage 5CI/CD: spend scarce capacity like a budget
  8. Deep diveCI/CD agents: where they live and how they run
  9. Deep diveBuild the agents: pinpoint the change, then fix it
  10. Stage 6When the change is an agent
  11. OperateVolume and cost: what breaks at 300 a day
  12. AdoptAdopt it in steps
  13. ReferenceHook events: which one, with a script for each
  14. ReferenceGlossary
  15. AboutAbout this site
Reference

Hook events: which one, with a script for each

Git fires some hook events and the coding agent fires others. Who fires each one, what it can stop, one tested script for each, and ten more uses.

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 fires pre-commit. The coding agent fires PreToolUse. 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.

StepWho actsEventCan a script stop the commit here?
1The model asks to run the shell commandnone yet
2The harness, before it runs the commandPreToolUse (agent hook), with the tool name Bash and the full command textYes. Exit 2 cancels the command and the model reads the reason.
3The harness starts the command; git beginsnone
4Git, before it creates the commitpre-commit (git hook)Yes. Non-zero exit, no commit.
5Git, after the message is writtencommit-msg (git hook)Yes. Non-zero exit, no commit.
6Git, after the commit existspost-commit (git hook)No. The commit exists.
7The harness, after the command returnedPostToolUse (agent hook), with the command outputNo. 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.

  1. Guide · inside the agent
    1. Hook before shell command: Fires before the agent runs a matching command, such as a push. It can cancel the command and explain why.
    2. Deny rules: Settings that make the harness refuse an action: a force push, an edit to a gate file.
    3. Sandbox: Operating-system limits on files and network for the agent's shell, whatever the command text says.
  2. Guard · developer machine
    1. 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.
    2. 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.
  3. Gate · repository host
    1. Push protection: The host scans the commits in a push as it arrives and rejects the push if it contains a known secret format.
    2. 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.
    3. 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.

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 hooksAgent hooks (here: Claude Code)
Who fires the eventThe git programThe agent harness
Example eventspre-commit, commit-msg, pre-push, post-commitPreToolUse, PostToolUse, Stop, UserPromptSubmit, SessionStart, SubagentStop
Where the script is registeredAn executable file named after the event, in .git/hooks/ or in the folder that core.hooksPath namesA hooks entry in a settings file, for example .claude/settings.json
What the script receivesCommand-line arguments and sometimes standard input, different for each eventOne JSON object on standard input that describes the event
How it blocksAny non-zero exit code, on the events that can blockExit code 2, or a JSON decision, on the events that can block
Who it coversEveryone who uses git in that clone: people, scripts and agentsOnly work done through that agent
Who can skip itAnyone who adds --no-verify, or who never installed the hooksAnyone 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 jobThe right eventWhy not the neighbor
Format or lint the files in this commitpre-commitpre-push would report it ten commits late.
Check the commit message formatcommit-msgpre-commit runs before the message exists.
Test the whole batch once before it leaves the machinepre-pushpre-commit would run it on every commit, and people would start skipping it.
Log or notify after a commitpost-commitIt cannot block, so no check belongs here.
Stop the agent before a risky commandPreToolUseA git hook only sees git commands.
Check a file right after the agent edits itPostToolUsepre-commit is later; the agent has built more on the mistake.
Keep the agent working until the tests passStopPostToolUse after every edit is too early; code is often broken mid-change.
Add context to a prompt, or refuse oneUserPromptSubmitSessionStart runs once and does not see the prompt.
Load the state of the repository when a session startsSessionStartUserPromptSubmit would repeat it on every prompt.
Check a helper agent's report before it returnsSubagentStopStop is for the main agent only.
Anything that must never be skippedNone 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 whengit commit starts, before the message editor opens
ReceivesNo arguments. The script asks git what is staged.
BlocksYes. Any non-zero exit: no commit is created.
Skipped bygit commit --no-verify
Time budgetA few seconds. It runs on every commit.
CheckThe 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

#ScenarioWhat the script does
1Format staged filesRuns the formatter in check mode on the staged file list; fails with the command to fix them.
2Lint staged files onlyPasses the staged list to the linter, so the run stays short on a large repository.
3Refuse large filesReads each staged file's size with git cat-file -s and fails above a limit such as 5 MB.
4No commits on the main branchReads the branch with git symbolic-ref --short HEAD and fails when it is main.
5Debug leftoversSearches the added lines for debugger, console.log( or pdb.set_trace.
6Broken data filesParses each staged .json and .yaml file and fails on the first one that does not parse.
7Gate filesPrints 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.
8Lock file out of stepFails when the dependency manifest is staged and its lock file is not.
9Migration namingChecks that a new file in db/migrations/ follows the timestamp name pattern.
10Stale generated fileRuns 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 whenThe message is ready, before the commit is created
ReceivesOne argument: the path of a file that holds the message
BlocksYes. Non-zero exit: no commit. The script may also change the file.
Skipped bygit commit --no-verify
Time budgetUnder 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

#ScenarioWhat the script does
1Subject lengthFails when the first line is longer than 72 characters.
2Blank second lineFails when the body starts directly under the subject.
3Work item from the branch nameFor 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.
4Sign-off lineFails when no Signed-off-by: line is present, for projects that require one.
5Agent trailerAdds a trailer that names the coding agent when an environment variable shows the agent made the commit, so agent volume can be measured later.
6Secrets in the messageSearches the message for key patterns, the same way the pre-commit example searches the diff.
7Body required for featuresFails a feat commit that has a subject and no body.
8Breaking-change footerFails a subject marked with ! that has no BREAKING CHANGE: footer.
9Internal addressesFails when the message contains an internal host name or a link to a private tracker, for repositories that are public.
10Docs-only exceptionLets 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 whengit push has contacted the remote, before any commit is sent
ReceivesTwo arguments: remote name and remote address. Standard input: one line per branch being pushed, with the local and remote commit ids.
BlocksYes. Non-zero exit: nothing is pushed.
Skipped bygit push --no-verify
Time budgetTens 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

#ScenarioWhat the script does
1Type check the projectRuns the type checker once, on the pushed commit.
2BuildRuns the build and fails the push when it fails.
3Unfinished commitsLists the subjects in the range and fails on WIP, fixup! or squash!.
4Forced push to a shared branchUses git merge-base --is-ancestor to see whether the remote commit is still in the history; fails when it is not.
5Secrets across the whole rangeScans every commit in the push, not only the last one. A secret removed in a later commit is still in history.
6Branch name patternFails when the branch name does not match the team pattern.
7Far behind mainCounts the commits on main that the branch lacks and warns above a limit.
8Local agent reviewRuns 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.
9Dependency auditRuns the audit only when the lock file is among the changed files.
10Oversized changeCounts 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 whenThe commit has been created
ReceivesNo arguments. The new commit is HEAD.
BlocksNo. Git ignores the exit code.
Skipped byNothing to skip; it cannot stop anything
Use it forRecords 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

#ScenarioWhat the script does
1Desktop noticeShows a notice with the commit id, useful after a long commit by an agent.
2Reminder to pushCounts unpushed commits and prints a reminder above a limit.
3Background test runStarts the affected tests in the background and writes the result to a file.
4Review lane hintPrints a line when the commit touched a path that will need its owner's review.
5Refresh a code indexRebuilds the local symbol index used by the editor.
6Drop a stale local reviewDeletes a saved local review result, because the code it described has changed.
7Change log reminderPrints a reminder when source files changed and the change log did not.
8Time between commitsAppends the time since the previous commit to a local file, to see the size of work steps.
9Preview refreshRegenerates a local documentation preview.
10Team notice from a shared branchPosts 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
EventFires whenCommon useBlocks
prepare-commit-msgBefore the message editor opensPre-fill the message, for example with the work-item id from the branch name. Not skipped by --no-verify.Yes
post-checkout and post-mergeAfter a branch switch, and after a merge or pullReinstall dependencies when the lock file changedNo
pre-rebaseBefore a rebase startsRefuse to rebase a branch that is already sharedYes
pre-receiveOn the server, before it accepts a pushA 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 whenThe model has asked for a tool call and the harness has not run it yet
Receivestool_name and tool_input. For the shell tool, tool_input.command is the full command text.
BlocksYes. Exit 2 cancels the call; the model reads the reason and can correct itself.
Narrowed bymatcher (the tool name) and if (one permission-style pattern, checked before the script starts)
LimitIt 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

#ScenarioWhat the script does
1Skipping git hooksCancels any commit or push command that contains --no-verify, so the agent cannot switch off the git layer.
2Push to a protected branchReads the target branch from the push command and cancels a push to main or a release branch. Acme's guard-push.sh does this.
3Edits to secret filesWith the matcher set to the edit and write tools, cancels a change to .env or a key file by checking tool_input.file_path.
4Ask before a migrationReturns the decision ask for an edit under db/migrations/, so a person confirms it.
5Delete outside the projectCancels a recursive delete whose target is not inside the project folder.
6Download and runCancels a command that pipes a download straight into a shell.
7New dependencyAsks a person before an install command adds a package that is not in the lock file.
8Production commandsCancels infrastructure commands that change live systems when the current context is production.
9One tool of a connected serverCancels a single tool of a connected tool server, for example the one that merges pull requests, and leaves the read tools open.
10Pull request before testsCancels 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 whenA tool call has finished successfully
Receivestool_name, tool_input and tool_response (what the tool returned)
BlocksNo. The tool already ran. The script can tell the model what to fix next.
Narrowed bymatcher and if, the same as PreToolUse
Time budgetSeconds. 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

#ScenarioWhat the script does
1Format after editFormats the changed file and says nothing, so layout never costs the model a turn.
2Type check one fileRuns the type checker on the changed file and returns the first errors.
3Run the matching test fileFinds the test file that belongs to the changed source file and runs only that.
4Remember what changedAppends the file path to a list that the Stop hook reads later.
5Owner path noticeAdds context for the model when the edited path will need its owner's review.
6Shorten long outputAfter a test command, replaces thousands of lines of output with the failures and a count.
7Audit recordAppends every tool call, with its time, to a local record. Runs in the background.
8Migration checkAfter a write under db/migrations/, runs the migration linter and returns its findings.
9API contract checkAfter an edit to the API description, compares it with the main branch and reports a breaking change.
10Secret just writtenSearches 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 whenThe model has finished and is about to hand back to the person. Not on a person's interrupt; an API error fires StopFailure instead.
Receivesstop_hook_active (true when the agent is already continuing because a stop hook sent it back) and last_assistant_message
BlocksYes. Exit 2 keeps the agent working, with the reason.
Narrowed byNothing. It has no matcher; it runs on every stop.
LimitGuard 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

#ScenarioWhat the script does
1Whole-change lintLints every changed file once, at the end, where a per-edit lint would be too noisy.
2Type check with dependentsType checks the changed files and the files that import them.
3Debug leftoversSends the agent back when the diff still contains debug statements.
4Unfinished task listReads the task file and sends the agent back when items are still open.
5Evidence in the final messageReads last_assistant_message and requires the test command and its result to be named.
6Docs follow the APISends the agent back when a public API file changed and its documentation did not.
7ScopeSends the agent back when files outside the task's folders changed.
8Generated filesRuns the generator and sends the agent back when the output is stale.
9Hand-over noteWrites a short summary of the session to a file. Never blocks.
10Finished noticeSends 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 whenA prompt is submitted, before the model sees it
Receivesprompt (the text the person typed)
BlocksYes. Exit 2 stops the prompt; it never reaches the model.
Adds contextPlain text on standard output is added for the model, next to the prompt
Narrowed byNothing. 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

#ScenarioWhat the script does
1Work-item textWhen the prompt names an id such as ORD-2187, fetches the title and acceptance criteria and adds them.
2Path rules on mentionWhen the prompt mentions payments or sign-in, adds the rule that those paths need an owner.
3Prompt recordAppends the prompt and time to a local audit record.
4Failing build contextWhen the prompt says to fix the build, adds the summary of the failing CI job for the current branch.
5Team shorthandExpands team terms into their full meaning before the model reads them.
6Risky instructionStops a prompt that says to skip tests or checks, and explains the team rule.
7Huge pasteStops a prompt above a size limit and asks for a file path, to keep a pasted log out of the context.
8Date and on-callAdds today's date and the current on-call owner for the affected service.
9Session titleSets the session title from the first prompt, so sessions are easy to find later.
10Repository not approvedStops 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 whenA session starts, resumes, is cleared or forked, or restarts after its context was compacted
Receivessource: startup, resume, clear, compact or fork
BlocksNo.
Adds contextPlain text on standard output is added before the first prompt
Narrowed bymatcher on the source value
ExtraLines 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

#ScenarioWhat the script does
1Open work itemReads the id from the branch name and adds the work item's text.
2Rules after compactionWith the matcher compact, adds the few rules that must survive a shortened context.
3On the main branchAdds a warning when the session starts on main, before any edit happens.
4Behind mainAdds how many commits the branch is behind, so the agent rebases first.
5Branch build statusAdds whether the last CI run on this branch passed.
6Tool versionsChecks the language and tool versions the project needs and reports a mismatch.
7Environment variablesWrites the variables the project needs to CLAUDE_ENV_FILE.
8Changes since last sessionLists the files that changed since the previous session ended.
9Session titleSets the session title from the branch name.
10Dependencies out of dateCompares 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 whenA subagent (a helper agent started by the main agent for one task) is about to return its report
Receivesagent_type, last_assistant_message (the text of the subagent's final response) and stop_hook_active
BlocksYes. Exit 2 keeps the subagent working, with the reason.
Narrowed bymatcher on the agent type
Use it forThe 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

#ScenarioWhat the script does
1Findings cite a locationSends a reviewer back when a finding has no file and line.
2Verifier resultRequires a verifier to end with supported, refuted or inconclusive.
3What was not checkedRequires a section that lists what the helper did not look at.
4Empty reportSends back a report that is empty or only says it is done.
5Report sizeSends back a search helper that returned whole files where a summary was asked.
6Tests were runFor a test-writing helper, runs the new tests and sends it back when they fail.
7Stayed in its folderSends a helper back when it changed files outside the folder it was given.
8Duration recordRecords the helper's type and run time. Never blocks.
9Transcript for auditSaves the path of the helper's transcript next to the pull request record. Never blocks.
10Severity orderRequires 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
EventFires whenCommon useBlocks
PostToolUseFailureA tool call failedAdd a hint for a known failure, such as a missing toolNo
PermissionRequestThe harness is about to ask a person for permissionAnswer routine requests by rule, so people see fewer promptsBy a JSON decision
NotificationThe agent needs attentionSend a desktop or chat noticeNo
PreCompactBefore the context is shortenedGive instructions for the summary, or save notes that must surviveYes
SessionEndThe session endsWrite a record; clean up temporary filesNo

6. Questions readers ask#

QuestionShort 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.