GLOBAL CODING STANDARDS
Reference guide for all project development. For detailed task planning, see TASK_PLAN_GUIDE.md
🔴 AGENT INSTRUCTIONS
IMPORTANT: As an agent, you MUST read and follow ALL guidelines in this document BEFORE executing any task in a task list. DO NOT skip or ignore any part of these standards. These standards supersede any conflicting instructions you may have received previously.
Project Structure
project_name/
├── docs/
│ ├── CHANGELOG.md
│ ├── memory_bank/
│ └── tasks/
├── examples/
├── pyproject.toml
├── README.md
├── src/
│ └── project_name/
├── tests/
│ ├── fixtures/
│ └── project_name/
└── uv.lock
- Package Management: Always use uv with pyproject.toml, never pip
- Mirror Structure: examples/, tests/ mirror the project structure in src/
- Documentation: Keep comprehensive docs in docs/ directory
Module Requirements
- Size: Maximum 500 lines of code per file
- Documentation Header: Every file must include:
- Description of purpose
- Links to third-party package documentation
- Sample input
- Expected output
- Validation Function: Every file needs a main block (
if __name__ == "__main__":) that tests with real data
Architecture Principles
Function-First: Prefer simple functions over classes
Class Usage: Only use classes when:
- Maintaining state
- Implementing data validation models
- Following established design patterns
Async Code: Never use asyncio.run() inside functions - only in main blocks
Type Hints: Use the typing library for clear type annotations to improve code understanding and tooling
- Type hints should be used for all function parameters and return values
- Use type hints for key variables where it improves clarity
- Prefer concrete types over Any when possible
- Do not add type hints if they significantly reduce code readability
# Good type hint usage:
from typing import Dict, List, Optional, Union, Tuple
def process_document(doc_id: str, options: Optional[Dict[str, str]] = None) -> Dict[str, Any]:
"""Process a document with optional configuration."""
# Implementation
return result
# Simple types don't need annotations inside functions if obvious:
def get_user_name(user_id: int) -> str:
name = "John" # Type inference works here, no annotation needed
return name
NO Conditional Imports:
- Never use try/except blocks for imports of required packages
- If a package is in pyproject.toml, import it directly at the top of the file
- Handle specific errors during usage, not during import
- Only use conditional imports for truly optional features (rare)
# INCORRECT - DO NOT DO THIS:
try:
import tiktoken
TIKTOKEN_AVAILABLE = True
except ImportError:
TIKTOKEN_AVAILABLE = False
# CORRECT APPROACH:
import tiktoken # Listed in pyproject.toml as a dependency
def count_tokens(text, model="gpt-3.5-turbo"):
# Handle errors during usage, not import
try:
encoding = tiktoken.encoding_for_model(model)
return len(encoding.encode(text))
except Exception as e:
logger.error(f"Token counting error: {e}")
return len(text) // 4 # Fallback estimation
Validation & Testing
- Real Data: Always test with actual data, never fake inputs
- Expected Results: Verify outputs against concrete expected results
- No Mocking: NEVER mock core functionality
- MagicMock Ban: MagicMock is strictly forbidden for testing core functionality
- Meaningful Assertions: Use assertions that verify specific expected values
- 🔴 Usage Functions Before Tests: ALL relevant usage functions MUST successfully output expected results BEFORE any creation of tests. Tests are a future-proofing step when Agents improve at test-writing capabilities.
- 🔴 Results Before Lint: ALL usage functionality MUST produce expected results BEFORE addressing ANY Pylint or other linter warnings. Functionality correctness ALWAYS comes before style compliance.
- 🔴 External Research After 3 Failures: If a usage function fails validation 3 consecutive times with different approaches, the agent MUST use external research tools (perplexity_ask, perplexity_research, web_search) to find current best practices, package updates, or solutions for the specific problem. Document the research findings in comments.
- 🔴 NO UNCONDITIONAL "TESTS PASSED" MESSAGES: NEVER include unconditional "All Tests Passed" or similar validation success messages. Success messages MUST be conditional on ACTUAL test results.
- 🔴 TRACK ALL VALIDATION FAILURES: ALWAYS track ALL validation failures and report them at the end. NEVER stop validation after the first failure.
# INCORRECT - DO NOT DO THIS:
if __name__ == "__main__":
test_data = "test input"
result = process_data(test_data)
# This always prints regardless of success/failure
print("✅ VALIDATION PASSED - All tests successful")
# CORRECT IMPLEMENTATION:
if __name__ == "__main__":
import sys
# List to track all validation failures
all_validation_failures = []
total_tests = 0
# Test 1: Basic functionality
total_tests += 1
test_data = "example input"
result = process_data(test_data)
expected = {"key": "processed value"}
if result != expected:
all_validation_failures.append(f"Basic test: Expected {expected}, got {result}")
# Test 2: Edge case handling
total_tests += 1
edge_case = "empty"
edge_result = process_data(edge_case)
edge_expected = {"key": ""}
if edge_result != edge_expected:
all_validation_failures.append(f"Edge case: Expected {edge_expected}, got {edge_result}")
# Test 3: Error handling
total_tests += 1
try:
error_result = process_data(None)
all_validation_failures.append("Error handling: Expected exception for None input, but no exception was raised")
except ValueError:
# This is expected - test passes
pass
except Exception as e:
all_validation_failures.append(f"Error handling: Expected ValueError for None input, but got {type(e).__name__}")
# Final validation result
if all_validation_failures:
print(f"❌ VALIDATION FAILED - {len(all_validation_failures)} of {total_tests} tests failed:")
for failure in all_validation_failures:
print(f" - {failure}")
sys.exit(1) # Exit with error code
else:
print(f"✅ VALIDATION PASSED - All {total_tests} tests produced expected results")
print("Function is validated and formal tests can now be written")
sys.exit(0) # Exit with success code
Standard Components
- Logging: Always use loguru for logging
from loguru import logger
# Configure logger
logger.add("app.log", rotation="10 MB")
- CLI Structure: Every command-line tool must use typer in a
cli.py fileimport typer
app = typer.Typer()
@app.command()
def command_name(param: str = typer.Argument(..., help="Description")):
"""Command description."""
# Implementation
if __name__ == "__main__":
app()
Package Selection
- Research First: Always research packages before adding dependencies
- 95/5 Rule: Use 95% package functionality, 5% customization
- Documentation: Include links to current documentation in comments
Development Priority
- Working Code
- Validation
- Readability
- Static Analysis (address only after code works)
Execution Standards
- Run scripts with:
uv run script.py
- Use environment variables:
env VAR_NAME="value" uv run command
Task Planning
All task plans must follow the standard structure defined in the Task Plan Guide:
- Document Location: Store in
docs/memory_bank/guides/TASK_PLAN_GUIDE.md
- Core Principles:
- Detailed task descriptions for consistent understanding
- Verification-first development approach
- Version control discipline with frequent commits
- Human-friendly documentation with usage examples
- Structure Elements:
- Clear objectives and requirements
- Step-by-step implementation tasks
- Verification methods for each function
- Usage tables with examples
- Version control plan
- Progress tracking
Refer to the full Task Plan Guide for comprehensive details.
🔴 VALIDATION OUTPUT REQUIREMENTS
- NEVER print "All Tests Passed" or similar unless ALL tests actually passed
- ALWAYS verify actual results against expected results BEFORE printing ANY success message
- ALWAYS test multiple cases, including normal cases, edge cases, and error handling
- ALWAYS track ALL failures and report them at the end - don't stop at first failure
- ALL validation functions MUST exit with code 1 if ANY tests fail
- ALL validation functions MUST exit with code 0 ONLY if ALL tests pass
- ALWAYS include count of failed tests and total tests in the output (e.g., "3 of 5 tests failed")
- ALWAYS include details of each failure when tests fail
- NEVER include irrelevant test output that could hide failures
- ALWAYS structure validation in a way that explicitly checks EACH test case
🔴 COMPLIANCE CHECK
As an agent, before completing a task, verify that your work adheres to ALL standards in this document. Confirm each of the following:
- All files have appropriate documentation headers
- Each module has a working validation function that produces expected results
- Type hints are used properly and consistently
- All functionality is validated with real data before addressing linting issues
- No asyncio.run() is used inside functions - only in the main block
- Code is under the 500-line limit for each file
- If function failed validation 3+ times, external research was conducted and documented
- Validation functions NEVER include unconditional "All Tests Passed" messages
- Validation functions ONLY report success if explicitly verified by comparing actual to expected results
- Validation functions track and report ALL failures, not just the first one encountered
- Validation output includes count of failed tests out of total tests run
If any standard is not met, fix the issue before submitting the work.
1---2name: global-coding-standards3description: Refer to the full Task Plan Guide for comprehensive details.4---5# GLOBAL CODING STANDARDS67> Reference guide for all project development. For detailed task planning, see [TASK_PLAN_GUIDE.md](./docs/memory_bank/guides/TASK_PLAN_GUIDE.md)89## 🔴 AGENT INSTRUCTIONS1011**IMPORTANT**: As an agent, you MUST read and follow ALL guidelines in this document BEFORE executing any task in a task list. DO NOT skip or ignore any part of these standards. These standards supersede any conflicting instructions you may have received previously.1213## Project Structure14```15project_name/16├── docs/17│ ├── CHANGELOG.md18│ ├── memory_bank/19│ └── tasks/20├── examples/21├── pyproject.toml22├── README.md23├── src/24│ └── project_name/25├── tests/26│ ├── fixtures/27│ └── project_name/28└── uv.lock29```3031- **Package Management**: Always use uv with pyproject.toml, never pip32- **Mirror Structure**: examples/, tests/ mirror the project structure in src/33- **Documentation**: Keep comprehensive docs in docs/ directory3435## Module Requirements36- **Size**: Maximum 500 lines of code per file37- **Documentation Header**: Every file must include:38 - Description of purpose39 - Links to third-party package documentation40 - Sample input41 - Expected output42- **Validation Function**: Every file needs a main block (`if __name__ == "__main__":`) that tests with real data4344## Architecture Principles45- **Function-First**: Prefer simple functions over classes46- **Class Usage**: Only use classes when:47 - Maintaining state48 - Implementing data validation models49 - Following established design patterns50- **Async Code**: Never use `asyncio.run()` inside functions - only in main blocks51- **Type Hints**: Use the typing library for clear type annotations to improve code understanding and tooling52 - Type hints should be used for all function parameters and return values53 - Use type hints for key variables where it improves clarity54 - Prefer concrete types over Any when possible55 - Do not add type hints if they significantly reduce code readability56 ```python57 # Good type hint usage:58 from typing import Dict, List, Optional, Union, Tuple59 60 def process_document(doc_id: str, options: Optional[Dict[str, str]] = None) -> Dict[str, Any]:61 """Process a document with optional configuration."""62 # Implementation63 return result64 65 # Simple types don't need annotations inside functions if obvious:66 def get_user_name(user_id: int) -> str:67 name = "John" # Type inference works here, no annotation needed68 return name69 ```70- **NO Conditional Imports**: 71 - Never use try/except blocks for imports of required packages72 - If a package is in pyproject.toml, import it directly at the top of the file73 - Handle specific errors during usage, not during import74 - Only use conditional imports for truly optional features (rare)75 76 ```python77 # INCORRECT - DO NOT DO THIS:78 try:79 import tiktoken80 TIKTOKEN_AVAILABLE = True81 except ImportError:82 TIKTOKEN_AVAILABLE = False83 84 # CORRECT APPROACH:85 import tiktoken # Listed in pyproject.toml as a dependency86 87 def count_tokens(text, model="gpt-3.5-turbo"):88 # Handle errors during usage, not import89 try:90 encoding = tiktoken.encoding_for_model(model)91 return len(encoding.encode(text))92 except Exception as e:93 logger.error(f"Token counting error: {e}")94 return len(text) // 4 # Fallback estimation95 ```9697## Validation & Testing98- **Real Data**: Always test with actual data, never fake inputs99- **Expected Results**: Verify outputs against concrete expected results100- **No Mocking**: NEVER mock core functionality101- **MagicMock Ban**: MagicMock is strictly forbidden for testing core functionality102- **Meaningful Assertions**: Use assertions that verify specific expected values103- **🔴 Usage Functions Before Tests**: ALL relevant usage functions MUST successfully output expected results BEFORE any creation of tests. Tests are a future-proofing step when Agents improve at test-writing capabilities.104- **🔴 Results Before Lint**: ALL usage functionality MUST produce expected results BEFORE addressing ANY Pylint or other linter warnings. Functionality correctness ALWAYS comes before style compliance.105- **🔴 External Research After 3 Failures**: If a usage function fails validation 3 consecutive times with different approaches, the agent MUST use external research tools (perplexity_ask, perplexity_research, web_search) to find current best practices, package updates, or solutions for the specific problem. Document the research findings in comments.106- **🔴 NO UNCONDITIONAL "TESTS PASSED" MESSAGES**: NEVER include unconditional "All Tests Passed" or similar validation success messages. Success messages MUST be conditional on ACTUAL test results.107- **🔴 TRACK ALL VALIDATION FAILURES**: ALWAYS track ALL validation failures and report them at the end. NEVER stop validation after the first failure.108 ```python109 # INCORRECT - DO NOT DO THIS:110 if __name__ == "__main__":111 test_data = "test input"112 result = process_data(test_data)113 # This always prints regardless of success/failure114 print("✅ VALIDATION PASSED - All tests successful")115 116 # CORRECT IMPLEMENTATION:117 if __name__ == "__main__":118 import sys119 120 # List to track all validation failures121 all_validation_failures = []122 total_tests = 0123 124 # Test 1: Basic functionality125 total_tests += 1126 test_data = "example input"127 result = process_data(test_data)128 expected = {"key": "processed value"}129 if result != expected:130 all_validation_failures.append(f"Basic test: Expected {expected}, got {result}")131 132 # Test 2: Edge case handling133 total_tests += 1134 edge_case = "empty"135 edge_result = process_data(edge_case)136 edge_expected = {"key": ""}137 if edge_result != edge_expected:138 all_validation_failures.append(f"Edge case: Expected {edge_expected}, got {edge_result}")139 140 # Test 3: Error handling141 total_tests += 1142 try:143 error_result = process_data(None)144 all_validation_failures.append("Error handling: Expected exception for None input, but no exception was raised")145 except ValueError:146 # This is expected - test passes147 pass148 except Exception as e:149 all_validation_failures.append(f"Error handling: Expected ValueError for None input, but got {type(e).__name__}")150 151 # Final validation result152 if all_validation_failures:153 print(f"❌ VALIDATION FAILED - {len(all_validation_failures)} of {total_tests} tests failed:")154 for failure in all_validation_failures:155 print(f" - {failure}")156 sys.exit(1) # Exit with error code157 else:158 print(f"✅ VALIDATION PASSED - All {total_tests} tests produced expected results")159 print("Function is validated and formal tests can now be written")160 sys.exit(0) # Exit with success code161 ```162163## Standard Components164- **Logging**: Always use loguru for logging165 ```python166 from loguru import logger167 168 # Configure logger169 logger.add("app.log", rotation="10 MB")170 ```171- **CLI Structure**: Every command-line tool must use typer in a `cli.py` file172 ```python173 import typer174 175 app = typer.Typer()176 177 @app.command()178 def command_name(param: str = typer.Argument(..., help="Description")):179 """Command description."""180 # Implementation181 182 if __name__ == "__main__":183 app()184 ```185186## Package Selection187- **Research First**: Always research packages before adding dependencies188- **95/5 Rule**: Use 95% package functionality, 5% customization189- **Documentation**: Include links to current documentation in comments190191## Development Priority1921. Working Code1932. Validation1943. Readability1954. Static Analysis (address only after code works)196197## Execution Standards198- Run scripts with: `uv run script.py`199- Use environment variables: `env VAR_NAME="value" uv run command`200201## Task Planning202All task plans must follow the standard structure defined in the Task Plan Guide:203204- **Document Location**: Store in `docs/memory_bank/guides/TASK_PLAN_GUIDE.md`205- **Core Principles**: 206 - Detailed task descriptions for consistent understanding207 - Verification-first development approach208 - Version control discipline with frequent commits209 - Human-friendly documentation with usage examples210- **Structure Elements**:211 - Clear objectives and requirements212 - Step-by-step implementation tasks213 - Verification methods for each function214 - Usage tables with examples215 - Version control plan216 - Progress tracking217218Refer to the full [Task Plan Guide](./docs/memory_bank/guides/TASK_PLAN_GUIDE.md) for comprehensive details.219220## 🔴 VALIDATION OUTPUT REQUIREMENTS221222- **NEVER print "All Tests Passed" or similar unless ALL tests actually passed**223- **ALWAYS verify actual results against expected results BEFORE printing ANY success message**224- **ALWAYS test multiple cases, including normal cases, edge cases, and error handling**225- **ALWAYS track ALL failures and report them at the end - don't stop at first failure**226- **ALL validation functions MUST exit with code 1 if ANY tests fail**227- **ALL validation functions MUST exit with code 0 ONLY if ALL tests pass**228- **ALWAYS include count of failed tests and total tests in the output (e.g., "3 of 5 tests failed")**229- **ALWAYS include details of each failure when tests fail**230- **NEVER include irrelevant test output that could hide failures**231- **ALWAYS structure validation in a way that explicitly checks EACH test case**232233## 🔴 COMPLIANCE CHECK234As an agent, before completing a task, verify that your work adheres to ALL standards in this document. Confirm each of the following:2352361. All files have appropriate documentation headers2372. Each module has a working validation function that produces expected results2383. Type hints are used properly and consistently2394. All functionality is validated with real data before addressing linting issues2405. No asyncio.run() is used inside functions - only in the main block2416. Code is under the 500-line limit for each file2427. If function failed validation 3+ times, external research was conducted and documented2438. Validation functions NEVER include unconditional "All Tests Passed" messages2449. Validation functions ONLY report success if explicitly verified by comparing actual to expected results24510. Validation functions track and report ALL failures, not just the first one encountered24611. Validation output includes count of failed tests out of total tests run247248If any standard is not met, fix the issue before submitting the work.