claude-code-commands
Provides a detailed reference for creating Claude Code slash commands with argument handling, file inclusion, bash execution, and hook integration. Includes practical templates for common workflows like code review, testing, and multi-agent orchestration.
Packaged view
This page reorganizes the original catalog entry around fit, installability, and workflow context first. The original raw source lives below.
Install command
npx @skill-hub/cli install vasilyu1983-ai-agents-public-claude-code-commands
Repository
Skill path: frameworks/shared-skills/skills/claude-code-commands
Provides a detailed reference for creating Claude Code slash commands with argument handling, file inclusion, bash execution, and hook integration. Includes practical templates for common workflows like code review, testing, and multi-agent orchestration.
Open repositoryBest for
Primary workflow: Ship Full Stack.
Technical facets: Full Stack, Testing, Integration.
Target audience: Claude Code users who want to create custom slash commands for repetitive tasks, team leads establishing coding standards, and developers building automated workflows with Claude..
License: Unknown.
Original source
Catalog source: SkillHub Club.
Repository owner: vasilyu1983.
This is still a mirrored public skill entry. Review the repository before installing into production workflows.
What it helps with
- Install claude-code-commands into Claude Code, Codex CLI, Gemini CLI, or OpenCode workflows
- Review https://github.com/vasilyu1983/AI-Agents-public before adding claude-code-commands to shared team environments
- Use claude-code-commands for meta workflows
Works across
Favorites: 0.
Sub-skills: 0.
Aggregator: No.
Original source / Raw SKILL.md
---
name: claude-code-commands
description: Create slash commands for Claude Code with $ARGUMENTS handling, agent invocation patterns, and template best practices. Reference for building user-triggered workflow shortcuts.
---
# Claude Code Commands — Meta Reference
This skill provides the definitive reference for creating Claude Code slash commands. Use this when building new commands or improving existing command patterns.
---
## When to Use This Skill
Use this skill when you need to:
- Create a new slash command for repeated workflows
- Add `$ARGUMENTS` handling to commands
- Invoke agents from commands
- Include file context or bash output in commands
- Organize commands for team sharing
---
## Quick Reference
| Component | Purpose | Example |
|-----------|---------|---------|
| Filename | Command name | `review.md` → `/review` |
| Content | Prompt template | Instructions for Claude |
| `$ARGUMENTS` | User input | `/review auth.js` → `$ARGUMENTS = "auth.js"` |
| `$1`, `$2` | Positional args | `/compare a.js b.js` → `$1 = "a.js"` |
| `@file` | Include file | `@CLAUDE.md` includes file contents |
| `!command` | Bash output | `!git status` includes command output |
## Command Locations
| Location | Scope | Use For |
|----------|-------|---------|
| `.claude/commands/` | Project | Team-shared commands (version control) |
| `~/.claude/commands/` | Personal | Cross-project commands (not shared) |
## Command Structure
```text
.claude/commands/
├── review.md # /review
├── test.md # /test
├── security-scan.md # /security-scan
└── deploy.md # /deploy
```
---
## Command Template
```markdown
---
description: Brief description for SlashCommand tool integration
---
# Command Title
[Clear instructions for what this command does]
User request: $ARGUMENTS
## Steps
1. [First action Claude should take]
2. [Second action]
3. [Third action]
## Output Format
[Specify expected output structure]
```
The `description:` frontmatter is required for the SlashCommand tool to reference the command.
---
## $ARGUMENTS Usage
### Single Argument
```markdown
# Code Review
Review the following file or code for quality, security, and best practices:
$ARGUMENTS
Focus on:
- Code quality issues
- Security vulnerabilities
- Performance concerns
- Best practice violations
```
**Usage**: `/review src/auth.js`
### Multiple Arguments
```markdown
# Compare Files
Compare these two files and explain the differences:
$ARGUMENTS
Provide:
- Line-by-line diff
- Semantic changes
- Impact analysis
```
**Usage**: `/compare old.js new.js`
### Optional Arguments
```markdown
# Run Tests
Run tests for the specified scope.
Scope: $ARGUMENTS
If no scope specified, run all tests.
If scope is a file, run tests for that file.
If scope is a directory, run tests in that directory.
```
**Usage**: `/test` or `/test auth/` or `/test login.test.ts`
### Positional Arguments
Use `$1`, `$2`, etc. for specific arguments (like shell scripts):
```markdown
# Compare Files
Compare $1 with $2.
Show:
- Line differences
- Semantic changes
- Which version is preferred
```
**Usage**: `/compare old.js new.js` → `$1 = "old.js"`, `$2 = "new.js"`
---
## File References (@ Prefix)
Include file contents directly in the command with `@`:
```markdown
# Review with Context
Review this code following our standards.
Project standards:
@CLAUDE.md
Code to review:
$ARGUMENTS
```
**Usage**: `/review-context src/auth.js` includes CLAUDE.md contents automatically.
---
## Bash Execution (! Prefix)
Include bash command output with `!`:
```markdown
# Smart Commit
Current status:
!git status --short
Recent commits:
!git log --oneline -5
Staged changes:
!git diff --cached
Generate a commit message for the staged changes.
```
**Usage**: `/smart-commit` runs git commands and includes their output.
---
## Command Patterns
### Agent Invocation
```markdown
# Security Audit
Perform a comprehensive security audit.
Target: $ARGUMENTS
Use the **security-auditor** agent to:
1. Scan for OWASP Top 10 vulnerabilities
2. Check authentication patterns
3. Review data validation
4. Analyze dependencies
Provide a severity-rated findings report.
```
### Multi-Agent Orchestration
```markdown
# Fullstack Feature
Build a complete fullstack feature.
Feature: $ARGUMENTS
Workflow:
1. Use **prd-architect** to clarify requirements
2. Use **system-architect** to design approach
3. Use **backend-engineer** for API implementation
4. Use **frontend-engineer** for UI implementation
5. Use **test-architect** for test coverage
Coordinate between agents and ensure integration.
```
### Validation Command
```markdown
# Pre-Commit Check
Validate changes before commit.
Files: $ARGUMENTS (or all staged files if not specified)
Checklist:
- [ ] All tests pass
- [ ] No linting errors
- [ ] No type errors
- [ ] No console.log statements
- [ ] No TODO comments
- [ ] No hardcoded secrets
Return READY or BLOCKED with details.
```
---
## Command Categories
### Development Commands
| Command | Purpose |
|---------|---------|
| `/review` | Code review |
| `/test` | Run/write tests |
| `/debug` | Debug issues |
| `/refactor` | Improve code |
### Architecture Commands
| Command | Purpose |
|---------|---------|
| `/design` | System design |
| `/architecture-review` | Review architecture |
| `/tech-spec` | Write tech spec |
### Security Commands
| Command | Purpose |
|---------|---------|
| `/security-scan` | Security audit |
| `/secrets-check` | Find exposed secrets |
| `/dependency-audit` | Check dependencies |
### Operations Commands
| Command | Purpose |
|---------|---------|
| `/deploy` | Deployment workflow |
| `/rollback` | Rollback changes |
| `/incident` | Incident response |
---
## Naming Conventions
| Pattern | Example | Use For |
|---------|---------|---------|
| `{action}` | `/review` | Simple actions |
| `{action}-{target}` | `/security-scan` | Specific targets |
| `{domain}-{action}` | `/pm-strategy` | Domain-prefixed |
| `{tool}-{action}` | `/git-commit` | Tool-specific |
---
## Command vs Agent vs Skill
| Feature | Command | Agent | Skill |
|---------|---------|-------|-------|
| **Trigger** | User types `/command` | Claude decides | Claude loads |
| **Purpose** | Quick shortcuts | Complex work | Knowledge |
| **Statefulness** | Stateless | Maintains context | Reference only |
| **Length** | Short prompt | Full instructions | Detailed docs |
**Flow**: User → Command → Agent → Skill
---
## Best Practices
### DO
```markdown
# Good Command
Clear, specific instructions.
Target: $ARGUMENTS
1. First, analyze the target
2. Then, perform action X
3. Finally, output result Y
Expected output:
- Summary of findings
- Actionable recommendations
```
### DON'T
```markdown
# Bad Command
Do stuff with $ARGUMENTS.
Make it good.
```
---
## Advanced Patterns
### Conditional Logic
```markdown
# Smart Review
Review target: $ARGUMENTS
If target is a PR number (e.g., #123):
- Fetch PR details with `gh pr view`
- Review all changed files
If target is a file path:
- Review that specific file
If target is a directory:
- Review all files in directory
```
### Template with Options
```markdown
# Generate Tests
Generate tests for: $ARGUMENTS
Options (parsed from arguments):
- `--unit` - Unit tests only
- `--e2e` - E2E tests only
- `--coverage` - Include coverage report
Default: Generate both unit and E2E tests.
```
---
## Navigation
### Resources
- [resources/command-patterns.md](resources/command-patterns.md) — Common patterns
- [resources/command-examples.md](resources/command-examples.md) — Full examples
- [data/sources.json](data/sources.json) — Documentation links
### Related Skills
- [../claude-code-agents/SKILL.md](../claude-code-agents/SKILL.md) — Agent creation
- [../claude-code-skills/SKILL.md](../claude-code-skills/SKILL.md) — Skill creation
- [../claude-code-hooks/SKILL.md](../claude-code-hooks/SKILL.md) — Hook automation
---
## Referenced Files
> The following files are referenced in this skill and included for context.
### ../claude-code-agents/SKILL.md
```markdown
---
name: claude-code-agents
description: Create and configure Claude Code agents with YAML frontmatter, tool selection, model specification, and naming conventions. Reference for building specialized AI subagents that handle complex, multi-step tasks.
---
# Claude Code Agents — Meta Reference
This skill provides the definitive reference for creating Claude Code agents. Use this when building new agents or understanding agent architecture.
---
## Quick Reference
| Field | Purpose | Required |
|-------|---------|----------|
| `name` | Agent identifier (kebab-case) | Yes |
| `description` | When to invoke this agent | Yes |
| `tools` | Allowed tool list | No (defaults: all) |
| `model` | Claude model variant | No (default: sonnet) |
## Agent Structure
```text
.claude/agents/
├── code-reviewer.md
├── security-auditor.md
├── test-architect.md
└── system-architect.md
```
---
## Agent Template
```markdown
---
name: agent-name
description: When to use this agent (single line)
tools: Read, Grep, Glob, Bash
model: sonnet
---
# Agent Name
You are a [role description].
## Responsibilities
- Responsibility 1
- Responsibility 2
- Responsibility 3
## Workflow
1. Step 1: [action]
2. Step 2: [action]
3. Step 3: [action]
## Output Format
[Specify expected output structure]
```
---
## Frontmatter Specification
### name (required)
```yaml
name: security-auditor
```
**Rules**:
- Kebab-case only
- Match filename (without .md)
- Descriptive but concise
### description (required)
```yaml
description: Analyze code for security vulnerabilities using OWASP Top 10
```
**Rules**:
- Single line, under 200 characters
- Explain WHEN Claude should invoke this agent
- Include key capabilities
### tools (optional)
```yaml
tools: Read, Grep, Glob, Bash, Edit, Write
```
**Available tools**:
| Tool | Purpose | Use When |
|------|---------|----------|
| `Read` | Read files | Always include |
| `Grep` | Search content | Code analysis |
| `Glob` | Find files | File discovery |
| `Bash` | Run commands | Build, test, git |
| `Edit` | Modify files | Code changes |
| `Write` | Create files | New files |
| `WebFetch` | Fetch URLs | Documentation lookup |
| `WebSearch` | Search web | Research tasks |
| `Task` | Spawn subagents | Delegation |
**Minimal permissions principle**: Only include tools the agent needs.
### model (optional)
```yaml
model: sonnet # or opus, haiku
```
| Model | Use For | Cost |
|-------|---------|------|
| `haiku` | Simple, fast tasks | Low |
| `sonnet` | Most tasks (default) | Medium |
| `opus` | Complex reasoning | High |
---
## Agent Categories
### Analysis Agents (Read-only)
```yaml
tools: Read, Grep, Glob
```
Examples:
- `code-reviewer` - Review code quality
- `security-auditor` - Find vulnerabilities
- `architecture-analyzer` - Analyze system design
### Implementation Agents (Read-write)
```yaml
tools: Read, Grep, Glob, Edit, Write, Bash
```
Examples:
- `backend-engineer` - Build APIs
- `frontend-engineer` - Build UIs
- `test-engineer` - Write tests
### Research Agents (Web access)
```yaml
tools: Read, WebFetch, WebSearch
```
Examples:
- `documentation-researcher` - Find docs
- `technology-scout` - Evaluate options
---
## Agent Design Patterns
### Single-Responsibility Agent
```markdown
---
name: sql-optimizer
description: Analyze and optimize SQL queries for performance
tools: Read, Grep, Glob
model: sonnet
---
# SQL Optimizer
You optimize SQL queries. Focus on:
1. Index usage analysis
2. Query plan examination
3. Performance recommendations
Output optimization suggestions with before/after examples.
```
### Orchestrator Agent
```markdown
---
name: fullstack-builder
description: Coordinate frontend, backend, and database changes
tools: Read, Grep, Glob, Task
model: sonnet
---
# Fullstack Builder
You coordinate multi-layer changes by delegating to specialized agents:
1. Analyze requirements
2. Delegate database changes to sql-engineer
3. Delegate API changes to backend-engineer
4. Delegate UI changes to frontend-engineer
5. Verify integration
```
### Verification Agent
```markdown
---
name: pre-commit-checker
description: Verify code quality before commits
tools: Read, Grep, Bash
model: haiku
---
# Pre-Commit Checker
Run quality checks:
- [ ] Linting passes
- [ ] Tests pass
- [ ] No console.logs
- [ ] No TODO comments
- [ ] Types correct
Return PASS or FAIL with details.
```
---
## Agent ↔ Skill Relationship
**Agents** do work → **Skills** provide knowledge
```text
Agent: backend-engineer
├── Uses skill: software-backend (API patterns)
├── Uses skill: dev-api-design (REST/GraphQL)
└── Uses skill: data-sql-optimization (query optimization)
```
Agents reference skills implicitly—Claude loads relevant skill content based on context.
---
## Naming Conventions
| Pattern | Example | Use For |
|---------|---------|---------|
| `{role}` | `code-reviewer` | General role |
| `{domain}-{role}` | `security-auditor` | Domain-specific |
| `{action}-{target}` | `test-generator` | Action-focused |
| `{tech}-{role}` | `typescript-migrator` | Tech-specific |
---
## Invocation Patterns
### Direct (user triggers)
```
User: "Review this code for security issues"
Claude: [invokes security-auditor agent]
```
### Via Command
```markdown
<!-- .claude/commands/security.md -->
Run security analysis using the security-auditor agent.
```
### Via Another Agent
```yaml
# Parent agent
tools: Task # Can spawn subagents
```
---
## Quality Checklist
```text
AGENT VALIDATION CHECKLIST
Frontmatter:
[ ] name matches filename (kebab-case)
[ ] description explains when to invoke
[ ] tools are minimal necessary
[ ] model appropriate for task complexity
Content:
[ ] Clear role definition
[ ] Specific responsibilities listed
[ ] Workflow steps defined
[ ] Output format specified
Integration:
[ ] Related skills identified
[ ] Commands reference this agent (if applicable)
```
---
## Security Best Practices
### Deny-All Default
Start with no tools, add only what's needed:
```yaml
# Reviewer: read-only
tools: Read, Grep, Glob
# Builder: add write access
tools: Read, Grep, Glob, Edit, Write, Bash
```
### Dangerous Command Awareness
Require explicit confirmation for:
- `rm -rf` — Recursive delete
- `git push --force` — Overwrite history
- `sudo` — Elevated permissions
- `DROP TABLE` — Database destruction
- Infrastructure changes (Terraform, K8s)
### Context Isolation
- Each subagent has isolated context window
- Orchestrator maintains global state (compact)
- Use CLAUDE.md for shared conventions
- Never pass full codebase to subagents
---
## Navigation
**Resources**
- [resources/agent-patterns.md](resources/agent-patterns.md) — Common agent patterns
- [resources/agent-tools.md](resources/agent-tools.md) — Tool capabilities reference
- [data/sources.json](data/sources.json) — Official documentation links
**Related Skills**
- [../claude-code-skills/SKILL.md](../claude-code-skills/SKILL.md) — Skill creation
- [../claude-code-commands/SKILL.md](../claude-code-commands/SKILL.md) — Command creation
- [../claude-code-hooks/SKILL.md](../claude-code-hooks/SKILL.md) — Hook automation
```
### ../claude-code-skills/SKILL.md
```markdown
---
name: claude-code-skills
description: Comprehensive reference for creating Claude Code skills with progressive disclosure, SKILL.md structure, resources/ organization, frontmatter specification, and best practices for modular capability development.
---
# Claude Code Skills — Meta Reference
This skill provides the definitive reference for creating, organizing, and maintaining Claude Code skills. Use this when building new skills or improving existing skill architecture.
---
## Quick Reference
| Component | Purpose | Required |
|-----------|---------|----------|
| `SKILL.md` | Main reference file with frontmatter | Yes |
| `resources/` | Detailed documentation | Recommended |
| `templates/` | Reusable code templates | Optional |
| `data/sources.json` | Curated external links | Recommended |
## Skill Structure
```text
skills/
└── skill-name/
├── SKILL.md # Main reference (required)
├── README.md # Usage notes (optional)
├── resources/ # Detailed docs
│ ├── patterns.md
│ └── examples.md
├── templates/ # Code templates
│ └── starter.md
└── data/
└── sources.json # External references
```
---
## SKILL.md Template
```markdown
---
name: skill-name
description: One-line description of what this skill provides and when to use it
---
# Skill Name — Quick Reference
Brief overview of the skill's purpose and value.
---
## Quick Reference
| Task | Tool/Method | When to Use |
|------|-------------|-------------|
| Task 1 | Tool A | Context for usage |
## When to Use This Skill
Claude should invoke this skill when a user requests:
- Use case 1
- Use case 2
- Use case 3
---
## Core Concepts
### Concept 1
Explanation with code example:
\`\`\`language
code example
\`\`\`
### Concept 2
Additional patterns...
---
## Navigation
**Resources**
- [resources/skill-patterns.md](resources/skill-patterns.md) — Common patterns
- [resources/skill-validation.md](resources/skill-validation.md) — Validation criteria
**Related Skills**
- [../claude-code-agents/SKILL.md](../claude-code-agents/SKILL.md) — Agent creation
```
---
## Progressive Disclosure
Skills use **progressive disclosure** to optimize token usage:
| Layer | Content | Token Cost |
|-------|---------|------------|
| **Metadata** | Name + description only | ~100 tokens |
| **SKILL.md** | Quick reference, patterns | <5K tokens |
| **resources/** | Deep dives, full examples | On-demand |
**Pattern**: SKILL.md provides overview → Resources provide depth
### When to Split Content
| Keep in SKILL.md | Move to resources/ |
|------------------|-------------------|
| Decision trees | Full API references |
| Quick commands | Step-by-step tutorials |
| Common patterns | Edge case handling |
| 1-2 code examples | Complete implementations |
---
## Frontmatter Specification
```yaml
---
name: string # Required: lowercase-kebab-case, matches folder name
description: string # Required: One line, explains when Claude should use it
---
```
**Name rules**:
- Use kebab-case: `ai-llm`, not `AI_LLM_Engineering`
- Match folder name exactly
- Be specific: `software-backend` not `backend`
**Description rules**:
- Single line, under 200 characters
- Include key technologies/concepts
- End with context of when to use
---
## Skill Categories
| Category | Prefix | Examples |
|----------|--------|----------|
| AI/ML | `ai-` | `ai-llm`, `ai-ml-data-science` |
| Software | `software-` | `software-backend`, `software-frontend` |
| Operations | `ops-` | `ops-devops-platform` |
| Data | `data-` | `data-lake-platform`, `data-sql-optimization` |
| Quality | `quality-` | `quality-debugging`, `qa-docs-coverage` |
| Developer Tools | `dev-`, `git-` | `dev-api-design`, `git-commit-message`, `dev-workflow-planning` |
| Product | `product-` | `product-management`, `docs-ai-prd` |
| Document | `document-` | `document-pdf`, `document-xlsx` |
| Testing | `testing-`, `qa-testing-` | `qa-testing-playwright`, `qa-testing-strategy` |
| Marketing | `marketing-` | `marketing-social-media`, `marketing-seo-technical` |
| Claude Code | `claude-code-` | `claude-code-agents`, `claude-code-skills` |
---
## sources.json Schema
```json
{
"metadata": {
"title": "Skill Name - Sources",
"description": "Brief description",
"last_updated": "YYYY-MM-DD",
"skill": "skill-name"
},
"category_name": [
{
"name": "Resource Name",
"url": "https://example.com/docs",
"description": "What this covers",
"add_as_web_search": true
}
]
}
```
**Categories** should group logically:
- `official_documentation`
- `tutorials`
- `community_resources`
- `tools_and_libraries`
---
## Quality Checklist
```text
SKILL VALIDATION CHECKLIST
Frontmatter:
[ ] name matches folder name (kebab-case)
[ ] description is concise and actionable
Structure:
[ ] SKILL.md under 5K characters (progressive disclosure)
[ ] resources/ for detailed content
[ ] data/sources.json with curated links
Content:
[ ] Quick reference table at top
[ ] "When to Use" section present
[ ] Code examples are copy-paste ready
[ ] Related skills linked at bottom
Quality:
[ ] >40% operational content (code, tables, checklists)
[ ] <50% prose paragraphs
[ ] All URLs are live (no 404s)
[ ] Sources updated within 6 months
```
---
## Multi-Tech vs Single-Tech Skills
### Single-Tech Skill
```text
software-backend/
├── SKILL.md # Node.js focus
└── resources/
└── nodejs-patterns.md
```
### Multi-Tech Skill
```text
software-backend/
├── SKILL.md # Overview + decision tree
├── resources/
│ ├── nodejs-patterns.md
│ ├── go-patterns.md
│ ├── rust-patterns.md
│ └── python-patterns.md
└── templates/
├── nodejs/
├── go/
├── rust/
└── python/
```
---
## Navigation
**Resources**
- [resources/skill-patterns.md](resources/skill-patterns.md) — Common skill patterns
- [resources/skill-validation.md](resources/skill-validation.md) — Validation criteria
- [data/sources.json](data/sources.json) — Official documentation links
**Related Skills**
- [../claude-code-agents/SKILL.md](../claude-code-agents/SKILL.md) — Agent creation
- [../claude-code-commands/SKILL.md](../claude-code-commands/SKILL.md) — Command creation
- [../claude-code-hooks/SKILL.md](../claude-code-hooks/SKILL.md) — Hook automation
```
### ../claude-code-hooks/SKILL.md
```markdown
---
name: claude-code-hooks
description: Create event-driven hooks for Claude Code automation. Configure PreToolUse, PostToolUse, Stop, and other hook events with bash scripts, environment variables, matchers, and exit codes.
---
# Claude Code Hooks — Meta Reference
This skill provides the definitive reference for creating Claude Code hooks. Use this when building automation that triggers on Claude Code events.
---
## When to Use This Skill
- Building event-driven automation for Claude Code
- Creating PreToolUse guards to block dangerous commands
- Implementing PostToolUse formatters, linters, or auditors
- Adding Stop hooks for testing or notifications
- Setting up SessionStart/SessionEnd for environment management
- Integrating Claude Code with CI/CD pipelines (headless mode)
---
## Quick Reference
| Event | Trigger | Use Case |
|-------|---------|----------|
| `PreToolUse` | Before tool execution | Validate, block dangerous commands |
| `PostToolUse` | After tool execution | Format, audit, notify |
| `Stop` | When Claude finishes | Run tests, summarize |
| `Notification` | On notifications | Alert integrations |
| `SessionStart` | Session begins | Initialize environment |
| `SessionEnd` | Session ends | Cleanup, save state |
| `UserPromptSubmit` | User sends message | Preprocessing |
## Hook Structure
```text
.claude/hooks/
├── pre-tool-validate.sh
├── post-tool-format.sh
├── post-tool-audit.sh
├── stop-run-tests.sh
└── session-start-init.sh
```
---
## Configuration
### settings.json
```json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/post-tool-format.sh"
}
]
}
],
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/pre-tool-validate.sh"
}
]
}
],
"Stop": [
{
"matcher": "",
"hooks": [
{
"type": "command",
"command": "$CLAUDE_PROJECT_DIR/.claude/hooks/stop-run-tests.sh"
}
]
}
]
}
}
```
---
## Environment Variables
| Variable | Description | Available In |
|----------|-------------|--------------|
| `CLAUDE_PROJECT_DIR` | Project root path | All hooks |
| `CLAUDE_TOOL_NAME` | Current tool name | Pre/PostToolUse |
| `CLAUDE_TOOL_INPUT` | Tool input (JSON) | PreToolUse |
| `CLAUDE_TOOL_OUTPUT` | Tool output | PostToolUse |
| `CLAUDE_FILE_PATHS` | Affected files | PostToolUse |
| `CLAUDE_SESSION_ID` | Session identifier | All hooks |
---
## Exit Codes
| Code | Meaning | Effect |
|------|---------|--------|
| `0` | Success | Continue execution |
| `1` | Error | Report error, continue |
| `2` | Block | Block tool execution (PreToolUse only) |
---
## Hook Templates
### Pre-Tool Validation
```bash
#!/bin/bash
set -euo pipefail
# Block dangerous commands
if [[ "$CLAUDE_TOOL_NAME" == "Bash" ]]; then
INPUT="$CLAUDE_TOOL_INPUT"
# Block rm -rf /
if echo "$INPUT" | grep -qE 'rm\s+-rf\s+/'; then
echo "BLOCKED: Dangerous rm command detected"
exit 2
fi
# Block force push to main
if echo "$INPUT" | grep -qE 'git\s+push.*--force.*(main|master)'; then
echo "BLOCKED: Force push to main/master not allowed"
exit 2
fi
# Block credential exposure
if echo "$INPUT" | grep -qE '(password|secret|api_key)\s*='; then
echo "WARNING: Possible credential exposure"
fi
fi
exit 0
```
### Post-Tool Formatting
```bash
#!/bin/bash
set -euo pipefail
# Auto-format modified files
if [[ "$CLAUDE_TOOL_NAME" =~ ^(Edit|Write)$ ]]; then
FILES="$CLAUDE_FILE_PATHS"
for file in $FILES; do
if [[ -f "$file" ]]; then
case "$file" in
*.js|*.ts|*.jsx|*.tsx|*.json|*.md)
npx prettier --write "$file" 2>/dev/null || true
;;
*.py)
ruff format "$file" 2>/dev/null || true
;;
*.go)
gofmt -w "$file" 2>/dev/null || true
;;
*.rs)
rustfmt "$file" 2>/dev/null || true
;;
esac
fi
done
fi
exit 0
```
### Post-Tool Security Audit
```bash
#!/bin/bash
set -euo pipefail
# Audit file changes for security issues
if [[ "$CLAUDE_TOOL_NAME" =~ ^(Edit|Write)$ ]]; then
FILES="$CLAUDE_FILE_PATHS"
for file in $FILES; do
if [[ -f "$file" ]]; then
# Check for hardcoded secrets
if grep -qE '(password|secret|api_key|token)\s*[:=]\s*["\x27][^"\x27]+["\x27]' "$file"; then
echo "WARNING: Possible hardcoded secret in $file"
fi
# Check for console.log in production code
if [[ "$file" =~ \.(ts|js|tsx|jsx)$ ]] && grep -q 'console.log' "$file"; then
echo "NOTE: console.log found in $file"
fi
fi
done
fi
exit 0
```
### Stop Hook (Run Tests)
```bash
#!/bin/bash
set -euo pipefail
# Run tests after Claude finishes
cd "$CLAUDE_PROJECT_DIR"
# Detect test framework
if [[ -f "package.json" ]]; then
if grep -q '"vitest"' package.json; then
npm run test 2>&1 | head -50
elif grep -q '"jest"' package.json; then
npm test 2>&1 | head -50
fi
elif [[ -f "pytest.ini" ]] || [[ -f "pyproject.toml" ]]; then
pytest --tb=short 2>&1 | head -50
fi
exit 0
```
### Session Start
```bash
#!/bin/bash
set -euo pipefail
cd "$CLAUDE_PROJECT_DIR"
# Check git status
echo "=== Git Status ==="
git status --short
# Check for uncommitted changes
if ! git diff --quiet; then
echo "WARNING: Uncommitted changes detected"
fi
# Verify dependencies
if [[ -f "package.json" ]]; then
if [[ ! -d "node_modules" ]]; then
echo "NOTE: node_modules missing, run npm install"
fi
fi
exit 0
```
---
## Matchers
Matchers filter which tool triggers the hook:
| Matcher | Matches |
|---------|---------|
| `""` (empty) | All tools |
| `"Bash"` | Bash tool only |
| `"Edit\|Write"` | Edit OR Write |
| `"Edit.*"` | Edit and variants (regex) |
---
## Security Best Practices
```text
HOOK SECURITY CHECKLIST
[ ] Validate all inputs with regex
[ ] Quote all variables: "$VAR" not $VAR
[ ] Use absolute paths
[ ] No eval with untrusted input
[ ] Set -euo pipefail at top
[ ] Keep hooks fast (<1 second)
[ ] Log actions for audit
[ ] Test manually before deploying
```
---
## Hook Composition
### Multiple Hooks on Same Event
```json
{
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": ".claude/hooks/format.sh" },
{ "type": "command", "command": ".claude/hooks/audit.sh" },
{ "type": "command", "command": ".claude/hooks/notify.sh" }
]
}
]
}
```
Hooks execute in order. If one fails, subsequent hooks may not run.
---
## Debugging Hooks
```bash
# Test hook manually
CLAUDE_TOOL_NAME="Edit" \
CLAUDE_FILE_PATHS="src/app.ts" \
CLAUDE_PROJECT_DIR="$(pwd)" \
bash .claude/hooks/post-tool-format.sh
# Check exit code
echo $?
```
---
## Navigation
### Resources
- [resources/hook-patterns.md](resources/hook-patterns.md) — Common patterns
- [resources/hook-security.md](resources/hook-security.md) — Security guide
- [data/sources.json](data/sources.json) — Documentation links
### Related Skills
- [../claude-code-commands/SKILL.md](../claude-code-commands/SKILL.md) — Command creation
- [../claude-code-agents/SKILL.md](../claude-code-agents/SKILL.md) — Agent creation
- [../ops-devops-platform/SKILL.md](../ops-devops-platform/SKILL.md) — CI/CD integration
```