Skip to content
Shell
6.5 KB
Raw Blame
#!/bin/bash
# ============================================================================
# CODE REVIEW GATE - "The Gatekeeper"
# ============================================================================
# A blocking code review hook for Claude Code that enforces quality standards
# before allowing code changes to proceed.
#
# Part of: ID8Pipeline Quality Enforcement System
# Author: ID8Labs
# Version: 1.0.0
#
# BLOCKING ISSUES (exit 2):
#   - CRITICAL: Hardcoded secrets, API keys, passwords
#   - ERROR: Type errors, syntax errors
#   - WARNING: Lint violations, type hint issues
#
# NON-BLOCKING (exit 0 with warning):
#   - INFO: console.log statements, large files, TODOs
#
# Usage: Triggered automatically via PostToolUse hook on Edit|Write
# ============================================================================

set -uo pipefail
# Note: not using -e because we want to continue after grep failures

# Read input from stdin (Claude Code hook format)
INPUT=$(cat)

# Extract file path from tool input
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // empty' 2>/dev/null)

# If no file path, try to get from positional arg (legacy format)
if [[ -z "$FILE_PATH" ]]; then
    FILE_PATH="${1:-}"
fi

# Exit if still no file path
if [[ -z "$FILE_PATH" || ! -f "$FILE_PATH" ]]; then
    exit 0
fi

# Get file extension
FILE_EXT="${FILE_PATH##*.}"

# Skip non-code files
case "$FILE_EXT" in
    md|txt|json|yaml|yml|env|gitignore|lock|log|css|scss|svg|png|jpg|jpeg|gif|ico|woff|woff2|ttf|eot)
        exit 0
        ;;
esac

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log() { echo -e "${BLUE}[CODE-REVIEW]${NC} $1"; }
warn() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
error() { echo -e "${RED}[ERROR]${NC} $1"; }
pass() { echo -e "${GREEN}[PASS]${NC} $1"; }

BLOCKING_ISSUES=0
INFO_ISSUES=0
REVIEW_REPORT=""

# Function to add issue to report
add_issue() {
    local severity="$1"
    local message="$2"
    REVIEW_REPORT="${REVIEW_REPORT}\n- [$severity] $message"

    # Only CRITICAL, ERROR, WARNING are blocking
    if [[ "$severity" == "CRITICAL" || "$severity" == "ERROR" || "$severity" == "WARNING" ]]; then
        BLOCKING_ISSUES=$((BLOCKING_ISSUES + 1))
    else
        INFO_ISSUES=$((INFO_ISSUES + 1))
    fi
}

log "Reviewing: $FILE_PATH"

# ==========================================
# 1. STATIC ANALYSIS CHECKS
# ==========================================

# TypeScript/JavaScript
if [[ "$FILE_EXT" == "ts" || "$FILE_EXT" == "tsx" || "$FILE_EXT" == "js" || "$FILE_EXT" == "jsx" ]]; then

    # Type check
    if [[ -f "tsconfig.json" ]] && command -v npx &> /dev/null; then
        if ! npx tsc --noEmit --skipLibCheck 2>&1 | head -5 | grep -q "error"; then
            pass "TypeScript: No type errors"
        else
            add_issue "ERROR" "TypeScript type errors detected"
        fi
    fi

    # ESLint
    if [[ -f ".eslintrc.json" || -f ".eslintrc.js" || -f "eslint.config.js" || -f "eslint.config.mjs" ]]; then
        if npx eslint "$FILE_PATH" --max-warnings 0 2>/dev/null; then
            pass "ESLint: Clean"
        else
            add_issue "WARNING" "ESLint issues in $FILE_PATH"
        fi
    fi
fi

# Python
if [[ "$FILE_EXT" == "py" ]]; then
    # Syntax check
    if python3 -m py_compile "$FILE_PATH" 2>/dev/null; then
        pass "Python: Syntax valid"
    else
        add_issue "ERROR" "Python syntax error in $FILE_PATH"
    fi

    # Type hints (if mypy available)
    if command -v mypy &> /dev/null; then
        if mypy "$FILE_PATH" --ignore-missing-imports 2>/dev/null; then
            pass "Mypy: Type hints valid"
        else
            add_issue "WARNING" "Type hint issues in $FILE_PATH"
        fi
    fi
fi

# ==========================================
# 2. SECURITY QUICK SCAN
# ==========================================

# Check for hardcoded secrets patterns
SECRET_PATTERNS="password\s*=\s*['\"][^'\"]+['\"]|api[_-]?key\s*=\s*['\"][^'\"]+['\"]|secret\s*=\s*['\"][^'\"]+['\"]|token\s*=\s*['\"][A-Za-z0-9]+"

if grep -iEq "$SECRET_PATTERNS" "$FILE_PATH" 2>/dev/null; then
    add_issue "CRITICAL" "Potential hardcoded secrets detected!"
fi

# Check for console.log in production code (not test files, not scripts)
if [[ "$FILE_PATH" != *"test"* && "$FILE_PATH" != *"spec"* && "$FILE_EXT" != "sh" ]]; then
    if [[ "$FILE_EXT" == "ts" || "$FILE_EXT" == "tsx" || "$FILE_EXT" == "js" || "$FILE_EXT" == "jsx" ]]; then
        if grep -q "console\.log\|console\.debug" "$FILE_PATH" 2>/dev/null; then
            add_issue "INFO" "console.log statements found (remove for production)"
        fi
    fi
fi

# ==========================================
# 3. CODE QUALITY PATTERNS
# ==========================================

# Check for TODO/FIXME comments (informational)
if grep -qE "TODO|FIXME|HACK|XXX" "$FILE_PATH" 2>/dev/null; then
    TODO_COUNT=$(grep -cE "TODO|FIXME|HACK|XXX" "$FILE_PATH" 2>/dev/null || echo "0")
    warn "Found $TODO_COUNT TODO/FIXME comments"
fi

# Check file size (large files may need refactoring)
LINE_COUNT=$(wc -l < "$FILE_PATH" | tr -d ' ')
if [[ $LINE_COUNT -gt 500 ]]; then
    add_issue "INFO" "Large file ($LINE_COUNT lines) - consider splitting"
fi

# ==========================================
# 4. OUTPUT REVIEW REPORT
# ==========================================

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "CODE REVIEW GATE: $FILE_PATH"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

TOTAL_ISSUES=$((BLOCKING_ISSUES + INFO_ISSUES))

if [[ $TOTAL_ISSUES -eq 0 ]]; then
    pass "All automated checks passed!"
    echo ""
    echo "✅ Ready for next pipeline stage"
    exit 0
elif [[ $BLOCKING_ISSUES -eq 0 ]]; then
    # Only INFO issues - warn but don't block
    warn "Found $INFO_ISSUES informational issue(s):"
    echo -e "$REVIEW_REPORT"
    echo ""
    echo "ℹ️  Non-blocking issues noted. Proceeding..."
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    exit 0
else
    error "Found $BLOCKING_ISSUES blocking issue(s):"
    echo -e "$REVIEW_REPORT"
    echo ""
    echo "🛑 BLOCKING: Fix these issues before proceeding"
    echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

    # Exit code 2 = blocking error (Claude sees stderr and must fix before continuing)
    exit 2
fi