| 1 |
# AI agent instructions for hass-nabucasa |
| 2 |
|
| 3 |
This file provides guidance to AI agents (Claude Code, GitHub Copilot, etc.) when working with code in this repository. |
| 4 |
|
| 5 |
## Meta instructions |
| 6 |
|
| 7 |
Important: Keep this file accurate and up to date. Update it immediately when (1) users give new instructions, (2) you find contradictions, or (3) new patterns or standards emerge. Treat this maintenance as a blocking, highest‑priority task that doesn’t need an explicit prompt. |
| 8 |
|
| 9 |
Note: This file is exempt from the “no new docs” rule below. Proactively edit and maintain this file as part of your duties. |
| 10 |
|
| 11 |
## Development commands |
| 12 |
|
| 13 |
### Testing |
| 14 |
- Use `scripts/test` to run the full suite (pytest). Defaults come from `pyproject.toml` (socket disabled, 127.0.0.1 allowed, timeout=5). |
| 15 |
- Run a module: `python -m pytest tests/test_<module>.py`. |
| 16 |
- Run a single test: `python -m pytest tests/test_<module>.py::test_function`. |
| 17 |
- Update snapshots when needed: `scripts/snapshot-update`. |
| 18 |
- Local iteration tips (optional): add `-x` to stop on first failure; `--no-header --no-summary --tb=short` for compact output. |
| 19 |
|
| 20 |
Important: All tests must pass. Partial success isn’t acceptable. |
| 21 |
- Fix every test failure before you consider the task complete. |
| 22 |
- If any test fails, the testing phase fails. |
| 23 |
- Don’t ignore or skip failing tests — they indicate bugs that must be resolved. |
| 24 |
- Run the full test suite after changes to ensure nothing breaks. |
| 25 |
- Test failures block merges. |
| 26 |
|
| 27 |
### Code quality |
| 28 |
- `scripts/lint` — Run pre-commit hooks (ruff, mypy, codespell, etc.). |
| 29 |
- `ruff check` — Run ruff linting. |
| 30 |
- `mypy hass_nabucasa` — Run type checking. |
| 31 |
|
| 32 |
### Environment |
| 33 |
- Python: >= 3.14 (see `pyproject.toml`). Ruff target: `py314`. |
| 34 |
- Before pushing, run `scripts/lint` and `scripts/test` locally. |
| 35 |
|
| 36 |
### Voice data updates |
| 37 |
- `python -m scripts.update_voice_data` — Update voice data from Azure (requires Azure TTS token). |
| 38 |
|
| 39 |
## Architecture overview |
| 40 |
|
| 41 |
### Core components |
| 42 |
|
| 43 |
**Cloud class (`hass_nabucasa/__init__.py`)** |
| 44 |
- Main orchestrator for cloud functionality. |
| 45 |
- Handles authentication state, subscription validation, and component lifecycle. |
| 46 |
- Manages tokens (id_token, access_token, refresh_token) and user authentication. |
| 47 |
- Initializes sub-components: `iot`, `account`, `accounts`, `alexa_api`, `auth`, `cloudhooks`, `files`, `google_report_state`, `ice_servers`, `instance`, `payments`, `remote`, `voice`, `voice_api`. |
| 48 |
|
| 49 |
**CloudClient interface (`hass_nabucasa/client.py`)** |
| 50 |
- Abstract base class that Home Assistant implements. |
| 51 |
- Provides platform-specific functionality (file system, event loop, web session). |
| 52 |
- Handles client-specific callbacks and cleanup operations. |
| 53 |
|
| 54 |
**CloudIoT (`hass_nabucasa/iot.py`)** |
| 55 |
- WebSocket-based communication with Nabu Casa cloud services. |
| 56 |
- Handles message routing, heartbeats, and connection management. |
| 57 |
- Implements request–response patterns for cloud API calls. |
| 58 |
|
| 59 |
### API components |
| 60 |
|
| 61 |
All API components extend `ApiBase` and provide specific cloud service integrations: |
| 62 |
- AccountApi — User account service availability/status. |
| 63 |
- AlexaApi — Amazon Alexa integration and access tokens. |
| 64 |
- PaymentsApi — Payment processing and subscription management. |
| 65 |
- VoiceApi — Voice processing and TTS services. |
| 66 |
- InstanceApi — Instance connection and management. |
| 67 |
- FilesApi — Cloud file management and backup storage. |
| 68 |
- AccountsApi — Accounts backend utility APIs (for example, DNS CNAME resolution). |
| 69 |
|
| 70 |
### Key services |
| 71 |
|
| 72 |
**Authentication (`hass_nabucasa/auth.py`)** |
| 73 |
- AWS Cognito integration for user authentication. |
| 74 |
- Token refresh and validation. |
| 75 |
- MFA/TOTP support. |
| 76 |
|
| 77 |
**Remote UI (`hass_nabucasa/remote.py`)** |
| 78 |
- ACME certificate management for secure remote access. |
| 79 |
- SniTun tunnel integration for remote connectivity. |
| 80 |
|
| 81 |
**Cloudhooks (`hass_nabucasa/cloudhooks.py`)** |
| 82 |
- Webhook management for cloud-to-local communication. |
| 83 |
- Dynamic webhook URL generation and routing. |
| 84 |
|
| 85 |
### Configuration and constants |
| 86 |
|
| 87 |
**Environment configuration (`hass_nabucasa/const.py`)** |
| 88 |
- Production vs. development server endpoints. |
| 89 |
- AWS Cognito configuration (client ID, user pool, region). |
| 90 |
- Default timeout values and connection states. |
| 91 |
|
| 92 |
**Mode support** |
| 93 |
- `Cloud(mode)` accepts `"production"` or `"development"`. |
| 94 |
- Production: Uses defaults from `DEFAULT_SERVERS` and `DEFAULT_VALUES`. |
| 95 |
- Development: Provide servers/values via the `Cloud(...)` constructor for tests/dev. |
| 96 |
|
| 97 |
## Development notes |
| 98 |
|
| 99 |
### Testing strategy |
| 100 |
- Unit tests for all major components in `tests/`. |
| 101 |
- Mocking for external services (AWS, cloud APIs). |
| 102 |
- Snapshot testing for voice data using syrupy. |
| 103 |
- Async test support with pytest-aiohttp. |
| 104 |
- Network calls are disabled by default (`pytest-socket --disable-socket` with 127.0.0.1 allowed). |
| 105 |
- Use freezegun to freeze time globally to 2018‑09‑17. |
| 106 |
|
| 107 |
**Time handling in tests** |
| 108 |
- Global `freeze_time_fixture` in `tests/conftest.py` freezes time to "2018-09-17 12:00:00" with `tick=True`. |
| 109 |
- To advance time in tests, add `frozen_time: FreezeTimeFixture` parameter and use `frozen_time.tick(seconds)` to move time forward. |
| 110 |
- After calling `frozen_time.tick()`, use `await asyncio.sleep(0.1)` to let the event loop process scheduled tasks. |
| 111 |
- The `mock_timing` fixture (used in remote tests) provides targeted patches for sleep/random/midnight. Use it where appropriate instead of changing global behavior. |
| 112 |
- Don't modify the global time freeze. Changes affect the whole suite. |
| 113 |
|
| 114 |
### Code style |
| 115 |
- Strict typing with mypy (type all functions). |
| 116 |
- Ruff for linting and formatting (line length 88). |
| 117 |
- Docstrings follow PEP 257 conventions. |
| 118 |
- Pre-commit hooks enforce code quality. |
| 119 |
- Import organization: Keep all imports at the top level of modules (never inside functions or methods). |
| 120 |
- Comments policy: Don’t add unnecessary inline comments — prefer clear names and structure. |
| 121 |
- Async I/O: Use `cloud.run_executor` for blocking file I/O or CPU‑heavy work. |
| 122 |
|
| 123 |
### Error handling |
| 124 |
- Custom exception hierarchy extending `CloudError`. |
| 125 |
- Specific error types for different failure modes (auth, network, subscription). |
| 126 |
- Automatic retry logic for transient failures. |
| 127 |
|
| 128 |
### Logging standards |
| 129 |
- Use `_LOGGER = logging.getLogger(__name__)` in modules. |
| 130 |
- Exception: `iot_base.py` uses `self._logger = logging.getLogger(self.package_name)` for instance-based logging. |
| 131 |
- Message guidance: |
| 132 |
- Use “Unexpected error …” for exception-level logging. |
| 133 |
- Prefer descriptive, consistent phrasing (for example, “Unable to connect due to …”). |
| 134 |
- Include context in error messages (for example, “Unexpected error handling message: %s”). |
| 135 |
- Use present tense and active voice. |
| 136 |
- Severity levels: |
| 137 |
- `debug()` — Development/troubleshooting info. |
| 138 |
- `info()` — Normal operation events. |
| 139 |
- `warning()` — Recoverable issues that should be noted. |
| 140 |
- `error()` — Non‑recoverable errors requiring attention. |
| 141 |
- `exception()` — Errors with full stack traces for debugging. |
| 142 |
|
| 143 |
### Subscription management |
| 144 |
- Automatic reconnection handler for expired subscriptions. |
| 145 |
- Graceful degradation when a subscription is invalid. |
| 146 |
- Repair issue creation for user notification. |
| 147 |
|
| 148 |
## File creation guidelines |
| 149 |
|
| 150 |
Important: File creation policy |
| 151 |
- Do only what the task asks. Don’t add extras. |
| 152 |
- Don’t create files unless they’re necessary to achieve the goal. |
| 153 |
- Always prefer editing an existing file to creating a new one. |
| 154 |
- Don’t proactively create documentation files (`*.md`) or README files. Create documentation only if the user explicitly asks. |
| 155 |
- Exception: Proactively maintain this `.github/copilot-instructions.md` file (see “Meta instructions”). |
| 156 |
|
| 157 |
## Security guidelines |
| 158 |
|
| 159 |
Important: Security policy |
| 160 |
- Assist with defensive security tasks only. |
| 161 |
- Refuse to create, modify, or improve code that could be used maliciously. |
| 162 |
- Allow security analysis, detection rules, vulnerability explanations, defensive tools, and security documentation. |
| 163 |
- Always follow security best practices. |
| 164 |
- Don’t introduce code that exposes or logs secrets or keys. |
| 165 |
- Don’t commit secrets or keys to the repository. |
| 166 |
|
| 167 |
### Security baselines (current state) |
| 168 |
- Don’t log secrets or tokens. Favor contextual messages without sensitive data. |
| 169 |
- JWT decoding for convenience uses signature verification disabled (see `Cloud._decode_claims` and `utils.expiration_from_token`). Don’t rely on unverified claims for security decisions. |
| 170 |
- TLS contexts follow a modern cipher suite selection (`utils.server_context_modern`), with legacy protocol versions disabled. |
| 171 |
- ACME artifacts and user info are stored with `0o600` permissions, and critical writes use atomic writes (see `acme.py` and `hass_nabucasa/__init__.py`). |
| 172 |
- ACME RSA key sizes currently default to 2048 bits (`acme.py`). If you change sizes, update tests and validate performance. |
| 173 |
|
| 174 |
### Security testing expectations |
| 175 |
- Validate security-related code paths with automated tests where feasible. |
| 176 |
- Prefer explicit failure modes and clear error messages without leaking sensitive details. |