{"data":{"slug":"discovered-32cdd07c1161dd383b77ce3680e59a62a4d6db332d0a6ad5","title":"Hook Development for Claude Code (2026)","summary":"Develop deterministic hooks for Claude Code to enforce rules and control behavior during specific events such as session start, tool use, and subagent stop. Hooks receive input as a JSON object on stdin and must output a JSON object on stdout with specific fields like continue, decision, and systemMessage.","url":"https:\/\/skillshunter.net\/skills\/discovered-32cdd07c1161dd383b77ce3680e59a62a4d6db332d0a6ad5","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/discovered-32cdd07c1161dd383b77ce3680e59a62a4d6db332d0a6ad5","markdown_url":"https:\/\/skillshunter.net\/skills\/discovered-32cdd07c1161dd383b77ce3680e59a62a4d6db332d0a6ad5.md","download_url":"https:\/\/skillshunter.net\/skills\/discovered-32cdd07c1161dd383b77ce3680e59a62a4d6db332d0a6ad5\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Ensure the runtime environment supports the required tools (e.g., bun, tsx, node). Prepare a JSON object on stdin with event-specific fields. The first deliverable is a JSON output on stdout with fields like continue, decision, or systemMessage, depending on the event.","instructions":"---\nname: hook-development\nversion: 2.0.0\ndescription: \"Claude Code hook development for 2026. Covers all 9 supported events (UserPromptSubmit, PreToolUse, PostToolUse, Notification, Stop, SubagentStop, SessionStart, SessionEnd, PreCompact), stdin\/stdout JSON contract, decision\/continue\/systemMessage outputs, matchers (tool patterns), exit-code semantics, cycle detection (stop_hook_active), settings.json registration, run-hook.sh dispatcher (bun \u2192 tsx \u2192 node fallback). Invoke when creating or modifying any .claude\/hooks\/* file or settings.json hook entry.\"\n---\n\n# Hook Development \u2014 Claude Code Hooks (2026)\n\n**ALWAYS invoke when creating or modifying Claude Code hooks.**\n\n> Hooks are user-controlled deterministic gates around the model. Anything you want **enforced**, not asked nicely \u2014 put in a hook. The agent cannot disable a hook from inside the conversation.\n\n## 1. Supported events (Claude Code, 2026)\n\n| Event | Fires | Common use |\n|---|---|---|\n| `SessionStart` | When a session begins (new chat or resume) | Inject onboarding context, restore state |\n| `SessionEnd` | When a session ends cleanly | Flush logs, persist state, run cleanup |\n| `UserPromptSubmit` | After user submits, before model receives | Inject workflow rules, block forbidden phrases |\n| `PreToolUse` | Before any tool is invoked | Approve \/ block \/ rewrite tool calls (security gate) |\n| `PostToolUse` | After tool completes | Log, validate output, react to specific tool results |\n| `Notification` | When the agent is idle and notifies (e.g. waiting for input) | Desktop notifications, status forwarding |\n| `Stop` | Before the agent ends its turn | Validate completion (clean tree, tests pass, docs updated) |\n| `SubagentStop` | When a Task() subagent finishes | Validate subagent output, persist artifacts |\n| `PreCompact` | Before transcript compaction is triggered | Snapshot\/export full transcript first |\n\n`Stop` and `Subagent` events are the most commonly customized. `PreToolUse` is the security workhorse.\n\n## 2. File layout\n\n```\n.claude\/\n\u251c\u2500\u2500 hooks\/\n\u2502   \u251c\u2500\u2500 run-hook.sh           # Entry point: bun \u2192 tsx \u2192 node fallback\n\u2502   \u251c\u2500\u2500 session-start.ts\n\u2502   \u251c\u2500\u2500 session-end.ts\n\u2502   \u251c\u2500\u2500 user-prompt-submit.ts\n\u2502   \u251c\u2500\u2500 pre-tool-use.ts\n\u2502   \u251c\u2500\u2500 post-tool-use.ts\n\u2502   \u251c\u2500\u2500 stop-validator.ts\n\u2502   \u251c\u2500\u2500 subagent-stop.ts\n\u2502   \u251c\u2500\u2500 pre-compact.ts\n\u2502   \u2514\u2500\u2500 lib\/                  # shared helpers (cmd(), readStdin(), etc.)\n\u2514\u2500\u2500 settings.json             # registers hooks\n```\n\n## 3. Stdin contract (per event)\n\nAll hook input arrives as **a single JSON object on stdin**. Read with a timeout \u2014 never hang.\n\n```typescript\n\/\/ Common envelope (most events)\ninterface HookInput {\n  session_id: string;\n  cwd: string;\n  transcript_path?: string;\n  hook_event_name: string;        \/\/ e.g. \"Stop\"\n}\n\ninterface UserPromptSubmitInput extends HookInput {\n  user_prompt: string;\n}\n\ninterface PreToolUseInput extends HookInput {\n  tool_name: string;              \/\/ \"Bash\" | \"Edit\" | \"Write\" | ...\n  tool_input: Record<string, unknown>;\n}\n\ninterface PostToolUseInput extends PreToolUseInput {\n  tool_response: unknown;\n  tool_error?: string;\n}\n\ninterface StopInput extends HookInput {\n  stop_hook_active?: boolean;     \/\/ TRUE if a previous Stop hook already blocked \u2014 don't loop\n}\n\ninterface SubagentStopInput extends StopInput {\n  subagent_id: string;\n}\n\ninterface PreCompactInput extends HookInput {\n  trigger: \"manual\" | \"auto\";\n}\n```\n\n## 4. Stdout contract (per event)\n\nOutput a **single JSON object on stdout**. Anything else (or invalid JSON) is treated as advisory only.\n\n```typescript\n\/\/ Universal fields\ninterface HookOutput {\n  continue?: boolean;             \/\/ false = stop the agent now (Stop family)\n  decision?: \"approve\" | \"block\"; \/\/ gate verdict\n  reason?: string;                \/\/ shown to user \/ logged\n  systemMessage?: string;         \/\/ injected as system message (UserPromptSubmit, SessionStart)\n  hookSpecificOutput?: Record<string, unknown>;\n}\n```\n\nPreToolUse \u2014 block \/ approve \/ rewrite a tool call:\n```json\n{ \"decision\": \"approve\", \"reason\": \"Edit on src\/ allowed\" }\n{ \"decision\": \"block\",   \"reason\": \"Write outside src\/ rejected\" }\n```\n\nStop \u2014 block prevents finalization until issues are fixed:\n```json\n{ \"continue\": true, \"decision\": \"block\", \"reason\": \"Uncommitted files\" }\n```\n\nSessionStart \u2014 inject context:\n```json\n{ \"systemMessage\": \"ROUTINE: research \u2192 plan \u2192 implement \u2192 test \u2192 commit\" }\n```\n\n## 5. Exit-code semantics\n\n| Exit | Meaning |\n|---|---|\n| `0` | Success \u2014 JSON output applied if present |\n| `2` | **Blocking** \u2014 message printed to stderr is shown to the user (alternative to `decision: \"block\"`) |\n| anything else | Non-blocking error \u2014 logged, agent continues |\n\n**Never** exit non-zero on a transient error (e.g. network) unless you intend to block. Hooks must be deterministic.\n\n## 6. `settings.json` registration\n\n```json\n{\n  \"hooks\": {\n    \"SessionStart\": [\n      {\n        \"hooks\": [{\n          \"type\": \"command\",\n          \"command\": \"bash \\\"$CLAUDE_PROJECT_DIR\/.claude\/hooks\/run-hook.sh\\\" session-start\",\n          \"timeout\": 10\n        }]\n      }\n    ],\n    \"UserPromptSubmit\": [\n      {\n        \"matcher\": \"\",\n        \"hooks\": [{\n          \"type\": \"command\",\n          \"command\": \"bash \\\"$CLAUDE_PROJECT_DIR\/.claude\/hooks\/run-hook.sh\\\" user-prompt-submit\",\n          \"timeout\": 10\n        }]\n      }\n    ],\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Bash|Write|Edit\",\n        \"hooks\": [{\n          \"type\": \"command\",\n          \"command\": \"bash \\\"$CLAUDE_PROJECT_DIR\/.claude\/hooks\/run-hook.sh\\\" pre-tool-use\",\n          \"timeout\": 10\n        }]\n      }\n    ],\n    \"Stop\": [\n      {\n        \"hooks\": [{\n          \"type\": \"command\",\n          \"command\": \"bash \\\"$CLAUDE_PROJECT_DIR\/.claude\/hooks\/run-hook.sh\\\" stop-validator\",\n          \"timeout\": 30\n        }]\n      }\n    ]\n  }\n}\n```\n\n`matcher` is a regex against `tool_name` (PreToolUse \/ PostToolUse) or empty for \"all\". Multiple entries per event are run in registration order.\n\n## 7. `run-hook.sh` dispatcher\n\nSurvives whichever runtime the user has installed. Always-zero exit so hook errors don't kill the session.\n\n```bash\n#!\/usr\/bin\/env bash\n# .claude\/hooks\/run-hook.sh\nset -uo pipefail\nHOOK_NAME=\"${1:?missing hook name}\"\nHOOK_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nHOOK_FILE=\"$HOOK_DIR\/${HOOK_NAME}.ts\"\n\n[[ -f \"$HOOK_FILE\" ]] || { echo '{\"continue\":true}'; exit 0; }\n\nif   command -v bun >\/dev\/null 2>&1; then bun  \"$HOOK_FILE\"\nelif command -v tsx >\/dev\/null 2>&1; then tsx  \"$HOOK_FILE\"\nelif command -v node >\/dev\/null 2>&1; then npx --yes tsx \"$HOOK_FILE\"\nelse echo '{\"continue\":true}'; exit 0\nfi\n```\n\n## 8. Stop validator template (gate-aware, with cycle detection)\n\nUse `execFileSync` (not `execSync` with shell strings) \u2014 passes args as an array, immune to shell injection.\n\n```typescript\n#!\/usr\/bin\/env node\nimport { execFileSync } from 'node:child_process';\nimport { readFileSync, existsSync } from 'node:fs';\n\nfunction git(...args: string[]): string {\n  try { return execFileSync('git', args, { encoding: 'utf8' }).trim(); } catch { return ''; }\n}\n\nconst input = JSON.parse(readFileSync(0, 'utf8'));      \/\/ stdin\n\n\/\/ Cycle detection \u2014 if we already blocked once, approve to avoid infinite loop\nif (input.stop_hook_active) {\n  console.log(JSON.stringify({ continue: false, decision: 'approve' }));\n  process.exit(0);\n}\n\nconst dirty   = git('status', '--porcelain');\nconst issues: string[] = [];\n\nif (dirty)                                                    issues.push(`GIT_TREE_NOT_CLEAN: ${dirty.split('\\n').length} file(s)`);\nif (existsSync('CLAUDE.md') &&\n    !\/^## (Last Change|Recent Changes)\/m.test(readFileSync('CLAUDE.md', 'utf8'))) {\n  \/\/ Accepts the legacy `## Last Change` (single, overwritten) OR `## Recent Changes`\n  \/\/ (append-only LIFO, multi-instance safe \u2014 see claude-md-compactor \u00a76.1).\n  issues.push('CLAUDE_MD_NOT_UPDATED');\n}\n\nconst result = issues.length === 0\n  ? { continue: false, decision: 'approve', reason: 'All checks passed' }\n  : { continue: true,  decision: 'block',   reason: issues.join(' | ') };\n\nconsole.log(JSON.stringify(result));\nprocess.exit(0);\n```\n\n## 9. Performance & safety rules\n\n1. **Timeouts:** 10s for `UserPromptSubmit` \/ `PreToolUse` \/ `SessionStart`; 30s for `Stop` \/ `SubagentStop`.\n2. **Always exit 0** unless intentionally blocking with exit 2 \u2014 non-zero kills the session.\n3. **Read stdin with timeout** \u2014 `readFileSync(0, 'utf8')` is fine (it returns immediately when EOF).\n4. **Output valid JSON** \u2014 invalid JSON is treated as advisory and silently dropped.\n5. **Cycle detection** \u2014 check `stop_hook_active` in `Stop` \/ `SubagentStop`. Without this, a buggy hook can lock the agent in an infinite block-fix-block loop.\n6. **No network calls** in hot-path hooks (`PreToolUse`, `UserPromptSubmit`) \u2014 they fire on every tool call \/ prompt.\n7. **Idempotent** \u2014 hooks may be invoked twice (retries, restarts). Don't write to immutable state without a guard.\n8. **Use `execFileSync`, never `execSync` with a shell string** \u2014 the latter is shell-injection-prone if any input ever flows in.\n\n## 10. Common patterns\n\n| Goal | Event | Pattern |\n|---|---|---|\n| \"Inject the current routine on every prompt\" | `UserPromptSubmit` | `{ continue: true, systemMessage: \"ROUTINE: ...\" }` |\n| \"Block writes outside `src\/`\" | `PreToolUse` | match `Write\\|Edit`, inspect `tool_input.path`, `decision: \"block\"` if outside |\n| \"Run quality gate before finishing\" | `Stop` | run typecheck\/lint\/tests, `decision: \"block\"` if any fail |\n| \"Persist subagent output to disk\" | `SubagentStop` | parse `tool_response`, write to `.claude\/subagent-outputs\/{id}.json` |\n| \"Snapshot transcript before compaction\" | `PreCompact` | copy `transcript_path` to `.claude\/transcripts\/{session_id}.jsonl` |\n\n## FORBIDDEN\n\n| Pattern | Why |\n|---|---|\n| `process.exit(1)` on transient error | Kills the session |\n| Hook output not valid JSON | Dropped silently \u2014 no enforcement |\n| Network call in `PreToolUse` | Adds latency to every tool call |\n| Forgetting `stop_hook_active` check | Infinite block loop |\n| Writing to `CLAUDE.md` from `Stop` hook | Triggers another `Stop` cycle |\n| Hardcoded user paths (`~\/Users\/me\/...`) | Won't run on other machines |\n| Shell-string `execSync` for git\/fs commands | Shell-injection surface |\n\n## See Also\n\n- `quality-gate` \u2014 the Stop validator's typical payload\n- `git-workflow` \u2014 branch \/ dirty-tree checks\n- `commit-manager` \u2014 pairs with Stop validator (validator detects, commit-manager fixes)\n","use_cases":["Inject onboarding context during SessionStart","Block forbidden phrases in UserPromptSubmit","Approve or block tool calls in PreToolUse","Validate subagent output in SubagentStop","Snapshot transcripts before compaction in PreCompact"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/0x57-1\/start-vibing-stacks\/blob\/6e398b34c4dfe73ac8f809216b218856b8e02ff4\/stacks\/_shared\/skills\/hook-development\/SKILL.md","source_commit":"6e398b34c4dfe73ac8f809216b218856b8e02ff4","license":null,"version":null,"listing_approved_at":"2026-12-03","created_at":"2026-12-02T09:11:18.000000Z","updated_at":"2026-12-03T16:20:08.000000Z","seo_title":"Claude Code Hook Development for 2026","seo_description":"Create and modify Claude Code hooks for 2026, covering all 9 supported events. Hooks are deterministic and receive input as a JSON object on stdin. Output a JSON objecton","seo_keywords":["Claude Code hooks","hook development","deterministic hooks","SessionStart event","PreToolUse event","SubagentStop event","transcript compaction","stdin JSON contract"]}}