# Contributing to Hephaestus

Welcome to Hephaestus! This guide provides everything you need to contribute to the modern Anvil MCP server project.

## Development Environment Setup

### Prerequisites

- **Python 3.13+**: Required for modern type annotations and performance optimizations
- **uv**: Fast Python package manager (install from [uv documentation](https://docs.astral.sh/uv/))
- **Git**: For version control

### Quick Start

#### For Contributors (Radicle)
```bash
# Clone via Radicle for full development access
rad clone rad:zwcVaZPYRXt8uA3uaBuUiH8hXzMw
cd hephaestus

# Install dependencies
uv sync

# Verify installation
just --list

# Run tests to ensure everything works
just test
```

#### For Users (GitHub Mirror)
```bash
# Clone via GitHub for access and usage
git clone https://github.com/empiria/hephaestus
cd hephaestus

# Install dependencies
uv sync

# Verify installation
just --list

# Run tests to ensure everything works
just test
```

### Development Dependencies

The project uses modern Python tooling for optimal developer experience:

```toml
[dependency-groups]
dev = [
    "pytest>=9.0.1",           # Testing framework
    "ruff>=0.14.7",            # Linting and formatting
    "basedpyright>=1.15.0",    # Type checking
]
```

## Development Tools

### Task Runner - Just

All development tasks are managed through a `justfile`:

```bash
# View all available commands
just --list

# Core development tasks
just test                    # Run pytest with coverage
just lint                    # Run ruff linting
just format                  # Format code with ruff
just typecheck              # Run basedpyright type checking

# Server management
just run                     # Run MCP server with stdio transport
just run-http               # Run MCP server with HTTP transport

# Package management
just build                  # Build wheel package
just clean                  # Clean build artifacts
just bump-patch             # Increment patch version
just bump-minor             # Increment minor version
```

### Code Quality Tools

#### Ruff - Linting and Formatting
```bash
# Check for issues
just lint

# Auto-fix issues where possible
ruff check --fix src/ tests/

# Format code
just format
```

Configuration in `pyproject.toml`:
```toml
[tool.ruff]
target-version = "py313"
line-length = 88
select = ["E", "F", "W", "I", "N", "UP", "B", "A", "C4", "ICN", "T20"]

[tool.ruff.lint.isort]
known-first-party = ["src"]
```

#### BasedPyright - Type Checking
```bash
# Run type checking
just typecheck

# Type check specific files
basedpyright src/server.py
```

Configuration in `pyproject.toml`:
```toml
[tool.basedpyright]
include = ["src"]
exclude = ["**/__pycache__"]
reportUnusedVariable = "none"
reportUndefinedVariable = "none"
# External boundary pattern: suppress warnings for dynamic/external interfaces
reportAny = "none"  # Flow of Any from external sources (YAML, CLI, JSON)
reportUnknownMemberType = "none"  # Dynamic operations on external data
reportUnknownArgumentType = "none"  # Arguments from external sources  
reportUnknownVariableType = "none"  # Variables from dynamic operations
```

#### Pytest - Testing
```bash
# Run all tests
just test

# Run specific test file
pytest tests/test_server.py -v

# Run with coverage
pytest tests/ --cov=src --cov-report=html
```

## Project Architecture

### Dependency Injection Pattern

Hephaestus uses a clean dependency injection pattern:

```python
# Container manages all dependencies
class Container:
    def create_version_manager(self) -> VersionManagerProtocol:
        return VersionManager()
    
    def create_command_executor(self, version_manager) -> CommandExecutorProtocol:
        return CommandExecutor(version_manager)
    
    def create_mcp_server_components(self):
        version_manager = self.create_version_manager()
        executor = self.create_command_executor(version_manager)
        tool_generator = self.create_tool_generator(version_manager, executor)
        mcp = FastMCP("hephaestus-mcp-server")
        return version_manager, tool_generator, mcp
```

### Protocol-Based Design

All major components are defined as protocols for testability:

```python
@runtime_checkable
class VersionManagerProtocol(Protocol):
    def get_installed_version(self) -> str: ...
    def get_current_definition(self) -> AnvilVersion: ...
    # ... other methods

@runtime_checkable
class ToolGeneratorProtocol(Protocol):
    def generate_all_tools(self) -> dict[str, Callable[..., str]]: ...
    def get_tool_schemas(self) -> dict[str, dict[str, Any]]: ...
```

### Exception Hierarchy

```python
class HephaestusMCPError(Exception):
    """Base exception for all Hephaestus operations."""

class AnvilVersionNotSupportedError(HephaestusMCPError):
    """Raised when Anvil version lacks definition support."""

class ComponentNotFoundError(HephaestusMCPError):
    """Raised when requested component not found in definitions."""

class InvalidPatternError(HephaestusMCPError):
    """Raised when pattern analysis fails validation."""
```

## Code Standards

### Comments Policy

**Use comments sparingly.** Only add comments when:
- The intention of the code is not immediately clear from reading it
- An obvious-looking alternative approach is not actually suitable (explain why)

**Prefer these alternatives to comments:**
1. **Proper variable naming**: Use descriptive names that explain purpose
2. **Refactor into named functions**: Extract complex logic into well-named functions  
3. **Docstrings**: Document public APIs, function parameters, return values, and exceptions

### Code Quality Principles

#### Declarative Code Patterns
```python
# Prefer declarative patterns
tools = {
    f"create_{component}": self._generate_component_tool(component, definition)
    for component, definition in modern_components.items()
}

# Over imperative building
tools = {}
for component, definition in modern_components.items():
    tools[f"create_{component}"] = self._generate_component_tool(component, definition)
```

#### Naming Conventions
- **Snake_case** for functions and variables
- **PascalCase** for classes and protocols
- **SCREAMING_SNAKE_CASE** for constants
- **Descriptive names** that explain purpose without comments

#### Error Handling Standards
- **Provide specific error messages** with actionable solutions
- **Use consistent formatting** with clear problem descriptions
- **Include diagnostic information** for debugging
- **Implement graceful degradation** when possible
- **Follow existing exception hierarchy**

### Testing Standards

#### Test Organization
```python
# Test structure follows src/ organization
tests/
├── test_server.py              # Server integration tests
├── test_project_analyzer.py    # Pattern detection tests
├── test_tool_generator.py      # Code generation tests
├── test_migration_tools.py     # Legacy migration tests
└── test_doubles.py            # Test utilities and mocks
```

#### Testing Patterns
```python
class TestModernComponentGeneration:
    """Test modern component generation tools."""
    
    def test_create_reactive_page_generates_optimal_patterns(self):
        """Test reactive page generation with M3 + routing + layouts."""
        # Arrange
        context = ProjectContext(
            generation_mode="modern",
            theme_type="material-3",
            has_reactive=True
        )
        
        # Act
        result = self.tool_generator.create_reactive_page(
            context, 
            name="UserDashboard",
            route="/dashboard"
        )
        
        # Assert
        assert "@reactive_class" in result.code
        assert "NavigationDrawerLayout" in result.template
        assert result.performance_score > 0.9
```

#### Mock-Based Testing
```python
# Mock external dependencies to isolate components
@patch("subprocess.run")
def test_anvil_version_detection(self, mock_run):
    mock_run.return_value = Mock(
        returncode=0,
        stdout="Anvil CLI v1.5.0\n"
    )
    
    manager = VersionManager()
    version = manager.get_installed_version()
    
    assert version == "1.5.0"
```

## Project Structure

### Source Code Organization
```
src/
├── __init__.py                 # Package metadata
├── server.py                   # Main MCP server entry point
├── container.py               # Dependency injection container
├── protocols.py               # Protocol interfaces
├── exceptions.py              # Custom exception hierarchy
├── project_analyzer.py        # Anvil pattern detection
├── tool_generator.py          # Dynamic MCP tool creation
├── modern_tools/              # Modern generation tools
│   ├── __init__.py
│   ├── project_scaffolding.py
│   ├── component_generation.py
│   └── routing_tools.py
├── migration_tools/           # Legacy support tools
│   ├── __init__.py
│   ├── pattern_detection.py
│   ├── migration_planning.py
│   └── compatibility.py
└── definitions/              # Anvil pattern definitions
    ├── __init__.py
    ├── schema.py
    └── anvil_patterns.yaml
```

### Configuration Files

#### pyproject.toml
```toml
[project]
name = "hephaestus-mcp-server"
version = "0.1.0"
description = "Modern Anvil MCP Server for intelligent code generation"
requires-python = ">=3.13"
dependencies = [
    "attrs>=25.4.0",
    "fastmcp>=0.11.0",
    "mcp>=1.22.0",
    "pyyaml>=6.0.3",
    "pydantic>=2.5.0",
    "jinja2>=3.1.0",
]

[project.scripts]
hephaestus-mcp-server = "src.server:main"

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
```

#### justfile
```justfile
default:
    @just --list

test:
    uv run python -m pytest tests/ -v --tb=short

test-coverage:
    uv run pytest tests/ -v --tb=short --cov=src --cov-report=html --cov-report=term

run:
    uv run python -m src.server

run-http:
    uv run python -m src.server --transport http --host localhost --port 8000

lint:
    ruff check src/ tests/

format:
    ruff format src/ tests/

typecheck:
    basedpyright

build:
    uv build

clean:
    rm -rf build/ dist/ *.egg-info/ .pytest_cache/ .coverage htmlcov/
    find . -type d -name __pycache__ -exec rm -rf {} +
    find . -type f -name "*.pyc" -delete
```

## Development Workflow

### Feature Development

1. **Create a branch** from main for your feature
2. **Write tests first** following TDD practices
3. **Implement the feature** with clean, self-documenting code
4. **Run full test suite** to ensure no regressions
5. **Update documentation** if adding new tools or changing APIs

### Code Review Process

1. **Ensure all tests pass**: `just test`
2. **Check code quality**: `just lint` and `just format`
3. **Verify type safety**: `just typecheck`
4. **Test manually** with real Anvil projects when possible
5. **Request review** focusing on architecture, patterns, and user experience

### Git Workflow

#### Commit Message Standards
Follow conventional commits for clear history:

```
feat: add create_reactive_store tool for modern state management

- Implements signals-based reactive store generation
- Includes automatic computed properties and effects
- Validates against Anvil Reactive library patterns
- Adds comprehensive tests for store generation

Closes #42
```

#### Branch Naming
- `feature/tool-name` - New tool development
- `fix/issue-description` - Bug fixes
- `refactor/component-name` - Code improvements
- `docs/section-name` - Documentation updates

### Testing Strategy

#### Unit Tests
Test individual components in isolation:
```python
def test_project_context_scoring():
    """Test modernization score calculation."""
    analyzer = ProjectAnalyzer()
    
    # Modern project should score highly
    modern_context = analyzer.analyze_project(modern_project_data)
    assert modern_context.modernization_score > 0.8
    
    # Legacy project should score lower
    legacy_context = analyzer.analyze_project(legacy_project_data)
    assert legacy_context.modernization_score < 0.4
```

#### Integration Tests
Test complete workflows:
```python
def test_modern_app_creation_workflow():
    """Test complete modern app creation from start to finish."""
    server = HephaestusMCPServer.create()
    
    # Create modern app
    result = server.execute_tool("create_modern_anvil_app", {
        "name": "TestApp",
        "enable_analytics": True
    })
    
    # Verify complete stack was created
    assert "Material 3 Theme" in result.dependencies
    assert "Official Routing" in result.dependencies
    assert "Reactive Library" in result.dependencies
    assert result.performance_score == 1.0
```

#### Performance Tests
Ensure generated code is optimal:
```python
def test_reactive_component_performance():
    """Test generated reactive components for performance."""
    generator = ComponentGenerator()
    
    component = generator.create_reactive_form({
        "name": "UserForm",
        "fields": ["name", "email", "preferences"]
    })
    
    # Should minimize re-renders
    assert component.render_effect_count <= len(component.reactive_fields)
    
    # Should use computed properties for derived state
    assert component.has_computed_properties
```

## AI Agent Development Guidelines

### Context7 Integration

When working with external libraries, always use Context7 for documentation:

```bash
# Get FastMCP documentation for tool registration
# Use Context7: resolve-library-id "fastmcp" -> get-library-docs topic="tool registration"

# Get Pydantic documentation for validation patterns  
# Use Context7: resolve-library-id "pydantic" -> get-library-docs topic="validation"
```

### Code Generation Patterns

Follow these patterns when adding new code generation tools:

```python
class ModernToolGenerator:
    def generate_component(self, context: ProjectContext, **params):
        """Generate component with context-aware patterns."""
        
        def validate_parameters() -> str | None:
            # Parameter validation logic
            return None
            
        def generate_optimal_code() -> Dict[str, Any]:
            # Modern pattern generation
            return {}
            
        def generate_compatible_code() -> Dict[str, Any]:
            # Legacy-compatible generation
            return {}
            
        # Main execution flow
        validation_error = validate_parameters()
        if validation_error:
            return validation_error
            
        if context.generation_mode == "modern":
            return self.format_result(generate_optimal_code())
        else:
            return self.format_result(generate_compatible_code())
```

### Performance-First Development

Always optimize for performance in generated code:

```python
# Good: Reactive patterns with minimal re-renders
@render_effect
def sync_user_display(self):
    bind(self.username, "text", lambda: self.user_store.name)
    bind(self.avatar, "source", lambda: self.user_store.avatar_url)

# Bad: Manual updates causing unnecessary work
def refresh_user_display(self):
    self.username.text = self.user_store.name
    self.avatar.source = self.user_store.avatar_url
    self.refresh_data_bindings()
```

## Troubleshooting

### Common Issues

#### Import Errors
```bash
# Ensure dependencies are installed
uv sync

# Check Python version
python --version  # Should be 3.13+
```

#### Test Failures
```bash
# Run specific test with verbose output
pytest tests/test_server.py::TestServerIntegration::test_tool_registration -v

# Check for import issues
python -c "from src.server import HephaestusMCPServer"
```

#### Type Checking Issues
```bash
# Run type checker with verbose output
basedpyright --verbose

# Check specific file
basedpyright src/tool_generator.py
```

### Development Environment Issues

#### UV Not Found
```bash
# Install uv
curl -LsSf https://astral.sh/uv/install.sh | sh

# Or with pip
pip install uv
```

#### Permission Issues
```bash
# Ensure correct permissions
chmod +x justfile
```

## Documentation Standards

### Docstring Format
```python
def create_reactive_component(
    self, 
    context: ProjectContext, 
    name: str, 
    component_type: str = "form"
) -> ComponentResult:
    """Create a reactive component with optimal patterns.
    
    Args:
        context: Project analysis context for pattern selection
        name: Component name in PascalCase
        component_type: Type of component ("form", "layout", "container")
        
    Returns:
        ComponentResult with generated code, template, and metadata
        
    Raises:
        InvalidPatternError: When component_type is not supported
        ValidationError: When name conflicts with existing components
        
    Example:
        >>> context = analyzer.analyze_project(project_data)
        >>> result = generator.create_reactive_component(
        ...     context, "UserProfile", "form"
        ... )
        >>> print(result.code)  # Generated Python code
    """
```

### API Documentation
Document all public tools and their parameters clearly, with examples that show both modern and legacy usage patterns.

## Project Management & Architecture

### Project Management System

Hephaestus uses **Radicle** as its primary project management system - a decentralized, peer-to-peer code collaboration platform. The repository is mirrored to GitHub for public access and distribution.

- **Radicle Repository**: `rad:zwcVaZPYRXt8uA3uaBuUiH8hXzMw`
- **GitHub Mirror**: https://github.com/empiria/hephaestus
- **Issue Tracking**: Managed via Radicle issues (5-phase implementation plan)
- **MCP Integration**: radicle-mcp-server provides seamless operations

### Development Workflow
1. **Project Management**: Track progress via Radicle issues
2. **Code Development**: Work with Radicle's decentralized version control
3. **GitHub Sync**: Automatic mirroring for public distribution
4. **Package Publishing**: PyPI distribution from GitHub Actions

### Architecture Overview

Hephaestus transforms Anvil development by providing comprehensive coverage of all development needs - from fundamental operations to advanced modern patterns. Named after the Greek god of craftsmanship and fire, Hephaestus forges complete, production-ready Anvil applications with the precision of a master craftsman.

#### Core Principles

- **Complete Coverage**: Tools for every aspect of Anvil development - UI, data, security, deployment, and beyond
- **Modern by Default**: New code uses Material 3 + Reactive + Official Routing + Layouts + Model Classes
- **Production Ready**: Enterprise-grade security, monitoring, testing, and deployment capabilities
- **Performance First**: Generate optimal, efficient patterns without compromise  
- **Legacy Respectful**: Comprehensive support for all Anvil patterns since v1.0
- **Clean Architecture**: Self-documenting code with clear separation of concerns

#### Intelligent Context System

Every tool execution begins with project analysis to determine the optimal generation approach:

```python
@dataclass
class ProjectContext:
    anvil_version: str
    theme_type: str  # "material-3", "classic", "custom"
    routing_system: str  # "official", "anvil-extras", "none" 
    has_reactive: bool
    data_layer: str  # "model-classes", "anvil-extras-orm", "raw-tables"
    layout_system: str  # "layouts", "traditional", "mixed"
    modernisation_score: float  # 0.0-1.0
    generation_mode: str  # "modern", "hybrid", "legacy-compatible"
    performance_opportunities: List[str]
    breaking_change_risks: List[str]
```

#### Smart Tool Routing
- **Modern Apps** (Score 0.8+): Full M3 + Reactive + Routing + Layouts + Model Classes + Enterprise features
- **Transitioning Apps** (Score 0.4-0.8): Enhanced patterns respecting existing architecture + strategic modernisation
- **Legacy Apps** (Score 0-0.4): Compatible patterns + comprehensive support + modernisation suggestions
- **All Apps**: Complete coverage of fundamental operations regardless of architecture

#### Complete Anvil Development Ecosystem

Hephaestus provides comprehensive tooling for all Anvil development needs, specialising in modern technologies for world-class applications:

**Core Technologies**
1. **[Material 3 Theme](https://anvil.works/dependencies/4UK6WHQ6UX7AKELK)** - Modern Material Design 3 components and layouts
2. **[Official Routing](https://anvil.works/dependencies/3PIDO5P3H4VPEMPL)** - Modern routing with data loading and caching
3. **[Reactive Library](https://anvil.works/dependencies/N7KFE4YBWMGWJ5OX)** - Signals-based state management for automatic UI updates
4. **Model Classes** - Type-safe, validated data models with automatic serialisation and relationships
5. **Layouts System** - Slot-based layout architecture replacing traditional panels
6. **Tabulator Integration** - High-performance reactive data tables with model integration

**Key Capabilities**

**Foundation Development**
- Data table operations, authentication, client-server communication, forms, file management

**Advanced UI/UX Development** 
- Custom components, themes, interactive interfaces, cross-platform compatibility

**Business Logic & Integration**
- Email services, payment processing, external APIs, background tasks, third-party connectors

**Production Operations**
- Testing, monitoring, security, deployment, enterprise features

**Modern Architecture Specialisation**
- Material 3 + Reactive + Routing + Layouts + Model Classes for optimal performance

## Contributing Process

1. **Check existing issues** or create a new issue to discuss your idea
2. **Fork the repository** and create a feature branch
3. **Follow code standards** and write comprehensive tests
4. **Update documentation** for any new tools or changed APIs
5. **Submit a pull request** with clear description and examples
6. **Participate in code review** and address feedback constructively

## Recognition

Contributors who help make Hephaestus the definitive modern Anvil development platform:

- Follow the code of conduct and maintain a positive, collaborative environment
- Focus on developer experience and performance in all contributions
- Help maintain comprehensive documentation and examples
- Participate constructively in discussions and code reviews

Thank you for contributing to Hephaestus - forging the future of Anvil development! 🔨