К основному содержанию
плагин официальный · Anthropic

hookify — плагин для Claude Code: что делает и как установить

Создаёт хуки и правила для Claude Code через простые Markdown-файлы. Защищает проект от случайных опасных команд и нежелательных правок в коде.

Установить в Claude Code · Через маркетплейс плагинов Все способы и платформы ↓
/plugin install hookify@claude-plugins-official
/plugin marketplace add anthropics/claude-plugins-official
Открыть на GitHub

Что делает hookify

Плагин заменяет ручную настройку файла hooks.json короткими правилами в формате Markdown с YAML-шапкой. Достаточно описать нежелательное действие своими словами через команду /hookify или запустить её без аргументов, чтобы агент сам нашёл спорные моменты в недавнем диалоге.

Файлы правил сохраняются в папку .claude/ с расширением .local.md. Они проверяют команды терминала (bash), правку файлов (file), остановку сессии (stop) или текст промптов (prompt) с помощью регулярных выражений Python. Действие можно настроить на простое предупреждение (warn) либо на полную блокировку вызова (block).

Перезапуск сессии после добавления правила не требуется: хук начинает действовать на следующем шаге. Для работы плагина нужен интерпретатор Python 3.7+, но сторонние библиотеки не понадобятся.

Какие задачи решает

  • блокировать опасные команды вроде rm -rf в терминале
  • запрещать добавление отладочного кода в файлы
  • предотвращать утечку API-ключей и паролей в коммиты
  • требовать обязательного запуска тестов перед завершением сессии

Примеры запросов агенту

  • /hookify Предупреждай меня при запуске команд rm -rf
  • /hookify Запрети писать console.log в файлах TypeScript
  • /hookify:configure

Как установить hookify

Через маркетплейс плагинов

/plugin install hookify@claude-plugins-official
/plugin marketplace add anthropics/claude-plugins-official

По шагам, с командами для каждой платформы: Плагины Claude Code: маркетплейсы, установка и как собрать свой

Вопросы о hookify

Как установить hookify в Claude Code?

Сначала добавьте официальный каталог командой /plugin marketplace add anthropics/claude-plugins-official, а затем запустите установку: /plugin install hookify@claude-plugins-official.

Что делает плагин hookify?

Он перехватывает действия Claude Code, сверяет команды и текст правок с регулярными выражениями и выдаёт предупреждения или блокирует небезопасные операции.

Какие требования нужны для работы плагина?

На компьютере должен быть установлен Python версии 3.7 или новее. Дополнительные пакеты ставить не нужно, плагин использует только стандартную библиотеку Python.

Исходный текст

hookify · Apache-2.0
# Hookify Plugin

Easily create custom hooks to prevent unwanted behaviors by analyzing conversation patterns or from explicit instructions.

## Overview

The hookify plugin makes it simple to create hooks without editing complex `hooks.json` files. Instead, you create lightweight markdown configuration files that define patterns to watch for and messages to show when those patterns match.

**Key features:**
- 🎯 Analyze conversations to find unwanted behaviors automatically
- 📝 Simple markdown configuration files with YAML frontmatter
- 🔍 Regex pattern matching for powerful rules
- 🚀 No coding required - just describe the behavior
- 🔄 Easy enable/disable without restarting

## Quick Start

### 1. Create Your First Rule

```bash
/hookify Warn me when I use rm -rf commands
```

This analyzes your request and creates `.claude/hookify.warn-rm.local.md`.

### 2. Test It Immediately

**No restart needed!** Rules take effect on the very next tool use.

Ask Claude to run a command that should trigger the rule:
```
Run rm -rf /tmp/test
```

You should see the warning message immediately!

## Usage

### Main Command: /hookify

**With arguments:**
```
/hookify Don't use console.log in TypeScript files
```
Creates a rule from your explicit instructions.

**Without arguments:**
```
/hookify
```
Analyzes recent conversation to find behaviors you've corrected or been frustrated by.

### Helper Commands

**List all rules:**
```
/hookify:list
```

**Configure rules interactively:**
```
/hookify:configure
```
Enable/disable existing rules through an interactive interface.

**Get help:**
```
/hookify:help
```

## Rule Configuration Format

### Simple Rule (Single Pattern)

`.claude/hookify.dangerous-rm.local.md`:
```markdown
---
name: block-dangerous-rm
enabled: true
event: bash
pattern: rm\s+-rf
action: block
---

⚠️ **Dangerous rm command detected!**

This command could delete important files. Please:
- Verify the path is correct
- Consider using a safer approach
- Make sure you have backups
```

**Action field:**
- `warn`: Shows warning but allows operation (default)
- `block`: Prevents operation from executing (PreToolUse) or stops session (Stop events)

### Advanced Rule (Multiple Conditions)

`.claude/hookify.sensitive-files.local.md`:
```markdown
---
name: warn-sensitive-files
enabled: true
event: file
action: warn
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.env$|credentials|secrets
  - field: new_text
    operator: contains
    pattern: KEY
---

🔐 **Sensitive file edit detected!**

Ensure credentials are not hardcoded and file is in .gitignore.
```

**All conditions must match** for the rule to trigger.

## Event Types

- **`bash`**: Triggers on Bash tool commands
- **`file`**: Triggers on Edit, Write, MultiEdit tools
- **`stop`**: Triggers when Claude wants to stop (for completion checks)
- **`prompt`**: Triggers on user prompt submission
- **`all`**: Triggers on all events

## Pattern Syntax

Use Python regex syntax:

| Pattern | Matches | Example |
|---------|---------|---------|
| `rm\s+-rf` | rm -rf | rm -rf /tmp |
| `console\.log\(` | console.log( | console.log("test") |
| `(eval\|exec)\(` | eval( or exec( | eval("code") |
| `\.env$` | files ending in .env | .env, .env.local |
| `chmod\s+777` | chmod 777 | chmod 777 file.txt |

**Tips:**
- Use `\s` for whitespace
- Escape special chars: `\.` for literal dot
- Use `|` for OR: `(foo|bar)`
- Use `.*` to match anything
- Set `action: block` for dangerous operations
- Set `action: warn` (or omit) for informational warnings

## Examples

### Example 1: Block Dangerous Commands

```markdown
---
name: block-destructive-ops
enabled: true
event: bash
pattern: rm\s+-rf|dd\s+if=|mkfs|format
action: block
---

🛑 **Destructive operation detected!**

This command can cause data loss. Operation blocked for safety.
Please verify the exact path and use a safer approach.
```

**This rule blocks the operation** - Claude will not be allowed to execute these commands.

### Example 2: Warn About Debug Code

```markdown
---
name: warn-debug-code
enabled: true
event: file
pattern: console\.log\(|debugger;|print\(
action: warn
---

🐛 **Debug code detected**

Remember to remove debugging statements before committing.
```

**This rule warns but allows** - Claude sees the message but can still proceed.

### Example 3: Require Tests Before Stopping

```markdown
---
name: require-tests-run
enabled: false
event: stop
action: block
conditions:
  - field: transcript
    operator: not_contains
    pattern: npm test|pytest|cargo test
---

**Tests not detected in transcript!**

Before stopping, please run tests to verify your changes work correctly.
```

**This blocks Claude from stopping** if no test commands appear in the session transcript. Enable only when you want strict enforcement.

## Advanced Usage

### Multiple Conditions

Check multiple fields simultaneously:

```markdown
---
name: api-key-in-typescript
enabled: true
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.tsx?$
  - field: new_text
    operator: regex_match
    pattern: (API_KEY|SECRET|TOKEN)\s*=\s*["']
---

🔐 **Hardcoded credential in TypeScript!**

Use environment variables instead of hardcoded values.
```

### Operators Reference

- `regex_match`: Pattern must match (most common)
- `contains`: String must contain pattern
- `equals`: Exact string match
- `not_contains`: String must NOT contain pattern
- `starts_with`: String starts with pattern
- `ends_with`: String ends with pattern

### Field Reference

**For bash events:**
- `command`: The bash command string

**For file events:**
- `file_path`: Path to file being edited
- `new_text`: New content being added (Edit, Write)
- `old_text`: Old content being replaced (Edit only)
- `content`: File content (Write only)

**For prompt events:**
- `user_prompt`: The user's submitted prompt text

**For stop events:**
- Use general matching on session state

## Management

### Enable/Disable Rules

**Temporarily disable:**
Edit the `.local.md` file and set `enabled: false`

**Re-enable:**
Set `enabled: true`

**Or use interactive tool:**
```
/hookify:configure
```

### Delete Rules

Simply delete the `.local.md` file:
```bash
rm .claude/hookify.my-rule.local.md
```

### View All Rules

```
/hookify:list
```

## Installation

This plugin is part of the Claude Code Marketplace. It should be auto-discovered when the marketplace is installed.

**Manual testing:**
```bash
cc --plugin-dir /path/to/hookify
```

## Requirements

- Python 3.7+
- No external dependencies (uses stdlib only)

## Troubleshooting

**Rule not triggering:**
1. Check rule file exists in `.claude/` directory (in project root, not plugin directory)
2. Verify `enabled: true` in frontmatter
3. Test regex pattern separately
4. Rules should work immediately - no restart needed
5. Try `/hookify:list` to see if rule is loaded

**Import errors:**
- Ensure Python 3 is available: `python3 --version`
- Check hookify plugin is installed

**Pattern not matching:**
- Test regex: `python3 -c "import re; print(re.search(r'pattern', 'text'))"`
- Use unquoted patterns in YAML to avoid escaping issues
- Start simple, then add complexity

**Hook seems slow:**
- Keep patterns simple (avoid complex regex)
- Use specific event types (bash, file) instead of "all"
- Limit number of active rules

## Contributing

Found a useful rule pattern? Consider sharing example files via PR!

## Future Enhancements

- Severity levels (error/warning/info distinctions)
- Rule templates library
- Interactive pattern builder
- Hook testing utilities
- JSON format support (in addition to markdown)

## License

MIT License

© Anthropic · Apache-2.0 · anthropics/claude-plugins-official

Похожие плагины

Все плагины по теме «Настройка агента: память, контекст, субагенты» →
ponytail DietrichGebert Плагин настраивает агента на короткие решения без лишних абстракций. Сгодится, когда нужно использовать возможности уже имеющегося кода и не усложнять задачу. ★ 176 443звёзд репо impeccable pbakaus Даёт агенту словарь дизайнера: 24 команды вроде polish, audit и bolder, чтобы правки интерфейса не сводились к «сделай красиво». ★ 88 212звёзд репо last-30-days-skill mvanhorn Собирает свежие посты, комментарии и транскрипты по любой теме за последний месяц и укладывает их в один отчёт. ★ 65 508звёзд репо claude-hud jarrodwatts Показывает под строкой ввода, сколько контекста занято, какие инструменты работают и как идут задачи. Пригодится, когда сессия длинная и надо видеть расход. ★ 28 841звёзд репо understand-anything Egonex-AI Плагин сканирует проект и строит интерактивный граф файлов, классов и зависимостей с веб-дашбордом. Пригодится при знакомстве с чужим или крупным кодом. ★ 88 314звёзд репо mem0 mem0ai Подключает долговременную память к Claude Code, сохраняя контекст проектов и привычки между сессиями. ★ 67 829звёзд репо

Из того же набора123

Весь набор →
laravel-boost MCP-сервер с инструментами Laravel: Artisan, Eloquent, роутинг, миграции и генерация кода под фреймворк. ★ 44 635звёзд репо kotlin-lsp Плагин подключает языковой сервер Kotlin к Claude Code. Помогает разбирать код и проводить рефакторинг в файлах .kt и .kts. ★ 44 635звёзд репо jdtls-lsp Подключает Eclipse JDT.LS к Claude Code для анализа Java-кода и рефакторинга. Нужен при работе с файлами .java. ★ 44 635звёзд репо imessage Подключает iMessage к Claude: читает историю из chat.db, отправляет через AppleScript. Только macOS. ★ 44 635звёзд репо gopls-lsp Подключает языковой сервер gopls к Claude, чтобы агент видел структуру Go-кода и увереннее его правил. ★ 44 635звёзд репо gitlab Подключает GitLab к Claude Code: агент работает с репозиториями, мерж-реквестами, пайплайнами, задачами и вики прямо из чата. ★ 44 635звёзд репо github Официальный MCP-сервер GitHub для управления репозиториями прямо из Claude Code. Помогает работать с пуллреквестами, задачами и кодом без браузера. ★ 44 635звёзд репо frontend-design Скилл для Claude, который ведёт фронтенд-работу к выразительной типографике, палитре и анимации вместо типовых ИИ-макетов. ★ 44 635звёзд репо

Спонсоры проекта

Компании, которые помогают держать аналитику открытой