# 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 1. Verify current state of the codebase 2. Check existing tests and coverage 3. Understand the specific change needed 4. Create a test case first if fixing a bug 5. Run full test suite to establish baseline ### When Generating Code 1. Follow Google-style docstrings strictly 2. Include comprehensive type hints 3. Add docstrings for all public APIs 4. Create corresponding tests 5. Ensure code passes all formatting tools 6. Add to appropriate module without reorganizing structure ### When Modifying Tests 1. Preserve test isolation (each test independent) 2. Use pytest fixtures for setup/teardown 3. Mock external dependencies (requests, etc.) 4. Test both success and error paths 5. Include descriptive test names: `test___` ### When Running Tests ```bash # 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: ```bash 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`**: Main `ElytraClient` class with API methods - **`models.py`**: All Pydantic models for request/response validation - **`exceptions.py`**: Custom exception hierarchy - **`config.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`: ```python 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: ```python 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 `ElytraAuthenticationError` for 401/403 responses - Use `ElytraNotFoundError` for 404 responses - Use `ElytraValidationError` for validation failures - Use `ElytraAPIError` as fallback for other 4xx/5xx errors ### Pattern ```python 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 client - `python-dotenv>=0.21.0` - Environment configuration - `pydantic>=2.0.0` - Data validation ### Dev Dependencies - `pytest>=7.0.0` - Testing - `pytest-cov>=4.0.0` - Coverage reporting - `black>=23.0.0` - Code formatting - `isort>=5.12.0` - Import sorting - `flake8>=6.0.0` - Code linting - `mypy>=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]` or `T | None` for 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 1. **Reliability**: Every change must be tested 2. **Type Safety**: Full type hints, verified with mypy 3. **Consistency**: Follow established patterns 4. **Documentation**: All changes must be documented in English 5. **Simplicity**: Keep modifications focused and atomic 6. **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: 1. Changes made (file, function, type of change) 2. Tests added/modified (test names) 3. Coverage impact (before/after percentage) 4. Any issues encountered and resolutions 5. Commands used for verification