# Getting Started with Hephaestus Development

## Quick Start Guide

### Prerequisites
- Python 3.13 or higher
- uv (fast Python package manager)
- Git
- Just (task runner)
- Radicle (for contributors) or GitHub access (for users)

### Initial Setup

#### For Contributors (Radicle Development)
```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 Environment

### IDE Configuration
For VS Code, create `.vscode/settings.json`:
```json
{
    "python.defaultInterpreterPath": ".venv/bin/python",
    "python.linting.enabled": true,
    "python.linting.ruffEnabled": true,
    "python.formatting.provider": "black",
    "python.formatting.ruffEnabled": true,
    "python.typeChecking.mode": "basic",
    "python.typeChecking.provider": "basedpyright"
}
```

### Environment Variables
Create `.env` file (optional):
```bash
# Development settings
HEPHAESTUS_LOG_LEVEL=DEBUG
HEPHAESTUS_CONFIG_PATH=./config.yaml
```

## Understanding the Codebase

### Core Components

#### 1. MCP Server (`src/server.py`)
- **HephaestusMCPServer**: Main server class
- **main()**: Entry point with CLI argument parsing
- **FastMCP**: Underlying MCP framework

#### 2. Tool System (to be implemented)
- Tool registration with FastMCP
- Context-aware code generation
- Validation and error handling

#### 3. Code Generation (to be implemented)
- Anvil YAML form generation
- Model class generation
- Reactive component generation

### Key Files to Understand

#### `pyproject.toml`
- Project metadata and dependencies
- Build configuration with hatchling
- Development tools configuration
- Type checking settings

#### `justfile`
- Development commands and recipes
- Testing, linting, formatting workflows
- Build and publishing commands

#### `AGENTS.md`
- Comprehensive technical specifications
- Anvil development patterns
- Code generation standards

## Common Development Tasks

### Adding a New MCP Tool

1. **Define the tool function**:
```python
@self.mcp.tool()
def create_anvil_component(component_type: str, name: str, **properties) -> str:
    """Create a new Anvil component with specified properties."""
    try:
        # Validate inputs
        validator = ComponentValidator()
        validator.validate_component_type(component_type)
        validator.validate_component_name(name)
        
        # Generate component
        generator = ComponentGenerator()
        component_yaml = generator.generate_component(component_type, name, properties)
        
        return {
            "success": True,
            "component_yaml": component_yaml,
            "component_type": component_type,
            "name": name
        }
    except ValidationError as e:
        return {
            "success": False,
            "error": str(e),
            "suggestion": "Check component type and name format"
        }
```

2. **Add validation**:
```python
class ComponentValidator:
    def validate_component_type(self, component_type: str):
        valid_types = ["Button", "TextBox", "Label", "ColumnPanel"]
        if component_type not in valid_types:
            raise ValidationError(f"Invalid component type: {component_type}")
    
    def validate_component_name(self, name: str):
        if not re.match(r'^[a-z][a-z0-9_]*$', name):
            raise ValidationError(f"Invalid component name: {name}")
```

3. **Write tests**:
```python
def test_create_anvil_component(mock_mcp_server):
    result = mock_mcp_server.create_anvil_component("Button", "submit_button", text="Submit")
    assert result["success"] is True
    assert "component_yaml" in result
```

### Adding Code Generation Support

1. **Create generator class**:
```python
class AnvilFormGenerator:
    def generate_form(self, form_config: dict) -> str:
        yaml_structure = {
            "container": {
                "type": form_config.get("container_type", "ColumnPanel"),
                "properties": self._generate_properties(form_config)
            },
            "components": self._generate_components(form_config.get("components", []))
        }
        return yaml.dump(yaml_structure, default_flow_style=False)
```

2. **Add validation**:
```python
def validate_form_config(self, config: dict):
    required_fields = ["name", "components"]
    for field in required_fields:
        if field not in config:
            raise ValidationError(f"Missing required field: {field}")
```

3. **Test generation**:
```python
def test_form_generation():
    generator = AnvilFormGenerator()
    config = {
        "name": "TestForm",
        "components": [
            {"type": "Button", "name": "submit_button", "text": "Submit"}
        ]
    }
    yaml_output = generator.generate_form(config)
    assert "Button" in yaml_output
    assert "submit_button" in yaml_output
```

## Testing Your Changes

### Running Tests
```bash
# Run all tests
just test

# Run with coverage
just test-coverage

# Run specific test file
uv run python -m pytest tests/test_generator.py -v

# Run with specific pattern
uv run python -m pytest tests/ -k "test_form" -v
```

### Writing Tests

#### Unit Tests
```python
import pytest
from src.generator import AnvilFormGenerator

class TestAnvilFormGenerator:
    def test_generate_simple_form(self):
        generator = AnvilFormGenerator()
        config = {
            "name": "SimpleForm",
            "components": [
                {"type": "Label", "name": "title", "text": "Hello World"}
            ]
        }
        
        result = generator.generate_form(config)
        
        assert "SimpleForm" in result
        assert "Label" in result
        assert "title" in result
        assert "Hello World" in result
```

#### Integration Tests
```python
def test_mcp_tool_integration():
    mcp = FastMCP("test")
    server = HephaestusMCPServer(mcp)
    
    # Test that tool is registered
    tools = mcp.list_tools()
    assert any(tool.name == "create_anvil_form" for tool in tools)
```

## Debugging

### Common Issues

#### 1. Server Won't Start
```bash
# Check Python version
python --version  # Should be 3.13+

# Check dependencies
uv tree

# Check for syntax errors
uv run python -m py_compile src/server.py
```

#### 2. Tools Not Registered
```bash
# Check server startup logs
uv run python -m src.server --verbose

# Test tool registration manually
uv run python -c "
from src.server import HephaestusMCPServer
from fastmcp import FastMCP
mcp = FastMCP('test')
server = HephaestusMCPServer(mcp)
print('Tools registered:', len(mcp.list_tools()))
"
```

#### 3. Code Generation Issues
```bash
# Test generator directly
uv run python -c "
from src.generator import AnvilFormGenerator
gen = AnvilFormGenerator()
print(gen.generate_form({'name': 'Test', 'components': []}))
"
```

### Debug Mode
```bash
# Run with debug logging
HEPHAESTUS_LOG_LEVEL=DEBUG uv run python -m src.server

# Run with Python debugger
uv run python -m pdb src/server.py
```

## Project Management with Radicle

Hephaestus uses **Radicle** as its primary project management system - a decentralized, peer-to-peer code collaboration platform. This means:

- **Issue Tracking**: All project phases and tasks are managed via Radicle issues
- **Code Collaboration**: Development happens through Radicle's decentralized network
- **GitHub Mirror**: The repository is mirrored to GitHub for public access and distribution
- **MCP Integration**: radicle-mcp-server provides seamless Radicle operations within development workflow

### Development Workflow
1. **Project Management**: Track progress via Radicle issues (5-phase implementation plan)
2. **Code Development**: Work with Radicle's decentralized version control
3. **GitHub Sync**: Mirror changes to GitHub for public distribution
4. **Package Publishing**: Publish to PyPI from GitHub Actions (when implemented)

## Contributing via Radicle

We use Radicle for project management and collaboration:

1. **Get Repository**: Clone via Radicle for full development access
2. **Track Issues**: Work is organized through Radicle issues (5-phase plan)
3. **Submit Changes**: Use Radicle's peer-to-peer collaboration features
4. **GitHub Mirror**: Changes are automatically mirrored to GitHub

### MCP Integration
The project uses radicle-mcp-server for seamless Radicle operations:
- Issue management via MCP tools
- Repository inspection and status
- Decentralized collaboration features

For users who prefer traditional workflows, GitHub serves as a read-only mirror for access and issue viewing.

## Contributing Guidelines

### Code Style
- Follow existing patterns in the codebase
- Use ruff for formatting and linting
- Add type hints for all public functions
- Write comprehensive docstrings

### Commit Messages
- Use conventional commit format
- Examples: `feat: add form generator`, `fix: validation error handling`
- Include issue numbers where applicable

### Development Process
1. **Setup**: Clone via Radicle for development access
2. **Track**: Work on Radicle issues from the 5-phase plan
3. **Develop**: Implement changes with comprehensive testing
4. **Quality**: Run full test suite and quality checks
5. **Document**: Update documentation as needed
6. **Sync**: Changes automatically mirror to GitHub

## Getting Help

### Documentation
- `AGENTS.md`: Comprehensive technical specifications
- `anvil_yaml_reference.md`: Anvil YAML component reference
- Code comments and docstrings

### Community
- **Radicle Issues**: Primary project management and issue tracking
- **GitHub Mirror**: Read-only access for users and public viewing
- **MCP Integration**: Use radicle-mcp-server for seamless operations

### Development Resources
- FastMCP documentation
- Anvil documentation
- Python 3.13+ features and best practices

## Next Steps

1. **Explore the codebase**: Read through `src/server.py` and `AGENTS.md`
2. **Run the server**: Try `just run` to see the MCP server start
3. **Add a simple tool**: Implement a basic Anvil component generator
4. **Write tests**: Add comprehensive test coverage
5. **Contribute**: Submit your first pull request!