Skip to main content

Hooks Event Reference

UPDATED 2026-07-15 4 min read EDIT ON GITHUB ↗

Claude Code’s hook system supports 29 event types, 5 hook types, per-event matchers, and smart behaviors. Hooks are the only deterministic control points in the agentic harness where execution is guaranteed — a prompt can be ignored, but a hook cannot.

For hook fundamentals and configuration, see the Hooks Guide. This page is the full event reference.

Hook Types

Five hook types are available.

TypeDescriptionExample
commandExecutes a shell script".claude/hooks/moai/handle-session-start.sh"
promptLLM evaluationAn LLM runs the prompt text and returns a result
agentSub-agent verificationAn agent verifies the work and returns a result
httpWebhook endpointDelivers the event via an HTTP POST request
mcp_toolMCP tool executionRemotely invokes an MCP server tool

Full Event Reference (29)

Lifecycle Events

EventDescriptionMatcher
SessionStartSession start
SessionEndSession end
PostSessionRuns after session end (a self-hosted runner lifecycle event, CC 2.1.169+). Fires after the session is fully released, later than SessionEnd. MoAI-ADK does not currently wire this hook. Documented as an available option for self-hosted deployments needing post-session cleanup/telemetry.
StopAgent stop
SubagentStopSub-agent stop
SubagentStartSub-agent start
StopFailureStop failureerrorType
SetupInitial setup

Tool Events

EventDescriptionMatcher
PreToolUseBefore tool executiontoolName
PostToolUseAfter tool executiontoolName
PostToolUseFailureTool execution failuretoolName, errorType
PostToolBatchAfter a parallel tool batch executes (v2.1.89+)

Context Events

EventDescriptionMatcher
PreCompactBefore context compaction
PostCompactAfter context compaction
InstructionsLoadedInstructions finished loading

Input Events

EventDescriptionMatcher
UserPromptSubmitUser prompt submitted
UserPromptExpansionSlash-command prompt expansion (v2.1.90+)
ElicitationElicitation started
ElicitationResultElicitation completed

Security Events

EventDescriptionMatcher
PermissionRequestPermission requesttoolName
PermissionDeniedPermission deniedtoolName

Team Events

EventDescriptionMatcher
TeammateIdleTeammate transitions to idle
TaskCompletedTask marked complete
TaskCreatedTask created

Worktree Events

EventDescriptionMatcher
WorktreeCreateWorktree creation
WorktreeRemoveWorktree removal

Environment Events

EventDescriptionMatcher
ConfigChangeConfiguration changeconfigSource
CwdChangedWorking directory change
FileChangedFile change

UI Events

EventDescriptionMatcher
NotificationUser notification

Smart Behaviors

MoAI-ADK hooks go beyond simple event handling to perform intelligent behaviors.

PermissionDenied Auto-Retry

When permission for a read-only tool (Read, Grep, Glob) is denied, the hook automatically triggers a retry. This mitigates the problem of permission prompts not being displayed for background agents.

StopFailure Error-Type Response

On agent stop failure, differentiated responses are provided by error type. This ensures stability in long-running sessions.

PostCompact Session-Note Restoration

After context compaction, important session notes (progress state, SPEC references) are automatically restored. Context compaction is a trade that saves tokens at the cost of information — this hook protects the essential information from that loss.

SubagentStart Context Injection

When a sub-agent starts, the necessary context (project rules, MX tags, progress state) is automatically injected.

Matchers

Matchers let you filter so a hook runs only under specific conditions. Attaching hooks to every event increases execution cost accordingly, so narrowing scope with matchers is the default.

json
{
  "hooks": {
    "PreToolUse": [{
      "matcher": { "toolName": "Bash" },
      "hooks": [{
        "type": "command",
        "command": "echo 'Bash tool detected'",
        "timeout": 5
      }]
    }]
  }
}

Available Matcher Fields

Matcher fieldApplicable eventsDescription
toolNamePreToolUse, PostToolUse, PostToolUseFailure, PermissionRequest, PermissionDeniedFilter by tool name
errorTypeStopFailure, PostToolUseFailureFilter by error type
configSourceConfigChangeFilter by configuration source

CLAUDE_ENV_FILE

Environment variables can be managed persistently via the CwdChanged and FileChanged hooks.

bash
# .claude/hooks/moai/handle-cwd-changed.sh
# Persist environment variables via CLAUDE_ENV_FILE
echo "MOAI_PROJECT_DIR=$(pwd)" >> "$CLAUDE_ENV_FILE"

This lets you keep environment variables across sessions and automatically reconfigure the environment on directory changes.

Key Hooks Used by MoAI-ADK

EventMoAI handlerRole
SessionStarthandle-session-start.shStatusline initialization, metrics session start
PostToolUsehandle-post-tool.shTask metrics logging
TeammateIdlehandle-teammate-idle.shLSP quality-gate verification
TaskCompletedhandle-task-completed.shSPEC document existence check
WorktreeCreate(none — not registered by MoAI by default)Uses Claude Code’s default worktree behavior (for isolation: worktree agents). If registered, the active-creator contract (directory creation + path stdout echo) is mandatory.
WorktreeRemove(none — not registered by MoAI by default)Uses Claude Code’s default worktree cleanup behavior. If registered, the observer-only contract (no output required) applies.
UserPromptSubmithandle-user-prompt-submit.shPrompt preprocessing (forwards user input)
Stophandle-stop-goal.shgoal engine — evaluates the /goal//moai goal autonomous-continuation condition
Stopsync-phase-quality-gate.shsync-phase quality gate (lint + test + coverage delta)
PostToolUsestatus-transition-ownership.shSPEC frontmatter status-transition audit logging (advisory)
TaskCompletedteam-ac-verify.shteam-mode per-AC PASS evidence-file verification (dormant by default)
Stop / SubagentStop / UserPromptSubmithandle-harness-observe-*.shself-evolving harness observation (Loop 0)

Next Steps