Major additions: - Add CODING_GUIDELINES.md with "NO EMOJIS" rule - Create code-fixer agent for automated violation fixes - Add offline mode v2 hooks with local caching/queue - Add periodic context save with invisible Task Scheduler setup - Add agent coordination rules and database connection docs Infrastructure: - Update hooks: task-complete-v2, user-prompt-submit-v2 - Add periodic_save_check.py for auto-save every 5min - Add PowerShell scripts: setup_periodic_save.ps1, update_to_invisible.ps1 - Add sync-contexts script for queue synchronization Documentation: - OFFLINE_MODE.md, PERIODIC_SAVE_INVISIBLE_SETUP.md - Migration procedures and verification docs - Fix flashing window guide Updates: - Update agent configs (backup, code-review, coding, database, gitea, testing) - Update claude.md with coding guidelines reference - Update .gitignore for new cache/queue directories Status: Pre-automated-fixer baseline commit Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
429 lines
9.3 KiB
Markdown
429 lines
9.3 KiB
Markdown
# ClaudeTools - Coding Guidelines
|
|
|
|
## General Principles
|
|
|
|
These guidelines ensure code quality, consistency, and maintainability across the ClaudeTools project.
|
|
|
|
---
|
|
|
|
## Character Encoding and Text
|
|
|
|
### NO EMOJIS - EVER
|
|
|
|
**Rule:** Never use emojis in any code files, including:
|
|
- Python scripts (.py)
|
|
- PowerShell scripts (.ps1)
|
|
- Bash scripts (.sh)
|
|
- Configuration files
|
|
- Documentation within code
|
|
- Log messages
|
|
- Output strings
|
|
|
|
**Rationale:**
|
|
- Emojis cause encoding issues (UTF-8 vs ASCII)
|
|
- PowerShell parsing errors with special Unicode characters
|
|
- Cross-platform compatibility problems
|
|
- Terminal rendering inconsistencies
|
|
- Version control diff issues
|
|
|
|
**Instead of emojis, use:**
|
|
```powershell
|
|
# BAD - causes parsing errors
|
|
Write-Host "✓ Success!"
|
|
Write-Host "⚠ Warning!"
|
|
|
|
# GOOD - ASCII text markers
|
|
Write-Host "[OK] Success!"
|
|
Write-Host "[SUCCESS] Task completed!"
|
|
Write-Host "[WARNING] Check settings!"
|
|
Write-Host "[ERROR] Failed to connect!"
|
|
```
|
|
|
|
**Allowed in:**
|
|
- User-facing web UI (where Unicode is properly handled)
|
|
- Database content (with proper UTF-8 encoding)
|
|
- Markdown documentation (README.md, etc.) - use sparingly
|
|
|
|
---
|
|
|
|
## Python Code Standards
|
|
|
|
### Style
|
|
- Follow PEP 8 style guide
|
|
- Use 4 spaces for indentation (no tabs)
|
|
- Maximum line length: 100 characters (relaxed from 79)
|
|
- Use type hints for function parameters and return values
|
|
|
|
### Imports
|
|
```python
|
|
# Standard library imports
|
|
import os
|
|
import sys
|
|
from datetime import datetime
|
|
|
|
# Third-party imports
|
|
from fastapi import FastAPI
|
|
from sqlalchemy import Column
|
|
|
|
# Local imports
|
|
from api.models import User
|
|
from api.utils import encrypt_data
|
|
```
|
|
|
|
### Naming Conventions
|
|
- Classes: `PascalCase` (e.g., `UserService`, `CredentialModel`)
|
|
- Functions/methods: `snake_case` (e.g., `get_user`, `create_session`)
|
|
- Constants: `UPPER_SNAKE_CASE` (e.g., `API_BASE_URL`, `MAX_RETRIES`)
|
|
- Private methods: `_leading_underscore` (e.g., `_internal_helper`)
|
|
|
|
---
|
|
|
|
## PowerShell Code Standards
|
|
|
|
### Style
|
|
- Use 4 spaces for indentation
|
|
- Use PascalCase for variables: `$TaskName`, `$PythonPath`
|
|
- Use approved verbs for functions: `Get-`, `Set-`, `New-`, `Remove-`
|
|
|
|
### Error Handling
|
|
```powershell
|
|
# Always use -ErrorAction for cmdlets that might fail
|
|
$Task = Get-ScheduledTask -TaskName $TaskName -ErrorAction SilentlyContinue
|
|
if (-not $Task) {
|
|
Write-Host "[ERROR] Task not found"
|
|
exit 1
|
|
}
|
|
```
|
|
|
|
### Output
|
|
```powershell
|
|
# Use clear status markers
|
|
Write-Host "[INFO] Starting process..."
|
|
Write-Host "[SUCCESS] Task completed"
|
|
Write-Host "[ERROR] Failed to connect"
|
|
Write-Host "[WARNING] Configuration missing"
|
|
```
|
|
|
|
---
|
|
|
|
## Bash Script Standards
|
|
|
|
### Style
|
|
- Use 2 spaces for indentation
|
|
- Always use `#!/bin/bash` shebang
|
|
- Quote all variables: `"$variable"` not `$variable`
|
|
- Use `set -e` for error handling (exit on error)
|
|
|
|
### Functions
|
|
```bash
|
|
# Use lowercase with underscores
|
|
function check_connection() {
|
|
local host="$1"
|
|
echo "[INFO] Checking connection to $host"
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## API Development Standards
|
|
|
|
### Endpoints
|
|
- Use RESTful conventions
|
|
- Use plural nouns: `/api/users` not `/api/user`
|
|
- Use HTTP methods appropriately: GET, POST, PUT, DELETE
|
|
- Version APIs if breaking changes: `/api/v2/users`
|
|
|
|
### Error Responses
|
|
```python
|
|
# Return consistent error format
|
|
{
|
|
"detail": "User not found",
|
|
"error_code": "USER_NOT_FOUND",
|
|
"status_code": 404
|
|
}
|
|
```
|
|
|
|
### Documentation
|
|
- Every endpoint must have a docstring
|
|
- Use Pydantic schemas for request/response validation
|
|
- Document in OpenAPI (automatic with FastAPI)
|
|
|
|
---
|
|
|
|
## Database Standards
|
|
|
|
### Table Naming
|
|
- Use lowercase with underscores: `user_sessions`, `billable_time`
|
|
- Use plural nouns: `users` not `user`
|
|
- Use consistent prefixes for related tables
|
|
|
|
### Columns
|
|
- Primary key: `id` (UUID)
|
|
- Timestamps: `created_at`, `updated_at`
|
|
- Foreign keys: `{table}_id` (e.g., `user_id`, `project_id`)
|
|
- Boolean: `is_active`, `has_access` (prefix with is_/has_)
|
|
|
|
### Indexes
|
|
```python
|
|
# Add indexes for frequently queried fields
|
|
Index('idx_users_email', 'email')
|
|
Index('idx_sessions_project_id', 'project_id')
|
|
```
|
|
|
|
---
|
|
|
|
## Security Standards
|
|
|
|
### Credentials
|
|
- Never hardcode credentials in code
|
|
- Use environment variables for sensitive data
|
|
- Use `.env` files (gitignored) for local development
|
|
- Encrypt passwords with AES-256-GCM (Fernet)
|
|
|
|
### Authentication
|
|
- Use JWT tokens for API authentication
|
|
- Hash passwords with Argon2
|
|
- Include token expiration
|
|
- Log all authentication attempts
|
|
|
|
### Audit Logging
|
|
```python
|
|
# Log all sensitive operations
|
|
audit_log = CredentialAuditLog(
|
|
credential_id=credential.id,
|
|
action="password_updated",
|
|
user_id=current_user.id,
|
|
details="Password updated via API"
|
|
)
|
|
```
|
|
|
|
---
|
|
|
|
## Testing Standards
|
|
|
|
### Test Files
|
|
- Name: `test_{module_name}.py`
|
|
- Location: Same directory as code being tested
|
|
- Use pytest framework
|
|
|
|
### Test Structure
|
|
```python
|
|
def test_create_user():
|
|
"""Test user creation with valid data."""
|
|
# Arrange
|
|
user_data = {"email": "test@example.com", "name": "Test"}
|
|
|
|
# Act
|
|
result = create_user(user_data)
|
|
|
|
# Assert
|
|
assert result.email == "test@example.com"
|
|
assert result.id is not None
|
|
```
|
|
|
|
### Coverage
|
|
- Aim for 80%+ code coverage
|
|
- Test happy path and error cases
|
|
- Mock external dependencies (database, APIs)
|
|
|
|
---
|
|
|
|
## Git Commit Standards
|
|
|
|
### Commit Messages
|
|
```
|
|
[Type] Brief description (50 chars max)
|
|
|
|
Detailed explanation if needed (wrap at 72 chars)
|
|
|
|
- Change 1
|
|
- Change 2
|
|
- Change 3
|
|
```
|
|
|
|
### Types
|
|
- `[Feature]` - New feature
|
|
- `[Fix]` - Bug fix
|
|
- `[Refactor]` - Code refactoring
|
|
- `[Docs]` - Documentation only
|
|
- `[Test]` - Test updates
|
|
- `[Config]` - Configuration changes
|
|
|
|
---
|
|
|
|
## File Organization
|
|
|
|
### Directory Structure
|
|
```
|
|
project/
|
|
├── api/ # API application code
|
|
│ ├── models/ # Database models
|
|
│ ├── routers/ # API endpoints
|
|
│ ├── schemas/ # Pydantic schemas
|
|
│ ├── services/ # Business logic
|
|
│ └── utils/ # Helper functions
|
|
├── .claude/ # Claude Code configuration
|
|
│ ├── hooks/ # Git-style hooks
|
|
│ └── agents/ # Agent instructions
|
|
├── scripts/ # Utility scripts
|
|
└── migrations/ # Database migrations
|
|
```
|
|
|
|
### File Naming
|
|
- Python: `snake_case.py`
|
|
- Classes: Match class name (e.g., `UserService` in `user_service.py`)
|
|
- Scripts: Descriptive names (e.g., `setup_database.sh`, `test_api.py`)
|
|
|
|
---
|
|
|
|
## Documentation Standards
|
|
|
|
### Code Comments
|
|
```python
|
|
# Use comments for WHY, not WHAT
|
|
# Good: "Retry 3 times to handle transient network errors"
|
|
# Bad: "Set retry count to 3"
|
|
|
|
def fetch_data(url: str) -> dict:
|
|
"""
|
|
Fetch data from API endpoint.
|
|
|
|
Args:
|
|
url: Full URL to fetch from
|
|
|
|
Returns:
|
|
Parsed JSON response
|
|
|
|
Raises:
|
|
ConnectionError: If API is unreachable
|
|
ValueError: If response is invalid JSON
|
|
"""
|
|
```
|
|
|
|
### README Files
|
|
- Include quick start guide
|
|
- Document prerequisites
|
|
- Provide examples
|
|
- Keep up to date
|
|
|
|
---
|
|
|
|
## Error Handling
|
|
|
|
### Python
|
|
```python
|
|
# Use specific exceptions
|
|
try:
|
|
result = api_call()
|
|
except ConnectionError as e:
|
|
logger.error(f"[ERROR] Connection failed: {e}")
|
|
raise
|
|
except ValueError as e:
|
|
logger.warning(f"[WARNING] Invalid data: {e}")
|
|
return None
|
|
```
|
|
|
|
### PowerShell
|
|
```powershell
|
|
# Use try/catch for error handling
|
|
try {
|
|
$Result = Invoke-RestMethod -Uri $Url
|
|
} catch {
|
|
Write-Host "[ERROR] Request failed: $_"
|
|
exit 1
|
|
}
|
|
```
|
|
|
|
---
|
|
|
|
## Logging Standards
|
|
|
|
### Log Levels
|
|
- `DEBUG` - Detailed diagnostic info (development only)
|
|
- `INFO` - General informational messages
|
|
- `WARNING` - Warning messages (non-critical issues)
|
|
- `ERROR` - Error messages (failures)
|
|
- `CRITICAL` - Critical errors (system failures)
|
|
|
|
### Log Format
|
|
```python
|
|
# Use structured logging
|
|
logger.info(
|
|
"[INFO] User login",
|
|
extra={
|
|
"user_id": user.id,
|
|
"ip_address": request.client.host,
|
|
"timestamp": datetime.utcnow()
|
|
}
|
|
)
|
|
```
|
|
|
|
### Output Markers
|
|
```
|
|
[INFO] Starting process
|
|
[SUCCESS] Task completed
|
|
[WARNING] Configuration missing
|
|
[ERROR] Failed to connect
|
|
[CRITICAL] Database unavailable
|
|
```
|
|
|
|
---
|
|
|
|
## Performance Guidelines
|
|
|
|
### Database Queries
|
|
- Use indexes for frequently queried fields
|
|
- Avoid N+1 queries (use joins or eager loading)
|
|
- Paginate large result sets
|
|
- Use connection pooling
|
|
|
|
### API Responses
|
|
- Return only necessary fields
|
|
- Use pagination for lists
|
|
- Compress large payloads
|
|
- Cache frequently accessed data
|
|
|
|
### File Operations
|
|
- Use context managers (`with` statements)
|
|
- Stream large files (don't load into memory)
|
|
- Clean up temporary files
|
|
|
|
---
|
|
|
|
## Version Control
|
|
|
|
### .gitignore
|
|
Always exclude:
|
|
- `.env` files (credentials)
|
|
- `__pycache__/` (Python cache)
|
|
- `*.pyc` (compiled Python)
|
|
- `.venv/`, `venv/` (virtual environments)
|
|
- `.claude/*.json` (local state)
|
|
- `*.log` (log files)
|
|
|
|
### Branching
|
|
- `main` - Production-ready code
|
|
- `develop` - Integration branch
|
|
- `feature/*` - New features
|
|
- `fix/*` - Bug fixes
|
|
- `hotfix/*` - Urgent production fixes
|
|
|
|
---
|
|
|
|
## Review Checklist
|
|
|
|
Before committing code, verify:
|
|
- [ ] No emojis or special Unicode characters
|
|
- [ ] All variables and functions have descriptive names
|
|
- [ ] No hardcoded credentials or sensitive data
|
|
- [ ] Error handling is implemented
|
|
- [ ] Code is formatted consistently
|
|
- [ ] Tests pass (if applicable)
|
|
- [ ] Documentation is updated
|
|
- [ ] No debugging print statements left in code
|
|
|
|
---
|
|
|
|
**Last Updated:** 2026-01-17
|
|
**Status:** Active
|