- Introduced .copilot-instructions.md for GitHub Copilot usage guidelines. - Created DEVELOPMENT.md detailing environment setup, workflow, and common tasks. - Established STYLE_GUIDE.md as a quick reference for code style, formatting, and conventions.
8.6 KiB
8.6 KiB
Agent Instructions for Elytra PIM Client
Purpose
This document provides detailed instructions for autonomous agents (automated tools, CI/CD systems, code generation tools) working with the Elytra PIM Client project.
Project Identity
- Name: Elytra PIM Client
- Description: A fully Pythonic, Pydantic-driven client for the Elytra Product Information Management API
- Language: Python 3.9+
- Type System: Full type hints with static type checking (mypy)
- Data Validation: Pydantic v2
- Package Manager: pip with setuptools
Mandatory Rules
1. Language Requirement
- ALL code must be in English
- ALL docstrings must be in English
- ALL comments must be in English
- ALL variable/function/class names must be in English
- NO exceptions to this rule
2. Code Quality Gates
- Must pass Black formatting (100 char line length)
- Must pass isort import checks
- Must pass Flake8 linting
- Must pass mypy type checking
- Must achieve >80% test coverage
- All tests must pass
3. Source of Truth
- OpenAPI specification (
openapi.yaml) is the source of truth for API design - All Pydantic models should reflect the OpenAPI spec
- API endpoints should match OpenAPI definitions
- Request/response models must align with OpenAPI
Automated Task Guidelines
Before Any Code Modification
- Verify current state of the codebase
- Check existing tests and coverage
- Understand the specific change needed
- Create a test case first if fixing a bug
- Run full test suite to establish baseline
When Generating Code
- Follow Google-style docstrings strictly
- Include comprehensive type hints
- Add docstrings for all public APIs
- Create corresponding tests
- Ensure code passes all formatting tools
- Add to appropriate module without reorganizing structure
When Modifying Tests
- Preserve test isolation (each test independent)
- Use pytest fixtures for setup/teardown
- Mock external dependencies (requests, etc.)
- Test both success and error paths
- Include descriptive test names:
test_<action>_<condition>_<expected_result>
When Running Tests
# Full test suite with coverage
pytest tests/ -v --cov=elytra_client --cov-report=term-missing
# Specific test file
pytest tests/test_client.py -v
# With markers (if defined)
pytest tests/ -v -m "not integration"
When Formatting Code
Execute in this order:
1. black elytra_client tests
2. isort elytra_client tests
3. flake8 elytra_client tests
4. mypy elytra_client
5. pytest tests/ -v
File Organization Rules
Module Responsibilities
client.py: MainElytraClientclass with API methodsmodels.py: All Pydantic models for request/response validationexceptions.py: Custom exception hierarchyconfig.py: Configuration and environment setup__init__.py: Package-level exports
Do Not
- ❌ Create new modules without justification
- ❌ Move code between modules without updating imports
- ❌ Reorganize directory structure
- ❌ Rename existing modules or classes
API Method Generation Rules
When adding new API methods to ElytraClient:
def method_name(
self,
required_param: str,
optional_param: Optional[str] = None,
lang: str = "en",
page: int = 1,
limit: int = 10,
) -> ResponseModelType | Dict[str, Any]:
"""
One-line summary.
Longer description if needed.
Args:
required_param: Description
optional_param: Description (default: None)
lang: Language code (default: "en")
page: Page number for pagination (default: 1)
limit: Items per page (default: 10)
Returns:
Pydantic model instance or dict with 'items' key for collections
Raises:
ElytraNotFoundError: If resource not found
ElytraAuthenticationError: If authentication fails
ElytraValidationError: If data validation fails
ElytraAPIError: For other API errors
"""
endpoint = f"/endpoint/{required_param}"
params = {"lang": lang, "page": page, "limit": limit}
if optional_param:
params["optional"] = optional_param
return self._make_request(
method="GET",
endpoint=endpoint,
params=params,
response_model=ResponseModelType,
)
Model Generation Rules
When creating new Pydantic models:
from pydantic import BaseModel, Field
from typing import List, Optional
class ResourceResponse(BaseModel):
"""Response model for a single resource.
This model validates and serializes API responses according to
the OpenAPI specification.
"""
id: str = Field(..., description="Unique identifier")
name: str = Field(..., description="Resource name")
optional_field: Optional[str] = Field(None, description="Optional field")
nested_items: List[str] = Field(default_factory=list, description="List of items")
model_config = ConfigDict(str_strip_whitespace=True)
Error Handling Rules
Exception Usage
- Use
ElytraAuthenticationErrorfor 401/403 responses - Use
ElytraNotFoundErrorfor 404 responses - Use
ElytraValidationErrorfor validation failures - Use
ElytraAPIErroras fallback for other 4xx/5xx errors
Pattern
try:
response = self.session.request(...)
response.raise_for_status()
if response_model:
return response_model.model_validate(response.json())
return response.json()
except requests.HTTPError as e:
_handle_http_error(e)
raise # Type guard for type checker
except requests.RequestException as e:
raise ElytraAPIError(f"Network error: {str(e)}") from e
except ValidationError as e:
raise ElytraValidationError(
f"Response validation failed: {str(e)}"
) from e
CI/CD Integration
Pre-Commit Requirements
- All code must be formatte with Black
- All imports must be sorted with isort
- All tests must pass
- Type checking must pass
Pull Request Checks
- Code coverage must remain ≥80%
- No type checking errors
- No linting errors
- All tests pass
Dependencies Management
Current Dependencies
requests>=2.28.0- HTTP clientpython-dotenv>=0.21.0- Environment configurationpydantic>=2.0.0- Data validation
Dev Dependencies
pytest>=7.0.0- Testingpytest-cov>=4.0.0- Coverage reportingblack>=23.0.0- Code formattingisort>=5.12.0- Import sortingflake8>=6.0.0- Code lintingmypy>=1.0.0- Static type checking
Rules
- ❌ Do not add dependencies without strong justification
- ❌ Do not update major versions without testing
- ✅ Keep dependency list minimal
- ✅ Pin minor versions for stability
Documentation Updates
When to Update
- README.md: When features change
- Docstrings: Always for public APIs
- CHANGELOG.md (if exists): For releases
- Code comments: When logic changes
When NOT to Update
- Do not update examples that aren't broken
- Do not add optional documentation
- Do not rewrite for style alone
Troubleshooting for Agents
Common Issues
ImportError or ModuleNotFoundError
- Ensure virtual environment is activated
- Verify dependencies installed:
pip install -e ".[dev]" - Check Python path includes project root
Type Checking Failures
- Review mypy errors carefully
- Use
Optional[T]orT | Nonefor nullable types - Use proper return types on all functions
- Check imports from pydantic match v2 API
Test Failures
- Always mock external requests
- Verify test isolation (no shared state)
- Check assertions match actual API behavior
- Review mocked response structure matches models
Formatting Issues
- Run Black first:
black elytra_client tests - Then isort:
isort elytra_client tests - Line length is 100 characters
- Follow PEP 8 style guide
Key Principles
- Reliability: Every change must be tested
- Type Safety: Full type hints, verified with mypy
- Consistency: Follow established patterns
- Documentation: All changes must be documented in English
- Simplicity: Keep modifications focused and atomic
- Quality Gates: Never skip formatting or testing
Success Criteria for Automated Tasks
A task is complete when:
- ✅ All code passes Black formatting
- ✅ All imports pass isort checks
- ✅ All code passes Flake8 linting
- ✅ All code passes mypy type checking
- ✅ All tests pass
- ✅ Code coverage ≥80%
- ✅ All docstrings are complete and in English
- ✅ No warnings or errors in logs
Reporting
When completing tasks, report:
- Changes made (file, function, type of change)
- Tests added/modified (test names)
- Coverage impact (before/after percentage)
- Any issues encountered and resolutions
- Commands used for verification