- Added a new QualityConfig class to manage test quality check configurations. - Implemented test quality checks for specific rules in test files, including prevention of conditionals, loops, and generic exceptions. - Integrated external context providers (Context7 and Firecrawl) for additional guidance on test quality violations. - Enhanced error messaging to provide detailed, actionable guidance for detected issues. - Updated README_HOOKS.md to document new test quality features and configuration options. - Added unit tests to verify the functionality of test quality checks and their integration with the pretooluse_hook.
Claude Code Quality Guard Hook
A comprehensive code quality enforcement system for Claude Code that prevents writing duplicate, complex, or non-modernized Python code.
Features
PreToolUse Analysis
Analyzes code before it's written to prevent quality issues:
- Internal Duplicate Detection: Detects duplicate code blocks within the same file using AST analysis
- Complexity Analysis: Measures cyclomatic complexity and flags overly complex functions
- Modernization Checks: Identifies outdated Python patterns and missing type hints
- Configurable Enforcement: Strict (deny), Warn (ask), or Permissive (allow with warning) modes
PostToolUse Verification
Verifies code after it's written to track quality:
- State Tracking: Detects quality degradation between edits
- Cross-File Duplicates: Finds duplicates across the entire codebase
- Naming Conventions: Verifies PEP8 naming standards
- Success Feedback: Optional success messages for clean code
Installation
Global Setup (Recommended)
Run the setup script to install the hook globally for all projects in ~/repos:
cd ~/repos/claude-scripts
./setup_global_hook.sh
This creates:
- Global Claude Code configuration at
~/.claude/claude-code-settings.json - Configuration helper at
~/.claude/configure-quality.sh - Convenience alias
claude-qualityin your shell
Quick Configuration
After installation, use the claude-quality command:
# Apply presets
claude-quality strict # Strict enforcement
claude-quality moderate # Moderate with warnings
claude-quality permissive # Permissive suggestions
claude-quality disabled # Disable all checks
# Check current settings
claude-quality status
Per-Project Setup
Alternatively, copy the configuration to a specific project:
cp hooks/claude-code-settings.json /path/to/project/
Configuration
Environment Variables
| Variable | Description | Default |
|---|---|---|
QUALITY_ENFORCEMENT |
Mode: strict/warn/permissive | strict |
QUALITY_COMPLEXITY_THRESHOLD |
Max cyclomatic complexity | 10 |
QUALITY_DUP_THRESHOLD |
Duplicate similarity (0-1) | 0.7 |
QUALITY_DUP_ENABLED |
Enable duplicate detection | true |
QUALITY_COMPLEXITY_ENABLED |
Enable complexity checks | true |
QUALITY_MODERN_ENABLED |
Enable modernization | true |
QUALITY_TYPE_HINTS |
Require type hints | false |
QUALITY_STATE_TRACKING |
Track file changes | true |
QUALITY_CROSS_FILE_CHECK |
Cross-file duplicates | true |
QUALITY_VERIFY_NAMING |
Check PEP8 naming | true |
QUALITY_SHOW_SUCCESS |
Show success messages | false |
Per-Project Overrides
Create a .quality.env file in your project root:
# .quality.env
QUALITY_ENFORCEMENT=moderate
QUALITY_COMPLEXITY_THRESHOLD=15
QUALITY_TYPE_HINTS=true
Then source it: source .quality.env
How It Works
Internal Duplicate Detection
The hook uses AST analysis to detect three types of duplicates within files:
- Exact Duplicates: Identical code blocks
- Structural Duplicates: Same AST structure, different names
- Semantic Duplicates: Similar logic patterns
Enforcement Modes
- Strict: Blocks (denies) code that fails quality checks
- Warn: Asks for user confirmation on quality issues
- Permissive: Allows code but shows warnings
State Tracking
Tracks quality metrics between edits to detect:
- Reduction in functions/classes
- Significant file size increases
- Quality degradation trends
Testing
The hook comes with a comprehensive test suite:
# Run all tests
pytest tests/hooks/
# Run specific test modules
pytest tests/hooks/test_pretooluse.py
pytest tests/hooks/test_posttooluse.py
pytest tests/hooks/test_edge_cases.py
pytest tests/hooks/test_integration.py
# Run with coverage
pytest tests/hooks/ --cov=hooks
Test Coverage
- 90 tests covering all functionality
- Edge cases and error handling
- Integration testing with Claude Code
- Concurrent access and thread safety
Architecture
code_quality_guard.py # Main hook implementation
├── QualityConfig # Configuration management
├── pretooluse_hook() # Pre-write analysis
├── posttooluse_hook() # Post-write verification
└── analyze_code_quality() # Quality analysis engine
internal_duplicate_detector.py # AST-based duplicate detection
├── InternalDuplicateDetector # Main detector class
├── extract_code_blocks() # AST traversal
└── find_duplicates() # Similarity algorithms
claude-code-settings.json # Hook configuration
└── Maps both hooks to same script
Examples
Detecting Internal Duplicates
# This would be flagged as duplicate
def calculate_tax(amount):
tax = amount * 0.1
total = amount + tax
return total
def calculate_fee(amount): # Duplicate!
fee = amount * 0.1
total = amount + fee
return total
Complexity Issues
# This would be flagged as too complex (CC > 10)
def process_data(data):
if data:
if data.type == 'A':
if data.value > 100:
# ... nested logic
Modernization Suggestions
# Outdated patterns that would be flagged
d = dict() # Use {} instead
if x == None: # Use 'is None'
for i in range(len(items)): # Use enumerate
Troubleshooting
Hook Not Working
- Verify installation:
ls ~/.claude/claude-code-settings.json - Check Python:
python --version(requires 3.8+) - Test directly:
echo '{"tool_name":"Read"}' | python hooks/code_quality_guard.py - Check claude-quality binary:
which claude-quality
False Positives
- Adjust thresholds via environment variables
- Use
.quality-exceptions.yamlfor suppressions - Switch to permissive mode for legacy code
Performance Issues
- Disable cross-file checks:
QUALITY_CROSS_FILE_CHECK=false - Increase thresholds for large files
- Use skip patterns for generated code
Development
Adding New Checks
- Add analysis logic to
analyze_code_quality() - Add issue detection to
check_code_issues() - Add configuration to
QualityConfig - Add tests to appropriate test module
Contributing
- Run tests:
pytest tests/hooks/ - Check types:
mypy hooks/ - Format code:
ruff format hooks/ - Submit PR with tests
License
Part of the Claude Scripts project. See main LICENSE file.