Skip to content

🌐 日本語

Hooks Lifecycle

IMPORTANT

→ Why: Hallucination mitigation (test execution Hooks detect mechanically) → Why: Sycophancy mitigation (compilers and test runners don't follow along) → Why: Instruction Decay mitigation (forced execution independent of context)

What Are Hooks?

Hooks are context-independent processing triggered by Claude Code lifecycle events. They don't consume the LLM's context window.

AttributeValue
Injection TimingNot injected into context
Context ConsumptionNone (except Prompt Hook)
Execution LocationClaude Code runtime (shell / HTTP)
Definition Locationhooks key in settings.json

Why They Exist

If you instruct an LLM to "run eslint every time,"

  1. It consumes the context window
  2. It may be forgotten due to Instruction Decay
  3. It may skip judgment due to Sycophancy ("looks fine")

Hooks execute at the runtime level, avoiding all these problems.

Lifecycle Flow

TIP

Three-layer structure: Session layer (SessionStartSessionEnd) wraps the agent loop layer, and async event layer fires in parallel with the loop.

Event List

Session Lifecycle

EventFire TimingMain Use Case
SessionStartSession start/resumeEnvironment check, log initialization
SessionEndSession endCleanup
UserPromptSubmitUser input submissionInput validation, context addition
StopResponse completionContinuation judgment, quality gate
StopFailureAPI error terminationError log, alert sending

Tool Execution

EventFire TimingMain Use Case
PreToolUseBefore tool executionBlock dangerous commands
PermissionRequestPermission dialog displayAuto-approve/deny permissions
PostToolUseAfter tool successAuto-format, run lint
PostToolUseFailureAfter tool failureError log, retry judgment

Subagent & Tasks

EventFire TimingMain Use Case
SubagentStartSubagent generationContext injection to agents
SubagentStopSubagent completionResult validation, continuation judgment
TaskCreatedTask creationEnforce naming conventions, task validation
TaskCompletedTask completionValidate completion conditions
TeammateIdleBefore teammate waitsQuality gate, resource validation

Configuration & Environment Changes

EventFire TimingMain Use Case
InstructionsLoadedCLAUDE.md / rules loadedAudit log, compliance tracking
ConfigChangeConfiguration file changeSecurity audit, policy enforcement
CwdChangedWorking directory changeEnvironment variable management (direnv, etc.)
FileChangedWatched file changeAutomate file change triggers
NotificationNotification occursDesktop notification

Context Management

EventFire TimingMain Use Case
PreCompactBefore context compressionPre-compression validation
PostCompactAfter context compressionPost-compression validation

Worktree & MCP

EventFire TimingMain Use Case
WorktreeCreateWorktree creationReplace Git operations
WorktreeRemoveWorktree deletionCleanup
ElicitationMCP input requestAutomate user input
ElicitationResultMCP input responseValidate/correct response data

NOTE

For detailed event information (JSON input/output schema, matcher specification, async Hooks, etc.), refer to the official reference: Hooks reference | Hooks guide

Hook Types

Command Hook (most common)

jsonc
{
  "hooks": {
    "PostToolUse": [
      {
        "type": "command",
        "command": "npx prettier --write $CLAUDE_FILE_PATH",
        "matcher": {
          "toolName": "edit_file",
          "pathPattern": "**/*.ts",
        },
        "timeout": 10000,
      },
    ],
  },
}

Prompt Hook (only one affecting context)

jsonc
{
  "hooks": {
    "UserPromptSubmit": [
      {
        "type": "prompt",
        "prompt": "Always git stash before making changes",
      },
    ],
  },
}

HTTP Hook (external service integration)

jsonc
{
  "hooks": {
    "PostToolUse": [
      {
        "type": "http",
        "url": "https://my-service.com/webhook",
        "matcher": { "toolName": "execute_command" },
      },
    ],
  },
}

Agent Hook (multi-turn validation)

Used for validations requiring file reading or command execution. Spawns a subagent to verify conditions with up to 50 turns of tool use.

jsonc
{
  "hooks": {
    "Stop": [
      {
        "type": "agent",
        "prompt": "Verify that all unit tests pass. Run the test suite and check the results.",
        "timeout": 120,
      },
    ],
  },
}

Exit Code Meanings

Exit CodeMeaning
0Allow operation (continue as is. stdout may be added to context)
2Block operation (stderr content fed back to Claude)
OtherContinue operation. stderr logged but not shown to Claude

前へ: The Role of settings.json

次へ: Why Not Show LLMs

Released under the CC BY 4.0 License.