By the end of this page your repo has two hooks that stop the agent from writing to protected files and from pushing to main, and you know how to see that they run on your teammates' machines. Claude Code's memory docs describe CLAUDE.md as "context, not enforced configuration", and for an action that has to stop whatever Claude decides, they recommend a PreToolUse hook (Memory). A hook is a script Claude Code runs by itself at a given event (in the glossary), and PreToolUse is the event that comes right before a tool call.

The Bash(git push *) rule in the permission list guide doesn't catch the form git -C . push origin main, and the second hook here closes that gap. The command and setting names come from Claude Code's hooks guide.

Which file a hook sits in

WhereWho it reaches
~/.claude/settings.jsonOnly you, not shared
.claude/settings.jsonThe team, once committed to the repo
.claude/settings.local.jsonOnly you, not shared
Managed policy settingsThe whole organization
hooks/hooks.json inside a pluginEveryone who installs the plugin
Skill or subagent frontmatterEveryone who gets that file

Write the team rule into .claude/settings.json. A hook under ~/.claude runs only on your machine, and when it changes nobody sees it in a PR.

Write the protected file hook into the repo

The example in the hooks guide stops the agent from writing to .env, package-lock.json and files under .git/. Claude Code passes the details of the call to the script as JSON on stdin, and the script pulls the path of the file to be edited out of it with jq. The script below is the same as the example in the docs, except the loop is split across lines. The line after the FILE_PATH assignment turns the backslashes in Windows paths into forward slashes. Save it as .claude/hooks/protect-files.sh.

#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}"
PROTECTED_PATTERNS=(".env" "package-lock.json" ".git/")

for pattern in "${PROTECTED_PATTERNS[@]}"
do
  if [[ "$FILE_PATH" == *"$pattern"* ]]
  then
    echo "Blocked: $FILE_PATH matches protected pattern '$pattern'" >&2
    exit 2
  fi
done

exit 0

The script doesn't count itself or the settings file among the protected files, so as it stands the agent can edit the script that blocks it. My suggestion is to add .claude/hooks/ and .claude/settings.json to the pattern list. The hook only sees the Edit and Write tools, so it doesn't stop an agent that writes to the same .env file with a Bash command. That path needs a separate hook tied to Bash.

The example assumes a machine with jq installed. On a machine without jq the path comes back empty, no pattern matches, and the script quits with exit 0 without showing an error and protects no file.

Stop pushes to main with a Bash hook

The docs say a hook's if filter works on a best-effort basis for Bash commands, and for a firm allow or deny they point to the permission system (Hooks guide). The permission rule misses the git -C . push form too (Example settings files). Tie the hook to the Bash matcher and don't leave the decision to the if field. Let the script read the command text.

The PreToolUse example in the "Hook output" section of the docs gets the command with jq -r '.tool_input.command', searches it with grep and exits with exit 2 on a match. The script below has the same skeleton. Its scope is the same as the deny rules in the permission list guide, pushing to main and force pushing. The regex is my suggestion. Save it as .claude/hooks/block-main-push.sh.

#!/bin/bash
if ! command -v jq >/dev/null
then
  echo "Blocked: jq is not installed" >&2
  exit 2
fi

INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // empty')
PATTERN='(^|[^[:alnum:]_-])git([[:space:]]+[^[:space:]]+)*[[:space:]]+push([[:space:]]+[^[:space:]]+)*[[:space:]]+([^[:space:]]*:)?(main|-f|--force[^[:space:]]*)([[:space:]]|$)'

if printf '%s' "$COMMAND" | grep -Eq "$PATTERN"
then
  echo "Blocked: push to main or force push" >&2
  exit 2
fi

exit 0

A script that looks only at the first words of the command misses the git -C . push form the same way the deny rule does. Unlike the protected file example, the first block also stops the call when jq is missing, so a machine without it gives itself away on the first Bash command.

In a test with macOS grep, git push origin main, git -C . push origin main, git push origin HEAD:main, git -C . push --force origin feat and git push -f were stopped, and git push origin feat/x went through. git log --grep push main is stopped too, which is a known false positive. It doesn't catch a command built from a variable, a git alias, a push inside another script, or a bare git push with no arguments while you're on main. Keep the deny rules in place for that reason and add the hook as a second layer. For a limit that doesn't depend on the command text, see the sandbox in the permission list guide.

Make both scripts executable.

chmod +x .claude/hooks/protect-files.sh
chmod +x .claude/hooks/block-main-push.sh

Then wire both into .claude/settings.json in the same PreToolUse list.

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh"
          }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-main-push.sh"
          }
        ]
      }
    ]
  }
}

Two ways to block

Both scripts above use the exit 2 path, and the basics are in the commands guide. The one detail that isn't there is that exit codes other than 0 and 2 don't block the call for most events, so a script that returns 1 because of its own error doesn't stop the agent.

The second path is JSON. The script writes a hookSpecificOutput object to stdout, with the permissionDecision field set to "deny" and the reason in permissionDecisionReason. Use only one of the two paths in a hook. If you write permissionDecision outside hookSpecificOutput, at the top level, the JSON is read without an error, but the field is silently ignored, so the hook looks like it's working and blocks nothing.

A hook runs before the permission mode

PreToolUse runs before any permission mode, so a hook's deny decision holds in bypassPermissions mode too, and in a session opened with --dangerously-skip-permissions. There's one exception. If there are no managed settings on the machine and the session doesn't use the /login sign-in of a Team or Enterprise plan, a mod, meaning a plugin that registers a function hook inside Claude Code's own process, can approve a call the hook blocked. A session opened with an API key or with a long-lived CLAUDE_CODE_OAUTH_TOKEN counts as not using that sign-in (permissions).

Commit the hook and know what happens on first open

Commit the scripts and .claude/settings.json in the same PR, so that if someone later takes a pattern off the list, that shows up in the diff too. The docs say hooks run "with your full user permissions" and ask that you read and test them before adding them (security considerations). Before you merge a PR that touches anything under .claude/hooks/, read the script line by line.

Before it runs a hook from a settings file, Claude Code checks whether the folder is trusted. In an interactive session, the hooks in every settings file, ~/.claude/settings.json included, wait until the trust dialog is accepted. A teammate who opens the repo for the first time should type /hooks after approving and see the hooks under PreToolUse.

In a session opened with claude -p or the Agent SDK, this dialog never appears and the folder counts as trusted (permissions). The committed hooks of a repo cloned in CI run in a folder nobody marked as trusted, which is why the rule about reading the script applies in CI too.

Who can turn a hook off

Settings are read from highest to lowest in this order, managed, command line (--settings), local project, shared project and user (Settings). For disableAllHooks, the value that comes out on top in this order applies. If the repo's .claude/settings.json says "disableAllHooks": false, a true a teammate writes into their own user settings can't override it. From the same order I conclude that if the same person writes true into .claude/settings.local.json or passes it with --settings, the shared false gets overridden, because both sit above the shared project file.

So a hook in the repo doesn't count as a limit against a teammate's own decision. A managed hook, on the other hand, can only be turned off by disableAllHooks at the managed level. If you want a rule a person can't turn off even on their own machine, it belongs in the managed settings.

Managed hooks and plugin hooks

For what the managed settings are, see the guide on managing MCP servers for a team.

allowManagedHooksOnly works only in the managed settings file. When it's on, the hooks of the user, the project, the local file and plugins don't run. The only exception is the hooks of plugins force-enabled with enabledPlugins in the managed settings. In that case the /hooks menu shows this line.

Only hooks from managed settings run here

In an organization that turns this setting on, neither of the two scripts you committed to the repo runs. Move the team's rule into the managed settings, or into a plugin enabled in the managed settings.

Test the hook

Once it's set up, ask the agent to add a comment line to the .env file. If the hook works, the edit doesn't happen and the agent sees the reason starting with Blocked:. Have every teammate try this once on their own machine. On a machine missing jq the edit goes through, and the problem shows up on the first try.

Test the Bash hook in a scratch repo by telling the agent to run git -C . push origin main, and watch the call stop. Don't test it in the real repo. If the hook has a bug, the push really goes out.

If the hook is loaded but its decision doesn't take effect, send the log to a file and search that file for the line Hook JSON output had unrecognized keys. The field the JSON ignored shows up there.

claude --debug-file ./claude-debug.txt

From here

The list of actions the hook should stop comes out role by role in the permission list guide, so fill in the table there first. A PostToolUse example and the basics of blocking with exit 2 are in the Claude Code commands guide. The team test asks whether it's clear on your team what the agent can touch.

The TeamHandbook plugin applies the policies written to your team's repo in every teammate's session through a PreToolUse hook. In an organization with allowManagedHooksOnly on, that plugin also has to be enabled with enabledPlugins in the managed settings, or the policies don't hold on that machine. The details are in TeamHandbook's security document.