# AI Agent-Friendly Coding Standards

## Overview

This document outlines coding standards optimized for AI agent development and collaboration. Following these standards ensures code is clear, unambiguous, and easy for both humans and AI agents to understand and modify.

## Core Principles

### 1. Clarity Over Cleverness
- Write code that is immediately understandable
- Avoid complex one-liners when multiple lines are clearer
- Use descriptive names even if they're longer
- Explicit is better than implicit

### 2. Consistency is Key
- Use the same patterns throughout the codebase
- Follow established naming conventions religiously
- Maintain consistent code structure
- Keep similar functionality in similar locations

### 3. Self-Documenting Code
- Code should explain itself through clear naming
- Add comments only when the "why" isn't obvious
- Use type hints to clarify intentions
- Structure code to tell a story

## Critical Anti-Patterns to Avoid

### 1. The "_refactored" Anti-Pattern ❌
**Never do this:**
```python
# Original file
user_handler.py

# Creating a refactored version
user_handler_refactored.py  # DON'T DO THIS!
```

**Why it's problematic:**
- Creates confusion about which version to use
- Breaks import statements
- Complicates version control history
- Makes AI agents uncertain about the canonical version

**Instead, do this:**
- Modify the original file directly
- Use version control for history
- If major changes needed, use clear versioning (v2, v3)

### 2. Ambiguous Naming ❌
**Avoid these patterns:**
- `_temp`, `_tmp` - What makes it temporary?
- `_old`, `_new` - Version control handles this
- `_copy`, `_backup` - Unclear purpose
- `_test` in production code - Tests belong in test directory

### 3. State-Based Names ❌
**Don't encode state in names:**
```python
# Bad
config_old.py
config_new.py
config_backup.py

# Good
config.py  # Let version control handle history
```

## File Organization Standards

### 1. Module Structure
```
project/
├── src/
│   ├── handlers/       # Group by functionality
│   ├── processors/     # Clear purpose
│   ├── utils/         # Shared utilities
│   └── config/        # Configuration
├── tests/             # Mirror src structure
└── docs/              # Documentation
```

### 2. File Naming
- Use lowercase with underscores
- Be descriptive but concise
- Group related files with common prefixes
- Avoid redundant suffixes

**Examples:**
```
Good: user_authentication.py, payment_processor.py
Bad: userAuth.py, payment_processor_new.py
```

## Code Structure Standards

### 1. Function Organization
```python
# Good: Clear sections with consistent ordering
class UserHandler:
    # Initialization
    def __init__(self):
        pass
    
    # Public methods (primary interface)
    def create_user(self):
        pass
    
    def update_user(self):
        pass
    
    # Private methods (internal helpers)
    def _validate_email(self):
        pass
    
    def _hash_password(self):
        pass
```

### 2. Import Organization
```python
# Standard library imports
import os
import sys
from pathlib import Path

# Third-party imports
import requests
from django.conf import settings

# Local imports
from .models import User
from .utils import validate_email
```

## Documentation Standards

### 1. Module Documentation
```python
"""
User authentication module.

This module handles user authentication including login, logout,
and session management. It integrates with Django's auth system
while providing additional business logic.

Key components:
- UserAuthenticator: Main authentication class
- SessionManager: Handles session lifecycle
- TokenValidator: Validates auth tokens
"""
```

### 2. Function Documentation
```python
def authenticate_user(username: str, password: str) -> Optional[User]:
    """
    Authenticate a user with username and password.
    
    Args:
        username: The user's username or email
        password: The user's password (will be hashed)
        
    Returns:
        User object if authentication successful, None otherwise
        
    Raises:
        ValidationError: If username/password format is invalid
        RateLimitError: If too many failed attempts
        
    Example:
        user = authenticate_user("john@example.com", "securepass")
        if user:
            create_session(user)
    """
```

### 3. Inline Comments
```python
# Good: Explains why, not what
# Use BCrypt for password hashing as it's resistant to timing attacks
hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())

# Bad: Explains what (obvious from code)
# Hash the password
hashed = hash_password(password)
```

## Testing Standards

### 1. Test File Organization
```
tests/
├── unit/
│   ├── test_user_handler.py
│   └── test_payment_processor.py
├── integration/
│   └── test_user_workflow.py
└── fixtures/
    └── user_fixtures.py
```

### 2. Test Naming
```python
class TestUserAuthentication:
    def test_valid_credentials_return_user(self):
        """Test that valid credentials return a user object."""
        pass
    
    def test_invalid_password_returns_none(self):
        """Test that invalid password returns None."""
        pass
    
    def test_rate_limiting_after_failed_attempts(self):
        """Test that rate limiting kicks in after 5 failed attempts."""
        pass
```

## Version Control Standards

### 1. Commit Messages
```
Format: <type>(<scope>): <subject>

Types:
- feat: New feature
- fix: Bug fix
- refactor: Code change that neither fixes a bug nor adds a feature
- test: Adding missing tests
- docs: Documentation only changes

Examples:
feat(auth): add two-factor authentication
fix(payments): resolve decimal precision issue
refactor(user): simplify validation logic
```

### 2. Branch Naming
```
feature/add-user-authentication
bugfix/payment-calculation-error
refactor/simplify-config-validation
```

## AI Agent Collaboration

### 1. Code Modifications
- Always modify files in place
- Never create parallel versions
- Use clear commit messages
- Document significant changes

### 2. Communication
```python
# When making non-obvious changes, add a comment
# Changed from email validation to username validation
# to support non-email usernames (ticket #123)
def validate_username(username: str) -> bool:
    # Previous implementation validated email format
    # New implementation supports any alphanumeric string
    return username.isalnum()
```

### 3. Refactoring Approach
1. Ensure tests pass before starting
2. Make incremental changes
3. Keep commits atomic and focused
4. Update documentation immediately
5. Never create `_refactored` versions

## Common Patterns

### 1. Configuration Management
```python
# Good: Clear, extensible configuration
class AppConfig:
    def __init__(self):
        self.debug = self._get_bool_env("DEBUG", False)
        self.database_url = self._get_env("DATABASE_URL")
        self.cache_ttl = self._get_int_env("CACHE_TTL", 3600)
```

### 2. Error Handling
```python
# Good: Specific error handling with context
try:
    user = User.objects.get(id=user_id)
except User.DoesNotExist:
    logger.warning(f"User not found: {user_id}")
    raise UserNotFoundError(f"No user with ID {user_id}")
except DatabaseError as e:
    logger.error(f"Database error retrieving user {user_id}: {e}")
    raise ServiceUnavailableError("Unable to retrieve user")
```

### 3. Dependency Injection
```python
# Good: Testable, flexible design
class UserService:
    def __init__(self, 
                 user_repo: UserRepository,
                 email_service: EmailService,
                 logger: Logger):
        self.user_repo = user_repo
        self.email_service = email_service
        self.logger = logger
```

## Checklist for AI-Friendly Code

Before committing code, ensure:

- [ ] No `_refactored`, `_temp`, `_old`, `_new` in filenames
- [ ] Clear, descriptive names throughout
- [ ] Consistent naming conventions
- [ ] Module and function docstrings present
- [ ] Complex logic has explanatory comments
- [ ] Tests updated with code changes
- [ ] Changes made to original files, not copies
- [ ] Commit message follows conventions
- [ ] No temporary code or files left behind
- [ ] Type hints used where helpful

## Summary

Following these standards ensures that code is:
1. **Clear**: Easy to understand at first glance
2. **Consistent**: Follows predictable patterns
3. **Maintainable**: Easy to modify and extend
4. **AI-Friendly**: Unambiguous for automated tools
5. **Professional**: Ready for enterprise use

Remember: The goal is to write code that any developer (human or AI) can understand and modify confidently without creating confusion or parallel versions.