# Contributing to ThinkBank

Thank you for your interest in contributing to ThinkBank! This document provides guidelines and instructions for contributing to the project.

---

## Table of Contents

- [Code of Conduct](#code-of-conduct)
- [Getting Started](#getting-started)
- [Development Setup](#development-setup)
- [Making Changes](#making-changes)
- [Code Style](#code-style)
- [Testing](#testing)
- [Submitting Changes](#submitting-changes)
- [Review Process](#review-process)
- [Community](#community)

---

## Code of Conduct

### Our Pledge

We are committed to providing a welcoming and inclusive experience for everyone. We expect all contributors to:

- **Be respectful** - Value differing opinions and experiences
- **Be collaborative** - Work together to achieve shared goals
- **Be constructive** - Provide helpful feedback and suggestions
- **Be patient** - Remember that everyone is learning

### Unacceptable Behavior

- Harassment, discrimination, or offensive comments
- Trolling, insulting remarks, or personal attacks
- Publishing others' private information
- Any conduct that would be inappropriate in a professional setting

---

## Getting Started

### Ways to Contribute

1. **Report Bugs** - Found a bug? [Open an issue](https://github.com/dwHou/ThinkBank/issues)
2. **Suggest Features** - Have an idea? [Start a discussion](https://github.com/dwHou/ThinkBank/discussions)
3. **Improve Documentation** - Fix typos, add examples, clarify explanations
4. **Write Code** - Fix bugs, implement features, optimize performance
5. **Review Pull Requests** - Help review and test changes

### Good First Issues

Look for issues tagged with:
- `good first issue` - Perfect for newcomers
- `help wanted` - We need community help
- `documentation` - Improve docs

---

## Development Setup

### Prerequisites

- Python 3.9 or higher
- Git
- Virtual environment tool (venv, virtualenv, or conda)

### Setup Steps

1. **Fork the repository**

   Click the "Fork" button on GitHub.

2. **Clone your fork**

   ```bash
   git clone https://github.com/YOUR_USERNAME/ThinkBank.git
   cd ThinkBank
   ```

3. **Create a virtual environment**

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

   # Or using conda
   conda create -n thinkbank python=3.9
   conda activate thinkbank
   ```

4. **Install development dependencies**

   ```bash
   pip install -e ".[dev]"
   ```

5. **Verify installation**

   ```bash
   pytest
   black --check thinkbank/
   flake8 thinkbank/
   mypy thinkbank/
   ```

### Project Structure

```
ThinkBank/
├── thinkbank/               # Main package
│   ├── core/              # Core library
│   ├── server/            # FastAPI backend
│   └── cli/               # CLI interface
├── tests/                 # Test suite
├── docs/                  # Documentation
├── templates/             # Knowledge templates
├── setup.py               # Package setup
├── pyproject.toml         # Modern packaging config
└── README.md              # Project README
```

---

## Making Changes

### Branch Naming

Use descriptive branch names:

```bash
# Feature branches
git checkout -b feature/add-vector-search
git checkout -b feature/improve-web-ui

# Bug fix branches
git checkout -b fix/export-encoding-issue
git checkout -b fix/server-timeout

# Documentation branches
git checkout -b docs/add-api-examples
git checkout -b docs/update-quickstart
```

### Commit Messages

Follow the [Conventional Commits](https://www.conventionalcommits.org/) format:

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

[optional body]

[optional footer]
```

**Types:**
- `feat` - New feature
- `fix` - Bug fix
- `docs` - Documentation changes
- `style` - Code style changes (formatting, etc.)
- `refactor` - Code refactoring
- `test` - Adding or updating tests
- `chore` - Maintenance tasks

**Examples:**

```bash
feat(core): add vector search for semantic similarity

Implements cosine similarity search using sentence transformers.
Adds VectorSearchManager class with index building and querying.

Closes #42

---

fix(export): handle unicode characters in knowledge pack names

Previously, exporting with non-ASCII characters in pack names
would fail with encoding errors. Now properly handles UTF-8.

Fixes #58

---

docs(readme): add troubleshooting section

Adds common issues and solutions to help users debug problems.
```

---

## Code Style

### Python Style Guide

We follow [PEP 8](https://pep8.org/) with these tools:

#### Black (Code Formatter)

```bash
# Format code
black thinkbank/

# Check without modifying
black --check thinkbank/
```

**Configuration:** See `[tool.black]` in `pyproject.toml`

#### isort (Import Sorting)

```bash
# Sort imports
isort thinkbank/

# Check without modifying
isort --check thinkbank/
```

#### Flake8 (Linter)

```bash
# Lint code
flake8 thinkbank/
```

#### MyPy (Type Checking)

```bash
# Type check
mypy thinkbank/
```

### Code Conventions

#### Type Hints

Always use type hints for function signatures:

```python
# Good
def calculate_score(factors: Dict[str, float], weights: Dict[str, float]) -> float:
    """Calculate weighted score."""
    return sum(factors[k] * weights[k] for k in factors)

# Bad
def calculate_score(factors, weights):
    return sum(factors[k] * weights[k] for k in factors)
```

#### Docstrings

Use Google-style docstrings:

```python
def export_knowledge_pack(
    output_path: str,
    filter_criteria: Optional[Dict[str, Any]] = None,
    format: str = "json",
    metadata: Optional[Dict[str, str]] = None
) -> Dict[str, Any]:
    """
    Export knowledge items to a compressed pack file.

    Args:
        output_path: Path to output .khb file
        filter_criteria: Optional filters (type, score, tags, etc.)
        format: Export format ("json" or "yaml")
        metadata: Optional pack metadata (name, author, description)

    Returns:
        dict: Export result with keys:
            - success (bool): Whether export succeeded
            - count (int): Number of items exported
            - path (str): Absolute path to output file
            - size_kb (float): File size in KB
            - metadata (dict): Pack metadata

    Raises:
        ValueError: If output_path doesn't end with .khb
        IOError: If file cannot be written

    Example:
        >>> result = export_knowledge_pack(
        ...     "my_knowledge.khb",
        ...     filter_criteria={"min_score": 0.7},
        ...     metadata={"name": "My Best Knowledge"}
        ... )
        >>> print(f"Exported {result['count']} items")
    """
```

#### Error Handling

Be explicit about exceptions:

```python
# Good
try:
    data = read_yaml(file_path)
except FileNotFoundError:
    logger.error(f"File not found: {file_path}")
    return None
except yaml.YAMLError as e:
    logger.error(f"Invalid YAML: {e}")
    return None

# Bad
try:
    data = read_yaml(file_path)
except:
    return None
```

---

## Testing

### Running Tests

```bash
# Run all tests
pytest

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

# Run specific test file
pytest tests/test_knowledge_manager.py

# Run specific test
pytest tests/test_knowledge_manager.py::test_create_knowledge_item
```

### Writing Tests

Use pytest with clear test names:

```python
import pytest
from thinkbank.core import KnowledgeManager

def test_create_knowledge_item_with_valid_data():
    """Test that valid knowledge items are created successfully."""
    km = KnowledgeManager()

    knowledge_id = km.create(
        knowledge_type="skill",
        title="Test Skill",
        content="Test content",
        factors={"reusability": 0.8}
    )

    assert knowledge_id is not None
    assert knowledge_id.startswith("skill-")


def test_create_knowledge_item_with_invalid_type():
    """Test that invalid knowledge types raise ValueError."""
    km = KnowledgeManager()

    with pytest.raises(ValueError, match="Invalid knowledge type"):
        km.create(
            knowledge_type="invalid_type",
            title="Test",
            content="Test"
        )
```

### Test Coverage

We aim for **80%+ test coverage**. Check coverage with:

```bash
pytest --cov=thinkbank --cov-report=term-missing
```

---

## Submitting Changes

### Pull Request Process

1. **Update your fork**

   ```bash
   git fetch upstream
   git checkout main
   git merge upstream/main
   ```

2. **Create a feature branch**

   ```bash
   git checkout -b feature/your-feature-name
   ```

3. **Make your changes**

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

4. **Run tests and linters**

   ```bash
   pytest
   black thinkbank/
   isort thinkbank/
   flake8 thinkbank/
   mypy thinkbank/
   ```

5. **Commit your changes**

   ```bash
   git add .
   git commit -m "feat(core): add your feature"
   ```

6. **Push to your fork**

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

7. **Open a pull request**

   - Go to the [ThinkBank repository](https://github.com/dwHou/ThinkBank)
   - Click "New Pull Request"
   - Select your branch
   - Fill out the PR template

### Pull Request Template

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

## Type of Change
- [ ] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing functionality to change)
- [ ] Documentation update

## Checklist
- [ ] Code follows project style guidelines
- [ ] Self-review completed
- [ ] Comments added to hard-to-understand areas
- [ ] Documentation updated
- [ ] Tests added/updated
- [ ] All tests pass
- [ ] No new warnings

## Related Issues
Closes #123
Related to #456
```

---

## Review Process

### What to Expect

1. **Automated Checks** - GitHub Actions will run tests and linters
2. **Code Review** - Maintainers will review your code
3. **Feedback** - You may be asked to make changes
4. **Approval** - Once approved, your PR will be merged

### Review Timeline

- Small PRs (< 50 lines): 1-2 days
- Medium PRs (50-200 lines): 3-5 days
- Large PRs (> 200 lines): 1 week+

**Tip:** Smaller PRs get reviewed faster!

### Responding to Feedback

- Be receptive to suggestions
- Ask questions if something is unclear
- Make requested changes promptly
- Update your PR with new commits

---

## Community

### Getting Help

- **GitHub Discussions** - [Ask questions](https://github.com/dwHou/ThinkBank/discussions)
- **GitHub Issues** - [Report bugs](https://github.com/dwHou/ThinkBank/issues)
- **Email** - (Add your contact email)

### Stay Connected

- Star the repository to show support
- Watch for updates
- Follow contributors

---

## Recognition

Contributors will be:
- Added to [CONTRIBUTORS.md](CONTRIBUTORS.md)
- Mentioned in release notes
- Forever appreciated!

---

## License

By contributing, you agree that your contributions will be licensed under the **MIT License**.

---

<p align="center">
  <b>Thank you for contributing to ThinkBank!</b><br>
  Together, we're building a better AI knowledge management system.
</p>
