🪝 Orbitron Hooks 완벽 가이드
🪝 Complete Guide to Orbitron Hooks
1. Hooks란 무엇인가?
1. What are Hooks?
Orbitron Hooks는 AI 도구 실행 전후에 자동으로 커스텀 스크립트를 실행할 수 있는 강력한 자동화 시스템입니다. Git의 hooks와 유사한 개념으로, AI와 함께 작업하는 워크플로우를 자동화하고 제어할 수 있습니다.
Orbitron Hooks is a powerful automation system that allows you to automatically execute custom scripts before and after AI tool execution. Similar to Git hooks, it enables you to automate and control your AI-assisted workflows.
왜 Hooks가 필요한가요?
"AI에게 파일을 수정하라고 했는데, 포맷이 깨졌어요."
"Bash 명령어를 실행하기 전에 안전 검사를 하고 싶어요."
"도구 실행이 완료되면 팀에게 자동으로 알림을 보내고 싶어요."
이 모든 것을 Hooks로 해결할 수 있습니다!Why do you need Hooks?
"AI modified a file but the formatting broke."
"I want to run safety checks before executing Bash commands."
"I want to automatically notify my team when tool execution completes."
All of these can be solved with Hooks!
2. 핵심 개념
2. Core Concepts
2.1 Hook 이벤트 타입
2.1 Hook Event Types
| 이벤트Event | 실행 시점Execution Timing | 주요 용도Primary Use Case |
|---|---|---|
preToolUse |
도구 실행 전Before tool execution | 검증, 보안 체크, 환경 설정Validation, security checks, environment setup |
postMessageUse |
도구 실행 후After tool execution | 후처리, 알림, 로깅, 테스트Post-processing, notifications, logging, testing |
2.2 Matcher 패턴
2.2 Matcher Patterns
Matcher는 어떤 도구에 hook을 적용할지 결정합니다:
Matcher determines which tools the hook applies to:
*- 모든 도구에 적용Bash- Bash 도구에만 적용Write- Write 도구에만 적용Edit- Edit 도구에만 적용- 기타 모든 도구 이름 사용 가능
*- Apply to all toolsBash- Apply only to Bash toolWrite- Apply only to Write toolEdit- Apply only to Edit tool- Any other tool name can be used
MCP(Model Context Protocol) 도구들은 내부적으로 Bash를 사용하더라도 각각 별도의 도구로 처리됩니다.
따라서 Bash matcher로는 MCP 도구를 매칭할 수 없습니다.
MCP (Model Context Protocol) tools are treated as separate tools even if they internally use Bash.
Therefore, the Bash matcher cannot match MCP tools.
- MCP 도구 포함:
*(모든 도구)를 사용하세요 - Bash만 타겟:
Bash를 사용하세요 (MCP 도구 제외됨) - 예시: 위험한 명령어 차단 hook은
*를 사용하여 MCP 도구도 검증해야 합니다
- Include MCP tools: Use
*(all tools) - Target Bash only: Use
Bash(excludes MCP tools) - Example: Dangerous command blocking hooks should use
*to validate MCP tools as well
2.3 주요 옵션
2.3 Key Options
| 옵션Option | 설명Description | 기본값Default |
|---|---|---|
| Blocking | 종료 코드가 0이 아니면 도구 실행 차단Block tool execution if exit code is non-zero | false |
| Enabled | Hook 활성화 여부Whether hook is enabled | true |
| InterpretOutput | AI가 출력을 해석하여 요약AI interprets and summarizes output | false |
| Args | 명령어에 전달할 인자 (공백 구분)Arguments to pass to command (space-separated) | (없음)(none) |
| UseShell | 셸을 통해 실행 (파이프, 리다이렉션 사용 가능)Execute through shell (allows pipes, redirects) | false |
3. Hook 설정 방법
3. Setting Up Hooks
3.1 TUI에서 Hook 추가
3.1 Adding Hooks in TUI
- Orbitron 실행 후
/hooks명령어로 Hooks 관리 화면 진입 a키를 눌러 "Add Hook" 대화상자 열기- 필드 입력:
- Event:
preToolUse또는postMessageUse - Matcher: 도구 이름 (예:
Bash,*) - Command: 실행할 스크립트 경로
- Args: 명령어 인자 (선택)
- Description: Hook 설명 (선택)
- Event:
- 옵션 체크박스 설정 (
Space로 토글):- ☑ Blocking
- ☑ Enabled
- ☑ InterpretOutput
- ☑ UseShell
Enter로 저장
- Launch Orbitron and use
/hookscommand to enter Hooks management - Press
ato open "Add Hook" dialog - Fill in fields:
- Event:
preToolUseorpostMessageUse - Matcher: Tool name (e.g.,
Bash,*) - Command: Script path to execute
- Args: Command arguments (optional)
- Description: Hook description (optional)
- Event:
- Set option checkboxes (toggle with
Space):- ☑ Blocking
- ☑ Enabled
- ☑ InterpretOutput
- ☑ UseShell
- Save with
Enter
3.2 직접 설정 파일 편집
3.2 Manual Configuration File Editing
Hook 설정 파일을 직접 편집할 수 있습니다. 설정 파일 위치는 Orbitron 실행 위치에 따라 다릅니다:
You can directly edit the hook configuration file. The file location depends on where Orbitron is executed:
- 홈 디렉토리에서 실행:
~/.orbitron/hooks.json - 프로젝트 디렉토리에서 실행:
<project>/.orbitron/hooks.json
- Executed from home directory:
~/.orbitron/hooks.json - Executed from project directory:
<project>/.orbitron/hooks.json
{
"preToolUse": [
{
"matcher": "bash",
"hooks": [
{
"command": "./scripts/check-git-status.sh",
"blocking": true,
"enabled": true,
"interpretOutput": false,
"useShell": false
}
]
}
],
"postMessageUse": [
{
"matcher": "*",
"hooks": [
{
"command": "./scripts/slack-notify.sh",
"blocking": false,
"enabled": true,
"interpretOutput": false,
"useShell": false
}
]
}
]
}
3.3 스크립트 실행 권한 설정
3.3 Setting Script Execution Permissions
모든 hook 스크립트에 실행 권한을 부여해야 합니다:
All hook scripts must have execute permissions:
chmod +x your-hook-script.sh
4. 실전 예시 8가지
4. 8 Practical Examples
아래 코드 블록에서 스크립트를 복사하여 바로 사용할 수 있습니다. 필요에 맞게 수정하여 사용하세요.
You can copy the scripts from the code blocks below and use them directly. Modify them to fit your needs.
preToolUse
Blocking
시나리오: 도구를 실행하기 전에 Git 작업 디렉토리에 uncommitted 변경사항이 있으면 실행을 차단합니다.
preToolUse
Blocking
Scenario: Block tool execution if there are uncommitted changes in Git working directory.
#!/bin/bash
# check-git-status.sh
echo "=== Checking Git Status ==="
echo "Tool: $ORBITRON_TOOL_NAME"
if ! git rev-parse --git-dir > /dev/null 2>&1; then
echo "⚠️ Not a Git repository."
exit 0
fi
if ! git diff-index --quiet HEAD -- 2>/dev/null; then
echo "❌ Uncommitted changes detected!"
git status --short
echo "💡 Please commit your changes before proceeding."
exit 1 # Block tool execution if Blocking=true
fi
echo "✅ Git working directory is clean."
exit 0
| Event | preToolUse |
| Matcher | * (모든 도구)(all tools) |
| Command | ./scripts/check-git-status.sh |
| Blocking | ☑ true |
| Enabled | ☑ true |
- 중요한 작업 전에 코드가 커밋되었는지 확인
- 특정 브랜치에서만 작업하도록 강제 가능
- 스크립트 수정하여 특정 파일 변경사항만 체크 가능
- Ensure code is committed before critical operations
- Can enforce working only on specific branches
- Can be modified to check only specific file changes
preToolUse
Non-blocking
시나리오: Bash 도구 사용 시 실행되는 모든 명령어를 로그 파일에 기록합니다.
preToolUse
Non-blocking
Scenario: Log all commands executed by Bash tool to a log file.
#!/bin/bash
# log-bash.sh
LOG_FILE=".orbitron/bash-commands.log"
mkdir -p "$(dirname "$LOG_FILE")"
if [ "$ORBITRON_TOOL_NAME" = "bash" ]; then
echo "=== Bash Command Execution Log ==="
COMMAND=$(echo "$ORBITRON_TOOL_INPUT" | grep -o '"command":"[^"]*"' | cut -d'"' -f4)
if [ -n "$COMMAND" ]; then
{
echo "Time: $(date '+%Y-%m-%d %H:%M:%S')"
echo "Session: $ORBITRON_SESSION_ID"
echo "Command: $COMMAND"
echo ""
} >> "$LOG_FILE"
echo "✅ Log saved: $LOG_FILE"
fi
fi
exit 0 # Always success (Non-blocking)
| Event | preToolUse |
| Matcher | bash |
| Command | ./scripts/log-bash.sh |
| Blocking | ☐ false |
preToolUse
Blocking
시나리오: rm -rf /, mkfs 등 위험한 명령어 패턴이 감지되면 실행을 차단합니다.
preToolUse
Blocking
Scenario: Block execution if dangerous command patterns like rm -rf /, mkfs are detected.
#!/bin/bash
# validate-input.sh
echo "=== Tool Input Validation ==="
if [ "$ORBITRON_TOOL_NAME" != "bash" ]; then
exit 0
fi
COMMAND=$(echo "$ORBITRON_TOOL_INPUT" | grep -o '"command":"[^"]*"' | sed 's/"command":"\([^"]*\)"/\1/')
DANGEROUS_PATTERNS=(
"rm -rf /"
"mkfs"
"dd if="
"> /dev/sda"
)
for pattern in "${DANGEROUS_PATTERNS[@]}"; do
if echo "$COMMAND" | grep -q "$pattern"; then
echo "❌ Dangerous command pattern detected!"
echo " Pattern: $pattern"
exit 1 # Block tool execution
fi
done
echo "✅ Validation passed"
exit 0
| Event | preToolUse |
| Matcher | bash |
| Command | ./scripts/validate-input.sh |
| Blocking | ☑ true |
preToolUse
시나리오: ORBITRON_TOOL_INPUT 환경 변수에서 JSON 데이터를 파싱하여 도구 파라미터를 검증합니다.
preToolUse
Scenario: Parse JSON data from ORBITRON_TOOL_INPUT environment variable to validate tool parameters.
모든 hook에서 사용 가능한 환경 변수:
Environment variables available in all hooks:
ORBITRON_TOOL_NAME: 실행될 도구 이름Name of tool to executeORBITRON_TOOL_INPUT: 도구 입력 파라미터 (JSON)Tool input parameters (JSON)ORBITRON_SESSION_ID: 현재 세션 IDCurrent session IDORBITRON_MESSAGE_ID: 현재 메시지 IDCurrent message IDORBITRON_TOOL_RESULT: 도구 실행 결과 (postMessageUse만)Tool execution result (postMessageUse only)
#!/bin/bash
# Environment variable usage example
echo "Tool name: $ORBITRON_TOOL_NAME"
echo "Session ID: $ORBITRON_SESSION_ID"
# JSON parsing example (for bash tool)
if [ "$ORBITRON_TOOL_NAME" = "bash" ]; then
COMMAND=$(echo "$ORBITRON_TOOL_INPUT" | grep -o '"command":"[^"]*"' | cut -d'"' -f4)
echo "Command to execute: $COMMAND"
fi
# For write tool
if [ "$ORBITRON_TOOL_NAME" = "write" ]; then
FILE_PATH=$(echo "$ORBITRON_TOOL_INPUT" | grep -o '"file_path":"[^"]*"' | cut -d'"' -f4)
echo "File to write: $FILE_PATH"
fi
postMessageUse
InterpretOutput
시나리오: 도구 실행 후 자동으로 테스트를 실행하고, JSON 형식의 결과를 AI가 분석하여 요약합니다.
postMessageUse
InterpretOutput
Scenario: After tool execution, automatically run tests and have AI analyze and summarize JSON-formatted results.
#!/bin/bash
# run-tests.sh
if [ -f "go.mod" ]; then
echo "Running Go tests..."
TEST_OUTPUT=$(go test ./... 2>&1)
TEST_EXIT_CODE=$?
# Output in JSON format for easy AI parsing
cat <<EOF
{
"test_framework": "go test",
"exit_code": $TEST_EXIT_CODE,
"status": "$([ $TEST_EXIT_CODE -eq 0 ] && echo "PASS" || echo "FAIL")",
"timestamp": "$(date -u +"%Y-%m-%dT%H:%M:%SZ")",
"summary": {
"total_packages": $(echo "$TEST_OUTPUT" | grep -c "^ok\|^FAIL" || echo 0),
"passed": $(echo "$TEST_OUTPUT" | grep -c "^ok" || echo 0),
"failed": $(echo "$TEST_OUTPUT" | grep -c "^FAIL" || echo 0)
}
}
EOF
fi
exit 0
| Event | postMessageUse |
| Matcher | * |
| Command | ./scripts/run-tests.sh |
| InterpretOutput | ☑ true |
AI가 더 정확하게 분석할 수 있도록 JSON 형식으로 출력하세요. AI는 출력 내용을 읽고 요약하여 사용자에게 친절한 형태로 전달합니다.
Output in JSON format for more accurate AI analysis. AI reads the output and summarizes it in a user-friendly format.
preToolUse
시나리오: 스크립트에 인자를 전달하여 재사용 가능한 범용 hook을 만듭니다.
preToolUse
Scenario: Create reusable generic hooks by passing arguments to scripts.
#!/bin/bash
# env-check.sh [required|optional]
ENV_VAR_NAME=$1
REQUIREMENT=${2:-"optional"}
if [ -z "$ENV_VAR_NAME" ]; then
echo "❌ Usage: env-check.sh [required|optional]"
exit 1
fi
ENV_VAR_VALUE=$(printenv "$ENV_VAR_NAME")
if [ -z "$ENV_VAR_VALUE" ]; then
if [ "$REQUIREMENT" = "required" ]; then
echo "❌ Required environment variable '$ENV_VAR_NAME' is not set!"
exit 1 # Blocking
else
echo "⚠️ Optional environment variable '$ENV_VAR_NAME' is not set."
fi
else
echo "✅ $ENV_VAR_NAME = ${ENV_VAR_VALUE:0:4}****"
fi
exit 0
| Event | preToolUse |
| Matcher | * |
| Command | ./scripts/env-check.sh |
| Args | API_KEY required |
| Blocking | ☑ true |
Args: API_KEY required- API_KEY 필수 확인Args: DEBUG_MODE optional- DEBUG_MODE 선택 확인Args: DATABASE_URL required- DATABASE_URL 필수 확인
Args: API_KEY required- Check API_KEY is requiredArgs: DEBUG_MODE optional- Check DEBUG_MODE is optionalArgs: DATABASE_URL required- Check DATABASE_URL is required
preToolUse
시나리오: 파이프(|), 리다이렉션(>), 상대 경로 등을 사용하는 복잡한 셸 명령어를 실행합니다.
preToolUse
Scenario: Execute complex shell commands using pipes (|), redirections (>), relative paths, etc.
#!/bin/bash
# format-code.sh - Auto-format based on file extension
FILE_PATH=$(echo "$ORBITRON_TOOL_INPUT" | grep -o '"file_path":"[^"]*"' | cut -d'"' -f4)
case "$FILE_PATH" in
*.go)
# Using pipe: save gofmt results to log file
gofmt -w "$FILE_PATH" 2>&1 | tee /tmp/format.log
echo "✅ Go code formatting complete"
;;
*.js|*.ts)
# Using pipe chain
prettier --write "$FILE_PATH" 2>&1 | grep -v "Checking" | tee -a /tmp/format.log
echo "✅ JavaScript/TypeScript formatting complete"
;;
*.py)
black "$FILE_PATH" 2>&1 | grep -E "(reformatted|unchanged)" | tee -a /tmp/format.log
echo "✅ Python formatting complete"
;;
esac
# Output log summary (using pipe)
tail -5 /tmp/format.log | sed 's/^/ /'
exit 0
| Event | preToolUse |
| Matcher | write |
| Command | ./scripts/format-code.sh |
| UseShell | ☑ true |
다음 셸 기능을 사용하려면 UseShell=true가 필요합니다:
UseShell=true is required for the following shell features:
- 파이프 (
|), 리다이렉션 (>,>>) - 셸 변수 확장 (
$VAR) 및 글로브 패턴 (*.txt) - 명령어 체인 (
&&,||,;)
- Pipes (
|), Redirections (>,>>) - Shell variable expansion (
$VAR) and glob patterns (*.txt) - Command chains (
&&,||,;)
참고: 상대 경로 스크립트(./script.sh)는 모든 모드에서 작동합니다!
Note: Relative path scripts (./script.sh) work in all modes!
postMessageUse
Non-blocking
시나리오: 도구 실행 완료 후 Slack 웹훅을 통해 팀에게 알림을 전송합니다.
postMessageUse
Non-blocking
Scenario: Send team notifications via Slack webhook after tool execution completes.
#!/bin/bash
# slack-notify.sh
SLACK_WEBHOOK_URL="${SLACK_WEBHOOK_URL:-}"
if [ -z "$SLACK_WEBHOOK_URL" ]; then
echo "⚠️ SLACK_WEBHOOK_URL environment variable is not set."
exit 0
fi
TOOL_NAME="$ORBITRON_TOOL_NAME"
RESULT_SUMMARY=$(echo "$ORBITRON_TOOL_RESULT" | head -c 100)
MESSAGE=$(cat <<EOF
{
"text": "Orbitron Tool Execution Complete",
"blocks": [
{
"type": "header",
"text": {"type": "plain_text", "text": "🤖 Orbitron Tool Execution Complete"}
},
{
"type": "section",
"fields": [
{"type": "mrkdwn", "text": "*Tool:*\n\`$TOOL_NAME\`"},
{"type": "mrkdwn", "text": "*Time:*\n$(date '+%H:%M:%S')"}
]
}
]
}
EOF
)
HTTP_STATUS=$(curl -s -o /dev/null -w "%{http_code}" \
-X POST -H "Content-Type: application/json" \
-d "$MESSAGE" "$SLACK_WEBHOOK_URL")
if [ "$HTTP_STATUS" = "200" ]; then
echo "✅ Slack notification sent successfully"
else
echo "❌ Slack notification failed (HTTP $HTTP_STATUS)"
fi
exit 0
export SLACK_WEBHOOK_URL='https://hooks.slack.com/services/YOUR/WEBHOOK/URL'
| Event | postMessageUse |
| Matcher | * |
| Command | ./scripts/slack-notify.sh |
| Blocking | ☐ false |
5. 환경 변수 활용
5. Using Environment Variables
모든 hook 스크립트는 Orbitron이 자동으로 설정하는 환경 변수를 사용할 수 있습니다. 이를 통해 실행 컨텍스트를 파악하고 동적으로 동작을 변경할 수 있습니다.
All hook scripts can use environment variables automatically set by Orbitron. This allows you to understand execution context and dynamically change behavior.
5.1 환경 변수 레퍼런스
5.1 Environment Variables Reference
| 환경 변수Environment Variable | 설명Description | 예시Example |
|---|---|---|
ORBITRON_TOOL_NAME |
실행될 도구 이름Name of tool to execute | Bash, Write, Read |
ORBITRON_TOOL_INPUT |
도구 입력 파라미터 (JSON)Tool input parameters (JSON) | {"command": "ls -la"} |
ORBITRON_SESSION_ID |
현재 세션 IDCurrent session ID | abc123... |
ORBITRON_MESSAGE_ID |
현재 메시지 IDCurrent message ID | msg456... |
ORBITRON_TOOL_RESULT |
도구 실행 결과 (postMessageUse만)Tool execution result (postMessageUse only) | 도구 출력 내용Tool output content |
5.2 환경 변수 사용 예시
5.2 Environment Variable Usage Examples
도구 이름으로 분기 처리
Branching by Tool Name
#!/bin/bash
case "$ORBITRON_TOOL_NAME" in
"bash")
echo "Bash command will be executed."
;;
"write"|"edit")
echo "File write/edit will be executed."
;;
*)
echo "Other tool: $ORBITRON_TOOL_NAME"
;;
esac
JSON 파라미터 파싱
Parsing JSON Parameters
#!/bin/bash
# Extract command from bash tool
if [ "$ORBITRON_TOOL_NAME" = "bash" ]; then
COMMAND=$(echo "$ORBITRON_TOOL_INPUT" | grep -o '"command":"[^"]*"' | cut -d'"' -f4)
echo "Command to execute: $COMMAND"
fi
# Extract file_path from write tool
if [ "$ORBITRON_TOOL_NAME" = "write" ]; then
FILE_PATH=$(echo "$ORBITRON_TOOL_INPUT" | grep -o '"file_path":"[^"]*"' | cut -d'"' -f4)
echo "File to write: $FILE_PATH"
fi
# Parsing with jq (more accurate)
if command -v jq &> /dev/null; then
COMMAND=$(echo "$ORBITRON_TOOL_INPUT" | jq -r '.command // empty')
FILE_PATH=$(echo "$ORBITRON_TOOL_INPUT" | jq -r '.file_path // empty')
fi
세션/메시지 ID로 로깅
Logging with Session/Message IDs
#!/bin/bash
LOG_FILE=".orbitron/hook.log"
{
echo "==================================="
echo "Timestamp: $(date -u +"%Y-%m-%dT%H:%M:%SZ")"
echo "Session: $ORBITRON_SESSION_ID"
echo "Message: $ORBITRON_MESSAGE_ID"
echo "Tool: $ORBITRON_TOOL_NAME"
echo "==================================="
} >> "$LOG_FILE"
6. Hook 옵션 상세 가이드
6. Detailed Hook Options Guide
6.1 Blocking
6.1 Blocking
Blocking=true로 설정하면, hook 스크립트가 0이 아닌 종료 코드로 종료했을 때
도구 실행을 차단합니다. preToolUse 이벤트에서만 의미가 있습니다.
When set to Blocking=true, tool execution is blocked if the hook script
exits with a non-zero exit code. Only meaningful for preToolUse events.
Hook이 도구 실행을 차단하면 다음과 같이 동작합니다:
When a hook blocks tool execution, the following happens:
- 도구 실행 중단: 해당 도구와 이후 도구들이 모두 실행되지 않음
- 에러 메시지 표시: 사용자에게 차단 메시지가 표시됨
- 대화 종료: AI가 도구 결과를 받지 못하므로 응답을 계속하지 않음
- Tool execution stopped: The tool and all subsequent tools are not executed
- Error message shown: User sees the blocking message
- Conversation ends: AI doesn't receive tool results, so it doesn't continue responding
사용자에게 표시되는 메시지:
Message shown to user:
❌ PreToolUse hook blocked execution: {hook 출력 내용}
또는
❌ PreToolUse hook blocked tool execution
❌ PreToolUse hook blocked execution: {hook output}
or
❌ PreToolUse hook blocked tool execution
Hook 스크립트에서 echo로 출력한 메시지가 사용자에게 그대로 전달되므로,
왜 차단되었는지, 어떻게 해결해야 하는지 명확히 설명하세요!
Messages output via echo in your hook script are displayed to the user,
so clearly explain why it was blocked and how to fix it!
💡 InterpretOutput와 함께 사용하면:
Hook이 차단되더라도 InterpretOutput=true 옵션이 설정되어 있으면,
AI가 Hook 출력을 해석하여 더 자연스럽고 친절한 메시지로 변환합니다.
이렇게 하면 사용자에게 더 명확한 안내를 제공할 수 있습니다.
💡 When used with InterpretOutput:
Even if the hook blocks execution, when InterpretOutput=true is set,
AI interprets the hook output and converts it into a more natural and friendly message.
This provides clearer guidance to the user.
예시: InterpretOutput 없이 차단
Example: Blocking without InterpretOutput
❌ PreToolUse hook blocked execution: ❌ Uncommitted 변경사항이 있습니다!
변경된 파일 목록:
M internal/config/config.go
M internal/llm/agent/agent.go
💡 변경사항을 커밋한 후 다시 시도하세요.
❌ PreToolUse hook blocked execution: ❌ Uncommitted changes detected!
Changed files:
M internal/config/config.go
M internal/llm/agent/agent.go
💡 Please commit your changes before proceeding.
예시: InterpretOutput로 차단
Example: Blocking with InterpretOutput
커밋되지 않은 변경사항이 있습니다.
다음 파일들이 수정되었습니다:
- internal/config/config.go
- internal/llm/agent/agent.go
변경사항을 커밋한 후 다시 시도해주세요.
There are uncommitted changes.
The following files have been modified:
- internal/config/config.go
- internal/llm/agent/agent.go
Please commit your changes before trying again.
- 보안: 위험한 명령어 차단
- 환경 검증: 필수 환경 변수나 파일 존재 확인
- 정책 강제: Git 커밋 필수, 코드 스타일 검사 등
- 전제 조건: 특정 서비스 실행 여부 확인
- Security: Block dangerous commands
- Environment validation: Check required environment variables or files
- Policy enforcement: Require Git commits, code style checks, etc.
- Prerequisites: Check if specific services are running
6.2 InterpretOutput
6.2 InterpretOutput
InterpretOutput=true로 설정하면, hook 출력을 AI가 읽고 해석하여
사용자에게 요약된 형태로 제공합니다. 복잡한 로그나 테스트 결과를 분석할 때 유용합니다.
When set to InterpretOutput=true, AI reads and interprets hook output
and provides a summarized version to the user. Useful for analyzing complex logs or test results.
- JSON 형식으로 출력하면 AI가 더 정확하게 파싱합니다
- 중요한 정보를
"status","summary","errors"등의 키로 구조화 - 긴 출력은 요약 섹션을 먼저 출력하고 상세 내용은 나중에 출력
- 에러 메시지는 명확하고 실행 가능한 형태로 작성
- Output in JSON format for more accurate AI parsing
- Structure important information with keys like
"status","summary","errors" - For long output, show summary first, then detailed content
- Write error messages in clear, actionable format
6.3 Args
6.3 Args
Args 필드에 공백으로 구분된 인자를 입력하면,
스크립트 실행 시 $1, $2 등으로 접근할 수 있습니다.
Enter space-separated arguments in the Args field,
and they can be accessed as $1, $2, etc. during script execution.
# Hook configuration
Command: ./check-env.sh
Args: API_KEY required
# In check-env.sh script
ENV_NAME=$1 # "API_KEY"
REQUIREMENT=$2 # "required"
- 여러 상황에 재사용 가능한 범용 스크립트 작성
- 환경별로 다른 파라미터 전달 (dev, staging, prod)
- 옵션 플래그 전달 (
--verbose,--strict) - 동일한 스크립트로 다양한 검증 수행
- Write reusable generic scripts for multiple scenarios
- Pass different parameters per environment (dev, staging, prod)
- Pass option flags (
--verbose,--strict) - Perform various validations with the same script
6.4 UseShell
6.4 UseShell
UseShell=true로 설정하면 sh -c "command args..." 형태로 실행되어
셸 기능(파이프, 리다이렉션 등)을 사용할 수 있습니다.
When set to UseShell=true, executes as sh -c "command args..."
enabling shell features (pipes, redirections, etc.).
- UseShell=true → 셸 실행 (
sh -c) - UseShell=false + Args 있음 → 직접 실행 (
exec.Command) - UseShell=false + Args 없음 → 셸 실행 (하위 호환성)
- UseShell=true → Shell execution (
sh -c) - UseShell=false + Args present → Direct execution (
exec.Command) - UseShell=false + No Args → Shell execution (backward compatibility)
중요: 모든 hook은 프로젝트 작업 디렉토리(cmd.Dir)에서 실행되므로,
상대 경로는 모든 모드에서 작동합니다!
Important: All hooks execute in the project working directory (cmd.Dir),
so relative paths work in all modes!
| 기능Feature | Args 없음No Args | Args 있음With Args | UseShell=true |
|---|---|---|---|
| 실행 방식Execution Mode | sh -c |
exec |
sh -c |
| 상대 경로 스크립트Relative path scripts | ✅ | ✅ | ✅ |
파이프 (|)Pipes (|) |
✅ | ❌ | ✅ |
리다이렉션 (>)Redirections (>) |
✅ | ❌ | ✅ |
글로브 패턴 (*.txt)Glob patterns (*.txt) |
✅ | ❌ | ✅ |
셸 변수 확장 ($VAR)Shell variable expansion ($VAR) |
✅ | ❌ | ✅ |
명령어 체인 (&&)Command chains (&&) |
✅ | ❌ | ✅ |
| 직접 실행 (더 빠름)Direct execution (faster) | ❌ | ✅ | ❌ |
UseShell 사용 예시
UseShell Usage Examples
# ✅ Basic usage - No Args (shell execution for backward compatibility)
Command: ./scripts/check-git-status.sh
UseShell: false # Automatically uses sh -c
# ✅ Relative path with Args (direct execution mode)
Command: ./scripts/env-check.sh
Args: API_KEY required
UseShell: false # Relative path works based on working directory ✅
# ✅ Using pipe with Args - UseShell required!
Command: ./scripts/env-check.sh
Args: API_KEY required | grep "API"
UseShell: true # UseShell is required to include pipes in Args
# ✅ Using pipes/redirections - UseShell required
Command: find . -name "*.log" | xargs rm
UseShell: true
# ✅ Using glob patterns - UseShell required
Command: ls *.go && go fmt
UseShell: true
# ✅ Direct execution (fastest) - Using Args
Command: ./scripts/env-check.sh
Args: API_KEY required
UseShell: false # Direct execution is faster when shell features are unnecessary
- 상대 경로는 항상 작동: 작업 디렉토리(
cmd.Dir) 기준으로 실행됨 - UseShell=true 필요한 경우: 파이프, 리다이렉션, 글로브, 변수 확장 등 셸 기능 사용 시
- UseShell=false + Args: 단순 스크립트 + 인자 → 가장 빠른 실행
- UseShell=false + Args 없음: 하위 호환성으로 자동 셸 실행
- Relative paths always work: Executed relative to working directory (
cmd.Dir) - UseShell=true needed for: Shell features like pipes, redirects, globs, variable expansion
- UseShell=false + Args: Simple script + args → fastest execution
- UseShell=false + No Args: Automatic shell execution for backward compatibility
7. 실무 워크플로우
7. Real-World Workflows
7.1 완전 자동화된 CI/CD 워크플로우
7.1 Fully Automated CI/CD Workflow
AI가 코드를 수정할 때 자동으로 검증, 테스트, 포맷팅을 수행하는 워크플로우:
Workflow that automatically validates, tests, and formats code when AI modifies it:
| 단계Step | HookHook | 이벤트Event | Blocking |
|---|---|---|---|
| 1 | Git 상태 확인Check Git status | preToolUse | ✅ |
| 2 | 환경 변수 검증Validate environment variables | preToolUse | ✅ |
| 3 | 위험 명령어 차단Block dangerous commands | preToolUse | ✅ |
| 4 | (도구 실행)(Tool execution) | - | - |
| 5 | 코드 포맷팅Code formatting | postMessageUse | ❌ |
| 6 | 테스트 실행 + AI 분석Run tests + AI analysis | postMessageUse | ❌ |
| 7 | Slack 알림Slack notification | postMessageUse | ❌ |
7.2 보안 중심 워크플로우
7.2 Security-Focused Workflow
모든 Bash 명령어를 검증하고 로깅하는 보안 강화 워크플로우:
Security-enhanced workflow that validates and logs all Bash commands:
- preToolUse - Bash 명령어 로깅 (Non-blocking)
- preToolUse - 위험 패턴 검증 (Blocking)
- preToolUse - 민감 파일 접근 검사 (Blocking)
- postMessageUse - 실행 결과 감사 로그 저장
- postMessageUse - 보안 팀에 알림 (특정 조건)
- preToolUse - Log Bash commands (Non-blocking)
- preToolUse - Validate dangerous patterns (Blocking)
- preToolUse - Check sensitive file access (Blocking)
- postMessageUse - Save execution result audit log
- postMessageUse - Notify security team (under certain conditions)
7.3 품질 보증 워크플로우
7.3 Quality Assurance Workflow
코드 품질을 자동으로 검증하고 개선하는 워크플로우:
Workflow that automatically validates and improves code quality:
- preToolUse (Write/Edit) - 린팅 및 정적 분석
- postMessageUse (Write/Edit) - 코드 포맷팅 자동 적용
- postMessageUse (Write/Edit) - 단위 테스트 실행 + AI 분석
- postMessageUse (Write/Edit) - 커버리지 리포트 생성
- postMessageUse - 코드 리뷰 체크리스트 생성 (AI 해석)
- preToolUse (Write/Edit) - Linting and static analysis
- postMessageUse (Write/Edit) - Auto-apply code formatting
- postMessageUse (Write/Edit) - Run unit tests + AI analysis
- postMessageUse (Write/Edit) - Generate coverage report
- postMessageUse - Generate code review checklist (AI interpretation)
8. 문제 해결
8. Troubleshooting
8.1 Hook이 실행되지 않아요
8.1 Hook Not Executing
- ✅ Hook이
Enabled=true로 설정되어 있나요? - ✅ Matcher가 실행하려는 도구 이름과 일치하나요?
- ✅ MCP 도구를 검증하려면
*를 사용하고 있나요? (Bash만으로는 부족) - ✅ 스크립트 파일에 실행 권한이 있나요? (
chmod +x) - ✅ 스크립트 경로가 올바른가요? (절대 경로 또는 상대 경로)
- ✅ Shebang(
#!/bin/bash)이 스크립트 첫 줄에 있나요?
- ✅ Is hook set to
Enabled=true? - ✅ Does Matcher match the tool name you're trying to execute?
- ✅ Are you using
*to validate MCP tools? (Bashalone is not enough) - ✅ Does script file have execute permissions? (
chmod +x) - ✅ Is script path correct? (absolute or relative path)
- ✅ Is shebang (
#!/bin/bash) on first line of script?
8.2 Hook이 도구 실행을 차단하지 않아요
8.2 Hook Not Blocking Tool Execution
Blocking=true로 설정되어 있나요?- 스크립트가
exit 1(또는 0이 아닌 값)로 종료하나요? - preToolUse 이벤트인가요? (postMessageUse는 차단 불가)
- 스크립트 내부에서 에러가 발생했지만
exit 0으로 끝나지 않았나요?
- Is
Blocking=trueset? - Does script exit with
exit 1(or non-zero value)? - Is it a preToolUse event? (postMessageUse cannot block)
- Did an error occur in script but it still ended with
exit 0?
8.3 환경 변수가 비어 있어요
8.3 Environment Variables Are Empty
# Debugging script
#!/bin/bash
echo "=== Environment Variable Debugging ==="
echo "TOOL_NAME: ${ORBITRON_TOOL_NAME:-'(empty)'}"
echo "TOOL_INPUT: ${ORBITRON_TOOL_INPUT:-'(empty)'}"
echo "SESSION_ID: ${ORBITRON_SESSION_ID:-'(empty)'}"
echo "MESSAGE_ID: ${ORBITRON_MESSAGE_ID:-'(empty)'}"
echo "TOOL_RESULT: ${ORBITRON_TOOL_RESULT:-'(empty)'}"
exit 0
참고: ORBITRON_TOOL_RESULT는 postMessageUse 이벤트에서만 사용할 수 있습니다.
Note: ORBITRON_TOOL_RESULT is only available in postMessageUse events.
8.4 UseShell을 사용했는데 파이프가 작동하지 않아요
8.4 Pipes Not Working Even with UseShell
UseShell=true로 설정되어 있나요?- Command 필드에 전체 명령어 (파이프 포함)가 들어가 있나요?
- Args 필드는 비워두었나요? (UseShell=true일 때는 Args를 Command에 포함)
- Is
UseShell=trueset? - Does Command field contain full command (including pipes)?
- Is Args field empty? (When UseShell=true, include Args in Command)
# ✅ Correct usage
Command: find . -name "*.log" | xargs rm
Args: (empty)
UseShell: true
# ❌ Incorrect usage
Command: find
Args: . -name "*.log" | xargs rm
UseShell: true
8.5 Hook 테스트 방법
8.5 How to Test Hooks
Orbitron TUI에서 Hook을 안전하게 테스트할 수 있습니다:
You can safely test hooks in Orbitron TUI:
/hooks명령어로 Hooks 관리 화면 진입- 방향키로 테스트할 Hook 선택
t키 입력 (Test)- 테스트 결과 화면에서 출력, 종료 코드, 실행 시간 확인
- Enter Hooks management with
/hookscommand - Select hook to test with arrow keys
- Press
tkey (Test) - Check output, exit code, execution time on test result screen
테스트 모드에서는 샘플 데이터로 Hook을 실행하므로 실제 도구는 실행되지 않습니다.
In test mode, hooks run with sample data so actual tools are not executed.
8.6 MCP 도구에 Hook이 적용되지 않아요
8.6 Hooks Not Applied to MCP Tools
MCP(Model Context Protocol) 도구들은 내부적으로 Bash를 사용하더라도
각각 별도의 도구로 인식됩니다. Bash matcher는 MCP 도구를 매칭하지 않습니다.
MCP (Model Context Protocol) tools are recognized as separate tools even if they internally use Bash.
The Bash matcher does not match MCP tools.
해결 방법
Solution
// ❌ Incorrect configuration - MCP tools excluded
{
"hooks": {
"preToolUse": [
{
"matcher": "bash", // MCP tools won't match!
"hooks": [
{
"command": "./validate-input.sh",
"blocking": true
}
]
}
]
}
}
// ✅ Correct configuration - MCP tools included
{
"hooks": {
"preToolUse": [
{
"matcher": "*", // All tools (including MCP)
"hooks": [
{
"command": "./validate-input.sh",
"blocking": true
}
]
}
]
}
}
언제 *를 사용해야 하나요?
When Should You Use *?
- 보안 검증: 위험한 명령어 차단, 입력 검증 등은 모든 도구에 적용
- 로깅/모니터링: 모든 도구 실행을 추적하려면
*사용 - 환경 체크: 필수 환경 변수나 파일 존재 여부 확인
- Bash 전용 기능: Bash 명령어에만 특화된 검증 (예: 특정 명령어만 로깅)
- 도구별 최적화: 각 도구 타입에 맞는 별도 hook 설정
- Security validation: Apply dangerous command blocking, input validation to all tools
- Logging/monitoring: Use
*to track all tool executions - Environment checks: Verify required environment variables or file existence
- Bash-specific features: Validation specific to Bash commands (e.g., logging specific commands only)
- Tool-specific optimization: Configure separate hooks for each tool type