[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79QFK3D071NF1QRNQD988XG":3,"skill-same:01M79QFK3D071NF1QRNQD988XG":120},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":13,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M79QFK3D071NF1QRNQD988XG","hook-development",null,"Creates and configures event-driven hooks in Claude Code plugins. Covers hooks.json structure, hook types (command, http, mcp_tool, prompt, agent), all hook events (PreToolUse, PostToolUse, Stop, SessionStart, UserPromptSubmit, etc.), stdin data parsing, nested JSON structure, exit code semantics, matchers, and production validation. Use when adding hooks to a plugin, writing hooks.json, implementing PreToolUse validation, blocking dangerous commands, running auto-format on file writes, enforcing completion standards with Stop hooks, loading session context at startup, automating responses to Claude Code events, or writing\u002Fconfiguring any Claude Code hook event. For reviewing an existing hook's quality\u002Fsafety before deployment, use the hook-reviewer agent instead.","AndreHahm\u002Fandres-cc-marketplace","AndreHahm","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F80748019?v=4","01M79N2VZJT9MAJ7K695C9VXQ4","01M79N2W06PFX8BSCQ592M8K8K",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: hook-development\ndescription: >-\n  Creates and configures event-driven hooks in Claude Code plugins. Covers\n  hooks.json structure, hook types (command, http, mcp_tool, prompt, agent),\n  all hook events (PreToolUse, PostToolUse, Stop, SessionStart, UserPromptSubmit,\n  etc.), stdin data parsing, nested JSON structure, exit code semantics, matchers,\n  and production validation. Use when adding hooks to a plugin, writing hooks.json,\n  implementing PreToolUse validation, blocking dangerous commands, running\n  auto-format on file writes, enforcing completion standards with Stop hooks,\n  loading session context at startup, automating responses to Claude Code events,\n  or writing\u002Fconfiguring any Claude Code hook event. For reviewing an existing\n  hook's quality\u002Fsafety before deployment, use the hook-reviewer agent instead.\nallowed-tools: Read Write Edit Glob Bash(jq:*) Bash(scripts\u002Fvalidate-hook-schema.sh:*) Bash(scripts\u002Ftest-hook.sh:*) Bash(scripts\u002Fhook-linter.sh:*) Bash(shellcheck:*) Bash(claude:*) Skill\n---\n\n# Hook Development for Claude Code Plugins\n\nHooks are event-driven automation scripts that execute in response to Claude Code events. Use them to validate operations, enforce policies, add context, and integrate external tools.\n\n**Key capabilities:** validate before tool runs (PreToolUse), react to results (PostToolUse), enforce completion standards (Stop), load project context (SessionStart).\n\n## Quick Start\n\n1. **Detect project type** — check for `.claude-plugin\u002Fplugin.json`; if present, hooks go to `hooks\u002Fhooks.json`; otherwise to `.claude\u002Fhooks.json`\n2. **Choose an event** — `PreToolUse` (validate before), `PostToolUse` (react after), `Stop` (completion check), `SessionStart` (context loading)\n3. **Pick a hook type** — prompt (LLM reasoning), command (deterministic bash), or agent (requires file inspection)\n4. **Write configuration** — use the nested `\"hooks\": [...]` array (see CRITICAL section below)\n5. **For command hooks** — read event data from stdin, not environment variables (see CRITICAL section below)\n6. **Validate** — run `scripts\u002Fvalidate-hook-schema.sh` and `shellcheck` on scripts\n7. **Test** — use `scripts\u002Ftest-hook.sh` with sample input, then `claude --debug` live\n\n*For the full 13-step workflow with tooling auto-detection, lint, and documentation steps, see [Implementation Workflow](#implementation-workflow) below.*\n\n## When to Use\n\n- Adding validation before tool calls (file writes, bash commands, API calls)\n- Enforcing project policies at runtime without editing every command\n- Loading project context or env vars at session start\n- Verifying Claude completes tasks fully before stopping\n- Logging, alerting, or auditing tool usage\n\n## When NOT to Use\n\n- For one-time prompts — use slash commands instead\n- For global config changes — modify `settings.json` directly\n- Never edit `~\u002F.claude\u002Fplugins\u002Fcache\u002F` — those are read-only installed copies\n- Reviewing an existing hook's quality\u002Fsafety before deployment → use the `hook-reviewer` agent instead\n\n## Finding-ID Fix Mode\n\nWhen invoked with a bounded finding-ID list (e.g. from `plugin-lifecycle-downstream`'s Phase\n4\u002F6\u002F8), follow `plugin-rulebook\u002Freferences\u002Ffinding-id-fix-contract.md` instead of this\nskill's normal open-ended workflow: touch only the named findings' files, report per-ID\n`applied`\u002F`deferred`\u002F`failed` status, and never mark a fix verified — that stays the\noriginating checker's job.\n\n---\n\n## CRITICAL: Hook File Location\n\n**Most common mistake:** placing hooks in `.claude-plugin\u002Fhooks.json` (WRONG).\n\n✅ **Correct locations:**\n- **Plugin projects** (has `.claude-plugin\u002Fplugin.json`): `hooks\u002Fhooks.json` at plugin root\n- **Regular projects** (no `.claude-plugin\u002F`): `.claude\u002Fhooks.json`\n\n❌ **Wrong:** `.claude-plugin\u002Fhooks.json` — only `plugin.json` belongs in `.claude-plugin\u002F`\n\n**Auto-detect:** check for `.claude-plugin\u002Fplugin.json`; its presence means plugin project. If hooks aren't firing, check file location first.\n\n---\n\n## CRITICAL: Command Hooks Receive Data via Stdin\n\n**The #1 reason command hooks silently do nothing:** expecting environment variables instead of reading stdin.\n\n❌ **WRONG — env var substitution does NOT work:**\n```json\n{ \"env\": {\"FILE_PATH\": \"${arguments.file_path}\"} }\n```\n\n✅ **CORRECT — read ALL event data from stdin as JSON:**\n```bash\n#!\u002Fbin\u002Fbash\nINPUT=$(cat)                                          # Read all event data from stdin\nFILE_PATH=$(echo \"$INPUT\" | jq -r '.tool_input.file_path')\nTOOL_NAME=$(echo \"$INPUT\" | jq -r '.tool_name')\n```\n\nSee `references\u002Fcommand-hook-input-parsing.md` for correct field paths per event type.\n\n---\n\n## CRITICAL: Nested \"hooks\" Array JSON Structure\n\n**The #1 JSON mistake:** forgetting the nested `\"hooks\": [...]` array inside each event matcher.\n\n✅ **CORRECT — required for all hooks:**\n```json\n{\n  \"hooks\": {\n    \"EventName\": [\n      {\n        \"matcher\": \"regex-pattern\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fscript.sh\",\n            \"timeout\": 5,\n            \"onError\": \"warn\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n❌ **WRONG — produces \"Expected array, but received undefined\":**\n```json\n{\n  \"hooks\": {\n    \"EventName\": [{ \"type\": \"command\", \"command\": \"...\" }]\n  }\n}\n```\n\nEvery hook action (command, http, mcp_tool, prompt, agent) **must** be inside a `\"hooks\": [...]` array.\n\n---\n\n## Hook Types\n\nFive action types: `prompt` (LLM-driven, flexible), `command` (bash, deterministic), `agent` (multi-turn, file inspection), `http` (webhook), `mcp_tool` (calls an installed MCP server tool). Full field reference and JSON example per type: `references\u002Fhook-types.md` (`mcp_tool` has its own dedicated reference, `references\u002Fmcp-tools.md`).\n\n**Type decision:**\n\n| Use Case | Type |\n|---|---|\n| Fast deterministic check (lint, file size, path regex) | command |\n| Intelligent reasoning (context-aware, needs judgment) | prompt |\n| Verification requiring file inspection or test runs | agent |\n| Complex branches or state checks | command |\n| Call an installed MCP server tool | mcp_tool |\n| Notify or delegate to an external system | http |\n\nNot every type is valid for every event (e.g. `SessionStart` supports only `command` and `mcp_tool`) — validate the type\u002Fevent combination, not just each independently. Full compatibility matrix: `references\u002Fevent-reference.md`.\n\n---\n\n## Hook Configuration Formats\n\n### Plugin Format (`hooks\u002Fhooks.json`)\n\n```json\n{\n  \"description\": \"Optional description\",\n  \"hooks\": {\n    \"PreToolUse\": [...],\n    \"Stop\": [...],\n    \"SessionStart\": [...]\n  }\n}\n```\n\n### Settings Format (`.claude\u002Fsettings.json` or `.claude\u002Fhooks.json`)\n\n```json\n{\n  \"PreToolUse\": [...],\n  \"Stop\": [...],\n  \"SessionStart\": [...]\n}\n```\n\nEvents go directly at the top level — no wrapper object. Plugin hooks merge with user hooks and run in parallel. Settings format also supports a top-level `disableAllHooks` boolean key to disable every configured hook at once — verify whether this applies to plugin `hooks\u002Fhooks.json` too before relying on it there.\n\n`hooks\u002Fhooks.json` has only two top-level keys: `description` and `hooks` — verify this against the current platform schema before enforcing it. Shared team hooks belong in `.claude\u002Fsettings.json` (checked into version control) — never in `.claude\u002Fsettings.local.json`, which is personal and gitignored.\n\n---\n\n## Hook Handler Fields\n\nAll handlers:\n\n| Field | Required | Description |\n|---|---|---|\n| `type` | yes | `\"command\"`, `\"http\"`, `\"mcp_tool\"`, `\"prompt\"`, or `\"agent\"` |\n| `timeout` | no | Seconds before canceling — except an async command hook (`async: true`) without `asyncRewake: true`, where `timeout` is not enforced (see Pattern 9 in `references\u002Fadvanced-hooks.md`). `asyncRewake: true` still runs in the background but keeps timeout enforcement. Defaults: command=600, prompt=30, agent=60. Flag values outside 1-600s as suspect |\n| `statusMessage` | no | Custom spinner text while hook runs |\n| `once` | no | Run once per session then auto-remove. **Only honored in skill frontmatter hooks** — ignored in settings files and agent frontmatter |\n| `if` | no | Exactly one permission rule — no `&&`, `\\|\\|`, or list syntax. Use separate handlers for multiple conditions |\n\nCommand-only:\n\n| Field | Required | Description |\n|---|---|---|\n| `command` | yes | Shell command to execute |\n| `args` | no | Array of arguments — when present, `command` runs as an executable (exec form, no shell interpretation) instead of being passed to a shell |\n| `async` | no | `true` = background, non-blocking, command hooks only. Cannot block, cannot return decisions, and delivers output on a later turn — never use for safety gates |\n| `asyncRewake` | no | Background mode only — wake Claude when the async hook exits with code 2 |\n| `shell` | no | Shell used to run `command` — `\"bash\"` or `\"powershell\"` |\n\nPrompt\u002FAgent-only:\n\n| Field | Required | Description |\n|---|---|---|\n| `prompt` | yes | Prompt text; use `$ARGUMENTS` as placeholder for the hook's full JSON input |\n| `model` | no | Model override (defaults to Haiku) |\n\nHTTP-only:\n\n| Field | Required | Description |\n|---|---|---|\n| `url` | yes | Endpoint to POST event data to |\n| `headers` | no | Custom HTTP headers |\n| `allowedEnvVars` | no | Env vars permitted to be forwarded to the request |\n\nMCP Tool-only:\n\n| Field | Required | Description |\n|---|---|---|\n| `server` | yes | MCP server name |\n| `tool` | yes | Tool name on that server |\n\n---\n\n## Hook Events\n\n| Event | When | Can Block? | Use For |\n|---|---|---|---|\n| `PreToolUse` | Before tool runs | ✅ Yes | Validate, deny, modify tool input |\n| `PermissionRequest` | Permission dialog | ✅ Yes | Auto-allow\u002Fdeny permissions |\n| `PostToolUse` | After tool (success) | ❌ No | Feedback, logging, follow-up |\n| `PostToolUseFailure` | After tool (failure) | ❌ No | Error guidance, alerts |\n| `UserPromptSubmit` | User submits prompt | ✅ Yes | Add context, validate, block |\n| `Stop` | Agent about to stop | ✅ Yes | Completeness check |\n| `SubagentStop` | Subagent about to stop | ✅ Yes | Subagent task validation |\n| `SubagentStart` | Subagent spawned | ❌ No | Inject context into subagent |\n| `SessionStart` | Session begins | ❌ No | Load context, set env vars |\n| `SessionEnd` | Session ends | ❌ No | Cleanup, logging |\n| `PreCompact` | Before context compact | ❌ No | Preserve critical context |\n| `Notification` | Claude sends notification | ❌ No | React to notifications |\n| `WorktreeCreate` | Worktree created | ⚠️ Special | Must return the absolute path of the created worktree — not a standard allow\u002Fblock decision |\n\nThis is not the full event list — Claude Code also ships `Setup`, `UserPromptExpansion`, `PostToolBatch`, `MessageDisplay`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeRemove`, `CwdChanged`, `PermissionDenied`, `StopFailure`, `InstructionsLoaded`, `ConfigChange`, `FileChanged`, `PostCompact`, `Elicitation`, and `ElicitationResult`. Full list, per-event payloads, and the hook-type\u002Fevent compatibility matrix: `references\u002Fevent-reference.md`.\n\n**⚠️ Stop\u002FSubagentStop infinite loop guard** — always check `stop_hook_active`:\n```bash\nINPUT=$(cat)\nif [ \"$(echo \"$INPUT\" | jq -r '.stop_hook_active')\" = \"true\" ]; then\n  exit 0  # Already in hook-triggered continuation — allow stop\nfi\n```\n\nFor per-event data payloads, timing, matcher values, and output schemas, see `references\u002Fevent-reference.md` and `references\u002Fdecision-schemas.md`.\n\n---\n\n## Matchers\n\n```json\n\"matcher\": \"Write\"           \u002F\u002F Exact tool name\n\"matcher\": \"Read|Write|Edit\" \u002F\u002F Multiple tools\n\"matcher\": \"*\"               \u002F\u002F All tools (use sparingly)\n\"matcher\": \"mcp__.*__delete\" \u002F\u002F Regex — all MCP delete tools\n```\n\nMatchers are **case-sensitive**. Events that match on something other than tool name:\n\n| Event | Matches on |\n|---|---|\n| `SubagentStart\u002FStop` | Agent type (`Bash`, `Explore`, custom names) |\n| `SessionStart` | How session started (`startup`, `resume`, `clear`, `compact`) |\n| `SessionEnd` | Why session ended (`clear`, `logout`, `prompt_input_exit`, `other`) |\n| `Notification` | Notification type (`permission_prompt`, `idle_prompt`, `auth_success`) |\n| `PreCompact` | What triggered it (`manual`, `auto`) |\n| `Stop`, `UserPromptSubmit`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged` | No matcher support — always fires (verify current list against `references\u002Fevent-reference.md`) |\n\n---\n\n## Environment Variables\n\nAvailable in a `hooks\u002Fhooks.json`\u002F`.claude\u002Fhooks.json` command hook:\n\n| Variable | Description |\n|---|---|\n| `$CLAUDE_PROJECT_DIR` | Project root path |\n| `$CLAUDE_PLUGIN_ROOT` | Plugin installation dir — use for portable file references in `hooks.json` |\n| `$CLAUDE_ENV_FILE` | **SessionStart only** — append `export VAR=val` here to persist env vars for the session |\n| `$CLAUDE_CODE_REMOTE` | Set if running in remote context |\n\n**A skill\u002Fagent frontmatter-embedded `hooks:` block is different — never use a bare relative path.**\nOfficial docs state hook handlers \"run in the current directory,\" i.e. the live session cwd (which\ntracks `cd`\u002Fworktree changes), not the skill's own directory, so a bare relative path resolves\nunpredictably depending on where Claude happens to be when the hook fires. Which variable to use\ninstead depends on distribution: `$CLAUDE_PROJECT_DIR` with the full path for a project-level skill\nnever distributed elsewhere (`$CLAUDE_PLUGIN_ROOT` is confirmed broken there — no enclosing plugin to\nresolve against); `$CLAUDE_PLUGIN_ROOT` for a plugin-nested skill meant for distribution (a real\nend-user's `$CLAUDE_PROJECT_DIR` won't contain this plugin's own source tree). See\n`references\u002Fcomponent-scoped-hooks.md`'s \"Environment Variables Available\" section for the full\nreasoning.\n\n---\n\n## Exit Codes & Output Contract\n\n| Exit Code | Meaning |\n|---|---|\n| `0` | Pass\u002Fcontinue |\n| `2` | Block — stderr content is fed to Claude |\n| other | Non-blocking warning — logged, execution continues |\n\nSome events have exceptions to this contract (e.g. `SessionStart` never blocks) — see `references\u002Fexit-code-behavior.md`. Blocking\u002Ferror messages go to stderr; informational context output goes to stdout.\n\nA hook must pick one signaling mode: exit-code mode, or structured JSON on stdout with exit `0`. JSON output is ignored whenever the exit code is `2`. All hook output (stdout, `additionalContext`, `systemMessage`) is capped at 10,000 characters — summarize large results and write details to a file. HTTP hooks cannot block via a non-2xx status; return `2xx` with a JSON decision body instead.\n\nFull semantics and JSON schemas: `references\u002Fexit-code-behavior.md`, `references\u002Fdecision-schemas.md`.\n\n---\n\n## Performance & Safety\n\n- Each hook should complete in under 5 seconds; hooks that regularly exceed this may be disabled by Claude Code\n- Keep total hook execution time across all matching hooks under ~30 seconds with parallel processing\n- Filter by event type, tool name, file path, and extension before doing expensive work — never scan the whole project inside a hook\n- Cap displayed findings to 5-10 items; emit a summary line if more exist\n- Prefer Python for cross-platform hook scripts; use `pathlib.Path` for all paths — never hardcode `\u002Ftmp\u002F` or OS-specific separators. Any hook invoked via a bare `hooks.json` command path MUST use the `uv` → `python3` → `python` runner fallback with graceful degradation if none is found — this is the required default, not an optional hardening step (see Pattern 11 in `references\u002Fpatterns-and-templates.md`)\n- Never use `shell=True` with string commands — use list arguments. Parse stdin as structured JSON and never interpolate raw input into shell commands (see `references\u002Fpatterns-and-templates.md` and `references\u002Fvalidation-guide.md`)\n- Command hooks run with the full permissions of the current system user — treat every hook script as privileged local code\n- Hooks must not open `\u002Fdev\u002Ftty` or send escape sequences directly to the interface; use the JSON `systemMessage` field instead\n\n---\n\n## Common Workflow Patterns\n\n| Pattern | Events | Description |\n|---|---|---|\n| Auto-format chain | PostToolUse (Write\\|Edit) | Run Prettier → ESLint → TypeScript check on every file write |\n| Test-on-save | PostToolUse (Write\\|Edit) | Locate and run the corresponding test file |\n| Observability pipeline | SessionStart + PreToolUse + PostToolUse + SessionEnd | Log session init, tool attempts, results, and summary |\n| Security guardrails | PreToolUse (Write\\|Edit\\|Bash) | Multi-layer: path traversal → permission → allowlist |\n| Context loading | SessionStart (startup) | Load project docs, check git status, validate environment |\n\n---\n\n## Implementation Workflow\n\nFor a `hooks\u002Fhooks.json`\u002F`.claude\u002Fhooks.json` hook. For a skill\u002Fagent frontmatter-embedded `hooks:`\nblock instead, see `references\u002Fcomponent-scoped-hooks.md` — step 7 below does not apply there.\n\n1. **Detect project type** — check for `.claude-plugin\u002Fplugin.json` to pick correct hooks file location\n2. **Auto-detect tooling** to suggest relevant hooks:\n   - `tsconfig.json` → PostToolUse type-check hook\n   - `.prettierrc` → PostToolUse auto-format hook\n   - `.eslintrc.*` → PostToolUse lint hook\n   - `package.json` with `test` script → Stop test-validation hook\n   - Git repository → PreToolUse security scan hook\n3. **Identify events** — use the Hook Events table above\n4. **Choose hook type** — prompt (flexible), agent (requires file inspection), command (deterministic)\n5. **Write configuration** — ensure nested `\"hooks\": [...]` array is present\n6. **For command hooks** — read all data from stdin (`INPUT=$(cat)`)\n7. **Use `${CLAUDE_PLUGIN_ROOT}`** for all file references (this step is `hooks.json`-specific — see the note above)\n8. **Add `stop_hook_active` guard** to all Stop\u002FSubagentStop hooks\n9. **Validate configuration** — `scripts\u002Fvalidate-hook-schema.sh hooks\u002Fhooks.json`\n10. **Lint scripts** — `shellcheck scripts\u002Fmy-hook.sh`\n11. **Test happy and sad paths** — `scripts\u002Ftest-hook.sh` with valid and invalid inputs\n12. **Test live** — `claude --debug`; look for hook registration and execution logs\n13. **Document hooks** in plugin README; validate against `references\u002Fvalidation-guide.md`\n\n**Optional (TDD-style):** define the behavior violation you want to prevent first, then write the hook, then review.\n\n---\n\n## Testing & Validation\n\nAfter writing or modifying hooks:\n\n1. **JSON structure** — `jq empty hooks\u002Fhooks.json && echo \"Valid\"` before anything else\n2. **Schema validation** — `scripts\u002Fvalidate-hook-schema.sh hooks\u002Fhooks.json`\n3. **Script lint** — `shellcheck scripts\u002Fmy-hook.sh` for all command hook scripts\n4. **Manual test** — pipe sample event JSON and check exit code and stdout:\n   ```bash\n   bash scripts\u002Fmy-hook.sh \u003C\u003C\u003C '{\"tool_name\":\"Write\",\"tool_input\":{\"file_path\":\"\u002Ftest.txt\"}}'\n   echo \"Exit: $?\"\n   ```\n5. **Live test** — restart Claude Code, trigger the hooked event, check `claude --debug` output\n\n**Quality gates:**\n- [ ] `jq empty` passes on hooks.json\n- [ ] `shellcheck` passes on all hook scripts (zero warnings)\n- [ ] Happy path: valid input → hook passes (exit 0)\n- [ ] Sad path: invalid\u002Fblocked input → hook fires correctly (exit 2 + stderr)\n- [ ] Stop hooks include `stop_hook_active` guard\n- [ ] `scripts\u002Fvalidate-hook-schema.sh` reports no errors\n\n**Deep Test coverage for a hook:** step 4's \"Manual test\" above exercises one sample input by\nhand — Deep Test coverage means running `scripts\u002Ftest-hook.sh --create-sample \u003Cevent-type>`\nfor every event type the hook's own `matcher` in `hooks.json` actually configures it to\nreceive, then running `scripts\u002Ftest-hook.sh` against each generated sample (a happy-path\ninput and, where meaningful, a blocked-path input) rather than just one. `scripts\u002Ftest-hook.sh\n--json`\u002F`--yaml` emits a machine-readable `status: pass|fail` result per run (plus\n`exit_code`\u002F`classification`\u002F`output`) so a caller aggregating results across every event\ntype — e.g. `plugin-lifecycle-downstream`'s optional Deep Test step — doesn't have to parse\nthe human-readable text output.\n\n**Verify this skill activates on:**\n- \"add a hook to this plugin\" \u002F \"write hooks.json\"\n- \"implement PreToolUse validation to block dangerous commands\"\n- \"auto-format on every file write\" \u002F \"enforce completion standards with a Stop hook\"\n- \"load session context at startup\" \u002F \"automate a response to a Claude Code event\"\n\n**Verify it does NOT activate on:**\n- \"just run this once\" → a slash command, not a hook\n- \"change a global config setting\" → edit `settings.json` directly instead\n- \"review this existing hook's quality\u002Fsafety before I ship it\" → the `hook-reviewer` agent instead\n\n**Last dated run record:** 2026-08-30, `evals\u002Fhook-development\u002F` — 3\u002F3 scenarios,\n8\u002F8 assertions passed (Quick Workflow, `with_skill` only — see `evals\u002Fhook-development\u002Fevals.json`).\n2 of 4 declared trigger scenarios aren't yet exercised by an eval (auto-format-on-write, session-context\nloading) — see `evals.json`'s `testing_validation_coverage` field. **eval-4 re-checked 2026-09-24**\n(issue #388 fix — Pattern 9's async-timeout-enforcement claim in `advanced-hooks.md` corrected to match\nofficial docs, plus the primary Hook Handler Fields table's `timeout` row qualified with the same\nexception): 6\u002F6 assertions pass. eval-4's own prompt was broadened to organically ask whether any hook\nconfiguration leaves `timeout` unenforced, so this is a direct, non-vacuous re-run against the graded\nresponse itself, not inferred from a separate probe (PR #391 round-1 review finding). **Re-verified\nagain same day** (PR #391 round-3 review finding): the async exception was further narrowed — a plain\n`async: true` hook (no `asyncRewake`) has `timeout` unenforced, but `asyncRewake: true` still runs in\nthe background while keeping `timeout` enforced; this distinction was verified against the live official\ndocs before applying it, and the same correction was swept into `validation-guide.md` and\n`how-hooks-work.md`, which made the same unqualified claim outside this PR's original diff\n(`evals\u002Fhook-development\u002Fworkspace\u002Fiteration-2\u002Feval-4\u002Fwith_skill\u002Fgrading.json`).\n\n---\n\n## Additional Resources\n\n| Reference | Purpose |\n|---|---|\n| `references\u002Fhook-types.md` | Full field reference and JSON example for each of the 5 hook action types |\n| `references\u002Fevent-reference.md` | Complete event docs: data payloads, timing, matcher values |\n| `references\u002Fdecision-schemas.md` | Output schemas for prompt\u002Fagent\u002Fcommand hooks by event |\n| `references\u002Fexit-code-behavior.md` | Exit code semantics (0\u002F1\u002F2) with per-event scenarios |\n| `references\u002Fcommand-hook-input-parsing.md` | Stdin field paths and bash parsing patterns per event |\n| `references\u002Fpatterns-and-templates.md` | 11 common patterns and copy-paste templates for all hook types |\n| `references\u002Fadvanced-hooks.md` | 18 advanced patterns: rate limiting, caching, retry, cross-event workflows, external integrations |\n| `references\u002Fhow-hooks-work.md` | Lifecycle, execution model, `onError`, hot-reload limits |\n| `references\u002Fvalidation-guide.md` | 7-phase systematic validation; production checklists; troubleshooting |\n| `references\u002Fmigration.md` | Migrating command hooks to prompt hooks |\n| `references\u002Fcomponent-scoped-hooks.md` | Hooks scoped to skills and subagents via YAML frontmatter |\n| `references\u002Fmcp-tools.md` | Hook patterns for MCP tool events |\n\n| Example | Contents |\n|---|---|\n| `examples\u002Fvalidate-write.sh` | File write validation with path safety checks |\n| `examples\u002Fvalidate-bash.sh` | Bash command validation and allowlist |\n| `examples\u002Fload-context.sh` | SessionStart context loading with `$CLAUDE_ENV_FILE` |\n\n| Script | Purpose |\n|---|---|\n| `scripts\u002Fvalidate-hook-schema.sh` | Validate hooks.json structure and syntax |\n| `scripts\u002Ftest-hook.sh` | Test hooks with sample input before deployment |\n| `scripts\u002Fhook-linter.sh` | Check hook scripts for common issues |\n| `plugin-rulebook` | Plugin-level rules — invoke before finalizing any hook to check naming, language, formatting, tool-scoping, and external-reference compliance |\n","# Hook Development for Claude Code Plugins\n\nHooks are event-driven automation scripts that execute in response to Claude Code events. Use them to validate operations, enforce policies, add context, and integrate external tools.\n\n**Key capabilities:** validate before tool runs (PreToolUse), react to results (PostToolUse), enforce completion standards (Stop), load project context (SessionStart).\n\n## Quick Start\n\n1. **Detect project type** — check for `.claude-plugin\u002Fplugin.json`; if present, hooks go to `hooks\u002Fhooks.json`; otherwise to `.claude\u002Fhooks.json`\n2. **Choose an event** — `PreToolUse` (validate before), `PostToolUse` (react after), `Stop` (completion check), `SessionStart` (context loading)\n3. **Pick a hook type** — prompt (LLM reasoning), command (deterministic bash), or agent (requires file inspection)\n4. **Write configuration** — use the nested `\"hooks\": [...]` array (see CRITICAL section below)\n5. **For command hooks** — read event data from stdin, not environment variables (see CRITICAL section below)\n6. **Validate** — run `scripts\u002Fvalidate-hook-schema.sh` and `shellcheck` on scripts\n7. **Test** — use `scripts\u002Ftest-hook.sh` with sample input, then `claude --debug` live\n\n*For the full 13-step workflow with tooling auto-detection, lint, and documentation steps, see [Implementation Workflow](#implementation-workflow) below.*\n\n## When to Use\n\n- Adding validation before tool calls (file writes, bash commands, API calls)\n- Enforcing project policies at runtime without editing every command\n- Loading project context or env vars at session start\n- Verifying Claude completes tasks fully before stopping\n- Logging, alerting, or auditing tool usage\n\n## When NOT to Use\n\n- For one-time prompts — use slash commands instead\n- For global config changes — modify `settings.json` directly\n- Never edit `~\u002F.claude\u002Fplugins\u002Fcache\u002F` — those are read-only installed copies\n- Reviewing an existing hook's quality\u002Fsafety before deployment → use the `hook-reviewer` agent instead\n\n## Finding-ID Fix Mode\n\nWhen invoked with a bounded finding-ID list (e.g. from `plugin-lifecycle-downstream`'s Phase\n4\u002F6\u002F8), follow `plugin-rulebook\u002Freferences\u002Ffinding-id-fix-contract.md` instead of this\nskill's normal open-ended workflow: touch only the named findings' files, report per-ID\n`applied`\u002F`deferred`\u002F`failed` status, and never mark a fix verified — that stays the\noriginating checker's job.\n\n---\n\n## CRITICAL: Hook File Location\n\n**Most common mistake:** placing hooks in `.claude-plugin\u002Fhooks.json` (WRONG).\n\n✅ **Correct locations:**\n- **Plugin projects** (has `.claude-plugin\u002Fplugin.json`): `hooks\u002Fhooks.json` at plugin root\n- **Regular projects** (no `.claude-plugin\u002F`): `.claude\u002Fhooks.json`\n\n❌ **Wrong:** `.claude-plugin\u002Fhooks.json` — only `plugin.json` belongs in `.claude-plugin\u002F`\n\n**Auto-detect:** check for `.claude-plugin\u002Fplugin.json`; its presence means plugin project. If hooks aren't firing, check file location first.\n\n---\n\n## CRITICAL: Command Hooks Receive Data via Stdin\n\n**The #1 reason command hooks silently do nothing:** expecting environment variables instead of reading stdin.\n\n❌ **WRONG — env var substitution does NOT work:**\n```json\n{ \"env\": {\"FILE_PATH\": \"${arguments.file_path}\"} }\n```\n\n✅ **CORRECT — read ALL event data from stdin as JSON:**\n```bash\n#!\u002Fbin\u002Fbash\nINPUT=$(cat)                                          # Read all event data from stdin\nFILE_PATH=$(echo \"$INPUT\" | jq -r '.tool_input.file_path')\nTOOL_NAME=$(echo \"$INPUT\" | jq -r '.tool_name')\n```\n\nSee `references\u002Fcommand-hook-input-parsing.md` for correct field paths per event type.\n\n---\n\n## CRITICAL: Nested \"hooks\" Array JSON Structure\n\n**The #1 JSON mistake:** forgetting the nested `\"hooks\": [...]` array inside each event matcher.\n\n✅ **CORRECT — required for all hooks:**\n```json\n{\n  \"hooks\": {\n    \"EventName\": [\n      {\n        \"matcher\": \"regex-pattern\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"${CLAUDE_PLUGIN_ROOT}\u002Fscripts\u002Fscript.sh\",\n            \"timeout\": 5,\n            \"onError\": \"warn\"\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n❌ **WRONG — produces \"Expected array, but received undefined\":**\n```json\n{\n  \"hooks\": {\n    \"EventName\": [{ \"type\": \"command\", \"command\": \"...\" }]\n  }\n}\n```\n\nEvery hook action (command, http, mcp_tool, prompt, agent) **must** be inside a `\"hooks\": [...]` array.\n\n---\n\n## Hook Types\n\nFive action types: `prompt` (LLM-driven, flexible), `command` (bash, deterministic), `agent` (multi-turn, file inspection), `http` (webhook), `mcp_tool` (calls an installed MCP server tool). Full field reference and JSON example per type: `references\u002Fhook-types.md` (`mcp_tool` has its own dedicated reference, `references\u002Fmcp-tools.md`).\n\n**Type decision:**\n\n| Use Case | Type |\n|---|---|\n| Fast deterministic check (lint, file size, path regex) | command |\n| Intelligent reasoning (context-aware, needs judgment) | prompt |\n| Verification requiring file inspection or test runs | agent |\n| Complex branches or state checks | command |\n| Call an installed MCP server tool | mcp_tool |\n| Notify or delegate to an external system | http |\n\nNot every type is valid for every event (e.g. `SessionStart` supports only `command` and `mcp_tool`) — validate the type\u002Fevent combination, not just each independently. Full compatibility matrix: `references\u002Fevent-reference.md`.\n\n---\n\n## Hook Configuration Formats\n\n### Plugin Format (`hooks\u002Fhooks.json`)\n\n```json\n{\n  \"description\": \"Optional description\",\n  \"hooks\": {\n    \"PreToolUse\": [...],\n    \"Stop\": [...],\n    \"SessionStart\": [...]\n  }\n}\n```\n\n### Settings Format (`.claude\u002Fsettings.json` or `.claude\u002Fhooks.json`)\n\n```json\n{\n  \"PreToolUse\": [...],\n  \"Stop\": [...],\n  \"SessionStart\": [...]\n}\n```\n\nEvents go directly at the top level — no wrapper object. Plugin hooks merge with user hooks and run in parallel. Settings format also supports a top-level `disableAllHooks` boolean key to disable every configured hook at once — verify whether this applies to plugin `hooks\u002Fhooks.json` too before relying on it there.\n\n`hooks\u002Fhooks.json` has only two top-level keys: `description` and `hooks` — verify this against the current platform schema before enforcing it. Shared team hooks belong in `.claude\u002Fsettings.json` (checked into version control) — never in `.claude\u002Fsettings.local.json`, which is personal and gitignored.\n\n---\n\n## Hook Handler Fields\n\nAll handlers:\n\n| Field | Required | Description |\n|---|---|---|\n| `type` | yes | `\"command\"`, `\"http\"`, `\"mcp_tool\"`, `\"prompt\"`, or `\"agent\"` |\n| `timeout` | no | Seconds before canceling — except an async command hook (`async: true`) without `asyncRewake: true`, where `timeout` is not enforced (see Pattern 9 in `references\u002Fadvanced-hooks.md`). `asyncRewake: true` still runs in the background but keeps timeout enforcement. Defaults: command=600, prompt=30, agent=60. Flag values outside 1-600s as suspect |\n| `statusMessage` | no | Custom spinner text while hook runs |\n| `once` | no | Run once per session then auto-remove. **Only honored in skill frontmatter hooks** — ignored in settings files and agent frontmatter |\n| `if` | no | Exactly one permission rule — no `&&`, `\\|\\|`, or list syntax. Use separate handlers for multiple conditions |\n\nCommand-only:\n\n| Field | Required | Description |\n|---|---|---|\n| `command` | yes | Shell command to execute |\n| `args` | no | Array of arguments — when present, `command` runs as an executable (exec form, no shell interpretation) instead of being passed to a shell |\n| `async` | no | `true` = background, non-blocking, command hooks only. Cannot block, cannot return decisions, and delivers output on a later turn — never use for safety gates |\n| `asyncRewake` | no | Background mode only — wake Claude when the async hook exits with code 2 |\n| `shell` | no | Shell used to run `command` — `\"bash\"` or `\"powershell\"` |\n\nPrompt\u002FAgent-only:\n\n| Field | Required | Description |\n|---|---|---|\n| `prompt` | yes | Prompt text; use `$ARGUMENTS` as placeholder for the hook's full JSON input |\n| `model` | no | Model override (defaults to Haiku) |\n\nHTTP-only:\n\n| Field | Required | Description |\n|---|---|---|\n| `url` | yes | Endpoint to POST event data to |\n| `headers` | no | Custom HTTP headers |\n| `allowedEnvVars` | no | Env vars permitted to be forwarded to the request |\n\nMCP Tool-only:\n\n| Field | Required | Description |\n|---|---|---|\n| `server` | yes | MCP server name |\n| `tool` | yes | Tool name on that server |\n\n---\n\n## Hook Events\n\n| Event | When | Can Block? | Use For |\n|---|---|---|---|\n| `PreToolUse` | Before tool runs | ✅ Yes | Validate, deny, modify tool input |\n| `PermissionRequest` | Permission dialog | ✅ Yes | Auto-allow\u002Fdeny permissions |\n| `PostToolUse` | After tool (success) | ❌ No | Feedback, logging, follow-up |\n| `PostToolUseFailure` | After tool (failure) | ❌ No | Error guidance, alerts |\n| `UserPromptSubmit` | User submits prompt | ✅ Yes | Add context, validate, block |\n| `Stop` | Agent about to stop | ✅ Yes | Completeness check |\n| `SubagentStop` | Subagent about to stop | ✅ Yes | Subagent task validation |\n| `SubagentStart` | Subagent spawned | ❌ No | Inject context into subagent |\n| `SessionStart` | Session begins | ❌ No | Load context, set env vars |\n| `SessionEnd` | Session ends | ❌ No | Cleanup, logging |\n| `PreCompact` | Before context compact | ❌ No | Preserve critical context |\n| `Notification` | Claude sends notification | ❌ No | React to notifications |\n| `WorktreeCreate` | Worktree created | ⚠️ Special | Must return the absolute path of the created worktree — not a standard allow\u002Fblock decision |\n\nThis is not the full event list — Claude Code also ships `Setup`, `UserPromptExpansion`, `PostToolBatch`, `MessageDisplay`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeRemove`, `CwdChanged`, `PermissionDenied`, `StopFailure`, `InstructionsLoaded`, `ConfigChange`, `FileChanged`, `PostCompact`, `Elicitation`, and `ElicitationResult`. Full list, per-event payloads, and the hook-type\u002Fevent compatibility matrix: `references\u002Fevent-reference.md`.\n\n**⚠️ Stop\u002FSubagentStop infinite loop guard** — always check `stop_hook_active`:\n```bash\nINPUT=$(cat)\nif [ \"$(echo \"$INPUT\" | jq -r '.stop_hook_active')\" = \"true\" ]; then\n  exit 0  # Already in hook-triggered continuation — allow stop\nfi\n```\n\nFor per-event data payloads, timing, matcher values, and output schemas, see `references\u002Fevent-reference.md` and `references\u002Fdecision-schemas.md`.\n\n---\n\n## Matchers\n\n```json\n\"matcher\": \"Write\"           \u002F\u002F Exact tool name\n\"matcher\": \"Read|Write|Edit\" \u002F\u002F Multiple tools\n\"matcher\": \"*\"               \u002F\u002F All tools (use sparingly)\n\"matcher\": \"mcp__.*__delete\" \u002F\u002F Regex — all MCP delete tools\n```\n\nMatchers are **case-sensitive**. Events that match on something other than tool name:\n\n| Event | Matches on |\n|---|---|\n| `SubagentStart\u002FStop` | Agent type (`Bash`, `Explore`, custom names) |\n| `SessionStart` | How session started (`startup`, `resume`, `clear`, `compact`) |\n| `SessionEnd` | Why session ended (`clear`, `logout`, `prompt_input_exit`, `other`) |\n| `Notification` | Notification type (`permission_prompt`, `idle_prompt`, `auth_success`) |\n| `PreCompact` | What triggered it (`manual`, `auto`) |\n| `Stop`, `UserPromptSubmit`, `TeammateIdle`, `TaskCreated`, `TaskCompleted`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged` | No matcher support — always fires (verify current list against `references\u002Fevent-reference.md`) |\n\n---\n\n## Environment Variables\n\nAvailable in a `hooks\u002Fhooks.json`\u002F`.claude\u002Fhooks.json` command hook:\n\n| Variable | Description |\n|---|---|\n| `$CLAUDE_PROJECT_DIR` | Project root path |\n| `$CLAUDE_PLUGIN_ROOT` | Plugin installation dir — use for portable file references in `hooks.json` |\n| `$CLAUDE_ENV_FILE` | **SessionStart only** — append `export VAR=val` here to persist env vars for the session |\n| `$CLAUDE_CODE_REMOTE` | Set if running in remote context |\n\n**A skill\u002Fagent frontmatter-embedded `hooks:` block is different — never use a bare relative path.**\nOfficial docs state hook handlers \"run in the current directory,\" i.e. the live session cwd (which\ntracks `cd`\u002Fworktree changes), not the skill's own directory, so a bare relative path resolves\nunpredictably depending on where Claude happens to be when the hook fires. Which variable to use\ninstead depends on distribution: `$CLAUDE_PROJECT_DIR` with the full path for a project-level skill\nnever distributed elsewhere (`$CLAUDE_PLUGIN_ROOT` is confirmed broken there — no enclosing plugin to\nresolve against); `$CLAUDE_PLUGIN_ROOT` for a plugin-nested skill meant for distribution (a real\nend-user's `$CLAUDE_PROJECT_DIR` won't contain this plugin's own source tree). See\n`references\u002Fcomponent-scoped-hooks.md`'s \"Environment Variables Available\" section for the full\nreasoning.\n\n---\n\n## Exit Codes & Output Contract\n\n| Exit Code | Meaning |\n|---|---|\n| `0` | Pass\u002Fcontinue |\n| `2` | Block — stderr content is fed to Claude |\n| other | Non-blocking warning — logged, execution continues |\n\nSome events have exceptions to this contract (e.g. `SessionStart` never blocks) — see `references\u002Fexit-code-behavior.md`. Blocking\u002Ferror messages go to stderr; informational context output goes to stdout.\n\nA hook must pick one signaling mode: exit-code mode, or structured JSON on stdout with exit `0`. JSON output is ignored whenever the exit code is `2`. All hook output (stdout, `additionalContext`, `systemMessage`) is capped at 10,000 characters — summarize large results and write details to a file. HTTP hooks cannot block via a non-2xx status; return `2xx` with a JSON decision body instead.\n\nFull semantics and JSON schemas: `references\u002Fexit-code-behavior.md`, `references\u002Fdecision-schemas.md`.\n\n---\n\n## Performance & Safety\n\n- Each hook should complete in under 5 seconds; hooks that regularly exceed this may be disabled by Claude Code\n- Keep total hook execution time across all matching hooks under ~30 seconds with parallel processing\n- Filter by event type, tool name, file path, and extension before doing expensive work — never scan the whole project inside a hook\n- Cap displayed findings to 5-10 items; emit a summary line if more exist\n- Prefer Python for cross-platform hook scripts; use `pathlib.Path` for all paths — never hardcode `\u002Ftmp\u002F` or OS-specific separators. Any hook invoked via a bare `hooks.json` command path MUST use the `uv` → `python3` → `python` runner fallback with graceful degradation if none is found — this is the required default, not an optional hardening step (see Pattern 11 in `references\u002Fpatterns-and-templates.md`)\n- Never use `shell=True` with string commands — use list arguments. Parse stdin as structured JSON and never interpolate raw input into shell commands (see `references\u002Fpatterns-and-templates.md` and `references\u002Fvalidation-guide.md`)\n- Command hooks run with the full permissions of the current system user — treat every hook script as privileged local code\n- Hooks must not open `\u002Fdev\u002Ftty` or send escape sequences directly to the interface; use the JSON `systemMessage` field instead\n\n---\n\n## Common Workflow Patterns\n\n| Pattern | Events | Description |\n|---|---|---|\n| Auto-format chain | PostToolUse (Write\\|Edit) | Run Prettier → ESLint → TypeScript check on every file write |\n| Test-on-save | PostToolUse (Write\\|Edit) | Locate and run the corresponding test file |\n| Observability pipeline | SessionStart + PreToolUse + PostToolUse + SessionEnd | Log session init, tool attempts, results, and summary |\n| Security guardrails | PreToolUse (Write\\|Edit\\|Bash) | Multi-layer: path traversal → permission → allowlist |\n| Context loading | SessionStart (startup) | Load project docs, check git status, validate environment |\n\n---\n\n## Implementation Workflow\n\nFor a `hooks\u002Fhooks.json`\u002F`.claude\u002Fhooks.json` hook. For a skill\u002Fagent frontmatter-embedded `hooks:`\nblock instead, see `references\u002Fcomponent-scoped-hooks.md` — step 7 below does not apply there.\n\n1. **Detect project type** — check for `.claude-plugin\u002Fplugin.json` to pick correct hooks file location\n2. **Auto-detect tooling** to suggest relevant hooks:\n   - `tsconfig.json` → PostToolUse type-check hook\n   - `.prettierrc` → PostToolUse auto-format hook\n   - `.eslintrc.*` → PostToolUse lint hook\n   - `package.json` with `test` script → Stop test-validation hook\n   - Git repository → PreToolUse security scan hook\n3. **Identify events** — use the Hook Events table above\n4. **Choose hook type** — prompt (flexible), agent (requires file inspection), command (deterministic)\n5. **Write configuration** — ensure nested `\"hooks\": [...]` array is present\n6. **For command hooks** — read all data from stdin (`INPUT=$(cat)`)\n7. **Use `${CLAUDE_PLUGIN_ROOT}`** for all file references (this step is `hooks.json`-specific — see the note above)\n8. **Add `stop_hook_active` guard** to all Stop\u002FSubagentStop hooks\n9. **Validate configuration** — `scripts\u002Fvalidate-hook-schema.sh hooks\u002Fhooks.json`\n10. **Lint scripts** — `shellcheck scripts\u002Fmy-hook.sh`\n11. **Test happy and sad paths** — `scripts\u002Ftest-hook.sh` with valid and invalid inputs\n12. **Test live** — `claude --debug`; look for hook registration and execution logs\n13. **Document hooks** in plugin README; validate against `references\u002Fvalidation-guide.md`\n\n**Optional (TDD-style):** define the behavior violation you want to prevent first, then write the hook, then review.\n\n---\n\n## Testing & Validation\n\nAfter writing or modifying hooks:\n\n1. **JSON structure** — `jq empty hooks\u002Fhooks.json && echo \"Valid\"` before anything else\n2. **Schema validation** — `scripts\u002Fvalidate-hook-schema.sh hooks\u002Fhooks.json`\n3. **Script lint** — `shellcheck scripts\u002Fmy-hook.sh` for all command hook scripts\n4. **Manual test** — pipe sample event JSON and check exit code and stdout:\n   ```bash\n   bash scripts\u002Fmy-hook.sh \u003C\u003C\u003C '{\"tool_name\":\"Write\",\"tool_input\":{\"file_path\":\"\u002Ftest.txt\"}}'\n   echo \"Exit: $?\"\n   ```\n5. **Live test** — restart Claude Code, trigger the hooked event, check `claude --debug` output\n\n**Quality gates:**\n- [ ] `jq empty` passes on hooks.json\n- [ ] `shellcheck` passes on all hook scripts (zero warnings)\n- [ ] Happy path: valid input → hook passes (exit 0)\n- [ ] Sad path: invalid\u002Fblocked input → hook fires correctly (exit 2 + stderr)\n- [ ] Stop hooks include `stop_hook_active` guard\n- [ ] `scripts\u002Fvalidate-hook-schema.sh` reports no errors\n\n**Deep Test coverage for a hook:** step 4's \"Manual test\" above exercises one sample input by\nhand — Deep Test coverage means running `scripts\u002Ftest-hook.sh --create-sample \u003Cevent-type>`\nfor every event type the hook's own `matcher` in `hooks.json` actually configures it to\nreceive, then running `scripts\u002Ftest-hook.sh` against each generated sample (a happy-path\ninput and, where meaningful, a blocked-path input) rather than just one. `scripts\u002Ftest-hook.sh\n--json`\u002F`--yaml` emits a machine-readable `status: pass|fail` result per run (plus\n`exit_code`\u002F`classification`\u002F`output`) so a caller aggregating results across every event\ntype — e.g. `plugin-lifecycle-downstream`'s optional Deep Test step — doesn't have to parse\nthe human-readable text output.\n\n**Verify this skill activates on:**\n- \"add a hook to this plugin\" \u002F \"write hooks.json\"\n- \"implement PreToolUse validation to block dangerous commands\"\n- \"auto-format on every file write\" \u002F \"enforce completion standards with a Stop hook\"\n- \"load session context at startup\" \u002F \"automate a response to a Claude Code event\"\n\n**Verify it does NOT activate on:**\n- \"just run this once\" → a slash command, not a hook\n- \"change a global config setting\" → edit `settings.json` directly instead\n- \"review this existing hook's quality\u002Fsafety before I ship it\" → the `hook-reviewer` agent instead\n\n**Last dated run record:** 2026-08-30, `evals\u002Fhook-development\u002F` — 3\u002F3 scenarios,\n8\u002F8 assertions passed (Quick Workflow, `with_skill` only — see `evals\u002Fhook-development\u002Fevals.json`).\n2 of 4 declared trigger scenarios aren't yet exercised by an eval (auto-format-on-write, session-context\nloading) — see `evals.json`'s `testing_validation_coverage` field. **eval-4 re-checked 2026-09-24**\n(issue #388 fix — Pattern 9's async-timeout-enforcement claim in `advanced-hooks.md` corrected to match\nofficial docs, plus the primary Hook Handler Fields table's `timeout` row qualified with the same\nexception): 6\u002F6 assertions pass. eval-4's own prompt was broadened to organically ask whether any hook\nconfiguration leaves `timeout` unenforced, so this is a direct, non-vacuous re-run against the graded\nresponse itself, not inferred from a separate probe (PR #391 round-1 review finding). **Re-verified\nagain same day** (PR #391 round-3 review finding): the async exception was further narrowed — a plain\n`async: true` hook (no `asyncRewake`) has `timeout` unenforced, but `asyncRewake: true` still runs in\nthe background while keeping `timeout` enforced; this distinction was verified against the live official\ndocs before applying it, and the same correction was swept into `validation-guide.md` and\n`how-hooks-work.md`, which made the same unqualified claim outside this PR's original diff\n(`evals\u002Fhook-development\u002Fworkspace\u002Fiteration-2\u002Feval-4\u002Fwith_skill\u002Fgrading.json`).\n\n---\n\n## Additional Resources\n\n| Reference | Purpose |\n|---|---|\n| `references\u002Fhook-types.md` | Full field reference and JSON example for each of the 5 hook action types |\n| `references\u002Fevent-reference.md` | Complete event docs: data payloads, timing, matcher values |\n| `references\u002Fdecision-schemas.md` | Output schemas for prompt\u002Fagent\u002Fcommand hooks by event |\n| `references\u002Fexit-code-behavior.md` | Exit code semantics (0\u002F1\u002F2) with per-event scenarios |\n| `references\u002Fcommand-hook-input-parsing.md` | Stdin field paths and bash parsing patterns per event |\n| `references\u002Fpatterns-and-templates.md` | 11 common patterns and copy-paste templates for all hook types |\n| `references\u002Fadvanced-hooks.md` | 18 advanced patterns: rate limiting, caching, retry, cross-event workflows, external integrations |\n| `references\u002Fhow-hooks-work.md` | Lifecycle, execution model, `onError`, hot-reload limits |\n| `references\u002Fvalidation-guide.md` | 7-phase systematic validation; production checklists; troubleshooting |\n| `references\u002Fmigration.md` | Migrating command hooks to prompt hooks |\n| `references\u002Fcomponent-scoped-hooks.md` | Hooks scoped to skills and subagents via YAML frontmatter |\n| `references\u002Fmcp-tools.md` | Hook patterns for MCP tool events |\n\n| Example | Contents |\n|---|---|\n| `examples\u002Fvalidate-write.sh` | File write validation with path safety checks |\n| `examples\u002Fvalidate-bash.sh` | Bash command validation and allowlist |\n| `examples\u002Fload-context.sh` | SessionStart context loading with `$CLAUDE_ENV_FILE` |\n\n| Script | Purpose |\n|---|---|\n| `scripts\u002Fvalidate-hook-schema.sh` | Validate hooks.json structure and syntax |\n| `scripts\u002Ftest-hook.sh` | Test hooks with sample input before deployment |\n| `scripts\u002Fhook-linter.sh` | Check hook scripts for common issues |\n| `plugin-rulebook` | Plugin-level rules — invoke before finalizing any hook to check naming, language, formatting, tool-scoping, and external-reference compliance |\n",{"name":5,"description":7,"allowed-tools":23},"Read Write Edit Glob Bash(jq:*) Bash(scripts\u002Fvalidate-hook-schema.sh:*) Bash(scripts\u002Ftest-hook.sh:*) Bash(scripts\u002Fhook-linter.sh:*) Bash(shellcheck:*) Bash(claude:*) Skill","main","1bf12900cac6f28e346abd2912bdb78d306de723","plugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace","https:\u002F\u002Fgithub.com\u002FAndreHahm","2026-11-15 04:26:16",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add AndreHahm\u002Fandres-cc-marketplace --skill hook-development",{"tool":36,"command":37},"bunx","bunx skills add AndreHahm\u002Fandres-cc-marketplace --skill hook-development",{"tool":39,"command":40},"pnpm","pnpm dlx skills add AndreHahm\u002Fandres-cc-marketplace --skill hook-development","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002FSKILL.md",true,[44,50,54,58,64,68,72,76,80,84,88,92,96,100,104,108,112,116],{"path":45,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":48,"sourceHtmlUrl":49},"examples\u002Fload-context.sh","SCRIPT","脚本",1690,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Fexamples\u002Fload-context.sh",{"path":51,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":52,"sourceHtmlUrl":53},"examples\u002Fvalidate-bash.sh",1465,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Fexamples\u002Fvalidate-bash.sh",{"path":55,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":56,"sourceHtmlUrl":57},"examples\u002Fvalidate-write.sh",1222,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Fexamples\u002Fvalidate-write.sh",{"path":59,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Fadvanced-hooks.md","REFERENCE","参考文档",25169,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fadvanced-hooks.md",{"path":65,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":66,"sourceHtmlUrl":67},"references\u002Fcommand-hook-input-parsing.md",6505,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fcommand-hook-input-parsing.md",{"path":69,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":70,"sourceHtmlUrl":71},"references\u002Fcomponent-scoped-hooks.md",12350,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fcomponent-scoped-hooks.md",{"path":73,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":74,"sourceHtmlUrl":75},"references\u002Fdecision-schemas.md",10002,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fdecision-schemas.md",{"path":77,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":78,"sourceHtmlUrl":79},"references\u002Fevent-reference.md",17187,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fevent-reference.md",{"path":81,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":82,"sourceHtmlUrl":83},"references\u002Fexit-code-behavior.md",9321,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fexit-code-behavior.md",{"path":85,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":86,"sourceHtmlUrl":87},"references\u002Fhook-types.md",2169,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fhook-types.md",{"path":89,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":90,"sourceHtmlUrl":91},"references\u002Fhow-hooks-work.md",21211,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fhow-hooks-work.md",{"path":93,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":94,"sourceHtmlUrl":95},"references\u002Fmcp-tools.md",7746,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fmcp-tools.md",{"path":97,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":98,"sourceHtmlUrl":99},"references\u002Fmigration.md",8698,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fmigration.md",{"path":101,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":102,"sourceHtmlUrl":103},"references\u002Fpatterns-and-templates.md",28138,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fpatterns-and-templates.md",{"path":105,"resourceType":60,"resourceTypeDesc":61,"sizeBytes":106,"sourceHtmlUrl":107},"references\u002Fvalidation-guide.md",30187,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Freferences\u002Fvalidation-guide.md",{"path":109,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":110,"sourceHtmlUrl":111},"scripts\u002Fhook-linter.sh",4312,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Fscripts\u002Fhook-linter.sh",{"path":113,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":114,"sourceHtmlUrl":115},"scripts\u002Ftest-hook.sh",8580,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Fscripts\u002Ftest-hook.sh",{"path":117,"resourceType":46,"resourceTypeDesc":47,"sizeBytes":118,"sourceHtmlUrl":119},"scripts\u002Fvalidate-hook-schema.sh",8205,"https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fplugin-devkit\u002Fskills\u002Fhook-development\u002Fscripts\u002Fvalidate-hook-schema.sh",[121,128,135,142,149,156],{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":125,"categories":126,"keywords":127,"publishedAt":18},"01M79R0K918Z0XDM74R0EY5H3P","demo","Fixture skill used by scripts.marketplace_ci sync tests.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Ftests\u002Fmarketplace_ci\u002Ffixtures\u002Fplugins\u002Fsample-kit\u002Fskills\u002Fdemo\u002FSKILL.md",[],[],{"skillNo":129,"name":130,"nameZh":6,"description":131,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":132,"categories":133,"keywords":134,"publishedAt":18},"01M79R08VMDJA2FPJKH3ZM309K","export-demo","Fixture skill used by scripts.marketplace_ci export tests.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Ftests\u002Fmarketplace_ci\u002Ffixtures\u002Fclaude\u002Fskills\u002Fexport-demo\u002FSKILL.md",[],[],{"skillNo":136,"name":137,"nameZh":6,"description":138,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":139,"categories":140,"keywords":141,"publishedAt":18},"01M79R042FS581DS2JNW5AZ1MK","work-to-development","Validate an accepted Linear Issue's readiness for implementation (criteria, dependencies, duplicate\u002Fexisting artifacts) and request governed branch\u002Fworktree creation through git-kit:starting-work — recording work-started Git\u002FGitHub evidence and a deliberate Linear Started transition only after Git identity is read back and verified. Use when asked to start work on a Linear issue, begin development for an accepted issue, or prepare an accepted issue for implementation. Never creates a branch directly — always delegates to git-kit.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkmanagement-kit\u002Fskills\u002Fwork-to-development\u002FSKILL.md",[],[],{"skillNo":143,"name":144,"nameZh":6,"description":145,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":146,"categories":147,"keywords":148,"publishedAt":18},"01M79QZZD4EHB82P72P4N92BKT","work-linking","Create and maintain stable cross-system links and authority labels between Notion and Linear records, and detect\u002Frepair drift between them. Use when asked to link a Notion record to a Linear record, check for drift between Notion and Linear, or repair a broken\u002Fstale link. Repairs only the bounded non-authoritative copy or link — never chooses by newest timestamp, and never creates a reverse-write loop against either system's own authority.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkmanagement-kit\u002Fskills\u002Fwork-linking\u002FSKILL.md",[],[],{"skillNo":150,"name":151,"nameZh":6,"description":152,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":153,"categories":154,"keywords":155,"publishedAt":18},"01M79QZVFA3GTVNZMJ51NESVSP","status-and-learning","Produce a dated, explicitly non-live Linear-to-Notion progress summary, or capture an outcome\u002Flearning after work completes. Use when asked to summarize progress to Notion, report portfolio status, or capture what was learned from a completed piece of work — not to disposition open follow-up items (see open-item-management for that). Never runs automatically or continuously — every summary is a deliberate, approved snapshot, not a live sync.","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkmanagement-kit\u002Fskills\u002Fstatus-and-learning\u002FSKILL.md",[],[],{"skillNo":157,"name":158,"nameZh":6,"description":159,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":160,"categories":161,"keywords":162,"publishedAt":18},"01M79QZNSKSABK7X2PT93X8QT5","repository-gates","Discover, delegate, record, and invalidate this repository's actual Git\u002FGitHub lifecycle gates (pre-commit, pre-push, PR required checks, Codex delta review, review requirements, merge rights) and the repository-policy provider profile that maps governed operations to git-kit. Use when asked what gates apply to this repository, to discover repository policy before starting Wave 2 work, or to check whether prior gate evidence is still valid after new commits. Discovery and delegation only — never executes a gate's own internal logic, and never invents a gate the repository doesn't actually define (in particular, never assumes a \"Review Changes\" gate exists).","https:\u002F\u002Fgithub.com\u002FAndreHahm\u002Fandres-cc-marketplace\u002Fblob\u002Fmain\u002Fplugins\u002Fworkmanagement-kit\u002Fskills\u002Frepository-gates\u002FSKILL.md",[],[]]