Claude Code guide in three levels, Beginner to Advanced: hands-on lessons with checked exercises, every volatile fact cited to its source. Independent community guide.
JavaScript agent-skillsagentic-codingai-agentsanthropicanthropic-claudebest-practicesclaudeclaude-aiclaude-codeclaude-code-guideclaude-code-hooksclaude-code-pluginsclaude-code-skillsclaude-code-tutorialclaude-code-workflowsguidelearn-claude-codemcpsubagentstutorial
docs: add the Intermediate lesson on enforcing a rule with a hook (#85)
Wesam Abousaid344ceac8eb2f
diff --git a/README.md b/README.mdindex 5016812..1c3d934 100644--- a/README.md+++ b/README.md@@ -46,7 +46,7 @@ macOS, Linux and WSL. For Windows and other installers, see the [official setup**Beginner Electives:** [IDE extensions](docs/beginner/electives/ide-extensions.md) · [Screenshots and images](docs/beginner/electives/screenshots-and-images.md) · [The built-in teachers](docs/beginner/electives/built-in-teachers.md)-**Intermediate** (being rebuilt): [Level index](docs/intermediate/README.md) · [Turn a repeated workflow into a skill](docs/intermediate/01-first-skill.md) · [Organize project memory and see what loaded](docs/intermediate/02-organize-memory.md) · [Pick the model and effort](docs/intermediate/03-model-and-effort.md) · [Permissions, settings scopes and the sandbox](docs/intermediate/04-permissions-and-sandbox.md)+**Intermediate** (being rebuilt): [Level index](docs/intermediate/README.md) · [Turn a repeated workflow into a skill](docs/intermediate/01-first-skill.md) · [Organize project memory and see what loaded](docs/intermediate/02-organize-memory.md) · [Pick the model and effort](docs/intermediate/03-model-and-effort.md) · [Permissions, settings scopes and the sandbox](docs/intermediate/04-permissions-and-sandbox.md) · [Enforce a rule with a hook](docs/intermediate/05-hooks.md)**Advanced** (being rebuilt): [Level index](docs/advanced/README.md)@@ -54,7 +54,7 @@ macOS, Linux and WSL. For Windows and other installers, see the [official setup**Reference:** [Reference index](docs/reference/README.md) · [Models and effort](docs/reference/models.md) · [Commands by level](docs/reference/commands.md) · [Feature map](docs/reference/feature-map.md) · [Further learning](docs/reference/further-reading.md) · [Glossary](docs/reference/glossary.md) · [Changelog](docs/reference/changelog.md)-**From the previous edition, not yet re-verified:** [Hooks](docs/legacy/hooks.md) · [Subagents and parallel work](docs/legacy/subagents-and-parallel-work.md) · [MCP](docs/legacy/mcp.md) · [Fast mode](docs/legacy/fast-mode.md) · [Skills in depth](docs/skills.md) · [Agent teams](docs/agent-teams.md) · [Dynamic workflows](docs/workflows.md) · [FAQ](docs/reference/faq.md)+**From the previous edition, not yet re-verified:** [Subagents and parallel work](docs/legacy/subagents-and-parallel-work.md) · [MCP](docs/legacy/mcp.md) · [Fast mode](docs/legacy/fast-mode.md) · [Skills in depth](docs/skills.md) · [Agent teams](docs/agent-teams.md) · [Dynamic workflows](docs/workflows.md) · [FAQ](docs/reference/faq.md)**Examples:** [How to use the examples](examples/README.md)@@ -82,7 +82,7 @@ The previous edition's README sections moved. If a link brought you here, find i- <a id="custom-slash-commands"></a><a id="claude-skills"></a><a id="your-first-skill-in-3-minutes"></a><a id="want-more-depth"></a><a id="what-are-skills"></a><a id="built-in-vs-custom-skills"></a><a id="skills-faq"></a><a id="creating-custom-skills"></a>Moved to [Turn a repeated workflow into a skill](docs/intermediate/01-first-skill.md).- <a id="troubleshooting-skills"></a><a id="skills-best-practices"></a>Moved to [Skills in depth (previous edition)](docs/skills.md).- <a id="available-skills-reference"></a><a id="using-skills-in-workflow"></a>Moved to [Skills topic](docs/topics/skills.md).-- <a id="hooks"></a><a id="setting-up-claude-hooks"></a><a id="setting-up-hooks"></a><a id="hook-events"></a><a id="hook-input"></a><a id="hook-output"></a><a id="security-considerations"></a><a id="hook-execution-details-and-debugging"></a><a id="execution--debugging"></a>Moved to [Hooks (previous edition)](docs/legacy/hooks.md).+- <a id="hooks"></a><a id="setting-up-claude-hooks"></a><a id="setting-up-hooks"></a><a id="hook-events"></a><a id="hook-input"></a><a id="hook-output"></a><a id="security-considerations"></a><a id="hook-execution-details-and-debugging"></a><a id="execution--debugging"></a>Moved to [Enforce a rule with a hook](docs/intermediate/05-hooks.md).- <a id="ai-agents"></a>Moved to [Subagents and parallel work topic](docs/topics/subagents-and-parallel-work.md).- <a id="running-agents-in-parallel"></a><a id="subagents--running-agents-in-parallel"></a><a id="1-git-worktrees--parallel-branches-parallel-sessions"></a><a id="2-general-purpose-subagents--when-one-claude-isnt-enough"></a><a id="orchestrating-specialists-from-the-main-session"></a>Moved to [Subagents and parallel work (previous edition)](docs/legacy/subagents-and-parallel-work.md).- <a id="agent-teams-experimental---2026"></a><a id="agent-teams-experimental"></a><a id="enable-it"></a><a id="the-example-that-justifies-the-cost"></a><a id="staff-a-team-with-the-role-prompts-you-already-have"></a><a id="three-things-that-catch-people-out"></a><a id="monitoring-and-the-naming-trap"></a><a id="best-practices"></a>Moved to [Agent teams (previous edition)](docs/agent-teams.md).diff --git a/docs/intermediate/04-permissions-and-sandbox.md b/docs/intermediate/04-permissions-and-sandbox.mdindex 8e69d69..370bcb6 100644--- a/docs/intermediate/04-permissions-and-sandbox.md+++ b/docs/intermediate/04-permissions-and-sandbox.md@@ -101,4 +101,4 @@ If the first item fails on a broad rule, replace it with the one command: `Bash(<sub>Sources: [Settings files and precedence](https://code.claude.com/docs/en/settings) · [All settings](https://code.claude.com/docs/en/settings-reference) · [Configure permissions](https://code.claude.com/docs/en/permissions) · [Configure the sandboxed Bash tool](https://code.claude.com/docs/en/sandboxing)</sub>-<sub>← [Pick the model and effort](03-model-and-effort.md) · [Intermediate index](README.md) · Topic: [Permissions and safety](../topics/permissions-and-safety.md) · [Stuck on this lesson?](https://github.com/wesammustafa/Claude-Code-Everything-You-Need-to-Know/issues/new?template=lesson-feedback.yml&lesson=i-4)</sub>+<sub>← [Pick the model and effort](03-model-and-effort.md) · [Intermediate index](README.md) · [Enforce a rule with a hook](05-hooks.md) → · Topic: [Permissions and safety](../topics/permissions-and-safety.md) · [Stuck on this lesson?](https://github.com/wesammustafa/Claude-Code-Everything-You-Need-to-Know/issues/new?template=lesson-feedback.yml&lesson=i-4)</sub>diff --git a/docs/intermediate/05-hooks.md b/docs/intermediate/05-hooks.mdnew file mode 100644index 0000000..04e4df2--- /dev/null+++ b/docs/intermediate/05-hooks.md@@ -0,0 +1,144 @@+# Enforce a rule with a hook++<sub>**Intermediate** · Lesson 5 of 8 · about 20 minutes · Needs: [Permissions, settings scopes and the sandbox](04-permissions-and-sandbox.md) · Verified against Claude Code v2.1.285 (stable) on 2026-10-06</sub>++## Goal++By the end of this lesson you can add a hook that enforces a rule every time Claude edits a file, and show it firing.++## You need++- The repository from [lesson 4](04-permissions-and-sandbox.md), with its `.claude/settings.json`, and your copy of the practice template with Node.js LTS: the check runs from the copy.+- `jq`, which the hook scripts use, and `python3`, which `format-after-edit.sh` uses.+- Usage: light.++## The idea++A `CLAUDE.md` rule is advice that Claude can miss. A [hook](https://code.claude.com/docs/en/hooks-guide) is your own command that Claude Code runs at a fixed point in a session, every time, whatever Claude decides. Claude Code passes the hook JSON about the event on stdin. A `PreToolUse` hook runs before a tool call; if it exits with code 2, the call is blocked, and what it printed to stderr goes to Claude as the reason ([Hooks reference](https://code.claude.com/docs/en/hooks#exit-code-2-behavior-per-event), [Block edits to protected files](https://code.claude.com/docs/en/hooks-guide#block-edits-to-protected-files)).++These are the events this lesson uses, and where they fall in a turn:++```mermaid+flowchart LR+ accTitle: Where hook events fire in a turn+ accDescr: A session starts with SessionStart. Each prompt fires UserPromptSubmit. Before each tool call, PreToolUse runs; exit code 2 blocks the call. After a successful call, PostToolUse runs, then Claude may call another tool. When Claude finishes responding, Stop fires. Notification fires on its own whenever Claude Code needs your attention.+ S[SessionStart] --> U[UserPromptSubmit]+ U --> P[PreToolUse]+ P -->|exit 2| B[Call blocked, stderr goes to Claude]+ P -->|exit 0| T[Permission check, then the tool runs]+ T --> Q[PostToolUse]+ Q -->|next tool call| P+ Q --> E[Stop]+ N[Notification, when Claude Code needs you]+```++A matcher picks the tools a hook watches: `Edit|Write` runs it for those two tools only ([Filter hooks with matchers](https://code.claude.com/docs/en/hooks-guide#filter-hooks-with-matchers)). `PreToolUse` hooks fire before the permission-mode check, so a block holds in every mode ([Hooks and permission modes](https://code.claude.com/docs/en/hooks-guide#hooks-and-permission-modes)).++## Worked example++1. In your repository, download two of this guide's [example hooks](../../examples/intermediate/05-hooks/README.md) and make them executable. Read them before you use them:++ ```bash+ mkdir -p .claude/hooks+ for f in protect-files format-after-edit; do+ curl -fsSL "https://raw.githubusercontent.com/wesammustafa/Claude-Code-Everything-You-Need-to-Know/main/examples/intermediate/05-hooks/dot-claude/hooks/$f.sh" -o ".claude/hooks/$f.sh"+ done+ chmod +x .claude/hooks/*.sh+ ```++ `protect-files.sh` is the hooks guide's script for blocking edits to `.env`, `package-lock.json` and `.git/`. `format-after-edit.sh` removes trailing spaces from a source file after Claude edits it.+2. Register them in `.claude/settings.json`, beside the `permissions` block from lesson 4:++ ```json+ "hooks": {+ "PreToolUse": [+ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/protect-files.sh", "args": [] } ] }+ ],+ "PostToolUse": [+ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/format-after-edit.sh", "args": [] } ] }+ ]+ }+ ```++ With `"args": []`, Claude Code runs the script directly, without a shell, so the path needs no quotes ([Exec form and shell form](https://code.claude.com/docs/en/hooks#exec-form-and-shell-form)).+3. Test the hook without Claude, by piping in the JSON an Edit call would send. Edit and Write always send an absolute path ([PreToolUse input](https://code.claude.com/docs/en/hooks#pretooluse-input)), so build it from `$PWD`:++ ```bash+ echo "{\"tool_input\":{\"file_path\":\"$PWD/package-lock.json\"}}" | .claude/hooks/protect-files.sh; echo "exit $?"+ ```++ It prints a `Blocked:` line and `exit 2`.+4. Start `claude` and run `/hooks`: your hooks appear under `PreToolUse` and `PostToolUse` ([Debug your configuration](https://code.claude.com/docs/en/debug-your-config#check-hooks)).+5. Ask for an edit the hook protects. In the practice template, `package-lock.json` exists; in your repository, name a protected file that it has:++ ```text+ Use your Edit tool, not a shell command, to change the top-level version in package-lock.json to 1.0.1.+ ```++ The Edit is blocked: Claude Code passes your script's `Blocked:` message to Claude as feedback ([Exit code output](https://code.claude.com/docs/en/hooks#exit-code-output)). Ask for the Edit tool by name here: Claude can also edit a file through a shell command, which an `Edit|Write` hook doesn't see.++## Your turn++The guide's script matches substrings. `*".env"*` also blocks `.env.example`, which teams commit on purpose, and a file such as `src/config.envelope.ts`; and nothing blocks a `secrets/` folder. Replace `.claude/hooks/protect-files.sh` with this skeleton, which keeps the guide's `package-lock.json` and `.git/` blocks, and finish it:++```bash+#!/bin/bash+INPUT=$(cat)+FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')+FILE_PATH="${FILE_PATH//\\//}"+NAME=$(basename "$FILE_PATH")++case "/$FILE_PATH" in+ */package-lock.json | */.git/*)+ echo "Blocked: $FILE_PATH is protected" >&2+ exit 2+ ;;+esac++# TODO: block a file named .env, or .env. followed by anything except example+# TODO: block any file inside a secrets/ folder++exit 0+```++1. Each block prints a `Blocked:` reason to stderr and exits with 2; everything else exits with 0.+2. Run the Check's test table until every row gives its expected exit code.+3. In a session, ask Claude to use its Write tool to create `secrets/test.key`. Your hook blocks it.+4. Commit the script and `.claude/settings.json`. Keep the script executable: `git ls-files -s .claude/hooks/protect-files.sh` starts with `100755`.++## Check++You are done when all of these are true:++- [ ] Each path gives its expected exit code: 2 for `.env`, `config/.env.local`, `secrets/api.key`, `package-lock.json` and `.git/config`; 0 for `.env.example`, `src/config.envelope.ts` and `src/app.js`. Run this from your repository's root:++ ```bash+ for p in .env config/.env.local .env.example secrets/api.key src/config.envelope.ts src/app.js package-lock.json .git/config; do+ printf '%s ' "$p"; echo "{\"tool_input\":{\"file_path\":\"$PWD/$p\"}}" | .claude/hooks/protect-files.sh 2>/dev/null; echo $?+ done+ ```++- [ ] The script is committed and executable, and the committed `.claude/settings.json` runs it as a `PreToolUse` hook for `Edit|Write`: `git show HEAD:.claude/settings.json | jq .hooks.PreToolUse` shows it.+- [ ] Self-check (not tested): Claude's attempt to create `secrets/test.key` was blocked with your `Blocked:` message.++Run `npm run check -- i-5 --dir <your repo>` from your practice copy, or `npm run check -- i-5` in the copy itself.++If a row is wrong, test that path alone and print the name the script sees: `basename` of `.env.local` is `.env.local`, so a `case` pattern `.env.*` matches it. The check runs the committed script, so commit each fix before you run it. If the second item fails on the file mode, run `chmod +x .claude/hooks/protect-files.sh`, then `git add` it and commit again.++## Watch out++- Hooks run with your user's rights: in an interactive session once you trust the folder, and in a `claude -p` run without asking ([Workspace trust](https://code.claude.com/docs/en/hooks#workspace-trust)). Read a repository's hooks before you trust it or script Claude Code in it.+- An `Edit|Write` hook doesn't see shell commands: `echo X >> .env` goes through Bash. Lesson 4's `Read` rules stop commands such as `cat .env` from reading those files, but a write such as that `>>` is checked against `Edit` rules, which lesson 4 doesn't add ([Redirections](https://code.claude.com/docs/en/permissions#redirections)). For a hook that sees every change, the hooks guide adds a `Bash|PowerShell` matcher or a `Stop` hook that scans the working tree ([Filter hooks with matchers](https://code.claude.com/docs/en/hooks-guide#filter-hooks-with-matchers)).+- A Notification hook, such as the example [`desktop-notify.sh`](../../examples/intermediate/05-hooks/dot-claude/hooks/desktop-notify.sh), is about you, not the project: the hooks guide registers its notification examples in `~/.claude/settings.json`. Do the same, with the path to wherever you keep the script.++## Go further++- [Automate actions with hooks](https://code.claude.com/docs/en/hooks-guide): more ready-made hooks, including notifications and re-injecting context after compaction.+- [Hooks reference](https://code.claude.com/docs/en/hooks): every event, its input and its output.+- [Debug your configuration](https://code.claude.com/docs/en/debug-your-config#check-hooks): what to check when a hook doesn't fire.++---++<sub>Sources: [Automate actions with hooks](https://code.claude.com/docs/en/hooks-guide) · [Hooks reference](https://code.claude.com/docs/en/hooks) · [Configure permissions](https://code.claude.com/docs/en/permissions) · [Debug your configuration](https://code.claude.com/docs/en/debug-your-config)</sub>++<sub>← [Permissions, settings scopes and the sandbox](04-permissions-and-sandbox.md) · [Intermediate index](README.md) · Topic: [Hooks](../topics/hooks.md) · [Stuck on this lesson?](https://github.com/wesammustafa/Claude-Code-Everything-You-Need-to-Know/issues/new?template=lesson-feedback.yml&lesson=i-5)</sub>diff --git a/docs/intermediate/README.md b/docs/intermediate/README.mdindex a40821e..0223434 100644--- a/docs/intermediate/README.md+++ b/docs/intermediate/README.md@@ -29,7 +29,7 @@ git commit -m "Add the Intermediate checks"Five of the ways to extend Claude Code; [Extend Claude Code](https://code.claude.com/docs/en/features-overview) lists the rest. Each links its lesson, or until that lesson lands, the previous edition's page, which is not yet re-verified.- **Skills:** you give Claude the same instructions or workflow again and again. A project skill lives in `.claude/skills/<name>/SKILL.md` ([Extend Claude with skills](https://code.claude.com/docs/en/skills); lesson: [Turn a repeated workflow into a skill](01-first-skill.md)).-- **Hooks:** something must happen every time at a set point in a session, such as before a tool runs, whatever Claude decides. Hooks are defined in a settings file such as `.claude/settings.json` ([Hooks](https://code.claude.com/docs/en/hooks); previous edition: [Hooks](../legacy/hooks.md)).+- **Hooks:** something must happen every time at a set point in a session, such as before a tool runs, whatever Claude decides. Hooks are defined in a settings file such as `.claude/settings.json` ([Hooks](https://code.claude.com/docs/en/hooks); lesson: [Enforce a rule with a hook](05-hooks.md)).- **Subagents:** a side task should run in its own context window and report back. A project subagent lives in `.claude/agents/` ([Create custom subagents](https://code.claude.com/docs/en/sub-agents); previous edition: [Subagents and parallel work](../legacy/subagents-and-parallel-work.md)).- **Dynamic workflows:** the job needs more agents than one conversation can coordinate. A saved project workflow lives in `.claude/workflows/` ([Workflows](https://code.claude.com/docs/en/workflows); previous edition: [Dynamic workflows](../workflows.md)).- **MCP servers:** Claude needs tools or data outside your files, such as a browser, a database or an API. A project-scope server is listed in `.mcp.json` at the project root ([Connect Claude Code to tools via MCP](https://code.claude.com/docs/en/mcp); previous edition: [MCP](../legacy/mcp.md)).@@ -42,7 +42,7 @@ They combine: a [plugin](https://code.claude.com/docs/en/plugins) packages skill2. [Organize project memory and see what loaded](02-organize-memory.md)3. [Pick the model and effort](03-model-and-effort.md)4. [Permissions, settings scopes and the sandbox](04-permissions-and-sandbox.md)-5. Enforce a rule with a hook+5. [Enforce a rule with a hook](05-hooks.md)6. Delegate to a custom subagent7. Connect a tool with MCP8. Install and manage pluginsdiff --git a/docs/legacy/hooks.md b/docs/legacy/hooks.mddeleted file mode 100644index d0a9d67..0000000--- a/docs/legacy/hooks.md+++ /dev/null@@ -1,118 +0,0 @@-# Hooks--> [!NOTE]-> From the previous edition, not yet re-verified. The guide is being rebuilt as lessons; this page keeps the earlier material reachable until they land.--> **Mental model:** Hooks are programmable checkpoints on Claude Code's lifecycle (before/after a tool call, session start, prompt submit, etc.). Your script inspects the proposed action and returns *allow* / *deny* / *modify*.--**Three cases that win most teams over:**--| Use case | What the hook does |-|---|---|-| Auto-format on save | Runs `prettier` / `ruff` / `gofmt` after every Edit so Claude's output matches your style |-| Block sensitive paths | Refuses changes to `.env`, `secrets/`, `infra/prod/` regardless of what Claude tries |-| Action audit log | Records every tool call to a file: a paper trail of what Claude did and when |--If none of those resonate, skip ahead.--<a id="setting-up-claude-hooks"></a>-## Setting up hooks--Hooks live in settings files at four scopes (later overrides earlier):--| Scope | Path |-|---|---|-| User-wide | `~/.claude/settings.json` |-| Project (committed) | `.claude/settings.json` |-| Project (local, gitignored) | `.claude/settings.local.json` |-| Enterprise managed policy | platform-specific |--**Quickest setup**: use the interactive menu:--```bash-/hooks # browse, enable, configure hooks without touching JSON-```--## Hook Events--Hooks run in response to various events within Claude Code's lifecycle:-[examples](https://github.com/disler/claude-code-hooks-mastery)-- **`PreToolUse`**: Runs **after Claude creates tool parameters but before processing the tool call**.-- **`PostToolUse`**: Runs **immediately after a tool completes successfully**.-- **`Notification`**: Runs when Claude Code sends notifications, such as when permission is needed to use a tool or when prompt input has been idle.-- **`UserPromptSubmit`**: Runs when the user submits a prompt, **before Claude processes it**.-- **`Stop`**: Runs when the main Claude Code agent has finished responding (does not run if stopped by user interrupt).-- **`SubagentStop`**: Runs when a Claude Code subagent (Task tool call) has finished responding.-- **`SessionEnd`**: Runs when a Claude Code session ends.-- **`PreCompact`**: Runs before Claude Code is about to run a compact operation.-- **`SessionStart`**: Runs when Claude Code starts a new session or resumes an existing session.-- **`TeammateIdle`**: Runs when an agent teammate becomes idle (Agent Teams); exit code 2 sends the teammate back to work.-- **`TaskCompleted`**: Runs when a task is marked as completed; exit code 2 blocks the completion.--> These are the most-used events. The full catalog is **33 events** as of October 4, 2026 (SubagentStart, PermissionRequest, FileChanged, WorktreeCreate, PostCompact, …); see the [official hooks reference](https://code.claude.com/docs/en/hooks).--## Hook input--Hooks receive **JSON via stdin**. Every event includes `session_id`, `transcript_path`, and `cwd`. Event-specific fields:--| Hook Event | Event-specific fields |-|---|---|-| `PreToolUse` | `tool_name`, `tool_input` |-| `PostToolUse` | `tool_name`, `tool_input`, `tool_response` |-| `Notification` | `message` |-| `UserPromptSubmit` | `prompt` |-| `Stop` / `SubagentStop` | `stop_hook_active` |-| `PreCompact` | `trigger`, `custom_instructions` |-| `SessionStart` | `source` |-| `SessionEnd` | `reason` |-| `TeammateIdle` | `teammate_id`, `last_activity` |-| `TaskCompleted` | `task_id`, `task_name`, `completion_time` |--> [!NOTE]-> The `team_name` field in `TaskCreated` / `TaskCompleted` / `TeammateIdle` payloads is deprecated since v2.1.178 (one implicit team per session).--## Hook output--Two ways to communicate back: **exit codes** for simple control, **JSON in stdout** for fine-grained behavior.--| Exit code | Effect |-|---|---|-| `0` (success) | `stdout` shown in transcript mode (CTRL-R). For `UserPromptSubmit` / `SessionStart`, `stdout` is added to Claude's context. |-| `2` (blocking) | `stderr` fed back to Claude (or shown to user) to block the action. Stops tool calls in `PreToolUse`; stops prompt processing in `UserPromptSubmit`. |-| Other | `stderr` shown; execution continues. |--**Advanced: structured JSON in stdout.** Per-event decision fields:--| Event | JSON output |-|---|---|-| `PreToolUse` | `permissionDecision`: `"allow"` / `"deny"` / `"ask"`; `updatedInput` to modify tool parameters |-| `PostToolUse` | `decision`: `"block"` or `undefined`; `additionalContext` can be returned |-| `UserPromptSubmit` | `decision`: `"block"` or `undefined`; `additionalContext` can be returned |-| `Stop` / `SubagentStop` | `decision`: `"block"` or `undefined` |-| `SessionStart` | `additionalContext` |--## Security considerations--Hooks run **arbitrary shell commands automatically** with your user permissions: they can read, modify, or delete any file you can. Anthropic provides no warranty for what your hooks do.--**Best practices:**--- Validate and sanitize all inputs from stdin JSON-- Quote shell variables (`"$var"`, not `$var`)-- Block path traversal (`..`, absolute paths outside the project)-- Use absolute paths for invoked scripts so PATH attacks don't redirect-- Explicitly skip sensitive files (`.env`, `.git/`, `secrets/`)--Claude Code snapshots your hook configuration at session start and warns if hooks change mid-session; review before applying.--<a id="hook-execution-details-and-debugging"></a>-## Execution & debugging--- **Timeout**: defaults vary by hook type: 600s for `command`/`http`/`mcp_tool` hooks, 30s for `prompt` hooks, 60s for `agent` hooks (some events lower these, e.g. `UserPromptSubmit` command hooks get 30s). Configurable per hook.-- **Parallelization**: all matching hooks run in parallel; identical handlers are deduplicated automatically.-- **Environment**: hooks run in the current dir with Claude Code's env; `CLAUDE_PROJECT_DIR` is available.-- **Debug**: `/hooks` shows current config; `claude --debug` shows hook execution logs; test scripts manually with the JSON payload piped to stdin.-------<sub>From the previous edition of [Claude Code: Everything You Need to Know](../../README.md).</sub>diff --git a/docs/reference/commands.md b/docs/reference/commands.mdindex d90acea..7f9ba96 100644--- a/docs/reference/commands.md+++ b/docs/reference/commands.md@@ -30,7 +30,7 @@ Electives: `/powerup` and `/output-style` ([the built-in teachers](../beginner/e- `/effort`: set the effort level. [Pick the model and effort](../intermediate/03-model-and-effort.md)- `/permissions`: manage allow, ask and deny rules. [Permissions, settings scopes and the sandbox](../intermediate/04-permissions-and-sandbox.md)- `/sandbox`: turn the sandbox on or off. [Permissions, settings scopes and the sandbox](../intermediate/04-permissions-and-sandbox.md)-- `/hooks`: see which hooks are configured. *Enforce a rule with a hook*+- `/hooks`: see which hooks are configured. [Enforce a rule with a hook](../intermediate/05-hooks.md)- `/agents`: a reminder of how to create and manage subagents. *Delegate to a custom subagent*- `/mcp`: manage MCP server connections and sign-ins. *Connect a tool with MCP*- `/plugin`: browse, install and manage plugins. *Install and manage plugins*diff --git a/docs/reference/feature-map.md b/docs/reference/feature-map.mdindex 2d4fb4c..ddacde0 100644--- a/docs/reference/feature-map.md+++ b/docs/reference/feature-map.md@@ -50,7 +50,7 @@ How to read it:| Feature | Label | Who gets it ||---|---|---|| [Skills](https://code.claude.com/docs/en/skills); taught in [Turn a repeated workflow into a skill](../intermediate/01-first-skill.md) | – | Every provider |-| [Hooks](https://code.claude.com/docs/en/hooks-guide) | – | Every provider |+| [Hooks](https://code.claude.com/docs/en/hooks-guide); taught in [Enforce a rule with a hook](../intermediate/05-hooks.md) | – | Every provider || [Agent hooks](https://code.claude.com/docs/en/hooks-guide#agent-based-hooks) | "Agent hooks are experimental." | As for hooks || [Subagents](https://code.claude.com/docs/en/sub-agents) | – | Every provider || [MCP](https://code.claude.com/docs/en/mcp) | – | Every provider; claude.ai connectors only when you sign in with a Claude subscription |diff --git a/docs/topics/hooks.md b/docs/topics/hooks.mdindex 323516a..415b950 100644--- a/docs/topics/hooks.md+++ b/docs/topics/hooks.md@@ -6,7 +6,9 @@ Commands that run at fixed points in a session, so a rule holds without relying## Lessons-This topic's lessons are linked here in level order, with its Electives, as they are published.+- Intermediate: [Enforce a rule with a hook](../intermediate/05-hooks.md)++More of this topic's lessons and Electives are linked here as they are published.## Official docsdiff --git a/examples/README.md b/examples/README.mdindex 9abbc40..560a63f 100644--- a/examples/README.md+++ b/examples/README.md@@ -15,3 +15,4 @@ Every executable example follows the guide's [safety contract](../CONTRIBUTING.mEach example is listed here, with its lesson, platforms and test line, when the lesson that uses it is published.- [`intermediate/01-first-skill/`](intermediate/01-first-skill/README.md): the `five-whys` skill and the unfinished `tdd` skill, for [Turn a repeated workflow into a skill](../docs/intermediate/01-first-skill.md). Any platform. Tested in Claude Code v2.1.285 (stable) on macOS, 2026-10-06.+- [`intermediate/05-hooks/`](intermediate/05-hooks/README.md): three teaching hooks (protect-files, format-after-edit and desktop-notify) and the settings that register them, for [Enforce a rule with a hook](../docs/intermediate/05-hooks.md). macOS, Linux and WSL 2, with bash, jq and python3. Tested in Claude Code v2.1.285 (stable) on macOS, 2026-10-06.