🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

claude-code-hooks

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

claude-code-hooks

A comprehensive collection of hooks for Claude Code that enforce coding standards, maintain consistency, and automate workflow tasks

Source
npmnpm
Version
2.2.1
Version published
Weekly downloads
58
346.15%
Maintainers
1
Weekly downloads
 
Created
Source

Claude Code Hooks by Sem

npm version npm downloads Version License Hooks Python Claude Code Status

Claude Code Hooks

A comprehensive collection of hooks for Claude Code that enforce coding standards, maintain consistency, and automate workflow tasks across all projects.

📚 Documentation

Features

🔒 Quality Gates

  • Pre-commit validation - Run tests, linting, and TypeScript checks before commits
  • Commit message standards - Enforce conventional commits and block co-authored commits
  • Code quality checks - Automatic validation of code style and patterns

🛡️ Safety & Consistency

  • Database protection - Prevent unnecessary table creation, encourage extending existing schemas
  • Duplicate prevention - Detect duplicate routes, components, and API endpoints
  • Style enforcement - Ensure theme-aware CSS, ShadCN usage, and consistent styling
  • API verification - Validate endpoint configuration, authentication, and naming conventions

🔄 Workflow Automation

  • Dart integration - Enforce task hierarchy and documentation sync
  • Command logging - Track all bash commands with timestamps
  • Session reminders - End-of-session summaries and pending task reminders
  • MCP tool suggestions - Recommend MCP tools when alternatives are available

🆕 New Advanced Hooks

  • No mock code - Prevents placeholder data (Lorem ipsum, test users, static returns)
  • Secret scanner - Detects API keys, passwords, tokens before they're committed
  • Environment sync - Keeps .env and .env.example synchronized
  • Gitignore enforcer - Prevents committing sensitive files and test scripts
  • README validator - Reminds to update documentation when features change

Installation

Install from npm

# Install the package globally
npm install -g claude-code-hooks

# Run the installation script to copy hooks to Claude Code directory
claude-hooks-install

Install from Source

# Clone the repository
git clone https://github.com/webdevtodayjason/claude-hooks.git
cd claude-hooks

# Run the install script
chmod +x install.sh
./install.sh

Manual Installation

  • Create the hooks directory:

    mkdir -p ~/.claude/hooks
    
  • Copy all Python hooks:

    cp hooks/*.py ~/.claude/hooks/
    chmod +x ~/.claude/hooks/*.py
    
  • Update your Claude Code settings:

    • If ~/.claude/settings.json exists, merge the hooks configuration from settings.example.json
    • If not, copy settings.example.json to ~/.claude/settings.json
  • Restart Claude Code for the hooks to take effect

CLI Usage

When installed via npm, you get access to the powerful claude-hooks CLI:

Available Commands

# Launch interactive menu (NEW!)
claude-hooks

# Install hooks to Claude Code directory
claude-hooks install
claude-hooks-install  # Also available as separate command

# List all available hooks with descriptions
claude-hooks list

# Get detailed information about a specific hook
claude-hooks info <hook-name>
# Example: claude-hooks info secret-scanner

# Check installation status (NEW!)
claude-hooks status

# Run diagnostics to check setup (NEW!)
claude-hooks doctor

# Initialize hooks for current project (NEW!)
claude-hooks init

# Hook Management Commands (NEW!)
claude-hooks enable <hook-name>    # Enable a disabled hook
claude-hooks disable <hook-name>   # Disable a hook temporarily
claude-hooks create <hook-name>    # Create a new custom hook
claude-hooks edit <hook-name>      # Edit an existing hook
claude-hooks remove <hook-name>    # Remove a hook permanently
claude-hooks config                # Edit Claude Code settings

# Run the comprehensive test suite
claude-hooks test

# Show version information
claude-hooks --version

# Display help and usage information
claude-hooks --help

Interactive Menu (NEW!)

Running claude-hooks without any arguments launches an interactive menu:

$ claude-hooks

🪝 Claude Code Hooks Interactive Menu

? What would you like to do? (Use arrow keys)
❯ 📦 Install hooks to Claude Code
  📋 List all available hooks
  🔍 Get info about a specific hook
  ✅ Check installation status
  🧪 Run tests
  🩺 Run diagnostics (doctor)
  🚀 Initialize project hooks
  ──────────────
  ❌ Exit

Examples

# See what hooks are available
$ claude-hooks list
Available Claude Code Hooks:

  pre-commit-validator.py        Enforces coding standards before commits
  validate-git-commit.py         Validates commit message format
  secret-scanner.py              Detects and blocks secrets
  no-mock-code.py               Prevents placeholder/mock code
  ... and more

# Check if everything is set up correctly
$ claude-hooks doctor

🩺 Running Claude Code Hooks Diagnostics...

✅ No issues found! Everything looks good.

# Check installation status
$ claude-hooks status

🔍 Checking Claude Code Hooks Status...

✅ Hooks directory exists
   17 hooks installed
✅ Settings file exists

# Get details about a specific hook
$ claude-hooks info secret-scanner
Hook: secret-scanner.py
Description: Detects and blocks secrets
Event: before_tool_call
Tools: Write, MultiEdit, Edit

# Run tests to ensure hooks are working
$ claude-hooks test
Running Claude Code Hooks Tests...
==================================
✅ All hooks are executable
✅ All 17 hooks passed tests!

Hooks Overview

HookTriggerPurpose
pre-commit-validator.pyBefore git commit/pushRuns tests, linting, TypeScript checks
validate-git-commit.pyBefore git commitEnforces commit message standards
database-extension-check.pyWhen editing schemasPrevents unnecessary table creation
duplicate-detector.pyWhen creating filesPrevents duplicate code/routes
style-consistency.pyWhen editing TSX/CSSEnforces theme-aware styling
api-endpoint-verifier.pyWhen editing API routesValidates endpoint configuration
api-docs-enforcer.pyBefore commits & API editsEnforces Swagger docs, Postman collections, API security
no-mock-code.pyBefore commits & file editsPrevents placeholder/mock code in production
secret-scanner.pyBefore commits & file editsDetects and prevents committing secrets
env-sync-validator.pyWhen editing .env filesKeeps .env and .env.example in sync
gitignore-enforcer.pyBefore git add/commitEnsures .gitignore exists and blocks forbidden files
readme-update-validator.pyBefore commitsReminds to update README when features change
validate-dart-task.pyCreating Dart tasksEnsures proper task hierarchy
sync-docs-to-dart.pyAfter creating .md filesReminds to sync docs
log-commands.pyBefore bash commandsLogs all commands
mcp-tool-enforcer.pyVarious operationsSuggests MCP tool usage
session-end-summary.pySession endProvides reminders

📋 Detailed Hook Documentation

Click on any hook below to see detailed information about what it does and how it helps your development workflow.

🔍 pre-commit-validator.py - Your Safety Net Before Commits

What it does:

This hook acts as your personal quality assurance assistant. Before any code gets committed, it automatically:

  • ✅ Runs your test suite to catch broken functionality
  • ✅ Executes linting tools to ensure code style consistency
  • ✅ Performs TypeScript type checking to prevent type errors
  • ✅ Validates that your code meets project standards

Why it's helpful:

Imagine pushing code only to find out later that tests are failing or there are linting errors. This hook prevents that embarrassment by catching issues before they reach the repository. It's like having a careful reviewer check your work every time.

Example output:

🔍 Running pre-commit validation...
✅ Tests passed (42 tests, 0 failures)
✅ Linting passed (0 errors, 0 warnings)
✅ TypeScript check passed
✨ All checks passed! Ready to commit.
✏️ validate-git-commit.py - Commit Message Police

What it does:

This hook ensures all commit messages follow a consistent format:

  • 📏 Enforces minimum message length (10+ characters)
  • 🔤 Requires capitalized first letter
  • 🚫 Blocks co-authored commits (no auto-generated attributions)
  • 📝 Ensures conventional commit format when configured

Why it's helpful:

Good commit messages make project history readable and searchable. This hook ensures everyone on the team writes clear, consistent commit messages that explain what changed and why.

Example:

❌ Bad: "fix bug"
✅ Good: "Fix navigation menu overflow on mobile devices"
🗄️ database-extension-check.py - Database Schema Guardian

What it does:

Prevents developers from creating unnecessary new database tables when they could extend existing ones:

  • 🔍 Detects when you're creating new migration files
  • 💡 Suggests existing tables that might be extended instead
  • 📊 Encourages proper database normalization
  • 🚫 Blocks creation of duplicate or redundant tables

Why it's helpful:

Keeps your database clean and maintainable by preventing table sprawl. Instead of having users, user_profiles, user_settings, and user_preferences as separate tables, it encourages you to use a single users table with appropriate columns.

Example:

⚠️  Creating new table 'user_settings'
💡 Consider extending the existing 'users' table instead
   You could add a 'settings' JSON column or related fields
🔁 duplicate-detector.py - Code Duplication Police

What it does:

Scans your codebase to prevent creating duplicate:

  • 🛣️ API routes (e.g., two /api/users endpoints)
  • 🧩 React/Vue components with the same name
  • 📦 Utility functions that already exist
  • 📄 Similar file names that might cause confusion

Why it's helpful:

Duplication leads to maintenance nightmares. This hook helps maintain the DRY (Don't Repeat Yourself) principle by alerting you when similar code already exists.

Example:

❌ Duplicate detected!
   You're creating: components/UserCard.tsx
   Already exists: components/user/UserCard.tsx
💡 Consider using the existing component or choosing a different name
🎨 style-consistency.py - Style & Theme Enforcer

What it does:

Ensures consistent styling across your application:

  • 🌓 Enforces dark mode support (checks for dark: variants)
  • 🎨 Prevents hardcoded colors (use theme variables instead)
  • 🧩 Suggests ShadCN UI components over raw HTML elements
  • 📏 Validates spacing uses consistent scale (2, 4, 6, 8, etc.)

Why it's helpful:

Maintains a professional, consistent look across your entire application. No more random colors or inconsistent spacing that makes your app look unprofessional.

Example:

⚠️  Style issues found:
   Line 23: Missing dark mode variant for bg-blue-500
   Line 45: Use ShadCN Button component instead of <button>
   Line 67: Hardcoded color #3B82F6 - use theme variables
🌐 api-endpoint-verifier.py - API Standards Enforcer

What it does:

Validates that all API endpoints follow best practices:

  • 🔐 Ensures authentication is implemented
  • 📝 Checks for proper input validation
  • 🏷️ Enforces consistent naming conventions
  • ⚡ Validates error handling is in place

Why it's helpful:

Prevents security vulnerabilities and ensures a consistent API experience for consumers. No more endpoints that work differently or have security holes.

Example:

❌ API endpoint issues:
   /api/getUser - Should use REST convention: GET /api/users/:id
   Missing authentication check
   No input validation for user ID
📚 api-docs-enforcer.py - API Documentation Guardian

What it does:

Ensures every API endpoint is properly documented:

  • 📋 Requires Swagger/OpenAPI documentation for all endpoints
  • 📮 Enforces Postman collection updates
  • 🔐 Validates security documentation for internal APIs
  • 🔗 Ensures documentation links between Swagger and Postman

Why it's helpful:

Good API documentation is crucial for team collaboration and API consumers. This hook ensures no endpoint goes undocumented, making your API easy to understand and use.

Example:

❌ API Documentation Required:
   New endpoint: POST /api/users/bulk-import
   Missing from swagger.json
   No Postman collection entry
   
💡 Run 'npm run generate-api-docs' to auto-generate documentation
🚫 no-mock-code.py - Real Code Enforcer

What it does:

Prevents placeholder or mock code from entering production:

  • 📝 Detects Lorem ipsum text
  • 👤 Flags test users (John Doe, test@example.com)
  • 🔄 Identifies functions that always return the same value
  • 📌 Catches TODO comments without implementation
  • 💾 Finds hardcoded test data

Why it's helpful:

Ensures your production code uses real, dynamic data. No more embarrassing moments where "John Doe" appears in production or where a function always returns the same test data.

Example:

❌ Mock/Placeholder Code Detected!
   Line 45: Found "Lorem ipsum" - Replace with real content
   Line 67: Static user data - Implement database query
   Line 89: TODO without implementation - Complete the function
🔒 secret-scanner.py - Security Guardian

What it does:

Scans code for accidentally exposed secrets:

  • 🔑 Detects API keys and tokens
  • 🔐 Finds passwords and credentials
  • 📧 Identifies private keys and certificates
  • 🚨 Checks .gitignore includes sensitive files

Why it's helpful:

Prevents the #1 security mistake: committing secrets to version control. Once a secret is in Git history, it's compromised forever. This hook is your last line of defense.

Example:

🚨 CRITICAL: Attempting to commit secrets!
   Line 23: API key detected: sk_test_abc...
   Line 45: Hardcoded password found
   
❌ Commit blocked - remove secrets and use environment variables
🔄 env-sync-validator.py - Environment Config Keeper

What it does:

Keeps your environment configuration files synchronized:

  • 📋 Ensures .env.example is updated when .env changes
  • 💡 Suggests safe placeholder values for examples
  • 🚫 Prevents real secrets in .env.example
  • 📝 Validates all team members know required variables

Why it's helpful:

When team members pull your code, they need to know what environment variables to set. This hook ensures .env.example always reflects the current requirements.

Example:

❌ Environment sync issues:
   New variable DATABASE_URL in .env
   Missing from .env.example
   
💡 Add to .env.example:
   DATABASE_URL=postgresql://user:password@localhost:5432/dbname
🚮 gitignore-enforcer.py - Repository Cleanliness Guard

What it does:

Ensures .gitignore is properly configured:

  • 📁 Verifies .gitignore exists
  • 🚫 Blocks commits of sensitive files (.env, *.key, *.pem)
  • 🧪 Prevents test scripts and temporary files
  • 💾 Stops large files and backups from being committed

Why it's helpful:

Keeps your repository clean and secure. Prevents accidentally committing files that should never be in version control, like private keys, large binaries, or temporary files.

Example:

🚨 FORBIDDEN FILES detected:
   • .env (environment file)
   • private-key.pem (private key)
   • test-script.sh (test script)
   
💡 Add these patterns to .gitignore:
   .env
   *.pem
   *test-script*
📝 readme-update-validator.py - Documentation Reminder

What it does:

Reminds you to update documentation when code changes:

  • 🆕 Detects new features and APIs
  • 📚 Suggests README sections to update
  • 🔧 Identifies configuration changes
  • 📦 Notices new dependencies

Why it's helpful:

Documentation often becomes outdated because developers forget to update it. This hook provides gentle reminders to keep your README current with your code.

Example:

📚 README Update Reminder:
   
🆕 New files detected:
   • api/users/bulk-import.js (API endpoint)
   • components/UserBulkUpload.tsx (Component)
   
💡 Consider updating these README sections:
   • API Documentation
   • Features
   • Usage Examples
✅ validate-dart-task.py - Task Hierarchy Enforcer

What it does:

Ensures proper task management in Dart:

  • 📊 Requires all tasks have a Phase parent
  • 🏷️ Validates task categorization
  • 🔗 Maintains project hierarchy
  • 📝 Enforces task metadata

Why it's helpful:

Keeps project management organized by ensuring all tasks are properly categorized and tracked within the correct project phase.

📄 sync-docs-to-dart.py - Documentation Sync Reminder

What it does:

Tracks when markdown files are created and reminds to sync with Dart:

  • 📝 Detects new .md file creation
  • 🔄 Tracks pending syncs
  • 📊 Maintains documentation consistency
  • 💾 Stores sync status

Why it's helpful:

Ensures documentation stays synchronized across different systems, preventing information silos.

📊 log-commands.py - Command Historian

What it does:

Logs all bash commands for audit and learning:

  • 🕒 Timestamps every command
  • 📁 Organizes logs by date
  • 📈 Tracks command frequency
  • 🔍 Enables command history search

Why it's helpful:

Creates an audit trail of all commands run, useful for debugging, learning patterns, and security auditing.

🛠️ mcp-tool-enforcer.py - Tool Usage Optimizer

What it does:

Suggests MCP tools when better alternatives exist:

  • 🔄 Detects suboptimal tool usage
  • 💡 Recommends MCP alternatives
  • ⚡ Improves workflow efficiency
  • 🎯 Promotes best practices

Why it's helpful:

Helps developers use the most efficient tools available, improving productivity and code quality.

👋 session-end-summary.py - Session Wrap-up Assistant

What it does:

Provides helpful reminders at session end:

  • 💾 Reminds about uncommitted changes
  • 📋 Lists pending tasks
  • 🔧 Shows workflow reminders
  • ✅ Ensures nothing is forgotten

Why it's helpful:

Acts like a helpful assistant making sure you don't forget important tasks before ending your coding session.

Configuration

Global Hook Configuration

Hooks are configured in ~/.claude/settings.json:

{
  "hooks": {
    "PreToolUse": [...],
    "PostToolUse": [...],
    "Stop": [...]
  }
}

See settings.example.json for the complete configuration.

Project-Specific Configuration

Some hooks now support project-specific configuration to avoid cross-project interference:

Session End Summary Hook

Create .claude/session-summary.json in your project:

{
  "show_dart_reminders": true,
  "show_git_reminders": true,
  "custom_reminders": [
    "Run tests before committing",
    "Update documentation"
  ]
}

Documentation Sync Hook

Create .claude/dart-config.json in your project:

{
  "enable_doc_sync": true,
  "default_docs_folder": "workspace/Docs",
  "workspace": "your-workspace",
  "dartboard": "workspace/Tasks"
}

See Project-Aware Hooks Documentation for detailed configuration options.

Customization

Disable a Hook

Edit ~/.claude/settings.json and remove or comment out the specific hook entry.

Add Custom Hooks

  • Create a Python script in ~/.claude/hooks/
  • Make it executable: chmod +x your-hook.py
  • Add it to the appropriate section in settings.json

Hook Exit Codes

  • 0 - Success, continue normally
  • 2 - Blocking error, prevents tool execution
  • Other - Non-blocking error, shows message but continues

Best Practices

  • Performance - Keep hooks fast to avoid slowing down Claude Code
  • Error Handling - Always handle exceptions gracefully
  • Clear Messages - Provide actionable feedback
  • Non-Blocking - Use warnings for suggestions, only block on critical issues

Troubleshooting

Hooks Not Running

  • Restart Claude Code after installation
  • Check ~/.claude/settings.json is valid JSON
  • Verify hook files are executable

Testing Hooks

echo '{"tool_name":"Bash","tool_input":{"command":"test"}}' | python3 ~/.claude/hooks/hook-name.py

Log Files

  • ~/.claude/bash-command-log.txt - All bash commands
  • ~/.claude/hooks/commands-YYYY-MM-DD.log - Daily command logs
  • ~/.claude/hooks/command-stats.json - Command frequency stats
  • ~/.claude/hooks/pending-dart-syncs.json - Pending doc syncs

Contributing

Contributions are welcome! Please:

  • Fork the repository
  • Create a feature branch
  • Add tests for new hooks
  • Submit a pull request

License

MIT License - see LICENSE file for details

Acknowledgments

Created for the Claude Code community to enhance productivity and maintain code quality.

Resources

Made with ❤️ by Sem

Sem Hooks Logo

Star History

Star History Chart

Keywords

claude

FAQs

Package last updated on 03 Jul 2025

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts