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. Вони забезпечують автоматизацію, валідацію, управління дозволами та кастомні робочі процеси.
Огляд
Хуки — це автоматичні дії (shell-команди, HTTP-вебхуки, LLM-промпти або оцінки субагентів), що виконуються автоматично при виникненні конкретних подій у Claude Code. Вони отримують JSON-вхід і повідомляють результати через коди виходу та JSON-вивід.
Ключові можливості:
- Автоматизація на основі подій
- Введення/виведення на основі JSON
- Підтримка типів хуків: command, prompt, HTTP та agent
- Відповідність шаблонам (pattern matching) для хуків, специфічних для інструментів
Конфігурація
Хуки налаштовуються у файлах налаштувань з конкретною структурою:
~/.claude/settings.json— налаштування користувача (усі проєкти).claude/settings.json— налаштування проєкту (спільні, комітяться).claude/settings.local.json— локальні налаштування проєкту (не комітяться)- Керована політика (Managed policy) — загальноорганізаційні налаштування
hooks/hooks.jsonплагіна — хуки з областю дії плагіна- Frontmatter навичок/агентів — хуки часу життя компонентів
Базова структура конфігурації
{
"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" (вебхук), "mcp_tool" (виклик MCP-інструмента, v2.1.118+) або "agent" (субагент) |
"command" |
command |
Shell-команда для виконання | "$CLAUDE_PROJECT_DIR/.claude/hooks/format.sh" |
timeout |
Необовʼязковий таймаут у секундах. За замовчуванням: 600 для command/http/mcp_tool, 30 для prompt, 60 для agent. | 30 |
once |
Якщо true, хук видаляється після першого успішного запуску (невдалі, заблоковані чи прострочені запуски його залишають). Лише у frontmatter навички; ігнорується в settings і frontmatter агента |
true |
async |
Якщо true, виконується у фоні без блокування |
true |
asyncRewake |
Якщо true, виконується у фоні та будить Claude при коді виходу 2. Неявно вмикає async. |
true |
shell |
Приймає "bash" або "powershell". За замовчуванням "bash", або "powershell" у Windows, якщо Git Bash не встановлено. |
"bash" |
statusMessage |
Власне повідомлення індикатора, що показується під час роботи хука | "Форматування…" |
Примітка: Деякі події знижують типовий таймаут.
UserPromptSubmitзнижує типове значення для command, http і mcp_tool до 30 секунд, аMessageDisplay— до 10 секунд. ХукиSessionEndмають спільний бюджет 1,5 секунди; якщо у ваших налаштуваннях указано довшийtimeoutдля окремого хука, Claude Code піднімає бюджет відповідно, до 60 секунд.
Шаблони matcher
| Шаблон | Опис | Приклад |
|---|---|---|
| Точний рядок | Відповідає конкретному інструменту | "Write" |
| Regex-шаблон | Відповідає кільком інструментам | "Edit|Write" |
| Підстановочний знак | Відповідає всім інструментам | "*" або "" |
| MCP-інструменти | Шаблон сервера та інструмента | "mcp__memory__.*" |
Значення matcher для InstructionsLoaded:
| Значення matcher | Опис |
|---|---|
session_start |
Інструкції завантажені при запуску сесії |
nested_traversal |
Інструкції завантажені при обході вкладених каталогів |
path_glob_match |
Інструкції завантажені через відповідність glob-шаблону шляху |
Типи хуків
Claude Code підтримує чотири типи хуків:
Command-хуки
Тип за замовчуванням. Виконує shell-команду та комунікує через JSON stdin/stdout і коди виходу.
{
"type": "command",
"command": "python3 \"$CLAUDE_PROJECT_DIR/.claude/hooks/validate.py\"",
"timeout": 60
}
HTTP-хуки
Додано у v2.1.63.
Віддалені вебхук-ендпоінти, які отримують той самий JSON-вхід, що й command-хуки. HTTP-хуки надсилають POST JSON на URL і отримують JSON-відповідь. HTTP-хуки маршрутизуються через пісочницю (sandbox), коли вона увімкнена. Інтерполяція змінних оточення у значення заголовків вимагає явного списку allowedEnvVars з міркувань безпеки.
{
"hooks": {
"PostToolUse": [{
"matcher": "Write",
"hooks": [{
"type": "http",
"url": "https://my-webhook.example.com/hook"
}]
}]
}
}
Ключові властивості:
"type": "http"— ідентифікує як HTTP-хук"url"— URL ендпоінту вебхука- Маршрутизується через sandbox, коли sandbox увімкнено
- Вимагає явного списку
allowedEnvVarsдля будь-якої інтерполяції змінних оточення у значенняхheaders
MCP tool-хуки
Додано у v2.1.118.
Тип mcp_tool викликає налаштований MCP-інструмент напряму; конфігурація посилається на ім'я MCP-сервера та інструмента, а не на shell-команду чи URL. Корисно, коли логіка валідації або реакції вже живе в налаштованому вами MCP-сервері.
{
"matcher": "Edit",
"hooks": [{
"type": "mcp_tool",
"server": "my-mcp-server",
"tool": "validate_edit"
}]
}
Ключові властивості:
"type": "mcp_tool"— ідентифікує як MCP tool-хук"server"— ім'я налаштованого MCP-сервера"tool"— ім'я інструмента, який слід викликати на цьому сервері
Prompt-хуки
Промпти, оцінювані LLM, де вміст хука є промптом, який оцінює Claude. Переважно використовуються з подіями Stop та SubagentStop для інтелектуальної перевірки завершення завдань.
{
"type": "prompt",
"prompt": "Evaluate if Claude completed all requested tasks.",
"timeout": 30
}
LLM оцінює промпт і повертає структуроване рішення (деталі див. у Хуки на основі промптів).
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— їхня відповідь ніколи не могла дозволити чи відхилити запит. Використовуйте там хук типу command або HTTP, що повертає об'єкт рішення (ok: falseprompt-хука не діє наPermissionRequest).
Ключові властивості:
"type": "agent"— ідентифікує як agent-хук"prompt"— опис завдання для субагента- Агент може використовувати інструменти (Read, Grep, Bash тощо) для оцінки
- Повертає структуроване рішення, аналогічне prompt-хукам
Події хуків
Claude Code підтримує 33 події хуків:
| Подія | Коли спрацьовує | Вхід matcher | Може блокувати | Типове використання |
|---|---|---|---|---|
| SessionStart | Початок/відновлення/очищення/компакція/форк сесії | startup/resume/clear/compact/fork | Ні | Налаштування середовища |
| Setup | --init-only або --init/--maintenance з -p (підготовка 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 | Неактивність учасника Agent Teams | (немає) | Так | Координація учасників |
| TaskCompleted | Завдання позначено як виконане | (немає) | Так | Дії після завершення завдання |
| TaskCreated | Завдання створене через TaskCreate | (немає) | Так | Відстеження завдань, логування |
| ConfigChange | Зміна файлу конфігурації | Джерело конфігурації (user_settings/project_settings/local_settings/policy_settings/skills) |
Так (крім policy) | Реакція на оновлення конфігурації |
| CwdChanged | Зміна робочого каталогу | (немає) | Ні | Налаштування для каталогу |
| DirectoryAdded | Новий робочий каталог зареєстровано під час сесії через /add-dir або control-запит 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 | Створення робочого дерева (worktree) | (немає) | Так (повернення шляху) | Ініціалізація worktree |
| WorktreeRemove | Видалення робочого дерева | (немає) | Так (ненульовий код виходу зриває видалення) | Очищення worktree |
| Elicitation | MCP-сервер запитує введення користувача | Назва MCP-сервера | Так | Валідація введення |
| ElicitationResult | Відповідь користувача на elicitation | Назва MCP-сервера | Так | Обробка відповіді |
| SessionEnd | Завершення сесії | Причина завершення (clear/resume/logout/prompt_input_exit/other) |
Ні | Очищення, фінальне логування |
TaskCreatedіTaskCompletedпотребують увімкнених todo-інструментів (v2.1.233). Ці події виникають від todo / task-tracking інструментів (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, щоб повернути їх.
PreToolUse
Запускається після створення параметрів інструмента Claude і перед обробкою. Використовується для валідації або модифікації вхідних даних інструмента.
Конфігурація:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate-bash.py"
}
]
}
]
}
}
Типові matcher: 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: Пояснення рішення. Показується користувачеві (не Claude) для"ask"; показується Claude для"deny"; для"allow"та"defer"записується лише в журнал налагодження (debug log)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
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). Підтримують оцінку на основі промптів для інтелектуальної перевірки завершення завдань.
Додаткове поле введення: Обидва хуки Stop та SubagentStop отримують поле last_assistant_message у JSON-вході, що містить останнє повідомлення від Claude або субагента перед зупинкою. Це корисно для оцінки завершення завдання.
Конфігурація:
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Evaluate if Claude completed all requested tasks.",
"timeout": 30
}
]
}
]
}
}
SubagentStart
Запускається при початку виконання субагента. Вхід matcher — назва типу агента, що дозволяє хукам націлюватися на конкретні типи субагентів.
Конфігурація:
{
"hooks": {
"SubagentStart": [
{
"matcher": "code-review",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/subagent-init.sh"
}
]
}
]
}
}
SessionStart
Запускається при старті або відновленні сесії. Може зберігати змінні оточення.
Matcher: startup, resume, clear, compact, fork
Оновлення v2.1.214: сесії, створені через форк, тепер повідомляють джерело
"fork"замість попереднього"resume".
Спеціальна можливість: Використовуйте 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
Оновлені matcher для подій сповіщень:
permission_prompt— сповіщення про запит дозволуidle_prompt— сповіщення про стан простоюauth_success— успішна автентифікаціяelicitation_dialog— діалог, показаний користувачу
Хуки з областю дії компонентів
Хуки можна прикріплювати до конкретних компонентів (навички, агенти, команди) у їхньому frontmatter:
У 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 # Лише frontmatter навички: видаляється після першого успішного запуску
---
Підтримувані події: усі події хуків. Хуки субагента працюють лише поки субагент активний (Stop → SubagentStop); хуки навички реєструються під час її виклику й лишаються активними до кінця сесії.
Це дозволяє визначати хуки безпосередньо в компоненті, що їх використовує, зберігаючи повʼязаний код разом.
Хуки у frontmatter субагента
Коли хук Stop визначений у frontmatter субагента, він автоматично перетворюється на хук 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)
Усі хуки отримують JSON-вхід через stdin:
{
"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 worktree, якщо агент працює в ньому |
Коди виходу
| Код виходу | Значення | Поведінка |
|---|---|---|
| 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"
}
}
}
retry(PermissionDenied): Використайте JSONhookSpecificOutput.retry: true, щоб повідомити модель, що вона може повторити відхилений виклик інструмента.
Змінні оточення
| Змінна | Доступність | Опис |
|---|---|---|
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 (перевизначає стандартний) |
Хуки на основі промптів
Для подій 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 дозволяє дію; reason обов'язковий, коли ok дорівнює false.
Приклади
Приклад 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
# Читання JSON з stdin
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-хук (на основі промпта)
{
"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 — Відстежує споживання токенів на запит.
Використовує UserPromptSubmit як хук "перед повідомленням" і Stop як хук "після відповіді"
для обчислення дельти використання токенів для кожного запиту.
Методи підрахунку токенів:
1. Оцінка за символами (за замовчуванням): ~4 символи на токен, без залежностей
2. tiktoken (необовʼязково): Точніший (~90-95%), потребує: pip install tiktoken
"""
import json
import os
import sys
import tempfile
# Конфігурація
CONTEXT_LIMIT = 1000000 # 1M у Opus 5, Sonnet 5, Opus 4.8, Sonnet 4.6; 200000 у Haiku 4.5 (налаштуйте для вашої моделі)
USE_TIKTOKEN = False # Встановіть True, якщо tiktoken встановлено для кращої точності
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 символи на токен для англійської
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% | Немає | <1мс |
| tiktoken (p50k_base) | ~90-95% | pip install tiktoken |
<10мс |
Примітка: Anthropic не випустили офіційний офлайн-токенізатор. Обидва методи є наближеннями. Транскрипт включає промпти користувача, відповіді Claude та вивід інструментів; з v2.1.300 він також записує системний промпт, інструменти й параметри кожного API-запиту.
Приклад 7: Початкове налаштування дозволів Auto-Mode (одноразовий скрипт)
Одноразовий скрипт налаштування, що додає до ~/.claude/settings.json безпечні правила дозволів, еквівалентні базовому набору auto-mode Claude Code — 37 типово, до 63 з усіма прапорцями категорій — без жодного хука, без запамʼятовування майбутніх виборів. Запустіть один раз; безпечно для повторного запуску (пропускає правила, що вже присутні).
Файл: 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:*) |
| Загальні shell-команди | 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, деплої на продакшн
Хуки плагінів
Плагіни можуть включати хуки у файлі 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\"}'"
}
]
}
]
}
}
Міркування безпеки
Застереження
ВИКОРИСТОВУЙТЕ НА ВЛАСНИЙ РИЗИК: Хуки виконують довільні shell-команди. Ви несете повну відповідальність за:
- Команди, які ви налаштовуєте
- Дозволи на доступ/модифікацію файлів
- Потенційну втрату даних або пошкодження системи
- Тестування хуків у безпечних середовищах перед використанням на продакшні
Примітки щодо безпеки
- Потрібна довіра до робочого простору: Команди виводу хуків
statusLineтаfileSuggestionтепер вимагають прийняття довіри до робочого простору перед набранням чинності. - HTTP-хуки та змінні оточення: HTTP-хуки вимагають явного списку
allowedEnvVarsдля використання інтерполяції змінних оточення у значеннях заголовків. Це запобігає випадковому витоку чутливих змінних оточення на віддалені ендпоінти. - Ієрархія керованих налаштувань: Налаштування
disableAllHooksтепер поважає ієрархію керованих налаштувань, тобто налаштування рівня організації можуть примусово вимкнути хуки, що не може бути перевизначено окремими користувачами.
Найкращі практики
| Рекомендовано | Не рекомендовано |
|---|---|
| Валідувати та санітизувати всі вхідні дані | Довіряти вхідним даним сліпо |
Екранувати змінні shell: "$VAR" |
Використовувати без лапок: $VAR |
Блокувати обхід шляху (..) |
Дозволяти довільні шляхи |
Використовувати абсолютні шляхи з $CLAUDE_PROJECT_DIR |
Жорстко кодувати шляхи |
Пропускати чутливі файли (.env, .git/, ключі) |
Обробляти всі файли |
| Тестувати хуки окремо спочатку | Деплоїти неперевірені хуки |
Використовувати явний allowedEnvVars для HTTP-хуків |
Відкривати всі змінні оточення для вебхуків |
Налагодження
Увімкнення режиму налагодження
Запустіть Claude з прапорцем debug для детальних журналів хуків:
claude --debug
Verbose-режим
Використовуйте Ctrl+O в Claude Code для увімкнення 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
}
]
}
]
}
}
Деталі виконання хуків
| Аспект | Поведінка |
|---|---|
| Таймаут | 60 секунд за замовчуванням, налаштовується для кожної команди |
| Паралелізація | Усі відповідні хуки запускаються паралельно; починаючи з v2.1.312, одночасно виконується не більше 24 prompt- або agent-хуків на сесію (включно із субагентами), плюс не більше 12 тих, що чекали довше за таймаут своєї події, решта чекає своєї черги (v2.1.302–v2.1.311: не більше 12 однієї події) |
| Дедуплікація | Ідентичні команди хуків дедуплікуються |
| Середовище | Запускається в поточному каталозі з середовищем Claude Code |
Усунення несправностей
Хук не виконується
- Перевірте правильність синтаксису JSON-конфігурації
- Переконайтеся, що шаблон matcher відповідає назві інструмента
- Перевірте існування та виконуваність скрипта:
chmod +x script.sh - Запустіть
claude --debugдля перегляду журналів виконання хуків - Переконайтеся, що хук читає JSON з stdin (не з аргументів команди)
Хук блокує несподівано
- Тестуйте хук зі зразковим JSON:
echo '{"tool_name": "Write", ...}' | ./hook.py - Перевірте код виходу: має бути 0 для дозволу, 2 для блокування
- Перевірте вивід stderr (показується при коді виходу 2)
Помилки парсингу JSON
- Завжди читайте з stdin, не з аргументів команди
- Використовуйте належний парсинг JSON (не маніпуляцію рядками)
- Обробляйте відсутні поля коректно
Встановлення
Крок 1: Створення каталогу хуків
mkdir -p ~/.claude/hooks
Крок 2: Копіювання прикладів хуків
cp 06-hooks/*.sh ~/.claude/hooks/
chmod +x ~/.claude/hooks/*.sh
Крок 3: Налаштування у settings
Відредагуйте ~/.claude/settings.json або .claude/settings.json з конфігурацією хуків, показаною вище.
Повʼязані концепції
- Контрольні точки та відкат — збереження та відновлення стану розмови
- Слеш-команди — створення кастомних слеш-команд
- Навички — повторно використовувані автономні можливості
- Субагенти — делеговане виконання завдань
- Плагіни — обʼєднані пакети розширень
- Розширені функції — дослідження розширених можливостей Claude Code
Додаткові ресурси
- Офіційна документація хуків — повний довідник хуків
- Довідник CLI — документація інтерфейсу командного рядка
- Посібник з памʼяті — конфігурація постійного контексту
Останнє оновлення: 1 листопада 2026 Версія 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/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