writing-hooks
Use when creating Claude Code hooks for code quality, static analysis, or workflow automation. Use when user says "add hook", "enforce linting", "add pre-commit check", "block bad code".
What this skill does
# Writing Hooks
## Overview
**Writing hooks IS creating automated quality gates.**
Hooks run on Claude Code events (PreToolUse, PostToolUse, etc.) and can block actions with exit code 2.
**Core principle:** Hooks enforce what humans forget. Fast checks only—slow hooks kill productivity.
**Violating the letter of the rules is violating the spirit of the rules.**
## Routing
**Pattern:** Skill Steps
**Handoff:** none
**Next:** none
## Task Initialization (MANDATORY)
Before ANY action, create task list using TaskCreate:
```
TaskCreate for EACH task below:
- Subject: "[writing-hooks] Task N: <action>"
- ActiveForm: "<doing action>"
```
**Tasks:**
0. Fetch latest official hook spec
1. Analyze requirements
2. RED - Test without hook
3. GREEN - Write hook script
4. Configure settings.json
5. Validate behavior
6. Test blocking
7. REFACTOR - Quality review
Announce: "Created 8 tasks (0–7). Starting execution..."
**Execution rules:**
1. `TaskUpdate status="in_progress"` BEFORE starting each task
2. `TaskUpdate status="completed"` ONLY after verification passes
3. If task fails → stay in_progress, diagnose, retry
4. NEVER skip to next task until current is completed
5. At end, `TaskList` to confirm all completed
## TDD Mapping for Hooks
| TDD Phase | Hook Creation | What You Do |
|-----------|---------------|-------------|
| **RED** | Test without hook | Write code, observe quality issues slip through |
| **Verify RED** | Document violations | Note specific issues that should be caught |
| **GREEN** | Write hook | Create script that catches those issues |
| **Verify GREEN** | Test blocking | Verify exit code 2 blocks violating code |
| **REFACTOR** | Optimize speed | Reduce hook runtime, filter file types |
## Task 0: Fetch Latest Official Spec
**Goal:** Pull the current Anthropic hook spec before designing — never trust cached memory.
**Action:**
```
Skill tool: fetching-claude-docs
component: hook
question: "hook events (PreToolUse, PostToolUse, etc.), matcher syntax,
exit code contract, settings.json schema, additionalContext field,
security considerations"
```
**Verification:** Received YAML with `source: https://code.claude.com/docs/en/hooks.md` and non-empty `spec_excerpt`. Use as authoritative reference; if any rule in this SKILL conflicts with the fetched spec, the fetched spec wins.
## Task 1: Analyze Requirements
**Goal:** Understand what quality gate to create.
**Questions to answer:**
- What violation should be blocked?
- Which files should be checked?
- What tool/command performs the check?
- What event triggers the hook?
- What is the project's primary language? (check `package.json`, `go.mod`, `Cargo.toml`, `pyproject.toml`, `*.csproj`, etc.)
**Event Selection:**
| Event | When | Use For |
|-------|------|---------|
| `PreToolUse` | Before tool runs | Block bad writes before they happen |
| `PostToolUse` | After tool runs | Validate written code |
| `UserPromptSubmit` | Before prompt processed | Add context to prompts |
| `Stop` | When agent tries to end its turn | Self-verify loop — block stop until checks pass (Ralph Wiggum pattern, enables L-Thread) |
**Verification:** Can describe the violation and the command to detect it.
## Task 2: RED - Test Without Hook
**Goal:** Write code WITHOUT the hook. Observe violations that slip through.
**Process:**
1. Ask agent to write code in the target file type
2. Intentionally introduce the violation (bad format, type error, etc.)
3. Observe that Claude Code doesn't catch it
4. Document the specific violation
**Verification:** Documented at least 1 violation that should have been caught.
## Task 3: GREEN - Write Hook Script
**Goal:** Create Python script that catches the violations you documented.
### Hook Structure
```
.claude/hooks/
├── eslint_check.py
├── prettier_check.py
└── typecheck.py
```
### Exit Code Contract
| Code | Meaning | Effect |
|------|---------|--------|
| 0 | Pass | Continue, stdout shown in verbose |
| 2 | Block | Action blocked, stderr fed to Claude |
| Other | Warning | Continue, stderr shown in verbose |
### Hook Template
See [references/static-checks.md](references/static-checks.md) for complete hook templates. For performance-optimized security hooks, see [references/performance-optimization.md](references/performance-optimization.md). Key pattern: read JSON from stdin, filter by extension, run check, exit 2 to block.
### Stop Event Self-Verify (Ralph Wiggum / L-Thread)
When the agent tries to end its turn, block until deterministic checks pass — turning a one-shot agent into a loop that won't quit until the work is actually done.
**Use when:** long-running tasks, refactors, migrations, anything where "I think I'm done" is unreliable.
**Shape:**
```python
# .claude/hooks/stop_verify.py
import json, subprocess, sys
data = json.load(sys.stdin)
# Avoid infinite loop: respect stop_hook_active to bail after one retry
if data.get("stop_hook_active"):
sys.exit(0)
result = subprocess.run(["pytest", "-x", "--tb=short"], capture_output=True, text=True)
if result.returncode != 0:
print(result.stdout[-2000:], file=sys.stderr)
sys.exit(2) # Block stop, feed stderr to Claude
sys.exit(0)
```
```json
{
"hooks": {
"Stop": [{
"hooks": [{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/stop_verify.py",
"timeout": 120
}]
}]
}
}
```
**Critical:** always check `stop_hook_active` to bail after one retry — otherwise the agent loops forever on unfixable failures.
### Critical Requirements
- **Fast** - Under 5 seconds, hooks run synchronously
- **Performance constraints** - Total execution < 30s, parallel processing support
- **Graceful degradation** - Handle timeouts without blocking development
- **Filter files** - Only check relevant extensions
- **Limit output** - First 5-10 errors, not all
- **Use Python** - Cross-platform, wrapped shell commands. In settings.json command, prefer `uv` → fallback `python3` → fallback `python` (see [cross-platform-scripts.md](../../references/cross-platform-scripts.md))
- **Progressive checks** - Fast/standard/thorough modes based on context
- **Cross-platform** - Must work on macOS, Linux, AND Windows
### Windows Compatibility (MANDATORY)
**Important:** Read [cross-platform-scripts.md](../../references/cross-platform-scripts.md) for full cross-platform rules covering paths, shell commands, line endings, and common pitfalls.
**Verification:**
- [ ] Script is executable (`chmod +x`) — skip on Windows
- [ ] Returns exit code 0 for valid files
- [ ] Returns exit code 2 for violations
- [ ] Runs under 5 seconds
- [ ] Uses `pathlib.Path` for all path operations
- [ ] No `shell=True` with string commands (use list args)
- [ ] No hardcoded `/tmp/` or path separators
- [ ] settings.json command uses three-runner fallback template (`uv` → `python3 --version` → `python`); `python3` probed by `--version` to avoid Windows Microsoft Store stub
## Task 4: Configure settings.json
**Goal:** Register hook in `.claude/settings.json`.
**Important:** Use `.claude/settings.json`, NOT `settings.local.json`. Settings are team-shared.
### Configuration Format
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [{
"type": "command",
"command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/eslint_check.py",
"timeout": 30
}]
}
]
}
}
```
### Matcher Patterns
| Matcher | Matches |
|---------|---------|
| `Write\|Edit` | Write or Edit tools |
| `Bash` | Bash tool only |
| `.*` | All tools |
**Verification:**
- [ ] Hook registered in correct event
- [ ] Matcher targets correct tools
- [ ] Command path uses `$CLAUDE_PROJECT_DIR`
- [ ] Timeout is reasonable (5-30 seconds)
## Task 5: Validate Behavior
**Goal:** Verify hook script works correctly.
**Test command:**
```bash
echo '{"tool_input":{"file_path":"test.ts"}}' | .claude/hooks/youRelated in AI Agents
skill-development
IncludedComprehensive meta-skill for creating, managing, validating, auditing, and distributing Claude Code skills and slash commands (unified in v2.1.3+). Provides skill templates, creation workflows, validation patterns, audit checklists, naming conventions, YAML frontmatter guidance, progressive disclosure examples, and best practices lookup. Use when creating new skills, validating existing skills, auditing skill quality, understanding skill architecture, needing skill templates, learning about YAML frontmatter requirements, progressive disclosure patterns, tool restrictions (allowed-tools), skill composition, skill naming conventions, troubleshooting skill activation issues, creating custom slash commands, configuring command frontmatter, using command arguments ($ARGUMENTS, $1, $2), bash execution in commands, file references in commands, command namespacing, plugin commands, MCP slash commands, Skill tool configuration, or deciding between skills vs slash commands. Delegates to docs-management skill for official documentation.
reprompter
IncludedTransform messy prompts into well-structured, effective prompts — single or multi-agent. Use when: "reprompt", "reprompt this", "clean up this prompt", "structure my prompt", rough text needing XML tags and best practices, "reprompter teams", "repromptception", "run with quality", "smart run", "smart agents", multi-agent tasks, audits, parallel work, anything going to agent teams. Don't use when: simple Q&A, pure chat, immediate execution-only tasks. See "Don't Use When" section for details. Outputs: Structured XML/Markdown prompt, quality score (before/after), optional team brief + per-agent sub-prompts, agent team output files. Success criteria: Single mode quality score ≥ 7/10; Repromptception per-agent prompt quality score 8+/10; all required sections present, actionable and specific.
adaptive-compaction
IncludedAdaptive add-on policy and recovery layer that decides WHEN to compact, prune, snapshot, or fork -- replacing fixed-percent auto-compaction across Claude Code, Codex, and MCP-capable hosts. Trigger on auto-compact timing or damage: "when should I compact", "is it safe to compact now or start a fresh session", "auto-compact fires too early/mid-task", "switching to an unrelated task but the window still has space", "context rot", "answers get worse the longer the session runs", "the agent forgot the plan or my decisions after it summarized", "add a layer on top that manages context without changing the agent", raising autoCompactWindow to give the policy room, or installing/tuning a cross-tool compaction policy or PreCompact hook -- even when "compaction" is never said but the problem is context-window pressure or post-summarization memory loss. Do NOT use to summarize a conversation, build RAG, write a summarization prompt (decides WHEN not HOW), or answer max-context-length trivia.
agent-skill-creator
IncludedCreate cross-platform agent skills from workflow descriptions. Activates when users ask to create an agent, automate a repetitive workflow, create a custom skill, or need advanced agent creation. Triggers on phrases like create agent for, automate workflow, create skill for, every day I have to, daily I need to, turn process into agent, need to automate, create a cross-platform skill, validate this skill, export this skill, migrate this skill. Supports single skills, multi-agent suites, transcript processing, template-based creation, interactive configuration, cross-platform export, and spec validation.
llm-wiki
IncludedUse when building or maintaining a persistent personal knowledge base (second brain) in Obsidian where an LLM incrementally ingests sources, updates entity/concept pages, maintains cross-references, and keeps a synthesis current. Triggers include "second brain", "Obsidian wiki", "personal knowledge management", "ingest this paper/article/book", "build a research wiki", "compound knowledge", "Memex", or whenever the user wants knowledge to accumulate across sessions instead of being re-derived by RAG on every query.
skill-master
IncludedAgent Skills authoring, evaluation, and optimization. Create, edit, validate, benchmark, and improve skills following the agentskills.io specification. Use when designing SKILL.md files, structuring skill folders (references, scripts, assets), ingesting external documentation into skills, running trigger evals, benchmarking skill quality, optimizing descriptions, or performing blind A/B comparisons. Keywords: agentskills.io, SKILL.md, skill authoring, eval, benchmark, trigger optimization.