# AI Agent Collaboration Patterns

## Introduction

This document outlines best practices and patterns for AI agents collaborating on code projects. These patterns prevent common issues like file duplication, naming confusion, and version conflicts while promoting clear, maintainable code.

## The Golden Rules

### Rule #1: Never Create _refactored Versions
**This is the most important rule for AI agents.**

❌ **Never do this:**
```
django_config.py → django_config_refactored.py
user_handler.py → user_handler_refactored.py
```

✅ **Always do this:**
```
# Modify django_config.py directly
# Use git commits to track changes
# If needed, create django_config_v2.py with clear purpose
```

### Rule #2: One Source of Truth
- Each piece of functionality should exist in exactly one place
- No duplicate implementations
- No parallel versions
- Clear module boundaries

### Rule #3: Communicate Through Code
- Use clear naming to express intent
- Add comments explaining decisions
- Write self-documenting code
- Use type hints for clarity

## File Modification Patterns

### Pattern: In-Place Modification
**When refactoring or improving code:**

```python
# Step 1: Read and understand the existing file
# Step 2: Make changes directly to the file
# Step 3: Ensure tests still pass
# Step 4: Commit with clear message

# Good commit message:
# refactor(config): simplify validation logic and improve type safety

# Bad approach (creates confusion):
# Creating config_improved.py or config_refactored.py
```

### Pattern: Extract and Replace
**When extracting functionality to new modules:**

```python
# Original: user_handler.py (1000 lines)
# Contains authentication, validation, and processing

# Good extraction:
# user_handler.py (300 lines) - Core handler logic
# user_authentication.py (400 lines) - Auth logic
# user_validation.py (300 lines) - Validation logic

# Bad extraction:
# user_handler_old.py (original)
# user_handler_new.py (refactored)
```

### Pattern: Version Evolution
**When making breaking changes:**

```python
# Good versioning:
api_v1.py  # Original API (deprecated)
api_v2.py  # New API with clear improvements

# Bad versioning:
api.py
api_new.py
api_refactored.py
api_updated.py
```

## Code Organization Patterns

### Pattern: Consistent Module Structure
```
module/
├── __init__.py       # Public API exports
├── core.py          # Core functionality
├── handlers.py      # Request/event handlers
├── validators.py    # Input validation
├── utils.py         # Helper functions
└── exceptions.py    # Custom exceptions
```

### Pattern: Clear Separation of Concerns
```python
# Good: Each class has one clear responsibility
class UserAuthenticator:
    """Handles user authentication only."""
    pass

class UserValidator:
    """Handles user data validation only."""
    pass

class UserNotifier:
    """Handles user notifications only."""
    pass

# Bad: Mixed responsibilities
class UserManager:
    """Does everything user-related."""
    def authenticate(self): pass
    def validate(self): pass
    def send_email(self): pass
    def update_profile(self): pass
```

## Communication Patterns

### Pattern: Decision Documentation
```python
# When making architectural decisions:
"""
Authentication Module

Decision: Use JWT tokens instead of sessions
Rationale: 
- Stateless authentication scales better
- Works across multiple services
- Simplifies mobile app integration

Trade-offs:
- Token revocation is more complex
- Requires careful key management
"""
```

### Pattern: Change Explanation
```python
# Before (in commit message or PR):
"""
refactor(auth): migrate from session to JWT authentication

- Replace session-based auth with JWT tokens
- Add token refresh mechanism
- Update all endpoints to use new auth
- Maintain backward compatibility for 30 days

Breaking changes:
- Session cookies no longer valid
- New Authorization header format

Migration guide in docs/migration/auth_v2.md
"""
```

### Pattern: TODO with Context
```python
# Good: Provides context and ownership
# TODO(ticket-123): Implement rate limiting for auth endpoints
# Current limit is 100/min, should be 10/min for failed attempts
# See security audit recommendation SA-2024-001

# Bad: Vague TODO
# TODO: Add rate limiting
```

## Testing Collaboration Patterns

### Pattern: Test-Driven Modifications
```python
# Workflow for AI agents:
# 1. Run existing tests to ensure they pass
# 2. Add tests for new behavior
# 3. Modify code to make tests pass
# 4. Refactor if needed (tests still pass)
# 5. Commit both tests and code together

# Example commit:
# feat(user): add email verification with tests
```

### Pattern: Test File Mirroring
```
src/
├── handlers/
│   ├── user_handler.py
│   └── payment_handler.py
tests/
├── handlers/
│   ├── test_user_handler.py
│   └── test_payment_handler.py
```

## Error Handling Patterns

### Pattern: Graceful Degradation
```python
# When AI agents encounter issues:
try:
    result = complex_operation()
except SpecificError as e:
    # Log the error with context
    logger.warning(f"Complex operation failed: {e}", extra={
        "operation": "complex_operation",
        "fallback": "simple_operation"
    })
    # Fall back to simpler approach
    result = simple_operation()
```

### Pattern: Clear Error Messages
```python
# Good: Actionable error messages
class ConfigurationError(Exception):
    """Raised when configuration is invalid."""
    
    def __init__(self, field: str, value: Any, reason: str):
        super().__init__(
            f"Invalid configuration for '{field}': {value}. {reason}"
        )

# Usage:
raise ConfigurationError(
    "database_url", 
    "localhost:1234",
    "URL must include scheme (e.g., postgresql://)"
)
```

## Workflow Patterns

### Pattern: Feature Development Workflow
```
1. Understand requirements
   - Read issue/ticket
   - Understand existing code
   - Identify affected modules

2. Plan implementation
   - Identify files to modify (not copy!)
   - Plan test strategy
   - Consider backward compatibility

3. Implement incrementally
   - Start with tests
   - Implement core functionality
   - Add error handling
   - Update documentation

4. Validate changes
   - Run all tests
   - Check code style
   - Verify documentation
   - Test edge cases

5. Commit atomically
   - Group related changes
   - Write clear commit message
   - Reference issues/tickets
```

### Pattern: Bug Fix Workflow
```
1. Reproduce the issue
   - Create failing test
   - Understand root cause
   - Document findings

2. Fix the issue
   - Modify affected code
   - Ensure test passes
   - Check for regressions

3. Prevent recurrence
   - Add comprehensive tests
   - Update documentation
   - Consider similar issues
```

### Pattern: Refactoring Workflow
```
1. Ensure comprehensive tests exist
   - If not, add tests first
   - Run tests, ensure all pass

2. Refactor incrementally
   - Small, focused changes
   - Run tests after each change
   - Commit working states

3. Clean up
   - Remove dead code
   - Update documentation
   - Verify no behavior changes
```

## Anti-Patterns to Avoid

### Anti-Pattern: Parallel Development
```python
# DON'T: Create parallel versions
main.py
main_improved.py
main_v2.py
main_refactored.py

# DO: Work on main.py directly
# Use branches for experimental changes
```

### Anti-Pattern: Confusion Through Naming
```python
# DON'T: Ambiguous names
handler_new.py
handler_old.py
handler_temp.py
handler_backup.py

# DO: Clear, purposeful names
user_handler.py
payment_handler.py
notification_handler.py
```

### Anti-Pattern: Hidden Dependencies
```python
# DON'T: Implicit dependencies
from .utils import *  # What's being imported?

# DO: Explicit imports
from .utils import validate_email, hash_password
```

## Best Practices for AI Agents

### 1. Before Making Changes
- Read existing code thoroughly
- Understand the architecture
- Check for existing patterns
- Review recent commits

### 2. During Development
- Follow existing patterns
- Maintain consistency
- Add helpful comments
- Keep changes focused

### 3. After Changes
- Run all tests
- Update documentation
- Check for side effects
- Commit with clear messages

### 4. Communication
- Explain complex changes
- Document decisions
- Reference issues/tickets
- Highlight breaking changes

## Examples of Good AI Agent Behavior

### Example 1: Refactoring Configuration
```python
# Task: Refactor django_config.py for better maintainability

# Good approach:
1. Analyze django_config.py structure
2. Identify improvement areas
3. Modify django_config.py directly
4. Add/update tests
5. Commit: "refactor(django): improve config maintainability"

# Bad approach:
1. Create django_config_refactored.py
2. Copy and modify code
3. Leave both files in place
4. Create confusion about which to use
```

### Example 2: Adding New Feature
```python
# Task: Add user notification system

# Good approach:
1. Create notification_handler.py (new functionality)
2. Integrate with existing user_handler.py
3. Add comprehensive tests
4. Update documentation
5. Commit: "feat(notifications): add user notification system"

# Bad approach:
1. Copy user_handler.py to user_handler_with_notifications.py
2. Add notification code to copy
3. Leave both versions
4. Unclear which to use
```

### Example 3: Fixing Bug
```python
# Task: Fix authentication timeout issue

# Good approach:
1. Add failing test for timeout scenario
2. Fix issue in auth_handler.py
3. Verify test passes
4. Check for similar issues
5. Commit: "fix(auth): resolve timeout on slow connections"

# Bad approach:
1. Create auth_handler_fixed.py
2. Apply fix to copy
3. Leave both versions
4. No tests added
```

## Summary

Successful AI agent collaboration requires:

1. **Clear Communication**: Through code, comments, and commits
2. **Consistent Patterns**: Following established conventions
3. **Single Source of Truth**: One version of each component
4. **In-Place Modification**: No parallel versions or _refactored files
5. **Comprehensive Testing**: Tests guide and validate changes
6. **Thoughtful Organization**: Clear structure and separation

By following these patterns, AI agents can work effectively together and with human developers, creating maintainable, professional code without confusion or duplication.