Source profileQuality 88/100

xiaolai/nlpm/skills/nlpm/writing-hooks/SKILL.md

writing-hooks

How to write Claude Code hooks -- event selection, hook types, matcher patterns, blocking vs advisory, portable paths. Use when creating hooks for quality gates, automation, or policy enforcement.

Source repository stars
104
Declared platforms
1
Static risk flags
2
Last source update
2026-08-04
Source checked
2026-08-04

Decision brief

What it does—and where it fits

Scope: covers Claude Code hooks.json authoring and hook script design. Hook event vocabularies are per-tool and NOT 1:1 mappable (nlpm design decision 4): Claude uses PreToolUse/PostToolUse/Stop/etc.; Codex overlaps with Claude plus PostCompact/SubagentStart; Antigravity/Gemini…

Best for

  • Use when creating hooks for quality gates, automation, or policy enforcement.

Not for

  • Tasks that require unconfirmed production actions or broad system permissions.
  • Environments where the pinned source and install steps cannot be inspected.

Compatibility matrix

Platform support, with evidence labels

PlatformStatusEvidenceWhat to check
CodexNot declaredNo explicit evidencePortability before use
Claude CodeDeclaredSource recordInstall path and trigger
CursorNot declaredNo explicit evidencePortability before use
Gemini CLINot declaredNo explicit evidencePortability before use
Open the compatibility checker

Installation

Inspect first. Install second.

The source command is displayed only when detected. A safe inspection prompt is always available so your agent can explain every action before execution.

Source-detected install commandSource
npx skills add https://github.com/xiaolai/nlpm --skill "skills/nlpm/writing-hooks"
Safe inspection promptEditorial

Inspect the Agent Skill "writing-hooks" from https://github.com/xiaolai/nlpm/blob/660db42b2f2351b5f21e2022ce8785e66218a724/skills/nlpm/writing-hooks/SKILL.md at commit 660db42b2f2351b5f21e2022ce8785e66218a724. List every install step, command, network request, credential, file read/write, external action, and rollback step. Explain whether it fits my task. Do not install or execute anything until I approve.

Workflow

What the source asks the agent to do

  1. 01

    1. Three Hook Types

    Hook script receives JSON on stdin with tool name and parameters. It outputs JSON to stdout.

    Hook script receives JSON on stdin with tool name and parameters. It outputs JSON to stdout.
  2. 02

    Type Selection Flowchart

    Review the “Type Selection Flowchart” section in the pinned source before continuing.

    Review and apply the “Type Selection Flowchart” source section.
  3. 03

    Command Hook Example

    Hook script receives JSON on stdin with tool name and parameters. It outputs JSON to stdout.

    Hook script receives JSON on stdin with tool name and parameters. It outputs JSON to stdout.
  4. 04

    Prompt Hook Example

    Review the “Prompt Hook Example” section in the pinned source before continuing.

    Review and apply the “Prompt Hook Example” source section.
  5. 05

    Agent Hook Example

    Review the “Agent Hook Example” section in the pinned source before continuing.

    Review and apply the “Agent Hook Example” source section.

Permission review

Static risk signals and limitations

Writes files

medium · line 169

The documentation asks the agent to create, modify, or delete local files.

| `"Write\|Edit"` | Write or Edit | Guard file modifications |

Writes files

medium · line 170

The documentation asks the agent to create, modify, or delete local files.

| `"Write"` | Write only | Guard new file creation |

Reads files

low · line 307

The documentation asks the agent to read local files, directories, or repositories.

| LOC limit enforcement | Fail-open | Better to allow a large file than block all writes |

Evidence record

Why each signal appears

EvidenceSourceComputedTestedEditorial
SignalValueEvidence typeMeaning
Quality score88/100ComputedDocumentation, specificity, maintenance, and trust rules
Repository stars104SourceRepository attention, not individual Skill quality
Compatibility1 platformsSourceDeclared in the catalog source record
Usage guideautomated source guideEditorialGenerated or reviewed according to the visible evidence level

Pinned source

Provenance and original SKILL.md

Repository
xiaolai/nlpm
Skill path
skills/nlpm/writing-hooks/SKILL.md
Commit
660db42b2f2351b5f21e2022ce8785e66218a724
License
ISC
Collected
2026-08-04
Default branch
main
View the original SKILL.md

Writing Hooks

Scope: covers Claude Code hooks.json authoring and hook script design. Hook event vocabularies are per-tool and NOT 1:1 mappable (nlpm design decision #4): Claude uses PreToolUse/PostToolUse/Stop/etc.; Codex overlaps with Claude plus PostCompact/SubagentStart; Antigravity/Gemini uses a different Before*/After* Agent/Model/Tool decomposition. The hook-script design principles here (idempotency, fail-open, exit codes, portable paths) transfer across tools; the event names and config locations do not. For the authoritative per-tool event tables see [[nlpm:conventions-claude]] §7, [[nlpm:conventions-codex]] §6, [[nlpm:conventions-antigravity]] §5. For plugin architecture, see [[writing-plugins]]. For rules (which are simpler but static), see [[writing-rules]].

1. Three Hook Types

TypeWhat it doesWhen to useComplexity
commandRuns a shell script, reads JSON from stdinDeterministic checks: file existence, JSON validation, regex matchingMedium
promptInjects text into Claude's contextAdvisory: reminders, context injection, style guidanceLow
agentSpawns a verification agentComplex verification: code quality, semantic analysis, multi-file checksHigh

Type Selection Flowchart

Is the check deterministic (regex, file exists, JSON schema)?
  YES --> command hook (shell script)
  NO  --> Does it need AI judgment?
    YES --> agent hook
    NO  --> prompt hook (context injection)

Command Hook Example

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "command",
            "command": "${CLAUDE_PLUGIN_ROOT}/scripts/check-loc.sh",
            "timeout": 10000
          }
        ]
      }
    ]
  }
}

Hook script receives JSON on stdin with tool name and parameters. It outputs JSON to stdout.

Prompt Hook Example

{
  "hooks": {
    "UserPromptSubmit": [
      {
        "hooks": [
          {
            "type": "prompt",
            "prompt": "Remember: this project uses Result<T, E> for error handling. Never use try/catch directly."
          }
        ]
      }
    ]
  }
}

Agent Hook Example

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Write|Edit",
        "hooks": [
          {
            "type": "agent",
            "agent": "Verify the written file follows project conventions. Check: import order, export style, naming conventions. Report any violations."
          }
        ]
      }
    ]
  }
}

2. Blocking vs Advisory

Blocking (PreToolUse with deny)

The hook prevents the tool from executing. Use for hard quality gates.

Script output for blocking:

{
  "hookSpecificOutput": {
    "permissionDecision": "deny",
    "permissionDecisionReason": "File exceeds 300 LOC limit (current: 342). Extract logic before writing."
  }
}

When to block:

  • Tests must pass before committing
  • File exceeds size limit
  • Required field missing from config
  • Dangerous operation detected (force push, drop table)

Advisory (PostToolUse with message)

The hook adds a message to Claude's context after the action completes. Use for suggestions and reminders.

Script output for advisory:

{
  "hookSpecificOutput": {
    "message": "The file you just edited has no tests. Consider adding tests in __tests__/."
  }
}

When to advise:

  • Suggest related actions (run tests, update docs)
  • Remind about conventions
  • Surface contextual information
  • Warn about potential issues without blocking

Decision Matrix

SituationBlock or Advise?Rationale
Test failure on commitBlockBroken tests should never be committed
File over LOC limitBlockEnforce hard limit
Missing JSDoc on exportAdviseNice to have, not a hard requirement
No tests for new fileAdviseReminder, not a gate
Force push to mainBlockDestructive, irreversible
Large file creation (>500 lines)AdviseMight be intentional (generated code)

Rule of thumb: block only what you would reject in a code review. Advise on everything else.

3. Event Selection Guide

EventWhen it firesCommon use cases
PreToolUseBefore a tool executesBlock dangerous operations, validate inputs, check preconditions
PostToolUseAfter a tool succeedsTrigger follow-up actions, lint changed files, update state
PostToolUseFailureAfter a tool failsError recovery, suggest alternatives, log failures
UserPromptSubmitWhen user sends a messageContext injection, session setup, mode activation
StopWhen Claude stops respondingCleanup, summary generation, state persistence
SessionStartSession beginsEnvironment validation, context loading, config checks

Event Selection by Goal

GoalEventHook type
Prevent bad writesPreToolUse + matcher Write|Editcommand
Lint after editPostToolUse + matcher Write|Editcommand
Inject project contextUserPromptSubmitprompt
Validate environment on startSessionStartcommand
Save session summary on exitStopagent
Recover from failed bash commandsPostToolUseFailure + matcher Bashprompt

4. Matcher Patterns

The matcher field uses regex to match tool names. It applies only to PreToolUse, PostToolUse, and PostToolUseFailure events.

PatternMatchesUse case
"Bash"Bash tool onlyGuard shell commands
"Write|Edit"Write or EditGuard file modifications
"Write"Write onlyGuard new file creation
"Edit"Edit onlyGuard file edits (not creation)
"Read"Read toolTrack what files Claude reads
"mcp__.*"All MCP tool callsGuard external integrations
"mcp__github__.*"GitHub MCP toolsGuard GitHub operations
"Task"Task tool (agent dispatch)Monitor agent dispatching
".*"EverythingUse carefully -- fires on every tool call

Matcher Testing

Before deploying, verify your matcher with test cases:

MatcherShould matchShould NOT match
"Write|Edit"Write, EditBash, Read, WriteFile
"Bash"BashBashScript, mcp__bash
"mcp__github__.*"mcp__github__create_prmcp__slack__send

5. Portable Paths

Always use ${CLAUDE_PLUGIN_ROOT} for script paths in hooks.json. This variable resolves to the plugin's installation directory at runtime.

Correct

{
  "command": "${CLAUDE_PLUGIN_ROOT}/scripts/check-loc.sh"
}

Wrong (breaks on other machines)

{
  "command": "/Users/joker/.claude/plugins/cache/xiaolai/my-plugin/0.1.0/scripts/check-loc.sh"
}

Script Location Convention

my-plugin/
  hooks/
    hooks.json          # hook definitions
  scripts/
    check-loc.sh        # hook scripts
    validate-config.sh
    lint-output.sh

Script Requirements

Every hook script must have:

  1. Shebang line: #!/bin/bash or #!/usr/bin/env node
  2. Executable permission: chmod +x scripts/*.sh
  3. JSON output: scripts must output valid JSON to stdout
  4. Stderr for logging: debug output goes to stderr, not stdout (stdout is parsed as JSON)
#!/bin/bash
# Read input from stdin
input=$(cat)

# Debug logging goes to stderr
echo "Hook triggered: $(date)" >&2

# Business logic
file_path=$(echo "$input" | jq -r '.toolInput.file_path // empty')

if [ -z "$file_path" ]; then
  # Allow if we can't determine the file
  echo '{"hookSpecificOutput":{"decision":"allow"}}'
  exit 0
fi

loc=$(wc -l < "$file_path" 2>/dev/null || echo "0")

if [ "$loc" -gt 300 ]; then
  echo "{\"hookSpecificOutput\":{\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"File has $loc lines, exceeds 300 LOC limit\"}}"
else
  echo '{"hookSpecificOutput":{"decision":"allow"}}'
fi

6. Fail-Open vs Fail-Closed

What happens when your hook script crashes?

Fail-Open (recommended default)

If the script crashes, allow the action. Safer for advisory hooks and non-critical checks.

#!/bin/bash
# Fail-open wrapper
set +e  # Don't exit on error

result=$(your_check_logic 2>/dev/null)
exit_code=$?

if [ $exit_code -ne 0 ]; then
  # Script failed -- allow the action (fail-open)
  echo '{"hookSpecificOutput":{"decision":"allow"}}'
  exit 0
fi

# Normal processing...
echo "$result"

Fail-Closed (security-critical only)

If the script crashes, deny the action. Use only for critical security gates.

#!/bin/bash
# Fail-closed wrapper
set +e

result=$(your_check_logic 2>/dev/null)
exit_code=$?

if [ $exit_code -ne 0 ]; then
  # Script failed -- deny the action (fail-closed)
  echo '{"hookSpecificOutput":{"permissionDecision":"deny","permissionDecisionReason":"Safety check script failed -- blocking action as precaution"}}'
  exit 0
fi

# Normal processing...
echo "$result"

When to Use Each

Hook purposeFail modeRationale
LOC limit enforcementFail-openBetter to allow a large file than block all writes
Style reminderFail-openNon-critical advisory
Prevent force push to mainFail-closedDestructive action, err on side of caution
Secret detectionFail-closedSecurity-critical, must not leak
Test runnerFail-openTest infra failures shouldn't block development

7. Common Mistakes

MistakeWhy it's wrongFix
Blocking on PostToolUseAction already happened -- too late to blockUse PreToolUse for blocking
Wrong event casepretooluse instead of PreToolUse -- case-sensitiveUse exact case: PreToolUse, PostToolUse, etc.
Script not executableHook fails silentlyRun chmod +x scripts/*.sh
Missing shebangScript may run with wrong interpreterAdd #!/bin/bash or #!/usr/bin/env node
Hardcoded pathsBreaks on other machinesUse ${CLAUDE_PLUGIN_ROOT}
stdout pollutionDebug output mixed into JSON responseUse stderr for logging: echo "debug" >&2
No timeoutSlow script blocks Claude indefinitelySet "timeout": 10000 (10 seconds)
Matcher too broad (".*")Fires on every tool call, performance impactNarrow to specific tools
No fail-open wrapperScript crash = broken hook = frustrated userWrap in fail-open try/catch

8. Quality Checklist

Before deploying hooks, verify:

  • Each hook has the correct event type for its purpose
  • Blocking hooks use PreToolUse, not PostToolUse
  • Matchers are tested against expected and unexpected tool names
  • All script paths use ${CLAUDE_PLUGIN_ROOT}
  • All scripts have shebangs and executable permissions
  • All scripts output valid JSON to stdout
  • Debug logging goes to stderr, not stdout
  • Fail-open or fail-closed is explicitly chosen for each hook
  • Timeouts are set (default: 10 seconds)
  • Hooks are tested with: normal input, edge case input, missing input

Alternatives

Compare before choosing