Skip to content

原文(日本語)

フックがブロッキングエラーを返した際に、stderr内容がUIに表示される問題を修正しました。

原文(英語)

Fixed hook blocking errors showing stderr content in UI

概要

Claude Code v2.1.41では、カスタムフック(hooks)がブロッキングエラー(終了コード2)を返した際のstderr(標準エラー出力)の表示方法が修正されました。この修正により、エラーメッセージが適切にフォーマットされ、読みやすく表示されるようになりました。

関連する修正との関係

本修正は、以下の2つの関連修正と連携して動作します:

  1. 2.1.41-hook-blocking-stderr-fix.md: フックブロッキングエラー時にstderrが表示されない問題を修正
  2. 本修正: stderrの表示方法を改善

つまり、stderrが確実に表示されるようになった上で、その表示方法も改善されました。

問題の詳細

修正前の動作

フックがブロッキングエラーを返した際、stderr内容が生のまま表示され、読みにくい状態でした。

bash
# 修正前の表示例
 Operation blocked by hook

Error: Bash tool is not allowed in production environment\nUse safe alternatives or request approval from the team lead\n\nDetails:\n  - Environment: production\n  - Command: rm -rf /tmp/test\n  - Policy: destructive-commands-blocked\n

# 改行コード(\n)がそのまま表示され、読みにくい

修正後の動作

stderr内容が適切にフォーマットされ、読みやすく表示されます。

bash
# 修正後の表示例
 Operation blocked by hook

Error: Bash tool is not allowed in production environment
Use safe alternatives or request approval from the team lead

Details:
  - Environment: production
  - Command: rm -rf /tmp/test
  - Policy: destructive-commands-blocked

# 改行が正しく処理され、見やすく表示される

基本的な使い方

フックのエラーメッセージ作成

修正後は、複数行のエラーメッセージを適切に表示できます。

bash
#!/bin/bash
# .claude/hooks/tool-call.sh

if [ "$TOOL_NAME" = "Bash" ]; then
  COMMAND="$2"

  if echo "$COMMAND" | grep -qE "rm -rf"; then
    # 複数行のエラーメッセージ
    cat >&2 <<EOF
⚠️  SECURITY WARNING: Destructive command detected

Command: $COMMAND
Risk Level: HIGH
Policy: Destructive operations require manual approval

Recommendations:
  1. Verify the target directory
  2. Create a backup first
  3. Use trash/recycle bin instead
  4. Request approval from team lead

To proceed, use the /bypass command or contact security team.
EOF
    exit 2
  fi
fi

exit 0

実行時の表示(修正後):

bash
> bash -c "rm -rf /data"

 Operation blocked by hook
⚠️  SECURITY WARNING: Destructive command detected

Command: rm -rf /data
Risk Level: HIGH
Policy: Destructive operations require manual approval

Recommendations:
  1. Verify the target directory
  2. Create a backup first
  3. Use trash/recycle bin instead
  4. Request approval from team lead

To proceed, use the /bypass command or contact security team.

実践例

セキュリティポリシー違反の詳細表示

セキュリティポリシーに違反した際、詳細な情報を表示します。

bash
#!/bin/bash
# .claude/hooks/tool-call.sh

if [ "$TOOL_NAME" = "Write" ]; then
  FILE_PATH="$2"

  if echo "$FILE_PATH" | grep -qE "production\.config|\.env\.prod"; then
    cat >&2 <<EOF
🔒 PRODUCTION FILE MODIFICATION BLOCKED

File: $FILE_PATH
Reason: Protected production configuration

Security Policy:
  - Production configs require PR review
  - Direct editing is not allowed
  - Changes must go through approval process

Required Actions:
  1. Create a feature branch
  2. Make changes in development environment
  3. Test thoroughly
  4. Create Pull Request
  5. Request review from DevOps team

Emergency Contact:
  - DevOps Lead: ops@company.com
  - Security Team: security@company.com

Override Code: Use '/bypass PROD_OVERRIDE_[ticket-number]'
EOF
    exit 2
  fi
fi

exit 0

実行時の表示(修正後):

bash
> "production.configを編集してください"

 Operation blocked by hook
🔒 PRODUCTION FILE MODIFICATION BLOCKED

File: production.config
Reason: Protected production configuration

Security Policy:
  - Production configs require PR review
  - Direct editing is not allowed
  - Changes must go through approval process

Required Actions:
  1. Create a feature branch
  2. Make changes in development environment
  3. Test thoroughly
  4. Create Pull Request
  5. Request review from DevOps team

Emergency Contact:
  - DevOps Lead: ops@company.com
  - Security Team: security@company.com

Override Code: Use '/bypass PROD_OVERRIDE_[ticket-number]'

コンプライアンスチェック

コンプライアンス要件に基づくチェックです。

bash
#!/bin/bash
# .claude/hooks/tool-call.sh

if [ "$TOOL_NAME" = "Bash" ] && echo "$2" | grep -q "git commit"; then
  COMMIT_MSG="$3"

  # コミットメッセージの要件チェック
  if ! echo "$COMMIT_MSG" | grep -qE "^(feat|fix|docs|refactor|test|chore):"; then
    cat >&2 <<EOF
❌ COMMIT MESSAGE POLICY VIOLATION

Your commit message does not follow the required format.

Required Format:
  <type>: <description>

Valid Types:
  - feat: New feature
  - fix: Bug fix
  - docs: Documentation changes
  - refactor: Code refactoring
  - test: Test updates
  - chore: Maintenance tasks

Examples:
  ✓ feat: Add user authentication
  ✓ fix: Resolve memory leak in parser
  ✓ docs: Update API documentation
  ✗ Updated code
  ✗ Fixed bug

Your message: "$COMMIT_MSG"

Please rewrite your commit message following the convention.
For more info: https://company.com/git-guidelines
EOF
    exit 2
  fi
fi

exit 0

実行時の表示(修正後):

bash
> git commit -m "Updated code"

 Operation blocked by hook
 COMMIT MESSAGE POLICY VIOLATION

Your commit message does not follow the required format.

Required Format:
  <type>: <description>

Valid Types:
  - feat: New feature
  - fix: Bug fix
  - docs: Documentation changes
  - refactor: Code refactoring
  - test: Test updates
  - chore: Maintenance tasks

Examples:
 feat: Add user authentication
 fix: Resolve memory leak in parser
 docs: Update API documentation
 Updated code
 Fixed bug

Your message: "Updated code"

Please rewrite your commit message following the convention.
For more info: https://company.com/git-guidelines

リソース制限チェック

システムリソース(ディスク、メモリなど)の制限チェックです。

bash
#!/bin/bash
# .claude/hooks/tool-call.sh

if [ "$TOOL_NAME" = "Bash" ]; then
  # ディスク使用量チェック
  DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//')

  if [ "$DISK_USAGE" -gt 90 ]; then
    cat >&2 <<EOF
⚠️  DISK SPACE CRITICAL WARNING

Current disk usage: ${DISK_USAGE}%
Threshold: 90%
Status: CRITICAL

Impact:
  - System performance degraded
  - Risk of operation failure
  - Database writes may fail

Immediate Actions Required:
  1. Check large files: du -sh /* | sort -hr | head -10
  2. Clean temporary files: rm -rf /tmp/*
  3. Remove old logs: find /var/log -mtime +30 -delete
  4. Clear package cache: apt-get clean

For assistance:
  - IT Support: support@company.com
  - Disk quota increase: ops@company.com

Operation blocked until disk usage < 85%
EOF
    exit 2
  fi
fi

exit 0

この修正の利点

可読性の向上

  • 改行が正しく処理される
  • エラーメッセージが整形される
  • 複数行のメッセージが読みやすい

ユーザー体験の改善

  • エラー内容が理解しやすい
  • アクション項目が明確
  • 技術的詳細が適切に表示

デバッグの容易化

  • エラーの原因が明確
  • 解決策が分かりやすく提示
  • ログ出力も整形される

エラーメッセージのベストプラクティス

構造化されたメッセージ

bash
cat >&2 <<EOF
❌ ERROR_TITLE

Problem: 具体的な問題の説明

Details:
  - 項目1: 詳細
  - 項目2: 詳細

Actions Required:
  1. 手順1
  2. 手順2

Additional Resources:
  - ドキュメント: URL
  - サポート: 連絡先
EOF

視覚的な区別

bash
# 絵文字を使用(修正後は正しく表示される)
echo "❌ Error" >&2
echo "⚠️  Warning" >&2
echo "ℹ️  Info" >&2
echo "✓ Success" >&2

注意点

  • stderr内容は適切にエスケープ処理されます
  • 非常に長いエラーメッセージは切り詰められる場合があります
  • エスケープシーケンス(色コードなど)は保持されます
  • エラーメッセージに機密情報を含めないよう注意してください

関連情報