スキル一覧に戻る
laurigates

claude-code-hooks-configuration

by laurigates

Claude Code plugins for development workflows

2🍴 0📅 2026年1月24日
GitHubで見るManusで実行

SKILL.md


model: haiku name: Claude Code Hooks Configuration description: Configure Claude Code lifecycle hooks with proper timeout settings to prevent hook cancellation errors. allowed-tools: Bash, Read, Write, Edit, Grep, Glob, TodoWrite created: 2025-12-27 modified: 2025-12-27 reviewed: 2025-12-27

Claude Code Hooks Configuration

Core Expertise

Configure Claude Code lifecycle hooks (SessionStart, SessionEnd, Stop, PreToolUse, PostToolUse) with proper timeout settings to prevent "Hook cancelled" errors during session management.

Hook Types

HookTriggerDefault Timeout
SessionStartWhen Claude Code session begins60 seconds
SessionEndWhen session ends or /clear runs60 seconds
StopWhen assistant stops responding60 seconds
PreToolUseBefore a tool executes60 seconds
PostToolUseAfter a tool completes60 seconds

Common Issue: Hook Cancelled Error

SessionEnd hook [bash ~/.claude/session-logger.sh] failed: Hook cancelled

Root cause: Hook execution exceeds the 60-second default timeout.

Solutions (in order of preference):

  1. Background subshell - Run slow operations in background, exit immediately
  2. Explicit timeout - Add timeout field to hook configuration

Hook Configuration

Location

Hooks are configured in .claude/settings.json:

  • User-level: ~/.claude/settings.json
  • Project-level: <project>/.claude/settings.json

Structure with Timeout

{
  "hooks": {
    "SessionEnd": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/session-logger.sh",
            "timeout": 120
          }
        ]
      }
    ],
    "SessionStart": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/session-setup.sh",
            "timeout": 180
          }
        ]
      }
    ],
    "Stop": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "~/.claude/stop-hook-git-check.sh",
            "timeout": 30
          }
        ]
      }
    ]
  }
}

Timeout Guidelines

Hook TypeRecommended TimeoutUse Case
SessionStart120-300sTests, linters, dependency checks
SessionEnd60-120sLogging, cleanup, state saving
Stop30-60sGit status checks, quick validations
PreToolUse10-30sQuick validations
PostToolUse30-60sLogging, notifications

Fixing Timeout Issues

The most portable and robust solution is to run slow operations in a background subshell and exit immediately:

#!/bin/bash
# ~/.claude/session-logger.sh
# Exits instantly, work continues in background

(
  # All slow operations go here
  echo "$(date): Session ended" >> ~/.claude/session.log
  curl -s -X POST "https://api.example.com/log" -d "session_end=$(date)"
  # Any other slow work...
) &>/dev/null &

exit 0

Why this works:

  • ( ) creates a subshell for the commands
  • & runs the subshell in background
  • &>/dev/null prevents stdout/stderr from blocking
  • exit 0 returns success immediately

Comparison of approaches:

ApproachPortabilitySpeedNotes
( ) &bash, zsh, shInstantRecommended
disownBash-onlyInstantNot POSIX
nohupPOSIXSlight overheadOverkill for hooks

Alternative: Increase Timeout

If you need synchronous execution, add explicit timeout to settings:

cat ~/.claude/settings.json | jq '.hooks'
# Edit to add "timeout": <seconds> to each hook

Script Optimization Patterns

OptimizationPattern
Background subshell( commands ) &>/dev/null &
Fast test modes--bail=1, -x, --dots
Skip heavy operationsConditional execution
Parallel executionUse & and wait

If you see:

[WARN] - (starship::utils): Executing command "...node" timed out.

This is a separate starship issue. Fix by adding to ~/.config/starship.toml:

command_timeout = 1000  # 1 second (default is 500ms)

For slow node version detection:

[nodejs]
disabled = false
detect_files = ["package.json"]  # Skip .nvmrc to speed up detection

[command]
command_timeout = 2000  # Increase if still timing out

Agentic Optimizations

ContextCommand
View hooks configcat ~/.claude/settings.json | jq '.hooks'
Test hook scripttime bash ~/.claude/session-logger.sh
Find slow operationsbash -x ~/.claude/session-logger.sh 2>&1 | head -50
Check starship configstarship config

Quick Reference

SettingLocationDefault
Hook timeout.claude/settings.json → hook → timeout60s
Starship timeout~/.config/starship.tomlcommand_timeout500ms
Node detection~/.config/starship.toml[nodejs]Auto

Error Handling

ErrorCauseFix
Hook cancelledTimeout exceededAdd "timeout": 120
Hook failedScript errorCheck exit code, add error handling
Command not foundMissing scriptVerify script path and permissions
Permission deniedScript not executablechmod +x ~/.claude/script.sh

Best Practices

  1. Use background subshell - Wrap slow operations in ( ) &>/dev/null & and exit 0
  2. Set explicit timeouts - Add timeout field for hooks requiring synchronous execution
  3. Test hook timing - Use time bash ~/.claude/script.sh to measure execution
  4. Redirect all output - Use &>/dev/null to prevent blocking on stdout/stderr
  5. Apply /hooks menu - Use Claude Code's hook menu to reload settings after changes

スコア

総合スコア

50/100

リポジトリの品質指標に基づく評価

SKILL.md

SKILL.mdファイルが含まれている

+20
LICENSE

ライセンスが設定されている

0/10
説明文

100文字以上の説明がある

0/10
人気

GitHub Stars 100以上

0/15
最近の活動

3ヶ月以内に更新がある

0/10
フォーク

10回以上フォークされている

0/5
Issue管理

オープンIssueが50未満

+5
言語

プログラミング言語が設定されている

+5
タグ

1つ以上のタグが設定されている

0/5

レビュー

💬

レビュー機能は近日公開予定です