跳到正文
cccskills
免费在 GitHub 公开

hook-template

Generate hook script from template. Use when adding a new hook, wiring a PreToolUse/PostToolUse/Stop/Notification hook, or scaffolding hook config for settings.json.

中文简介正在准备中。当前显示原文说明。

查看安装方法

包含的文件(1)

  • SKILL.md6.1 KB

SKILL.md(原文)

安装前可以查看交给 AI 代理的指令内容。

Hook Template Generator

Generate a hook script and configuration based on requirements.

Usage: /hook-template [hook-event] [purpose]


Hook Events

Claude Code defines 30 hook events. The common ones, grouped:

GroupEvents
LifecycleSessionStart, SessionEnd, Setup
PromptUserPromptSubmit, UserPromptExpansion
ToolPreToolUse, PostToolUse, PostToolUseFailure, PostToolBatch
PermissionPermissionRequest, PermissionDenied
SubagentSubagentStart, SubagentStop
StopStop, StopFailure
TaskTaskCreated, TaskCompleted
CompactionPreCompact, PostCompact
NotificationNotification, MessageDisplay
MCP elicitationElicitation, ElicitationResult
EnvironmentConfigChange, CwdChanged, FileChanged, InstructionsLoaded, WorktreeCreate, WorktreeRemove, TeammateIdle

That is all 30 events. See the official Claude Code hooks docs for the full list and each event's payload. The templates below cover the practical 90%.


Hook Config Fields

FieldTypeRequiredDefaultNotes
typeStringNocommandcommand, prompt, http, mcp_tool, or agent
commandStringIf type=command-Shell command to execute
promptStringIf type=prompt-Natural language prompt evaluated by an LLM
matcherStringNo-For tool events: tool name, regex, or *
timeoutIntegerNo60Seconds, per hook
onceBooleanNofalseRun hook only once per session
ifStringNo-Conditional guard for the hook
statusMessageStringNo-Message shown while the hook runs

type: command (default) and type: prompt (LLM-evaluated) cover most needs. The http, mcp_tool, and agent entry types also exist for calling an endpoint, invoking an MCP tool, or dispatching a subagent.


Hook Input (stdin JSON)

All hooks receive JSON on stdin. The event name is in hook_event_name:

{
  "session_id": "abc123",
  "transcript_path": "/path/to/transcript.txt",
  "cwd": "/current/working/dir",
  "permission_mode": "ask",
  "hook_event_name": "PreToolUse",
  "tool_name": "Write",
  "tool_input": { "file_path": "/path/to/file" }
}

Decision output cheatsheet

  • PreToolUse: return hookSpecificOutput.permissionDecision of allow, deny, or ask. Exit code 2 with a stderr message is the shorthand for deny. The legacy top-level {"decision": "approve" | "block"} is still accepted.
  • Stop / SubagentStop: to continue the loop, return {"decision": "block", "reason": "<next prompt>"} — the key is reason.
  • Silent success is exit 0 with no output.

Process

  1. Gather Requirements

    • Hook event
    • Purpose
    • Matcher (for tool events: tool name, regex, or *)
  2. Generate Script at .claude/hooks/[name].sh

  3. Update settings.json with hook config

  4. Make Executable: chmod +x

  5. Validate with /hooks-check


Templates

PreToolUse (Blocker, exit-code shorthand)

#!/bin/bash
INPUT=$(cat)
TOOL=$(echo "$INPUT" | jq -r '.tool_name')
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

# Block edits to specific files
if [[ "$FILE" == *"package-lock.json"* ]]; then
    echo "BLOCKED: Do not edit lockfiles directly" >&2
    exit 2   # exit 2 = deny for PreToolUse
fi
exit 0  # Allow (no output needed)

PreToolUse (Deny via JSON permissionDecision)

#!/bin/bash
INPUT=$(cat)
FILE=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')

if [[ "$FILE" == *"package-lock.json"* ]]; then
    jq -n '{
      "hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "permissionDecision": "deny",
        "permissionDecisionReason": "Do not edit lockfiles directly"
      }
    }'
    exit 0
fi
# permissionDecision may be "allow", "deny", or "ask"
exit 0

PreToolUse (Context Adding)

#!/bin/bash
cat > /dev/null  # Consume stdin
INFO="This file requires careful review"
jq -n --arg ctx "$INFO" '{
    "hookSpecificOutput": {
        "hookEventName": "PreToolUse",
        "additionalContext": $ctx
    }
}'
exit 0

PostToolUse (Logger)

#!/bin/bash
INPUT=$(cat)
# Process and log... (no stdout needed)
exit 0

Stop (Auto-Loop)

#!/bin/bash
CHECKPOINT=".auto-loop/checkpoint.json"
if [[ ! -f "$CHECKPOINT" ]]; then
    exit 0  # Allow stop
fi
# Block stop to continue loop — key is "reason", used as the next prompt
jq -n --arg reason "Continuing iteration" \
    '{"decision": "block", "reason": $reason}'
exit 0

SessionStart (Context Load)

#!/bin/bash
cat > /dev/null
echo "Loading project context..." >&2
exit 0

Prompt Hook (LLM-based)

Instead of a bash script, use type: "prompt" in settings.json:

{
  "hooks": {
    "Stop": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Review the work done. Return 'approve' if complete, or 'block' with reason.",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Settings.json Format

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/validate.sh",
            "timeout": 60
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "$CLAUDE_PROJECT_DIR/.claude/hooks/load-context.sh",
            "once": true
          }
        ]
      }
    ]
  }
}

Example

/hook-template PreToolUse "block edits to package-lock.json"

Creates:
- .claude/hooks/protect-lockfile.sh
- Updates .claude/settings.json

评价

还没有评价。欢迎分享你的使用感受。

评论

无需登录即可发表。欢迎分享使用感受、提问,或说明在哪些环境下无法运行。

还没有评论。来写第一条吧。

提交后会立即公开。请勿填写邮箱、电话等个人信息。URL 最多 2 个。

0 / 1000 字

此表单受 reCAPTCHA 保护,适用 Google 的隐私权政策和服务条款。

同一仓库的技能

Validate custom agent file format and structure. Use after creating or editing an agent, before committing agent changes, or when an agent fails to load.

中文简介正在准备中。当前显示原文说明。

claude-world/director-mode-lite802026年8月31日 更新

Generate custom agent from template. Use when creating a new subagent from scratch, or scaffolding an agent file with correct frontmatter.

中文简介正在准备中。当前显示原文说明。

claude-world/director-mode-lite802026年8月31日 更新

agents

免费

List all available agents (core, expert, self-evolving). Use when the user asks what agents are available or runs /agents.

中文简介正在准备中。当前显示原文说明。

claude-world/director-mode-lite802026年8月31日 更新

auto-loop

免费

TDD-based autonomous development loop with checkpoint recovery and observability changelog

中文简介正在准备中。当前显示原文说明。

claude-world/director-mode-lite802026年8月31日 更新

changelog

免费

View and manage the runtime changelog for observability

中文简介正在准备中。当前显示原文说明。

claude-world/director-mode-lite802026年8月31日 更新

Track development session events in a daily markdown changelog, including file changes, test results, and key decisions.

中文简介正在准备中。当前显示原文说明。

claude-world/director-mode-lite802026年8月31日 更新

查看 claude-world 的全部技能

报告此技能的问题