diff --git a/docs/docs.json b/docs/docs.json
index 7e895997..9f2c1143 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -144,9 +144,7 @@
"pages": [
"features/hooks/index",
"features/hooks/hook-reference",
- "features/hooks/samples",
- "features/hooks/advanced-patterns",
- "features/hooks/testing-and-debugging"
+ "features/hooks/samples"
]
},
"features/multiroot-workspace",
diff --git a/docs/features/hooks/advanced-patterns.mdx b/docs/features/hooks/advanced-patterns.mdx
deleted file mode 100644
index 36730538..00000000
--- a/docs/features/hooks/advanced-patterns.mdx
+++ /dev/null
@@ -1,803 +0,0 @@
----
-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.
diff --git a/docs/features/hooks/index.mdx b/docs/features/hooks/index.mdx
index 1c496d19..32bc042e 100644
--- a/docs/features/hooks/index.mdx
+++ b/docs/features/hooks/index.mdx
@@ -135,14 +135,6 @@ The key is combining hooks with external tools. A hook can be the glue between C
Practical examples and complete working scripts for common use cases.
-
-
- Complex hook combinations, stateful patterns, and performance optimization techniques.
-
-
-
- Hook testing strategies, debugging techniques, and development best practices.
-
## Related Features
diff --git a/docs/features/hooks/testing-and-debugging.mdx b/docs/features/hooks/testing-and-debugging.mdx
deleted file mode 100644
index e13c9c83..00000000
--- a/docs/features/hooks/testing-and-debugging.mdx
+++ /dev/null
@@ -1,829 +0,0 @@
----
-title: "Testing & Debugging"
-sidebarTitle: "Testing & Debugging"
-description: "Hook testing strategies, debugging techniques, and development best practices"
----
-
-This page provides comprehensive guidance for testing, debugging, and developing robust hooks. It covers testing methodologies, common troubleshooting scenarios, performance optimization, and development best practices.
-
-## Hook Testing Strategies
-
-### Unit Testing Hooks
-
-Test hooks in isolation by providing controlled input and verifying expected output.
-
-**Basic Test Framework:**
-```bash
-#!/usr/bin/env bash
-# test-hook.sh - Simple hook testing framework
-
-HOOK_NAME="$1"
-TEST_DATA="$2"
-EXPECTED_RESULT="$3"
-
-if [[ -z "$HOOK_NAME" || -z "$TEST_DATA" ]]; then
- echo "Usage: $0 [expected-result]"
- exit 1
-fi
-
-# Ensure hook exists and is executable
-if [[ ! -x ".clinerules/hooks/$HOOK_NAME" ]]; then
- echo "ERROR: Hook $HOOK_NAME not found or not executable"
- exit 1
-fi
-
-# Run the hook with test data
-echo "Testing hook: $HOOK_NAME"
-echo "Input data: $TEST_DATA"
-echo "---"
-
-result=$(cat "$TEST_DATA" | ".clinerules/hooks/$HOOK_NAME" 2>&1)
-exit_code=$?
-
-echo "Output:"
-echo "$result"
-echo "Exit code: $exit_code"
-
-# Validate JSON output
-if ! echo "$result" | jq empty 2>/dev/null; then
- echo "ERROR: Hook output is not valid JSON"
- exit 1
-fi
-
-# Check expected result if provided
-if [[ -n "$EXPECTED_RESULT" ]]; then
- cancel_value=$(echo "$result" | jq -r '.cancel // false')
- if [[ "$cancel_value" != "$EXPECTED_RESULT" ]]; then
- echo "ERROR: Expected cancel=$EXPECTED_RESULT, got cancel=$cancel_value"
- exit 1
- fi
-fi
-
-echo "✅ Test passed"
-```
-
-**Test Data Examples:**
-
-**File: `test-data/pretooluse-write-js.json`**
-```json
-{
- "clineVersion": "1.0.0",
- "hookName": "PreToolUse",
- "timestamp": "2024-01-01T12:00:00Z",
- "taskId": "test-task-001",
- "workspaceRoots": ["/test/workspace"],
- "userId": "test-user",
- "preToolUse": {
- "toolName": "write_to_file",
- "parameters": {
- "path": "src/component.js",
- "content": "const Component = () => Hello
;"
- }
- }
-}
-```
-
-**File: `test-data/posttooluse-success.json`**
-```json
-{
- "clineVersion": "1.0.0",
- "hookName": "PostToolUse",
- "timestamp": "2024-01-01T12:00:00Z",
- "taskId": "test-task-001",
- "workspaceRoots": ["/test/workspace"],
- "userId": "test-user",
- "postToolUse": {
- "toolName": "write_to_file",
- "parameters": {
- "path": "src/component.tsx",
- "content": "const Component = () => Hello
;"
- },
- "result": "File created successfully",
- "success": true,
- "executionTimeMs": 150
- }
-}
-```
-
-**Running Tests:**
-```bash
-# Test that TypeScript hook blocks JS files
-./test-hook.sh PreToolUse test-data/pretooluse-write-js.json true
-
-# Test that successful operations don't get cancelled
-./test-hook.sh PostToolUse test-data/posttooluse-success.json false
-
-# Create test suite
-for test_file in test-data/*.json; do
- echo "Running test: $test_file"
- ./test-hook.sh PreToolUse "$test_file"
- echo "---"
-done
-```
-
-### Integration Testing
-
-Test hooks in realistic scenarios with actual Cline operations.
-
-**Integration Test Setup:**
-```bash
-#!/usr/bin/env bash
-# integration-test.sh
-
-# Create test workspace
-test_workspace="/tmp/cline-hook-test-$(date +%s)"
-mkdir -p "$test_workspace"
-cd "$test_workspace"
-
-# Setup test environment
-echo '{"name": "test-project", "dependencies": {"react": "^18.0.0"}}' > package.json
-echo '{"compilerOptions": {"strict": true}}' > tsconfig.json
-
-# Copy hooks to test workspace
-mkdir -p .clinerules/hooks
-cp /path/to/your/hooks/* .clinerules/hooks/
-chmod +x .clinerules/hooks/*
-
-# Simulate Cline operations
-echo "Testing file creation blocking..."
-
-# This should be blocked by TypeScript hooks
-test_input='{
- "clineVersion": "1.0.0",
- "hookName": "PreToolUse",
- "timestamp": "'$(date -Iseconds)'",
- "taskId": "integration-test",
- "workspaceRoots": ["'$test_workspace'"],
- "userId": "integration-test-user",
- "preToolUse": {
- "toolName": "write_to_file",
- "parameters": {
- "path": "src/Component.js",
- "content": "export const Component = () => Test
;"
- }
- }
-}'
-
-result=$(echo "$test_input" | .clinerules/hooks/PreToolUse 2>&1)
-echo "Result: $result"
-
-if echo "$result" | jq -e '.cancel == true' > /dev/null; then
- echo "✅ Integration test passed - JS file correctly blocked"
-else
- echo "❌ Integration test failed - JS file should have been blocked"
-fi
-
-# Cleanup
-cd /
-rm -rf "$test_workspace"
-```
-
-### Performance Testing
-
-Measure hook execution time and identify performance bottlenecks.
-
-**Performance Test Script:**
-```bash
-#!/usr/bin/env bash
-# perf-test.sh
-
-HOOK_NAME="$1"
-TEST_DATA="$2"
-ITERATIONS="${3:-100}"
-
-if [[ -z "$HOOK_NAME" || -z "$TEST_DATA" ]]; then
- echo "Usage: $0 [iterations]"
- exit 1
-fi
-
-echo "Performance testing hook: $HOOK_NAME"
-echo "Iterations: $ITERATIONS"
-echo "---"
-
-total_time=0
-max_time=0
-min_time=999999
-
-for i in $(seq 1 $ITERATIONS); do
- start_time=$(date +%s%N)
- cat "$TEST_DATA" | ".clinerules/hooks/$HOOK_NAME" > /dev/null 2>&1
- end_time=$(date +%s%N)
-
- execution_time=$(( (end_time - start_time) / 1000000 )) # Convert to milliseconds
- total_time=$(( total_time + execution_time ))
-
- if (( execution_time > max_time )); then
- max_time=$execution_time
- fi
-
- if (( execution_time < min_time )); then
- min_time=$execution_time
- fi
-done
-
-average_time=$(( total_time / ITERATIONS ))
-
-echo "Results:"
-echo " Average: ${average_time}ms"
-echo " Min: ${min_time}ms"
-echo " Max: ${max_time}ms"
-echo " Total: ${total_time}ms"
-
-# Performance thresholds
-if (( average_time > 100 )); then
- echo "⚠️ WARNING: Hook is slower than recommended (>100ms average)"
-elif (( average_time > 50 )); then
- echo "ℹ️ INFO: Hook is approaching slow threshold (>50ms average)"
-else
- echo "✅ Hook performance is good (<50ms average)"
-fi
-```
-
-## Debugging Techniques
-
-### Debug Mode Hook Template
-
-Create hooks with built-in debugging capabilities.
-
-```bash
-#!/usr/bin/env bash
-# Debug-Enabled Hook Template
-#
-# Overview: A comprehensive hook template with built-in debugging capabilities that can
-# be toggled via environment variables. Includes error handling, detailed logging, and
-# proper input validation - perfect as a starting point for production hooks.
-#
-# Demonstrates: Environment-based debug toggling, stderr logging patterns, error trapping,
-# JSON validation, graceful error handling, and structured debug output.
-
-# Enable debug mode via environment variable
-DEBUG=${CLINE_HOOK_DEBUG:-false}
-HOOK_NAME="PreToolUse"
-
-# Debug logging function
-debug_log() {
- if [[ "$DEBUG" == "true" ]]; then
- echo "[DEBUG $HOOK_NAME $(date)] $1" >&2
- fi
-}
-
-# Error handling with debugging
-error_handler() {
- local exit_code=$?
- debug_log "Hook failed with exit code $exit_code"
- echo '{"cancel": false}'
- exit 0
-}
-trap error_handler ERR
-
-debug_log "Hook starting"
-
-# Read and validate input
-input=$(cat)
-debug_log "Input received: ${#input} characters"
-
-if ! echo "$input" | jq empty 2>/dev/null; then
- debug_log "ERROR: Invalid JSON input"
- echo '{"cancel": false}'
- exit 0
-fi
-
-# Extract common fields with debugging
-tool_name=$(echo "$input" | jq -r '.preToolUse.toolName // "unknown"')
-user_id=$(echo "$input" | jq -r '.userId // "unknown"')
-task_id=$(echo "$input" | jq -r '.taskId // "unknown"')
-
-debug_log "Processing: tool=$tool_name, user=$user_id, task=$task_id"
-
-# Your hook logic here...
-debug_log "Hook logic completed"
-
-# Return result
-result='{"cancel": false}'
-debug_log "Returning: $result"
-echo "$result"
-```
-
-**Enable debugging:**
-```bash
-export CLINE_HOOK_DEBUG=true
-# Now all debug-enabled hooks will log detailed information
-```
-
-### Hook Execution Tracing
-
-Trace hook execution flow to understand behavior.
-
-**Trace Script:**
-```bash
-#!/usr/bin/env bash
-# trace-hooks.sh - Monitor hook execution
-
-TRACE_DIR="$HOME/.cline_hook_traces"
-mkdir -p "$TRACE_DIR"
-
-# Wrap existing hooks with tracing
-for hook in .clinerules/hooks/*; do
- if [[ -f "$hook" && -x "$hook" ]]; then
- hook_name=$(basename "$hook")
-
- # Backup original hook
- mv "$hook" "${hook}.original"
-
- # Create tracing wrapper
- cat > "$hook" << EOF
-#!/usr/bin/env bash
-# Auto-generated tracing wrapper for $hook_name
-
-TRACE_FILE="$TRACE_DIR/${hook_name}_trace.log"
-ORIGINAL_HOOK="\${0}.original"
-
-# Log start
-echo "[\$(date -Iseconds)] START $hook_name" >> "\$TRACE_FILE"
-
-# Capture input
-input=\$(cat)
-echo "[\$(date -Iseconds)] INPUT: \$input" >> "\$TRACE_FILE"
-
-# Execute original hook
-result=\$(echo "\$input" | "\$ORIGINAL_HOOK" 2>&1)
-exit_code=\$?
-
-# Log result
-echo "[\$(date -Iseconds)] OUTPUT: \$result" >> "\$TRACE_FILE"
-echo "[\$(date -Iseconds)] EXIT: \$exit_code" >> "\$TRACE_FILE"
-echo "[\$(date -Iseconds)] END $hook_name" >> "\$TRACE_FILE"
-echo "" >> "\$TRACE_FILE"
-
-# Return result
-echo "\$result"
-exit \$exit_code
-EOF
-
- chmod +x "$hook"
- fi
-done
-
-echo "Tracing enabled for all hooks. Traces will be saved to $TRACE_DIR"
-```
-
-**View traces:**
-```bash
-# View all traces
-tail -f ~/.cline_hook_traces/*.log
-
-# View specific hook traces
-grep "PreToolUse" ~/.cline_hook_traces/PreToolUse_trace.log
-
-# Analyze hook timing
-grep -E "(START|END)" ~/.cline_hook_traces/*.log |
- awk '{print $1, $2, $3}' |
- sort
-```
-
-### Interactive Hook Debugging
-
-Debug hooks interactively during development.
-
-**Interactive Debugger:**
-```bash
-#!/usr/bin/env bash
-# debug-hook-interactive.sh
-
-HOOK_NAME="$1"
-
-if [[ -z "$HOOK_NAME" ]]; then
- echo "Usage: $0 "
- exit 1
-fi
-
-echo "Interactive Hook Debugger"
-echo "Hook: $HOOK_NAME"
-echo "Enter JSON input (Ctrl+D when done):"
-
-# Read multi-line input
-input=$(cat)
-
-echo "---"
-echo "Input received:"
-echo "$input" | jq .
-
-echo "---"
-echo "Executing hook..."
-
-# Create temporary script to debug the hook
-debug_script=$(mktemp)
-cat > "$debug_script" << 'EOF'
-#!/usr/bin/env bash
-set -x # Enable command tracing
-
-# Your hook code here - copy from actual hook
-input=$(cat)
-
-# Add breakpoints by uncommenting:
-# read -p "Press Enter to continue..."
-
-# Continue with hook logic...
-EOF
-
-chmod +x "$debug_script"
-
-# Run with input
-echo "$input" | "$debug_script"
-
-# Cleanup
-rm "$debug_script"
-```
-
-## Common Troubleshooting Scenarios
-
-### Hook Not Running
-
-**Symptoms:** Hook appears to be ignored, no output in logs.
-
-**Troubleshooting Steps:**
-
-1. **Check Hook Installation:**
-```bash
-# Verify hook file exists and is executable
-ls -la .clinerules/hooks/
-# Should show executable permissions (x flag)
-
-# Make hook executable if needed
-chmod +x .clinerules/hooks/HookName
-```
-
-2. **Verify Cline Settings:**
-```bash
-# Check if hooks are enabled in Cline settings
-# Open Cline -> Settings -> Features -> Enable Hooks (must be checked)
-```
-
-3. **Check Hook Syntax:**
-```bash
-# Test hook syntax manually
-echo '{"test": "data"}' | .clinerules/hooks/HookName
-# Should return valid JSON, not error messages
-```
-
-4. **Examine VSCode Output:**
-```bash
-# Check VSCode Output panel:
-# View -> Output -> Select "Cline" from dropdown
-# Look for hook-related error messages
-```
-
-5. **Hook Location Verification:**
-```bash
-# Verify hook is in correct location
-find . -name "HookName" -type f 2>/dev/null
-# Should find hooks in .clinerules/hooks/ or ~/Documents/Cline/Rules/Hooks/
-```
-
-### Hook Timing Out
-
-**Symptoms:** Hook execution takes too long, operations get blocked.
-
-**Troubleshooting:**
-
-1. **Identify Performance Issues:**
-```bash
-#!/usr/bin/env bash
-# Quick performance check
-time (echo '{"test": "input"}' | .clinerules/hooks/HookName)
-# Should complete in under 1 second
-```
-
-2. **Common Performance Fixes:**
-```bash
-#!/usr/bin/env bash
-# Avoid expensive operations in hooks
-
-# BAD - Network calls in main execution path
-curl -s "https://api.example.com/validate" --max-time 30
-
-# GOOD - Background processing
-curl -s "https://api.example.com/validate" --max-time 5 > /dev/null 2>&1 &
-
-# BAD - Heavy file processing
-find / -name "*.js" -exec eslint {} \;
-
-# GOOD - Process only relevant files
-find . -maxdepth 3 -name "*.js" -exec eslint {} \;
-```
-
-3. **Optimize Common Operations:**
-```bash
-#!/usr/bin/env bash
-# Cache expensive computations
-cache_file="/tmp/hook_cache_$(echo -n "$input" | md5sum | cut -d' ' -f1)"
-
-if [[ -f "$cache_file" ]] && [[ $(find "$cache_file" -mmin -10) ]]; then
- # Use cached result
- cat "$cache_file"
- exit 0
-fi
-
-# Compute result and cache it
-result=$(expensive_operation)
-echo "$result" | tee "$cache_file"
-```
-
-### Context Not Affecting Behavior
-
-**Symptoms:** Context modifications don't influence AI behavior.
-
-**Understanding Context Timing:**
-
-Context injection affects **future** decisions, not current ones. When a hook runs:
-
-1. The AI has already decided what to do
-2. The hook can block or allow it
-3. Any context gets added to the conversation
-4. The **next** AI request sees that context
-
-**Effective Context Strategies:**
-
-```bash
-#!/usr/bin/env bash
-# EFFECTIVE: PreToolUse for immediate blocking + context for next decision
-if [[ "$tool_name" == "write_to_file" && "$file_path" == *.js ]]; then
- # Block immediately
- echo '{"cancel": true, "errorMessage": "Use .ts files instead of .js"}'
- exit 0
-fi
-
-# Add context for next decision
-context="CODING_STANDARDS: This project uses TypeScript. Always create .ts/.tsx files."
-jq -n --arg ctx "$context" '{"cancel": false, "contextModification": $ctx}'
-```
-
-**Context Best Practices:**
-
-1. **Use Clear Prefixes:**
-```bash
-# Good - categorized context
-"SECURITY: Detected potential API key in code"
-"PERFORMANCE: Large file operations detected"
-"CODING_STANDARDS: Use functional components"
-
-# Bad - unclear context
-"This might be a problem"
-"Consider changing this"
-```
-
-2. **Be Specific and Actionable:**
-```bash
-# Good - specific guidance
-"VALIDATION: Use TypeScript interfaces for component props: interface Props { title: string; count: number; }"
-
-# Bad - vague guidance
-"Use proper types"
-```
-
-3. **Check Context Size:**
-```bash
-context="Your context string here"
-if [[ ${#context} -gt 50000 ]]; then
- echo "WARNING: Context too large, may be truncated" >&2
- context="${context:0:50000}..."
-fi
-```
-
-### Handling Strings with Quotes in JSON Payloads
-
-**Problem:** Hook fails when context contains unescaped quotes.
-
-**Solution:** Use `jq --arg` for proper escaping:
-
-```bash
-#!/usr/bin/env bash
-# When $output contains unescaped quote characters (")...
-output='{"config": "value with "quotes""}'
-
-# WRONG - Will break JSON parsing
-echo '{"cancel": false, "contextModification": "OUTPUT: '"$output"'"}'
-
-# CORRECT - Use jq --arg for automatic escaping
-jq -n --arg ctx "OUTPUT: $output" '{"cancel": false, "contextModification": $ctx}'
-
-# Result:
-# {
-# "cancel": false,
-# "contextModification": "OUTPUT: {\"config\": \"value with \\\"quotes\\\"\"}"
-# }
-```
-
-**Complex Escaping Examples:**
-```bash
-#!/usr/bin/env bash
-# Handle multiple variables with special characters
-error_msg='Error: File "config.json" contains "invalid" syntax'
-file_path='/path/with spaces/and "quotes"/file.txt'
-suggestion='Use JSON.stringify() for "safe" output'
-
-# Combine multiple escaped arguments
-jq -n \
- --arg error "$error_msg" \
- --arg path "$file_path" \
- --arg suggest "$suggestion" \
- '{
- cancel: true,
- errorMessage: $error,
- contextModification: ("FILE_ERROR: " + $path + " - " + $suggest)
- }'
-```
-
-## Development Best Practices
-
-### Hook Development Workflow
-
-**1. Start with Simple Templates:**
-```bash
-#!/usr/bin/env bash
-# Basic hook template
-input=$(cat)
-
-# Validate input
-if ! echo "$input" | jq empty 2>/dev/null; then
- echo '{"cancel": false}'
- exit 0
-fi
-
-# Extract fields
-tool_name=$(echo "$input" | jq -r '.preToolUse.toolName // "unknown"')
-
-# Your logic here...
-
-# Always return valid JSON
-echo '{"cancel": false}'
-```
-
-**2. Add Error Handling:**
-```bash
-#!/usr/bin/env bash
-# Robust error handling
-set -o pipefail
-
-error_handler() {
- echo '{"cancel": false}' >&2
- exit 0
-}
-trap error_handler ERR
-
-# Your hook logic...
-```
-
-**3. Test Early and Often:**
-```bash
-# Create test data for your hook
-mkdir -p test-data
-echo '{"clineVersion": "1.0.0", ...}' > test-data/basic-test.json
-
-# Test your hook
-cat test-data/basic-test.json | .clinerules/hooks/YourHook
-```
-
-### Security Best Practices
-
-**1. Validate All Input:**
-```bash
-#!/usr/bin/env bash
-# Always validate JSON input
-input=$(cat)
-if ! echo "$input" | jq empty 2>/dev/null; then
- exit 0
-fi
-
-# Validate required fields exist
-if ! echo "$input" | jq -e '.taskId' >/dev/null; then
- exit 0
-fi
-```
-
-**2. Sanitize File Paths:**
-```bash
-#!/usr/bin/env bash
-file_path=$(echo "$input" | jq -r '.preToolUse.parameters.path // ""')
-
-# Prevent directory traversal
-if [[ "$file_path" == *".."* ]]; then
- echo '{"cancel": true, "errorMessage": "Invalid file path"}'
- exit 0
-fi
-
-# Ensure path is within workspace
-if [[ "$file_path" =~ ^/ ]]; then
- echo '{"cancel": true, "errorMessage": "Absolute paths not allowed"}'
- exit 0
-fi
-```
-
-**3. Limit Resource Usage:**
-```bash
-#!/usr/bin/env bash
-# Set resource limits
-ulimit -t 10 # 10 second CPU limit
-ulimit -v 104857600 # 100MB memory limit
-
-# Limit file operations
-max_files=100
-file_count=$(find . -name "*.js" | wc -l)
-if (( file_count > max_files )); then
- exit 0 # Skip processing for large projects
-fi
-```
-
-### Performance Optimization
-
-**1. Cache Expensive Operations:**
-```bash
-#!/usr/bin/env bash
-# Content-based caching
-content=$(echo "$input" | jq -r '.preToolUse.parameters.content // ""')
-cache_key=$(echo -n "$content" | sha256sum | cut -d' ' -f1)
-cache_file="$HOME/.cline_cache/lint_${cache_key:0:16}"
-
-if [[ -f "$cache_file" ]] && [[ $(find "$cache_file" -mmin -30) ]]; then
- cat "$cache_file"
- exit 0
-fi
-
-# Perform expensive operation
-result=$(expensive_lint_operation)
-echo "$result" | tee "$cache_file"
-```
-
-**2. Use Background Processing:**
-```bash
-#!/usr/bin/env bash
-# Queue expensive work for background processing
-if [[ "$tool_name" == "write_to_file" ]]; then
- # Queue for background analysis
- echo "$input" >> "$HOME/.cline_queue/analysis.queue"
-
- # Start background processor if needed
- pgrep -f "cline_background" > /dev/null || start_background_processor &
-fi
-
-# Return immediately
-echo '{"cancel": false}'
-```
-
-**3. Profile Hook Performance:**
-```bash
-#!/usr/bin/env bash
-# Built-in performance monitoring
-start_time=$(date +%s%N)
-
-# Your hook logic here...
-
-end_time=$(date +%s%N)
-execution_time=$(( (end_time - start_time) / 1000000 ))
-
-# Log slow operations
-if (( execution_time > 100 )); then
- echo "SLOW_HOOK: $(basename "$0") took ${execution_time}ms" >> "$HOME/.cline_perf.log"
-fi
-```
-
-### Maintenance and Monitoring
-
-**Hook Health Monitoring:**
-```bash
-#!/usr/bin/env bash
-# monitor-hooks.sh - Check hook health
-
-echo "Hook Health Report - $(date)"
-echo "=================================="
-
-for hook in .clinerules/hooks/*; do
- if [[ -f "$hook" && -x "$hook" ]]; then
- hook_name=$(basename "$hook")
-
- # Test basic functionality
- test_result=$(echo '{}' | "$hook" 2>&1)
- exit_code=$?
-
- if [[ $exit_code -eq 0 ]] && echo "$test_result" | jq empty 2>/dev/null; then
- echo "✅ $hook_name - OK"
- else
- echo "❌ $hook_name - FAILED (exit: $exit_code)"
- echo " Error: $test_result"
- fi
- fi
-done
-
-# Check for abandoned trace/cache files
-echo ""
-echo "Cleanup Recommendations:"
-find ~/.cline_* -type f -mtime +7 2>/dev/null | head -5 | while read file; do
- echo " Consider removing old file: $file"
-done
-```
-
-This comprehensive testing and debugging guide provides the tools and techniques needed to develop robust, reliable hooks. Remember to start simple, test thoroughly, and incrementally add complexity as you become more comfortable with the hook system.
-
-
-Always test hooks thoroughly in a development environment before deploying them to production workflows. Faulty hooks can block important operations and disrupt your development process.
-