agentleFS
pr-pmpr-pm/prpm/.cursor/rules/creating-claude-hooks.md

prpm / rules

Cursor rule122 starsChanged 9 months agoMITView on GitHub

Guidelines for creating Claude Code hooks - executable scripts triggered by events with JSON I/O

  • Reads credentials
  • Installs packages

The file

We split this creating-claude-hooks.md into the rules it gives an agent

4 rules. About 0 are common, 2 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Use stderr (>&2) for debug logs

    line 78
  2. Distinctive:

    Always validate JSON input:

    line 141
  3. Very specific:

    When distributing via PRPM, document hooks with frontmatter:

    line 280
  4. Distinctive:

    Before deploying a hook:

    line 389

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
creating-claude-hooks.md

Claude Code Hooks - Format Guidelines

Hook File Format

Claude Code hooks are executable files (not markdown) that run in response to specific events.

Location: .claude/hooks/<event-name>

Format: Executable file (shell script, TypeScript, Python, binary)

Required Elements

  1. Shebang line (first line):
#!/bin/bash
# or
#!/usr/bin/env node
# or
#!/usr/bin/env python3
  1. Executable permissions:
chmod +x .claude/hooks/hook-name
  1. JSON input via stdin:
INPUT=$(cat)
DATA=$(echo "$INPUT" | jq -r '.input.field')
  1. Exit with appropriate code:
  • 0 = Success (continue)
  • 2 = Block operation (show error)
  • 1 or other = Error (log but continue)

Available Events

  • session-start - Runs when new session begins
  • user-prompt-submit - Runs before user message processes
  • tool-call - Runs before tool execution
  • assistant-response - Runs after assistant responds

Input/Output Format

JSON Input Structure

Hooks receive event data via stdin:

{
  "event": "tool-call",
  "timestamp": "2025-01-15T10:30:00Z",
  "session_id": "abc123",
  "current_dir": "/path/to/project",
  "input": {
    "file_path": "/path/to/file.ts",
    "command": "npm test",
    "old_string": "...",
    "new_string": "..."
  }
}

Output via stdout

  • Normal output shown to user as feedback
  • Empty output runs silently
  • Use stderr (>&2) for debug logs

Schema Reference

Validate hook structure against:

URL: https://github.com/pr-pm/prpm/blob/main/packages/converters/schemas/claude-hook.schema.json

Required fields:

  • name - Hook identifier (lowercase, hyphens)
  • description - What hook does (max 1024 chars)

Optional fields:

  • event - Event type (inferred from filename if omitted)
  • language - bash, typescript, javascript, python, binary
  • hookType: "hook" - For round-trip conversion

Basic Examples

Shell Script Hook

#!/bin/bash
# .claude/hooks/session-start

# Log session start
echo "Session started at $(date)" >> ~/.claude/session.log

# Run setup
npm install --silent

# Output to user
echo "Development environment ready"
exit 0

TypeScript Hook

#!/usr/bin/env node
// .claude/hooks/user-prompt-submit

import { readFileSync } from 'fs';

// Read JSON from stdin
const input = readFileSync(0, 'utf-8');
const data = JSON.parse(input);

// Check for security issues
if (data.prompt.includes('API_KEY') || data.prompt.includes('SECRET')) {
  console.error('Warning: Prompt may contain secrets');
  process.exit(2); // Block operation
}

// Allow prompt
console.log('Prompt validated');
process.exit(0);

Validation Guidelines

1. Input Validation

Always validate JSON input:

INPUT=$(cat)

# Parse with error handling
if ! FILE=$(echo "$INPUT" | jq -r '.input.file_path // empty' 2>&1); then
  echo "JSON parse failed: $FILE" >&2
  exit 1
fi

# Check field exists
if [[ -z "$FILE" ]]; then
  echo "No file path provided" >&2
  exit 1
fi

2. Path Sanitization

Prevent directory traversal:

# Block traversal attempts
if [[ "$FILE" == *".."* ]]; then
  echo "Path traversal detected" >&2
  exit 2
fi

# Keep files in project
if [[ "$FILE" != "$CLAUDE_PROJECT_DIR"* ]]; then
  echo "File outside project" >&2
  exit 2
fi

3. Variable Quoting

Always quote variables:

# WRONG - breaks on spaces
prettier --write $FILE

# RIGHT - handles spaces
prettier --write "$FILE"

4. Dependency Checks

Handle missing tools gracefully:

# Check tool exists
if ! command -v prettier &> /dev/null; then
  echo "prettier not installed, skipping" >&2
  exit 0
fi

Security Best Practices

Block Sensitive Files

#!/bin/bash
set -euo pipefail

INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.input.file_path // empty')

[[ -n "$FILE" ]] || exit 0

# Sensitive patterns
BLOCKED=(".env" ".env.*" "*.pem" "*.key" "*secret*" "*credential*")

for pattern in "${BLOCKED[@]}"; do
  case "$FILE" in
    $pattern)
      echo "Blocked: $FILE is sensitive" >&2
      exit 2  # Block operation
      ;;
  esac
done

exit 0  # Allow

User Confirmation

Claude Code automatically:

  • Requires explicit user confirmation to install hooks
  • Shows hook source code before installation
  • Warns about hook execution
  • Displays hook output in transcript mode

Performance Guidelines

Keep Hooks Fast

Target < 100ms for PreToolUse hooks:

# BAD - blocks Claude for 30 seconds
npm test

# GOOD - run in background
(npm test &)
exit 0

Use Specific Matchers

In hook configuration JSON:

{
  "hooks": {
    "PreToolUse": [{
      "matcher": "Write",  // Only file writes
      "hooks": [{ "type": "command", "command": "./hook.sh" }]
    }]
  }
}

Publishing as PRPM Package

Package Structure

my-hook/
├── prpm.json          # Package manifest
├── HOOK.md            # Hook documentation
└── hook-script.sh     # Hook executable

HOOK.md Format

When distributing via PRPM, document hooks with frontmatter:

---
name: session-logger
description: Logs session start/end times for tracking
event: SessionStart
language: bash
hookType: hook
---

# Session Logger Hook

Logs Claude Code session activity for tracking and debugging.

## Installation

This hook will be installed to `.claude/hooks/session-start`.

## Behavior

- Logs session start time to `~/.claude/session.log`
- Displays environment status
- Runs silent dependency checks

## Source Code

\`\`\`bash
#!/bin/bash
echo "Session started at $(date)" >> ~/.claude/session.log
echo "Session initialized"
exit 0
\`\`\`

prpm.json

{
  "name": "@username/hook-name",
  "version": "1.0.0",
  "description": "Brief description shown in search",
  "author": "Your Name",
  "format": "claude",
  "subtype": "hook",
  "tags": ["automation", "security", "formatting"],
  "main": "HOOK.md"
}

Common Pitfalls

IssueCauseFix
Hook doesn't runNot executablechmod +x hook-file
Parse errorsMissing shebangAdd #!/bin/bash
Breaks on spacesUnquoted variablesUse "$VAR"
Can't find scriptsRelative pathsUse $CLAUDE_PLUGIN_ROOT
Clutters transcriptLogging to stdoutUse stderr: >&2
Doesn't blockWrong exit codeUse exit 2
Security riskNo validationAlways validate input
SlowBlocking operationsRun in background

Environment Variables

Available in hooks:

  • $CLAUDE_PROJECT_DIR - Project root directory
  • $CLAUDE_CURRENT_DIR - Current working directory
  • $SESSION_ID - Session identifier
  • $CLAUDE_PLUGIN_ROOT - Hook installation directory
  • $CLAUDE_ENV_FILE - File for persisting variables

Testing Hooks

Manual Testing

# Create test input
echo '{
  "session_id": "test",
  "input": {
    "file_path": "/tmp/test.ts"
  }
}' | ./my-hook.sh

# Check exit code
echo $?  # Should be 0, 1, or 2

Edge Cases

Test with:

  • Files with spaces: "my file.txt"
  • Unicode filenames: "文件.txt"
  • Deep paths: "src/deep/nested/path/file.tsx"
  • Missing fields in JSON
  • Malformed JSON
  • Empty strings

Related Documentation

Quick Checklist

Before deploying a hook:

  • Shebang line included
  • File is executable (chmod +x)
  • Validates all stdin input
  • Quotes all variables
  • Handles missing dependencies
  • Uses appropriate exit codes (0, 1, 2)
  • Logs errors to stderr or file
  • Tests with edge cases
  • Documents dependencies
  • Includes installation instructions

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.