From 0cf0ed0f2ca8291bb8615949b041dff7fda2b8e0 Mon Sep 17 00:00:00 2001 From: Jasper Delahaije Date: Sat, 17 Oct 2026 01:00:12 +0200 Subject: [PATCH] Fix live lock and schedule contracts and complete validation coverage --- README.md | 2 +- custom_components/notty/api.py | 32 ++++- custom_components/notty/manifest.json | 2 +- docs/apk-contracts.md | 12 +- docs/apk-schedules.md | 9 ++ docs/app-validation.md | 67 +++++++++- docs/validation-coverage.md | 35 ++++++ pyproject.toml | 2 +- release-notes/v0.4.1.md | 23 ++++ scripts/app_actions.py | 35 +++++- scripts/app_validation.py | 50 +++++++- scripts/monitor_firmware.py | 174 ++++++++++++++++++++++++++ scripts/validation_status.py | 129 +++++++++++++++++++ tests/test_api.py | 5 +- tests/test_app_validation.py | 35 ++++++ tests/test_schedules.py | 15 ++- tests/test_setting_contracts.py | 4 +- tests/test_validation_monitoring.py | 83 ++++++++++++ uv.lock | 2 +- 19 files changed, 693 insertions(+), 23 deletions(-) create mode 100644 docs/validation-coverage.md create mode 100644 release-notes/v0.4.1.md create mode 100755 scripts/monitor_firmware.py create mode 100755 scripts/validation_status.py create mode 100644 tests/test_validation_monitoring.py diff --git a/README.md b/README.md index ca26710..d974138 100644 --- a/README.md +++ b/README.md @@ -246,7 +246,7 @@ cleaning mode unchanged. The app describes Scheduled mode as cleaning at configu fixed times; behavior outside that mode and with an empty plan list remains unverified. Create does not send an enable state, matching the app; inspect readback to see the server's resulting state. Update preserves a disabled plan by omitting -its enable field. Unknown plan quantity/recurrence types block time edits. +its enable field. Unknown plan quantities/types block time edits. Live litter-box plans use `plan_type_id: 2` and may omit quantity; the app's edit payload still uses `quantity: 1`. **Times are raw NOTTY schedule-clock values in `HH:MM`, not Home Assistant local times or UTC timestamps.** Readback returns `clock_basis: notty_schedule_clock` diff --git a/custom_components/notty/api.py b/custom_components/notty/api.py index d50633b..a44c850 100644 --- a/custom_components/notty/api.py +++ b/custom_components/notty/api.py @@ -16,6 +16,7 @@ ACTION_SET_AUTO_DELAY = "set_auto_delay" ACTION_SET_ALIAS = "set_alias" ACTION_SET_LANGUAGE = "set_language" +ACTION_SET_KEY = "set_key" MODE_SCHEDULED = 2 MIN_ALIAS_UNITS = 2 MAX_ALIAS_UNITS = 8 @@ -34,6 +35,7 @@ PLAN_ACTIONS = set(PLAN_FIELDS) PLAN_TIME_RE = re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]") MAX_LITTER_PLANS = 10 +LITTER_PLAN_TYPE_ID = 2 ACTION_SET_MODE = "set_mode" @@ -134,6 +136,24 @@ _LOGGER = logging.getLogger(__name__) +def child_lock_payload(device_id: str, data: JsonObject) -> JsonObject: + """Construct the app's exact integer child-lock fields. + + Returns: + Only integer user_device_id and switch; no legacy device_id alias. + + Raises: + NottyApiError: If identity, fields or switch encoding is invalid. + """ + if not device_id.isascii() or not device_id.isdecimal() or int(device_id) <= 0: + msg = "Child lock requires a positive numeric physical device ID" + raise NottyApiError(msg) + if set(data) != {"switch"} or type(data.get("switch")) is not int or data["switch"] not in {0, 1}: + msg = "Child lock accepts only integer switch 0 or 1" + raise NottyApiError(msg) + return {"user_device_id": int(device_id), "switch": data["switch"]} + + def matches_value(value: object, choices: tuple[object, ...]) -> bool: """Compare JSON values without requiring hashability. @@ -248,11 +268,11 @@ def _plan_time_fields(data: JsonObject, current: JsonObject) -> JsonObject: if not isinstance(clock, str) or not PLAN_TIME_RE.fullmatch(clock): msg = "Schedule time must be a NOTTY clock value in HH:MM format" raise NottyApiError(msg) - for field in ("quantity", "plan_type_id"): - value = current.get(field, 1) - if type(value) is not int or value != 1: - msg = "Cannot edit an unsupported schedule quantity or recurrence type" - raise NottyApiError(msg) + quantity = current.get("quantity", 1) + plan_type = current.get("plan_type_id", LITTER_PLAN_TYPE_ID) + if type(quantity) is not int or quantity != 1 or type(plan_type) is not int or plan_type != LITTER_PLAN_TYPE_ID: + msg = "Cannot edit an unsupported schedule quantity or plan type" + raise NottyApiError(msg) return {"time": clock, "quantity": 1} @@ -1332,6 +1352,8 @@ async def litter_action(self, device_id: str, action: str, data: JsonObject | No return await self.request("POST", path, data=payload) async def _setting_payload(self, device_id: str, action: str, data: JsonObject) -> JsonObject | None: + if action == ACTION_SET_KEY: + return child_lock_payload(device_id, data) settings = reminder_payload(action, data) if action in REMINDER_CYCLE_FIELDS else data if action in REMINDER_RESET_ACTIONS | REMINDER_INTERVAL_ACTIONS and not await self._validate_reminder_edit( device_id, action, settings diff --git a/custom_components/notty/manifest.json b/custom_components/notty/manifest.json index 9d93a77..ed04367 100644 --- a/custom_components/notty/manifest.json +++ b/custom_components/notty/manifest.json @@ -10,5 +10,5 @@ "iot_class": "cloud_polling", "issue_tracker": "https://github.com/Repsay/notty/issues", "requirements": [], - "version": "0.4.0" + "version": "0.4.1" } diff --git a/docs/apk-contracts.md b/docs/apk-contracts.md index 7b8574c..4f6cc00 100644 --- a/docs/apk-contracts.md +++ b/docs/apk-contracts.md @@ -13,9 +13,9 @@ output remain local and ignored. Tests use synthetic data. | Litter renewal reminder | `open_litter_remind`, `default_remaining_days`, `remaining_days` | `/device/litter_box/set_litter_remind`: `action` (1 enable, 2 disable) and required `cycle_time`; `user_device_id` | | Trash bag reminder | `open_garbagebag_remind`, `garbage_bag_cycle_time`, `garbage_bag_remaining_days` | `/device/litter_box/set_garbage_bag_remind`: `action` (1 enable, 2 disable) and required `cycle_time`; `user_device_id` | -The client currently adds a `device_id` alias alongside `user_device_id` for -device actions. That is existing compatibility behavior, not a field established -by these app paths. +Some older device actions retain a `device_id` alias alongside `user_device_id`. +That is compatibility behavior, not a field established by these app paths. +Child lock now uses only the exact APK fields. ## Child lock (#11) @@ -24,6 +24,12 @@ in context field `0x13`. Its shared closure at `0xccd7dc` converts the Dart bool to an integer (`cset`, then the Dart small-integer tag shift): true becomes `1`, false becomes `0`. The map inserts `switch` at `0xcd3ebc` and POSTs at `0xcd3f04`. Reading state continues to use `switch_key` and entity unique IDs are unchanged. +The physical-ID closure `0xcc1b14` boxes the controller ID as an integer. The +child-lock builder now sends exactly integer `user_device_id` and integer +`switch`, rejecting legacy aliases, target overrides and non-enum values. An +owner-authorized live change and restoration both matched fresh API readback +after two seconds on 17 October 2026. This verifies the endpoint flag transition, +not physical button behavior on every model. ## Do Not Disturb (#12) diff --git a/docs/apk-schedules.md b/docs/apk-schedules.md index 0be7fc8..500b0ba 100644 --- a/docs/apk-schedules.md +++ b/docs/apk-schedules.md @@ -80,3 +80,12 @@ read-only listing and failures without retries. No schedule writes were performe against the owner's account or physical device. Server acceptance, creation's default enable state, actual firing time, DST behavior and recurrence require owner-observed live checks; #17 remains open for that validation. + +## Live plan-schema correction (17 October 2026) + +Fresh litter-box plans, including a temporary plan created with this client, +report `plan_type_id: 2` and omit `quantity`. The earlier synthetic type-1 +assumption incorrectly blocked edits. Editing now accepts the observed type 2 +(or absent type metadata) and quantity 1 (or absent quantity), while rejecting +unknown types/quantities. The write still sends only time, quantity 1 and the +selected native plan ID. No recurrence meaning is inferred from the type marker. diff --git a/docs/app-validation.md b/docs/app-validation.md index 0f8d752..c18fe9a 100644 --- a/docs/app-validation.md +++ b/docs/app-validation.md @@ -110,11 +110,11 @@ uv run python scripts/validate_lock.py \ ``` `--roundtrip` restores and checks the original lock, mode/delay/language, alias, -pet edited fields or notification category. It attempts restoration even after +pet edited fields, a selected association or notification category. It attempts restoration even after an uncertain write failure. Inspect the restoration file and app before retrying an interrupted test. Immediate readback may lag; a mismatch needs investigation, not a blind repeat. Roundtrips are deliberately rejected for motor commands, -reminder countdowns, schedules, timezone changes, associations, memos, firmware +reminder countdowns, schedules, timezone changes, memos, firmware and deleted history because their original effect cannot be generically restored. Those operations can be selected explicitly without `--roundtrip`. @@ -207,3 +207,66 @@ or history deletion was performed in this development run. Those scripts exist for explicit owner-selected tests with app/physical observations. No empty command was sent. Raw captures and editable app-value templates remain private under `probe-output/app-validation-20261017/`; they are not published in GitHub. + +## Follow-up verification, 17 October 2026 + +The child-lock request now follows the exact APK contract: integer +`user_device_id`, integer `switch`, and no legacy `device_id` field. A live +transition and restoration both matched API readback after two seconds. This +resolves the earlier unchanged-immediate-readback result. The scripts now poll +GET readback after one mutation; they never resend a write while waiting. +Use `--readback-attempts 4 --readback-interval 2` to control the bounded wait. +Restoration also waits for matching readback. A final mismatch remains a failure. + +DND off/on, English/Icons and Auto/Soft stool changes were also observed in live +API readback, then restored. Raw DND boundaries and LED were unchanged throughout. +DND switch-only and selected known-association roundtrips are now supported; clock edits still require explicit +before/after app verification. Actual scheduled firing and DST remain separate +checks, not implied by matching JSON clocks. The device currently reports +`auto_delay: 0`, outside the app-traced 1–15 minute write options; an automatic +roundtrip must not alter it because the original value cannot be safely restored +through that established contract. + +Inspect coverage of every in-scope issue without contacting NOTTY: + +```sh +uv run python scripts/validation_status.py \ + --evidence-dir /absolute/path/to/probe-output +``` + +This lists script coverage, observed API/app comparisons, failures and restoration +results. It does not automatically close an issue or treat a script's existence +as successful validation. Older failure reports can coexist with newer passes. +Feeders/water (#27/#28) remain deferred. See [issue coverage](validation-coverage.md). + +Monitor an owner-selected firmware update without starting another installation: + +```sh +uv run python scripts/monitor_firmware.py \ + --session-file probe-output/session.private.json \ + --device-id YOUR_PHYSICAL_BOX_ID \ + --output-dir probe-output/firmware-observation \ + --samples 12 --interval 10 +``` + +Each sample and the selected target are saved privately. To continue after +restarting the script, pass `--target-version EXACT_PREVIOUS_TARGET` and a new +output directory. Only matching installed-version readback confirms completion; +a success status alone does not. A failure from a different offered target is +not attributed to the selected update. No firmware is installed by this monitor, +no percentage is inferred, and this does not add restart persistence or realtime +firmware-event subscriptions to HA itself. On the owner's current device there +is no offered firmware update, so installation/failure lifecycle validation needs +a future offer. + +The follow-up schedule test found and fixed a real edit guard error: litter-box +plans report `plan_type_id: 2`, not the earlier assumed 1. After correction, +a temporary plan passed create, edit, disable, enable and delete. Scheduled mode +readback also matched, then the original mode and all original plan records +were restored. A selected pet association was toggled and restored with matching +readback. Actual scheduled physical firing still needs observation; these +roundtrips do not assert that it occurred. + +Completed implementation tickets link to [#42](https://github.com/Repsay/notty/issues/42) +for their remaining external acceptance checks. #21, #22 and #41 retain the +specific timezone, firmware and measured-weight work. Emptying is excluded. diff --git a/docs/validation-coverage.md b/docs/validation-coverage.md new file mode 100644 index 0000000..8ad601b --- /dev/null +++ b/docs/validation-coverage.md @@ -0,0 +1,35 @@ +# Remaining-issue coverage + +Every in-scope issue has implementation/contract tests and a dedicated live +validation command. Tests do not operate hardware. Command examples and explicit +write payloads are in [app-validation.md](app-validation.md). Emptying is blocked. + +| Issue | Current implementation / evidence | Validation command | Remaining acceptance | +| --- | --- | --- | --- | +| #11 | Exact integer lock payload; live flag change/restoration confirmed | `validate_lock.py` | Optional physical-button/app observation on other models | +| #12 | Shared DND builder; live switch change/restoration preserves raw clocks/LED | `validate_dnd.py` | DST/actual schedule firing belongs to #21 | +| #14 | Email-code metadata and migration implemented; authenticated reads work | `validate_login.py` | Fresh code exchange with current metadata; HA expiry/reauth flow | +| #15 | Central APK mappings clean=1, empty=2, level=3 | `validate_cleaning.py` | Observe clean/level effects; empty testing is excluded by owner | +| #16 | 1–15 minute Auto-only select and guarded action | `validate_settings.py` | Owner device reports 0; determine its meaning before a restorable write test | +| #17 | Plan CRUD/toggle fixed for live type 2 and validated with cleanup | `validate_schedules.py` | Actual scheduled physical firing | +| #19 | APK enums and guarded mode writes; all three mode readbacks passed with restoration | `validate_settings.py` | Actual scheduled physical firing and broader model behavior | +| #20 | Alias entity, stable HA IDs/override tests; live rename/restoration passed | `validate_alias.py` | Broader model acceptance only | +| #21 | Catalog/change actions, snapshot drift reporting and DST unit tests | `validate_timezone.py` | Explicit timezone transition and actual firing across date/DST boundaries | +| #22 | Update availability/install and Boolean pending target implemented | `validate_firmware.py`, `monitor_firmware.py` | Future offered update; realtime events and HA restart persistence remain unimplemented | +| #23 | Scoped association actions, preservation tests and a live restored association toggle | `validate_associations.py` | Selected association change/restoration and app readback | +| #24 | Account category switches/actions; live toggle/restoration passed | `validate_notifications.py` | Broader app/model acceptance only | +| #25 | Scoped text memo list/detail/create/edit implemented | `validate_memos.py` | Selected text memo lifecycle and app date/reminder semantics | +| #26 | Explicit irreversible empty-body statistics-clear action | `validate_statistics.py` | Exact affected counters/history, only when deletion is wanted | +| #41 | Private weight before/after probes and cat-ID validation | `probe_weights.py` | Independently observed visits, measured source/freshness/history; upstream attribution is outside scope | +| #42 | Consolidated live acceptance checklist | `validation_status.py` plus feature scripts | Remaining physical/app observations; no untested criterion is treated as passed | +| #27/#28 | Deferred by owner | None | Feeder/water support excluded | + +HA unit tests cover entity lifecycle, account ownership, request contracts, +invalid targets, name overrides, IDs, unknown data and failure recovery. A real HA +installation is still needed to observe device/model-specific UI and expired +session reauthentication. Firmware-event support and measured weight/history are +separate development work; monitoring scripts do not imply they are implemented. + +`validation_status.py` audits script coverage and private report counts without +publishing names, weights, account IDs, credentials or capture contents. It keeps +API readback, app-field matches and full acceptance distinct. diff --git a/pyproject.toml b/pyproject.toml index b25fe53..d92a38c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "notty-home-assistant" -version = "0.4.0" +version = "0.4.1" description = "NOTTY smart litter box integration for Home Assistant" readme = "README.md" requires-python = ">=3.14.2" diff --git a/release-notes/v0.4.1.md b/release-notes/v0.4.1.md new file mode 100644 index 0000000..4a65a08 --- /dev/null +++ b/release-notes/v0.4.1.md @@ -0,0 +1,23 @@ +# NOTTY v0.4.1 + +Fix litter-box schedule editing: live plans report plan_type_id 2 and omit +quantity. The previous type-1 assumption rejected those plans. Keep unknown +plan types/quantities blocked while sending the app's quantity-1 edit payload. + +Fix the child-lock request to send only the APK's integer physical +`user_device_id` and integer `switch` fields. Legacy target aliases, extra fields +and loosely coerced switch values are rejected. A live lock transition and +restoration matched fresh readback after two seconds. + +Validation scripts now wait for bounded GET readback after a single write and +again after restoring a setting. Add DND switch-only and scoped association roundtrips, a read-only +firmware lifecycle monitor and a private-evidence coverage audit for all +in-scope issues. Empty-litter commands remain prohibited in validation tools. + +Live DND, screen-language, association and all three cleaning-mode changes were +restored. Temporary schedule CRUD/toggle validation restored every original plan; raw +DND clocks/LED stayed unchanged. Actual scheduled firing/DST, fresh login-code +exchange, a future firmware offer and independently observed cat weigh-ins still +need their own acceptance evidence. Feeders and water dispensers remain deferred. + +Update through HACS and restart Home Assistant. Existing entity IDs are retained. diff --git a/scripts/app_actions.py b/scripts/app_actions.py index 1b878d4..171d124 100644 --- a/scripts/app_actions.py +++ b/scripts/app_actions.py @@ -34,6 +34,8 @@ ALIAS = "alias" PETS = "pets" NOTIFICATIONS = "notifications" +DND = "dnd" +ASSOCIATIONS = "associations" @dataclass @@ -337,6 +339,8 @@ def restore_request(feature: str, operation: str, changes: JsonObject, before: J """ if feature in {"lock", "settings"} and operation in {SET_KEY, SET_DELAY, SET_MODE, "set_language"}: return _setting_restore(operation, changes, before) + if feature == DND and operation == SET_DND: + return _dnd_restore(changes, before) if feature == ALIAS: device = before.get("device") if isinstance(device, dict): @@ -347,11 +351,13 @@ def restore_request(feature: str, operation: str, changes: JsonObject, before: J profile = before.get("profile") if isinstance(profile, dict) and all(key in profile for key in changes): return "update", profile_changes({key: profile[key] for key in changes}) + if feature == ASSOCIATIONS: + return _association_restore(changes, before) if feature == NOTIFICATIONS: restored = _notification_restore(changes, before) if restored is not None: return restored - msg = "Automatic restoration is supported only for lock, mode/delay/language, alias, pet fields and notifications" + msg = "Automatic restoration requires a supported lock/DND toggle, mode/delay/language, alias, pet field, association or notification change" raise NottyApiError(msg) @@ -382,3 +388,30 @@ def _setting_restore(operation: str, changes: JsonObject, before: JsonObject) -> msg = "Original setting is outside the restorable write range" raise NottyApiError(msg) return operation, {field: value} + + +def _dnd_restore(changes: JsonObject, before: JsonObject) -> tuple[str, JsonObject]: + require_fields(changes, {"switch_dnd"}) + info = before.get("info") + state = plan_enabled(info.get("switch_dnd")) if isinstance(info, dict) else None + if state is None: + msg = "DND restoration requires a known original switch state" + raise NottyApiError(msg) + return SET_DND, {"switch_dnd": int(state)} + + +def _association_restore(changes: JsonObject, before: JsonObject) -> tuple[str, JsonObject]: + require_fields(changes, set()) + profile = before.get("profile") + rows = before.get("associations") + pet_id = identifier(profile.get("pet_id")) if isinstance(profile, dict) else None + matches = ( + [row for row in rows if isinstance(row, dict) and row.get("pet_id") == pet_id] if isinstance(rows, list) else [] + ) + state = ( + plan_enabled(matches[0].get("is_associated")) if len(matches) == 1 and isinstance(matches[0], dict) else None + ) + if state is None: + msg = "Association restoration requires one known account pet and binding state" + raise NottyApiError(msg) + return ASSOCIATE if state else "disassociate", {} diff --git a/scripts/app_validation.py b/scripts/app_validation.py index 3b9cc66..d02229d 100644 --- a/scripts/app_validation.py +++ b/scripts/app_validation.py @@ -7,6 +7,7 @@ from dataclasses import dataclass from datetime import UTC, datetime import json +import math from pathlib import Path import sys from typing import cast @@ -77,6 +78,8 @@ LITTER_WORD = "litter" PET_SOURCE = "pet" LITTER_ID = 2 +MAX_READBACK_ATTEMPTS = 10 +MAX_READBACK_INTERVAL = 10 @dataclass @@ -95,6 +98,8 @@ class Options: roundtrip: bool = False output: Path | None = None show_values: bool = False + readback_attempts: int = 4 + readback_interval: float = 2.0 def private_json(path: Path) -> JsonObject: @@ -285,6 +290,13 @@ def validate_options(options: Options) -> None: Raises: ValueError: If modes conflict, paths exist or write evidence would be absent. """ + if ( + not 1 <= options.readback_attempts <= MAX_READBACK_ATTEMPTS + or not math.isfinite(options.readback_interval) + or not 0 <= options.readback_interval <= MAX_READBACK_INTERVAL + ): + msg = "Readback requires 1-10 attempts and a finite interval of 0-10 seconds" + raise ValueError(msg) if (options.session_file is None) == (options.from_file is None): msg = "Choose exactly one saved session or offline capture" raise ValueError(msg) @@ -366,7 +378,7 @@ async def execute( try: await app_actions.apply(api, feature, target, operation, changes) result["write_status"] = "acknowledged_not_physically_verified" - data, after_errors = await collect(api, feature, target, options.memo_id) + data, after_errors = await read_until_applied(api, feature, target, request, options) result.update({"data": data, "errors": after_errors, "captured_at": datetime.now(UTC).isoformat()}) write_json(phase_path(options.capture_raw, "after"), result) except NottyApiError: @@ -406,6 +418,7 @@ async def run(feature: str, options: Options) -> JsonObject: "sources": list(data), "app_comparison": app_comparison(data, expected, show_values=options.show_values), "write_status": capture.get("write_status", "not_attempted"), + "operation": captured_operation(feature, capture), "api_write_readback": write_readback(feature, capture, data), "restore_status": capture.get("restore_status", "not_requested"), "remaining": "Phone-app observations, physical effects, schedule firing/DST and firmware completion are not proved by HTTP success. Login uses an existing session; fresh code login and expiry need a separate auth test.", @@ -433,6 +446,8 @@ def main(feature: str) -> int: parser.add_argument(f"--{name}") for name in ("expect", "template", "capture-raw", "execute", "output"): parser.add_argument(f"--{name}", type=Path) + parser.add_argument("--readback-attempts", type=int, default=4) + parser.add_argument("--readback-interval", type=float, default=2.0) parser.add_argument("--roundtrip", action="store_true") parser.add_argument("--show-values", action="store_true", help="Print private API values locally") options = cast("Options", parser.parse_args()) @@ -485,7 +500,9 @@ async def _restore( fresh_devices = await api.user_devices(await api.pets()) if feature == ALIAS else [] fresh_device = next((row for row in fresh_devices if str(row.get("user_device_id")) == target.box), target.device) restored_target = app_actions.Target(target.box, target.pet, fresh_device) - restored, errors = await collect(api, feature, restored_target, options.memo_id) + restored, errors = await read_until_applied( + api, feature, restored_target, {"operation": restore[0], "changes": restore[1]}, options + ) restored_values = app_actions.restore_request(feature, restore[0], restore[1], restored) status = ( "readback_matches_baseline" if not errors and restored_values == restore else "readback_mismatch_or_unavailable" @@ -510,3 +527,32 @@ def write_readback(feature: str, capture: JsonObject, data: JsonObject) -> str: except NottyApiError: return "not_interpreted_verify_in_app" return "match" if actual == (operation, changes) else MISMATCH + + +async def read_until_applied( + api: app_actions.ValidationApi, feature: str, target: app_actions.Target, request: JsonObject, options: Options +) -> tuple[JsonObject, list[JsonValue]]: + """Poll GET readback after exactly one write, without repeating the mutation. + + Returns: + The latest data and errors, keeping a final mismatch visible to callers. + """ + for attempt in range(options.readback_attempts): + if attempt: + await asyncio.sleep(options.readback_interval) + data, errors = await collect(api, feature, target, options.memo_id) + status = write_readback(feature, {"request": request}, data) + if not errors and status != MISMATCH: + return data, errors + return data, errors + + +def captured_operation(feature: str, capture: JsonObject) -> str | None: + """Expose only a recognized operation label, never private request values. + + Returns: + The selected operation or None for reads/old/unrecognized captures. + """ + request = capture.get("request") + value = request.get("operation") if isinstance(request, dict) else None + return value if isinstance(value, str) and value in app_actions.OPERATIONS.get(feature, set()) else None diff --git a/scripts/monitor_firmware.py b/scripts/monitor_firmware.py new file mode 100755 index 0000000..75f31bc --- /dev/null +++ b/scripts/monitor_firmware.py @@ -0,0 +1,174 @@ +#!/usr/bin/env python3 +"""Observe a NOTTY firmware update with bounded read-only polling and private evidence. + +Run during an update started in the app or with validate_firmware.py. This tool +never installs firmware. Installed-version readback is the completion criterion. +""" + +from __future__ import annotations + +import argparse +import asyncio +from dataclasses import dataclass +from datetime import UTC, datetime +import json +import math +from pathlib import Path +import sys +from typing import cast + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import aiohttp + +from custom_components.notty.api import JsonObject, JsonValue, NottyApiError +from custom_components.notty.device_features import owned_litter +from custom_components.notty.feature_contracts import identifier +from scripts.app_actions import ValidationApi +from scripts.console import console +from scripts.probe_datapoints import write_json +from scripts.validate_commands import ValidationError, load_session + +MAX_SAMPLES = 120 +MAX_INTERVAL = 60 +SUCCEEDED = "installed_version_confirmed" +FAILED = "reported_failure" +NO_OFFER = "no_offered_update" + + +def classify(metadata: JsonValue, target: str | None) -> str: + """Never infer installation from an acknowledgement or a success status alone. + + Returns: + Conservative lifecycle status based on the selected target and current version. + """ + if ( + not isinstance(metadata, dict) + or not isinstance(metadata.get("src_version"), str) + or not metadata["src_version"] + ): + return "metadata_unavailable" + if target and metadata["src_version"] == target: + return SUCCEEDED + status = metadata.get("task_status") + if ( + target + and metadata.get("dest_version") == target + and isinstance(status, str) + and status in {"FAILED", "CANCELED"} + ): + return FAILED + destination = metadata.get("dest_version") + if not target and isinstance(destination, str) and not destination: + return NO_OFFER + return "pending_or_unknown" + + +@dataclass +class MonitorOptions: + """A selected device, optional persisted target, and bounded observation window.""" + + session_file: Path + device_id: str + output_dir: Path + target_version: str | None = None + samples: int = 6 + interval: float = 10 + + +async def run(options: MonitorOptions) -> JsonObject: + """Read the selected device once per sample and save evidence without write calls. + + Returns: + Completion/failure/pending status and sample count; no fabricated percentage. + + Raises: + ValueError: If bounds, paths or target version are invalid. + TypeError: If session credentials are malformed. + """ + device_id = str(identifier(options.device_id)) + if options.target_version is not None and ( + not options.target_version.strip() or not options.target_version.isprintable() + ): + msg = "Target version must be nonempty printable text" + raise ValueError(msg) + if ( + not 1 <= options.samples <= MAX_SAMPLES + or not math.isfinite(options.interval) + or not 0 <= options.interval <= MAX_INTERVAL + ): + msg = "Use 1-120 samples and a finite 0-60 second interval" + raise ValueError(msg) + if options.output_dir.exists() or options.output_dir.is_symlink(): + msg = "Choose a new private output directory" + raise ValueError(msg) + saved = load_session(options.session_file) + token, user = saved.get("access_token"), saved.get("user_id") + if not isinstance(token, str) or not isinstance(user, str): + msg = "Session credentials must be strings" + raise TypeError(msg) + options.output_dir.mkdir(mode=0o700, parents=True) + target = options.target_version + status = "pending_or_unknown" + async with aiohttp.ClientSession() as session: + api = ValidationApi(session, token=token, user_id=user, region_code=str(saved.get("region_code") or "NL")) + await owned_litter(api, device_id) + for index in range(options.samples): + if index: + await asyncio.sleep(options.interval) + metadata = await api.request("GET", f"/device/check_upgrade/{device_id}") + if target is None and isinstance(metadata, dict): + offered = metadata.get("dest_version") + if isinstance(offered, str) and offered.strip(): + target = offered + status = classify(metadata, target) + write_json( + options.output_dir / f"sample-{index + 1:03}.private.json", + { + "captured_at": datetime.now(UTC).isoformat(), + "target_version": target, + "metadata": metadata, + "status": status, + }, + ) + if status in {SUCCEEDED, FAILED, NO_OFFER}: + break + result: JsonObject = { + "status": status, + "samples": index + 1, + "target_version": target, + "progress_percentage": None, + "installation_attempted": False, + } + write_json(options.output_dir / "summary.private.json", result) + return result + + +def main() -> int: + """Observe firmware only; reuse --target-version when continuing after a restart. + + Returns: + Zero for confirmed installed/no offer, one for failure, two for errors, three pending. + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--session-file", type=Path, required=True) + parser.add_argument("--device-id", required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--target-version") + parser.add_argument("--samples", type=int, default=6) + parser.add_argument("--interval", type=float, default=10) + options = cast("MonitorOptions", parser.parse_args()) + try: + result = asyncio.run(run(options)) + console(json.dumps(result, indent=2)) + except NottyApiError, ValidationError, OSError, ValueError, TypeError: + console("Firmware observation failed; no installation was attempted.", file=sys.stderr) + return 2 + if result["status"] == FAILED: + return 1 + return 0 if result["status"] in {SUCCEEDED, NO_OFFER} else 3 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/validation_status.py b/scripts/validation_status.py new file mode 100755 index 0000000..936c294 --- /dev/null +++ b/scripts/validation_status.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Audit open-work validation coverage and summarize private reports without their values.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys +from typing import TYPE_CHECKING, cast + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from scripts.console import console + +if TYPE_CHECKING: + from custom_components.notty.api import JsonObject, JsonValue + +CASES = { + 11: ("lock", "validate_lock.py"), + 12: ("dnd", "validate_dnd.py"), + 14: ("login", "validate_login.py"), + 15: ("commands", "validate_cleaning.py"), + 16: ("settings", "validate_settings.py"), + 17: ("schedules", "validate_schedules.py"), + 19: ("settings", "validate_settings.py"), + 20: ("alias", "validate_alias.py"), + 21: ("timezone", "validate_timezone.py"), + 22: ("firmware", "validate_firmware.py"), + 23: ("associations", "validate_associations.py"), + 24: ("notifications", "validate_notifications.py"), + 25: ("memos", "validate_memos.py"), + 26: ("statistics", "validate_statistics.py"), + 41: ("weight", "probe_weights.py"), + 42: ("acceptance", "validation_status.py"), +} +CASE_OPERATIONS = {16: "set_auto_delay", 19: "set_mode"} +APP_MATCH = "matches_supplied_phone_app_values" +API_MATCH = "match" +API_MISMATCH = "mismatch" +RESTORED = "readback_matches_baseline" +READS_COMPLETE = "completed" + + +def summaries(directory: Path | None) -> tuple[dict[str, list[JsonObject]], int]: + """Load only feature report fields used as evidence, never echoing private values. + + Returns: + Known feature reports and unreadable-file count. + """ + results: dict[str, list[JsonObject]] = {} + failures = 0 + if directory is None: + return results, failures + known = {feature for feature, _ in CASES.values()} + for path in directory.rglob("*.report.private.json"): + try: + value = cast("JsonValue", json.loads(path.read_text(encoding="utf-8"))) + except OSError, ValueError: + failures += 1 + continue + if isinstance(value, dict): + feature = value.get("feature") + if isinstance(feature, str) and feature in known: + results.setdefault(feature, []).append(value) + return results, failures + + +def audit(directory: Path | None = None) -> JsonObject: + """Separate tool coverage, live API evidence and independently supplied app evidence. + + Returns: + A value-free issue-by-issue summary; script existence does not imply validation passed. + """ + reports, errors = summaries(directory) + root = Path(__file__).resolve().parent + cases: list[JsonValue] = [] + missing = 0 + for issue, (feature, script) in CASES.items(): + exists = (root / script).is_file() + missing += not exists + evidence = reports.get(feature, []) + writes = [ + row for row in evidence if issue not in CASE_OPERATIONS or row.get("operation") == CASE_OPERATIONS[issue] + ] + app_matches = 0 + for row in evidence: + comparison = row.get("app_comparison") + if isinstance(comparison, dict) and comparison.get("status") == APP_MATCH: + app_matches += 1 + cases.append({ + "issue": issue, + "feature": feature, + "script": script, + "script_available": exists, + "api_read_reports": sum(row.get("api_reads") == READS_COMPLETE for row in evidence), + "write_readback_matches": sum(row.get("api_write_readback") == API_MATCH for row in writes), + "write_readback_mismatches": sum(row.get("api_write_readback") == API_MISMATCH for row in writes), + "restoration_matches": sum(row.get("restore_status") == RESTORED for row in writes), + "reports_matching_supplied_app_values": app_matches, + "acceptance": "review_required_not_inferred_from_script_presence", + }) + return { + "cases": cases, + "missing_scripts": missing, + "unreadable_reports": errors, + "deferred_issues": [27, 28], + "notes": "Reports may include older failures and newer successes. App matches cover only supplied fields. Physical effects, DST firing, firmware completion and measured-weight freshness need their own evidence.", + } + + +def main() -> int: + """Print coverage without running a probe, changing settings or closing issues. + + Returns: + One for missing scripts/unreadable reports, zero for complete tool coverage. + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--evidence-dir", type=Path) + options = parser.parse_args() + directory = cast("Path | None", options.evidence_dir) + result = audit(directory) + console(json.dumps(result, indent=2)) + return int(bool(result["missing_scripts"] or result["unreadable_reports"])) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_api.py b/tests/test_api.py index 3113ada..b26d06b 100644 --- a/tests/test_api.py +++ b/tests/test_api.py @@ -128,8 +128,9 @@ async def test_action_payload_cannot_override_selected_device() -> None: """Verify action payload cannot override selected device.""" api = NottyApi(MagicMock()) api.request = AsyncMock() - await api.litter_action("box-1", "set_key", {"switch": 1, "user_device_id": "box-2", "device_id": "box-2"}) - assert api.request.call_args.kwargs["data"] == {"switch": 1, "user_device_id": "box-1", "device_id": "box-1"} + with pytest.raises(NottyApiError, match="only integer switch"): + await api.litter_action("123", "set_key", {"switch": 1, "user_device_id": "456", "device_id": "456"}) + api.request.assert_not_awaited() @pytest.mark.parametrize(("status", "error"), [(401, NottyAuthError), (500, NottyApiError)]) diff --git a/tests/test_app_validation.py b/tests/test_app_validation.py index a9aed23..7f92aaa 100644 --- a/tests/test_app_validation.py +++ b/tests/test_app_validation.py @@ -158,3 +158,38 @@ def test_acknowledged_but_unchanged_api_write_is_a_mismatch() -> None: capture: JsonObject = {"request": {"operation": "set_key", "changes": {"switch": 1}}} assert app_validation.write_readback("lock", capture, {"info": {"switch_key": 0}}) == EXPECTED_MISMATCH assert app_validation.write_readback("lock", capture, {"info": {"switch_key": 1}}) != EXPECTED_MISMATCH + + +async def test_delayed_readback_polls_without_repeating_the_write() -> None: + """An asynchronous device acknowledgement can settle after the first GET.""" + api = MagicMock() + request: JsonObject = {"operation": "set_key", "changes": {"switch": 1}} + snapshots = [({"info": {"switch_key": 0}}, []), ({"info": {"switch_key": 1}}, [])] + with patch.object(app_validation, "collect", AsyncMock(side_effect=snapshots)) as collect: + data, errors = await app_validation.read_until_applied( + api, "lock", app_actions.Target("123", "", {}), request, app_validation.Options(readback_interval=0) + ) + assert data["info"]["switch_key"] == 1 + assert errors == [] + assert collect.await_count == len(snapshots) + api.request.assert_not_called() + + +async def test_final_readback_mismatch_is_not_hidden_by_polling() -> None: + """Exhausting GET attempts retains the failed requested-value comparison.""" + request: JsonObject = {"operation": "set_key", "changes": {"switch": 1}} + with patch.object(app_validation, "collect", AsyncMock(return_value=({"info": {"switch_key": 0}}, []))): + data, _ = await app_validation.read_until_applied( + MagicMock(), "lock", app_actions.Target("123", "", {}), request, app_validation.Options(readback_attempts=1) + ) + assert app_validation.write_readback("lock", {"request": request}, data) == EXPECTED_MISMATCH + + +@pytest.mark.parametrize("switch", [True, "1", 1.0, -1, 2, None]) +async def test_child_lock_rejects_non_app_switch_encodings(switch: JsonValue) -> None: + """The integer enum is not a loosely coerced Boolean/string.""" + api = NottyApi(MagicMock()) + api.request = AsyncMock() + with pytest.raises(NottyApiError, match="integer switch"): + await api.litter_action("123", "set_key", {"switch": switch}) + api.request.assert_not_awaited() diff --git a/tests/test_schedules.py b/tests/test_schedules.py index 2a2185c..bb6f934 100644 --- a/tests/test_schedules.py +++ b/tests/test_schedules.py @@ -18,7 +18,7 @@ from tests.test_lifecycle import setup CONTRACT = json.loads((Path(__file__).parent / "fixtures/apk_litter_plans.json").read_text()) -PLAN = {"plan_id": 81, "time": "07:00", "open": False, "quantity": 1, "plan_type_id": 1} +PLAN = {"plan_id": 81, "time": "07:00", "open": False, "quantity": 1, "plan_type_id": 2} EXPECTED_FALSE_COUNT = 1 EXPECTED_EDIT = "edit_plan" EXPECTED_OPEN = "open_plan" @@ -144,7 +144,7 @@ async def test_toggle_is_idempotent_and_preserves_other_fields(*, enabled: bool) assert api.request.await_count == 1 -@pytest.mark.parametrize("changes", [{"quantity": 2}, {"quantity": True}, {"plan_type_id": 2}, {"plan_type_id": "1"}]) +@pytest.mark.parametrize("changes", [{"quantity": 2}, {"quantity": True}, {"plan_type_id": 9}, {"plan_type_id": "2"}]) def test_edit_does_not_reinterpret_other_plan_types(changes: dict[str, object]) -> None: """Unknown recurrence/quantity is not overwritten by the litter-box default.""" with pytest.raises(NottyApiError, match="unsupported schedule"): @@ -271,3 +271,14 @@ def test_plan_rows_preserve_id_type_and_unknown_read_fields() -> None: before = json.dumps(rows) assert plan_rows(rows) == rows assert json.dumps(rows) == before + + +def test_live_litter_plan_shape_with_type_two_and_omitted_quantity_is_editable() -> None: + """Real litter-box plans use type 2 and omit quantity; requests still use quantity 1.""" + current = {"plan_id": 81, "time": "08:00", "open": True, "plan_type_id": 2} + assert plan_payload("edit_plan", {"plan_id": 81, "time": "23:58"}, [current], "123") == { + "plan_id": 81, + "time": "23:58", + "quantity": 1, + } + assert current == {"plan_id": 81, "time": "08:00", "open": True, "plan_type_id": 2} diff --git a/tests/test_setting_contracts.py b/tests/test_setting_contracts.py index 1d39cd4..c02b3f3 100644 --- a/tests/test_setting_contracts.py +++ b/tests/test_setting_contracts.py @@ -132,9 +132,9 @@ async def test_child_lock_request_contract(*, enabled: int | str | bool) -> None """Verify child lock request contract.""" api = NottyApi(MagicMock()) api.request = AsyncMock() - await api.litter_action("box-1", "set_key", {"switch": enabled}) + await api.litter_action("123", "set_key", {"switch": enabled}) api.request.assert_awaited_once_with( - "POST", "/device/litter_box/set_key", data={"user_device_id": "box-1", "device_id": "box-1", "switch": enabled} + "POST", "/device/litter_box/set_key", data={"user_device_id": 123, "switch": enabled} ) diff --git a/tests/test_validation_monitoring.py b/tests/test_validation_monitoring.py new file mode 100644 index 0000000..f9a0fa3 --- /dev/null +++ b/tests/test_validation_monitoring.py @@ -0,0 +1,83 @@ +"""Firmware observations and evidence audits never substitute HTTP success for acceptance.""" + +from __future__ import annotations + +import json +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from custom_components.notty.api import JsonValue +from scripts import monitor_firmware, validation_status +from scripts.probe_datapoints import write_json + +PENDING = "pending_or_unknown" +NO_OFFER = "no_offered_update" +TARGET = "1.2.3" +CONFIRMED = "installed_version_confirmed" +FAILED = "reported_failure" +METHOD_GET = "GET" +PRIVATE_MODE = 0o600 +LOCK_ISSUE = 11 +PRIVATE_MARKER = "private@example.test" + + +@pytest.mark.parametrize( + ("metadata", "target", "expected"), + [ + ({"src_version": "1.0", "dest_version": TARGET, "task_status": "SUCCEEDED"}, TARGET, PENDING), + ({"src_version": TARGET, "dest_version": "", "task_status": ""}, TARGET, CONFIRMED), + ({"src_version": "1.0", "dest_version": "", "task_status": ""}, None, NO_OFFER), + ({"src_version": "1.0", "dest_version": None}, None, PENDING), + ({"src_version": "1.0", "dest_version": TARGET, "task_status": "FAILED"}, TARGET, FAILED), + ({"src_version": "1.0", "dest_version": "other", "task_status": "FAILED"}, TARGET, PENDING), + ({"src_version": "", "dest_version": ""}, None, "metadata_unavailable"), + ], +) +def test_firmware_completion_requires_actual_installed_version( + metadata: JsonValue, target: str | None, expected: str +) -> None: + """A stale failure or success string cannot establish this target's outcome.""" + assert monitor_firmware.classify(metadata, target) == expected + + +async def test_monitor_only_reads_and_stops_when_installed(tmp_path: Path) -> None: + """A target can be continued after restarting the script without installing it again.""" + session = tmp_path / "session.private.json" + write_json(session, {"access_token": "test-token", "user_id": "test-user"}) + api = MagicMock( + request=AsyncMock( + side_effect=[{"src_version": "1.0", "dest_version": TARGET}, {"src_version": TARGET, "dest_version": ""}] + ) + ) + options = monitor_firmware.MonitorOptions(session, "123", tmp_path / "monitor", target_version=TARGET, interval=0) + with ( + patch.object(monitor_firmware, "owned_litter", AsyncMock()), + patch.object(monitor_firmware, "ValidationApi", return_value=api), + ): + result = await monitor_firmware.run(options) + assert result["status"] == CONFIRMED + assert result["installation_attempted"] is False + assert all(call.args[0] == METHOD_GET for call in api.request.await_args_list) + assert (options.output_dir / "summary.private.json").stat().st_mode & 0o777 == PRIVATE_MODE + + +def test_evidence_audit_reports_coverage_without_private_values_or_automatic_acceptance(tmp_path: Path) -> None: + """Stale failures and pending app observations remain visible alongside successes.""" + write_json( + tmp_path / "lock.report.private.json", + { + "feature": "lock", + "api_reads": "completed", + "api_write_readback": "mismatch", + "restore_status": "readback_matches_baseline", + "values": {"email": "private@example.test"}, + }, + ) + report = validation_status.audit(tmp_path) + assert report["missing_scripts"] == 0 + lock = next(row for row in report["cases"] if row["issue"] == LOCK_ISSUE) + assert lock["write_readback_mismatches"] == 1 + assert lock["reports_matching_supplied_app_values"] == 0 + assert PRIVATE_MARKER not in json.dumps(report) diff --git a/uv.lock b/uv.lock index 9bb7ebc..fab285b 100644 --- a/uv.lock +++ b/uv.lock @@ -1916,7 +1916,7 @@ wheels = [ [[package]] name = "notty-home-assistant" -version = "0.4.0" +version = "0.4.1" source = { virtual = "." } dependencies = [ { name = "aiohttp" },