|
| 1 | +# GitHub Copilot & Claude Code Instructions |
| 2 | + |
| 3 | +This repository contains the Home Assistant Supervisor, a Python 3 based container |
| 4 | +orchestration and management system for Home Assistant. |
| 5 | + |
| 6 | +## Supervisor Capabilities & Features |
| 7 | + |
| 8 | +### Architecture Overview |
| 9 | + |
| 10 | +Home Assistant Supervisor is a Python-based container orchestration system that |
| 11 | +communicates with the Docker daemon to manage containerized components. It is tightly |
| 12 | +integrated with the underlying Operating System and core Operating System components |
| 13 | +through D-Bus. |
| 14 | + |
| 15 | +**Managed Components:** |
| 16 | +- **Home Assistant Core**: The main home automation application running in its own |
| 17 | + container (also provides the web interface) |
| 18 | +- **Add-ons**: Third-party applications and services (each add-on runs in its own |
| 19 | + container) |
| 20 | +- **Plugins**: Built-in system services like DNS, Audio, CLI, Multicast, and Observer |
| 21 | +- **Host System Integration**: OS-level operations and hardware access via D-Bus |
| 22 | +- **Container Networking**: Internal Docker network management and external |
| 23 | + connectivity |
| 24 | +- **Storage & Backup**: Data persistence and backup management across all containers |
| 25 | + |
| 26 | +**Key Dependencies:** |
| 27 | +- **Docker Engine**: Required for all container operations |
| 28 | +- **D-Bus**: System-level communication with the host OS |
| 29 | +- **systemd**: Service management for host system operations |
| 30 | +- **NetworkManager**: Network configuration and management |
| 31 | + |
| 32 | +### Add-on System |
| 33 | + |
| 34 | +**Add-on Architecture**: Add-ons are containerized applications available through |
| 35 | +add-on stores. Each store contains multiple add-ons, and each add-on includes metadata |
| 36 | +that tells Supervisor the version, startup configuration (permissions), and available |
| 37 | +user configurable options. Add-on metadata typically references a container image that |
| 38 | +Supervisor fetches during installation. If not, the Supervisor builds the container |
| 39 | +image from a Dockerfile. |
| 40 | + |
| 41 | +**Built-in Stores**: Supervisor comes with several pre-configured stores: |
| 42 | +- **Core Add-ons**: Official add-ons maintained by the Home Assistant team |
| 43 | +- **Community Add-ons**: Popular third-party add-ons repository |
| 44 | +- **ESPHome**: Add-ons for ESPHome ecosystem integration |
| 45 | +- **Music Assistant**: Audio and music-related add-ons |
| 46 | +- **Local Development**: Local folder for testing custom add-ons during development |
| 47 | + |
| 48 | +**Store Management**: Stores are Git-based repositories that are periodically updated. |
| 49 | +When updates are available, users receive notifications. |
| 50 | + |
| 51 | +**Add-on Lifecycle**: |
| 52 | +- **Installation**: Supervisor fetches or builds container images based on add-on |
| 53 | + metadata |
| 54 | +- **Configuration**: Schema-validated options with integrated UI management |
| 55 | +- **Runtime**: Full container lifecycle management, health monitoring |
| 56 | +- **Updates**: Automatic or manual version management |
| 57 | + |
| 58 | +### Update System |
| 59 | + |
| 60 | +**Core Components**: Supervisor, Home Assistant Core, HAOS, and built-in plugins |
| 61 | +receive version information from a central JSON file fetched from |
| 62 | +`https://version.home-assistant.io/{channel}.json`. The `Updater` class handles |
| 63 | +fetching this data, validating signatures, and updating internal version tracking. |
| 64 | + |
| 65 | +**Update Channels**: Three channels (`stable`/`beta`/`dev`) determine which version |
| 66 | +JSON file is fetched, allowing users to opt into different release streams. |
| 67 | + |
| 68 | +**Add-on Updates**: Add-on version information comes from store repository updates, not |
| 69 | +the central JSON file. When repositories are refreshed via the store system, add-ons |
| 70 | +compare their local versions against repository versions to determine update |
| 71 | +availability. |
| 72 | + |
| 73 | +### Backup & Recovery System |
| 74 | + |
| 75 | +**Backup Capabilities**: |
| 76 | +- **Full Backups**: Complete system state capture including all add-ons, |
| 77 | + configuration, and data |
| 78 | +- **Partial Backups**: Selective backup of specific components (Home Assistant, |
| 79 | + add-ons, folders) |
| 80 | +- **Encrypted Backups**: Optional backup encryption with user-provided passwords |
| 81 | +- **Multiple Storage Locations**: Local storage and remote backup destinations |
| 82 | + |
| 83 | +**Recovery Features**: |
| 84 | +- **One-click Restore**: Simple restoration from backup files |
| 85 | +- **Selective Restore**: Choose specific components to restore |
| 86 | +- **Automatic Recovery**: Self-healing for common system issues |
| 87 | + |
| 88 | +--- |
| 89 | + |
| 90 | +## Supervisor Development |
| 91 | + |
| 92 | +### Python Requirements |
| 93 | + |
| 94 | +- **Compatibility**: Python 3.13+ |
| 95 | +- **Language Features**: Use modern Python features: |
| 96 | + - Type hints with `typing` module |
| 97 | + - f-strings (preferred over `%` or `.format()`) |
| 98 | + - Dataclasses and enum classes |
| 99 | + - Async/await patterns |
| 100 | + - Pattern matching where appropriate |
| 101 | + |
| 102 | +### Code Quality Standards |
| 103 | + |
| 104 | +- **Formatting**: Ruff |
| 105 | +- **Linting**: PyLint and Ruff |
| 106 | +- **Type Checking**: MyPy |
| 107 | +- **Testing**: pytest with asyncio support |
| 108 | +- **Language**: American English for all code, comments, and documentation |
| 109 | + |
| 110 | +### Code Organization |
| 111 | + |
| 112 | +**Core Structure**: |
| 113 | +``` |
| 114 | +supervisor/ |
| 115 | +├── __init__.py # Package initialization |
| 116 | +├── const.py # Constants and enums |
| 117 | +├── coresys.py # Core system management |
| 118 | +├── bootstrap.py # System initialization |
| 119 | +├── exceptions.py # Custom exception classes |
| 120 | +├── api/ # REST API endpoints |
| 121 | +├── addons/ # Add-on management |
| 122 | +├── backups/ # Backup system |
| 123 | +├── docker/ # Docker integration |
| 124 | +├── host/ # Host system interface |
| 125 | +├── homeassistant/ # Home Assistant Core management |
| 126 | +├── dbus/ # D-Bus system integration |
| 127 | +├── hardware/ # Hardware detection and management |
| 128 | +├── plugins/ # Plugin system |
| 129 | +├── resolution/ # Issue detection and resolution |
| 130 | +├── security/ # Security management |
| 131 | +├── services/ # Service discovery and management |
| 132 | +├── store/ # Add-on store management |
| 133 | +└── utils/ # Utility functions |
| 134 | +``` |
| 135 | + |
| 136 | +**Shared Constants**: Use constants from `supervisor/const.py` instead of hardcoding |
| 137 | +values. Define new constants following existing patterns and group related constants |
| 138 | +together. |
| 139 | + |
| 140 | +### Supervisor Architecture Patterns |
| 141 | + |
| 142 | +**CoreSysAttributes Inheritance Pattern**: Nearly all major classes in Supervisor |
| 143 | +inherit from `CoreSysAttributes`, providing access to the centralized system state |
| 144 | +via `self.coresys` and convenient `sys_*` properties. |
| 145 | + |
| 146 | +```python |
| 147 | +# Standard Supervisor class pattern |
| 148 | +class MyManager(CoreSysAttributes): |
| 149 | + """Manage my functionality.""" |
| 150 | + |
| 151 | + def __init__(self, coresys: CoreSys): |
| 152 | + """Initialize manager.""" |
| 153 | + self.coresys: CoreSys = coresys |
| 154 | + self._component: MyComponent = MyComponent(coresys) |
| 155 | + |
| 156 | + @property |
| 157 | + def component(self) -> MyComponent: |
| 158 | + """Return component handler.""" |
| 159 | + return self._component |
| 160 | + |
| 161 | + # Access system components via inherited properties |
| 162 | + async def do_something(self): |
| 163 | + await self.sys_docker.containers.get("my_container") |
| 164 | + self.sys_bus.fire_event(BusEvent.MY_EVENT, {"data": "value"}) |
| 165 | +``` |
| 166 | + |
| 167 | +**Key Inherited Properties from CoreSysAttributes**: |
| 168 | +- `self.sys_docker` - Docker API access |
| 169 | +- `self.sys_run_in_executor()` - Execute blocking operations |
| 170 | +- `self.sys_create_task()` - Create async tasks |
| 171 | +- `self.sys_bus` - Event bus for system events |
| 172 | +- `self.sys_config` - System configuration |
| 173 | +- `self.sys_homeassistant` - Home Assistant Core management |
| 174 | +- `self.sys_addons` - Add-on management |
| 175 | +- `self.sys_host` - Host system access |
| 176 | +- `self.sys_dbus` - D-Bus system interface |
| 177 | + |
| 178 | +**Load Pattern**: Many components implement a `load()` method which effectively |
| 179 | +initialize the component from external sources (containers, files, D-Bus services). |
| 180 | + |
| 181 | +### API Development |
| 182 | + |
| 183 | +**REST API Structure**: |
| 184 | +- **Base Path**: `/api/` for all endpoints |
| 185 | +- **Authentication**: Bearer token authentication |
| 186 | +- **Consistent Response Format**: `{"result": "ok", "data": {...}}` or |
| 187 | + `{"result": "error", "message": "..."}` |
| 188 | +- **Validation**: Use voluptuous schemas with `api_validate()` |
| 189 | + |
| 190 | +**Use `@api_process` Decorator**: This decorator handles all standard error handling |
| 191 | +and response formatting automatically. The decorator catches `APIError`, `HassioError`, |
| 192 | +and other exceptions, returning appropriate HTTP responses. |
| 193 | + |
| 194 | +```python |
| 195 | +from ..api.utils import api_process, api_validate |
| 196 | + |
| 197 | +@api_process |
| 198 | +async def backup_full(self, request: web.Request) -> dict[str, Any]: |
| 199 | + """Create full backup.""" |
| 200 | + body = await api_validate(SCHEMA_BACKUP_FULL, request) |
| 201 | + job = await self.sys_backups.do_backup_full(**body) |
| 202 | + return {ATTR_JOB_ID: job.uuid} |
| 203 | +``` |
| 204 | + |
| 205 | +### Docker Integration |
| 206 | + |
| 207 | +- **Container Management**: Use Supervisor's Docker manager instead of direct |
| 208 | + Docker API |
| 209 | +- **Networking**: Supervisor manages internal Docker networks with predefined IP |
| 210 | + ranges |
| 211 | +- **Security**: AppArmor profiles, capability restrictions, and user namespace |
| 212 | + isolation |
| 213 | +- **Health Checks**: Implement health monitoring for all managed containers |
| 214 | + |
| 215 | +### D-Bus Integration |
| 216 | + |
| 217 | +- **Use dbus-fast**: Async D-Bus library for system integration |
| 218 | +- **Service Management**: systemd, NetworkManager, hostname management |
| 219 | +- **Error Handling**: Wrap D-Bus exceptions in Supervisor-specific exceptions |
| 220 | + |
| 221 | +### Async Programming |
| 222 | + |
| 223 | +- **All I/O operations must be async**: File operations, network calls, subprocess |
| 224 | + execution |
| 225 | +- **Use asyncio patterns**: Prefer `asyncio.gather()` over sequential awaits |
| 226 | +- **Executor jobs**: Use `self.sys_run_in_executor()` for blocking operations |
| 227 | +- **Two-phase initialization**: `__init__` for sync setup, `post_init()` for async |
| 228 | + initialization |
| 229 | + |
| 230 | +### Testing |
| 231 | + |
| 232 | +- **Location**: `tests/` directory with module mirroring |
| 233 | +- **Fixtures**: Extensive use of pytest fixtures for CoreSys setup |
| 234 | +- **Mocking**: Mock external dependencies (Docker, D-Bus, network calls) |
| 235 | +- **Coverage**: Minimum 90% test coverage, 100% for security-sensitive code |
| 236 | + |
| 237 | +### Error Handling |
| 238 | + |
| 239 | +- **Custom Exceptions**: Defined in `exceptions.py` with clear inheritance hierarchy |
| 240 | +- **Error Propagation**: Use `from` clause for exception chaining |
| 241 | +- **API Errors**: Use `APIError` with appropriate HTTP status codes |
| 242 | + |
| 243 | +### Security Considerations |
| 244 | + |
| 245 | +- **Container Security**: AppArmor profiles mandatory for add-ons, minimal |
| 246 | + capabilities |
| 247 | +- **Authentication**: Token-based API authentication with role-based access |
| 248 | +- **Data Protection**: Backup encryption, secure secret management, comprehensive |
| 249 | + input validation |
| 250 | + |
| 251 | +### Development Commands |
| 252 | + |
| 253 | +```bash |
| 254 | +# Run tests with coverage |
| 255 | +pytest tests/ --cov=supervisor --cov-report=term-missing |
| 256 | + |
| 257 | +# Linting and formatting |
| 258 | +ruff check supervisor/ |
| 259 | +ruff format supervisor/ |
| 260 | + |
| 261 | +# Type checking |
| 262 | +mypy --ignore-missing-imports supervisor/ |
| 263 | + |
| 264 | +# Pre-commit hooks |
| 265 | +pre-commit run --all-files |
| 266 | +``` |
| 267 | + |
| 268 | +Always run the pre-commit hooks at the end of code editing. |
| 269 | + |
| 270 | +### Common Patterns to Follow |
| 271 | + |
| 272 | +**✅ Use These Patterns**: |
| 273 | +- Inherit from `CoreSysAttributes` for system access |
| 274 | +- Use `@api_process` decorator for API endpoints |
| 275 | +- Use `self.sys_run_in_executor()` for blocking operations |
| 276 | +- Access Docker via `self.sys_docker` not direct Docker API |
| 277 | +- Use constants from `const.py` instead of hardcoding |
| 278 | + |
| 279 | +**❌ Avoid These Patterns**: |
| 280 | +- Direct Docker API usage - use Supervisor's Docker manager |
| 281 | +- Blocking operations in async context (use asyncio alternatives) |
| 282 | +- Hardcoded values - use constants from `const.py` |
| 283 | +- Manual error handling in API endpoints - let `@api_process` handle it |
| 284 | + |
| 285 | +This guide provides the foundation for contributing to Home Assistant Supervisor. |
| 286 | +Follow these patterns and guidelines to ensure code quality, security, and |
| 287 | +maintainability. |
0 commit comments