# Development Guide

## Getting Started

### Prerequisites
- Python 3.10+
- pip
- git

### Setup Development Environment

1. **Clone the repository**
   ```bash
   git clone https://github.com/yourusername/behavioural-contracts.git
   cd behavioural-contracts
   ```

2. **Create virtual environment**
   ```bash
   python -m venv venv
   source venv/bin/activate  # On Windows: venv\Scripts\activate
   ```

3. **Install dependencies**
   ```bash
   pip install -e ".[dev]"
   ```

4. **Install pre-commit hooks**
   ```bash
   pre-commit install
   ```

## Development Workflow

### 1. Code Quality

**Linting and Formatting**
```bash
# Check code style
ruff check .

# Format code
ruff format .

# Type checking
mypy behavioural_contracts/
```

**Pre-commit Hooks**
The repository uses pre-commit hooks to ensure code quality:
- ruff (linting and formatting)
- mypy (type checking)
- pytest (basic tests)

### 2. Testing

**Run all tests**
```bash
pytest tests/ -v
```

**Run specific test categories**
```bash
# Security tests
pytest tests/test_phase1_enhancements.py -v
pytest tests/test_github_hallucination_fix.py -v

# Compliance tests
pytest tests/test_compliance_templates.py -v

# Performance tests
pytest tests/test_performance.py -v

# Basic functionality
pytest tests/test_simple_contract.py -v
```

**Run with coverage**
```bash
pytest tests/ -v --cov=behavioural_contracts --cov-report=html
```

**Run the test suite**
```bash
python run_tests.py
```

### 3. Interactive Development

**Demo Applications**
```bash
# Interactive demo
python demo/interactive_demo.py

# Live agent testing
python demo/live_agent_demo.py
```

## Architecture Overview

### Core Modules

1. **`contract.py`** - Main contract enforcement logic
2. **`security.py`** - Security features (prompt injection, context validation)
3. **`compliance_templates.py`** - Pre-configured compliance templates
4. **`validator.py`** - Response validation logic
5. **`performance.py`** - Performance optimization features
6. **`generator.py`** - Contract generation utilities
7. **`health_monitor.py`** - Health monitoring and metrics
8. **`temperature.py`** - Temperature control logic

### Key Design Patterns

1. **Decorator Pattern** - `@behavioural_contract` and `@create_compliant_agent`
2. **Strategy Pattern** - Different validation strategies
3. **Template Pattern** - Compliance templates
4. **Observer Pattern** - Health monitoring

## Adding New Features

### 1. New Compliance Template

```python
# In compliance_templates.py
@staticmethod
def new_framework_template() -> dict[str, Any]:
    """New compliance framework template."""
    return {
        "version": "1.0.0",
        "description": "New Framework compliant contract",
        "compliance_framework": "NEW_FRAMEWORK",
        "policy": {
            "pii": False,
            "compliance_tags": ["NEW_FRAMEWORK"],
        },
        "behavioural_flags": {
            "conservatism": "high",
            "temperature_control": {
                "mode": "strict",
                "range": [0.1, 0.3],
            },
        },
        "response_contract": {
            "output_format": {
                "required_fields": [
                    "compliance_status",
                    "framework_specific_field",
                ]
            },
        },
    }
```

### 2. New Security Feature

```python
# In security.py
class NewSecurityFeature:
    """New security feature implementation."""
    
    def __init__(self):
        self.config = {}
    
    def validate(self, input_data: dict[str, Any]) -> tuple[bool, str]:
        """Validate input data."""
        # Implementation here
        return True, "Validation passed"
```

### 3. New Performance Optimization

```python
# In performance.py
def new_optimization_decorator(func: Callable) -> Callable:
    """New performance optimization decorator."""
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # Optimization logic here
        return func(*args, **kwargs)
    return wrapper
```

## Testing Guidelines

### 1. Test Structure

```python
class TestNewFeature:
    """Test new feature functionality."""
    
    def test_basic_functionality(self):
        """Test basic functionality."""
        # Arrange
        # Act
        # Assert
    
    def test_edge_cases(self):
        """Test edge cases."""
        pass
    
    def test_error_conditions(self):
        """Test error conditions."""
        pass
    
    @pytest.mark.asyncio
    async def test_async_functionality(self):
        """Test async functionality."""
        pass
```

### 2. Test Naming Conventions

- `test_<feature>_<scenario>` - Basic functionality tests
- `test_<feature>_<edge_case>` - Edge case tests
- `test_<feature>_error_<condition>` - Error condition tests
- `test_<feature>_integration` - Integration tests

### 3. Test Coverage Requirements

- Unit tests: 80%+ coverage
- Integration tests: All major workflows
- Performance tests: All optimization features
- Security tests: All security features

## Documentation Guidelines

### 1. Code Documentation

```python
def function_name(param1: str, param2: int) -> dict[str, Any]:
    """
    Brief description of what the function does.
    
    Args:
        param1: Description of param1
        param2: Description of param2
        
    Returns:
        Description of return value
        
    Raises:
        ValueError: When param1 is invalid
        
    Example:
        >>> function_name("test", 42)
        {'result': 'success'}
    """
    pass
```

### 2. Module Documentation

```python
"""
Module description.

This module provides functionality for...

Key Features:
- Feature 1
- Feature 2

Usage:
    from behavioural_contracts import module_name
    
    result = module_name.function_name()
"""
```

### 3. API Documentation

Update `docs/API_REFERENCE.md` when adding new public APIs.

## Release Process

### 1. Version Bumping

```bash
# Update version in pyproject.toml
# Update __version__ in __init__.py
# Update CHANGELOG.md
```

### 2. Pre-release Checklist

- [ ] All tests pass
- [ ] Code coverage >= 80%
- [ ] Documentation updated
- [ ] CHANGELOG.md updated
- [ ] Version bumped
- [ ] Security scan clean

### 3. Release Commands

```bash
# Build package
python -m build

# Check package
twine check dist/*

# Upload to PyPI (test)
twine upload --repository testpypi dist/*

# Upload to PyPI (production)
twine upload dist/*
```

## Troubleshooting

### Common Issues

1. **Import errors**
   ```bash
   pip install -e .
   ```

2. **Test failures**
   ```bash
   pytest tests/ -v --tb=short
   ```

3. **Linting errors**
   ```bash
   ruff check . --fix
   ```

4. **Type checking errors**
   ```bash
   mypy behavioural_contracts/ --ignore-missing-imports
   ```

### Performance Issues

1. **Slow tests**
   ```bash
   pytest tests/ -v --durations=10
   ```

2. **Memory issues**
   ```bash
   pytest tests/ --maxfail=1
   ```

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Update documentation
6. Run the full test suite
7. Submit a pull request

### Pull Request Checklist

- [ ] Code follows style guidelines
- [ ] Tests pass
- [ ] Documentation updated
- [ ] No security vulnerabilities
- [ ] Performance impact assessed
- [ ] Backward compatibility maintained 