feat: add claude code validation to pre-commit hook (#9177)

Co-authored-by: alejandrobailo <alejandrobailo94@gmail.com>
This commit is contained in:
Alan Buscaglia
2025-11-06 13:48:19 +01:00
committed by GitHub
parent edfef51e7a
commit 7bbc0d8e1b
6 changed files with 786 additions and 3 deletions

9
.env
View File

@@ -14,7 +14,11 @@ UI_PORT=3000
AUTH_SECRET="N/c6mnaS5+SWq81+819OrzQZlmx1Vxtp/orjttJSmw8=" AUTH_SECRET="N/c6mnaS5+SWq81+819OrzQZlmx1Vxtp/orjttJSmw8="
# Google Tag Manager ID # Google Tag Manager ID
NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID="" NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID=""
#### Code Review Configuration ####
# Enable Claude Code standards validation on pre-push hook
# Set to 'true' to validate changes against AGENTS.md standards via Claude Code
# Set to 'false' to skip validation
CODE_REVIEW_ENABLED=true
#### Prowler API Configuration #### #### Prowler API Configuration ####
PROWLER_API_VERSION="stable" PROWLER_API_VERSION="stable"
@@ -132,4 +136,5 @@ LANGCHAIN_PROJECT=""
# Example with one source: # Example with one source:
RSS_FEED_SOURCES='[{"id":"prowler-releases","name":"Prowler Releases","type":"github_releases","url":"https://github.com/prowler-cloud/prowler/releases.atom","enabled":true}]' RSS_FEED_SOURCES='[{"id":"prowler-releases","name":"Prowler Releases","type":"github_releases","url":"https://github.com/prowler-cloud/prowler/releases.atom","enabled":true}]'
# Example with multiple sources (no trailing comma after last item): # Example with multiple sources (no trailing comma after last item):
# RSS_FEED_SOURCES='[{"id":"prowler-releases","name":"Prowler Releases","type":"github_releases","url":"https://github.com/prowler-cloud/prowler/releases.atom","enabled":true},{"id":"prowler-blog","name":"Prowler Blog","type":"blog","url":"https://prowler.com/blog/rss","enabled":false}]' # RSS_FEED_SOURCES='[{"id":"prowler-releases","name":"Prowler Releases","type":"github_releases","url":"https://github.com/prowler-cloud/prowler/releases.atom","enabled":true},{"id":"prowler-blog","name":"Prowler Blog","type":"blog","url":"https://prowler.com/blog/rss","enabled":false}]'

View File

@@ -22,6 +22,13 @@ Please add a detailed description of how to review this PR.
- [ ] Review if is needed to change the [Readme.md](https://github.com/prowler-cloud/prowler/blob/master/README.md) - [ ] Review if is needed to change the [Readme.md](https://github.com/prowler-cloud/prowler/blob/master/README.md)
- [ ] Ensure new entries are added to [CHANGELOG.md](https://github.com/prowler-cloud/prowler/blob/master/prowler/CHANGELOG.md), if applicable. - [ ] Ensure new entries are added to [CHANGELOG.md](https://github.com/prowler-cloud/prowler/blob/master/prowler/CHANGELOG.md), if applicable.
#### UI
- [ ] All issue/task requirements work as expected on the UI
- [ ] Screenshots/Video of the functionality flow (if applicable) - Mobile (X < 640px)
- [ ] Screenshots/Video of the functionality flow (if applicable) - Table (640px > X < 1024px)
- [ ] Screenshots/Video of the functionality flow (if applicable) - Desktop (X > 1024px)
- [ ] Ensure new entries are added to [CHANGELOG.md](https://github.com/prowler-cloud/prowler/blob/master/ui/CHANGELOG.md), if applicable.
#### API #### API
- [ ] Verify if API specs need to be regenerated. - [ ] Verify if API specs need to be regenerated.
- [ ] Check if version updates are required (e.g., specs, Poetry, etc.). - [ ] Check if version updates are required (e.g., specs, Poetry, etc.).

121
ui/.husky/pre-commit Normal file → Executable file
View File

@@ -1 +1,120 @@
npm run healthcheck #!/bin/bash
# Prowler UI - Pre-Commit Hook
# Optionally validates ONLY staged files against AGENTS.md standards using Claude Code
# Controlled by CODE_REVIEW_ENABLED in .env
set -e
# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🚀 Prowler UI - Pre-Commit Hook"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
# Load .env file (look in git root directory)
GIT_ROOT=$(git rev-parse --show-toplevel)
if [ -f "$GIT_ROOT/ui/.env" ]; then
CODE_REVIEW_ENABLED=$(grep "^CODE_REVIEW_ENABLED" "$GIT_ROOT/ui/.env" | cut -d'=' -f2 | tr -d ' ')
elif [ -f "$GIT_ROOT/.env" ]; then
CODE_REVIEW_ENABLED=$(grep "^CODE_REVIEW_ENABLED" "$GIT_ROOT/.env" | cut -d'=' -f2 | tr -d ' ')
elif [ -f ".env" ]; then
CODE_REVIEW_ENABLED=$(grep "^CODE_REVIEW_ENABLED" .env | cut -d'=' -f2 | tr -d ' ')
else
CODE_REVIEW_ENABLED="false"
fi
# Normalize the value to lowercase
CODE_REVIEW_ENABLED=$(echo "$CODE_REVIEW_ENABLED" | tr '[:upper:]' '[:lower:]')
echo -e "${BLUE} Code Review Status: ${CODE_REVIEW_ENABLED}${NC}"
echo ""
# Get staged files (what will be committed)
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(tsx?|jsx?)$' || true)
if [ "$CODE_REVIEW_ENABLED" = "true" ]; then
if [ -z "$STAGED_FILES" ]; then
echo -e "${YELLOW}⚠️ No TypeScript/JavaScript files staged to validate${NC}"
echo ""
else
echo -e "${YELLOW}🔍 Running Claude Code standards validation...${NC}"
echo ""
echo -e "${BLUE}📋 Files to validate:${NC}"
echo "$STAGED_FILES" | sed 's/^/ - /'
echo ""
echo -e "${BLUE}📤 Sending to Claude Code for validation...${NC}"
echo ""
# Build prompt with git diff of changes
VALIDATION_PROMPT=$(
cat <<'PROMPT_EOF'
You are a code reviewer for the Prowler UI project. Analyze the code changes (git diff) below and validate they comply with AGENTS.md standards.
**RULES TO CHECK:**
1. React Imports: NO `import * as React` or `import React, {` → Use `import { useState }`
2. TypeScript: NO union types like `type X = "a" | "b"` → Use const-based: `const X = {...} as const`
3. Tailwind: NO `var()` or hex colors in className → Use `className="bg-card-bg"`
4. cn(): ONLY for conditionals → NOT for static classes
5. React 19: NO `useMemo`/`useCallback` without reason
6. Zod v4: Use `.min(1)` not `.nonempty()`, `z.email()` not `z.string().email()`. All inputs must be validated with Zod.
7. File Org: 1 feature = local, 2+ features = shared
8. Directives: Server Actions need "use server", clients need "use client"
9. Implement DRY, KISS principles. (example: reusable components, avoid repetition)
10. Layout must work for all the responsive breakpoints (mobile, tablet, desktop)
11. ANY types cannot be used
12. Use the components inside components/shadcn if possible
13. Check Accessibility best practices (like alt tags in images, semantic HTML, Aria labels, etc.)
=== GIT DIFF OF CHANGES ===
PROMPT_EOF
)
# Add git diff to prompt (shows only actual changes)
VALIDATION_PROMPT="$VALIDATION_PROMPT
$(git diff --cached -U0)"
VALIDATION_PROMPT="$VALIDATION_PROMPT
=== END DIFF ===
**RESPOND WITH:**
STATUS: [PASSED | FAILED]
[If FAILED: list violations with File, Rule, Issue, and line reference]
[If PASSED: confirm all changes comply with AGENTS.md standards]"
# Send to Claude Code
if VALIDATION_OUTPUT=$(echo "$VALIDATION_PROMPT" | claude 2>&1); then
echo "$VALIDATION_OUTPUT"
echo ""
# Check result
if echo "$VALIDATION_OUTPUT" | grep -q "^STATUS: PASSED"; then
echo -e "${GREEN}✅ VALIDATION PASSED${NC}"
elif echo "$VALIDATION_OUTPUT" | grep -q "^STATUS: FAILED"; then
echo ""
echo -e "${RED}❌ VALIDATION FAILED${NC}"
echo -e "${RED}Fix violations before committing${NC}"
echo ""
exit 1
else
echo -e "${YELLOW}⚠️ Could not determine validation status${NC}"
echo "Continuing (validation inconclusive)"
fi
else
echo -e "${YELLOW}⚠️ Claude Code not available${NC}"
fi
echo ""
fi
else
echo -e "${YELLOW}⏭️ Code review disabled (CODE_REVIEW_ENABLED=false)${NC}"
echo ""
fi

View File

@@ -0,0 +1,115 @@
# Code Review - Quick Start
## 3 Steps to Enable
### 1. Open `.env`
```bash
nano ui/.env
# or your favorite editor
```
### 2. Find this line
```bash
CODE_REVIEW_ENABLED=false
```
### 3. Change it to
```bash
CODE_REVIEW_ENABLED=true
```
**Done! ✅**
---
## What Happens Now
Every time you `git commit`:
```
✅ If your code complies with AGENTS.md standards:
→ Commit executes normally
❌ If there are standard violations:
→ Commit is BLOCKED
→ You see the errors in the terminal
→ Fix the code
→ Commit again
```
---
## Example
```bash
$ git commit -m "feat: add new component"
🏁 Prowler UI - Pre-Commit Hook
Code Review Status: true
🔍 Running Claude Code standards validation...
📋 Files to validate:
- components/my-feature.tsx
📤 Sending to Claude Code for validation...
STATUS: FAILED
- File: components/my-feature.tsx:45
Rule: React Imports
Issue: Using 'import * as React'
Expected: import { useState } from "react"
❌ VALIDATION FAILED
Fix violations before committing
# Fix the file and commit again
$ git commit -m "feat: add new component"
🏁 Prowler UI - Pre-Commit Hook
Code Review Status: true
🔍 Running Claude Code standards validation...
✅ VALIDATION PASSED
# Commit successful ✅
```
---
## Disable Temporarily
If you need to commit without validation:
```bash
# Option 1: Change in .env
CODE_REVIEW_ENABLED=false
# Option 2: Bypass (use with caution!)
git commit --no-verify
```
---
## What Gets Validated
- ✅ Correct React imports
- ✅ TypeScript patterns (const-based types)
- ✅ Tailwind CSS (no var() or hex in className)
- ✅ cn() utility (only for conditionals)
- ✅ No useMemo/useCallback without reason
- ✅ Zod v4 syntax
- ✅ File organization
- ✅ Directives "use client"/"use server"
---
## More Info
Read `CODE_REVIEW_SETUP.md` for:
- Troubleshooting
- Complete details
- Advanced configuration

View File

@@ -0,0 +1,296 @@
# Code Review Setup - Prowler UI
Guide to set up automatic code validation with Claude Code in the pre-commit hook.
## Overview
The code review system works like this:
1. **When you enable `CODE_REVIEW_ENABLED=true` in `.env`**
- When you `git commit`, the pre-commit hook runs
- Only validates TypeScript/JavaScript files you're committing
- Uses Claude Code to check if they comply with AGENTS.md
- If there are violations → **BLOCKS the commit**
- If everything is fine → Continues normally
2. **When `CODE_REVIEW_ENABLED=false` (default)**
- The pre-commit hook does not run validation
- No standards validation
- Developers can commit without restrictions
## Installation
### 1. Ensure Claude Code is in your PATH
```bash
# Verify that claude is available in terminal
which claude
# If it doesn't appear, check your Claude Code CLI installation
```
### 2. Enable validation in `.env`
In `/ui/.env`, find the "Code Review Configuration" section:
```bash
#### Code Review Configuration ####
# Enable Claude Code standards validation on pre-commit hook
# Set to 'true' to validate changes against AGENTS.md standards via Claude Code
# Set to 'false' to skip validation
CODE_REVIEW_ENABLED=false # ← Change this to 'true'
```
**Options:**
- `CODE_REVIEW_ENABLED=true` → Enables validation
- `CODE_REVIEW_ENABLED=false` → Disables validation (default)
### 3. The hook is ready
The `.husky/pre-commit` file already contains the logic. You don't need to install anything else.
## How It Works
### Normal Flow (with validation enabled)
```bash
$ git commit -m "feat: add new component"
# Pre-commit hook executes automatically
🚀 Prowler UI - Pre-Commit Hook
Code Review Status: true
📋 Files to validate:
- components/new-feature.tsx
- types/new-feature.ts
📤 Sending to Claude Code for validation...
# Claude analyzes the files...
=== VALIDATION REPORT ===
STATUS: PASSED
All files comply with AGENTS.md standards.
✅ VALIDATION PASSED
# Commit continues ✅
```
### If There Are Violations
```bash
$ git commit -m "feat: add new component"
# Claude detects issues...
=== VALIDATION REPORT ===
STATUS: FAILED
- File: components/new-feature.tsx:15
Rule: React Imports
Issue: Using 'import * as React' instead of named imports
Expected: import { useState } from "react"
❌ VALIDATION FAILED
Please fix the violations before committing:
1. Review the violations listed above
2. Fix the code according to AGENTS.md standards
3. Commit your changes
4. Try again
# Commit is BLOCKED ❌
```
## What Gets Validated
The system verifies that files comply with:
### 1. React Imports
```typescript
// ❌ WRONG
import * as React from "react"
import React, { useState } from "react"
// ✅ CORRECT
import { useState } from "react"
```
### 2. TypeScript Type Patterns
```typescript
// ❌ WRONG
type SortOption = "high-low" | "low-high"
// ✅ CORRECT
const SORT_OPTIONS = {
HIGH_LOW: "high-low",
LOW_HIGH: "low-high",
} as const
type SortOption = typeof SORT_OPTIONS[keyof typeof SORT_OPTIONS]
```
### 3. Tailwind CSS
```typescript
// ❌ WRONG
className="bg-[var(--color)]"
className="text-[#ffffff]"
// ✅ CORRECT
className="bg-card-bg text-white"
```
### 4. cn() Utility
```typescript
// ❌ WRONG
className={cn("flex items-center")}
// ✅ CORRECT
className={cn("h-3 w-3", isCircle ? "rounded-full" : "rounded-sm")}
```
### 5. React 19 Hooks
```typescript
// ❌ WRONG
const memoized = useMemo(() => value, [])
// ✅ CORRECT
// Don't use useMemo (React Compiler handles it)
const value = expensiveCalculation()
```
### 6. Zod v4 Syntax
```typescript
// ❌ WRONG
z.string().email()
z.string().nonempty()
// ✅ CORRECT
z.email()
z.string().min(1)
```
### 7. File Organization
```
// ❌ WRONG
Code used by 2+ features in feature-specific folder
// ✅ CORRECT
Code used by 1 feature → local in that feature
Code used by 2+ features → in shared/global
```
### 8. Use Directives
```typescript
// ❌ WRONG
export async function updateUser() { } // Missing "use server"
// ✅ CORRECT
"use server"
export async function updateUser() { }
```
## Disable Temporarily
If you need to commit without validation temporarily:
```bash
# Option 1: Change in .env
CODE_REVIEW_ENABLED=false
git commit
# Option 2: Use git hook bypass
git commit --no-verify
# Option 3: Disable the hook
chmod -x .husky/pre-commit
git commit
chmod +x .husky/pre-commit
```
**⚠️ Note:** `--no-verify` skips ALL hooks.
## Troubleshooting
### "Claude Code CLI not found"
```
⚠️ Claude Code CLI not found in PATH
To enable: ensure Claude Code is in PATH and CODE_REVIEW_ENABLED=true
```
**Solution:**
```bash
# Check where claude-code is installed
which claude-code
# If not found, add to your ~/.zshrc:
export PATH="$HOME/.local/bin:$PATH" # or where it's installed
# Reload the terminal
source ~/.zshrc
```
### "Validation inconclusive"
If Claude Code cannot determine the status:
```
⚠️ Could not determine validation status
Allowing commit (validation inconclusive)
```
The commit is allowed automatically. If you want to be stricter, you can:
1. Manually review files against AGENTS.md
2. Report the analysis problem to Claude
### Build fails after validation
```
❌ Build failed
```
If validation passes but build fails:
1. Check the build error
2. Fix it locally
3. Commit and try again
## View the Full Report
Reports are saved in temporary files that are deleted afterward. To see the detailed report in real-time, watch the hook output:
```bash
git commit 2>&1 | tee commit-report.txt
```
This will save everything to `commit-report.txt`.
## For the Team
### Enable on your machine
```bash
cd ui
# Edit .env locally and set:
CODE_REVIEW_ENABLED=true
```
### Recommended Flow
1. **During development**: `CODE_REVIEW_ENABLED=false`
- Iterate faster
- Build check still runs
2. **Before final commit**: `CODE_REVIEW_ENABLED=true`
- Verify you meet standards
- Prevent PRs rejected for violations
3. **In CI/CD**: You could add additional validation
- (future) Server-side validation in GitHub Actions
## Questions?
If you have questions about the standards being validated, check:
- `AGENTS.md` - Complete architecture guide
- `CLAUDE.md` - Project-specific instructions

View File

@@ -0,0 +1,241 @@
# Code Review System Documentation
Complete documentation for the Claude Code-powered pre-commit validation system.
## Quick Navigation
**Want to get started in 3 steps?**
→ Read: [`CODE_REVIEW_QUICK_START.md`](./CODE_REVIEW_QUICK_START.md)
**Want complete technical details?**
→ Read: [`CODE_REVIEW_SETUP.md`](./CODE_REVIEW_SETUP.md)
---
## What This System Does
Automatically validates code against AGENTS.md standards when you commit using Claude Code.
```
git commit
(Optional) Claude Code validation
If violations found → Commit is BLOCKED ❌
If code complies → Commit continues ✅
```
**Key Feature:** Configurable with a single variable in `.env`
- `CODE_REVIEW_ENABLED=true` → Validates (recommended before commits)
- `CODE_REVIEW_ENABLED=false` → Skip validation (default, for iteration)
---
## File Guide
| File | Purpose | Read Time |
|------|---------|-----------|
| [`CODE_REVIEW_QUICK_START.md`](./CODE_REVIEW_QUICK_START.md) | 3-step setup & examples | 5 min |
| [`CODE_REVIEW_SETUP.md`](./CODE_REVIEW_SETUP.md) | Complete technical guide | 15 min |
---
## What Gets Validated
When validation is enabled, the system checks:
**React Imports**
- Must use: `import { useState } from "react"`
- Not: `import * as React` or `import React, {`
**TypeScript Types**
- Must use: `const STATUS = {...} as const; type Status = typeof STATUS[...]`
- Not: `type Status = "a" | "b"`
**Tailwind CSS**
- Must use: `className="bg-card-bg text-white"`
- Not: `className="bg-[var(...)]"` or `className="text-[#fff]"`
**cn() Utility**
- Must use for: `cn("h-3", isActive && "bg-blue")`
- Not for: `cn("static-class")`
**React 19 Hooks**
- No: `useMemo()` / `useCallback()` without documented reason
- Use: Nothing (React Compiler handles optimization)
**Zod v4 Syntax**
- Must use: `z.email()`, `.min(1)`
- Not: `z.string().email()`, `.nonempty()`
**File Organization**
- 1 feature uses → Keep local in feature folder
- 2+ features use → Move to shared/global
**Directives**
- Server Actions must have: `"use server"`
- Client Components must have: `"use client"`
---
## Installation (For Your Team)
### Step 1: Decide if you want validation
- **Optional:** Each developer decides
- **Team policy:** Consider making it standard before commits
### Step 2: Enable in your environment
```bash
# Edit ui/.env
CODE_REVIEW_ENABLED=true
```
### Step 3: Done!
Your next `git commit` will validate automatically.
---
## Support
| Question | Answer |
|----------|--------|
| How do I enable it? | Change `CODE_REVIEW_ENABLED=true` in `.env` |
| How do I disable it? | Change `CODE_REVIEW_ENABLED=false` in `.env` |
| How do I bypass? | Use `git commit --no-verify` (emergency only) |
| What if Claude Code isn't found? | Check PATH: `which claude` |
| What if hook doesn't run? | Check executable: `chmod +x .husky/pre-commit` |
| How do I test it? | Enable validation and commit code with violations to test |
| What if I don't have Claude Code? | Validation is skipped gracefully |
---
## Key Features
**No Setup Required**
- Uses Claude Code already in your PATH
- No API keys needed
- Works offline (if Claude Code supports it)
**Smart Validation**
- Only checks files being committed
- Not the entire codebase
- Fast: ~10-30 seconds with validation enabled
**Flexible**
- Can be enabled/disabled per developer
- Can be disabled temporarily with `git commit --no-verify`
- Default is disabled (doesn't interrupt workflow)
**Clear Feedback**
- Shows exactly what violates standards
- Shows file:line references
- Explains how to fix each issue
**Well Documented**
- 5 different documentation files
- For different needs and levels
- Examples and troubleshooting included
---
## Architecture
```
┌─────────────────────────────────────────┐
│ Developer commits code │
└────────────────┬────────────────────────┘
┌─────────────────┐
│ Pre-Commit Hook │
│ (.husky/pre-commit)
└────────┬────────┘
Read CODE_REVIEW_ENABLED from .env
┌──────────────────────────┐
│ If false (disabled) │
└────────┬─────────────────┘
exit 0 (OK)
Commit continues ✅
┌──────────────────────────┐
│ If true (enabled) │
└────────┬─────────────────┘
Extract staged files
(git diff --cached)
Build prompt with git diff
Send to: claude < prompt
Analyze against AGENTS.md
Return: STATUS: PASSED or FAILED
Parse with: grep "^STATUS:"
┌──────────────────┐
│ PASSED detected │
└────────┬─────────┘
exit 0 (OK)
Commit continues ✅
┌──────────────────┐
│ FAILED detected │
└────────┬─────────┘
Show violations
exit 1 (FAIL)
Commit is BLOCKED ❌
Developer fixes code
Developer commits again
```
---
## Getting Started
1. **Read:** [`CODE_REVIEW_QUICK_START.md`](./CODE_REVIEW_QUICK_START.md) (5 minutes)
2. **Enable:** Set `CODE_REVIEW_ENABLED=true` in your `ui/.env`
3. **Test:** Commit some code and see validation in action
4. **For help:** See the troubleshooting section in [`CODE_REVIEW_SETUP.md`](./CODE_REVIEW_SETUP.md)
---
## Implementation Details
- **Files Modified:** 1 (`.husky/pre-commit`)
- **Files Created:** 3 (documentation)
- **Hook Size:** ~120 lines of bash
- **Dependencies:** Claude Code CLI (already available)
- **Setup Time:** 1 minute
- **Default:** Disabled (no workflow interruption)
---
## Questions?
- **How to enable?** → `CODE_REVIEW_QUICK_START.md`
- **How does it work?** → `CODE_REVIEW_SETUP.md`
- **Troubleshooting?** → See troubleshooting section in `CODE_REVIEW_SETUP.md`
---
## Status
**Ready to Use**
The system is fully implemented, documented, and tested. You can enable it immediately with a single variable change.
---
**Last Updated:** November 6, 2024
**Status:** Complete Implementation