jpskill.com
🧩 Skill開発 Anthropic公式 🔴 エンジニア向け 👤 エンジニア・AI開発者

🪝 Claude Code Hookify ルール作成

Writing Hookify Rules

Claude Code の「Hookify ルール」(動作の差し込みルール)を書くためのSkill。上級者向け。

⏱ 社内ナレッジ → Skill化 1日 → 1時間

📺 まず動画で見る(YouTube)

▶ 【Claude Code Skills超入門】自分専用のAI社員を作る方法 ↗

※ jpskill.com 編集部が参考用に選んだ動画です。動画の内容と Skill の挙動は厳密には一致しないことがあります。

📜 元の英語説明(参考)

This skill should be used when the user asks to "create a hookify rule", "write a hook rule", "configure hookify", "add a hookify rule", or needs guidance on hookify rule syntax and patterns.

🇯🇵 日本人クリエイター向け解説

一言でいうと

Claude Code の「Hookify ルール」(動作の差し込みルール)を書くためのSkill。上級者向け。

日本人がよく使う場面
・社内チームの Claude Code 利用にガードレール設置 ・コミット前の自動レビュールール ・特定コマンドの実行制限ルール

※ jpskill.com 編集部が日本のビジネス現場向けに補足した解説です。Skill本体の挙動とは独立した参考情報です。

⚠️ ダウンロード・利用は自己責任でお願いします。当サイトは内容・動作・安全性について責任を負いません。

🎯 このSkillでできること

下記の説明文を読むと、このSkillがあなたに何をしてくれるかが分かります。Claudeにこの分野の依頼をすると、自動で発動します。

📦 インストール方法 (3ステップ)

  1. 1. 上の「ダウンロード」ボタンを押して .skill ファイルを取得
  2. 2. ファイル名の拡張子を .skill から .zip に変えて展開(macは自動展開可)
  3. 3. 展開してできたフォルダを、ホームフォルダの .claude/skills/ に置く
    • · macOS / Linux: ~/.claude/skills/
    • · Windows: %USERPROFILE%\.claude\skills\

Claude Code を再起動すれば完了。「このSkillを使って…」と話しかけなくても、関連する依頼で自動的に呼び出されます。

詳しい使い方ガイドを見る →
最終更新
2026-05-17
取得日時
2026-05-17
同梱ファイル
1

💬 こう話しかけるだけ — サンプルプロンプト

  • Claude Code Hookify ルール作成 を使って、最小構成のサンプルコードを示して
  • Claude Code Hookify ルール作成 の主な使い方と注意点を教えて
  • Claude Code Hookify ルール作成 を既存プロジェクトに組み込む方法を教えて

これをClaude Code に貼るだけで、このSkillが自動発動します。

📖 Skill本文(日本語訳)

※ 原文(英語/中国語)を Gemini で日本語化したものです。Claude 自身は原文を読みます。誤訳がある場合は原文をご確認ください。

Hookifyルールの記述

概要

Hookifyルールは、監視するパターンと、そのパターンが一致したときに表示するメッセージを定義する、YAMLフロントマター付きのMarkdownファイルです。ルールは.claude/hookify.{rule-name}.local.mdファイルに保存されます。

ルールファイルの形式

基本構造

---
name: rule-identifier
enabled: true
event: bash|file|stop|prompt|all
pattern: regex-pattern-here
---

このルールがトリガーされたときにClaudeに表示するメッセージです。
Markdown形式、警告、提案などを含めることができます。

フロントマターフィールド

name (必須): ルールの一意な識別子

  • ケバブケースを使用します: warn-dangerous-rm, block-console-log
  • 説明的で行動指向にします
  • 動詞で始めます: warn, prevent, block, require, check

enabled (必須): 有効/無効を切り替えるブール値

  • true: ルールがアクティブです
  • false: ルールは無効です(トリガーされません)
  • ルールを削除せずに切り替えることができます

event (必須): どのフックイベントでトリガーするか

  • bash: Bashツールコマンド
  • file: Edit、Write、MultiEditツール
  • stop: エージェントが停止したいとき
  • prompt: ユーザーがプロンプトを送信したとき
  • all: すべてのイベント

action (オプション): ルールが一致したときに何をするか

  • warn: メッセージを表示しますが、操作を許可します(デフォルト)
  • block: 操作を防止します(PreToolUse)またはセッションを停止します(Stopイベント)
  • 省略した場合、デフォルトはwarnです

pattern (簡易形式): マッチさせる正規表現パターン

  • 単純な単一条件ルールに使用されます
  • コマンド(bash)またはnew_text(file)に対してマッチします
  • Pythonの正規表現構文

例:

event: bash
pattern: rm\s+-rf

高度な形式(複数条件)

複数の条件を持つ複雑なルールの場合:

---
name: warn-env-file-edits
enabled: true
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.env$
  - field: new_text
    operator: contains
    pattern: API_KEY
---

.envファイルにAPIキーを追加しています。このファイルが.gitignoreに含まれていることを確認してください!

条件フィールド:

  • field: チェックするフィールド
    • bashの場合: command
    • fileの場合: file_path, new_text, old_text, content
  • operator: マッチ方法
    • regex_match: 正規表現パターンマッチング
    • contains: 部分文字列チェック
    • equals: 完全一致
    • not_contains: 部分文字列が存在してはならない
    • starts_with: 接頭辞チェック
    • ends_with: 接尾辞チェック
  • pattern: マッチさせるパターンまたは文字列

ルールがトリガーされるには、すべての条件が一致する必要があります。

メッセージ本文

フロントマターの後のMarkdownコンテンツは、ルールがトリガーされたときにClaudeに表示されます。

良いメッセージ:

  • 何が検出されたかを説明します
  • なぜそれが問題なのかを説明します
  • 代替案やベストプラクティスを提案します
  • 明確にするために書式設定(太字、リストなど)を使用します

例:

⚠️ **Console.logが検出されました!**

本番コードにconsole.logを追加しています。

**これが重要な理由:**
- デバッグログは本番環境に出荷すべきではありません
- Console.logは機密データを公開する可能性があります
- ブラウザのパフォーマンスに影響を与えます

**代替案:**
- 適切なロギングライブラリを使用する
- コミットする前に削除する
- 条件付きデバッグビルドを使用する

イベントタイプガイド

bashイベント

Bashコマンドパターンにマッチします:

---
event: bash
pattern: sudo\s+|rm\s+-rf|chmod\s+777
---

危険なコマンドが検出されました!

一般的なパターン:

  • 危険なコマンド: rm\s+-rf, dd\s+if=, mkfs
  • 権限昇格: sudo\s+, su\s+
  • 権限の問題: chmod\s+777, chown\s+root

fileイベント

Edit/Write/MultiEdit操作にマッチします:

---
event: file
pattern: console\.log\(|eval\(|innerHTML\s*=
---

潜在的に問題のあるコードパターンが検出されました!

異なるフィールドでマッチ:

---
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.tsx?$
  - field: new_text
    operator: regex_match
    pattern: console\.log\(
---

TypeScriptファイルにConsole.logがあります!

一般的なパターン:

  • デバッグコード: console\.log\(, debugger, print\(
  • セキュリティリスク: eval\(, innerHTML\s*=, dangerouslySetInnerHTML
  • 機密ファイル: \.env$, credentials, \.pem$
  • 生成されたファイル: node_modules/, dist/, build/

stopイベント

エージェントが停止したいとき(完了チェック)にマッチします:

---
event: stop
pattern: .*
---

停止する前に、以下を確認してください:
- [ ] テストは実行されましたか
- [ ] ビルドは成功しましたか
- [ ] ドキュメントは更新されましたか

用途:

  • 必要な手順のリマインダー
  • 完了チェックリスト
  • プロセス強制

promptイベント

ユーザープロンプトの内容にマッチします(高度な機能):

---
event: prompt
conditions:
  - field: user_prompt
    operator: contains
    pattern: deploy to production
---

本番デプロイメントチェックリスト:
- [ ] テストはパスしていますか?
- [ ] チームによるレビューは行われましたか?
- [ ] モニタリングは準備できていますか?

パターン記述のヒント

正規表現の基本

リテラル文字: ほとんどの文字はそれ自体にマッチします

  • rm は "rm" にマッチします
  • console.log は "console.log" にマッチします

特殊文字はエスケープが必要です:

  • . (任意の文字) → \. (リテラルなドット)
  • ( )\( \) (リテラルな丸括弧)
  • [ ]\[ \] (リテラルな角括弧)

一般的なメタ文字:

  • \s - 空白文字(スペース、タブ、改行)
  • \d - 数字(0-9)
  • \w - 単語文字(a-z、A-Z、0-9、_)
  • . - 任意の文字
  • + - 1回以上
  • * - 0回以上
  • ? - 0回または1回
  • | - OR

例:

rm\s+-rf         マッチ: rm -rf, rm  -rf
console\.log\(   マッチ: console.log(
(eval|exec)\(    マッチ: eval( または exec(
chmod\s+777      マッチ: chmod 777, chmod  777
API_KEY\s*=      マッチ: API_KEY=, API_KEY =

パターンのテスト

使用する前に正規表現パターンをテストしてください:

python3 -c "import re; print(re.search(r'your_pattern', 'test text'))"

または、オンラインの正規表現テスター(Pythonフレーバーのregex101.com)を使用してください。

よくある落とし穴

広すぎる:

pattern: log    # "log", "login", "dialog", "catalog" にマッチします

より良い: console\.log\(|logger\.

狭すぎる:

pattern: rm -rf /tmp  # 正確なパスのみにマッチします

より良い: rm\s+-rf

エスケープの問題:

  • YAML引用符付き文字列: "pattern" は二重バックスラッシュ \\s を必要とします
  • YAML引用符なし
📜 原文 SKILL.md(Claudeが読む英語/中国語)を展開

Writing Hookify Rules

Overview

Hookify rules are markdown files with YAML frontmatter that define patterns to watch for and messages to show when those patterns match. Rules are stored in .claude/hookify.{rule-name}.local.md files.

Rule File Format

Basic Structure

---
name: rule-identifier
enabled: true
event: bash|file|stop|prompt|all
pattern: regex-pattern-here
---

Message to show Claude when this rule triggers.
Can include markdown formatting, warnings, suggestions, etc.

Frontmatter Fields

name (required): Unique identifier for the rule

  • Use kebab-case: warn-dangerous-rm, block-console-log
  • Be descriptive and action-oriented
  • Start with verb: warn, prevent, block, require, check

enabled (required): Boolean to activate/deactivate

  • true: Rule is active
  • false: Rule is disabled (won't trigger)
  • Can toggle without deleting rule

event (required): Which hook event to trigger on

  • bash: Bash tool commands
  • file: Edit, Write, MultiEdit tools
  • stop: When agent wants to stop
  • prompt: When user submits a prompt
  • all: All events

action (optional): What to do when rule matches

  • warn: Show message but allow operation (default)
  • block: Prevent operation (PreToolUse) or stop session (Stop events)
  • If omitted, defaults to warn

pattern (simple format): Regex pattern to match

  • Used for simple single-condition rules
  • Matches against command (bash) or new_text (file)
  • Python regex syntax

Example:

event: bash
pattern: rm\s+-rf

Advanced Format (Multiple Conditions)

For complex rules with multiple conditions:

---
name: warn-env-file-edits
enabled: true
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.env$
  - field: new_text
    operator: contains
    pattern: API_KEY
---

You're adding an API key to a .env file. Ensure this file is in .gitignore!

Condition fields:

  • field: Which field to check
    • For bash: command
    • For file: file_path, new_text, old_text, content
  • operator: How to match
    • regex_match: Regex pattern matching
    • contains: Substring check
    • equals: Exact match
    • not_contains: Substring must NOT be present
    • starts_with: Prefix check
    • ends_with: Suffix check
  • pattern: Pattern or string to match

All conditions must match for rule to trigger.

Message Body

The markdown content after frontmatter is shown to Claude when the rule triggers.

Good messages:

  • Explain what was detected
  • Explain why it's problematic
  • Suggest alternatives or best practices
  • Use formatting for clarity (bold, lists, etc.)

Example:

⚠️ **Console.log detected!**

You're adding console.log to production code.

**Why this matters:**
- Debug logs shouldn't ship to production
- Console.log can expose sensitive data
- Impacts browser performance

**Alternatives:**
- Use a proper logging library
- Remove before committing
- Use conditional debug builds

Event Type Guide

bash Events

Match Bash command patterns:

---
event: bash
pattern: sudo\s+|rm\s+-rf|chmod\s+777
---

Dangerous command detected!

Common patterns:

  • Dangerous commands: rm\s+-rf, dd\s+if=, mkfs
  • Privilege escalation: sudo\s+, su\s+
  • Permission issues: chmod\s+777, chown\s+root

file Events

Match Edit/Write/MultiEdit operations:

---
event: file
pattern: console\.log\(|eval\(|innerHTML\s*=
---

Potentially problematic code pattern detected!

Match on different fields:

---
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.tsx?$
  - field: new_text
    operator: regex_match
    pattern: console\.log\(
---

Console.log in TypeScript file!

Common patterns:

  • Debug code: console\.log\(, debugger, print\(
  • Security risks: eval\(, innerHTML\s*=, dangerouslySetInnerHTML
  • Sensitive files: \.env$, credentials, \.pem$
  • Generated files: node_modules/, dist/, build/

stop Events

Match when agent wants to stop (completion checks):

---
event: stop
pattern: .*
---

Before stopping, verify:
- [ ] Tests were run
- [ ] Build succeeded
- [ ] Documentation updated

Use for:

  • Reminders about required steps
  • Completion checklists
  • Process enforcement

prompt Events

Match user prompt content (advanced):

---
event: prompt
conditions:
  - field: user_prompt
    operator: contains
    pattern: deploy to production
---

Production deployment checklist:
- [ ] Tests passing?
- [ ] Reviewed by team?
- [ ] Monitoring ready?

Pattern Writing Tips

Regex Basics

Literal characters: Most characters match themselves

  • rm matches "rm"
  • console.log matches "console.log"

Special characters need escaping:

  • . (any char) → \. (literal dot)
  • ( )\( \) (literal parens)
  • [ ]\[ \] (literal brackets)

Common metacharacters:

  • \s - whitespace (space, tab, newline)
  • \d - digit (0-9)
  • \w - word character (a-z, A-Z, 0-9, _)
  • . - any character
  • + - one or more
  • * - zero or more
  • ? - zero or one
  • | - OR

Examples:

rm\s+-rf         Matches: rm -rf, rm  -rf
console\.log\(   Matches: console.log(
(eval|exec)\(    Matches: eval( or exec(
chmod\s+777      Matches: chmod 777, chmod  777
API_KEY\s*=      Matches: API_KEY=, API_KEY =

Testing Patterns

Test regex patterns before using:

python3 -c "import re; print(re.search(r'your_pattern', 'test text'))"

Or use online regex testers (regex101.com with Python flavor).

Common Pitfalls

Too broad:

pattern: log    # Matches "log", "login", "dialog", "catalog"

Better: console\.log\(|logger\.

Too specific:

pattern: rm -rf /tmp  # Only matches exact path

Better: rm\s+-rf

Escaping issues:

  • YAML quoted strings: "pattern" requires double backslashes \\s
  • YAML unquoted: pattern: \s works as-is
  • Recommendation: Use unquoted patterns in YAML

File Organization

Location: All rules in .claude/ directory Naming: .claude/hookify.{descriptive-name}.local.md Gitignore: Add .claude/*.local.md to .gitignore

Good names:

  • hookify.dangerous-rm.local.md
  • hookify.console-log.local.md
  • hookify.require-tests.local.md
  • hookify.sensitive-files.local.md

Bad names:

  • hookify.rule1.local.md (not descriptive)
  • hookify.md (missing .local)
  • danger.local.md (missing hookify prefix)

Workflow

Creating a Rule

  1. Identify unwanted behavior
  2. Determine which tool is involved (Bash, Edit, etc.)
  3. Choose event type (bash, file, stop, etc.)
  4. Write regex pattern
  5. Create .claude/hookify.{name}.local.md file in project root
  6. Test immediately - rules are read dynamically on next tool use

Refining a Rule

  1. Edit the .local.md file
  2. Adjust pattern or message
  3. Test immediately - changes take effect on next tool use

Disabling a Rule

Temporary: Set enabled: false in frontmatter Permanent: Delete the .local.md file

Examples

See ${CLAUDE_PLUGIN_ROOT}/examples/ for complete examples:

  • dangerous-rm.local.md - Block dangerous rm commands
  • console-log-warning.local.md - Warn about console.log
  • sensitive-files-warning.local.md - Warn about editing .env files

Quick Reference

Minimum viable rule:

---
name: my-rule
enabled: true
event: bash
pattern: dangerous_command
---

Warning message here

Rule with conditions:

---
name: my-rule
enabled: true
event: file
conditions:
  - field: file_path
    operator: regex_match
    pattern: \.ts$
  - field: new_text
    operator: contains
    pattern: any
---

Warning message

Event types:

  • bash - Bash commands
  • file - File edits
  • stop - Completion checks
  • prompt - User input
  • all - All events

Field options:

  • Bash: command
  • File: file_path, new_text, old_text, content
  • Prompt: user_prompt

Operators:

  • regex_match, contains, equals, not_contains, starts_with, ends_with