Configurando Hooks no Claude Code (Mac e Windows)


O Claude Code (da Anthropic) possibilita a injeção de hooks customizados para automatizar tarefas em momentos-chave da sua sessão. Seja para garantir a qualidade do código antes de um commit ou para integrar notificações no Slack, os hooks são a ponte entre a IA e o seu sistema operacional.
Embora o nosso exemplo foque em produtividade e Go, é importante conhecer todo o arsenal disponível. Aqui está a lista completa de eventos que você pode monitorar:
SessionStart: Disparado ao iniciar ou retomar uma sessão. Ótimo para injetar contexto do projeto ou configurar variáveis de ambiente.SessionEnd: Executado ao encerrar a CLI. Perfeito para logs finais, limpezas ou exportar métricas.Setup: Acionado apenas durante operações de manutenção ou inicialização (--init).UserPromptSubmit: Disparado assim que você envia um prompt. Útil para validar perguntas ou injetar instruções extras.Notification: Ocorre quando o Claude Code envia um alerta (ex: terminou uma tarefa em background).PermissionRequest: Disparado quando o Claude pede permissão para executar comandos.Stop: Disparado quando o Claude termina de responder ou precisa pausar.PreToolUse: Roda antes de qualquer ferramenta (Bash, Write, etc) ser executada. O melhor lugar para segurança.PostToolUse: Roda após o sucesso de uma ferramenta. Ideal para linting e formatação.PostToolUseFailure: Acionado especificamente quando uma ferramenta falha.SubagentStart / SubagentStop: Monitoram o ciclo de vida de instâncias paralelas do Claude.TaskCompleted: Acionado no encerramento de tarefas complexas compostas por vários passos.Agora, vamos entender o que as regras do nosso arquivo (abaixo) fazem na prática:
SessionStart & SessionEndosascript para dar play na sua playlist de foco no Spotify e cravar o volume em 30%.git diff e git log, enviando um relatório de produtividade para o seu Notion.Stop (O Alerta de Pausa)PreToolUse (A Muralha de Segurança)git push em branches como main ou develop.git commit, ele roda go test e go vet. Se falhar, o commit é bloqueado.PostToolUse (A Faxina)gofmt imediatamente após edições em arquivos Go.gocyclo) e vulnerabilidades (govulncheck) assim que novas dependências são baixadas.Copie e adapte o código abaixo para o seu ~/.claude/settings.json:
{ "language": "portuguese", "hooks": { "SessionStart": [ { "matcher": "", "hooks": [ { "type": "command", "command": "osascript -e 'tell application \"Spotify\" to play track \"spotify:playlist:YOUR_PLAYLIST_ID_HERE\"' 2>/dev/null; osascript -e 'tell application \"Spotify\" to set sound volume to 30' 2>/dev/null", "async": true } ] } ], "SessionEnd": [ { "matcher": "", "hooks": [ { "type": "command", "command": "osascript -e 'tell application \"Spotify\" to pause' 2>/dev/null", "async": true }, { "type": "command", "command": "if [ -n \"$NOTION_TOKEN\" ] && [ -n \"$NOTION_DB_ID\" ]; then branch=$(git branch --show-current 2>/dev/null); msg=$(git log -1 --pretty=format:'%s' 2>/dev/null); files=$(git diff --name-only 2>/dev/null | head -10 | tr '\\n' ', '); added=$(git diff --numstat 2>/dev/null | awk '{s+=$1}END{print s+0}'); payload=$(jq -n --arg title \"Claude Session $(date '+%d/%m %H:%M')\" --arg branch \"$branch\" --arg commit \"$msg\" --arg files \"$files\" --arg added \"+$added linhas\" '{\"parent\":{\"database_id\":\"'\"$NOTION_DB_ID\"'\"},\"properties\":{\"Name\":{\"title\":[{\"text\":{\"content\":$title}}]},\"Branch\":{\"rich_text\":[{\"text\":{\"content\":$branch}}]},\"Ultimo Commit\":{\"rich_text\":[{\"text\":{\"content\":$commit}}]},\"Linhas\":{\"rich_text\":[{\"text\":{\"content\":$added}}]},\"Arquivos\":{\"rich_text\":[{\"text\":{\"content\":$files}}]}}}'); curl -s -X POST 'https://api.notion.com/v1/pages' -H 'Content-Type: application/json' -H \"Authorization: Bearer $NOTION_TOKEN\" -H 'Notion-Version: 2022-06-28' --data \"$payload\" > /dev/null 2>&1; fi", "async": true, "timeout": 15 } ] } ], "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "osascript -e 'display notification \"O Claude parou e está aguardando sua ação!\" with title \"Claude Code\"' && afplay /System/Library/Sounds/Glass.aiff" }, { "type": "command", "command": "curl -s -X POST -H 'Content-type: application/json' --data '{\"text\":\"Claude Code: Terminei uma etapa ou preciso de permissao para continuar!\"}' https://hooks.slack.com/services/YOUR_WEBHOOK_URL_HERE > /dev/null", "async": true }, { "type": "command", "command": "files=$(git diff --name-only 2>/dev/null | wc -l | tr -d ' '); say -v Samantha \"Done. ${files} files modified. I need your action.\" 2>/dev/null", "async": true }, { "type": "command", "command": "osascript -e 'tell application \"Spotify\" to pause' 2>/dev/null", "async": true } ] } ], "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "if": "Bash(git push*)", "command": "cmd=$(cat | jq -r '.tool_input.command'); if echo \"$cmd\" | grep -qE 'push.*(develop|master|main)'; then echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"Push direto para develop/master bloqueado\"}}'; else exit 0; fi" }, { "type": "command", "if": "Bash(go get*)", "command": "echo 'Vulnerabilidades serao verificadas apos instalacao...'", "statusMessage": "Verificando dependencia..." }, { "type": "command", "if": "Bash(git commit*)", "command": "output=$(go test ./... -count=1 -short 2>&1); if echo \"$output\" | grep -q 'FAIL'; then echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"Testes falhando. Corrija antes de commitar.\"}}'; else exit 0; fi", "timeout": 120, "statusMessage": "Validando testes antes do commit..." }, { "type": "command", "if": "Bash(git commit*)", "command": "vet=$(go vet ./... 2>&1); if [ -n \"$vet\" ]; then reason=$(echo \"$vet\" | head -3 | tr '\\n' ' '); echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"go vet encontrou problemas: '\"$reason\"'\"}}'; else exit 0; fi", "timeout": 60, "statusMessage": "Rodando go vet..." }, { "type": "agent", "if": "Bash(git commit*)", "prompt": "Analise o output de 'git diff --cached' (ou 'git diff' se nao houver staged). Verifique APENAS: (1) nil pointer dereference sem check previo, (2) erros ignorados (err retornado mas nao verificado), (3) dados sensiveis em logs (seller_id, tokens, passwords). Se encontrar problemas criticos, responda com exit code 2 e liste os problemas. Se tudo ok, responda com exit code 0.", "timeout": 120, "statusMessage": "Agente revisando codigo..." } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "file=$(cat | jq -r '.tool_input.file_path // .tool_input.filePath'); if [[ \"$file\" == *.go && \"$file\" != *_test.go ]]; then dir=$(dirname \"$file\"); go test \"$dir/...\" -count=1 -short 2>&1 | tail -5; fi", "timeout": 60, "statusMessage": "Rodando testes...", "async": true }, { "type": "command", "command": "file=$(cat | jq -r '.tool_input.file_path // .tool_input.filePath'); if [[ \"$file\" == *.go ]]; then gofmt -w \"$file\" 2>&1; fi", "async": true, "statusMessage": "Formatando Go..." }, { "type": "command", "command": "file=$(cat | jq -r '.tool_input.file_path // .tool_input.filePath'); if [[ \"$file\" == *.go ]]; then if command -v gocyclo &>/dev/null; then high=$(gocyclo -over 15 \"$file\" 2>/dev/null); if [ -n \"$high\" ]; then echo \"Complexidade alta detectada:\"; echo \"$high\"; fi; fi; fi", "async": true, "statusMessage": "Analisando complexidade..." } ] }, { "matcher": "Bash", "hooks": [ { "type": "command", "if": "Bash(go get*)", "command": "govulncheck ./... 2>&1 | tail -10", "timeout": 120, "statusMessage": "Verificando vulnerabilidades...", "async": true }, { "type": "command", "if": "Bash(go test*)", "command": "cmd=$(cat | jq -r '.tool_input.command'); pkg=$(echo \"$cmd\" | grep -oE '\\./[^ ]+' | head -1); if [ -n \"$pkg\" ]; then go test \"$pkg\" -cover -count=1 -short 2>&1 | grep -E 'coverage|FAIL' | tail -3; fi", "timeout": 60, "statusMessage": "Calculando cobertura...", "async": true }, { "type": "command", "if": "Bash(go test*)", "command": "result=$(cat | jq -r '.tool_result.stdout // empty'); if echo \"$result\" | grep -q 'FAIL'; then say -v Samantha 'Warning, tests failed' 2>/dev/null; fi", "async": true } ] } ] } }
Abaixo estão os comandos para substituir no Windows (PowerShell):
powershell -Command "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys([char]179)"powershell -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('O Claude parou!', 'Claude Code')"powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('Finished! Awaiting Action.')"Personalizar seus hooks transforma o Claude Code de um simples chat em um motor de automação robusto. Experimente novos gatilhos e leve sua produtividade para o próximo nível!
Claude Code (by Anthropic) allows you to inject custom hooks to automate tasks at key moments in your session. Whether it's ensuring code quality before a commit or integrating Slack notifications, hooks are the bridge between AI and your operating system.
While our practical example focuses on productivity and Go, it's important to know the full arsenal available. Here is the complete list of events you can monitor:
SessionStart: Fires when starting or resuming a session. Great for injecting project context or setting environment variables.SessionEnd: Executed when closing the CLI. Perfect for final logs, cleanup, or exporting metrics.Setup: Triggered only during maintenance or initialization operations (--init).UserPromptSubmit: Fires immediately after you send a prompt. Useful for validating questions or injecting extra system instructions.Notification: Occurs when Claude Code sends an alert (e.g., finished a background task).PermissionRequest: Fires when Claude requests permission to run commands.Stop: Fires when Claude finishes responding or needs to pause.PreToolUse: Runs before any tool (Bash, Write, etc.) is executed. The best place for security checks.PostToolUse: Runs after a tool successfully completes. Ideal for linting and formatting.PostToolUseFailure: Triggered specifically when a tool call fails.SubagentStart / SubagentStop: Monitor the lifecycle of parallel Claude instances.TaskCompleted: Triggered at the definitive conclusion of a multi-step complex task.PreCompact: Fires before "context compaction" (when history is summarized due to length).ConfigChange: Occurs when the settings.json file is modified.TeammateIdle: Advanced event for coordination in multi-agent workflows.Now, let's understand what the rules in our configuration file (below) actually do:
SessionStart & SessionEndosascript to play your focus playlist on Spotify and sets the volume to 30%.git diff and git log, sending a productivity report to your Notion.Stop (The Pause Alert)PreToolUse (The Security Wall)git push on sensitive branches like main or develop.git commit, it runs go test and go vet. If they fail, the commit is blocked.PostToolUse (The Cleanup)gofmt immediately after edits to Go files.gocyclo) and vulnerabilities (govulncheck) as soon as new dependencies are downloaded.Copy and adapt the following code to your ~/.claude/settings.json:
{ "language": "portuguese", "hooks": { "SessionStart": [ { "matcher": "", "hooks": [ { "type": "command", "command": "osascript -e 'tell application \"Spotify\" to play track \"spotify:playlist:YOUR_PLAYLIST_ID_HERE\"' 2>/dev/null; osascript -e 'tell application \"Spotify\" to set sound volume to 30' 2>/dev/null", "async": true } ] } ], "SessionEnd": [ { "matcher": "", "hooks": [ { "type": "command", "command": "osascript -e 'tell application \"Spotify\" to pause' 2>/dev/null", "async": true }, { "type": "command", "command": "if [ -n \"$NOTION_TOKEN\" ] && [ -n \"$NOTION_DB_ID\" ]; then branch=$(git branch --show-current 2>/dev/null); msg=$(git log -1 --pretty=format:'%s' 2>/dev/null); files=$(git diff --name-only 2>/dev/null | head -10 | tr '\\n' ', '); added=$(git diff --numstat 2>/dev/null | awk '{s+=$1}END{print s+0}'); payload=$(jq -n --arg title \"Claude Session $(date '+%d/%m %H:%M')\" --arg branch \"$branch\" --arg commit \"$msg\" --arg files \"$files\" --arg added \"+$added linhas\" '{\"parent\":{\"database_id\":\"'\"$NOTION_DB_ID\"'\"},\"properties\":{\"Name\":{\"title\":[{\"text\":{\"content\":$title}}]},\"Branch\":{\"rich_text\":[{\"text\":{\"content\":$branch}}]},\"Ultimo Commit\":{\"rich_text\":[{\"text\":{\"content\":$commit}}]},\"Linhas\":{\"rich_text\":[{\"text\":{\"content\":$added}}]},\"Arquivos\":{\"rich_text\":[{\"text\":{\"content\":$files}}]}}}'); curl -s -X POST 'https://api.notion.com/v1/pages' -H 'Content-Type: application/json' -H \"Authorization: Bearer $NOTION_TOKEN\" -H 'Notion-Version: 2022-06-28' --data \"$payload\" > /dev/null 2>&1; fi", "async": true, "timeout": 15 } ] } ], "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "osascript -e 'display notification \"O Claude parou e está aguardando sua ação!\" with title \"Claude Code\"' && afplay /System/Library/Sounds/Glass.aiff" }, { "type": "command", "command": "curl -s -X POST -H 'Content-type: application/json' --data '{\"text\":\"Claude Code: Terminei uma etapa ou preciso de permissao para continuar!\"}' https://hooks.slack.com/services/YOUR_WEBHOOK_URL_HERE > /dev/null", "async": true }, { "type": "command", "command": "files=$(git diff --name-only 2>/dev/null | wc -l | tr -d ' '); say -v Samantha \"Done. ${files} files modified. I need your action.\" 2>/dev/null", "async": true }, { "type": "command", "command": "osascript -e 'tell application \"Spotify\" to pause' 2>/dev/null", "async": true } ] } ], "PreToolUse": [ { "matcher": "Bash", "hooks": [ { "type": "command", "if": "Bash(git push*)", "command": "cmd=$(cat | jq -r '.tool_input.command'); if echo \"$cmd\" | grep -qE 'push.*(develop|master|main)'; then echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"Push direto para develop/master bloqueado\"}}'; else exit 0; fi" }, { "type": "command", "if": "Bash(go get*)", "command": "echo 'Vulnerabilidades serao verificadas apos instalacao...'", "statusMessage": "Verificando dependencia..." }, { "type": "command", "if": "Bash(git commit*)", "command": "output=$(go test ./... -count=1 -short 2>&1); if echo \"$output\" | grep -q 'FAIL'; then echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"Testes falhando. Corrija antes de commitar.\"}}'; else exit 0; fi", "timeout": 120, "statusMessage": "Validando testes antes do commit..." }, { "type": "command", "if": "Bash(git commit*)", "command": "vet=$(go vet ./... 2>&1); if [ -n \"$vet\" ]; then reason=$(echo \"$vet\" | head -3 | tr '\\n' ' '); echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"permissionDecision\":\"deny\",\"permissionDecisionReason\":\"go vet encontrou problemas: '\"$reason\"'\"}}'; else exit 0; fi", "timeout": 60, "statusMessage": "Rodando go vet..." }, { "type": "agent", "if": "Bash(git commit*)", "prompt": "Analise o output de 'git diff --cached' (ou 'git diff' se nao houver staged). Verifique APENAS: (1) nil pointer dereference sem check previo, (2) erros ignorados (err retornado mas nao verificado), (3) dados sensiveis em logs (seller_id, tokens, passwords). Se encontrar problemas criticos, responda com exit code 2 e liste os problemas. Se tudo ok, responda com exit code 0.", "timeout": 120, "statusMessage": "Agente revisando codigo..." } ] } ], "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "file=$(cat | jq -r '.tool_input.file_path // .tool_input.filePath'); if [[ \"$file\" == *.go && \"$file\" != *_test.go ]]; then dir=$(dirname \"$file\"); go test \"$dir/...\" -count=1 -short 2>&1 | tail -5; fi", "timeout": 60, "statusMessage": "Rodando testes...", "async": true }, { "type": "command", "command": "file=$(cat | jq -r '.tool_input.file_path // .tool_input.filePath'); if [[ \"$file\" == *.go ]]; then gofmt -w \"$file\" 2>&1; fi", "async": true, "statusMessage": "Formatando Go..." }, { "type": "command", "command": "file=$(cat | jq -r '.tool_input.file_path // .tool_input.filePath'); if [[ \"$file\" == *.go ]]; then if command -v gocyclo &>/dev/null; then high=$(gocyclo -over 15 \"$file\" 2>/dev/null); if [ -n \"$high\" ]; then echo \"Complexidade alta detectada:\"; echo \"$high\"; fi; fi; fi", "async": true, "statusMessage": "Analisando complexidade..." } ] }, { "matcher": "Bash", "hooks": [ { "type": "command", "if": "Bash(go get*)", "command": "govulncheck ./... 2>&1 | tail -10", "timeout": 120, "statusMessage": "Verificando vulnerabilidades...", "async": true }, { "type": "command", "if": "Bash(go test*)", "command": "cmd=$(cat | jq -r '.tool_input.command'); pkg=$(echo \"$cmd\" | grep -oE '\\./[^ ]+' | head -1); if [ -n \"$pkg\" ]; then go test \"$pkg\" -cover -count=1 -short 2>&1 | grep -E 'coverage|FAIL' | tail -3; fi", "timeout": 60, "statusMessage": "Calculando cobertura...", "async": true }, { "type": "command", "if": "Bash(go test*)", "command": "result=$(cat | jq -r '.tool_result.stdout // empty'); if echo \"$result\" | grep -q 'FAIL'; then say -v Samantha 'Warning, tests failed' 2>/dev/null; fi", "async": true } ] } ] } }
Here are the commands to replace for Windows (PowerShell):
powershell -Command "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys([char]179)"powershell -Command "Add-Type -AssemblyName System.Windows.Forms; [System.Windows.Forms.MessageBox]::Show('Claude has stopped!', 'Claude Code')"powershell -Command "Add-Type -AssemblyName System.Speech; (New-Object System.Speech.Synthesis.SpeechSynthesizer).Speak('Finished! Awaiting Action.')"Customizing your hooks transforms Claude Code from a simple chat into a robust automation engine. Experiment with new triggers and take your productivity to the next level!