// Claude Code hook execution strategies, timing models, sequencing patterns, and orchestration for automated workflow enforcement. Covers all hook types and execution timing models.
| name | moai-cc-hook-model-strategy |
| version | 4.0.0 |
| updated | "2025-11-19T00:00:00.000Z" |
| status | stable |
| stability | stable |
| description | Claude Code hook execution strategies, timing models, sequencing patterns, and orchestration for automated workflow enforcement. Covers all hook types and execution timing models. |
| focus_areas | ["Hook types and timing models","Sequential vs parallel execution","Hook composition and chaining","Error handling in hooks"] |
| keywords | ["hooks","automation","execution","validation","pre-tool","post-tool","session"] |
| allowed-tools | Read, Glob, Bash |
Hooks provide automation triggers at strategic points in Claude Code workflows: pre-tool execution (validation), post-tool execution (processing), and session lifecycle events (initialization, cleanup). Enable systematic enforcement of quality standards and security policies.
WORKFLOW TIMELINE
โ
โโ Session Start
โ โโ SessionStart hooks trigger
โ
โโ Tool Invocation
โ โโ Pre-Tool hooks trigger (validation)
โ โโ Tool executes
โ โโ Post-Tool hooks trigger (processing)
โ
โโ Task Completion
โ โโ SessionEnd hooks trigger (cleanup)
โ
โโ Session Close
Execute BEFORE tool runs:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "python3 .claude/hooks/validate-command.py"
}
]
}
]
}
}
Execution Timing:
User: bash("git commit -m 'message'")
โ
Pre-Tool Hook: validate-command.py
โโ Check command syntax
โโ Verify permissions
โโ Scan for dangerous patterns
โโ Decision: ALLOW / DENY
โ
ALLOW โ Tool executes
DENY โ Block & report error
Use Cases:
Example Hook Script:
#!/usr/bin/env python3
import re
import sys
import json
DANGEROUS_PATTERNS = [
r"rm -rf",
r"sudo ",
r"chmod 777",
r"&&.*rm",
r"\|.*sh"
]
def validate_command(command):
for pattern in DANGEROUS_PATTERNS:
if re.search(pattern, command):
return False, f"Dangerous pattern: {pattern}"
return True, "Safe"
if __name__ == "__main__":
input_data = json.load(sys.stdin)
command = input_data.get("command", "")
is_safe, message = validate_command(command)
if not is_safe:
print(f"SECURITY BLOCK: {message}", file=sys.stderr)
sys.exit(2) # Non-zero = block
sys.exit(0) # Zero = allow
Execute AFTER tool completes:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Edit",
"hooks": [
{
"type": "command",
"command": "python3 .claude/hooks/post-edit-processing.py"
}
]
}
]
}
}
Execution Timing:
Tool executes: Edit(src/auth.py)
โ
Post-Tool Hook: post-edit-processing.py
โโ Validate syntax
โโ Run linter
โโ Check formatting
โโ Log results
โ
Returns to user with processing results
Use Cases:
Execute at session start/end:
{
"hooks": {
"SessionStart": [
{
"type": "command",
"command": "uv run .moai/scripts/statusline.py"
}
],
"SessionEnd": [
{
"type": "command",
"command": "python3 .claude/hooks/cleanup.py"
}
]
}
}
Timing:
SESSION START
โ
SessionStart hooks trigger
โโ Load project config
โโ Initialize memory
โโ Check dependencies
โโ Display status
โ
WORK PHASE
โ
SESSION END
โ
SessionEnd hooks trigger
โโ Save state
โโ Cleanup temp files
โโ Generate report
โโ Close connections
Use Cases:
Hooks run one after another, in order:
Tool Call
โ
Pre-Hook 1 (VALIDATE INPUT)
โโ Check syntax โ Pass/Fail
โโ Output: validated_input
โ
Pre-Hook 2 (CHECK PERMISSIONS)
โโ Verify permissions โ Pass/Fail
โโ Output: permission_result
โ
Pre-Hook 3 (AUDIT LOG)
โโ Log operation โ Always pass
โโ Output: audit_entry
โ
Tool Execution
โ
Post-Hook 1 (VALIDATE OUTPUT)
Post-Hook 2 (FORMAT RESULTS)
Post-Hook 3 (UPDATE METRICS)
โ
Result
When to use sequential:
Hooks run simultaneously when independent:
Tool Call
โ
Pre-Hooks (all in parallel):
โโ Thread 1: Validate syntax
โโ Thread 2: Check permissions
โโ Thread 3: Scan for secrets
โโ Thread 4: Verify resources
โ
(All must pass for tool to execute)
โ
Tool Execution
โ
Post-Hooks (all in parallel):
โโ Thread 1: Validate output
โโ Thread 2: Update metrics
โโ Thread 3: Log operation
โโ Thread 4: Format results
โ
Result
When to use parallel:
# Pre-execution chain:
# 1. Validation Hook (input validation)
# 2. Permission Hook (authorization)
# 3. Resource Hook (availability check)
# 4. Audit Hook (logging)
# 5. Execution (actual tool)
# Post-execution chain:
# 1. Output Hook (result validation)
# 2. Processing Hook (transformation)
# 3. Cleanup Hook (resource release)
# 4. Metrics Hook (usage tracking)
#!/bin/bash
# Hook only runs if specific conditions met
if [[ "$TOOL_TYPE" == "Edit" ]]; then
# Run linter for edit operations
python3 -m pylint --score=no "$FILE" || exit 1
fi
if [[ "$COMMAND" == "rm -rf" ]]; then
echo "BLOCKED: Destructive command"
exit 2
fi
exit 0
# Hook exit codes:
# 0 = Success (allow/continue)
# 1 = Warning (log but continue)
# 2 = Error (block/stop)
#!/usr/bin/env python3
import sys
try:
# Perform validation
result = validate_operation()
if not result.valid:
# Block operation
print(f"BLOCK: {result.error}", file=sys.stderr)
sys.exit(2) # Exit code 2 = block
except Exception as e:
# Unexpected error
print(f"ERROR: {e}", file=sys.stderr)
sys.exit(1) # Exit code 1 = warning
# Success
sys.exit(0) # Exit code 0 = allow
{
"hooks": {
"PreToolUse": [
{
"command": "python3 .claude/hooks/fast-validation.py",
"timeout": 5000 # 5 second timeout
}
]
}
}
#!/bin/bash
# Pre-commit hook: validate before git commit
# Check for secrets
if grep -r "PASSWORD\|API_KEY\|SECRET" --include="*.py" . ; then
echo "ERROR: Secrets found in code"
exit 2
fi
# Check code formatting
python3 -m black --check . || exit 2
# All checks pass
exit 0
#!/bin/bash
# Post-edit hook: auto-format edited files
# Get edited file from input
FILE="$1"
# Auto-format
python3 -m black "$FILE" || exit 1
python3 -m ruff check --fix "$FILE" || exit 1
echo "Formatted: $FILE"
exit 0
#!/bin/bash
# SessionStart hook: initialize project context
# Load project status
echo "Loading project configuration..."
python3 .moai/scripts/statusline.py
# Check dependencies
echo "Verifying dependencies..."
uv sync --quiet
echo "Session ready!"
exit 0
moai-cc-permission-mode - Permission validation in hooksmoai-cc-subagent-lifecycle - Lifecycle hooks for subagentsmoai-core-workflow - Overall workflow orchestrationLast Updated: 2025-11-19 Version: 4.0.0 Enterprise Production Ready: Yes โ Maturity: Stable