# Contributing to Agent Orchestrator

Thank you for your interest in contributing! This guide will help you get started.

## Code of Conduct

Please be respectful and constructive in all interactions. We welcome contributors of all experience levels.

## Development Setup

### 1. Fork and Clone

```bash
# Fork the repository on GitHub, then:
git clone https://github.com/YOUR_USERNAME/agent-orchestrator.git
cd agent-orchestrator
```

### 2. Create Virtual Environment

```bash
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
```

### 3. Install Dependencies

```bash
# Install with development dependencies
pip install -e ".[dev]"

# Install pre-commit hooks
pre-commit install
```

### 4. Verify Setup

```bash
# Run tests
pytest tests/unit/ -v

# Run linting
make lint

# Run type checking
mypy src/
```

## Development Workflow

### 1. Create a Branch

```bash
git checkout -b feature/your-feature-name
# or
git checkout -b fix/your-bug-fix
```

### 2. Make Changes

- Write code following our style guidelines
- Add tests for new functionality
- Update documentation as needed

### 3. Run Checks

```bash
# Format code
black src/ tests/
isort src/ tests/

# Run linting
ruff check src/ tests/

# Run type checking
mypy src/

# Run tests
pytest tests/ -v --cov=agent_orchestrator
```

### 4. Commit Changes

```bash
# Stage changes
git add .

# Commit with conventional commit message
git commit -m "feat: add new feature description"
```

### 5. Push and Create PR

```bash
git push origin feature/your-feature-name
```

Then create a Pull Request on GitHub.

## Code Style

### Python Style

- **Formatter**: Black (line length 88)
- **Linter**: Ruff
- **Type Checker**: mypy
- **Import Sorter**: isort

### Conventions

```python
# Use type hints
def process_task(task: Task, timeout: int = 300) -> TaskResult:
    """Process a task and return the result.

    Args:
        task: The task to process.
        timeout: Timeout in seconds.

    Returns:
        The task result.

    Raises:
        TaskError: If processing fails.
    """
    ...

# Use dataclasses for data structures
@dataclass
class TaskConfig:
    name: str
    priority: int = 5
    timeout: int = 300

# Use enums for fixed values
class TaskStatus(Enum):
    PENDING = "pending"
    RUNNING = "running"
    COMPLETED = "completed"
    FAILED = "failed"

# Use async/await for I/O operations
async def fetch_data(url: str) -> dict:
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.json()
```

### Docstrings

Use Google-style docstrings:

```python
def calculate_cost(tokens: int, model: str) -> float:
    """Calculate the cost for token usage.

    Args:
        tokens: Number of tokens used.
        model: The model identifier.

    Returns:
        Cost in USD.

    Raises:
        ValueError: If model is not recognized.

    Example:
        >>> calculate_cost(1000, "opus")
        0.015
    """
```

## Testing

### Test Structure

```
tests/
├── unit/           # Unit tests (fast, isolated)
├── integration/    # Integration tests (slower, real components)
├── e2e/            # End-to-end tests (full system)
└── conftest.py     # Shared fixtures
```

### Writing Tests

```python
# tests/unit/test_budget.py
import pytest
from agent_orchestrator.budget import BudgetEnforcer

@pytest.fixture
def enforcer():
    """Create a budget enforcer for testing."""
    return BudgetEnforcer(daily_limit=100.0)

def test_check_budget_under_limit(enforcer):
    """Should allow request when under budget."""
    result = enforcer.check_budget("agent-1", estimated_cost=10.0)
    assert result.allowed is True

def test_check_budget_over_limit(enforcer):
    """Should reject request when over budget."""
    # Use up budget
    enforcer.record_usage("agent-1", cost=100.0)

    result = enforcer.check_budget("agent-1", estimated_cost=10.0)
    assert result.allowed is False
    assert "exceeded" in result.reason.lower()

@pytest.mark.asyncio
async def test_async_operation():
    """Test async operations."""
    result = await some_async_function()
    assert result is not None
```

### Running Tests

```bash
# Run all tests
pytest

# Run specific test file
pytest tests/unit/test_budget.py

# Run with coverage
pytest --cov=agent_orchestrator --cov-report=html

# Run only fast tests
pytest -m "not slow"

# Run in parallel
pytest -n auto
```

## Commit Messages

Use [Conventional Commits](https://www.conventionalcommits.org/):

```
<type>(<scope>): <description>

[optional body]

[optional footer]
```

### Types

| Type | Description |
|------|-------------|
| `feat` | New feature |
| `fix` | Bug fix |
| `docs` | Documentation changes |
| `style` | Code style (formatting, no logic change) |
| `refactor` | Code refactoring |
| `test` | Adding or updating tests |
| `chore` | Maintenance tasks |
| `perf` | Performance improvements |

### Examples

```bash
feat(budget): add cost optimization recommendations

fix(control): prevent race condition in agent cleanup

docs(api): add OpenAPI specification

test(workflows): add integration tests for parallel execution

refactor(adapters): extract common CLI adapter logic
```

## Pull Request Guidelines

### Before Submitting

- [ ] Tests pass locally (`pytest tests/`)
- [ ] Linting passes (`make lint`)
- [ ] Type checking passes (`mypy src/`)
- [ ] Documentation updated if needed
- [ ] Commit messages follow conventions

### PR Description Template

```markdown
## Summary
Brief description of changes.

## Type of Change
- [ ] Bug fix
- [ ] New feature
- [ ] Breaking change
- [ ] Documentation update

## Testing
- [ ] Added unit tests
- [ ] Added integration tests
- [ ] Manual testing performed

## Checklist
- [ ] Code follows style guidelines
- [ ] Self-review completed
- [ ] Documentation updated
- [ ] Tests added/updated
```

### Review Process

1. Automated checks run on PR
2. Maintainer reviews code
3. Address feedback
4. Approval and merge

## Adding New Features

### 1. Discuss First

For significant changes, open an issue first to discuss the approach.

### 2. Implementation Checklist

- [ ] Add feature code
- [ ] Add unit tests
- [ ] Add integration tests (if applicable)
- [ ] Update configuration (if needed)
- [ ] Update documentation
- [ ] Add example usage

### 3. Feature Flags

New features should be behind feature flags initially:

```python
if config.features.new_feature_enabled:
    # New feature code
else:
    # Existing behavior
```

## Creating Adapters

See [Adapter Development Guide](docs/ADAPTER_REFERENCE.md) for creating new agent adapters.

## Questions?

- **Issues**: [GitHub Issues](https://github.com/your-org/agent-orchestrator/issues)
- **Discussions**: [GitHub Discussions](https://github.com/your-org/agent-orchestrator/discussions)

Thank you for contributing!
