A modern replacement for pre-commit with intelligent code analysis. Built in Rust for performance and reliability.
smart-hooks provides intelligent code analysis with seamless prek integration. Works perfectly standalone or as an enhanced layer over prek v0.2.20, combining enterprise-grade pre-commit infrastructure with AI-powered analysis.
- Smart dependency analysis - Only runs tests affected by your changes
- Configurable pattern matching - Customize test selection rules for your project
- Three-tier analysis: Configuration β Static Analysis β Claude AI
- Semantic tag mapping - File patterns β cucumber tags (
@business-logic,@api,@workflow) - Automatic command generation - Ready-to-run cucumber commands
- Targeted test execution - Run only relevant BDD scenarios
- Modular design - 11 focused modules following Single Responsibility Principle
- Structural pattern recognition - Based on software architecture, not business domain
- Comprehensive testing - 227 tests with 78 new inline unit tests
- Fully configurable - No hard-coded business logic
- Reusable across projects - Works for any Rust project structure
- Semantic code analysis - Understands code intent, not just syntax
- Intelligent feature selection - Maps changes to behavioral requirements
- Graceful fallback - Works with or without Claude CLI
- Seamless integration - Works with prek v0.2.20 stable
- Zero coupling - No dependencies, perfect standalone operation
- Intelligent delegation - Auto-detects prek and enhances with smart analysis
- Enterprise ready - Production-grade pre-commit infrastructure when needed
Get started in 2 minutes with verified installation:
# 1. Install both tools (tested on macOS)
cargo install smart-hooks prek@0.2.20
# 2. Verify installation
smart-hooks --version # Should show: smart-hooks 0.2.0
prek --version # Should show: prek 0.2.20
# 3. Test integration (shows prek + smart capabilities)
smart-hooks list
# 4. Run intelligent analysis on any file
smart-hooks test README.mdExpected output:
π Available prek hooks:
[prek hooks listed here]
π§ Additional smart-hooks capabilities:
π§ smart-test-selector - Intelligent test selection
π§ bdd-feature-selector - AI-powered BDD feature selection
π§ dependency-analyzer - Multi-language dependency analysis
# Install both tools for complete functionality
cargo install smart-hooks prek@0.2.20
# Verify installation
smart-hooks --version && prek --versionBuild time: ~2 minutes | Disk usage: ~50MB | Status: β Production ready
# Standalone mode (works perfectly without prek)
cargo install smart-hooks
# Still get intelligent analysis + fallback capabilities
smart-hooks test --help# From source (workspace structure)
git clone https://github.com/CaptainEmpower/smart-hooks
cd smart-hooks
# Install from workspace member (note: smart-hooks subdirectory)
cargo install --path smart-hooks
# Alternative: build only
cargo build --release --manifest-path smart-hooks/Cargo.toml
# Optional: Add prek integration
cargo install prek@0.2.20Note: This project uses a Cargo workspace structure. The main binary is in the
smart-hooks/subdirectory, not the root.
# Homebrew (may not be available yet)
brew tap CaptainEmpower/smart-hooks
brew install smart-hooks
# Install script (may need updates)
curl -sSL https://raw.githubusercontent.com/CaptainEmpower/smart-hooks/main/install.sh | bashAdd to your Cargo.toml:
[dev-dependencies]
smart-hooks = "0.2"# Verify both tools are working
smart-hooks --version # Expected: smart-hooks 0.2.0
prek --version # Expected: prek 0.2.20
# Test integration
smart-hooks list # Should show prek + smart capabilities
# Test core functionality
smart-hooks test README.md # Should analyze file intelligentlyIf verification fails, see Troubleshooting below.
π For detailed installation instructions, see INSTALL.md
Available Commands:
# Enhanced pre-commit commands (with prek integration)
smart-hooks run [HOOKS]... # Run hooks (uses prek when available)
smart-hooks install [TYPE] # Install git hooks (prek or smart)
smart-hooks list # List available hooks (prek + smart)
smart-hooks validate # Validate configuration (prek + smart)
# Smart analysis commands (always available)
smart-hooks test [FILES]... # Intelligent test selection
smart-hooks analyze [--verbose] # Multi-language project analysis
smart-hooks check [PATH] # Check conditional compilation
smart-hooks bdd [FILES]... # BDD feature selection (requires claude-ai)Direct Usage (no additional tools needed):
# Analyze specific files
smart-hooks test src/main.rs src/lib.rs
# Analyze changed files in git
smart-hooks test $(git diff --cached --name-only --diff-filter=AM)
# Analyze entire project
smart-hooks analyze --verbose
# Check compilation configuration
smart-hooks checkGit Hook Integration (manual setup):
# Add to .git/hooks/pre-commit
#!/bin/sh
exec smart-hooks test $(git diff --cached --name-only --diff-filter=AM)Create configuration file (config.toml):
enable_content_analysis = false
[bdd_structural_patterns]
core_business_logic = ["/core/", "/service/", "/domain/"]
application_logic = ["/apply/", "/strategy/", "/handler/"]
error_handling = ["/error", "/validate", "/types"]
api_interfaces = ["/api/", "/controller/", "/endpoint/"]
[bdd_pattern_tags]
"/core/" = ["@business-logic", "@critical"]
"/api/" = ["@api", "@external"]
"/error" = ["@error-handling", "@robustness"]# Automatically select tests based on changed files
smart-hooks test src/core/processor.rs src/api/controller.rs
# Output:
# π Running unit tests for: processor, controller
# π§ͺ Running integration tests for core changes
# π BDD recommendation: cucumber --tags "@business-logic or @api"# Intelligent BDD feature selection with Claude AI (requires claude-ai feature)
smart-hooks bdd src/core/processor.rs src/api/controller.rs
# Output:
# π€ Claude AI Analysis Results:
# π Recommended Features: payment_validation.feature, fraud_detection.feature
# π― Priority: high (confidence: 89%)
# π·οΈ Tags: @business-logic @critical @paymentuse smart_hooks::{TestSelectorConfig, select_bdd_features_static_with_config};
let config = TestSelectorConfig::from_file("project-config.toml")?;
// Get cucumber tags for a file
let tags = config.get_cucumber_tags_for_file("src/core/payment.rs");
// Returns: ["@business-logic", "@critical"]
// Get ready-to-run cucumber command
let cmd = config.get_cucumber_command_for_file("src/api/users.rs");
// Returns: "cucumber --tags '@api or @external'"smart-hooks/
βββ src/
β βββ analysis/ # Core analysis modules
β β βββ bdd/ # BDD-specific analysis
β β β βββ feature_discovery.rs # Feature file discovery
β β β βββ file_analyzer.rs # BDD file analysis
β β β βββ static_selector.rs # Static pattern selection
β β β βββ types.rs # BDD type definitions
β β βββ bdd_detector.rs # Static BDD pattern detection
β β βββ claude_bdd_detector.rs # Claude AI integration
β β βββ bdd_feature_selector.rs # Intelligent feature selection
β β βββ config.rs # Configuration management
β β βββ dependency_mapper.rs # Test dependency analysis
β β βββ file_analyzer.rs # File content analysis
β βββ dependency/ # Dependency analysis
β β βββ analyzers/ # Language-specific analyzers
β β βββ graph.rs # Dependency graph
β β βββ multi_lang_analyzer.rs # Multi-language support
β β βββ types.rs # Dependency types
β βββ examples/ # π SRP Module - Usage examples (298 LOC)
β β βββ commands.rs # Command-specific examples
β β βββ scenarios.rs # Workflow & integration scenarios
β β βββ mod.rs # Module organization
β βββ execution/ # Test execution coordination
β β βββ plan_executor.rs # Test plan execution
β β βββ test_runner.rs # Cargo command runner
β βββ hotreload/ # Hot-reload capabilities (disabled - missing deps)
β β βββ cache/ # Caching system
β β βββ engine.rs # Hot-reload engine
β β βββ execution/ # Execution tracking
β β βββ tracking/ # File change tracking
β βββ prek/ # π SRP Module - Prek integration (815 LOC total)
β β βββ commands.rs # Command execution & delegation (329 LOC)
β β βββ detection.rs # Availability detection (144 LOC)
β β βββ fallback.rs # Graceful fallback functionality (272 LOC)
β β βββ mod.rs # Module organization (13 LOC)
β βββ project/ # Project discovery
β β βββ discovery/ # Language detection
β β βββ types.rs # Project types
β β βββ multi_lang_discovery.rs # Multi-language discovery
β βββ smart_analysis/ # π SRP Module - Intelligent analysis (725 LOC total)
β β βββ test_selection.rs # Test selection & BDD functionality (159 LOC)
β β βββ project_analysis.rs # Multi-lang project analysis (184 LOC)
β β βββ file_impact.rs # File impact analysis (361 LOC)
β β βββ mod.rs # Module organization (21 LOC)
β βββ utilities/ # Shared utilities
β β βββ file_utils.rs # File operations
β β βββ impact_analyzer.rs # Change impact assessment
β β βββ module_utils.rs # Module name extraction
β βββ agent_commands.rs # Agent-friendly commands (109 LOC)
β βββ cli.rs # CLI configuration (270 LOC)
β βββ json_output.rs # JSON formatting utilities (293 LOC)
β βββ schema.rs # JSON schema generation (353 LOC)
β βββ system_info.rs # System information (304 LOC)
β βββ main.rs # π Refactored CLI coordinator (195 LOC)
β βββ lib.rs # Library interface
βββ features/ # BDD feature files
βββ tests/ # Integration tests
βββ example-config.toml # Configuration template
βββ README.md # This file
π = New SRP-compliant modules (78 inline unit tests added)
π = Refactored for SRP compliance (reduced from 1,239 LOC)
Define architectural patterns that should trigger BDD tests:
[bdd_structural_patterns]
# Core business logic
core_business_logic = ["/core/", "/service/", "/domain/", "/business/"]
# Application workflows
application_logic = ["/apply/", "/strategy/", "/handler/", "/processor/"]
# Error handling and validation
error_handling = ["/error", "/validate", "/types", "/exception/"]
# API interfaces
api_interfaces = ["/api/", "/controller/", "/endpoint/", "/web/"]
# Domain patterns (DDD, CQRS, etc.)
behavioral_patterns = ["/command/", "/event/", "/aggregate/", "/saga/"]Map file patterns to semantic cucumber tags:
[bdd_pattern_tags]
# Business logic
"/core/" = ["@business-logic", "@critical"]
"/service/" = ["@business-logic", "@integration"]
"/domain/" = ["@business-logic", "@domain-rules"]
# API layer
"/api/" = ["@api", "@external"]
"/controller/" = ["@api", "@web"]
"/endpoint/" = ["@api", "@rest"]
# Error handling
"/error" = ["@error-handling", "@robustness"]
"/validate" = ["@error-handling", "@validation"]Configure which files trigger which test types:
# Unit test patterns (file β module mapping)
[unit_test_patterns]
"processor.rs" = "processor"
"validator.rs" = "validator"
# Integration test patterns
integration_test_patterns = ["/core/", "/types.rs", "/error.rs"]
# BDD test patterns
bdd_test_patterns = ["/apply/", "/strategy/", "/service/"]- Install Claude CLI:
# Follow Claude CLI installation instructions
# https://docs.anthropic.com/claude/docs/claude-code- Install with Claude AI feature:
cargo install smart-hooks --features claude-ai- Usage:
# Analyze staged changes
git add src/core/payment_processor.rs
smart-hooks bdd src/core/payment_processor.rs- Semantic understanding - Understands code intent beyond syntax
- Context-aware - Considers project domain and business logic
- Intelligent recommendations - Suggests specific test scenarios
- Confidence scoring - Provides reliability metrics
The crate includes comprehensive test coverage:
# Run all tests
cargo test --lib
# Run with Claude AI features
cargo test --lib --features claude-ai
# Run specific test modules
cargo test analysis::config
cargo test analysis::bdd_detectorTest Coverage:
- β 227 comprehensive tests (121 binary + 106 library) covering all core functionality
- β Static analysis pattern detection
- β Configuration parsing and validation
- β Tag mapping and command generation
- β BDD feature selection algorithms
- β Error handling and edge cases
smart-hooks follows Single Responsibility Principle with comprehensive modular refactoring:
Main Refactoring Achievement: Transformed monolithic main.rs (1,239 LOC) into 11 focused modules with 78 new inline unit tests:
prek/- Prek integration with graceful fallback (4 sub-modules, 815 total LOC)commands.rs(329 LOC) - Command execution & delegationdetection.rs(144 LOC) - Availability detectionfallback.rs(272 LOC) - Graceful fallback functionalitymod.rs(13 LOC) - Module organization
smart_analysis/- Intelligent analysis (4 sub-modules, 725 total LOC)test_selection.rs(159 LOC) - Test selection & BDD functionalityproject_analysis.rs(184 LOC) - Multi-language project analysisfile_impact.rs(361 LOC) - File impact analysis & risk assessmentmod.rs(21 LOC) - Module organization
examples/- Usage examples & scenarios (3 sub-modules, 767 total LOC)commands.rs(298 LOC) - Command-specific examplesscenarios.rs(356 LOC) - Workflow & integration scenariosmod.rs(113 LOC) - Module organization
cli.rs(270 LOC) - CLI configuration & argument parsingjson_output.rs(293 LOC) - Structured JSON response formattingschema.rs(353 LOC) - JSON schema generation for API validationsystem_info.rs(304 LOC) - System capabilities & status checkingagent_commands.rs(109 LOC) - Agent-friendly command implementationsmain.rs(195 LOC) - Refactored CLI coordinator
- Structural pattern detection (domain-agnostic)
- Content analysis (optional file reading)
- AI-powered semantic analysis (Claude integration)
- Configuration management (TOML-based)
- Test plan creation based on analysis
- Cargo command execution with proper error handling
- Result coordination and reporting
- File operations with safety checks
- Impact analysis for change assessment
- Module utilities for Rust project navigation
- 227 total tests (121 binary + 106 library)
- 78 new inline unit tests added during refactoring
- 99.5% test success rate (1 flaky test in legacy Claude BDD detector)
# GitHub Actions
- name: Smart Test Selection
run: |
smart-hooks test $(git diff --name-only HEAD~1)
# GitLab CI
script:
- smart-hooks analyze --verbose
- smart-hooks checkπ Seamless integration with prek v0.2.20 for enterprise-grade workflows:
# Install both tools
cargo install smart-hooks prek@0.2.20
# Use enhanced pre-commit commands
smart-hooks run trailing-whitespace --files src/
smart-hooks install pre-commit # Uses prek infrastructure
smart-hooks list # Shows prek + smart hooks# Install smart-hooks only
cargo install smart-hooks
# Still get full intelligent functionality
smart-hooks install pre-commit # Creates smart git hooks
smart-hooks run # Uses intelligent analysisSee PREK_INTEGRATION.md for complete documentation.
Three migration paths:
# Keep your .pre-commit-config.yaml, add intelligence
cargo install smart-hooks prek@0.2.20
smart-hooks run --all-files # Enhanced with smart analysis# Replace pre-commit entirely with intelligent hooks
cargo install smart-hooks
smart-hooks install pre-commit # Creates intelligent git hooks# Use both side by side
smart-hooks test $(git diff --cached --name-only) # Smart analysis
prek run --all-files # Standard hooks#!/bin/bash
# run-smart-tests.sh
CHANGED_FILES=$(git diff --cached --name-only --diff-filter=AM | grep "\.rs$")
if [[ -n "$CHANGED_FILES" ]]; then
echo "π Analyzing changed files: $CHANGED_FILES"
smart-hooks test $CHANGED_FILES
fi// Configuration
pub struct TestSelectorConfig {
pub bdd_structural_patterns: Option<BddStructuralPatterns>,
pub bdd_pattern_tags: Option<HashMap<String, Vec<String>>>,
pub enable_content_analysis: bool,
}
// BDD Analysis
pub struct BddFeatureSelection {
pub should_run_bdd: bool,
pub confidence: f32,
pub selected_features: Vec<SelectedFeature>,
pub suggested_test_focus: Vec<String>,
}
// Test Planning
pub struct TestPlan {
pub unit_tests: Vec<String>,
pub integration_tests: bool,
pub bdd_tests: bool,
}// Configuration-based analysis
pub fn select_bdd_features_static_with_config(
staged_files: &[FileChange],
available_features: &[String],
config: &TestSelectorConfig,
) -> Result<BddFeatureSelection>
// Claude AI analysis (requires "claude-ai" feature)
pub async fn select_bdd_features_with_claude(
staged_files: &[FileChange],
available_features: &[String],
project_context: &str,
) -> Result<BddFeatureSelection>
// Test plan creation
pub fn create_test_plan_with_config(
files: &[String],
config: &TestSelectorConfig,
) -> Result<TestPlan>| Platform | Status | Verification | Performance |
|---|---|---|---|
| macOS | β Verified | Full integration tested | Build: ~20s, Install: ~2min |
| Linux | π‘ Expected | Similar to macOS | Estimated similar |
| Windows | π‘ Expected | Cargo standard | May need WSL |
- Binary size: ~25MB (smart-hooks) + ~25MB (prek)
- Memory usage: Minimal footprint
- Startup time: Instant (<100ms)
- Build success rate: 100% on tested platforms
- Integration success: β Full prek v0.2.20 compatibility
β Successfully tested scenarios:
- Clean installation on fresh macOS system
- Version verification and help commands
- Prek auto-detection and intelligent delegation
- Smart analysis fallback when prek unavailable
- All original smart-hooks functionality preserved
- Git hook creation and installation
- Integration with existing repositories
π Performance benchmarks:
- File analysis: <500ms for typical source files
- Hook execution: <1s for standard pre-commit workflows
- Configuration loading: <50ms
- CLI responsiveness: Instant for all commands
See DEPLOYMENT_EXAMPLE.md for complete deployment verification results.
# Install Rust first
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
source ~/.cargo/env# Force reinstall latest version
cargo install smart-hooks --force# This is fine! Smart-hooks works perfectly standalone
# To get prek integration:
cargo install prek@0.2.20This is expected behavior! Prek requires a .pre-commit-config.yaml file. Smart-hooks gracefully falls back to showing its own capabilities.
To fix (optional):
# Create basic pre-commit config
echo "repos: []" > .pre-commit-config.yaml
smart-hooks list # Should now show prek hooks# Check if both tools are properly installed
which smart-hooks # Should show: ~/.cargo/bin/smart-hooks
which prek # Should show: ~/.cargo/bin/prek (optional)
# Test standalone mode
smart-hooks test --help # Should respond instantlyThis affects the analyze command and is expected in non-Rust projects. The core functionality still works:
# Use other commands instead
smart-hooks test [files] # β
Works everywhere
smart-hooks list # β
Works everywhere
smart-hooks validate # β
Works everywhere- Expected: ~2 minutes for both tools
- If slower: Check internet connection and cargo registry access
# Verify installation
ls -la ~/.cargo/bin/smart-hooks # Should show recent binary
# Test in release mode (if building from source)
cargo build --release --manifest-path smart-hooks/Cargo.toml# Use correct workspace path
cargo build --manifest-path smart-hooks/Cargo.toml # β
Correct
cargo build # β Wrong (tries to build workspace root)Expected behavior due to workspace restructuring. Core functionality works:
# Install and test the binary directly
cargo install --path smart-hooks
smart-hooks --version # Should work- Issues: GitHub Issues
- Documentation: PREK_INTEGRATION.md
- Deployment: DEPLOYMENT_EXAMPLE.md
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Follow SRP guidelines (β€365 LOC per module - see existing modules for reference)
- Add comprehensive tests (include inline unit tests)
- Update documentation
- Submit a pull request
- Single Responsibility Principle - Each module has one clear purpose
- Configuration over code - Make patterns configurable, not hard-coded
- Domain-agnostic design - Avoid business-specific assumptions
- Comprehensive testing - Maintain >95% test coverage
- Clear documentation - Document architectural decisions
This project is licensed under the MIT License - see the LICENSE file for details.
- Prek (by @j178) for excellent pre-commit infrastructure and inspiration
- Anthropic Claude for semantic code analysis capabilities
- Cucumber for excellent BDD testing framework
- Rust community for amazing tooling and ecosystem
- git-mvh project for inspiring the initial architecture
- Multi-language support for TypeScript, Python, PHP, and Rust projects
Built with β€οΈ for intelligent test automation across all projects