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
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository64 other files it gives its agents.
- AGENTS.mdAGENTS.md
- CLAUDE.mdCLAUDE.md
- beanstalk-deployCursor rule
- .cursor/rules/core-principles.mdcCursor rule
- .cursor/rules/creating-agents-md.mdcCursor rule
- .cursor/rules/creating-claude-agents.mdCursor rule
- .cursor/rules/creating-claude-commands.mdCursor rule
- .cursor/rules/creating-continue-packages.mdCursor rule
- .cursor/rules/creating-copilot-packages.mdCursor rule
- .cursor/rules/creating-cursor-commands.mdCursor rule
- .cursor/rules/creating-cursor-rules.mdcCursor rule
- .cursor/rules/creating-kiro-agents.mdcCursor rule
- .cursor/rules/creating-kiro-packages.mdCursor rule
- .cursor/rules/creating-skills.mdcCursor rule
- .cursor/rules/creating-windsurf-packages.mdCursor rule
- .cursor/rules/elastic-beanstalk-deployment.mdCursor rule
- .cursor/rules/format-conversion.mdcCursor rule
- .cursor/rules/github-actions-testing.mdcCursor rule
- .cursor/rules/karen-repo-reviewer.mdcCursor rule
- .cursor/rules/prpm-json-best-practices.mdcCursor rule
- .cursor/rules/self-improve-cursor.mdcCursor rule
- .cursor/rules/testing-patterns.mdcCursor rule
- .cursor/rules/typescript-type-safety.mdcCursor rule
- .cursor/rules/typescript-type-specialist.mdcCursor rule
- creating-agent-skillsSkill
- adding-new-ai-formatSkill
- agent-builderSkill
- aws-beanstalk-expertSkill
- beanstalk-deploySkill
- claude-hook-writerSkill
- creating-agents-mdSkill
- creating-claude-agentsSkill
- creating-claude-commandsSkill
- creating-claude-hooksSkill
- creating-claude-rulesSkill
- creating-continue-packagesSkill
- creating-copilot-packagesSkill
- creating-cursor-commandsSkill
- creating-cursor-rules-skillSkill
- creating-kiro-agentsSkill
- creating-kiro-packagesSkill
- creating-opencode-agentsSkill
- creating-opencode-pluginsSkill
- creating-skillsSkill
- creating-windsurf-packagesSkill
- creating-zed-extensionsSkill
- documentation-standardsSkill
- elastic-beanstalk-deploymentSkill
- github-actions-testingSkill
- human-writingSkill
- integrating-stripe-webhooksSkill
- karen-repo-reviewerSkill
- npm-trusted-publishingSkill
- osgrepSkill
- postgres-migrationsSkill
- prpm-developmentSkill
- prpm-json-best-practicesSkill
- pulumi-troubleshootingSkill
- self-improvingSkill
- slash-command-builderSkill
- The first 60 shown.
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
- Very specific: line 78
Use stderr (>&2) for debug logs
- Distinctive: line 141
Always validate JSON input:
- Very specific: line 280
When distributing via PRPM, document hooks with frontmatter:
- Distinctive: line 389
Before deploying a hook:
≈ “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.
Files
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
- Shebang line (first line):
#!/bin/bash
# or
#!/usr/bin/env node
# or
#!/usr/bin/env python3- Executable permissions:
chmod +x .claude/hooks/hook-name- JSON input via stdin:
INPUT=$(cat)
DATA=$(echo "$INPUT" | jq -r '.input.field')- Exit with appropriate code:
0= Success (continue)2= Block operation (show error)1or other = Error (log but continue)
Available Events
session-start- Runs when new session beginsuser-prompt-submit- Runs before user message processestool-call- Runs before tool executionassistant-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, binaryhookType: "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 0TypeScript 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
fi2. 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
fi3. 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
fiSecurity 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 # AllowUser 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 0Use 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 executableHOOK.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
| Issue | Cause | Fix |
| Hook doesn't run | Not executable | chmod +x hook-file |
| Parse errors | Missing shebang | Add #!/bin/bash |
| Breaks on spaces | Unquoted variables | Use "$VAR" |
| Can't find scripts | Relative paths | Use $CLAUDE_PLUGIN_ROOT |
| Clutters transcript | Logging to stdout | Use stderr: >&2 |
| Doesn't block | Wrong exit code | Use exit 2 |
| Security risk | No validation | Always validate input |
| Slow | Blocking operations | Run 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 2Edge 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
- Claude Code Hooks Official Docs
- JSON Schema
- See
claude-hook-writerskill for advanced guidance - See
typescript-hook-writerskill for TypeScript hooks
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
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
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.

