Lesson 41 of 45 · Track 4: Automate and code with AI

Claude Code hooks and permissions: rules an AI agent cannot ignore

Intermediate15 min6 steps2 videosFree · no login
The short answer

A rule in CLAUDE.md is a request the model can skip. Permission rules and hooks are enforced by Claude Code itself: deny, ask and allow rules in .claude/settings.json decide which tool calls run, and a hook is your own script that runs at a set moment, such as before every edit, and can block the call by exiting with code 2. Use them for the few things that must never happen, like reading .env or pushing to main.

Start a free mock interviewOut loud, with a voice interviewer · by Tough Tongue AI
  1. 1

    Why isn’t a rule in CLAUDE.md enough?

    In July 2025 a Replit coding agent deleted SaaStr founder Jason Lemkin’s production database during a code freeze. Days earlier, in a LinkedIn video quoted by The Register, he said he had told the agent “eleven times in ALL CAPS” not to make up data, and it did anyway. After the deletion he wrote: “There is no way to enforce a code freeze in vibe coding apps like Replit.” Replit’s CEO, quoted by Fortune, called it “Unacceptable and should never be possible”.

    Anthropic’s Claude Code docs draw the line that would have helped. “Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.” Permission rules work the same way: “Permission rules are enforced by Claude Code, not by the model.” Anthropic’s tip: “Use hooks for actions that must happen every time with zero exceptions.”

    4 ways to give Claude Code a rule · Anthropic docs · checked 25 Nov 2026
    Only permission rules, hooks and the sandbox are enforced; CLAUDE.md is advice
    LayerWho enforces itCan the model skip it?Best for
    CLAUDE.md or promptNobody: the model reads itYesGuidelines, commands, team habits
    Permission ruleClaude CodeNoWhich tools, commands, files and sites are allowed
    Hook (command type)Claude Code runs your scriptNoChecks a pattern can’t express; formatting after edits
    SandboxThe operating systemNoStopping scripts that open files or the network themselves
    3 options comparedSwipe →
    Hooks here means command hooks (scripts). A prompt hook is a “single-turn LLM evaluation”, so its answer can vary like any model’s.Source: Claude Code docs: best practices, Claude Code docs: permissions, Claude Code docs: hooks guide, The Register: Replit agent deleted a production database (21 Jul 2025), Fortune: AI coding tool Replit wiped a database (23 Jul 2025) · 25 Nov 2026
    Key idea

    Keep “usually” in CLAUDE.md. Turn every “never” into a deny rule or a hook.

  2. 2

    How does Claude Code decide whether a tool call runs?

    Every time the agent wants to run a command, read or edit a file, or fetch a page, Claude Code checks in a fixed order. PreToolUse hooks run first. Then the rules: “deny, then ask, then allow. The first match in that order determines the outcome.” If no rule matches, the permission mode decides.

    Two consequences surprise people. First, “an allow rule can’t carve an exception out of a deny rule”, and if a tool is denied in any settings file, no other file can allow it. Second, Claude Code’s approval table says file reads inside the working directory need no approval. So unless you deny it, Claude can read your .env without asking.

    • default (shown as Manual): asks the first time each tool is used.
    • acceptEdits: accepts file edits and mkdir, touch, rm, rmdir, mv, cp and sed inside the working directory. Yes, rm: add an ask rule if that worries you.
    • plan: reads and explores but doesn’t edit your source files.
    • auto: a background classifier checks actions against your request. With Claude Code v2.1.283 or later it is the built-in starting mode for terminal and VS Code sessions, where available. Anthropic: it “does not guarantee safety.”
    • dontAsk: denies anything that would prompt. bypassPermissions: skips prompts; Anthropic says use it only in containers or VMs. Set in a project’s .claude/settings.json, bypassPermissions and auto don’t take effect.
    1. Agent wants a tool
    2. PreToolUse hooks (exit 2 = blocked)
    3. Deny rules
    4. Ask rules
    5. Allow rules
    6. Permission mode
    Key idea

    Deny beats everything. Ask beats allow. Allow beats the mode.

  3. 3

    How do you write a permission rule?

    Rules live in .claude/settings.json (shared with your team), .claude/settings.local.json (just you) or ~/.claude/settings.json (all your projects), as allow, ask and deny lists. Each rule is a tool name, optionally with a pattern in brackets: Bash(npm run build), Read(./.env), WebFetch(domain:example.com). Type /permissions to see every rule and the file it came from.

    The details matter. In Bash rules, the space before a trailing * counts: Bash(ls *) matches ls and ls -la but not lsof; Bash(ls*) matches lsof too. Claude Code also splits chained commands on &&, ||, ;, | and &: an allow rule must match every part, while a deny or ask rule applies if any part matches.

    • File paths: //path is absolute, ~/path is from your home folder, /path is from the project the settings file belongs to, and ./path is from the current folder. A bare name like .env (no slash) matches at any depth, so Read(.env) also covers config/.env; Read(./.env) covers only the top folder.
    • Only Edit(path) and Read(path) are checked for files. A Write(path) rule is accepted but never matches; write Edit(path) instead.
    • A bare tool name in deny, like "WebFetch", removes the tool so Claude never sees it.
    • MCP tools: mcp__github__* (every tool on a server) or mcp__github__create_issue (one tool), with no brackets.
    • Rules combine across files: managed settings beat the command line, which beats settings.local.json, then settings.json, then your user file. A deny anywhere can’t be allowed elsewhere.
    • Know the limits. A Read deny also covers cat, head, tail, sed and tee in Bash, but not a Python or Node script that opens the file itself, and a Bash deny matches command text, not the program (git -C . push is not git push). For OS-level limits, Anthropic points to the sandbox.
    Anthropic’s settings example: run lint and tests freely, never read .env
    {
      "permissions": {
        "allow": ["Bash(npm run lint)", "Bash(npm run test *)"],
        "deny": ["Read(./.env)", "Read(./.env.*)"]
      }
    }
  4. 4

    What is a hook, and when do you need one?

    A hook is a shell command Claude Code runs at a set moment in its loop. Anthropic’s definition: hooks give “deterministic control: certain actions always happen rather than relying on the LLM to choose to run them.” You add them under "hooks" in the same settings files, pick an event, and use a matcher like "Edit|Write" to choose which tools trigger it.

    Your script gets the call as JSON on stdin (session_id, tool_name, tool_input). Exit 0 means no objection, and for PreToolUse the normal permission check still applies. Exit 2 blocks the action and sends what you wrote to stderr back to Claude as feedback. A PreToolUse hook that denies “blocks the tool even in bypassPermissions mode”.

    • PreToolUse: before a tool runs. The hook that stops a tool call before it happens.
    • PostToolUse: after a tool succeeds. Good for formatters and checks; it “can’t undo actions since the tool has already executed.”
    • Stop: when Claude finishes. Anthropic uses it as a gate that blocks the turn from ending until your check passes.
    • SessionStart, UserPromptSubmit and Notification: load context, check a prompt, or ping you when Claude needs input.
    • Hooks run with your full user permissions, so read any hook before you add it, especially one in a repo you didn’t write.
    Instead of exit 2, a PreToolUse hook can print JSON with a reason (Anthropic’s example)
    {
      "hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "deny",
        "permissionDecisionReason": "Use rg instead of grep for better performance"
      }
    }
    Worked workflow

    Worked workflow: wire up Anthropic’s protect-files hook

    Input

    A project where Claude must never edit .env, package-lock.json or anything in .git/, in any mode.

    1. Save the script as .claude/hooks/protect-files.sh

      Anthropic’s example from the hooks guide (shortened). It reads the call from stdin, pulls out the file path with jq, and exits 2 on a match.

      #!/bin/bash
      # protect-files.sh
      
      INPUT=$(cat)
      FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
      
      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
    2. Make it runnable

      The script needs execute permission, and jq must be installed (brew install jq, or apt install jq).

      chmod +x .claude/hooks/protect-files.sh
    3. Register it on PreToolUse in .claude/settings.json

      The matcher picks the tools; the quotes around $CLAUDE_PROJECT_DIR keep paths with spaces working.

      {
        "hooks": {
          "PreToolUse": [
            {
              "matcher": "Edit|Write",
              "hooks": [
                { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-files.sh" }
              ]
            }
          ]
        }
      }
    4. Test it by hand before trusting it

      Feed it a fake call. It should print the Blocked line and exit with 2.

      echo '{"tool_name":"Edit","tool_input":{"file_path":".env"}}' | .claude/hooks/protect-files.sh; echo "exit: $?"
    5. Check Claude Code loaded it

      Type /hooks in Claude Code. The menu is read-only; edit the JSON to change anything.

    Output

    The next time Claude tries to edit .env, the call is blocked before it runs and Claude sees “Blocked: .env matches protected pattern”, so it can choose another way.

    Key idea

    Reach for a permission rule first. Write a hook only when a pattern can’t express the check.

  5. 5

    Worked example: locking down a project in six changes

    jobtrack is a fictional Next.js job tracker. Its settings file looked productive: no prompts at all. We ran it through the tester on this page with 8 things an agent might try, 6 of them risky.

    Worked workflow

    Worked workflow: from “never asks” to “asks only when it matters”

    Input

    A .claude/settings.json with defaultMode bypassPermissions, allow "Bash" and "Edit", one deny rule written as Write(prisma/migrations/**), and a protect-files hook on PostToolUse. Tester: 6 of 6 risky calls run with no check; 0 of 7 file checks pass.

    1. Remove the bypass line

      In a project file Claude Code ignores bypassPermissions and starts in Manual mode, so the line only misled the team. The real hole was the next one. defaultMode becomes acceptEdits.

    2. Swap “allow everything” for the commands you run

      "Bash" approved every shell command. It becomes five exact commands, so tests and lint still run without a prompt.

      "allow": ["Bash(pnpm test *)", "Bash(pnpm lint)", "Bash(pnpm typecheck)", "Bash(git status)", "Bash(git diff *)"]
    3. Fix the rule that never matched

      Write(prisma/migrations/**) was ignored, because Claude Code checks files against Edit and Read rules only. It becomes Edit(prisma/migrations/**).

    4. Deny the secrets and the disasters

      Reads inside the project need no approval, so .env was open. Bare names cover every folder, so config/.env.production is caught too. Then rm -rf and force-push.

      "deny": ["Read(.env)", "Read(.env.*)", "Edit(prisma/migrations/**)", "Bash(rm -rf *)", "Bash(git push --force *)"]
    5. Make pushes and deletes ask

      Bash(git push *) and Bash(rm *) go in ask (acceptEdits would otherwise run rm inside the project). Ask applies when any part of a chain matches, so “pnpm test && git push origin main” now stops for you.

    6. Move the guard hook to PreToolUse

      On PostToolUse the script could only complain after the edit. On PreToolUse its exit 2 blocks the edit. The path is quoted, and a Prettier hook stays on PostToolUse, where formatting belongs.

    Output

    Tester: 0 of 6 risky calls run unchecked (5 blocked, 1 asks you), tests and edits still run without prompts, and 6 of 6 file checks pass. Load both files in the tester below to see each decision.

    8 test calls, 6 risky · computed by the tester on this page · 25 Nov 2026
    With no settings file, Claude Code still reads .env unprompted: 2 of 6 risky calls run
    • Risky file (allow Bash + Edit)6 of 6
    • No settings file (Manual mode)2 of 6
    • Fixed file (this workflow)0 of 6
    Risky calls: reading .env, reading config/.env.production, rewriting a migration, test-then-push, force-push, rm -rf. With no file, the two reads run because reads inside the project need no approval; the rest prompt. In auto mode the two reads still run and a classifier, not a rule, decides the other four.Source: Claude Code docs: permissions · 25 Nov 2026
    View as table
    ItemValueNote
    Risky file (allow Bash + Edit)6 of 6
    No settings file (Manual mode)2 of 6
    Fixed file (this workflow)0 of 6
  6. 6

    Do other coding agents have hooks and permissions?

    Yes, and the ideas carry over. Cursor, GitHub Copilot and Gemini CLI now have hooks with a “before a tool runs” event that can block. OpenAI Codex controls the same risk with approval policies and a sandbox; its approvals page doesn’t mention hooks. Each tool names things differently, so check its own docs before you copy a config.

    5 coding agents · each tool’s docs · checked 25 Nov 2026
    Four of five have hooks that can stop a tool call; Codex relies on approvals and a sandbox
    ToolHooksWhere you configure itBlock before a tool runs
    Claude CodeYes.claude/settings.jsonPreToolUse: exit 2 or "deny"
    CursorYes.cursor/hooks.jsonpreToolUse, beforeShellExecution
    GitHub CopilotYes.github/hooks/*.jsonpreToolUse can approve or deny
    Gemini CLIYes.gemini/settings.jsonBeforeTool: exit 2 aborts it
    OpenAI CodexNo value~/.codex/config.tomlApproval policy + sandbox mode
    3 options comparedSwipe →
    A dash means the page we read doesn’t mention hooks, not that they can’t exist.Source: Claude Code docs: hooks guide, Cursor docs: hooks, GitHub docs: hooks for Copilot agents, Gemini CLI docs: hooks, OpenAI Codex: approvals and security · 25 Nov 2026
    Key idea

    Whatever the tool: write the never-do list as rules, and use a hook for the checks rules can’t express.

From the people who built it

Straight from the source

The original idea, then the same idea taken apart, then how you use it today.

Anthropic, Claude Code team
The team that builds Claude Code and writes its best-practices guide
Claude Code docs: best practices, “Set up hooks” (2026)
1 · Understand
“Unlike CLAUDE.md instructions which are advisory, hooks are deterministic and guarantee the action happens.” Their tip: “Use hooks for actions that must happen every time with zero exceptions.”
2 · Break it down
  • The model is good at judgement, so give it guidelines.
  • Judgement can say “this case is different”, so guidelines can be skipped.
  • The harness (Claude Code) doesn’t judge; it runs your rules.
  • A prompt hook asks a model, so for a hard rule use a command hook (a script).
3 · Use it
Sort your CLAUDE.md lines into “usually” and “never”. Keep the “usually” lines there and turn each “never” into a deny rule or a hook.
6 terms

Words to know

Permission rule
A line in an allow, ask or deny list, like Bash(git push *) or Read(.env). Claude Code enforces it, not the model.
Hook
Your own command that Claude Code runs at a set moment, such as before every edit. It can block the action or run a formatter.
PreToolUse
The hook event that fires before a tool runs, so it can stop a tool call before it happens.
Exit code 2
How a command hook says no, on events that can block. On PreToolUse, Claude Code blocks the call and passes the hook’s stderr message to Claude.
Permission mode
What happens when no rule matches: ask (default), accept edits, plan only, a classifier (auto), deny (dontAsk) or skip prompts (bypassPermissions).
Sandbox
Operating-system limits on what shell commands can touch on disk and on the network, which also catch scripts that rules miss.
2 videos · plays here

Watch

Hand-picked from the people who explain this best. The video loads only when you press play.

Claude Code Hooks explained in 5 minutes
shanraisshan

A quick visual tour of the hook events. Watch it after step 4 and note which events can block.

Claude Code Hooks: MUST KNOW to Keep Claude Agent in Control!
Mervin Praison

Builds hooks live. Recorded in Aug 2025, so check event names against the docs; the core idea hasn’t changed.

Tester · deny → ask → allow → mode · 8 example calls · 25 Nov 2026 · no AI

Test your settings.json

Paste your Claude Code settings, or load the risky and fixed files from the worked example. See which checks fail, then try any tool call and watch the order Claude Code decides in.

This file is

Checked in your browser; nothing is sent anywhere.

0 of 7 checks pass.

Rules
3
1 deny · 0 ask · 2 allow
Hooks
1
commands that run at set moments
Checks
0 of 7
pass
  • Fix

    1 rule that never matches: Write(prisma/migrations/**)

    Claude Code checks file permissions against Edit(path) and Read(path) rules only. A Write, NotebookEdit or Glob path rule is accepted but never used. Write it as Edit(…) instead.

    Claude Code docs: permissions

  • Improve

    defaultMode "bypassPermissions" is ignored in a project file

    In .claude/settings.json or settings.local.json this value doesn’t take effect and the session starts in Manual mode. Remove it so nobody thinks it works. In ~/.claude/settings.json it would skip prompts, which Anthropic says to use only in containers or VMs.

    Claude Code docs: permission modes

  • Improve

    Nothing stops Claude reading .env

    Add "Read(./.env)" and "Read(./.env.*)" to deny, as in Anthropic’s settings example. A line in CLAUDE.md is only a request.

    Claude Code docs: settings

  • Improve

    Very broad allow: Bash, Edit

    This approves every shell command (or every edit) without a prompt, so only deny and ask rules stand in the way. Allow the exact commands you run instead, e.g. Bash(npm run test *).

    Claude Code docs: permissions

  • Improve

    git push can run without a rule stopping it

    Add "Bash(git push *)" to ask (or deny) so a push never happens silently. Deny and ask apply when any part of a chained command matches.

    Claude Code docs: permissions

  • Improve

    Unquoted $CLAUDE_PROJECT_DIR in a hook command

    A project path with a space breaks the command. Anthropic’s examples write "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/…" and its security notes say always quote shell variables.

    Claude Code docs: hooks reference

  • Improve

    A blocking script on PostToolUse

    PostToolUse hooks can’t undo actions since the tool has already executed. Put guards on PreToolUse; keep PostToolUse for formatters and checks.

    Claude Code docs: hooks guide

  • Note

    No PreToolUse command hook

    Rules cover most needs. Add a PreToolUse hook only for a check a pattern can’t express (for example, “block edits to any file under migrations/ unless a ticket ID is in the prompt”).

    Claude Code docs: hooks guide

Test a tool call against this file

Pick what the agent tries to do. The tester walks the order Claude Code documents: hooks, then deny, then ask, then allow, then the permission mode.

Runs

RunsBash

Bash allows it, so it runs without a prompt.

Split into 2 parts: “pnpm test” · “git push origin main”

  1. 1PreToolUse hooks: No PreToolUse hook in this file.
  2. 2Deny rules: No match.
  3. 3Ask rules: No match.
  4. 4Allow rules: Every part is covered (Bash).

All 8 example calls under this file: 6 of 6 risky ones run with no check

Swipe the table sideways →

CallOutcomeWhy
Run the testsBash(pnpm test --run)RunsBash
Read the secrets fileRead(.env)Runsmode: default
Read production secretsRead(config/.env.production)Runsmode: default
Edit a source fileEdit(src/app/jobs/page.tsx)RunsEdit
Rewrite a migrationWrite(prisma/migrations/0007_stages/migration.sql)RunsEdit
Test, then pushBash(pnpm test && git push origin main)RunsBash
Force-pushBash(git push --force origin main)RunsBash
Delete a folderBash(rm -rf prisma)RunsBash

A teaching model of the rules in Anthropic’s permissions and hooks docs, checked 25 Nov 2026. It assumes Claude Code started in the project folder, splits commands on &&, ||, ;, | and &, and doesn’t read shell quoting, subshells or symlinks. Run /permissions in Claude Code to see the rules it actually loaded.

Hands-on · 10 minutes or less

Try it

Lock down one project in 10 minutes

  1. 1Open your project in Claude Code and type /permissions to see which rules are loaded and from which file.
  2. 2Paste your .claude/settings.json into the tester above (no file yet? start from Empty) and fix every “Fix” item.
  3. 3Write down the two things that must never happen in this project. Add a deny rule for each, and Bash(git push *) to ask.
  4. 4Pick the three commands you approve most often (tests, lint, typecheck) and add exact allow rules for them.
  5. 5Ask Claude to “show me the contents of .env”. It should be refused by your deny rule, not by its own judgement.
Claude Code docs: permissions
Practise this lesson with an AI tutor

It checks what you understood, then gives you a small real task to try.

Read the prompt
Be my patient tutor. I just studied this lesson: "Hooks and permissions". Summary: A rule in CLAUDE.md is a request the model can skip. Permission rules and hooks are enforced by Claude Code itself: deny, ask and allow rules in .claude/settings.json decide which tool calls run, and a hook is your own script that runs at a set moment, such as before every edit, and can block the call by exiting with code 2. Use them for the few things that must never happen, like reading .env or pushing to main.
Key terms: Permission rule, Hook, PreToolUse, Exit code 2, Permission mode, Sandbox.

Do this, one step at a time, waiting for me each time:
1. Ask me to explain the main idea in my own words. Correct me kindly with one concrete example.
2. Ask 4 questions, easy to hard. After each answer, say what was right and what was missing.
3. Give me one small workflow I can try in 10 minutes that uses this idea in real work or study. Walk me through it step by step and check my result.
4. End with 3 lines: what I now know, what I should practise, what to learn next.
3 questions · instant feedback

Check yourself

Pick an answer to see if you are right, and why.

Question 1

Question 1 of 3

Your settings allow "Bash(git *)" and deny "Bash(git push *)". Claude tries git push origin main. What happens?

Question 2

Question 2 of 3

You want to stop Claude reading .env. Which is the strongest single step?

Question 3

Question 3 of 3

Your guard script runs on PostToolUse and exits 2 when a migration file is edited. What goes wrong?

Lesson 41 of 45

Done? Keep going

Mark this lesson complete to keep your place. Progress is saved on this device, no login.

Up next · Lesson 42 · 12 minPrompting vs RAG vs fine-tuningStart with prompting, always. Add RAG (retrieval-augmented generation) when the model is missing knowledge, such as your private documents or facts that change often. Use fine-tuning only when the model is missing behaviour, like a strict format or style, that good prompts and examples cannot fix. Let a small test set decide, not hype.← Previous: CLAUDE.md and AGENTS.md
People also ask

Questions people ask

What are Claude Code hooks?

Hooks are shell commands (or HTTP calls) that Claude Code runs at set moments, such as before a tool runs (PreToolUse), after it succeeds (PostToolUse) or when Claude finishes (Stop). You configure them under "hooks" in .claude/settings.json. A PreToolUse hook can block an action by exiting with code 2, which no permission mode can override.

What is the difference between hooks and permissions in Claude Code?

Permission rules are allow, ask and deny patterns that Claude Code matches against each tool call. Hooks are your own scripts, so they can check anything a script can, like whether a branch name or ticket ID is right. Use rules for simple “never” and “always fine” lists, and hooks for checks a pattern can’t express or for actions like formatting after every edit.

Can Claude Code read my .env file?

Yes, unless you stop it. Claude Code’s approval table says file reads inside the working directory need no approval, in any mode. Add "Read(.env)" and "Read(.env.*)" to the deny list (bare names match in every folder; "./.env" only the top one). A deny rule doesn’t stop a script Claude runs from opening the file itself, so turn on the sandbox for OS-level protection too.

Why is my Claude Code hook not running?

Check the event name (it is case-sensitive: PreToolUse, not pretooluse), the matcher (Edit|Write must match the tool name), that the script is executable and its path is quoted, and which settings file it lives in. Type /hooks to see what Claude Code loaded; the menu is read-only.

11 sources · checked Nov 2026

Sources and further reading

Free to start · runs in your browser · by Tough Tongue AI

Going for an AI role? Practise the interview.

Talk to an AI interviewer about what you just learned and get feedback on every answer.

  1. Pick a round

    PM case, consulting case, AI engineer round or a speaking coach

  2. Answer out loud

    The interviewer follows up on what you actually said

  3. Read the feedback, go again

    What was strong, what was thin, then a retry

Start a free mock interviewOut loud, with a voice interviewer · by Tough Tongue AIOr build a day-by-day prep plan →