--- title: "Advanced Patterns" sidebarTitle: "Advanced Patterns" description: "Complex hook combinations, stateful patterns, and performance optimization techniques" --- This page covers advanced hook patterns that leverage multiple hook types together, maintain state across operations, and implement sophisticated logic for complex development workflows. ## Hook Chaining Patterns Hook chaining coordinates multiple hooks across the operation lifecycle, allowing you to build stateful validation pipelines. The key advantage is maintaining context between pre-execution and post-execution phases - your PreToolUse hook can record warnings and expectations, then PostToolUse can verify whether those concerns materialized or provide recovery guidance if operations failed. This pattern is particularly valuable for operations with complex side effects (file overwrites, directory creation, configuration changes) where you want to track the complete operation flow rather than just the individual steps. ### Multi-Stage Validation Pipeline This example demonstrates a full validation pipeline that: - Stores validation state in PreToolUse for later reference - Checks if pre-identified warnings actually caused issues in PostToolUse - Provides contextual guidance based on the complete operation outcome - Automatically cleans up old state files to prevent accumulation The state directory approach allows hooks to maintain context across Cline restarts and provides an audit trail of validation decisions. **File: `PreToolUse`** ```bash #!/usr/bin/env bash # Multi-Stage Validation Pipeline - Pre-validation Hook # # Overview: First stage of a two-part validation system that records warnings and # concerns during pre-validation, then correlates them with actual outcomes in the # post-validation stage. Enables intelligent feedback based on complete operation flow. # # Demonstrates: Stateful validation with persistent storage, JSON-based state management, # warning detection patterns, and preparation for post-execution correlation analysis. input=$(cat) tool_name=$(echo "$input" | jq -r '.preToolUse.toolName') task_id=$(echo "$input" | jq -r '.taskId') # Create validation state directory state_dir="$HOME/.cline_hook_state" mkdir -p "$state_dir" # Store validation context for post-hook processing validation_file="$state_dir/${task_id}_validation.json" validation_context=$(jq -n \ --arg tool "$tool_name" \ --arg timestamp "$(date -Iseconds)" \ --arg validation_level "pre" \ '{ tool: $tool, timestamp: $timestamp, validation_level: $validation_level, checks_performed: [], warnings: [], context_suggestions: [] }') echo "$validation_context" > "$validation_file" # Perform pre-validation checks warnings=() context_suggestions=() if [[ "$tool_name" == "write_to_file" ]]; then file_path=$(echo "$input" | jq -r '.preToolUse.parameters.path // empty') # Check for potential overwrites of important files if [[ -f "$file_path" ]] && [[ "$file_path" =~ \.(config|env)$ ]]; then warnings+=("overwrite_config_file") context_suggestions+=("VALIDATION: You're overwriting a configuration file. Consider backing up the original.") fi # Check for missing directories dir_path=$(dirname "$file_path") if [[ ! -d "$dir_path" ]] && [[ "$dir_path" != "." ]]; then warnings+=("missing_directory") context_suggestions+=("DIRECTORY_STRUCTURE: Creating file in non-existent directory: $dir_path") fi fi # Update validation context updated_context=$(jq \ --argjson warnings "$(printf '%s\n' "${warnings[@]}" | jq -R . | jq -s .)" \ --argjson suggestions "$(printf '%s\n' "${context_suggestions[@]}" | jq -R . | jq -s .)" \ '.warnings = $warnings | .context_suggestions = $suggestions' \ "$validation_file") echo "$updated_context" > "$validation_file" # Return context if any suggestions were generated if [[ ${#context_suggestions[@]} -gt 0 ]]; then combined_context=$(IFS=$'\n'; echo "${context_suggestions[*]}") jq -n --arg ctx "$combined_context" '{"cancel": false, "contextModification": $ctx}' else echo '{"cancel": false}' fi ``` **File: `PostToolUse`** ```bash #!/usr/bin/env bash # Multi-Stage Validation Pipeline - Post-validation Hook # # Overview: Second stage that correlates pre-validation warnings with actual operation # outcomes. Provides intelligent feedback by analyzing whether concerns materialized, # offers recovery suggestions for failures, and tracks complete operation history. # # Demonstrates: State correlation across hook executions, outcome-based conditional logic, # failure recovery patterns, performance monitoring, and audit trail creation with cleanup. input=$(cat) tool_name=$(echo "$input" | jq -r '.postToolUse.toolName') success=$(echo "$input" | jq -r '.postToolUse.success') task_id=$(echo "$input" | jq -r '.taskId') execution_time=$(echo "$input" | jq -r '.postToolUse.executionTimeMs // 0') state_dir="$HOME/.cline_hook_state" validation_file="$state_dir/${task_id}_validation.json" # Check if we have pre-validation context # PostToolUse runs after every tool execution, but we only have validation # context if PreToolUse ran first and stored state for this task_id if [[ ! -f "$validation_file" ]]; then echo '{"cancel": false}' exit 0 fi # Load and update validation context # This retrieves the warnings and context that PreToolUse identified validation_context=$(cat "$validation_file") pre_warnings=$(echo "$validation_context" | jq -r '.warnings[]?' | tr '\n' '|') # Perform post-validation # The key insight here is checking whether pre-identified warnings actually # caused problems, or if the operation succeeded despite the concerns post_context="" if [[ "$success" == "true" ]]; then # Success case - provide outcome-specific guidance based on pre-warnings # If PreToolUse warned about config overwrites and the operation succeeded, # we now know the overwrite was safe and can suggest next steps if [[ "$pre_warnings" =~ "overwrite_config_file" ]]; then post_context+="VALIDATION_RESULT: Configuration file was successfully updated. Consider testing the application. " fi # Directory creation warnings that didn't prevent success indicate # automatic directory creation - mention this to set expectations if [[ "$pre_warnings" =~ "missing_directory" ]]; then post_context+="VALIDATION_RESULT: Directory structure was created automatically. " fi # Performance validation based on execution time # >1000ms operations might indicate issues worth addressing if (( execution_time > 1000 )); then post_context+="PERFORMANCE_NOTE: Operation took ${execution_time}ms - this may indicate large files or slow I/O. " fi else # Failure case - correlate pre-warnings with actual failure to provide # actionable recovery suggestions rather than generic error messages post_context="VALIDATION_FAILURE: Operation failed. " if [[ "$pre_warnings" =~ "missing_directory" ]]; then post_context+="This might be due to directory permission issues. Try creating the directory manually first. " fi fi # Update validation log with final results # This creates a complete audit trail showing pre-warnings, execution outcome, # and timing data for later analysis or debugging final_context=$(echo "$validation_context" | jq \ --arg post_level "post" \ --arg success "$success" \ --arg exec_time "$execution_time" \ --arg post_timestamp "$(date -Iseconds)" \ '. + { post_validation: { success: ($success == "true"), execution_time_ms: ($exec_time | tonumber), timestamp: $post_timestamp, validation_level: $post_level } }') echo "$final_context" > "$validation_file" # Cleanup old validation files (keep only files from last 24 hours) # This prevents unbounded growth while maintaining recent history for debugging find "$state_dir" -name "*_validation.json" -mtime +1 -exec rm {} \; 2>/dev/null || true if [[ -n "$post_context" ]]; then jq -n --arg ctx "$post_context" '{"cancel": false, "contextModification": $ctx}' else echo '{"cancel": false}' fi ``` ## Stateful Hook Patterns Stateful hooks maintain persistent data across multiple Cline sessions, enabling progressive learning and context building. The fundamental technique is storing structured data in JSON files that accumulate insights over time. This pattern is powerful for project-specific intelligence - hooks can detect patterns in task descriptions, track framework usage, and build a historical understanding of the project's architecture and conventions. The key advantage is that your hooks become smarter with every task. Initial tasks receive generic guidance, but after 10-20 tasks, the hooks have learned enough about your project to provide highly targeted suggestions. ### Project Knowledge Accumulation This example implements an incremental learning system that: - Analyzes each task description for framework and pattern indicators - Maintains frequency counters for detected frameworks/patterns in per-project JSON files - Provides context based on historical usage patterns (sorted by frequency) - Suggests conventions appropriate for the current task type - Leverages project files (package.json) for additional insights The counter-based approach using `jq` allows simple frequency tracking - frameworks/patterns used most often appear first in context suggestions. The per-project directory structure (`~/.cline_knowledge/$(basename "$PWD")`) isolates learning between projects while persisting across Cline restarts. **File: `TaskStart`** ```bash #!/usr/bin/env bash input=$(cat) task_text=$(echo "$input" | jq -r '.taskStart.taskMetadata.initialTask') task_id=$(echo "$input" | jq -r '.taskId') # Project knowledge storage knowledge_dir="$HOME/.cline_knowledge/$(basename "$PWD")" mkdir -p "$knowledge_dir" # Load existing project knowledge patterns_file="$knowledge_dir/patterns.json" frameworks_file="$knowledge_dir/frameworks.json" conventions_file="$knowledge_dir/conventions.json" # Initialize knowledge files if they don't exist [[ ! -f "$patterns_file" ]] && echo '{}' > "$patterns_file" [[ ! -f "$frameworks_file" ]] && echo '{}' > "$frameworks_file" [[ ! -f "$conventions_file" ]] && echo '{}' > "$conventions_file" # Analyze task for patterns detected_patterns=() detected_frameworks=() suggested_conventions=() # Framework detection if echo "$task_text" | grep -qi "react\|component\|jsx\|tsx"; then detected_frameworks+=("react") suggested_conventions+=("Use functional components with TypeScript interfaces") fi if echo "$task_text" | grep -qi "api\|endpoint\|server\|express"; then detected_frameworks+=("api") suggested_conventions+=("Follow RESTful conventions with proper error handling") fi if echo "$task_text" | grep -qi "test\|testing\|spec"; then detected_patterns+=("testing") suggested_conventions+=("Include comprehensive test coverage with descriptive test names") fi if echo "$task_text" | grep -qi "database\|db\|sql\|migration"; then detected_patterns+=("database") suggested_conventions+=("Use migrations for schema changes and include rollback procedures") fi # Update knowledge files if [[ ${#detected_frameworks[@]} -gt 0 ]]; then for framework in "${detected_frameworks[@]}"; do jq --arg fw "$framework" --arg ts "$(date -Iseconds)" \ '.[$fw] = (.[$fw] // 0) + 1 | .last_seen = $ts' \ "$frameworks_file" > "$frameworks_file.tmp" && mv "$frameworks_file.tmp" "$frameworks_file" done fi if [[ ${#detected_patterns[@]} -gt 0 ]]; then for pattern in "${detected_patterns[@]}"; do jq --arg pt "$pattern" --arg ts "$(date -Iseconds)" \ '.[$pt] = (.[$pt] // 0) + 1 | .last_seen = $ts' \ "$patterns_file" > "$patterns_file.tmp" && mv "$patterns_file.tmp" "$patterns_file" done fi # Load historical knowledge to build context historical_frameworks=$(jq -r 'to_entries | sort_by(.value) | reverse | .[0:3] | .[].key' "$frameworks_file" 2>/dev/null | tr '\n' ' ') historical_patterns=$(jq -r 'to_entries | sort_by(.value) | reverse | .[0:3] | .[].key' "$patterns_file" 2>/dev/null | tr '\n' ' ') # Build intelligent context context_parts=() if [[ -n "$historical_frameworks" ]]; then context_parts+=("PROJECT_KNOWLEDGE: Based on previous work, this project commonly uses: $historical_frameworks") fi if [[ -n "$historical_patterns" ]]; then context_parts+=("DEVELOPMENT_PATTERNS: Frequently used patterns in this project: $historical_patterns") fi # Add specific suggestions for current task if [[ ${#suggested_conventions[@]} -gt 0 ]]; then conventions_text=$(IFS='; '; echo "${suggested_conventions[*]}") context_parts+=("TASK_CONVENTIONS: For this task type, consider: $conventions_text") fi # Check for file structure insights if [[ -f "package.json" ]]; then deps=$(jq -r '.dependencies // {} | keys | join(", ")' package.json 2>/dev/null | head -c 100) if [[ -n "$deps" && "$deps" != "null" ]]; then context_parts+=("PROJECT_DEPENDENCIES: Available libraries include: $deps") fi fi # Combine all context if [[ ${#context_parts[@]} -gt 0 ]]; then final_context=$(IFS=$'\n'; echo "${context_parts[*]}") jq -n --arg ctx "$final_context" '{"cancel": false, "contextModification": $ctx}' else echo '{"cancel": false}' fi ``` ### Adaptive Rule Learning Learn from user corrections and gradually improve validation rules. **File: `UserPromptSubmit`** ```bash #!/usr/bin/env bash input=$(cat) prompt_text=$(echo "$input" | jq -r '.userPromptSubmit.prompt') task_id=$(echo "$input" | jq -r '.taskId') # Learning storage learning_dir="$HOME/.cline_learning" mkdir -p "$learning_dir" corrections_file="$learning_dir/user_corrections.json" # Initialize corrections file [[ ! -f "$corrections_file" ]] && echo '[]' > "$corrections_file" # Detect correction patterns in user prompts correction_indicators=("actually" "instead" "not" "don't" "shouldn't" "wrong" "fix" "change" "correct") is_correction=false for indicator in "${correction_indicators[@]}"; do if echo "$prompt_text" | grep -qi "$indicator"; then is_correction=true break fi done # Process corrections to learn new rules if [[ "$is_correction" == true ]]; then # Extract what the user is correcting correction_entry=$(jq -n \ --arg timestamp "$(date -Iseconds)" \ --arg task_id "$task_id" \ --arg prompt "$prompt_text" \ --arg workspace "$(basename "$PWD")" \ '{ timestamp: $timestamp, task_id: $task_id, prompt: $prompt, workspace: $workspace, type: "user_correction" }') # Add to corrections log jq --argjson new_entry "$correction_entry" '. += [$new_entry]' "$corrections_file" > "${corrections_file}.tmp" && mv "${corrections_file}.tmp" "$corrections_file" # Keep only last 100 corrections jq '.[-100:]' "$corrections_file" > "${corrections_file}.tmp" && mv "${corrections_file}.tmp" "$corrections_file" # Generate learned context context="LEARNING: User correction detected. This feedback helps improve future suggestions for this project type." # Look for patterns in recent corrections recent_corrections=$(jq -r '.[-5:] | .[].prompt' "$corrections_file" 2>/dev/null) if echo "$recent_corrections" | grep -qi "typescript"; then context+=" Note: Recent corrections indicate strong TypeScript preferences." elif echo "$recent_corrections" | grep -qi "test\|testing"; then context+=" Note: Recent corrections emphasize testing practices." fi jq -n --arg ctx "$context" '{"cancel": false, "contextModification": $ctx}' else echo '{"cancel": false}' fi ``` ## Performance Optimization Patterns Performance optimization in hooks focuses on preventing expensive operations from blocking Cline's workflow. The two key techniques are async processing (offloading work to background processes) and caching (avoiding redundant computation for identical inputs). ### Async Hook Processing This pattern implements true background processing by creating a persistent worker process that consumes jobs from a queue directory. The critical insight is that hooks must return quickly - ideally within milliseconds - to avoid blocking Cline's tool execution flow. The job queue approach decouples the hook response from the actual work. The hook instantly acknowledges the operation by creating a job file, then returns. A separate background processor handles the expensive work (linting, metrics calculation) without impacting Cline's responsiveness. The `pgrep` check ensures only one background processor runs at a time across all Cline instances. The `nohup` wrapper allows the processor to survive terminal closure and continue processing jobs until the user logs out. **File: `PostToolUse` (Async Pattern)** ```bash #!/usr/bin/env bash input=$(cat) tool_name=$(echo "$input" | jq -r '.postToolUse.toolName') success=$(echo "$input" | jq -r '.postToolUse.success') # Only process successful file operations if [[ "$success" != "true" ]] || [[ "$tool_name" != "write_to_file" && "$tool_name" != "replace_in_file" ]]; then echo '{"cancel": false}' exit 0 fi file_path=$(echo "$input" | jq -r '.postToolUse.parameters.path // empty') task_id=$(echo "$input" | jq -r '.taskId') # Skip non-code files if [[ ! "$file_path" =~ \.(ts|tsx|js|jsx|py|rs|go)$ ]]; then echo '{"cancel": false}' exit 0 fi # Queue directory for background processing queue_dir="$HOME/.cline_processing_queue" mkdir -p "$queue_dir" # Create processing job job_file="$queue_dir/${task_id}_$(date +%s).json" job_data=$(jq -n \ --arg file "$file_path" \ --arg task "$task_id" \ --arg workspace "$PWD" \ --arg timestamp "$(date -Iseconds)" \ '{ file_path: $file, task_id: $task, workspace: $workspace, timestamp: $timestamp, job_type: "code_analysis" }') echo "$job_data" > "$job_file" # Start background processor if not running pgrep -f "cline_background_processor" > /dev/null || { nohup bash -c " while true; do for job in '$queue_dir'/*.json; do [[ -f \"\$job\" ]] || continue # Process job file_path=\$(jq -r '.file_path' \"\$job\") workspace=\$(jq -r '.workspace' \"\$job\") cd \"\$workspace\" 2>/dev/null || continue # Run expensive analysis (linting, complexity metrics, etc.) if [[ \"\$file_path\" =~ \\.(ts|tsx|js|jsx)\$ ]] && command -v eslint > /dev/null; then eslint \"\$file_path\" --format json > \"/tmp/\$(basename \"\$job\").lint\" 2>/dev/null || true fi # Calculate complexity metrics if command -v cloc > /dev/null; then cloc \"\$file_path\" --json > \"/tmp/\$(basename \"\$job\").metrics\" 2>/dev/null || true fi # Remove processed job rm \"\$job\" done sleep 5 done " > /dev/null 2>&1 & } # Provide immediate feedback without waiting echo '{"cancel": false, "contextModification": "BACKGROUND_PROCESSING: Code analysis queued for background processing. Results will be available for future tasks."}' ``` ### Caching and Memoization Caching eliminates redundant computation by storing results indexed by input. This pattern uses content-based hashing (SHA256) to generate cache keys - identical file contents produce identical hashes, enabling cache hits even across different tasks or sessions. The strategy implements a simple time-based expiration (60 minutes) using file modification time. This balances cache effectiveness with freshness - lint rules might change, dependencies might update, so cached results shouldn't persist indefinitely. The critical performance benefit comes from expensive operations like ESLint validation, which can take 500ms-2s on large files. With caching, subsequent writes of identical content return instantly. The truncated hash (16 characters) prevents excessively long filenames while maintaining extremely low collision probability (2^64 possibilities). **File: `PreToolUse` (With Caching)** ```bash #!/usr/bin/env bash input=$(cat) tool_name=$(echo "$input" | jq -r '.preToolUse.toolName') # Only process file operations if [[ "$tool_name" != "write_to_file" ]]; then echo '{"cancel": false}' exit 0 fi file_path=$(echo "$input" | jq -r '.preToolUse.parameters.path // empty') content=$(echo "$input" | jq -r '.preToolUse.parameters.content // empty') # Setup caching cache_dir="$HOME/.cline_cache" mkdir -p "$cache_dir" # Generate cache key from content hash # SHA256 ensures identical content always produces the same hash # This enables cache hits even if the same code is written to different file paths content_hash=$(echo -n "$content" | sha256sum | cut -d' ' -f1) cache_key="validation_${content_hash:0:16}" cache_file="$cache_dir/$cache_key" # Check cache first # -mmin -60 checks if file was modified within last 60 minutes # This provides time-based cache expiration - after 60 minutes, validation re-runs if [[ -f "$cache_file" ]] && [[ $(find "$cache_file" -mmin -60) ]]; then # Cache hit - return cached result instantly without re-running validation # This transforms a 500ms-2s operation into <1ms cached_result=$(cat "$cache_file") echo "$cached_result" exit 0 fi # Cache miss - perform validation # Default to passing validation if no issues found validation_result='{"cancel": false}' # Perform expensive validation only if not cached # Using temp file allows ESLint to run without modifying the actual workspace if [[ "$file_path" =~ \.(ts|tsx|js|jsx)$ ]] && command -v eslint > /dev/null; then temp_file=$(mktemp) echo "$content" > "$temp_file" # Run ESLint and capture results # || echo "[]" ensures the hook doesn't fail if ESLint encounters an error lint_output=$(eslint "$temp_file" --format json 2>/dev/null || echo "[]") error_count=$(echo "$lint_output" | jq '.[0].errorCount // 0' 2>/dev/null || echo "0") # Block the write if linting errors are found if (( error_count > 0 )); then validation_result='{"cancel": true, "errorMessage": "ESLint validation failed. Check code quality."}' fi rm -f "$temp_file" fi # Cache the result for future writes of identical content # Even failed validations are cached - if the content is bad, it stays bad echo "$validation_result" > "$cache_file" # Cleanup old cache files (keep only files from last 24 hours) # -mtime +1 finds files older than 24 hours # This prevents unbounded cache growth while maintaining reasonable hit rates find "$cache_dir" -name "validation_*" -mtime +1 -delete 2>/dev/null || true echo "$validation_result" ``` ## Conditional Logic Patterns Conditional logic in hooks enables adaptive behavior based on context. Rather than applying the same rules universally, hooks can adjust their behavior based on user preferences, time of day, project configuration, Git branch context, and other environmental factors. ### Context-Aware Decision Making This pattern demonstrates multi-layered decision making that considers multiple context sources: - **User preferences**: Stored per-user settings for strictness levels and notification preferences - **Time-based logic**: Different behavior during business hours vs. off-hours - **Project configuration**: Project-specific overrides via `.cline-project-config.json` - **Git context**: Branch-aware suggestions (stricter on main, focused on hotfix branches) The hierarchical approach allows project settings to override user defaults, enabling team-wide standards while respecting individual preferences. The strictness level system (`strict`, `medium`, `permissive`) provides coarse-grained control, while notification preferences offer fine-grained tuning. **File: `PreToolUse` (Context-Aware)** ```bash #!/usr/bin/env bash input=$(cat) tool_name=$(echo "$input" | jq -r '.preToolUse.toolName') user_id=$(echo "$input" | jq -r '.userId') task_id=$(echo "$input" | jq -r '.taskId') # Load user preferences and history # Per-user storage allows individual developers to have different validation levels prefs_dir="$HOME/.cline_user_prefs" mkdir -p "$prefs_dir" user_prefs="$prefs_dir/${user_id}_preferences.json" # Initialize user preferences if needed # These defaults provide sensible starting points that users can customize if [[ ! -f "$user_prefs" ]]; then echo '{ "strictness_level": "medium", "preferred_languages": [], "coding_style": "standard", "notification_preferences": { "security_alerts": true, "performance_warnings": true, "style_suggestions": false } }' > "$user_prefs" fi # Load current preferences # The // operator provides defaults if fields are missing or null strictness=$(jq -r '.strictness_level // "medium"' "$user_prefs") security_alerts=$(jq -r '.notification_preferences.security_alerts // true' "$user_prefs") style_suggestions=$(jq -r '.notification_preferences.style_suggestions // false' "$user_prefs") # Adapt behavior based on user preferences # Case statement allows clean handling of different strictness levels case "$strictness" in "strict") # Strict mode - block more operations, provide detailed feedback # This mode is useful for production code or when following strict standards if [[ "$tool_name" == "write_to_file" ]]; then file_path=$(echo "$input" | jq -r '.preToolUse.parameters.path // empty') content=$(echo "$input" | jq -r '.preToolUse.parameters.content // empty') # In strict mode, require documentation for new functions # Regex matches both traditional functions and arrow functions # Negative lookahead (?!...) ensures JSDoc /** */ is NOT present if echo "$content" | grep -q "function\|const.*=.*=>" && ! echo "$content" | grep -q "\/\*\*"; then echo '{"cancel": true, "errorMessage": "Strict mode: All functions must have JSDoc documentation."}' exit 0 fi fi ;; "permissive") # Permissive mode - minimal blocking, focus on critical issues only # Early exit if user has disabled security alerts if [[ "$security_alerts" == "false" ]]; then echo '{"cancel": false}' exit 0 fi ;; esac # Time-based logic # Different rules during off-hours (before 6 AM or after 6 PM) # This accommodates late-night coding sessions where speed > style current_hour=$(date +%H) if (( current_hour >= 18 || current_hour <= 6 )); then # After hours - be less intrusive # Reduce style noise when developers are working outside business hours if [[ "$style_suggestions" == "true" ]]; then # Override style suggestions during off-hours echo '{"cancel": false, "contextModification": "AFTER_HOURS: Style suggestions reduced during off-hours. Focus on functionality."}' exit 0 fi fi # Project-specific context context_suggestions="" # Check for project-specific configuration files # This allows teams to enforce project-wide standards regardless of user preferences # .cline-project-config.json would be committed to version control if [[ -f ".cline-project-config.json" ]]; then project_strictness=$(jq -r '.validation.strictness // "inherit"' .cline-project-config.json 2>/dev/null) # "inherit" means use user's personal preference if [[ "$project_strictness" != "inherit" && "$project_strictness" != "null" ]]; then strictness="$project_strictness" context_suggestions+="PROJECT_CONFIG: Using project-specific validation level: $project_strictness. " fi fi # Git context awareness # Different suggestions based on current branch type if git rev-parse --git-dir > /dev/null 2>&1; then current_branch=$(git branch --show-current 2>/dev/null) # Main/master branches - extra cautious recommendations if [[ "$current_branch" == "main" || "$current_branch" == "master" ]]; then context_suggestions+="GIT_CONTEXT: Working on main branch - extra caution recommended. " # Hotfix branches - encourage minimal, focused changes elif [[ "$current_branch" =~ ^hotfix/ ]]; then context_suggestions+="GIT_CONTEXT: Hotfix branch detected - focus on minimal, targeted changes. " fi fi # Build final response # Combine all context sources into a single coherent message if [[ -n "$context_suggestions" ]]; then jq -n --arg ctx "$context_suggestions" '{"cancel": false, "contextModification": $ctx}' else echo '{"cancel": false}' fi ``` ## Error Recovery and Resilience Hook failures should never block Cline's operation. This pattern implements graceful degradation through health tracking - after repeated failures, the hook automatically enters "degraded mode" where it stops attempting complex operations and simply passes operations through. ### Self-Healing Hook System This pattern implements automatic failure detection and recovery through: - **Error trapping**: All potential failure points are wrapped with fallbacks - **Health tracking**: Persistent monitoring of success/failure rates across sessions - **Degraded mode**: Automatic disabling after threshold failures (3 consecutive) - **Automatic recovery**: Resetting to normal mode upon first success The threshold-based approach (3 consecutive failures) distinguishes between occasional issues and systematic problems. The health file persists across Cline sessions, so degraded mode survives restarts - hooks won't repeatedly fail on every startup if there's a configuration issue. **File: `PostToolUse` (Resilient)** ```bash #!/usr/bin/env bash # Trap errors and ensure graceful failure # set -o pipefail ensures pipeline failures are caught # trap ensures ANY error results in graceful passthrough, never blocking Cline set -o pipefail trap 'echo "{\"cancel\": false}" >&2; exit 0' ERR input=$(cat) # Validate input JSON # Malformed input should not crash the hook - just pass through # The 2>/dev/null suppresses error messages that would clutter output if ! echo "$input" | jq empty 2>/dev/null; then echo '{"cancel": false}' exit 0 fi # Extract tool information with safe defaults # The // operator provides fallback values if fields are missing tool_name=$(echo "$input" | jq -r '.postToolUse.toolName // "unknown"') success=$(echo "$input" | jq -r '.postToolUse.success // "false"') # Health check directory # 2>/dev/null || { ... } provides fallback if directory creation fails health_dir="$HOME/.cline_hook_health" mkdir -p "$health_dir" 2>/dev/null || { echo '{"cancel": false}' exit 0 } health_file="$health_dir/hook_health.json" # Initialize health tracking # Tracks both lifetime failures and consecutive failures to distinguish # between occasional hiccups and systemic problems if [[ ! -f "$health_file" ]]; then echo '{ "last_success": null, "failure_count": 0, "consecutive_failures": 0, "degraded_mode": false }' > "$health_file" 2>/dev/null || { echo '{"cancel": false}' exit 0 } fi # Update health status if [[ "$success" == "true" ]]; then # Reset failure counters on success # A single success immediately exits degraded mode # This allows hooks to self-heal after fixes (e.g., installing missing dependencies) jq '. + { "last_success": now, "consecutive_failures": 0, "degraded_mode": false }' "$health_file" > "${health_file}.tmp" 2>/dev/null && mv "${health_file}.tmp" "$health_file" 2>/dev/null || true else # Increment failure counters # Both lifetime and consecutive failures are tracked # || true ensures script continues even if jq fails jq '. + { "failure_count": (.failure_count + 1), "consecutive_failures": (.consecutive_failures + 1) }' "$health_file" > "${health_file}.tmp" 2>/dev/null && mv "${health_file}.tmp" "$health_file" 2>/dev/null || true fi # Check if we should enter degraded mode # 3 consecutive failures triggers degraded mode # This threshold balances between tolerance and responsiveness consecutive_failures=$(jq -r '.consecutive_failures // 0' "$health_file" 2>/dev/null || echo "0") if (( consecutive_failures >= 3 )); then # Enable degraded mode # The hook will now pass through all operations without processing # This prevents repeated failures from blocking the user's workflow jq '. + {"degraded_mode": true}' "$health_file" > "${health_file}.tmp" 2>/dev/null && mv "${health_file}.tmp" "$health_file" 2>/dev/null || true # Notify user of degraded mode # This context appears in Cline's chat to explain reduced functionality context="HOOK_HEALTH: Operating in degraded mode due to repeated failures. Hook functionality is reduced to prevent blocking operations." jq -n --arg ctx "$context" '{"cancel": false, "contextModification": $ctx}' 2>/dev/null || echo '{"cancel": false}' else # Normal operation - no notification needed echo '{"cancel": false}' fi ``` These advanced patterns demonstrate how hooks can work together to create sophisticated, intelligent development workflows. They show how to maintain state, optimize performance, adapt to user preferences, and ensure resilient operation even when individual components fail. Remember to test these patterns thoroughly in your environment and adapt them to your specific workflow requirements. The key to successful advanced hook implementation is gradual adoption - start with simpler patterns and build up to more complex combinations as you become comfortable with the system.