Type: docs Makes the version stamps, Compatible Models footers and locale README badges say only what has been checked. Every claim below was checked against `https://code.claude.com/docs/en/<page>.md` or the raw changelog (2.1.303–2.1.322), not written from memory. ## Part A: English footers at 2.1.310 / 2.1.302 Each file's behavioural claims were checked against every changelog entry after its stamp, up to 2.1.322, and against the current docs. A stamp moves only when every claim checks out. | File | Claims checked | Fixes | Sources | New stamp | |---|---|---|---|---| | `INDEX.md` | ~75: AGENTS.md rule (v2.1.277); skill/agent/MCP install paths; `/mcp__github__list_prs`; 5 hook types, 33 events, task-tool model note; `--plugin-dir`; checkpoint menu (6 options); `/workflows`, ultracode (v2.1.284), size guideline; 6 permission modes; `/loop` and the cron tools; Chrome; Remote Control; `SendMessage`/`ListAgents`/`notify_when_idle`; CLI flags | 1. Workflow size: medium aims for fewer than 10 agents only since v2.1.271 (15 before), and the default is small on a Pro plan. 2. dontAsk: file reads inside the working directories also run, as do *most* calls a `permissions.allow` rule or a `PreToolUse` hook approves (neither can approve critical-path `rm`/`rmdir` or network-path reads), and an installed mod can approve some calls. No version is given: the changelog doesn't say when a mod's `tool.check` allow arrived (it is already referenced in 2.1.290, 2.1.292 and 2.1.299). 3. `SendMessage` also reaches sessions on other machines and in the cloud, from a session connected to Remote Control with a claude.ai sign-in; a cloud session can't answer with `SendMessage`. The L383 use-case column now says the same. 4. The `--model` list adds the Fable models. 5. Plan mode: "Read-only analysis" → researches and proposes, runs shell commands to explore, edits blocked until the plan is approved. | [workflows#set-a-size-guideline](https://code.claude.com/docs/en/workflows#set-a-size-guideline) ("The default is `medium`, or `small` when you're signed in on a Pro plan with Claude Code v2.1.271 or later"); CL 2.1.219 ("aim for fewer than 15 agents"), CL 2.1.271 ("lowered the medium size guideline from 15 to 10 agents"); [permission-modes](https://code.claude.com/docs/en/permission-modes#allow-only-pre-approved-tools-with-dontask-mode) ("a mod you installed can still approve some of those calls"; "Claude still runs … file reads inside your working directories and read-only Bash commands"; "It also denies the built-in `AskUserQuestion` tool even if your allow rules match it"; "An allow rule or `PreToolUse` hook can't approve these: Recognized `rm` and `rmdir` critical-path removals … Reads from a network path"); CL 2.1.292 ("Fixed a plugin's `tool.check` hook answering allow running a tool…"), CL 2.1.299 ("…that a `PreToolUse` hook or a mod's `tool.check` hook allowed"); [permission-modes#analyze-before-you-edit-with-plan-mode](https://code.claude.com/docs/en/permission-modes#analyze-before-you-edit-with-plan-mode) ("Claude reads files, runs shell commands to explore, and writes a plan, but does not edit your source. Except in interactive terminal sessions with bypass permissions available, edits stay blocked until you approve the plan."); [cross-session-messaging](https://code.claude.com/docs/en/cross-session-messaging) ("reach your sessions on other machines or in the cloud"; "from a session that is connected to Remote Control, which needs a claude.ai sign-in"; "A cloud session … can't use `SendMessage` to answer a message from another machine"); model-config. The "device card" line checked out against [whats-new/2026-w34](https://code.claude.com/docs/en/whats-new/2026-w34). | **2.1.322** | | `LEARNING-ROADMAP.md` | 33 hook events / 5 types; 6 built-in subagents (Explore, Plan, General-purpose, claude, statusline-setup, claude-code-guide); 60+ commands (commands page has 121 rows); `/design` (v2.1.265); `/plan`, `/rewind`, `/loop 5m`, `/schedule`; 6 permission modes (Manual since v2.1.200); Alt+T; skill `effort`/`shell`; plugin `workflows`/`channels`/`dependencies`; agent-teams env var; `claude mcp add --transport http`; `-r`, `--max-turns`, `--output-format json`; all 17 source links resolve | 1. Remote Control: "generally available" → "out of research preview", the docs' own wording. 2. Extended thinking (L368, Exercise 3, checklist): Opus 5.5, Sonnet 5.5, Haiku 5.5 and the Fable models always use extended thinking, so the exercise uses `/effort` and scopes Alt+T / Option+T to models that allow turning thinking off. 3. Exercise 4: checkpoints are automatic and unnamed, so step 1 no longer creates a named "Clean state" checkpoint and step 5 says which one to `/rewind` to. | [whats-new/2026-w34](https://code.claude.com/docs/en/whats-new/2026-w34): "Any machine running `claude remote-control` now shows up as a device card at the top of the Code tab in the Claude app. Remote Control is also out of research preview."; [interactive-mode](https://code.claude.com/docs/en/interactive-mode): Alt+T "Has no effect on Opus 5.5, Sonnet 5.5, Haiku 5.5, or the Fable models, which always use extended thinking."; [model-config](https://code.claude.com/docs/en/model-config): "the effort level is the primary control for how much thinking happens"; [checkpointing](https://code.claude.com/docs/en/checkpointing): "Every prompt you send that starts a turn creates a new checkpoint" | **2.1.322** | | `resources.md` | Adaptive reasoning on Opus 4.7+, Sonnet 5+, Haiku 5.5 and the Fable models; permission modes; 33 hook events; `/loop` and cron; 7 memory tiers; Chrome; keybinding chords; Code Review; Monitor (2.1.98); `/goal` and `claude agents` (2.1.139); `--json` (2.1.145); all links | none needed | model-config, hooks, memory, agent-view, changelog | **stays 2.1.310**: L253 gives `/run`, `/verify`, `/run-skill-generator` as "(v2.1.145+)". Neither the changelog, the v2.1.145 release notes, the skills/commands docs nor the what's-new pages for weeks 19–22 give a version. | | `03-skills/claude-md/SKILL.md` | `name`/`description` frontmatter, `$ARGUMENTS`; CLAUDE.md locations and loading; "under 200 lines"; AGENTS.md gates (v2.1.277, v2.1.281), blocking files, `/config` Project instructions values and default; `@AGENTS.md`/symlink fallback; `.claude/agents/` | L196: the list of cases where AGENTS.md isn't read now includes a disabled built-in plugin, and limits the upgrade case to "in some cases" after upgrading from v2.1.276 or earlier | [memory#when-agents-md-support-is-unavailable](https://code.claude.com/docs/en/memory#when-agents-md-support-is-unavailable): "You used `/plugin` to disable the built-in plugin that reads `AGENTS.md`"; "In some cases, it's your first session after you upgrade from v2.1.276 or earlier" | **stays 2.1.302**: no primary source states L24 ("~150-200 instructions", "system prompt already uses ~50") or L214 (the system reminder says CLAUDE.md "may or may not be relevant") | | `07-plugins/devops-automation/README.md` | `--plugin-dir` install; commands; agents; hooks; MCP; workflow; source URLs (all 200) | none: the stale claims need a design decision (below) | [plugins/components](https://code.claude.com/docs/en/plugins/components): "Save a command at `commands/<file>.md` and it becomes `/<plugin>:<file>`"; [plugins-reference](https://code.claude.com/docs/en/plugins-reference) standard layout: "Hooks \| `hooks/hooks.json`", "MCP servers \| `.mcp.json`" | **stays 2.1.302**: bare `/deploy`, `/rollback`, `/status` (`/status` is also a built-in), `/incident`; `hooks/*.js` are never registered (no `hooks/hooks.json`); `mcp/kubernetes-config.json` never loads (no `.mcp.json` or `mcpServers`) | | `07-plugins/documentation/README.md` | same | none | same | **stays 2.1.302**: bare command names; `mcp/github-docs-config.json` never loads, so the `GITHUB_TOKEN` setup has no effect | | `07-plugins/pr-review/README.md` | same | none | same | **stays 2.1.302**: bare command names; `hooks/pre-review.js` is not registered; `mcp/github-config.json` never loads | No changelog entry from 2.1.303 to 2.1.322 touched the plugin READMEs or SKILL.md. Their problems predate the stamps, and #209 already listed the hook/MCP files that never load. **Locale copies:** the same factual fixes went into every locale with the same sentence. That's dontAsk and plan mode in all six INDEX files; workflow size in fa and ko; `SendMessage` and the use-case column in fa and ko; the `--model` list in fa and ko; "generally available" in fa and ko LEARNING-ROADMAP; the extended-thinking exercise/checklist and the checkpoint exercise in all six LEARNING-ROADMAP copies; the AGENTS.md cases in all six SKILL.md copies. Locale stamps were not bumped. INDEX and LEARNING-ROADMAP stay at 2.1.310 in every locale, and the SKILL.md copies keep their footers. ## Part B: Compatible Models footers The new list is **Claude Fable 5.2, Claude Fable 5.1, Claude Fable 5, Claude Opus 5.5, Claude Opus 5, Claude Sonnet 5.5, Claude Sonnet 5, Claude Sonnet 4.6, Claude Opus 4.8, Claude Haiku 5.5, Claude Haiku 4.5**. It is used on root docs and module pages alike, and it's the README FAQ's list, so the footers and the FAQ no longer disagree. Why one list for both file types: STYLE_GUIDE's footer rule ("List all compatible models") applies to both. A shorter "current models only" list on module pages would break that rule. Justification from [model-config](https://code.claude.com/docs/en/model-config): - **Current models:** "| Anthropic API | Opus 5.5 | Sonnet 5.5 | Haiku 5.5 |"; "the `fable` alias resolves to Fable 5 in Claude apps gateway sessions and to Fable 5.2 everywhere else"; "Fable 5.2 requires Claude Code v2.1.321 or later". - **Older models still in use:** - "**Fable 5.1 or Fable 5**: select it by model ID." - "| Claude Platform on AWS | Opus 5.5 | Sonnet 4.6 | Haiku 4.5 |". - "biology-flagged requests re-run on Opus 5, and cybersecurity-flagged requests re-run on Opus 4.8". - "**Sonnet 5.5**: cybersecurity-flagged requests re-run on Sonnet 5." - **None are retired.** The [models overview](https://platform.claude.com/docs/en/about-claude/models/overview) that model-config links marks only Opus 4.1, Opus 4 and Sonnet 4 as "retired". All eleven listed models appear there without that mark. Scope: 336 lines in 331 files. The changed lines are the `**Compatible Models**` lines (92, some of them in locale files) and every localized label (`호환 모델`, `مدلهای سازگار`, `Các Mô Hình Tương Thích`, `Сумісні моделі`, `対応モデル`, `互換モデル`, `兼容模型`), plus the italic `*対応:…*` / `*Для …*` / `*适用于 …*` lines in the ja/uk/zh concepts guides. Labels, separators (`, ` `、` `، `) and locale stamps are unchanged. The README FAQ lines and the 05-mcp `tool_reference` note are not footers and were left alone. The footer lines of `CHANGELOG.md`, `fa/CHANGELOG.md` and `ko/CHANGELOG.md` also carry the new list; only the footer line changed, not the entries. ## Part C: locale README badges Real state: the newest version that most (more than half) of the locale's ten module READMEs carry or exceed, backed by the sync commit that brought them there. A badge is marked **(partial)** when one or more of the locale's module READMEs has no version footer (never synced since its first translation), or when the locale is a condensed translation. A module synced to an older version than the badge doesn't make it partial on its own; the majority rule above already covers that. Only zh meets the rule (02-memory and 05-mcp have no footer, and #247 calls zh condensed). | Locale | Old badge / "latest" | Evidence | New | |---|---|---|---| | ja | 2.1.119 (badge, "latest", FAQ) | module footers: 3×2.1.322, 5×2.1.316, 1×2.1.310, 1×2.1.302; 8/10 ≥ 2.1.316 (#230); #247 carried only the sections ja has | **2.1.316** (Oct 2026) | | uk | 2.1.112 (FAQ line; no badge) | 3×2.1.322, 4×2.1.316, 1×2.1.310, 2×2.1.302; 7/10 ≥ 2.1.316 (#230) | **2.1.316** (Oct 2026) | | zh | 2.1.112 (badge, "latest", FAQ) | 2.1.316, 2.1.310 ×2, 2.1.302 ×2, 2.1.300 ×2, 2.1.278; 02 and 05 have no footer (untouched since the first translation); 7/10 ≥ 2.1.300 (#193); #247 was "condensed", model lists only | **2.1.300 (partial)** (Oct 2026): the badge, "latest" and FAQ lines say zh is condensed and that 02-memory and 05-mcp haven't been synced since the April 2026 translation | | ko | 2.1.310 | 5×2.1.322, 5×2.1.310; #228 synced ko to 2.1.310, and #247 says 2.1.316 "was not backfilled" | **2.1.310** (unchanged) | | fa | 2.1.310 | 5×2.1.322, 5×2.1.316; #241 "syncs the translation from v2.1.310 to v2.1.316"; #247 carried only the 2.1.322 P1 changes | **2.1.316** (Oct 2026) | | vi | none (README has no badge or version line) | 4×2.1.322, 6×2.1.316 | no change | Months come from the docs changelog: 2.1.300 was released October 14, 2026 and 2.1.316 October 31, 2026. The README *footers* in fa/ja/ko/uk/zh stay at 2.1.322: #247 checked those files themselves, while the badge describes the whole locale. ## Deliberately left - **Stamps not bumped:** `resources.md` (2.1.310), `03-skills/claude-md/SKILL.md` and the three plugin READMEs (2.1.302), for the reasons in the Part A table. - **Example plugins:** the fix is a design choice between wiring up `hooks/hooks.json` / `.mcp.json` and rewording the READMEs, and renaming commands to `/<plugin>:<name>` touches seven languages plus `07-plugins/README.md` (bare `/review-pr`). It needs a follow-up issue. - **Same unverifiable version elsewhere:** `03-skills/README.md` also said `/run-skill-generator` is v2.1.145+. Handled by #262, now merged into this branch from `main`. - **Older `--model` lists:** ja/uk/vi/zh INDEX have pre-5.x lists (e.g. "Sonnet 4.6, Opus 4.7, Haiku 4.5"). That isn't the English sentence, so it belongs to a locale sync. ## Follow-ups - **LEARNING-ROADMAP `/effort` line (review r3 N13):** line 368 can read as if `/effort` applies only to the models that always use extended thinking; per model-config's effort table it also works on Opus 5, Sonnet 5 and Opus 4.8. Not wrong; clarify in the next pass. - **Compatible Models scope (review S3):** Opus 4.6 is Microsoft Foundry's current `opus`, and Sonnet 4.5 is the current `sonnet` on Bedrock, Google Cloud's Agent Platform and Foundry (deprecated, retiring Nov 30, 2026), per model-config's alias table. Both are still in use, so either add them to the FAQ and every footer (Sonnet 4.5 marked deprecated), or define the list's scope in STYLE_GUIDE (e.g. the models the aliases resolve to on the Anthropic API plus older models in active use) and cite the deprecations table. - **Model order (review N8):** the list puts Opus 4.8 after Sonnet 4.6. Grouping by family (Fable, Opus 5.5/5/4.8, Sonnet, Haiku) would read better; the order is shared by STYLE_GUIDE, the FAQ and every footer, so change it everywhere at once. - **Example plugins:** the follow-up issue proposed above. ## Validation - `SKIP=mermaid,vietnamese-mermaid,japanese-mermaid,korean-mermaid,persian-mermaid pre-commit run --files <338 changed files>`: every hook passes, including link-check (246 URLs per language). The Mermaid hooks can't install here (`language: node must have package.json or additional_dependencies`, the same failure #247 reported). `python scripts/check_mermaid.py --strict` was run directly instead: Pele 1.6.0 rendered all 416 blocks. - `python scripts/check_cross_references.py`: all valid (674 files). - Review fix round 1 (18 files): the same `pre-commit run --files` passes every hook (Mermaid hooks skipped as above; no Mermaid block was touched), and the cross-reference check is still valid after merging `main`. - Review fix round 2 (14 files: the extended-thinking wording in all 7 LEARNING-ROADMAP files, the dontAsk line in all 7 INDEX files): `pre-commit run --files` passes every hook (Mermaid hooks skipped; no Mermaid block touched), and the cross-reference check is valid (674 files) after merging `main` again (#257). - Pre-push secret scan: it flagged `06-hooks/README.md:1683` (en, fa, vi), a false positive. The `sk-…{20,}` pattern matches the docs anchor `hooks#pretooluse-ask-decisions-in-auto-mode`, which has been on `main` since11b2ae3(en),c2f92c8(fa) and8de1820(vi), and is not on a line this PR changes. The PR's added lines have no secret-pattern matches. Closes #256
フック
フックは、Claude Code セッション中の特定イベントに応答して実行される自動化スクリプトである。自動化、検証、権限管理、カスタムワークフローを可能にする。
概要
フックは、Claude Code 内で特定イベントが発生したときに自動実行される自動化アクション(シェルコマンド、HTTP webhook、LLM プロンプト、MCP ツール呼び出し、サブエージェント評価)である。フックは JSON 入力を受け取り、終了コードと JSON 出力で結果を伝える。
主な機能:
- イベント駆動の自動化
- JSON ベースの入出力
command、http、mcp_tool、prompt、agentの各フックタイプをサポート- ツール固有のフック向けのパターンマッチング
設定
フックは設定ファイル内に決まった構造で記述する。
~/.claude/settings.json- ユーザー設定(全プロジェクト).claude/settings.json- プロジェクト設定(共有可、コミット対象).claude/settings.local.json- ローカルプロジェクト設定(コミットしない)- 管理ポリシー - 組織全体の設定
- プラグインの
hooks/hooks.json- プラグインスコープのフック - スキル/エージェントのフロントマター - コンポーネントライフタイムフック
基本的な設定構造
{
"hooks": {
"EventName": [
{
"matcher": "ToolPattern",
"hooks": [
{
"type": "command",
"command": "your-command-here",
"timeout": 60
}
]
}
]
}
}
主要フィールド:
| フィールド | 説明 | 例 |
|---|---|---|
matcher |
ツール名にマッチするパターン(大文字小文字を区別) | "Write"、"Edit|Write"、"*" |
hooks |
フック定義の配列 | [{ "type": "command", ... }] |
type |
フックタイプ:"command"(bash)、"prompt"(LLM)、"http"(webhook)、"mcp_tool"(MCP ツール呼び出し、v2.1.118 以降)、"agent"(サブエージェント) |
"command" |
command |
実行するシェルコマンド | "$CLAUDE_PROJECT_DIR/.claude/hooks/format.sh" |
timeout |
オプションのタイムアウト(秒)。デフォルトは command/http/mcp_tool が 600、prompt が 30、agent が 60。 | 30 |
once |
true の場合、最初に成功した実行の後でフックが削除される(失敗・ブロック・タイムアウトした実行では残る)。スキルのフロントマターのみ有効で、settings やエージェントのフロントマターでは無視される |
true |
async |
true の場合、ブロックせずにバックグラウンドで実行 |
true |
asyncRewake |
true の場合、バックグラウンドで実行し、終了コード 2 で Claude を起こす。async を含意する。 |
true |
shell |
"bash" または "powershell" を受け付ける。デフォルトは "bash"、Git Bash が未インストールの Windows では "powershell"。 |
"bash" |
statusMessage |
フック実行中に表示されるカスタムスピナーメッセージ | "フォーマット中…" |
注意: 一部のイベントはデフォルトのタイムアウトを引き下げる。
UserPromptSubmitは command / http / mcp_tool のデフォルトを 30 秒に、MessageDisplayは 10 秒に下げる。SessionEndフックは 1.5 秒の予算を共有し、設定でより長いtimeoutを指定した場合は Claude Code が最大 60 秒まで予算を引き上げる。
マッチャーパターン
| パターン | 説明 | 例 |
|---|---|---|
| 完全一致文字列 | 特定のツールにマッチ | "Write" |
| 正規表現 | 複数のツールにマッチ | "Edit|Write" |
| ワイルドカード | すべてのツールにマッチ | "*" または "" |
| MCP ツール | サーバーとツールのパターン | "mcp__memory__.*" |
InstructionsLoaded のマッチャー値:
| マッチャー値 | 説明 |
|---|---|
session_start |
セッション開始時に読み込まれる指示 |
nested_traversal |
ネストされたディレクトリ走査中に読み込まれる指示 |
path_glob_match |
パス glob パターンマッチで読み込まれる指示 |
フックタイプ
Claude Code は 5 種類のフックタイプをサポートする。
Command フック
デフォルトのフックタイプ。シェルコマンドを実行し、JSON の標準入出力と終了コードで通信する。
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate.py\"",
"timeout": 60
}
HTTP フック
v2.1.63 で追加。
リモート webhook エンドポイントが、command フックと同じ JSON 入力を受け取る。HTTP フックは URL に JSON を POST し、JSON レスポンスを受け取る。サンドボックスが有効な場合、HTTP フックはサンドボックス経由でルーティングされる。ヘッダー値への環境変数展開には、セキュリティのため明示的な allowedEnvVars リストが必要。
{
"hooks": {
"PostToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "http",
"url": "https://my-webhook.example.com/hook"
}]
}]
}
}
主要プロパティ:
"type": "http"-- HTTP フックであることを示す"url"-- webhook エンドポイント URL- サンドボックスが有効ならサンドボックス経由でルーティング
headersの値への環境変数展開には明示的なallowedEnvVarsリストが必要
Prompt フック
LLM が評価するプロンプトで、フック内容は Claude が評価するプロンプトとなる。主に Stop および SubagentStop イベントで、知的なタスク完了チェックに使用される。
{
"type": "prompt",
"prompt": "Evaluate if Claude completed all requested tasks.",
"timeout": 30
}
LLM はプロンプトを評価し、構造化された判定を返す(詳細は Prompt ベースのフック を参照)。
MCP Tool フック
v2.1.118 で追加。
mcp_tool タイプは設定された MCP ツールを直接呼び出す。設定はシェルコマンドや URL ではなく、MCP サーバーとツール名を参照する。検証や反応ロジックがすでに設定済みの MCP サーバー側にある場合に有用である。
{
"matcher": "Edit",
"hooks": [{
"type": "mcp_tool",
"server": "my-mcp-server",
"tool": "validate_edit",
"input": { "file_path": "${tool_input.file_path}" }
}]
}
主要プロパティ:
"type": "mcp_tool"-- MCP ツールフックであることを示す"server"-- 設定済み MCP サーバーの名前"tool"-- そのサーバー上で呼び出すツール名"input"-- ツールに渡す任意の引数。文字列値ではフックの JSON 入力から${path}置換が使える(例:"${tool_input.file_path}")
ツールの引数は input(${path} 置換付き)から作られ、フック入力がそのまま渡されるわけではない。MCP サーバーの設定方法は MCP サーバーセットアップ を参照。
Agent フック
サブエージェントベースの検証フックで、専用エージェントを生成して条件評価や複雑なチェックを実行する。prompt フック(単発の LLM 評価)と異なり、agent フックはツールを使用してマルチステップの推論を行える。
{
"type": "agent",
"prompt": "Verify the code changes follow our architecture guidelines. Check the relevant design docs and compare.",
"timeout": 120
}
注意: Agent フックは実験的機能であり、変更される可能性がある。
注意: v2.1.280 以降、agent フックは
PermissionRequestでは実行されない。その応答ではリクエストを許可も拒否もできないためである。PermissionRequestには判定オブジェクトを返す command フックまたは HTTP フックを使うこと(prompt フックのok: falseはPermissionRequestでは効果がない)。
主要プロパティ:
"type": "agent"-- agent フックであることを示す"prompt"-- サブエージェントへのタスク説明- エージェントはツール(Read、Grep、Bash など)を使用して評価を行える
- prompt フックと同様に構造化された判定を返す
フックイベント
Claude Code は 33 種類のフックイベント をサポートする。
| イベント | 発火タイミング | マッチャー入力 | ブロック可否 | 用途例 |
|---|---|---|---|---|
| SessionStart | セッション開始/再開/clear/compact/fork | startup/resume/clear/compact/fork | 不可 | 環境セットアップ |
| Setup | --init-only、または -p と併用した --init/--maintenance(CI/スクリプト準備) |
init/maintenance |
不可 | ツールのプロビジョニング、依存関係のインストール |
| InstructionsLoaded | CLAUDE.md やルールファイルが読み込まれた後 | 読み込み理由(session_start/nested_traversal/path_glob_match/include/compact) |
不可 | 監査・可観測性のためのロギング |
| UserPromptSubmit | ユーザーがプロンプトを送信 | (なし) | 可 | プロンプト検証 |
| UserPromptExpansion | ユーザーが入力したスラッシュコマンドまたは MCP プロンプトがプロンプトに展開される | コマンド名 | 可 | 展開後のプロンプトを変換/検査 |
| MessageDisplay | アシスタントのメッセージ本文が表示される際 | (なし) | 不可 | 表示テキストの変換・非表示化(v2.1.152) |
| PreToolUse | ツール実行前 | ツール名 | 可(allow/deny/ask) | 入力の検証・修正 |
| PermissionRequest | 権限ダイアログ表示 | ツール名 | 可 | 自動承認/拒否 |
| PermissionDenied | auto モードがツール呼び出しを拒否 | ツール名 | 不可 | ロギング、解析、ポリシー強制 |
| PostToolUse | ツール成功後 | ツール名 | 不可 | コンテキスト追加、フィードバック |
| PostToolUseFailure | ツール実行失敗時 | ツール名 | 不可 | エラー処理、ロギング |
| PostToolBatch | ツールバッチ完了後 | (なし) | 可 | 集約レポート、バッチ検証 |
| Notification | 通知送信時 | 通知タイプ | 不可 | カスタム通知 |
| SubagentStart | サブエージェント生成 | エージェントタイプ名 | 不可 | サブエージェントセットアップ |
| SubagentStop | サブエージェント完了 | エージェントタイプ名 | 可 | サブエージェント検証 |
| Stop | Claude が応答を終えたとき | (なし) | 可 | タスク完了チェック |
| StopFailure | API エラーでターン終了 | エラー種別(rate_limit、overloaded、server_error など) |
不可 | エラー復旧、ロギング |
| TeammateIdle | エージェントチームのメイトがアイドル | (なし) | 可 | チームメイト連携 |
| TaskCompleted | タスク完了マーク | (なし) | 可 | タスク後の処理 |
| TaskCreated | TaskCreate でタスク作成 | (なし) | 可 | タスク追跡、ロギング |
| ConfigChange | 設定ファイル変更 | 設定ソース(user_settings/project_settings/local_settings/policy_settings/skills) |
可(ポリシーを除く) | 設定更新への反応 |
| CwdChanged | 作業ディレクトリ変更 | (なし) | 不可 | ディレクトリ固有のセットアップ |
| DirectoryAdded | /add-dir または SDK の register_repo_root コントロールリクエストにより、セッション中に新しい作業ディレクトリが登録された時(v2.1.219) |
slash_command/register_repo_root |
不可 | 追加されたディレクトリ向けのツール設定 |
| FileChanged | 監視ファイル変更 | 監視するファイル名(例:.envrc|.env) |
不可 | ファイル監視、再ビルド |
| PreCompact | コンテキスト圧縮前 | manual/auto | 可 | 圧縮前の処理 |
| PostCompact | 圧縮完了後 | (なし) | 不可 | 圧縮後の処理 |
| PreModelSwitch | 要求されたモデル切り替えを Claude Code が適用する前 | 切り替え先モデルの正式名(to_model から導出) |
可 | モデル変更の制御・拒否 |
| PostModelSwitch | セッションのモデルが変更された後(再開時のモデル復元など、Claude Code 自身による変更を含む) | 切り替え先モデルの正式名(to_model から導出) |
不可 | モデル変更のロギング・追随処理 |
| WorktreeCreate | ワークツリー作成中 | (なし) | 可(パス返却) | ワークツリー初期化 |
| WorktreeRemove | ワークツリー削除中 | (なし) | 可(非ゼロ終了で削除が失敗) | ワークツリークリーンアップ |
| Elicitation | MCP サーバーがユーザー入力を要求 | MCP サーバー名 | 可 | 入力検証 |
| ElicitationResult | ユーザーが elicitation に応答 | MCP サーバー名 | 可 | 応答処理 |
| SessionEnd | セッション終了 | 終了理由(clear/resume/logout/prompt_input_exit/other) |
不可 | クリーンアップ、最終ロギング |
TaskCreatedとTaskCompletedは todo ツールが有効なときのみ発火する(v2.1.233)。 これらのイベントは todo/タスク追跡ツール(TaskCreate/Get/Update/List、TodoWrite)から発火するが、それらは Claude 3.x モデル、Opus 4〜4.7、Sonnet 4〜4.6、Haiku 4.5 でのみデフォルトで利用できる。それ以外のモデルではフックの設定自体は有効なまま、単に発火しない — 出力もエラーも出ない。CLAUDE_CODE_ENABLE_TODO_TOOLS=1を設定すると復活する。
PostToolUse の duration(v2.1.119):
PostToolUseとPostToolUseFailureのフック入力にduration_msが含まれるようになった。詳細は PostToolUse セクションを参照。
PreToolUse
Claude がツールパラメータを生成した後、処理開始前に動作する。ツール入力の検証・修正に使う。
設定:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py"
}
]
}
]
}
}
一般的なマッチャー: Agent、Bash、Glob、Grep、Read、Edit、Write、WebFetch、WebSearch
出力制御:
permissionDecision:"allow"、"deny"、"ask"、"defer""allow"は権限プロンプトをスキップする(ユーザー操作が必須のツール、および組織がaskに設定したコネクタツールを除く)"deny"はツール呼び出しを阻止する"ask"はユーザーに確認を求める"defer"はターンを終了して後でツールを再開できるようにする。-pを使った非対話モードでのみ機能する(対話セッションでは警告をログに記録して無視する)。結果にはstop_reason: "tool_deferred"が含まれる。この値ではpermissionDecisionReason、updatedInput、additionalContextはいずれも無視される- フックが何を返しても deny/ask のルールは引き続き評価される。複数の
PreToolUseフックの判定が食い違う場合、優先順位はdeny>defer>ask>allowとなる
permissionDecisionReason: 判定の理由。"ask"では(Claude ではなく)ユーザーに表示され、"deny"では Claude に表示される。"allow"と"defer"ではデバッグログにのみ記録されるupdatedInput: 置き換え用のツール入力(入力オブジェクト全体を置き換える)。v2.1.300 以降は Claude 自身の入力と同様に検証され、未知のキーは破棄され、ツールが拒否する入力では呼び出しが拒否される。
PostToolUse
ツール完了直後に動作する。検証、ロギング、Claude へのコンテキスト返却に使う。
設定:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/security-scan.py"
}
]
}
]
}
}
出力制御:
"block"判定で Claude にフィードバックを促すadditionalContext: Claude へ追加されるコンテキスト
追加入力フィールド(v2.1.119):
| フィールド | 型 | 説明 |
|---|---|---|
duration_ms |
number | ツール実行時間(ミリ秒)。権限プロンプトおよび PreToolUse フック実行時間は除外。PostToolUse と PostToolUseFailure の両フックで利用可能。 |
UserPromptSubmit
ユーザーがプロンプトを送信し、Claude が処理を開始する前に動作する。v2.1.299 以降はスキルやカスタムコマンドが展開される前に実行されるため、プロンプトをブロックするとそのコマンドの ! シェル行も止まる。UserPromptExpansion はその後に発火する。
設定:
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-prompt.py"
}
]
}
]
}
}
出力制御:
decision:"block"で処理を阻止reason: ブロックされた理由additionalContext: プロンプトに追加されるコンテキスト
Stop と SubagentStop
Claude が応答を終えたとき(Stop)、サブエージェントが完了したとき(SubagentStop)に動作する。知的なタスク完了チェックのために、prompt ベースの評価をサポートする。
追加入力フィールド: Stop と SubagentStop の両フックは、JSON 入力に last_assistant_message フィールドを受け取る。これは停止前の Claude もしくはサブエージェントからの最終メッセージを含み、タスク完了の評価に有用である。
設定:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Evaluate if Claude completed all requested tasks.",
"timeout": 30
}
]
}
]
}
}
SubagentStart
サブエージェントが実行を開始したときに動作する。マッチャー入力はエージェントタイプ名であり、特定のサブエージェントタイプを対象にできる。
設定:
{
"hooks": {
"SubagentStart": [
{
"matcher": "code-review",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/subagent-init.sh"
}
]
}
]
}
}
SessionStart
セッション開始または再開時に動作する。環境変数を永続化できる。
マッチャー: startup、resume、clear、compact、fork
v2.1.214 の更新: フォークされたセッションは、以前の
"resume"ではなく"fork"をソースとして報告するようになった。
特別な機能: CLAUDE_ENV_FILE を使って環境変数を永続化できる(CwdChanged と FileChanged フックでも利用可能)。
#!/bin/bash
if [ -n "$CLAUDE_ENV_FILE" ]; then
echo 'export NODE_ENV=development' >> "$CLAUDE_ENV_FILE"
fi
exit 0
SessionEnd
セッション終了時に、クリーンアップや最終ロギングを実行する。終了をブロックすることはできない。
Reason フィールドの値:
clear- ユーザーがセッションをクリアlogout- ユーザーがログアウトprompt_input_exit- ユーザーがプロンプト入力で終了other- その他の理由
設定:
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/session-cleanup.sh\""
}
]
}
]
}
}
Notification イベント
通知イベントの更新済みマッチャー:
permission_prompt- 権限要求の通知idle_prompt- アイドル状態の通知auth_success- 認証成功elicitation_dialog- ユーザーへ表示されるダイアログ
コンポーネントスコープのフック
フックは、特定のコンポーネント(スキル、エージェント、コマンド)のフロントマターにアタッチできる。
SKILL.md、agent.md、command.md 内:
---
name: secure-operations
description: Perform operations with security checks
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/check.sh"
once: true # スキルのフロントマターのみ:最初の成功実行後に削除
---
サポートされるイベント: すべてのフックイベント。サブエージェントのフックはそのサブエージェントがアクティブな間だけ実行される(Stop → SubagentStop)。スキルのフックはスキル呼び出し時に登録され、セッション終了まで有効のまま残る。
これにより、フックを使用するコンポーネント内に直接定義でき、関連コードを近くにまとめられる。
サブエージェントフロントマター内のフック
サブエージェントのフロントマターで Stop フックを定義すると、自動的にそのサブエージェントにスコープされた SubagentStop フックに変換される。これにより、メインセッション停止時ではなく、その特定サブエージェント完了時にのみフックが発火することが保証される。
---
name: code-review-agent
description: Automated code review subagent
hooks:
Stop:
- hooks:
- type: prompt
prompt: "Verify the code review is thorough and complete."
# 上記の Stop フックは、このサブエージェント用の SubagentStop に自動変換される
---
PermissionRequest イベント
カスタム出力フォーマットで権限要求を処理する。
{
"hookSpecificOutput": {
"hookEventName": "PermissionRequest",
"decision": {
"behavior": "allow|deny",
"updatedInput": {},
"message": "Custom message",
"interrupt": false
}
}
}
フックの入出力
JSON 入力(stdin 経由)
すべてのフックは stdin 経由で JSON 入力を受け取る。
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript.jsonl",
"cwd": "/current/working/directory",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Write",
"tool_input": {
"file_path": "/path/to/file.js",
"content": "..."
},
"tool_use_id": "toolu_01ABC123...",
"agent_id": "agent-abc123",
"agent_type": "security-reviewer",
"worktree": "/path/to/worktree"
}
共通フィールド:
| フィールド | 説明 |
|---|---|
session_id |
セッションの一意識別子 |
transcript_path |
会話トランスクリプトファイルへのパス |
cwd |
カレント作業ディレクトリ |
hook_event_name |
フックを発火させたイベント名 |
agent_id |
このフックを実行しているエージェントの識別子 |
agent_type |
エージェント名(例:"Explore"、"security-reviewer")。セッションが --agent を使う場合か、フックがサブエージェント内で発火した場合にのみ存在する |
worktree |
エージェントが git ワークツリーで動作している場合のパス |
終了コード
| 終了コード | 意味 | 動作 |
|---|---|---|
| 0 | 成功 | 続行、JSON stdout を解析 |
| 2 | ブロッキングエラー | 操作をブロック、stderr をエラーとして表示 |
| その他 | 非ブロッキングエラー | 続行。トランスクリプトの <hook name> hook error 通知に stderr の最初の行が表示される |
JSON 出力(stdout、終了コード 0)
{
"continue": true,
"stopReason": "Optional message if stopping",
"suppressOutput": false,
"systemMessage": "Optional warning message",
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow",
"permissionDecisionReason": "File is in allowed directory",
"updatedInput": {
"file_path": "/modified/path.js"
}
}
}
環境変数
| 変数 | 利用可能なフック | 説明 |
|---|---|---|
CLAUDE_PROJECT_DIR |
すべてのフック | プロジェクトルートへの絶対パス |
CLAUDE_ENV_FILE |
SessionStart、CwdChanged、FileChanged | 環境変数を永続化するファイルパス |
CLAUDE_CODE_REMOTE |
すべてのフック | リモート環境で動作中なら "true" |
${CLAUDE_PLUGIN_ROOT} |
プラグインフック | プラグインディレクトリへのパス |
${CLAUDE_PLUGIN_DATA} |
プラグインフック | プラグインデータディレクトリへのパス |
CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS |
SessionEnd フック | SessionEnd フック向けのミリ秒単位タイムアウト設定(デフォルトを上書き) |
Prompt ベースのフック
Stop および SubagentStop イベントには、LLM ベースの評価を使用できる。
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Review if all tasks are complete. Return your decision.",
"timeout": 30
}
]
}
]
}
}
LLM レスポンススキーマ:
{
"ok": false,
"reason": "Tests were not run after the last edit"
}
ok: true でアクションを許可する。ok が false のときは reason が必須。
例
例 1:Bash コマンドバリデータ(PreToolUse)
ファイル: .claude/hooks/validate-bash.py
#!/usr/bin/env python3
import json
import sys
import re
BLOCKED_PATTERNS = [
(r"\brm\s+-rf\s+/", "Blocking dangerous rm -rf / command"),
(r"\bsudo\s+rm", "Blocking sudo rm command"),
]
def main():
input_data = json.load(sys.stdin)
tool_name = input_data.get("tool_name", "")
if tool_name != "Bash":
sys.exit(0)
command = input_data.get("tool_input", {}).get("command", "")
for pattern, message in BLOCKED_PATTERNS:
if re.search(pattern, command):
print(message, file=sys.stderr)
sys.exit(2) # 終了コード 2 = ブロッキングエラー
sys.exit(0)
if __name__ == "__main__":
main()
設定:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py\""
}
]
}
]
}
}
例 2:セキュリティスキャナ(PostToolUse)
ファイル: .claude/hooks/security-scan.py
#!/usr/bin/env python3
import json
import sys
import re
SECRET_PATTERNS = [
(r"password\s*=\s*['\"][^'\"]+['\"]", "Potential hardcoded password"),
(r"api[_-]?key\s*=\s*['\"][^'\"]+['\"]", "Potential hardcoded API key"),
]
def main():
input_data = json.load(sys.stdin)
tool_name = input_data.get("tool_name", "")
if tool_name not in ["Write", "Edit"]:
sys.exit(0)
tool_input = input_data.get("tool_input", {})
content = tool_input.get("content", "") or tool_input.get("new_string", "")
file_path = tool_input.get("file_path", "")
warnings = []
for pattern, message in SECRET_PATTERNS:
if re.search(pattern, content, re.IGNORECASE):
warnings.append(message)
if warnings:
output = {
"hookSpecificOutput": {
"hookEventName": "PostToolUse",
"additionalContext": f"Security warnings for {file_path}: " + "; ".join(warnings)
}
}
print(json.dumps(output))
sys.exit(0)
if __name__ == "__main__":
main()
例 3:コード自動フォーマット(PostToolUse)
ファイル: .claude/hooks/format-code.sh
#!/bin/bash
# stdin から JSON を読み取る
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | python3 -c "import sys, json; print(json.load(sys.stdin).get('tool_name', ''))")
FILE_PATH=$(echo "$INPUT" | python3 -c "import sys, json; print(json.load(sys.stdin).get('tool_input', {}).get('file_path', ''))")
if [ "$TOOL_NAME" != "Write" ] && [ "$TOOL_NAME" != "Edit" ]; then
exit 0
fi
# ファイル拡張子に基づいてフォーマット
case "$FILE_PATH" in
*.js|*.jsx|*.ts|*.tsx|*.json)
command -v prettier &>/dev/null && prettier --write "$FILE_PATH" 2>/dev/null
;;
*.py)
command -v black &>/dev/null && black "$FILE_PATH" 2>/dev/null
;;
*.go)
command -v gofmt &>/dev/null && gofmt -w "$FILE_PATH" 2>/dev/null
;;
esac
exit 0
例 4:プロンプトバリデータ(UserPromptSubmit)
ファイル: .claude/hooks/validate-prompt.py
#!/usr/bin/env python3
import json
import sys
import re
BLOCKED_PATTERNS = [
(r"delete\s+(all\s+)?database", "Dangerous: database deletion"),
(r"rm\s+-rf\s+/", "Dangerous: root deletion"),
]
def main():
input_data = json.load(sys.stdin)
prompt = input_data.get("prompt", "")
for pattern, message in BLOCKED_PATTERNS:
if re.search(pattern, prompt, re.IGNORECASE):
output = {
"decision": "block",
"reason": f"Blocked: {message}"
}
print(json.dumps(output))
sys.exit(0)
sys.exit(0)
if __name__ == "__main__":
main()
例 5:知的な Stop フック(Prompt ベース)
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Review if Claude completed all requested tasks. Check: 1) Were all files created/modified? 2) Were there unresolved errors? If incomplete, explain what's missing.",
"timeout": 30
}
]
}
]
}
}
例 6:コンテキスト使用量トラッカー(フックペア)
UserPromptSubmit(メッセージ前)と Stop(応答後)フックを組み合わせて、リクエストごとのトークン消費量を追跡する。
ファイル: .claude/hooks/context-tracker.py
#!/usr/bin/env python3
"""
Context Usage Tracker - Tracks token consumption per request.
Uses UserPromptSubmit as "pre-message" hook and Stop as "post-response" hook
to calculate the delta in token usage for each request.
Token Counting Methods:
1. Character estimation (default): ~4 chars per token, no dependencies
2. tiktoken (optional): More accurate (~90-95%), requires: pip install tiktoken
"""
import json
import os
import sys
import tempfile
# 設定
CONTEXT_LIMIT = 1000000 # Opus 5、Sonnet 5、Opus 4.8、Sonnet 4.6 は 1M、Haiku 4.5 は 200000(モデルに合わせて調整)
USE_TIKTOKEN = False # tiktoken がインストール済みなら True にして精度向上
def get_state_file(session_id: str) -> str:
"""メッセージ前のトークン数を保存する一時ファイルパスを取得(セッションごとに分離)。"""
return os.path.join(tempfile.gettempdir(), f"claude-context-{session_id}.json")
def count_tokens(text: str) -> int:
"""
テキスト内のトークン数をカウント。
tiktoken が利用可能なら p50k_base エンコーディングを使用(約 90〜95% の精度)、
それ以外は文字数による推定にフォールバック(約 80〜90% の精度)。
"""
if USE_TIKTOKEN:
try:
import tiktoken
enc = tiktoken.get_encoding("p50k_base")
return len(enc.encode(text))
except ImportError:
pass # 推定にフォールバック
# 文字ベースの推定:英語の場合、約 4 文字で 1 トークン
return len(text) // 4
def read_transcript(transcript_path: str) -> str:
"""トランスクリプトファイルから全コンテンツを読み込み連結。"""
if not transcript_path or not os.path.exists(transcript_path):
return ""
content = []
with open(transcript_path, "r") as f:
for line in f:
try:
entry = json.loads(line.strip())
# 様々なメッセージ形式からテキストコンテンツを抽出
if "message" in entry:
msg = entry["message"]
if isinstance(msg.get("content"), str):
content.append(msg["content"])
elif isinstance(msg.get("content"), list):
for block in msg["content"]:
if isinstance(block, dict) and block.get("type") == "text":
content.append(block.get("text", ""))
except json.JSONDecodeError:
continue
return "\n".join(content)
def handle_user_prompt_submit(data: dict) -> None:
"""メッセージ前フック:リクエスト前の現在のトークン数を保存。"""
session_id = data.get("session_id", "unknown")
transcript_path = data.get("transcript_path", "")
transcript_content = read_transcript(transcript_path)
current_tokens = count_tokens(transcript_content)
# 後で比較するため一時ファイルに保存
state_file = get_state_file(session_id)
with open(state_file, "w") as f:
json.dump({"pre_tokens": current_tokens}, f)
def handle_stop(data: dict) -> None:
"""応答後フック:トークンの差分を計算してレポート。"""
session_id = data.get("session_id", "unknown")
transcript_path = data.get("transcript_path", "")
transcript_content = read_transcript(transcript_path)
current_tokens = count_tokens(transcript_content)
# メッセージ前のカウントを読み込む
state_file = get_state_file(session_id)
pre_tokens = 0
if os.path.exists(state_file):
try:
with open(state_file, "r") as f:
state = json.load(f)
pre_tokens = state.get("pre_tokens", 0)
except (json.JSONDecodeError, IOError):
pass
# 差分を計算
delta_tokens = current_tokens - pre_tokens
remaining = CONTEXT_LIMIT - current_tokens
percentage = (current_tokens / CONTEXT_LIMIT) * 100
# 使用量をレポート
method = "tiktoken" if USE_TIKTOKEN else "estimated"
print(f"Context ({method}): ~{current_tokens:,} tokens ({percentage:.1f}% used, ~{remaining:,} remaining)", file=sys.stderr)
if delta_tokens > 0:
print(f"This request: ~{delta_tokens:,} tokens", file=sys.stderr)
def main():
data = json.load(sys.stdin)
event = data.get("hook_event_name", "")
if event == "UserPromptSubmit":
handle_user_prompt_submit(data)
elif event == "Stop":
handle_stop(data)
sys.exit(0)
if __name__ == "__main__":
main()
設定:
{
"hooks": {
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/context-tracker.py\""
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/context-tracker.py\""
}
]
}
]
}
}
動作の仕組み:
UserPromptSubmitがプロンプト処理前に発火し、現在のトークン数を保存Stopが Claude の応答後に発火し、差分を計算して使用量をレポート- 各セッションは一時ファイル名内の
session_idで分離
トークンカウント方式:
| 方式 | 精度 | 依存 | 速度 |
|---|---|---|---|
| 文字推定 | 約 80〜90% | なし | 1ms 未満 |
| tiktoken(p50k_base) | 約 90〜95% | pip install tiktoken |
10ms 未満 |
注意: Anthropic は公式のオフライントークナイザをリリースしていない。両方式とも近似である。トランスクリプトはユーザープロンプト、Claude の応答、ツール出力を含む。v2.1.300 以降は各 API リクエストのシステムプロンプト、ツール、パラメータも記録される。
例 7:自動モード権限のシード(一度限りのセットアップスクリプト)
~/.claude/settings.json に Claude Code の自動モードベースラインに相当する安全な権限ルール(デフォルトで 37 個、すべてのカテゴリフラグを有効にすると最大 63 個)をシードする一度限りのセットアップスクリプト。フックなし、将来の選択を覚えることもなし。1 回実行すれば良く、再実行しても安全(既存ルールはスキップ)。
ファイル: 09-advanced-features/setup-auto-mode-permissions.py
# 追加内容をプレビュー
python3 09-advanced-features/setup-auto-mode-permissions.py --dry-run
# 適用
python3 09-advanced-features/setup-auto-mode-permissions.py
追加される項目:
| カテゴリ | 例 |
|---|---|
| 組み込みツール | Read(*)、Grep(*)、Agent(*)、WebSearch(*) |
| オプションの編集(--include-edits) | Edit(*) |
| Git 読み取り | Bash(git status:*)、Bash(git log:*)、Bash(git diff:*) |
| Git 書き込み(ローカル) | Bash(git add:*)、Bash(git commit:*)、Bash(git checkout:*) |
| パッケージマネージャ | Bash(npm ci:*)、Bash(npm install:*)、Bash(pip install:*)、Bash(pip3 install:*) |
| ビルド・テスト | Bash(make:*)、Bash(pytest:*)、Bash(go test:*) |
| 一般的なシェル | Bash(ls:*)、Bash(cat:*)、Bash(find:*) |
| GitHub CLI | Bash(gh pr view:*)、Bash(gh pr create:*)、Bash(gh issue list:*) |
意図的に除外される項目(このスクリプトでは追加されない):
rm -rf、sudo、force push、git reset --hardDROP TABLE、kubectl delete、terraform destroynpm publish、curl | bash、本番デプロイ
例 8:学習進捗ロガー(SessionEnd)
各 Claude Code セッション終了時に、どのモジュールを学習したかをログに残す。進捗は
~/.claude-howto-progress.json に保存される。これはリポジトリ外のため、git pull 後も
上書きされず保持される。
なぜ Stop ではなく SessionEnd を使うのか?
Stop は Claude の すべての 応答後に発火する。SessionEnd はセッション終了時に
1 回だけ発火する。セッション終了時の日記エントリにはまさにこれが必要である。
なぜ対話プロンプトを使わないのか?
フックは制御端末なしで実行されるため /dev/tty は使えず、フックからユーザーに入力を求めることはできない。
モジュール(と任意のメモ)は Claude Code 起動時に環境変数で渡す(例:CLAUDE_HOWTO_MODULES=06,07 claude)。
ファイル: 06-hooks/session-end.sh
#!/usr/bin/env bash
# SessionEnd hook: records the modules worked on, then appends a session record
# to ~/.claude-howto-progress.json for persistent learning progress tracking.
PROGRESS_FILE="$HOME/.claude-howto-progress.json"
# ガード:このリポジトリ内でのみ実行
if [[ "$CLAUDE_PROJECT_DIR" != *"claude-howto"* ]] && [[ "$PWD" != *"claude-howto"* ]]; then
exit 0
fi
if [ ! -f "$PROGRESS_FILE" ]; then
echo '{"sessions":[]}' > "$PROGRESS_FILE"
fi
DATE=$(date +"%Y-%m-%d")
TIME=$(date +"%H:%M")
# Modules worked on, e.g. launch with: CLAUDE_HOWTO_MODULES=06,07 claude
# 01=Slash 02=Memory 03=Skills 04=Subagents 05=MCP
# 06=Hooks 07=Plugins 08=Checkpoints 09=Advanced 10=CLI
INPUT="${CLAUDE_HOWTO_MODULES:-}"
if [ -z "$INPUT" ] || [ "$INPUT" = "skip" ]; then
exit 0
fi
MODULES_JSON=$(echo "$INPUT" | tr ',' '\n' | tr -d ' ' | while read -r m; do
case "$m" in
01) echo '"01-slash-commands"' ;;
02) echo '"02-memory"' ;;
03) echo '"03-skills"' ;;
04) echo '"04-subagents"' ;;
05) echo '"05-mcp"' ;;
06) echo '"06-hooks"' ;;
07) echo '"07-plugins"' ;;
08) echo '"08-checkpoints"' ;;
09) echo '"09-advanced-features"' ;;
10) echo '"10-cli"' ;;
*) echo "\"$m\"" ;;
esac
done | paste -sd ',' -)
# Optional notes, e.g. CLAUDE_HOWTO_NOTES="tried the pre-commit example"
NOTES="${CLAUDE_HOWTO_NOTES:-}"
# NOTES を別の引数として渡し、Python に JSON エスケープを処理させる。
# これにより、ノートに引用符やバックスラッシュを含む場合でも JSON が壊れない。
python3 - "$PROGRESS_FILE" "$DATE" "$TIME" "$MODULES_JSON" "$NOTES" <<'PYEOF'
import sys, json
path, date, time_str, modules_raw, notes = sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5]
new_session = {
"date": date,
"time": time_str,
"modules": json.loads(f"[{modules_raw}]") if modules_raw else [],
"notes": notes,
}
with open(path, 'r') as f:
data = json.load(f)
data.setdefault('sessions', []).append(new_session)
with open(path, 'w') as f:
json.dump(data, f, indent=2)
PYEOF
echo " Saved to $PROGRESS_FILE"
インストール — settings.json 内のパスが解決されるよう、スクリプトをプロジェクトのフックディレクトリにコピー:
mkdir -p .claude/hooks
cp 06-hooks/session-end.sh .claude/hooks/
chmod +x .claude/hooks/session-end.sh
設定(.claude/settings.json 内):
{
"hooks": {
"SessionEnd": [
{
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/session-end.sh\"",
"timeout": 10
}
]
}
]
}
}
SessionEnd フックのデフォルト予算は 1.5 秒。フックごとに "timeout"(秒)を設定すると予算がそれに合わせて引き上げられる(最大 60 秒)。独自の timeout を持たないフックは 1.5 秒でキャンセルされる。
出力 — ~/.claude-howto-progress.json:
{
"sessions": [
{
"date": "2026-04-18",
"time": "14:32",
"modules": ["06-hooks", "07-plugins"],
"notes": "Installed first hook, tried pre-commit example"
}
]
}
示されている主要パターン:
| パターン | なぜ重要か |
|---|---|
SessionEnd イベント |
終了時に 1 回だけ発火 — Stop のように毎応答後に発火しない |
INPUT="${CLAUDE_HOWTO_MODULES:-}" |
フックには端末がない(/dev/tty は使えない)ため、入力は環境変数から受け取る |
"timeout": 10 |
SessionEnd フックは独自の timeout がなければ 1.5 秒でキャンセルされる |
$CLAUDE_PROJECT_DIR |
ポータブルなパス — /Users/yourname/... を絶対にハードコードしない |
| 先頭のガード句 | グローバル設定された場合に、無関係なプロジェクトでフックが動作するのを防ぐ |
| リポジトリ外に保存 | ~/ のパスは git pull でデータを上書きされず保持される |
コンパニオン:ビジュアル進捗トラッカー
10 モジュールすべてをカバーするチェックボックスベースの完全な UI を、ブラウザで開ける。
open local-progress/index.html
進捗はブラウザの localStorage に保存される(リポジトリ内のディスクには書き込まれない)。
Export ボタンでスナップショットを JSON として保存し、Import で復元できる。
プラグインフック
プラグインは hooks/hooks.json ファイルにフックを含めることができる。
ファイル: plugins/hooks/hooks.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "\"${CLAUDE_PLUGIN_ROOT}\"/scripts/validate.sh"
}
]
}
]
}
}
プラグインフック内の環境変数:
${CLAUDE_PLUGIN_ROOT}- プラグインディレクトリへのパス${CLAUDE_PLUGIN_DATA}- プラグインデータディレクトリへのパス
これにより、プラグインがカスタム検証や自動化フックを含められるようになる。
MCP ツールフック
MCP ツールは mcp__<server>__<tool> パターンに従う。
{
"hooks": {
"PreToolUse": [
{
"matcher": "mcp__memory__.*",
"hooks": [
{
"type": "command",
"command": "echo '{\"systemMessage\": \"Memory operation logged\"}'"
}
]
}
]
}
}
セキュリティに関する考慮事項
免責事項
自己責任で使用すること: フックは任意のシェルコマンドを実行する。以下については利用者が単独で責任を負う。
- 設定したコマンド
- ファイルアクセス/変更権限
- データ損失やシステム障害の可能性
- 本番運用前に安全な環境でフックをテストすること
セキュリティ上の注意点
- ワークスペースの信頼が必要:
statusLineおよびfileSuggestionのフック出力コマンドは、有効化前にワークスペースの信頼を受け入れる必要がある。 - HTTP フックと環境変数: HTTP フックはヘッダー値で環境変数の補間を使うために明示的な
allowedEnvVarsリストを必要とする。これにより、機密の環境変数がリモートエンドポイントへ意図せず漏洩することを防ぐ。 - 管理対象設定の階層:
disableAllHooks設定は管理対象設定の階層を尊重するようになった。つまり、組織レベルの設定でフック無効化を強制でき、個別ユーザーが上書きできない。 - PowerShell 自動承認(v2.1.119): PowerShell ツールコマンドは権限モードで Bash と同様に自動承認可能になった。Windows ユーザーが PowerShell バックエンドのシェルツールで Claude Code を実行する際の同等性が確保された。
ベストプラクティス
| 推奨 | 非推奨 |
|---|---|
| すべての入力を検証・サニタイズ | 入力データを盲目的に信用 |
シェル変数を引用符で囲む:"$VAR" |
引用符なし:$VAR |
パストラバーサル(..)をブロック |
任意のパスを許可 |
$CLAUDE_PROJECT_DIR を使った絶対パス |
パスのハードコード |
機密ファイル(.env、.git/、鍵)をスキップ |
すべてのファイルを処理 |
| まずフックを単独でテスト | 未テストのフックをデプロイ |
HTTP フックには明示的な allowedEnvVars を使う |
webhook へすべての環境変数を露出 |
デバッグ
デバッグモードの有効化
詳細なフックログを得るため、Claude をデバッグフラグ付きで実行する。
claude --debug
Verbose モード
Claude Code 内で Ctrl+O を押して verbose モードを有効化し、フック実行の進捗を確認する。
フックを単独でテスト
# サンプル JSON 入力でテスト
echo '{"tool_name": "Bash", "tool_input": {"command": "ls -la"}}' | python3 .claude/hooks/validate-bash.py
# 終了コードを確認
echo $?
完全な設定例
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py\"",
"timeout": 10
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/format-code.sh\"",
"timeout": 30
},
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/security-scan.py\"",
"timeout": 10
}
]
}
],
"UserPromptSubmit": [
{
"hooks": [
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate-prompt.py\""
}
]
}
],
"SessionStart": [
{
"matcher": "startup",
"hooks": [
{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/session-init.sh\""
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Verify all tasks are complete before stopping.",
"timeout": 30
}
]
}
]
}
}
フック実行の詳細
| 項目 | 動作 |
|---|---|
| タイムアウト | command/http/mcp_tool はデフォルト 600 秒(prompt は 30 秒、agent は 60 秒)、フックごとに設定可能 |
| 並列化 | マッチしたフックはすべて並列実行。v2.1.312 以降、同時に実行される prompt/agent フックはセッションあたり最大 24 個(サブエージェントを含む)に加え、イベントのタイムアウトより長く待機したものが最大 12 個で、残りは順番を待つ(v2.1.302〜v2.1.311 では 1 つのイベントにつき最大 12 個) |
| 重複排除 | 同一のフックコマンドは重複排除される |
| 環境 | カレントディレクトリで Claude Code の環境のもと実行 |
トラブルシューティング
フックが実行されない
- JSON 設定の構文が正しいことを確認
- マッチャーパターンがツール名にマッチするか確認
- スクリプトが存在し実行可能であること:
chmod +x script.sh claude --debugでフック実行ログを確認- フックが(コマンド引数ではなく)stdin から JSON を読み込んでいるか確認
フックが想定外にブロックする
- サンプル JSON でフックをテスト:
echo '{"tool_name": "Write", ...}' | ./hook.py - 終了コードを確認:許可は 0、ブロックは 2
- stderr 出力を確認(終了コード 2 のときに表示される)
JSON パースエラー
- 必ず stdin から読み込み、コマンド引数を使わない
- 適切な JSON パースを使用(文字列操作ではなく)
- 欠落フィールドを安全に処理
インストール
Step 1:フックディレクトリの作成
mkdir -p ~/.claude/hooks
Step 2:フックの例をコピー
cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
Step 3:設定ファイルでの設定
~/.claude/settings.json または .claude/settings.json を上記のフック設定で編集する。
関連概念
- チェックポイントと巻き戻し - 会話状態の保存と復元
- スラッシュコマンド - カスタムスラッシュコマンドの作成
- スキル - 再利用可能な自律機能
- サブエージェント - 委譲タスクの実行
- プラグイン - 拡張機能のバンドルパッケージ
- 高度な機能 - 高度な Claude Code 機能の探索
追加リソース
- Official Hooks Documentation - 完全なフックリファレンス
- CLI Reference - コマンドラインインターフェースのドキュメント
- メモリガイド - 永続的コンテキストの設定
最終更新: 2026 年 11 月 1 日 Claude Code バージョン: 2.1.316 情報源:
- https://code.claude.com/docs/en/hooks
- https://code.claude.com/docs/en/plugins/manifest-reference#quoting-and-path-separators
- https://code.claude.com/docs/en/permissions
- https://code.claude.com/docs/en/tools-reference#task-tool-availability
- https://code.claude.com/docs/en/changelog
- https://github.com/anthropics/claude-code/releases/tag/v2.1.118
- https://github.com/anthropics/claude-code/releases/tag/v2.1.119
- https://code.claude.com/docs/en/hooks#pretooluse
- https://code.claude.com/docs/en/hooks#pretooluse-decision-control
- https://code.claude.com/docs/en/hooks#hook-lifecycle
- https://code.claude.com/docs/en/hooks#userpromptsubmit-input
- https://code.claude.com/docs/en/changelog#2-1-299
- https://code.claude.com/docs/en/changelog#2-1-300
- https://code.claude.com/docs/en/hooks#defer-a-tool-call-for-later
- https://code.claude.com/docs/en/changelog#2-1-312 対応モデル: Claude Fable 5.2、Claude Fable 5.1、Claude Fable 5、Claude Opus 5.5、Claude Opus 5、Claude Sonnet 5.5、Claude Sonnet 5、Claude Sonnet 4.6、Claude Opus 4.8、Claude Haiku 5.5、Claude Haiku 4.5