notque/vexjoy-agent / skills/meta/toolkit
toolkit
VerifiedToolkit management: create and evaluate skills and agents, manage routing tables, generate Claude.md.
references/toolkit-governance/hook-standardization.md
View on GitHub# Hook Standardization Reference
> **Scope**: Hook event types, settings.json registration format, exit code conventions, output protocols, timeout configuration, and common hook failure modes. Does not cover frontmatter compliance (see frontmatter-compliance.md).
> **Version range**: Claude Code hooks system (all current versions)
> **Generated**: 2026-04-15
---
## Overview
Hooks are shell commands registered in `settings.json` that execute in response to Claude Code lifecycle events. The most common failure modes are: wrong exit code (non-zero blocks Claude unexpectedly), missing `timeout` (hooks that hang stall the session indefinitely), and using `sys.stdin.isatty()` to detect TTY state (always False in hook context — hooks run with piped stdin).
---
## Event Type Reference
| Event | When Fires | `once` Default | Typical Timeout (seconds) |
|-------|------------|---------------|-----------------|
| `SessionStart` | Session begins | `true` | 5–10 |
| `UserPromptSubmit` | Before prompt is processed | — | 5 |
| `PreToolUse` | Before a tool executes | — | 5 (gates: 10) |
| `PostToolUse` | After a tool returns | — | 5 |
| `PreCompact` | Before context compression | `true` | 5 |
| `PostCompact` | After context compression | — | 5 |
| `SubagentStart` | Before a subagent starts | — | 5 |
| `SubagentStop` | After subagent finishes | — | 5 |
| `StopFailure` | Session ends with error | — | 5 |
| `Stop` | After every turn | — | 5–10 |
| `SessionEnd` | Session ends | — | 5 |
Claude Code reads `timeout` in **seconds**, so `"timeout": 3000` means 50 minutes, not 3 seconds. The timeout is a kill limit, not a latency budget: keep critical-path hooks fast in code, and give gates headroom, because a gate killed by its timeout cannot deny the call.
---
## settings.json Registration Format
```json
{
"hooks": {
"SessionStart": [
{
"hooks": [
{
"type": "command",
"command": "sh \"$HOME/.claude/hooks/lib/pyrun.sh\" \"$HOME/.claude/hooks/my-hook.py\"",
"description": "One-line description of what the hook does",
"timeout": 10,
"once": true
}
]
}
],
"PostToolUse": [
{
"hooks": [
{
"type": "command",
"command": "sh \"$HOME/.claude/hooks/lib/pyrun.sh\" \"$HOME/.claude/hooks/security-review-hook.py\"",
"description": "Scan edited files for security risks",
"timeout": 5
}
]
}
]
}
}
```
| Field | Required | Type | Notes |
|-------|----------|------|-------|
| `type` | yes | `"command"` | Only `"command"` is currently supported |
| `command` | yes | string | Use the launcher form shown above, exactly; it runs the installer-linked python 3.10+ (`docs/installer-layout.md`, Hook interpreter). Before registering, stamp the version guard: `python3 scripts/hook-pyguard.py --apply --file hooks/<file>.py` |
| `description` | yes | string | Shown in session startup output |
| `timeout` | recommended | number (seconds) | Omitting leaves the runtime default kill limit; a value written in milliseconds becomes a very long limit |
| `once` | no | boolean | `true` = run only once per session (SessionStart default) |
Agent frontmatter `hooks:` use the same shape: each event maps to a list of matcher groups, and each group holds its own `hooks:` list (`- matcher: "Edit|Write"` then `hooks:` then `- type: command`). When a bare `- type: command` entry sits directly under PostToolUse or another non-guard event, Claude Code drops it with the note `Hook matcher "hooks" must be an array of hook entries; received undefined; entry ignored`, so the hook never runs. Under PreToolUse or PermissionRequest the same mistake is worse: Claude Code applies nothing from the agent file until the entry is fixed.
---
## Two-File Architecture (settings.json)
Hook registrations exist in **two** settings.json files. Editing the wrong one is the most common hook registration failure.
| File | Role | Persistence |
|------|------|-------------|
| `.claude/settings.json` (repo) | **Source of truth.** Version-controlled. All hook registrations go here. | Permanent — survives sessions, commits, deploys |
| `~/.claude/settings.json` (user home) | **Runtime copy.** Rebuilt by `sync-to-user-claude.py` at every SessionStart. | Ephemeral — overwritten on next session start |
**Rule:** Register hooks in the repo file only. Edits to `~/.claude/settings.json` are overwritten by the sync hook within seconds of the next session starting.
**Sync mechanism:** `hooks/sync-to-user-claude.py` runs as the first SessionStart hook. It copies `agents/`, `skills/`, `hooks/`, and merges `.claude/settings.json` into `~/.claude/settings.json`. This enables hooks to work from any working directory, not just the toolkit repo.
---
## Correct Patterns
### Always Exit 0
All hooks must exit 0. Non-zero exit codes block Claude from proceeding.
```python
#!/usr/bin/env python3
"""Hook docstring explaining purpose and advisory/blocking intent."""
import sys
def main():
# ... hook logic ...
pass
if __name__ == "__main__":
try:
main()
except Exception:
pass # Never let exceptions propagate as non-zero exit
sys.exit(0) # Explicit exit 0
```
**Why**: Hooks that exit non-zero act as blockers — Claude cannot continue until the user resolves the exit. Advisory hooks (the vast majority) must always exit 0, even on internal error, to avoid stalling the session.
---
### Read Event JSON from stdin
Hooks receive the triggering event as JSON on stdin.
```python
import json
import sys
def read_event() -> dict:
"""Read hook event from stdin. Returns empty dict on parse failure."""
try:
raw = sys.stdin.read()
if not raw.strip():
return {}
return json.loads(raw)
except (json.JSONDecodeError, OSError):
return {}
event = read_event()
tool_name = event.get("tool_name", "")
tool_input = event.get("tool_input") or {}
tool_response = event.get("tool_response", {})
```
**Why**: Hooks that skip stdin reading miss the event context. For `PostToolUse`, the event carries `tool_name`, `tool_input`, and `tool_response`; a hook that reads other keys (`tool`, `tool_result`, `output`) gets empty values and never fires.
---
### Inject Context via stdout
Hooks inject context into Claude's prompt by printing `hookSpecificOutput.additionalContext` JSON to stdout.
```python
from hook_utils import context_output, empty_output # hooks/lib/hook_utils.py
# Inject context (appears as a system-reminder in Claude's context)
context_output("PostToolUse", "[hook-name] Action suggested: fix the broken reference").print_and_exit()
# prints {"hookSpecificOutput": {"hookEventName": "PostToolUse", "additionalContext": "..."}}
# Silent hook — print nothing when there's nothing to report
# (preferred: hooks should be silent when they have no signal)
empty_output("PostToolUse").print_and_exit()
```
Plain-text stdout reaches the model only for `SessionStart` and `UserPromptSubmit`; for `PostToolUse` and the other tool events it shows in the transcript only, so a plain `print()` reminder there never reaches the model.
**Why**: Hooks that always print output — even when silent — add noise to every interaction. Hooks should only print when they have a signal to communicate.
---
### Timeout Configuration by Event Type
```json
"SessionStart": { "timeout": 10 } // Sync operations, file reads (seconds)
"UserPromptSubmit": { "timeout": 5 } // Must be fast in code — blocks prompt processing
"PreToolUse": { "timeout": 10 } // Gates: headroom, since a killed gate cannot deny
"PostToolUse": { "timeout": 5 } // Advisory; runs after tool completes
"Stop": { "timeout": 10 } // Session ending — can afford more time
```
**Why**: `timeout` is in seconds. `UserPromptSubmit` and `PreToolUse` hooks are on the critical path — they block user interaction, so their code must finish in well under a second; the timeout only caps a hang. `Stop` and `SessionStart` hooks can afford longer limits since they don't block active work.
---
## Gate vs Advisory Classification
PreToolUse hooks split into **gates** (can block tool execution) and **advisory** (context injection only). This distinction matters for exit code behavior and testing.
### Gates (9 hooks — block on violation)
| Hook | Matcher | Blocking Mechanism |
|------|---------|-------------------|
| `pretool-unified-gate.py` | Bash\|Write\|Edit | JSON `permissionDecision: deny` (exit 0) |
| `pretool-branch-safety.py` | Bash | JSON `permissionDecision: deny` (exit 0) |
| `ci-merge-gate.py` | Bash | JSON `permissionDecision: deny` (exit 0) — **non-functional**: uses `gh pr checks --json conclusion` but `conclusion` is invalid; use `bucket` |
| `pretool-ruff-format-gate.py` | Bash | JSON `permissionDecision: deny` (exit 0) |
| `pretool-review-before-push-gate.py` | Bash | JSON `permissionDecision: deny` (exit 0); denies on crash once a push or PR is detected |
| `pretool-synthesis-gate.py` | Write\|Edit | JSON `permissionDecision: deny` (exit 0) |
| `pretool-plan-gate.py` | Write\|Edit | JSON `permissionDecision: deny` (exit 0) |
| `pretool-adr-creation-gate.py` | Write | JSON `permissionDecision: deny` (exit 0) |
| `pipeline-phase-gate.py` | Write\|Edit | **exit(2)** — inconsistent with other gates; should migrate to JSON `permissionDecision: deny` |
### Advisory (7 hooks — context injection only)
| Hook | Matcher | Purpose |
|------|---------|---------|
| `suggest-compact.py` | (all) | Suggest `/compact` at edit threshold |
| `pretool-learning-injector.py` | Bash\|Edit | Inject known error patterns |
| `pretool-prompt-injection-scanner.py` | Write\|Edit | Warn about prompt injection |
| `pretool-file-backup.py` | Edit | Backup files before modification |
| `reference-loading-enforcer.py` | Agent | Inject reference loading requirements |
| `creation-protocol-enforcer.py` | Agent | Soft-warn on creation without ADR |
---
## Hook Output Conventions
Hooks use three stdout output patterns. All work, but new hooks should prefer JSON with `additionalContext` for advisory output and JSON with `permissionDecision` for gates.
| Pattern | When to Use | Example |
|---------|-------------|---------|
| JSON `additionalContext` | Advisory context injection — Claude sees it as system context | `{"additionalContext": "[hook-name] Warning: ..."}` |
| JSON `permissionDecision` | Gates that block tool execution | `{"permissionDecision": "deny", "permissionDecisionReason": "..."}` |
| Plain text to stdout | Simple informational output | `print("[hook-name] 3 patterns loaded")` |
**Preferred pattern for new hooks:** Use `hooks/lib/hook_utils.py` helpers:
- `context_output(event, content)` — advisory context injection
- `user_message_output(event, msg)` — critical notifications that must reach the user verbatim
- `empty_output(event)` — silent exit when nothing to report
---
## Pattern Catalog
<!-- no-pair-required: section header with no content -->
### Set Timeout on Every Hook
**Detection**:
```bash
# Find hooks registered without timeout field
python3 -c "
import json
settings = json.load(open('$HOME/.claude/settings.json'))
for event, groups in settings.get('hooks', {}).items():
for group in groups:
for hook in group.get('hooks', []):
if 'timeout' not in hook:
print(f'NO TIMEOUT: [{event}] {hook.get(\"description\", hook.get(\"command\", \"?\"))}')
"
```
**Signal**:
```json
{
"type": "command",
"command": "sh \"$HOME/.claude/hooks/lib/pyrun.sh\" \"$HOME/.claude/hooks/my-hook.py\"",
"description": "Does something"
}
```
**Why this matters**: Without `timeout`, a hook that hangs (network call, waiting for input) stalls the session indefinitely. Claude cannot proceed until the hook exits or the user kills it.
**Preferred action:**
Always add `"timeout"` to every hook entry in `settings.json`, in seconds. Use 5 for informational and `UserPromptSubmit` hooks, 10 for `PreToolUse` gates, and up to 10 for `SessionStart` hooks doing file reads. Run the detection script above to find any hooks currently missing this field.
**Preferred action**: Always set `"timeout"` in seconds. Use 5 as a safe default for informational hooks and 10 for gates.
---
### Detect Session Type via Environment Variables
**Detection**:
```bash
grep -rn "stdin.isatty\|stdout.isatty" ~/.claude/hooks/*.py
```
**Signal**: <!-- no-pair-required: sub-block split by code-comment heading; Do instead is inline below -->
```python
# In a hook — WRONG
if sys.stdin.isatty():
print("Interactive session")
else:
print("Non-interactive — activating AFK mode")
```
**Why this matters**: Claude Code pipes stdin (the event JSON) into hooks and captures stdout (the hook output). Both are always non-TTY in hook context, so `isatty()` always returns False — every session is classified as non-interactive regardless of actual session type.
**Preferred action:**
Detect session type using environment variables: check `SSH_CONNECTION` or `SSH_TTY` for SSH sessions, `TMUX` for tmux sessions, and `TERM_PROGRAM` for terminal type. Replace any `isatty()` call with an environment variable check as shown in the Fix code below.
**Preferred action**: Detect session type via environment variables instead.
```python
import os
is_ssh = bool(os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_TTY"))
is_tmux = bool(os.environ.get("TMUX"))
is_afk = is_ssh or is_tmux
```
---
### Exit 0 in Advisory Hooks
**Detection**:
```bash
# Find hooks that call sys.exit with non-zero values
grep -rn "sys.exit([^0)]" ~/.claude/hooks/*.py
grep -rn "exit(1\|exit(2\|exit(-" ~/.claude/hooks/*.py
```
**Signal**:
```python
def main():
if not validate_something():
print("Validation failed")
sys.exit(1) # WRONG for advisory hook
```
**Why this matters**: Exit code 1 signals Claude to block and surface the error to the user. For advisory hooks (lint hints, context injection, learning), this is almost always wrong — the hook should report its finding and exit 0 so Claude can continue.
**Preferred action:**
Wrap all hook logic in a `try/except` block and call `sys.exit(0)` unconditionally at the end. Only use non-zero exit codes in deliberately blocking hooks (e.g., branch safety gates, ADR creation guards) where preventing Claude from proceeding is the intended behavior.
**Preferred action**: Wrap all hook logic in try/except and always exit 0. Only use non-zero exit for deliberately blocking hooks (branch safety gates, ADR creation guards).
```python
try:
main()
except Exception:
pass
sys.exit(0)
```
---
### Deploy Hook File Before Registering in settings.json
**Detection**:
```bash
# Check that all registered hook commands reference files that exist
python3 -c "
import json, os, re
settings = json.load(open(os.path.expanduser('~/.claude/settings.json')))
for event, groups in settings.get('hooks', {}).items():
for group in groups:
for hook in group.get('hooks', []):
cmd = hook.get('command', '')
m = re.search(r'[\"\047]([^\"\047]+\.py)[\"\047]', cmd)
if m:
path = os.path.expandvars(m.group(1))
if not os.path.exists(path):
print(f'MISSING: [{event}] {path}')
"
```
**Why this matters**: Registering a hook before deploying the file causes a startup error on every session. The hook runs, finds no file, and exits non-zero — blocking or noising every session until fixed.
**Preferred action:**
Deploy the hook Python file to `~/.claude/hooks/` first, verify it exists with `ls ~/.claude/hooks/my-hook.py`, and only then add its entry to `settings.json`. Use `scripts/register-hook.py` to enforce this ordering mechanically rather than relying on memory.
**Preferred action**: Always deploy the hook file to `~/.claude/hooks/` BEFORE adding its entry to `settings.json`.
---
## Error-Fix Mappings
| Symptom | Root Cause | Fix |
|---------|------------|-----|
| Session startup fails or hangs | Hook missing `timeout` and hangs | Add `"timeout": 10` (seconds) to the hook config |
| A hung hook stalls the session for many minutes | `timeout` written in milliseconds (`3000`) is read as seconds (50 minutes) | Write seconds: `5` for advisory hooks, `10` for gates |
| Every session classified as AFK | `sys.stdin.isatty()` check in hook | Replace with `os.environ.get("SSH_CONNECTION")` check |
| Hook blocks Claude from proceeding | Advisory hook exits non-zero | Wrap in try/except, call `sys.exit(0)` unconditionally |
| Hook registered but errors on startup | Hook file not deployed to `~/.claude/hooks/` | Deploy file first, then register in settings.json |
| Hook runs multiple times per session | Missing `"once": true` on SessionStart hook | Add `"once": true` for one-time session initialization hooks |
| Hook output appears as noise every turn | Hook prints even when no signal | Add early-return guard: only print when there's something to report |
| Hook registration disappears after restart | Registered in `~/.claude/settings.json` (runtime copy) | Register in `.claude/settings.json` (repo) — see Two-File Architecture above |
| Hook depends on nonexistent file | Script imports or shells to a file that was removed/never created | Verify all dependencies exist before registering |
| Gate uses wrong `gh` API field | `gh pr checks --json conclusion` — `conclusion` is not a valid field | Use `bucket` field instead of `conclusion`; known case: `ci-merge-gate.py` |
| Duplicate detection across hooks | Multiple hooks scan for the same vulnerability class | Keep one hook per scanner engine. Known case: `posttool-security-scan.py` duplicated the PostToolUse path of `security-review-hook.py` and was removed |
| Gate uses exit(2) instead of JSON deny | Inconsistent blocking mechanism across gate hooks | Migrate to `{"permissionDecision": "deny", "permissionDecisionReason": "..."}` pattern; known case: `pipeline-phase-gate.py` |
| error-learner captures non-error output | Hook stdout parsed as "error" by error-learner | Ensure non-error hooks output structured JSON (not plain text that matches error patterns), or scope error-learner's detection |
## Hook Health Status (as of 2026-05-15)
**58/60 registered hooks functional.** 2 non-functional:
| Hook | Event | Issue | Status |
|------|-------|-------|--------|
| `ci-merge-gate.py` | PreToolUse (Bash) | Uses `gh pr checks --json conclusion` — `conclusion` is not a valid field name; should use `bucket` | Fix pending |
| Retired agent grading hook | PostToolUse (Write\|Edit) | Depended on a missing evaluation harness | Retired 2026-09-04 |
### Registered Hook Inventory by Event
Counts are command entries in `.claude/settings.json` on 2026-11-09. The file is the source of truth: recount it before you rely on a number here.
| Event | Count | Notes |
|-------|-------|-------|
| SessionStart | 18 | sync, context loading, environment detection (17 hook files plus `session-bootstrap.sh`) |
| UserPromptSubmit | 8 | pipeline detection, prompt capture, routing-outcome finalizer |
| PreToolUse | 21 | safety gates, branch safety, config protection, context injection |
| PostToolUse | 16 | lint, security scan, routing decisions, index refresh |
| PreCompact | 1 | archive the session transcript |
| PostCompact | 1 | re-inject plan context |
| SubagentStart | 1 | warm-start context for the subagent |
| SubagentStop | 5 | completion guard, routing-outcome recorder, state tracking |
| StopFailure | 1 | failure recording |
| Stop | 4 | summary, routing-outcome fallback (errored or stale), rules distill, drift guard |
| SessionEnd | 1 | routing-outcome fallback (every pending outcome) |
| **Total** | **77** | 76 hook-file registrations plus `session-bootstrap.sh` |
Other hook files exist in `hooks/` but are not registered in settings.json (retired, superseded by the unified gate, or feature-flagged).
---
## Detection Commands Reference
```bash
# List all registered hooks with their events and descriptions
python3 -c "
import json, os
settings = json.load(open(os.path.expanduser('~/.claude/settings.json')))
for event, groups in settings.get('hooks', {}).items():
for group in groups:
for hook in group.get('hooks', []):
timeout = hook.get('timeout', 'MISSING')
once = hook.get('once', False)
desc = hook.get('description', '?')
print(f'[{event}] timeout={timeout} once={once} — {desc}')
"
# Find hooks with missing timeout
python3 -c "
import json, os
s = json.load(open(os.path.expanduser('~/.claude/settings.json')))
for ev, groups in s.get('hooks', {}).items():
for g in groups:
for h in g.get('hooks', []):
if 'timeout' not in h: print(f'NO TIMEOUT [{ev}]: {h.get(\"description\",\"?\")}')
"
# Find hook files with sys.exit non-zero
grep -rn "sys.exit([^0)]" ~/.claude/hooks/*.py
# Find hook files using isatty (TTY detection anti-pattern) <!-- no-pair-required: detection command label, not an anti-pattern block -->
grep -rn "isatty" ~/.claude/hooks/*.py
# Verify all registered hook files exist on disk
python3 -c "
import json, os, re
s = json.load(open(os.path.expanduser('~/.claude/settings.json')))
for ev, groups in s.get('hooks', {}).items():
for g in groups:
for h in g.get('hooks', []):
m = re.search(r'[\"\047]([^\"\047]+\.py)[\"\047]', h.get('command',''))
if m:
p = os.path.expandvars(m.group(1))
if not os.path.exists(p): print(f'MISSING [{ev}]: {p}')
"
```
---
## See Also
- `frontmatter-compliance.md` — agent/skill YAML field standards
- `routing-table-patterns.md` — routing entry validation
- `skills/meta/do/references/hooks-guide.md` — hook event types overview
- `~/.claude/hooks/` — deployed hook files
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis. | Stars: 471k | Updated | Claude CodeCodex | Verified | Install |
| diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness. | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependencies | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |