Hooks Automationのロゴ

Hooks Automation

コミュニティ
frankxai
hooks-automation

Configure and automate Claude Code hooks in .claude/settings.json (PreToolUse, PostToolUse, UserPromptSubmit, Stop, SubagentStop, SessionEnd). Use when setting up Claude Code hooks to auto-format files after edits, run pre-commit or safety checks before Bash commands, guard secrets or protected files, save session state on Stop or SessionEnd, or wire optional external CLI and MCP hook runners.

概要

公開者frankxai
リポジトリclaude-skills-library
スキル名hooks-automation
スター
47
フォーク
6
同梱ファイル
5
ライセンスMIT
リンク
  • Markdown形式の指示

    モデルが必要に応じて読み込むSKILL.mdファイルです。関連するリクエストがあったときだけトークンを消費します。

  • どのLLMでも利用可能

    AIスキルはプロバイダー固有のコードではなく、通常のMarkdownなので、GPT、Claude、Gemini、Grok、ローカルモデルで利用できます。

  • 5個の同梱ファイル

    モデルが作業中に読み取れるスクリプト、テンプレート、参考資料です。ファイルは読み取り専用で、実行されることはありません。

  • オープンソース

    frankxaiがGitHubで公開しています。インストールする前にソースを確認してください。

インストール

AIスキル「Hooks Automation」をTypingMindにインストールすれば、どのLLMでも利用できます。SKILL.mdを読み取れる別のAIエージェントに追加することもできます。

1

TypingMindにインストール

TypingMindはGitHubフォルダから直接スキルをインストールします。SKILL.mdを読み取り、リソースファイルをまとめてローカルに保存します。

  1. アプリを開き、「プラグイン」→「スキル」に移動します。
  2. 「GitHubからインストール」を選択します。
  3. 以下のスキルフォルダのURLを貼り付けて確定します。
    https://github.com/frankxai/claude-skills-library/tree/main/free-skills/hooks-automation
  4. スキルを利用したいチャットごとに、そのスキルを有効にしてください。
「プラグイン」→「スキル」→「スキルを追加」→「GitHubのURLから」を選択し、フォルダのURLを貼り付けて「続行」を押します。
2

別のAIエージェントにインストール

Agent Skills形式を読み取れるAIエージェントなら、このスキルを利用できます。フォルダをそのAIエージェントのスキルディレクトリにコピーしてください。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/frankxai/claude-skills-library.git /tmp/claude-skills-library
mkdir -p .claude/skills
cp -r /tmp/claude-skills-library/free-skills/hooks-automation .claude/skills/hooks-automation
コピー後、新しいスキルを読み込むためにClaude Codeを再起動してください。

TypingMindで使用

TypingMindのチャットでHooks Automationを有効にするだけで、あとはモデルが対応します。名前と説明がシステムプロンプトに含まれ、関連するリクエストがあると、モデルが指示の全文を自動で読み込みます。手動で呼び出す必要はなく、実際に使用されるまでトークンを消費しません。

関連するリクエストがあるとすぐに、モデルが自動的にHooks Automationを読み込みます。

どのAIモデルでも利用可能

AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、Hooks Automationは作成時に想定されたモデルに縛られません。TypingMindに一度インストールすれば、ご自身のAPIキーを使って、GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama、またはご自身で実行するローカルモデルで利用できます。

  • 必要なときだけ読み込み

    システムプロンプトには名前と説明だけが含まれます。関連するリクエストが初めてあったときに指示を取得するため、スキルを使わない間は指示の読み込みにトークンを消費しません。

  • チャットの途中でモデルを切り替え

    スキルはコードではなく指示なので、モデルを切り替えてもそのまま使えます。次のモデルも同じSKILL.mdを読み込みます。

スキルの指示

モデルが読み込むSKILL.mdの内容です。スキルはモデルが従う指示なので、インストールする前に確認してください。

Claude Code Hooks Automation

Configure deterministic lifecycle hooks in .claude/settings.json (project) or ~/.claude/settings.json (user) so Claude Code automatically formats edited files, gates risky shell or Git commands before execution, blocks secret leaks or protected-file writes, and persists session state on completion.

Trigger Boundaries

  • Activate when: Setting up or debugging .claude/settings.json or ~/.claude/settings.json "hooks", writing PreToolUse / PostToolUse / UserPromptSubmit / Stop / SubagentStop / SessionEnd scripts, enforcing exit 2 blocking gates, or returning structured JSON decisions on stdout.
  • Do NOT activate when: Writing React hooks (useState, useEffect), Git-only .git/hooks/ without Claude Code lifecycle integration, or generic webhook endpoints (Stripe/Polar/GitHub HTTP webhooks).

Native Claude Code Hooks (settings.json)

Claude Code executes shell commands registered under the "hooks" key in .claude/settings.json at specific lifecycle events. Every hook receives a JSON payload on stdin and communicates back via exit codes and stdout/stderr.

Hook Lifecycle Events

EventWhen It FiresCommon Use Cases
PreToolUseBefore a tool call executes (matches tool_name via regex matcher)Block unsafe Bash commands, run pre-commit checks before git commit, guard secrets and protected files
PostToolUseAfter a tool call completes successfullyAuto-format files after Write, Edit, or MultiEdit; run targeted tests
UserPromptSubmitWhen the user submits a prompt, before Claude processes itInject repository context, validate prompt constraints
StopWhen the main Claude Code agent finishes respondingSave session state, log trajectory metrics, verify completion checks
SubagentStopWhen a spawned subagent (Task) finishes respondingAggregate subagent outputs, verify handoff receipts
SessionEndWhen a Claude Code session closes or terminatesPersist final session state, export metrics, clean up temporary artifacts

Exit Code, Stdin & JSON Stdout Decision Contract

  • Stdin JSON payload: Every hook command receives JSON on stdin containing session_id, transcript_path, cwd, hook_event_name, and (for tool hooks) tool_name, tool_input, and tool_response.
  • Exit code 0 (Allow): Operation proceeds normally. When exiting 0, a hook may also print structured JSON to stdout for fine-grained decision control:
    json
    {
      "hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "allow",
        "permissionDecisionReason": "Verified safe read-only command"
      }
    }
    (Supported permissionDecision values for PreToolUse: "allow", "deny", "ask"; for Stop / SubagentStop: {"decision": "block", "reason": "Run test suite before stopping"}.)
  • Exit code 2 (Block): Immediately blocks the action (for PreToolUse, prevents the tool call; for Stop, prevents stopping) and feeds stderr directly back to Claude so it can self-correct.
  • Any other non-zero exit code: Non-blocking warning; logged to debug output while execution continues.

Primary Recipes (.claude/settings.json)

Recipe 1: Auto-Format After Every Edit + Pre-Commit Check + Secret/File Guard

Place this configuration in .claude/settings.json to:

  1. Guard against secret leaks and protected file edits (PreToolUse on Write|Edit|MultiEdit),
  2. Run a pre-commit check before git commit (PreToolUse on Bash), and
  3. Run Prettier automatically after every file edit (PostToolUse on Write|Edit|MultiEdit):
json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/file-and-secret-guard.sh"
          }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/pre-commit-check.sh"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path // empty' | xargs -r npx prettier --write"
          }
        ]
      }
    ]
  }
}
Blocking Pre-Commit Gate (.claude/hooks/pre-commit-check.sh)
bash
#!/usr/bin/env bash
set -euo pipefail
PAYLOAD="$(cat)"
CMD="$(printf '%s' "$PAYLOAD" | jq -r '.tool_input.command // empty')"

if [[ "$CMD" =~ git[[:space:]]+commit ]]; then
  if ! npm run lint --silent || ! npm test --silent; then
    echo "Pre-commit check failed: fix lint/test errors before committing." >&2
    exit 2
  fi
fi
exit 0
Blocking Secret & Protected-File Guard (.claude/hooks/file-and-secret-guard.sh)
bash
#!/usr/bin/env bash
set -euo pipefail
PAYLOAD="$(cat)"
FILE_PATH="$(printf '%s' "$PAYLOAD" | jq -r '.tool_input.file_path // empty')"
CONTENT="$(printf '%s' "$PAYLOAD" | jq -r '(.tool_input.content // .tool_input.new_string // empty)')"

if [[ "$FILE_PATH" =~ (^|/)(\.env|CANON_LOCKED\.md)$ ]]; then
  echo "Blocked write to protected file: $FILE_PATH" >&2
  exit 2
fi

if printf '%s' "$CONTENT" | grep -Eq '(sk-[A-Za-z0-9_-]{20,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{16})'; then
  echo "Blocked write: detected hardcoded secret token in $FILE_PATH" >&2
  exit 2
fi

exit 0

Recipe 2: Save Session State When a Session Ends (Stop / SessionEnd)

Use Stop (end of turn/task) and SessionEnd (when the session closes) in .claude/settings.json to persist session state and transcript metadata:

json
{
  "hooks": {
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/save-session-state.sh"
          }
        ]
      }
    ],
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": ".claude/hooks/save-session-state.sh"
          }
        ]
      }
    ]
  }
}

Example .claude/hooks/save-session-state.sh:

bash
#!/usr/bin/env bash
set -euo pipefail
mkdir -p .claude/state
PAYLOAD="$(cat)"
SESSION_ID="$(printf '%s' "$PAYLOAD" | jq -r '.session_id // "unknown"')"
printf '%s\n' "$PAYLOAD" > ".claude/state/session-${SESSION_ID}.json"
exit 0

Optional Integration: External CLI & Swarm Hook Runners

When running multi-agent swarms or external memory coordination alongside native .claude/settings.json hooks, you can wire optional CLI runners such as claude-flow inside the command field of a native hook:

bash
# Optional: pre-task and post-edit swarm memory hooks invoked from a command script
npx claude-flow hook pre-task --description "Implement authentication"
npx claude-flow hook post-edit --file "src/auth.js" --memory-key "auth/login"
npx claude-flow hook session-end --session-id "dev-session" --export-metrics

Reference

Detailed catalogs and extended patterns live in references/ and load on demand:

Verification Checklist

  1. Valid JSON: Verify .claude/settings.json parses cleanly with jq empty .claude/settings.json.
  2. Stdin Payload Test: Pipe a synthetic payload (echo '{"tool_name":"Bash","tool_input":{"command":"git commit -m test"}}' | .claude/hooks/pre-commit-check.sh) and verify exit code 0 vs 2.
  3. Fast Execution: Keep synchronous PreToolUse and PostToolUse hooks under 100ms or scope matcher tightly (Write|Edit|MultiEdit, Bash).
  4. Fail Closed with Exit Code 2: Always write the blocking reason to stderr (>&2) before exit 2 so Claude receives actionable feedback.

同梱ファイル

スキルが読み込まれている間、モデルは必要に応じてこれらを読み取ります。読み取り可能なファイルとして提供され、実行されることはありません。

よくある質問

AIスキル「Hooks Automation」では何ができますか?

Configure and automate Claude Code hooks in .claude/settings.json (PreToolUse, PostToolUse, UserPromptSubmit, Stop, SubagentStop, SessionEnd). Use when setting up Claude Code hooks to auto-format files after edits, run pre-commit or safety checks before Bash commands, guard secrets or protected files, save session state on Stop or SessionEnd, or wire optional external CLI and MCP hook runners.

TypingMindでHooks Automationを使うメリットは何ですか?

一度インストールすれば、どのモデルでも使えるからです。Hooks Automationはプロバイダー固有のコードではなく、通常のMarkdownで記述されているため、同じスキルをGPT-5、Claude、Gemini、Grok、ローカルモデルで利用できます。チャットの途中でモデルを切り替えても、そのまま使い続けられます。TypingMindは自分のAPIキーで動作するため、シート単位のサブスクリプションではなく、プロバイダーに直接料金を支払います。スキルとチャットは自分のストレージに保持されます。

TypingMindにHooks Automationをインストールするにはどうすればよいですか?

TypingMindで「プラグイン」→「スキル」→「GitHubからインストール」を開き、https://github.com/frankxai/claude-skills-library/tree/main/free-skills/hooks-automationを貼り付けてください。TypingMindがSKILL.mdを読み込み、関連ファイルをまとめて、チャットごとに有効にできるスキルとしてインストールします。

Hooks Automationを使えるAIモデルはどれですか?

TypingMindに接続したどのモデルでも利用できます。AIスキルはプロバイダー固有のコードではなく、通常のMarkdownで書かれた指示です。そのため、GPT、Claude、Gemini、Grok、ローカルモデルのいずれも、リクエストの内容がこのスキルの用途に合ったときに、このスキルを読み込めます。

Hooks Automationで使えるAIモデルの数に制限はありますか?

数に制限はありません。スキルに対応したモデルであれば、GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llamaなど、どのモデルでもHooks Automationを利用できます。すべてTypingMind上で、自分のAPIキーを使って利用できます。

AIスキル「Hooks Automation」は無料ですか?

はい。frankxaiがMITライセンスのもとでGitHubに公開しています。ご利用のAIプロバイダーに支払うのは、使用したトークンの料金だけです。

AIスキルとは何ですか?

AIスキルは、特定のタスクの実行方法をAIモデルに教える、再利用可能な指示のセットです。オープンなAgent Skills形式に従い、名前と説明を含むSKILL.mdファイルに加え、モデルが必要とするスクリプト、テンプレート、参照ファイルで構成されます。モデルはリクエストがスキルに合致したときだけ指示を読み込むため、インストール済みのスキルも、使うまでは費用がかかりません。

AIスキルは、プラグインやMCPサーバーとどう違いますか?

プラグインやMCPサーバーは、モデルが呼び出せる新しいツールを提供します。ツールとは、どこかで実行され、結果を返すコードです。一方、AIスキルは、タスクへの取り組み方、従うべき手順、望ましい出力の例といった知識や進め方をモデルに伝えます。スキルは通常のMarkdownで記述されているため、サーバー、APIキー、実行環境は不要で、どのモデルでも利用できます。

すべて見る

今すぐ自分専用のAIワークスペースを作成

ニュースレターに登録すると、新機能や今後のプレゼント企画のお知らせが届きます👇