From df7bb7602c021353f45c1cca41e9263d0e945dcf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:05:50 -0500 Subject: [PATCH 01/11] feat(flow): read-only local-state effect checker for files and OS settings --- packages/flow/openadapt_flow/deployment.py | 28 +- .../flow/openadapt_flow/execution_profiles.py | 1 + .../runtime/effects/__init__.py | 9 +- .../runtime/effects/local_state.py | 431 ++++++++++++++++++ .../flow/tests/test_local_state_verifier.py | 403 ++++++++++++++++ 5 files changed, 868 insertions(+), 4 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/effects/local_state.py create mode 100644 packages/flow/tests/test_local_state_verifier.py diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index c667d64721..c9b05ec432 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -26,7 +26,7 @@ import os import re from pathlib import Path -from typing import Any, Callable, Final, Literal, Mapping, Optional +from typing import Annotated, Any, Callable, Final, Literal, Mapping, Optional from pydantic import ( BaseModel, @@ -55,6 +55,7 @@ from openadapt_flow.runtime.effects.effect import Region, ValueExpr from openadapt_flow.runtime.effects.frame import FrameAttribution, FrameDatabase from openadapt_flow.runtime.effects.fresh_session import FreshSessionSpec +from openadapt_flow.runtime.effects.local_state import LocalStateSource from openadapt_flow.runtime.effects.smart_auth import SmartBackendConfig from openadapt_flow.runtime.effects.ui_readback import UiReadbackSpec @@ -225,6 +226,8 @@ def _surface_matches_kind(self) -> "BackendConfig": "email", "document", "document-hash", + "local-state", + "local_state", "desktop_readback", "desktop-readback", "deferred_report", @@ -306,7 +309,7 @@ class EffectsConfig(BaseModel): #: ``none`` | ``onscreen`` | ``ui_readback`` | ``rest`` | ``graphql`` | #: ``fhir`` | ``sql`` | ``file`` | ``email`` | ``document`` | - #: ``document-hash``, or a PLUGIN + #: ``document-hash`` | ``local-state``, or a PLUGIN #: kind registered under the #: ``openadapt_flow.effect_verifiers`` entry-point group (the customer #: adapter SDK seam -- see docs/EFFECT_KIT.md). ``onscreen`` is the no-API @@ -538,6 +541,15 @@ class EffectsConfig(BaseModel): root: Optional[str] = None glob: str = "*" + # -- local-state (files and OS settings on this computer) ---------------- + #: The typed, read-only sources ``kind: local-state`` reads: ``file`` + #: (contents and SHA-256), ``macos_defaults`` (a preference key) and + #: ``windows_registry`` (a registry value). There is no free-form command; + #: see :mod:`openadapt_flow.runtime.effects.local_state`. + local_state: list[Annotated[LocalStateSource, Field(discriminator="type")]] = ( + Field(default_factory=list) + ) + # -- plugin record-check packs (registered kinds only) -------------------- #: Non-secret settings for a PLUGIN verifier kind: the per-system record #: check a private pack implements (which read endpoint, which record @@ -2606,6 +2618,18 @@ def _build_effect_verifier_unredacted( return DocumentHashVerifier(cfg.root, glob=cfg.glob) + if kind in ("local-state", "local_state"): + if not cfg.local_state: + raise ValueError( + "effects.kind 'local-state' requires effects.local_state " + "(the files or settings to read)" + ) + from openadapt_flow.runtime.effects import LocalStateVerifier + + return LocalStateVerifier( + list(cfg.local_state), poll_interval_s=cfg.poll_interval_s + ) + if kind == "graphql": if not cfg.base_url: raise ValueError("effects.kind 'graphql' requires effects.base_url") diff --git a/packages/flow/openadapt_flow/execution_profiles.py b/packages/flow/openadapt_flow/execution_profiles.py index ceeb706779..46a536e19a 100644 --- a/packages/flow/openadapt_flow/execution_profiles.py +++ b/packages/flow/openadapt_flow/execution_profiles.py @@ -2680,6 +2680,7 @@ def _external_network_call_state( "onscreen", "file", "document_hash", + "local_state", "snapshot", "test", "fake", diff --git a/packages/flow/openadapt_flow/runtime/effects/__init__.py b/packages/flow/openadapt_flow/runtime/effects/__init__.py index 0eca8e8d43..f6d09c5037 100644 --- a/packages/flow/openadapt_flow/runtime/effects/__init__.py +++ b/packages/flow/openadapt_flow/runtime/effects/__init__.py @@ -24,8 +24,9 @@ :class:`SqlRecordVerifier` (read-only SQL, enforced whitelist), :class:`FileArrivalVerifier` (file / SFTP arrival), :class:`MaildirDeliveryVerifier` (maildir / SMTP-capture email delivery), - :class:`DocumentArrivalVerifier` (report arrival + parseable content), and - :class:`DocumentHashVerifier` (filesystem document store). + :class:`DocumentArrivalVerifier` (report arrival + parseable content), + :class:`DocumentHashVerifier` (filesystem document store), and + :class:`LocalStateVerifier` (files and OS settings on this computer). - The adapter platform (:mod:`openadapt_flow.runtime.effects.adapter`): :class:`VerifierAdapter` / :class:`VerifierAdapterBase` (lifecycle: configure -> test-connection -> capture-before -> capture-after -> @@ -122,6 +123,9 @@ ArrivalTransport, FileArrivalVerifier, ) +from openadapt_flow.runtime.effects.local_state import ( # noqa: F401 + LocalStateVerifier, +) from openadapt_flow.runtime.effects.graphql import ( # noqa: F401 GraphQLRecordVerifier, assert_read_only_graphql, @@ -207,6 +211,7 @@ "capture_table_counts", "FileArrivalVerifier", "ArrivalTransport", + "LocalStateVerifier", "SeparateSessionReadbackVerifier", "UiReadbackSpec", "DesktopReadbackSpec", diff --git a/packages/flow/openadapt_flow/runtime/effects/local_state.py b/packages/flow/openadapt_flow/runtime/effects/local_state.py new file mode 100644 index 0000000000..5770b44e32 --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/effects/local_state.py @@ -0,0 +1,431 @@ +"""Read-only local-state :class:`EffectVerifier`: files and OS settings. + +Some workflows change state that no application database holds: a document +saved to disk, or an operating-system setting such as the appearance mode. +The screen showing the change proves nothing. This verifier reads that state +back through the operating system's own supported, read-only interfaces, so +a run can be checked the same way a REST or SQL write is checked. + +Each **source** is a typed, closed description of one piece of state. There is +no free-form command: the verifier decides how to read each type, and every +read is read-only. + +``file`` + A path on this computer. Read with ordinary file I/O, never opened for + writing. +``macos_defaults`` + A preference ``key`` in a ``domain`` (``NSGlobalDomain`` or a bundle id). + Read with ``/usr/bin/defaults export -``, the supported reader of + the preferences system. It goes through ``cfprefsd``, so it sees the + current value, not a stale plist on disk. +``windows_registry`` + A value ``name`` under ``hive`` (``HKCU`` or ``HKLM``) and ``path``. Read + with :mod:`winreg` and ``KEY_READ`` access only. + +Each source flattens to one record, keyed by the source's ``id``: + +* every source: ``id``, ``type`` and ``present`` (``True`` or ``False``); +* ``file`` adds ``size``, ``sha256`` and ``text`` (the contents decoded as + UTF-8 when they are at most :data:`TEXT_LIMIT` bytes and valid UTF-8, else + ``None``); +* ``macos_defaults`` and ``windows_registry`` add ``value`` (the value as + text: see :func:`value_text`) and ``value_type``. + +So an example declares its expected change with the shared effect kinds:: + + effects: + - kind: field_equals + match: {id: note} + field: text + value: {param: note} + +A missing file, key or value is a real, readable state (``present: False``): +an expected state of "this setting is off" can be the key's absence. A read +that fails for any other reason (wrong operating system, permission denied, +``defaults`` exiting non-zero, output that does not parse) makes the whole +read unreadable, so the verdict is INDETERMINATE and the run halts. The +verifier never guesses a value it could not read. + +The tier is ``INDEPENDENT_SYSTEM``: the read goes to the store the state +lives in (the file system, the preferences system, the registry) through a +separate process or API, not through the screen that showed the change. + +No model calls, no network, and nothing here writes. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import plistlib +import re +import subprocess +import sys +from pathlib import Path +from typing import Any, Callable, Literal, Optional, Union + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +from openadapt_flow.runtime.effects.adapter import ( + VerifierAdapterBase, + poll_until_settled, +) +from openadapt_flow.runtime.effects.effect import ( + Effect, + EffectState, + EffectVerdict, +) +from openadapt_flow.verification import VerificationTier + +#: A file larger than this many bytes is hashed, but its ``text`` is ``None``. +TEXT_LIMIT = 1 << 20 # 1 MiB + +#: The supported macOS preferences reader. An absolute path, so ``PATH`` +#: cannot substitute another program. +DEFAULTS_BINARY = "/usr/bin/defaults" + +#: A source id: what an effect's ``match: {id: ...}`` names. +_SOURCE_ID = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,63}") +#: A preferences domain: ``NSGlobalDomain`` or a reverse-DNS bundle id. A +#: leading ``-`` is refused, so a domain can never become a ``defaults`` flag. +_DEFAULTS_DOMAIN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,254}") +#: Registry hives a source may read. Per-user settings and machine settings; +#: nothing else is needed for read-back. +REGISTRY_HIVES = ("HKCU", "HKLM") + +Runner = Callable[[list[str]], "subprocess.CompletedProcess[bytes]"] + + +class _Source(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + id: str + + @field_validator("id") + @classmethod + def _check_id(cls, value: str) -> str: + if not _SOURCE_ID.fullmatch(value): + raise ValueError( + "local-state source id must start with a letter and use only " + "letters, digits, '_', '.' or '-' (at most 64 characters)" + ) + return value + + +class FileSource(_Source): + """A file on this computer: its contents and SHA-256.""" + + type: Literal["file"] = "file" + #: The file's path. ``~`` and environment variables are expanded. + path: str = Field(min_length=1) + + +class MacosDefaultsSource(_Source): + """One key in a macOS preferences domain.""" + + type: Literal["macos_defaults"] = "macos_defaults" + #: ``NSGlobalDomain`` (``-g`` is accepted and means the same) or a bundle id. + domain: str + key: str = Field(min_length=1, max_length=255) + + @field_validator("domain") + @classmethod + def _check_domain(cls, value: str) -> str: + if value == "-g": + return "NSGlobalDomain" + if not _DEFAULTS_DOMAIN.fullmatch(value): + raise ValueError( + "macos_defaults domain must be NSGlobalDomain or a bundle id " + "(letters, digits, '.', '_' or '-'; not starting with '-')" + ) + return value + + +class WindowsRegistrySource(_Source): + """One value in the Windows registry.""" + + type: Literal["windows_registry"] = "windows_registry" + hive: Literal["HKCU", "HKLM"] + #: The key path under the hive, with backslashes (no leading backslash). + path: str = Field(min_length=1, max_length=1024) + #: The value's name. An empty string is the key's default value. + name: str = Field(default="", max_length=16383) + + @field_validator("path") + @classmethod + def _check_path(cls, value: str) -> str: + if value.startswith("\\") or "\x00" in value: + raise ValueError( + "windows_registry path is relative to the hive and must not " + "start with a backslash" + ) + return value + + +LocalStateSource = Union[FileSource, MacosDefaultsSource, WindowsRegistrySource] + + +class _Unreadable(Exception): + """A source could not be read. The whole read is then unreadable.""" + + +def value_text(value: Any) -> Optional[str]: + """A setting's value as the text an effect compares against. + + Text stays as it is, a boolean is ``"true"`` or ``"false"``, a number is + its decimal form, bytes are lowercase hex, and anything else (a list or a + dictionary from a plist, a multi-string from the registry) is compact JSON + with sorted keys. ``None`` stays ``None``. + """ + + if value is None: + return None + if isinstance(value, bool): + return "true" if value else "false" + if isinstance(value, (int, float, str)): + return str(value) + if isinstance(value, (bytes, bytearray)): + return bytes(value).hex() + try: + return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str) + except (TypeError, ValueError) as exc: + raise _Unreadable(f"value of type {type(value).__name__} has no text form") from exc + + +def _plist_type(value: Any) -> str: + for kind, name in ( + (bool, "boolean"), + (int, "integer"), + (float, "float"), + (str, "string"), + (bytes, "data"), + (list, "array"), + (dict, "dictionary"), + ): + if isinstance(value, kind): + return name + return type(value).__name__ + + +def _run(argv: list[str]) -> "subprocess.CompletedProcess[bytes]": + return subprocess.run(argv, capture_output=True, timeout=10, check=False) + + +class LocalStateVerifier(VerifierAdapterBase): + """Verify effects against files and OS settings on this computer. + + Args: + sources: The typed sources to read, each with a distinct ``id``. + poll_interval_s: Re-read interval while an effect settles (the OS + may apply a setting a moment after the click). + runner: Runs the fixed ``defaults`` argv; injectable for tests. + registry: The :mod:`winreg` module (or a stand-in for tests); + ``None`` imports it, and its absence makes registry sources + unreadable. + platform: ``sys.platform`` override for tests. + session: Unused; present for protocol symmetry. + """ + + substrate = "local_state" + verification_tier = VerificationTier.INDEPENDENT_SYSTEM + + def __init__( + self, + sources: list[LocalStateSource], + *, + poll_interval_s: float = 0.25, + runner: Optional[Runner] = None, + registry: Any = None, + platform: Optional[str] = None, + session: Any = None, + ) -> None: + if not sources: + raise ValueError("effects.kind 'local-state' needs at least one source") + ids = [s.id for s in sources] + duplicates = sorted({i for i in ids if ids.count(i) > 1}) + if duplicates: + raise ValueError( + "local-state source ids must be distinct: " + ", ".join(duplicates) + ) + self.sources = list(sources) + self.poll_interval_s = poll_interval_s + self._runner = runner or _run + self._registry = registry + self._platform = platform or sys.platform + #: Why the last read was unreadable, for the verdict's detail. + self.last_error: Optional[str] = None + + # -- reads --------------------------------------------------------------- + + def _read_file(self, source: FileSource) -> dict[str, Any]: + path = Path(os.path.expandvars(os.path.expanduser(source.path))) + record: dict[str, Any] = {"id": source.id, "type": source.type} + try: + # O_RDONLY only: the read never creates or truncates the file. + with path.open("rb") as fh: + data = fh.read(TEXT_LIMIT + 1) + digest = hashlib.sha256(data) + size = len(data) + for block in iter(lambda: fh.read(1 << 16), b""): + digest.update(block) + size += len(block) + except FileNotFoundError: + if not path.parent.is_dir(): + # The folder that should hold the file is gone: that is not + # "the file was not saved", it is a store we can't see. + raise _Unreadable(f"{source.id}: folder {path.parent} does not exist") + record.update(present=False, size=None, sha256=None, text=None) + return record + except OSError as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + text: Optional[str] = None + if size <= TEXT_LIMIT: + try: + text = data.decode("utf-8") + except UnicodeDecodeError: + text = None + record.update(present=True, size=size, sha256=digest.hexdigest(), text=text) + return record + + def _read_defaults( + self, source: MacosDefaultsSource, cache: dict[str, dict[str, Any]] + ) -> dict[str, Any]: + if self._platform != "darwin": + raise _Unreadable(f"{source.id}: macos_defaults needs macOS") + domain = cache.get(source.domain) + if domain is None: + try: + done = self._runner([DEFAULTS_BINARY, "export", source.domain, "-"]) + except (OSError, subprocess.SubprocessError) as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + if done.returncode != 0: + raise _Unreadable( + f"{source.id}: defaults exited {done.returncode}" + ) + try: + parsed = plistlib.loads(done.stdout) + except Exception as exc: # noqa: BLE001 - any parse failure is unreadable + raise _Unreadable(f"{source.id}: defaults output is not a plist") from exc + if not isinstance(parsed, dict): + raise _Unreadable(f"{source.id}: defaults output is not a dictionary") + domain = parsed + cache[source.domain] = domain + record: dict[str, Any] = {"id": source.id, "type": source.type} + if source.key not in domain: + record.update(present=False, value=None, value_type=None) + return record + value = domain[source.key] + record.update( + present=True, value=value_text(value), value_type=_plist_type(value) + ) + return record + + def _winreg(self) -> Any: + if self._registry is not None: + return self._registry + if self._platform != "win32": + raise _Unreadable("windows_registry needs Windows") + try: + import winreg # type: ignore[import-not-found,unused-ignore] + except ImportError as exc: + raise _Unreadable("windows_registry needs Windows") from exc + return winreg + + def _read_registry(self, source: WindowsRegistrySource) -> dict[str, Any]: + try: + reg = self._winreg() + except _Unreadable as exc: + raise _Unreadable(f"{source.id}: {exc}") from exc + hive = getattr(reg, "HKEY_CURRENT_USER" if source.hive == "HKCU" else "HKEY_LOCAL_MACHINE") + record: dict[str, Any] = {"id": source.id, "type": source.type} + try: + with reg.OpenKey(hive, source.path, 0, reg.KEY_READ) as key: + value, kind = reg.QueryValueEx(key, source.name) + except FileNotFoundError: + record.update(present=False, value=None, value_type=None) + return record + except OSError as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + names = { + getattr(reg, n): n + for n in ( + "REG_SZ", + "REG_EXPAND_SZ", + "REG_MULTI_SZ", + "REG_DWORD", + "REG_QWORD", + "REG_BINARY", + ) + if hasattr(reg, n) + } + record.update( + present=True, value=value_text(value), value_type=names.get(kind, str(kind)) + ) + return record + + def read(self) -> Optional[list[dict[str, Any]]]: + """One read of every source, or ``None`` when any source is unreadable.""" + cache: dict[str, dict[str, Any]] = {} + records: list[dict[str, Any]] = [] + try: + for source in self.sources: + if isinstance(source, FileSource): + records.append(self._read_file(source)) + elif isinstance(source, MacosDefaultsSource): + records.append(self._read_defaults(source, cache)) + else: + records.append(self._read_registry(source)) + except _Unreadable as exc: + self.last_error = str(exc) + return None + self.last_error = None + return records + + def _detail(self) -> dict[str, Any]: + detail: dict[str, Any] = { + "sources": [s.model_dump() for s in self.sources], + } + if self.last_error: + detail["unreadable"] = self.last_error + return detail + + # -- EffectVerifier protocol -------------------------------------------- + + def capture_pre_state(self, context: Any = None) -> EffectState: + records = self.read() + return EffectState( + substrate=self.substrate, + reachable=records is not None, + records=records or [], + detail=self._detail(), + ) + + def verify( + self, expected: Effect, before: EffectState, context: Any = None + ) -> EffectVerdict: + verdict = poll_until_settled( + self.read, + expected, + before, + substrate=self.substrate, + poll_interval_s=self.poll_interval_s, + ) + if self.last_error and not verdict.confirmed: + verdict = verdict.model_copy( + update={"reason": f"{verdict.reason} ({self.last_error})"} + ) + return verdict + + +__all__ = [ + "DEFAULTS_BINARY", + "FileSource", + "LocalStateSource", + "LocalStateVerifier", + "MacosDefaultsSource", + "REGISTRY_HIVES", + "TEXT_LIMIT", + "WindowsRegistrySource", + "value_text", +] diff --git a/packages/flow/tests/test_local_state_verifier.py b/packages/flow/tests/test_local_state_verifier.py new file mode 100644 index 0000000000..f2b87a5c9e --- /dev/null +++ b/packages/flow/tests/test_local_state_verifier.py @@ -0,0 +1,403 @@ +"""The read-only local-state verifier: files, macOS defaults, Windows registry. + +Every OS read goes through an injected stand-in, so this runs on any +platform and never reads this computer's own settings. The real reads are +qualified on the lab machines (docs/LOCAL_STATE_CHECKS.md). +""" + +from __future__ import annotations + +import hashlib +import plistlib +import subprocess +from pathlib import Path +from typing import Any + +import pytest +from pydantic import ValidationError + +from openadapt_flow.deployment import EffectsConfig, build_effect_verifier +from openadapt_flow.runtime.effects import Effect, EffectKind, Verdict +from openadapt_flow.runtime.effects.local_state import ( + DEFAULTS_BINARY, + FileSource, + LocalStateVerifier, + MacosDefaultsSource, + WindowsRegistrySource, + value_text, +) +from openadapt_flow.verify_run import VerifyConfig, capture_baseline, verify_run +from openadapt_flow.verification import VerificationTier + +RUN_RECORD = {"executor_kind": "flow_replay", "executor_id": "test-replay"} + + +def _field(source_id: str, field: str, value: Any, **kw: Any) -> Effect: + return Effect( + kind=EffectKind.FIELD_EQUALS, + match={"id": source_id}, + field=field, + value=value, + timeout_s=kw.pop("timeout_s", 0.0), + **kw, + ) + + +def _judge(verifier: LocalStateVerifier, effect: Effect) -> Verdict: + before = verifier.capture_pre_state() + return verifier.verify(effect, before).verdict + + +# -- file ---------------------------------------------------------------------- + + +def test_file_contents_and_hash_confirm(tmp_path: Path) -> None: + note = tmp_path / "note.txt" + note.write_text("synthetic note 9022", encoding="utf-8") + v = LocalStateVerifier([FileSource(id="note", path=str(note))]) + (record,) = v.read() or [] + assert record["present"] is True + assert record["text"] == "synthetic note 9022" + assert record["sha256"] == hashlib.sha256(b"synthetic note 9022").hexdigest() + assert _judge(v, _field("note", "text", "synthetic note 9022")) is Verdict.CONFIRMED + assert _judge(v, _field("note", "text", "synthetic note 4711")) is Verdict.REFUTED + + +def test_missing_file_is_a_readable_state(tmp_path: Path) -> None: + v = LocalStateVerifier([FileSource(id="note", path=str(tmp_path / "none.txt"))]) + (record,) = v.read() or [] + assert record["present"] is False + assert _judge(v, _field("note", "present", "False")) is Verdict.CONFIRMED + assert _judge(v, _field("note", "text", "anything")) is Verdict.REFUTED + + +def test_missing_folder_is_unreadable(tmp_path: Path) -> None: + v = LocalStateVerifier( + [FileSource(id="note", path=str(tmp_path / "gone" / "note.txt"))] + ) + assert v.read() is None + verdict = v.verify(_field("note", "present", "False"), v.capture_pre_state()) + assert verdict.verdict is Verdict.INDETERMINATE + assert "does not exist" in verdict.reason + + +def test_large_or_binary_file_has_no_text_but_a_hash(tmp_path: Path) -> None: + blob = tmp_path / "blob.bin" + blob.write_bytes(b"\xff\xfe\x00" * 10) + big = tmp_path / "big.txt" + big.write_bytes(b"a" * ((1 << 20) + 5)) + v = LocalStateVerifier( + [FileSource(id="blob", path=str(blob)), FileSource(id="big", path=str(big))] + ) + blob_rec, big_rec = v.read() or [] + assert blob_rec["text"] is None and blob_rec["size"] == 30 + assert big_rec["text"] is None + assert big_rec["sha256"] == hashlib.sha256(b"a" * ((1 << 20) + 5)).hexdigest() + + +def test_reading_never_changes_the_file(tmp_path: Path) -> None: + note = tmp_path / "note.txt" + note.write_text("unchanged", encoding="utf-8") + before = note.stat() + LocalStateVerifier([FileSource(id="note", path=str(note))]).read() + assert note.read_text() == "unchanged" + assert note.stat().st_mtime_ns == before.st_mtime_ns + + +# -- macOS defaults ------------------------------------------------------------- + + +class _Defaults: + """Stands in for ``defaults export -``.""" + + def __init__(self, domains: dict[str, dict[str, Any]], rc: int = 0, raw: bytes = b"") -> None: + self.domains = domains + self.rc = rc + self.raw = raw + self.calls: list[list[str]] = [] + + def __call__(self, argv: list[str]) -> subprocess.CompletedProcess[bytes]: + self.calls.append(argv) + out = self.raw or plistlib.dumps(self.domains.get(argv[2], {})) + return subprocess.CompletedProcess(argv, self.rc, out, b"") + + +def _mac(runner: _Defaults, *sources: Any) -> LocalStateVerifier: + return LocalStateVerifier(list(sources), runner=runner, platform="darwin") + + +APPEARANCE = MacosDefaultsSource(id="appearance", domain="-g", key="AppleInterfaceStyle") + + +def test_defaults_value_and_absent_key() -> None: + dark = _Defaults({"NSGlobalDomain": {"AppleInterfaceStyle": "Dark"}}) + v = _mac(dark, APPEARANCE) + assert _judge(v, _field("appearance", "value", "Dark")) is Verdict.CONFIRMED + # The read is the fixed, read-only argv; -g is normalized. + assert dark.calls[0] == [DEFAULTS_BINARY, "export", "NSGlobalDomain", "-"] + + light = _mac(_Defaults({"NSGlobalDomain": {}}), APPEARANCE) + (record,) = light.read() or [] + assert record["present"] is False and record["value"] is None + assert _judge(light, _field("appearance", "present", "False")) is Verdict.CONFIRMED + assert _judge(light, _field("appearance", "value", "Dark")) is Verdict.REFUTED + + +def test_defaults_reads_each_domain_once_per_read() -> None: + runner = _Defaults({"NSGlobalDomain": {"A": 1, "B": True}}) + v = _mac( + runner, + MacosDefaultsSource(id="a", domain="NSGlobalDomain", key="A"), + MacosDefaultsSource(id="b", domain="NSGlobalDomain", key="B"), + ) + a, b = v.read() or [] + assert (a["value"], a["value_type"]) == ("1", "integer") + assert (b["value"], b["value_type"]) == ("true", "boolean") + assert len(runner.calls) == 1 + + +@pytest.mark.parametrize( + "runner", + [_Defaults({}, rc=1), _Defaults({}, raw=b"not a plist"), _Defaults({}, raw=plistlib.dumps([1]))], + ids=["nonzero-exit", "not-a-plist", "not-a-dict"], +) +def test_defaults_failure_is_unreadable_not_absent(runner: _Defaults) -> None: + v = _mac(runner, APPEARANCE) + assert v.read() is None + verdict = v.verify(_field("appearance", "present", "False"), v.capture_pre_state()) + assert verdict.verdict is Verdict.INDETERMINATE + + +def test_defaults_on_another_os_is_unreadable() -> None: + runner = _Defaults({"NSGlobalDomain": {"AppleInterfaceStyle": "Dark"}}) + v = LocalStateVerifier([APPEARANCE], runner=runner, platform="win32") + assert v.read() is None + assert runner.calls == [] + + +def test_defaults_runner_error_is_unreadable() -> None: + def boom(argv: list[str]) -> subprocess.CompletedProcess[bytes]: + raise subprocess.TimeoutExpired(argv, 10) + + v = LocalStateVerifier([APPEARANCE], runner=boom, platform="darwin") + assert v.read() is None + + +@pytest.mark.parametrize("domain", ["-currentHost", "--help", "a b", "", "x;rm"]) +def test_defaults_domain_can_never_be_a_flag_or_command(domain: str) -> None: + with pytest.raises(ValidationError): + MacosDefaultsSource(id="x", domain=domain, key="k") + + +# -- Windows registry ----------------------------------------------------------- + + +class _Key: + def __init__(self, values: dict[str, tuple[Any, int]]) -> None: + self.values = values + + def __enter__(self) -> "_Key": + return self + + def __exit__(self, *exc: object) -> None: + return None + + +class _Winreg: + """Stands in for :mod:`winreg`.""" + + HKEY_CURRENT_USER = "HKCU" + HKEY_LOCAL_MACHINE = "HKLM" + KEY_READ = 0x20019 + REG_SZ = 1 + REG_DWORD = 4 + + def __init__(self, keys: dict[tuple[str, str], dict[str, tuple[Any, int]]], error: type[OSError] | None = None) -> None: + self.keys = keys + self.error = error + self.opened: list[tuple[Any, str, int, int]] = [] + + def OpenKey(self, hive: str, path: str, reserved: int, access: int) -> _Key: # noqa: N802 + self.opened.append((hive, path, reserved, access)) + if self.error is not None: + raise self.error("denied") + if (hive, path) not in self.keys: + raise FileNotFoundError(path) + return _Key(self.keys[(hive, path)]) + + def QueryValueEx(self, key: _Key, name: str) -> tuple[Any, int]: # noqa: N802 + if name not in key.values: + raise FileNotFoundError(name) + return key.values[name] + + +PERSONALIZE = r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" +THEME = WindowsRegistrySource(id="apps_theme", hive="HKCU", path=PERSONALIZE, name="AppsUseLightTheme") + + +def test_registry_value_absent_and_read_only_access() -> None: + reg = _Winreg({("HKCU", PERSONALIZE): {"AppsUseLightTheme": (0, 4)}}) + v = LocalStateVerifier([THEME], registry=reg, platform="win32") + (record,) = v.read() or [] + assert (record["value"], record["value_type"]) == ("0", "REG_DWORD") + assert _judge(v, _field("apps_theme", "value", "0")) is Verdict.CONFIRMED + assert _judge(v, _field("apps_theme", "value", "1")) is Verdict.REFUTED + assert all(access == reg.KEY_READ for *_, access in reg.opened) + + missing_value = _Winreg({("HKCU", PERSONALIZE): {}}) + (rec,) = LocalStateVerifier([THEME], registry=missing_value).read() or [] + assert rec["present"] is False + missing_key = _Winreg({}) + (rec,) = LocalStateVerifier([THEME], registry=missing_key).read() or [] + assert rec["present"] is False + + +def test_registry_permission_error_is_unreadable() -> None: + v = LocalStateVerifier([THEME], registry=_Winreg({}, error=PermissionError)) + assert v.read() is None + + +def test_registry_on_another_os_is_unreadable() -> None: + assert LocalStateVerifier([THEME], platform="darwin").read() is None + + +def test_registry_path_is_relative_to_the_hive() -> None: + with pytest.raises(ValidationError): + WindowsRegistrySource(id="x", hive="HKCU", path=r"\Software", name="v") + with pytest.raises(ValidationError): + WindowsRegistrySource(id="x", hive="HKCR", path="Software", name="v") # type: ignore[arg-type] + + +# -- shared --------------------------------------------------------------------- + + +def test_one_unreadable_source_makes_the_whole_read_unreadable(tmp_path: Path) -> None: + note = tmp_path / "note.txt" + note.write_text("ok") + v = LocalStateVerifier( + [FileSource(id="note", path=str(note)), THEME], platform="darwin" + ) + assert v.read() is None + assert "apps_theme" in (v.last_error or "") + + +def test_value_text_forms() -> None: + assert value_text(None) is None + assert value_text(False) == "false" + assert value_text(7) == "7" + assert value_text(b"\x01\xab") == "01ab" + assert value_text({"b": 1, "a": [1, 2]}) == '{"a":[1,2],"b":1}' + + +def test_sources_need_distinct_ids_and_at_least_one(tmp_path: Path) -> None: + with pytest.raises(ValueError): + LocalStateVerifier([]) + with pytest.raises(ValueError, match="distinct"): + LocalStateVerifier( + [FileSource(id="a", path="x"), FileSource(id="a", path="y")] + ) + + +def test_tier_is_independent_system() -> None: + assert LocalStateVerifier.verification_tier is VerificationTier.INDEPENDENT_SYSTEM + assert LocalStateVerifier.independent_system_of_record is True + + +# -- config and verify-run ------------------------------------------------------ + + +def test_effects_config_builds_and_refuses_free_form_commands(tmp_path: Path) -> None: + cfg = EffectsConfig.model_validate( + { + "kind": "local-state", + "local_state": [ + {"type": "file", "id": "note", "path": str(tmp_path / "n.txt")}, + {"type": "macos_defaults", "id": "a", "domain": "-g", "key": "K"}, + {"type": "windows_registry", "id": "r", "hive": "HKCU", "path": "S", "name": "v"}, + ], + } + ) + verifier = build_effect_verifier(cfg) + assert isinstance(verifier, LocalStateVerifier) + assert [type(s).__name__ for s in verifier.sources] == [ + "FileSource", + "MacosDefaultsSource", + "WindowsRegistrySource", + ] + with pytest.raises(ValidationError): + EffectsConfig.model_validate( + {"kind": "local-state", "local_state": [{"type": "command", "id": "x", "argv": ["sh"]}]} + ) + with pytest.raises(ValidationError): + EffectsConfig.model_validate( + {"kind": "local-state", "local_state": [{"type": "file", "id": "x", "path": "p", "command": "sh"}]} + ) + with pytest.raises(ValueError, match="requires effects.local_state"): + build_effect_verifier(EffectsConfig(kind="local-state")) + + +def _verify_cfg(path: Path) -> VerifyConfig: + return VerifyConfig.model_validate( + { + "schema_version": "openadapt.verify/v1", + "minimum_effect_strength": "independent_system_of_record", + "verifier": { + "kind": "local-state", + "local_state": [{"type": "file", "id": "note", "path": str(path)}], + }, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "note"}, + "field": "text", + "value": {"param": "note"}, + "timeout_s": 0.2, + } + ], + } + ) + + +@pytest.mark.parametrize( + ("written", "verdict", "outcome"), + [("synthetic note 9022", "CONFIRMED", "verified"), ("stale text", "REFUTED", None)], +) +def test_verify_run_rules_on_a_saved_file( + tmp_path: Path, written: str, verdict: str, outcome: str | None +) -> None: + note = tmp_path / "doc" / "note.txt" + note.parent.mkdir() + note.write_text("", encoding="utf-8") + cfg = _verify_cfg(note) + params = {"note": "synthetic note 9022"} + baseline = tmp_path / "baseline.json" + capture_baseline(cfg, params, baseline) + note.write_text(written, encoding="utf-8") + result = verify_run( + cfg, + params=params, + run_record=RUN_RECORD, + authorization_ref="local-state-test", + baseline_path=baseline, + private_dir=tmp_path / "private", + ) + receipt = result["receipt"] + assert receipt["effect_verdict"] == verdict + if outcome: + assert receipt["outcome"] == outcome + assert receipt["verification_tier"] == "independent_readback" + else: + assert receipt["outcome"] != "verified" + + +def test_verify_run_halts_when_the_state_cannot_be_read(tmp_path: Path) -> None: + cfg = _verify_cfg(tmp_path / "gone" / "note.txt") + result = verify_run( + cfg, + params={"note": "x"}, + run_record=RUN_RECORD, + authorization_ref="local-state-test", + private_dir=tmp_path / "private", + ) + assert result["receipt"]["effect_verdict"] == "INDETERMINATE" + assert result["receipt"]["outcome"] != "verified" From 3717799104c3b30ca35b4fd443a7f435c66a3303 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:10:44 -0500 Subject: [PATCH 02/11] feat(flow): local-state examples, lab harness and docs --- CAPABILITIES.md | 1 + packages/flow/docs/EFFECT_KIT.md | 4 +- packages/flow/docs/LOCAL_STATE_CHECKS.md | 104 ++++++ .../local_state/macos-dark-mode/verify.yaml | 21 ++ .../local_state/notepad-save/verify.yaml | 20 + .../local_state/textedit-save/verify.yaml | 20 + .../local_state/windows-dark-mode/verify.yaml | 31 ++ .../scripts/desktop/qualify_local_state.py | 344 ++++++++++++++++++ .../flow/tests/test_local_state_verifier.py | 51 ++- 9 files changed, 594 insertions(+), 2 deletions(-) create mode 100644 packages/flow/docs/LOCAL_STATE_CHECKS.md create mode 100644 packages/flow/examples/local_state/macos-dark-mode/verify.yaml create mode 100644 packages/flow/examples/local_state/notepad-save/verify.yaml create mode 100644 packages/flow/examples/local_state/textedit-save/verify.yaml create mode 100644 packages/flow/examples/local_state/windows-dark-mode/verify.yaml create mode 100644 packages/flow/scripts/desktop/qualify_local_state.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 3214679ba6..77f5970460 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -156,6 +156,7 @@ improvising or retrying when something is off. | Qualify against a rule the app itself enforces: verify.yaml `business_rules` seed the conflicting record (an existing chart for the same person, checked in the read-back), and the certified bundle must stop at the rule's check before the save with nothing written on every trial, or certification is withdrawn | On main | Unit tests; the OpenEMR fixture's verify.yaml declares the existing-duplicate rule | [QUALIFY_A_WORKFLOW.md](packages/flow/docs/QUALIFY_A_WORKFLOW.md) | | Right-record check before any write (structure, then OCR, then pixels) | Released | Real app and synthetic | [RESOLUTION_LADDER.md](packages/flow/docs/RESOLUTION_LADDER.md), `runtime/identity.py` | | Read the saved record back from the system of record (API, database, FHIR, separate session) | Released | Real app (OpenEMR 12 of 12 fields) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md), `runtime/effects/` | +| Check a change that no app database holds: a saved file (contents and SHA-256), a macOS preference key (`defaults export`) or a Windows registry value (`winreg`, read-only), declared as typed sources in `verify.yaml` (`kind: local-state`); a missing key is a state, any other failed read halts | On main | Real app, lab: Windows 11 Notepad on the zenbook, recorded with the desktop recorder over the lab agent, compiled, replayed with a new note and checked inside the guest by `verify-run`: 3 of 3 trials `verified` (tier 1), each with a skipped-replay control `REFUTED` and an unreadable path `INDETERMINATE`; Notepad needs its status bar off for replay to confirm the typing. Windows dark mode: the check reads the registry, but Settings can't change the mode on the unactivated lab Windows, so no end-to-end run. TextEdit and macOS Dark Mode: not run (the macOS VM lacked disk). Night Shift and Notes can't be checked | [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `runtime/effects/local_state.py`, `examples/local_state/` | | Read values out of an app as a workflow step (READ), with a records format, a signed review queue and export to CSV or a database | Released ([#1229](https://github.com/OpenAdaptAI/OpenAdapt/pull/1229), [#1215](https://github.com/OpenAdaptAI/OpenAdapt/pull/1215), [#1218](https://github.com/OpenAdaptAI/OpenAdapt/pull/1218)–[#1224](https://github.com/OpenAdaptAI/OpenAdapt/pull/1224)) | Synthetic (mock desktop apps) | `openadapt_flow/interchange/` | | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | diff --git a/packages/flow/docs/EFFECT_KIT.md b/packages/flow/docs/EFFECT_KIT.md index 5725099c0f..f7ed2f99ac 100644 --- a/packages/flow/docs/EFFECT_KIT.md +++ b/packages/flow/docs/EFFECT_KIT.md @@ -151,6 +151,7 @@ environment-assigned surrogate key is the right choice for it. | `email` | `MaildirDeliveryVerifier` | maildir / SMTP-capture directory → one record per message (`to`, `subject`, `message_id`, body probe, freshness); verifies delivery TO THE CAPTURE POINT, not end-to-end receipt | **contract-proven in CI against maildir/tmp-dir fixtures** (wrong recipient, duplicate send, leak-to-other-recipient collateral hook) -- not live-proven against a production MTA | | `document` | `DocumentArrivalVerifier` | report arrival + **parseable-content assertion**: each candidate parses (JSON dotted paths or named-regex groups) into judgeable fields; a corrupt report REFUTEs a `parseable: True` contract | **contract-proven in CI against temp-dir fixtures** (corrupt report, wrong entity, duplicates, stale mtime) | | `document-hash` | `DocumentHashVerifier` | SHA-256 of each document in a store | live in CI (no external service) | +| `local-state` | `LocalStateVerifier` | typed, read-only sources on this computer: a file (contents, SHA-256), a macOS preference key, a Windows registry value; one record per source ([LOCAL_STATE_CHECKS.md](LOCAL_STATE_CHECKS.md)) | unit tests with stand-ins in CI; lab-proven on Windows 11 (Notepad file save, registry read) | All substrates share one judge (`runtime/effects/_common.py`), so at-most-once counting, idempotency-key de-duplication, field read-back, @@ -1233,6 +1234,7 @@ Per-kind required fields: | `email` | `root` | `mail_pattern`, `file_mtime_window_s` (freshness), `file_content_probe` (body regex) | | `document` | `root` | `file_pattern`, `document_format` (`json` \| `text`), `document_field_paths`, `document_text_pattern`, `file_mtime_window_s` | | `document-hash` | `root` | `glob` | +| `local-state` | `local_state`: a list of `file`, `macos_defaults` or `windows_registry` sources | `poll_interval_s` | | `surfaces` | `surfaces`: name -> one plain verifier config (any kind above) | each effect's `probe` names its surface (`surface=`); an effect naming none, or an unknown one, halts | A paged list is read whole or not at all. `fhir` follows the Bundle's `next` @@ -1473,7 +1475,7 @@ profiles gate on the tier, never on prose: | Tier | Label | What it proves | Adapters | |---|---|---|---| -| 1 | `independent-system` | a read through the SoR's own API/DB/store -- independent proof | `rest`, `graphql`, `fhir`, `sql`, `file`, `email`, `document`, `document-hash` | +| 1 | `independent-system` | a read through the SoR's own API/DB/store -- independent proof | `rest`, `graphql`, `fhir`, `sql`, `file`, `email`, `document`, `document-hash`, `local-state` | | 2 | `independent-session` | same app, read through its record page in a separate, separately signed-in, read-only session. **Not a system-of-record read** | `ui_readback`; `desktop_readback` with its own sign-in; a plugin may also declare it | | 3 | `reacquired-state` | the app's own UI re-navigated to re-fetch persisted state | `onscreen` with a different-path read-back; `desktop_readback` without its own sign-in | | 4 | `screen-consistency` | the same surface the write drove still shows the value | `onscreen` same-surface | diff --git a/packages/flow/docs/LOCAL_STATE_CHECKS.md b/packages/flow/docs/LOCAL_STATE_CHECKS.md new file mode 100644 index 0000000000..985d9f6739 --- /dev/null +++ b/packages/flow/docs/LOCAL_STATE_CHECKS.md @@ -0,0 +1,104 @@ +# Check a change on this computer: files and OS settings + +Most OpenAdapt checks read a saved record back from an application's +database or API. Some tasks change state that no application database holds: +a document saved to disk, or a setting such as Dark Mode. For those, the +`local-state` record check reads the state back through the operating +system's own read-only interfaces, so a run can still end "done and checked". + +It is one check for every such task. An example declares which state it +changes and what that state must be after the run; the check reads it and +rules. It never runs a command you supply, and it never writes. + +## What it can read + +| Source `type` | What it reads | How | Record fields | +| --- | --- | --- | --- | +| `file` | A file's contents | Ordinary read-only file I/O | `present`, `size`, `sha256`, `text` (UTF-8, files up to 1 MiB) | +| `macos_defaults` | One key in a preferences domain | `/usr/bin/defaults export -` (goes through `cfprefsd`, so it sees the current value) | `present`, `value`, `value_type` | +| `windows_registry` | One registry value under `HKCU` or `HKLM` | `winreg` with `KEY_READ` access only | `present`, `value`, `value_type` | + +Each source becomes one record with the source's `id`, judged by the same +effect kinds every other record check uses (`field_equals`, `record_written`). +A value is compared as text: numbers in decimal, booleans as `true`/`false`. + +A missing file, key or value is a real state (`present: False`). Light Mode +on macOS, for example, is the absence of `AppleInterfaceStyle`. Any other +failed read (the wrong operating system, permission denied, `defaults` +failing, a missing folder) makes the read unreadable: the verdict is +`INDETERMINATE` and the run stops. The check never guesses a value. + +The check is tier 1 (`independent-system`): it reads the store the state +lives in, through a separate process or API, not the screen that showed the +change. + +## Use it + +```yaml +# verify.yaml +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: file + id: note + path: ~/openadapt-examples/note.txt +# Saving rewrites the file, so its hash and size change with its text. +frame: + target_fields: [present, text, sha256, size] +effects: + - kind: field_equals + match: {id: note} + field: text + value: {param: note} +``` + +`verify-run` also checks that nothing else in the read changed (the +frame). Without `frame.target_fields`, only the fields the effects name may +change, so a save would show `sha256` and `size` as unexpected changes and +the receipt would say `reconciliation_required`. List every field the change +is allowed to move; a change to any other source still fails the check. + +```bash +openadapt-flow verify-run --verify verify.yaml --params task.json --capture-baseline before.json +openadapt-flow replay bundle/ --param note="synthetic note 9022" +openadapt-flow verify-run --verify verify.yaml --params task.json \ + --run-record run.json --authorization-ref local --baseline before.json --out receipt/ +``` + +The same `verifier:` keys work as the `effects:` section of a deployment +YAML, so a `run` can check each step as it goes. + +Run the check on the computer whose state changed. It reads only that +computer. + +## Examples + +The examples live in [`examples/local_state/`](../examples/local_state/). + +| Example | State | Status | +| --- | --- | --- | +| `notepad-save` | `~/openadapt-examples/note.txt`, text equals the note | See CAPABILITIES.md for the lab evidence | +| `textedit-save` | The same file, saved from TextEdit as plain text | See CAPABILITIES.md | +| `windows-dark-mode` | `HKCU\...\Themes\Personalize` `AppsUseLightTheme` and `SystemUsesLightTheme` are `0` | Check only; see below | +| `macos-dark-mode` | `NSGlobalDomain` `AppleInterfaceStyle` is `Dark` | Check only; see below | + +## What it can't check, and why + +- **Night Shift (macOS).** Its state lives in CoreBrightness, a private + framework. There is no public API and no preference key that reliably + shows whether Night Shift is on now (the stored schedule is in a root-only + file and is not the current state). OpenAdapt can't check it, so there is + no Night Shift example. +- **Notes (macOS).** The supported ways to read a note are AppleScript and + Shortcuts. Both are scripts, not a typed read, and both need an Automation + consent prompt per app. The Notes database is private and protected by + Full Disk Access. There is no Notes source. +- **Calendar (macOS).** EventKit is a supported, public read API. It needs a + Calendar permission prompt and a PyObjC dependency that OpenAdapt doesn't + ship today. It is a candidate source, not built. +- **Windows dark mode on an unactivated Windows.** Windows locks the + Personalization pages until it is activated, so the setting can't be + demonstrated through Settings there. The check itself reads the registry + on any Windows. diff --git a/packages/flow/examples/local_state/macos-dark-mode/verify.yaml b/packages/flow/examples/local_state/macos-dark-mode/verify.yaml new file mode 100644 index 0000000000..548d532457 --- /dev/null +++ b/packages/flow/examples/local_state/macos-dark-mode/verify.yaml @@ -0,0 +1,21 @@ +# Dark Mode (macOS): System Settings > Appearance > Dark. +# The check reads the appearance preference through the preferences system +# (`defaults export NSGlobalDomain -`): Dark Mode stores +# AppleInterfaceStyle = Dark; Light Mode removes the key. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: macos_defaults + id: appearance + domain: NSGlobalDomain + key: AppleInterfaceStyle +frame: + target_fields: [present, value, value_type] +effects: + - kind: field_equals + match: {id: appearance} + field: value + value: Dark + timeout_s: 5 diff --git a/packages/flow/examples/local_state/notepad-save/verify.yaml b/packages/flow/examples/local_state/notepad-save/verify.yaml new file mode 100644 index 0000000000..4f65c337e4 --- /dev/null +++ b/packages/flow/examples/local_state/notepad-save/verify.yaml @@ -0,0 +1,20 @@ +# Notepad (Windows): type a note into a text file and save it. +# The check reads the saved file back from disk: its text must be exactly +# the note this run was asked to type. Synthetic text only. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: file + id: note + path: ~/openadapt-examples/note.txt +# Saving rewrites the file, so its hash and size change with its text. +frame: + target_fields: [present, text, sha256, size] +effects: + - kind: field_equals + match: {id: note} + field: text + value: {param: note} + timeout_s: 5 diff --git a/packages/flow/examples/local_state/textedit-save/verify.yaml b/packages/flow/examples/local_state/textedit-save/verify.yaml new file mode 100644 index 0000000000..702467b50d --- /dev/null +++ b/packages/flow/examples/local_state/textedit-save/verify.yaml @@ -0,0 +1,20 @@ +# TextEdit (macOS, plain text): type a note into a text file and save it. +# The check reads the saved file back from disk: its text must be exactly +# the note this run was asked to type. Synthetic text only. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: file + id: note + path: ~/openadapt-examples/note.txt +# Saving rewrites the file, so its hash and size change with its text. +frame: + target_fields: [present, text, sha256, size] +effects: + - kind: field_equals + match: {id: note} + field: text + value: {param: note} + timeout_s: 5 diff --git a/packages/flow/examples/local_state/windows-dark-mode/verify.yaml b/packages/flow/examples/local_state/windows-dark-mode/verify.yaml new file mode 100644 index 0000000000..6b00feef5e --- /dev/null +++ b/packages/flow/examples/local_state/windows-dark-mode/verify.yaml @@ -0,0 +1,31 @@ +# Dark mode (Windows): Settings > Personalization > Colors > Dark. +# The check reads the two per-user theme values from the registry with +# read-only access: 0 is dark, 1 is light. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: windows_registry + id: apps_theme + hive: HKCU + path: Software\Microsoft\Windows\CurrentVersion\Themes\Personalize + name: AppsUseLightTheme + - type: windows_registry + id: system_theme + hive: HKCU + path: Software\Microsoft\Windows\CurrentVersion\Themes\Personalize + name: SystemUsesLightTheme +frame: + target_fields: [present, value, value_type] +effects: + - kind: field_equals + match: {id: apps_theme} + field: value + value: "0" + timeout_s: 5 + - kind: field_equals + match: {id: system_theme} + field: value + value: "0" + timeout_s: 5 diff --git a/packages/flow/scripts/desktop/qualify_local_state.py b/packages/flow/scripts/desktop/qualify_local_state.py new file mode 100644 index 0000000000..468f41facc --- /dev/null +++ b/packages/flow/scripts/desktop/qualify_local_state.py @@ -0,0 +1,344 @@ +"""Record, compile, replay and check a local-state example on a Windows lab host. + +Lab only (the zenbook or the UTM VM, under its lease). Synthetic text only. + +For one example under ``examples/local_state//``: + +1. reset the state the example changes, open the app, and record the + demonstration with the desktop recorder (``record_desktop_demo`` over the + lab's win_agent backend, so every click is armed with its UIA locator); +2. compile the recording; +3. reset again, take the checker's baseline, replay with a new parameter + value, and run ``openadapt-flow verify-run`` with the example's + ``verify.yaml`` **inside the guest**, where the state lives. The receipt + is the check; +4. a negative control: reset, skip the replay, and run the same check. It + must refute; +5. an unreadable case: the same check pointed at state it cannot read. It + must halt (``INDETERMINATE``), never pass. + +The guest needs the checker installed at ``C:\\oa\\lsc`` (``venv`` with +``pydantic pyyaml cryptography httpx idna``, and the worktree's +``packages/flow`` and ``packages/types`` under ``src``); this script prints +what is missing. + +Usage, from packages/flow:: + + OAFLOW_LAB_PROFILE=winlap python scripts/desktop/qualify_local_state.py \\ + notepad-save --out ~/oa/scratch/local-state-check/runs/notepad-1 +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time +import traceback +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Callable + +HERE = Path(__file__).resolve().parent +FLOW = HERE.parents[1] +sys.path.insert(0, str(HERE)) + +import winrm_lab # noqa: E402 + +LSC = r"C:\oa\lsc" +GUEST_PY = rf"{LSC}\venv\Scripts\python.exe" +GUEST_PATH = rf"{LSC}\src\packages\flow;{LSC}\src\packages\types" +#: Where the examples' files live in the guest (``~`` in their verify.yaml). +EXAMPLE_DIR = r"$env:USERPROFILE\openadapt-examples" + + +# -- the examples' lab steps (fixtures, not engine code) ----------------------- + + +class Example: + """What the lab does around one example: reset, open, demonstrate.""" + + name: str + params_recorded: dict[str, str] + params_replayed: dict[str, str] + + def reset(self, lab: winrm_lab.WinRMLab) -> None: + raise NotImplementedError + + def demonstrate(self, rec: Any, viewport: tuple[int, int]) -> None: + raise NotImplementedError + + def unreadable_verify(self, verify: dict[str, Any]) -> dict[str, Any]: + raise NotImplementedError + + +class NotepadSave(Example): + name = "notepad-save" + params_recorded = {"note": "synthetic note 4711 recorded"} + params_replayed = {"note": "synthetic note 9022 replayed"} + + def reset(self, lab: winrm_lab.WinRMLab) -> None: + lab.stop_interactive("OAFlowLSC") + lab.run_ps( + "Stop-Process -Name notepad -Force -ErrorAction SilentlyContinue; " + # Close what would cover the app: a vendor screensaver blocks capture. + "Get-Process | Where-Object { $_.ProcessName -like '*Screensaver*' } | " + "Stop-Process -Force -ErrorAction SilentlyContinue; " + # Notepad restores unsaved tabs after it is closed; start clean + # (the lab backed the original tab state up to C:\\oa\\lsc first). + "Start-Sleep 1; Remove-Item -Recurse -Force " + "$env:LOCALAPPDATA\\Packages\\Microsoft.WindowsNotepad_8wekyb3d8bbwe\\LocalState\\TabState\\* " + "-ErrorAction SilentlyContinue; " + f"New-Item -ItemType Directory -Force {EXAMPLE_DIR} | Out-Null; " + f"Set-Content -NoNewline -Encoding ascii -Path {EXAMPLE_DIR}\\note.txt -Value ''", + check=False, + timeout_s=90.0, + ) + lab.launch_interactive( + rf'cmd.exe /c start "" /max notepad.exe "%USERPROFILE%\openadapt-examples\note.txt"', + name="OAFlowLSC", + ) + time.sleep(6) + + def demonstrate(self, rec: Any, viewport: tuple[int, int]) -> None: + # Notepad opens the file with the caret in the editor, so the person + # types straight away. A click in blank editor space has no control + # to anchor to (Notepad's editor exposes no UIA AutomationId there), + # and the visual resolver then anchors it to the nearest text, the + # Edit menu. + rec.type_text(self.params_recorded["note"], param="note") + rec.hotkey(["ctrl"], "s") + time.sleep(1.5) + + def unreadable_verify(self, verify: dict[str, Any]) -> dict[str, Any]: + doc = json.loads(json.dumps(verify)) + doc["verifier"]["local_state"][0]["path"] = "~/openadapt-examples-missing/note.txt" + return doc + + +EXAMPLES: dict[str, Callable[[], Example]] = {"notepad-save": NotepadSave} + + +# -- guest checker ------------------------------------------------------------- + + +def _guest_check( + lab: winrm_lab.WinRMLab, + out: Path, + tag: str, + verify: dict[str, Any], + params: dict[str, str], + *, + baseline: bool, + run_record: dict[str, Any], +) -> dict[str, Any]: + """Run verify-run in the guest; return the receipt and the exit code.""" + work = out / f"check-{tag}" + work.mkdir(parents=True, exist_ok=True) + g = rf"{LSC}\checks\{tag}" + lab.run_ps( + f"Remove-Item -Recurse -Force '{g}' -ErrorAction SilentlyContinue; " + f"New-Item -ItemType Directory -Force '{g}' | Out-Null" + ) + for name, body in ( + ("verify.json", verify), + ("params.json", params), + ("run-record.json", run_record), + ): + (work / name).write_text(json.dumps(body, indent=2)) + lab.push_file(work / name, rf"{g}\{name}") + env = f"$env:PYTHONPATH='{GUEST_PATH}'; $env:OPENADAPT_FLOW_PLAINTEXT_AT_REST='lab: synthetic text'; " + base = f"& '{GUEST_PY}' -m openadapt_flow verify-run --verify '{g}\\verify.json' --params '{g}\\params.json'" + return {"guest_dir": g, "env": env, "base": base, "work": work, "baseline": baseline} + + +def _capture_baseline(lab: winrm_lab.WinRMLab, ctx: dict[str, Any]) -> str: + done = lab.run_ps( + ctx["env"] + ctx["base"] + f" --capture-baseline '{ctx['guest_dir']}\\baseline.json'", + check=False, + ) + return (done.stdout or "") + (done.stderr or "") + + +def _verify(lab: winrm_lab.WinRMLab, ctx: dict[str, Any]) -> dict[str, Any]: + g = ctx["guest_dir"] + extra = f" --baseline '{g}\\baseline.json'" if ctx["baseline"] else "" + done = lab.run_ps( + ctx["env"] + + ctx["base"] + + extra + + f" --run-record '{g}\\run-record.json' --authorization-ref lab-{Path(g).name}" + + f" --out '{g}\\out'; \"EXIT=$LASTEXITCODE\"", + check=False, + ) + text = (done.stdout or "") + (done.stderr or "") + (ctx["work"] / "verify-run.log").write_text(text) + receipt_raw = lab.run_ps( + f"Get-Content -Raw '{g}\\out\\effect-receipt.json' -ErrorAction SilentlyContinue", + check=False, + ).stdout + receipt = None + if receipt_raw and "{" in receipt_raw: + body = receipt_raw[receipt_raw.index("{") : receipt_raw.rindex("}") + 1] + doc = json.loads(body) + (ctx["work"] / "effect-receipt.json").write_text(json.dumps(doc, indent=2)) + # write_result stores {"receipt": ..., "evidence": ...}. + receipt = doc.get("receipt", doc) + receipt["readback_effects"] = doc.get("evidence", {}).get("readback", {}).get("effects") + receipt["frame_status"] = doc.get("evidence", {}).get("frame", {}).get("status") + exit_line = [ln for ln in text.splitlines() if ln.startswith("EXIT=")] + return { + "exit": exit_line[-1][5:] if exit_line else None, + "effect_verdict": receipt and receipt.get("effect_verdict"), + "outcome": receipt and receipt.get("outcome"), + "verification_tier": receipt and receipt.get("verification_tier"), + "checked_how": receipt and receipt.get("checked_how"), + "frame_status": receipt and receipt.get("frame_status"), + "effects": receipt and [ + {k: e.get(k) for k in ("kind", "verdict", "substrate", "flow_verification_tier")} + for e in receipt.get("readback_effects") or [] + ], + "log_tail": text.strip().splitlines()[-6:], + } + + +# -- the trial ----------------------------------------------------------------- + + +def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: + from openadapt_flow.adapters.desktop_recorder import ( + record_desktop_demo, + structural_armed_coverage, + ) + from openadapt_flow.compiler import compile_recording + from openadapt_flow.runtime import Replayer + + verify = _load_yaml(FLOW / "examples" / "local_state" / example.name / "verify.yaml") + lab = winrm_lab.WinRMLab() + prefix = lab.profile.prefix + row.update( + { + "example": example.name, + "host": lab.profile.name, + "started_at": datetime.now(timezone.utc).isoformat(), + "candidate_commit": subprocess.run( + ["git", "rev-parse", "HEAD"], capture_output=True, text=True, cwd=HERE + ).stdout.strip(), + } + ) + endpoint = lab.launch_agent(token=os.environ[prefix + "AGENT_TOKEN"], wait_s=240) + agent = endpoint.backend() + (Path.home() / "oa/scratch" / lab.profile.name / "agent_pin.txt").write_text( + endpoint.pin_fingerprint or "" + ) + viewport = agent.viewport + row["viewport"] = list(viewport) + + # 1. Record. + example.reset(lab) + rec_check = _guest_check( + lab, out, "record", verify, example.params_recorded, baseline=True, + run_record={"executor_kind": "human", "executor_id": "lab-demonstration"}, + ) + row["record_baseline"] = _capture_baseline(lab, rec_check)[-300:] + t0 = time.monotonic() + recording = record_desktop_demo(agent, out / "recording", lambda r: example.demonstrate(r, viewport)) + row["record_s"] = round(time.monotonic() - t0, 1) + row["record_check"] = _verify(lab, rec_check) + + # 2. Compile. + t0 = time.monotonic() + workflow = compile_recording(recording, out / "bundle", name=example.name) + row["compile_s"] = round(time.monotonic() - t0, 1) + row["steps"] = [ + {"id": s.id, "action": getattr(s.action, "value", s.action), "param": s.param} + for s in workflow.steps + ] + row["params"] = sorted(workflow.params) + row["structural"] = structural_armed_coverage(workflow) + + # 3. Replay with a new value, then check. + example.reset(lab) + run_check = _guest_check( + lab, out, "replay", verify, example.params_replayed, baseline=True, + run_record={"executor_kind": "flow_replay", "executor_id": f"lab-{example.name}"}, + ) + row["replay_baseline"] = _capture_baseline(lab, run_check)[-300:] + t0 = time.monotonic() + report = Replayer(agent, use_structural=True).run( + workflow, + params=dict(example.params_replayed), + bundle_dir=out / "bundle", + run_dir=out / "run", + ) + row["replay_s"] = round(time.monotonic() - t0, 1) + row["replay"] = { + "success": report.success, + "steps": [ + {"step": r.step_id, "status": getattr(r, "status", None), "reason": (getattr(r, "reason", "") or "")[:160]} + for r in report.results + ], + # What the replay itself says about checking, with no effect declared. + "verified": getattr(report, "verified", None), + "transaction_outcome": getattr(report, "transaction_outcome", None), + } + row["replay_check"] = _verify(lab, run_check) + + # 4. Negative control: reset, no replay, same check. + example.reset(lab) + neg = _guest_check( + lab, out, "no-replay", verify, example.params_replayed, baseline=True, + run_record={"executor_kind": "flow_replay", "executor_id": "lab-skipped"}, + ) + _capture_baseline(lab, neg) + row["negative_control"] = _verify(lab, neg) + + # 5. Unreadable: the same contract on state that cannot be read. + bad = _guest_check( + lab, out, "unreadable", example.unreadable_verify(verify), example.params_replayed, + baseline=False, + run_record={"executor_kind": "flow_replay", "executor_id": "lab-unreadable"}, + ) + row["unreadable"] = _verify(lab, bad) + lab.stop_interactive("OAFlowLSC") + lab.run_ps("Stop-Process -Name notepad -Force -ErrorAction SilentlyContinue", check=False) + + row["accepted"] = bool( + row["record_check"]["outcome"] == "verified" + and report.success + and row["replay_check"]["effect_verdict"] == "CONFIRMED" + and row["replay_check"]["outcome"] == "verified" + and row["negative_control"]["effect_verdict"] == "REFUTED" + and row["unreadable"]["effect_verdict"] == "INDETERMINATE" + ) + + +def _load_yaml(path: Path) -> dict[str, Any]: + import yaml + + return yaml.safe_load(path.read_text(encoding="utf-8")) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0], allow_abbrev=False) + parser.add_argument("example", choices=sorted(EXAMPLES)) + parser.add_argument("--out", type=Path, required=True) + args = parser.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + row: dict[str, Any] = {} + try: + run_trial(EXAMPLES[args.example](), args.out, row) + except Exception as exc: # noqa: BLE001 - recorded as a rejected trial + row["accepted"] = False + row["failure"] = f"{type(exc).__name__}: {str(exc)[:400]}" + (args.out / "traceback.txt").write_text(traceback.format_exc()) + row["completed_at"] = datetime.now(timezone.utc).isoformat() + (args.out / "evidence.json").write_text(json.dumps(row, indent=2, sort_keys=True, default=str) + "\n") + print(json.dumps(row, indent=2, sort_keys=True, default=str)) + return 0 if row.get("accepted") else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/flow/tests/test_local_state_verifier.py b/packages/flow/tests/test_local_state_verifier.py index f2b87a5c9e..8f6eaf65b8 100644 --- a/packages/flow/tests/test_local_state_verifier.py +++ b/packages/flow/tests/test_local_state_verifier.py @@ -336,9 +336,15 @@ def test_effects_config_builds_and_refuses_free_form_commands(tmp_path: Path) -> build_effect_verifier(EffectsConfig(kind="local-state")) -def _verify_cfg(path: Path) -> VerifyConfig: +def _verify_cfg(path: Path, *, frame: bool = True) -> VerifyConfig: + extra: dict[str, Any] = ( + {"frame": {"target_fields": ["present", "text", "sha256", "size"]}} + if frame + else {} + ) return VerifyConfig.model_validate( { + **extra, "schema_version": "openadapt.verify/v1", "minimum_effect_strength": "independent_system_of_record", "verifier": { @@ -390,6 +396,31 @@ def test_verify_run_rules_on_a_saved_file( assert receipt["outcome"] != "verified" +def test_without_frame_target_fields_the_hash_change_is_collateral( + tmp_path: Path, +) -> None: + # The lab found this: a save moves sha256 and size with the text. Unless + # the example says those fields may change, the frame counts them as + # unexpected changes, so the receipt can't say verified. + note = tmp_path / "doc" / "note.txt" + note.parent.mkdir() + note.write_text("", encoding="utf-8") + cfg = _verify_cfg(note, frame=False) + params = {"note": "synthetic note 9022"} + baseline = tmp_path / "baseline.json" + capture_baseline(cfg, params, baseline) + note.write_text("synthetic note 9022", encoding="utf-8") + receipt = verify_run( + cfg, + params=params, + run_record=RUN_RECORD, + authorization_ref="local-state-test", + baseline_path=baseline, + private_dir=tmp_path / "private", + )["receipt"] + assert receipt["outcome"] != "verified" + + def test_verify_run_halts_when_the_state_cannot_be_read(tmp_path: Path) -> None: cfg = _verify_cfg(tmp_path / "gone" / "note.txt") result = verify_run( @@ -401,3 +432,21 @@ def test_verify_run_halts_when_the_state_cannot_be_read(tmp_path: Path) -> None: ) assert result["receipt"]["effect_verdict"] == "INDETERMINATE" assert result["receipt"]["outcome"] != "verified" + + +EXAMPLES = Path(__file__).resolve().parents[1] / "examples" / "local_state" + + +@pytest.mark.parametrize( + "name", sorted(p.name for p in EXAMPLES.iterdir() if (p / "verify.yaml").is_file()) +) +def test_every_example_contract_loads_and_builds(name: str) -> None: + import yaml + + doc = yaml.safe_load((EXAMPLES / name / "verify.yaml").read_text(encoding="utf-8")) + cfg = VerifyConfig.model_validate(doc) + verifier = build_effect_verifier(cfg.verifier) + assert isinstance(verifier, LocalStateVerifier) + # Every field an effect checks is one a save may move. + allowed = set(doc["frame"]["target_fields"]) + assert {e["field"] for e in doc["effects"]} <= allowed From 0c6df69b370c385f060bace8c5bc083507823995 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:18:27 -0500 Subject: [PATCH 03/11] test(lab): focus setup click before record and replay --- .../flow/scripts/desktop/qualify_local_state.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/packages/flow/scripts/desktop/qualify_local_state.py b/packages/flow/scripts/desktop/qualify_local_state.py index 468f41facc..44a52c49d9 100644 --- a/packages/flow/scripts/desktop/qualify_local_state.py +++ b/packages/flow/scripts/desktop/qualify_local_state.py @@ -67,6 +67,9 @@ class Example: def reset(self, lab: winrm_lab.WinRMLab) -> None: raise NotImplementedError + def bring_to_front(self, agent: Any, viewport: tuple[int, int]) -> None: + return None + def demonstrate(self, rec: Any, viewport: tuple[int, int]) -> None: raise NotImplementedError @@ -102,6 +105,17 @@ def reset(self, lab: winrm_lab.WinRMLab) -> None: ) time.sleep(6) + def bring_to_front(self, agent: Any, viewport: tuple[int, int]) -> None: + """Setup, not part of the demonstration: put Notepad in front. + + A window started from a scheduled task doesn't always get the + foreground, so typed keys could go nowhere. One click in the empty + editor puts the caret there, the state a person starts from. + """ + w, h = viewport + agent.click(w // 2, h // 2) + time.sleep(1.0) + def demonstrate(self, rec: Any, viewport: tuple[int, int]) -> None: # Notepad opens the file with the caret in the editor, so the person # types straight away. A click in blank editor space has no control @@ -243,6 +257,7 @@ def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: run_record={"executor_kind": "human", "executor_id": "lab-demonstration"}, ) row["record_baseline"] = _capture_baseline(lab, rec_check)[-300:] + example.bring_to_front(agent, viewport) t0 = time.monotonic() recording = record_desktop_demo(agent, out / "recording", lambda r: example.demonstrate(r, viewport)) row["record_s"] = round(time.monotonic() - t0, 1) @@ -266,6 +281,7 @@ def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: run_record={"executor_kind": "flow_replay", "executor_id": f"lab-{example.name}"}, ) row["replay_baseline"] = _capture_baseline(lab, run_check)[-300:] + example.bring_to_front(agent, viewport) t0 = time.monotonic() report = Replayer(agent, use_structural=True).run( workflow, From 9ad79babfaf5a42d1318b04a4fceb385d3cc2add Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:19:54 -0500 Subject: [PATCH 04/11] style: ruff format and import order --- packages/flow/openadapt_flow/deployment.py | 4 +- .../runtime/effects/__init__.py | 6 +- .../runtime/effects/local_state.py | 16 ++-- .../scripts/desktop/qualify_local_state.py | 88 +++++++++++++++---- .../flow/tests/test_local_state_verifier.py | 50 ++++++++--- 5 files changed, 123 insertions(+), 41 deletions(-) diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index c9b05ec432..d291c35cc4 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -546,8 +546,8 @@ class EffectsConfig(BaseModel): #: (contents and SHA-256), ``macos_defaults`` (a preference key) and #: ``windows_registry`` (a registry value). There is no free-form command; #: see :mod:`openadapt_flow.runtime.effects.local_state`. - local_state: list[Annotated[LocalStateSource, Field(discriminator="type")]] = ( - Field(default_factory=list) + local_state: list[Annotated[LocalStateSource, Field(discriminator="type")]] = Field( + default_factory=list ) # -- plugin record-check packs (registered kinds only) -------------------- diff --git a/packages/flow/openadapt_flow/runtime/effects/__init__.py b/packages/flow/openadapt_flow/runtime/effects/__init__.py index f6d09c5037..2d3cf74da8 100644 --- a/packages/flow/openadapt_flow/runtime/effects/__init__.py +++ b/packages/flow/openadapt_flow/runtime/effects/__init__.py @@ -123,13 +123,13 @@ ArrivalTransport, FileArrivalVerifier, ) -from openadapt_flow.runtime.effects.local_state import ( # noqa: F401 - LocalStateVerifier, -) from openadapt_flow.runtime.effects.graphql import ( # noqa: F401 GraphQLRecordVerifier, assert_read_only_graphql, ) +from openadapt_flow.runtime.effects.local_state import ( # noqa: F401 + LocalStateVerifier, +) from openadapt_flow.runtime.effects.rest import ( # noqa: F401 RestRecordVerifier, ) diff --git a/packages/flow/openadapt_flow/runtime/effects/local_state.py b/packages/flow/openadapt_flow/runtime/effects/local_state.py index 5770b44e32..dcc7c72e34 100644 --- a/packages/flow/openadapt_flow/runtime/effects/local_state.py +++ b/packages/flow/openadapt_flow/runtime/effects/local_state.py @@ -190,7 +190,9 @@ def value_text(value: Any) -> Optional[str]: try: return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str) except (TypeError, ValueError) as exc: - raise _Unreadable(f"value of type {type(value).__name__} has no text form") from exc + raise _Unreadable( + f"value of type {type(value).__name__} has no text form" + ) from exc def _plist_type(value: Any) -> str: @@ -300,13 +302,13 @@ def _read_defaults( except (OSError, subprocess.SubprocessError) as exc: raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc if done.returncode != 0: - raise _Unreadable( - f"{source.id}: defaults exited {done.returncode}" - ) + raise _Unreadable(f"{source.id}: defaults exited {done.returncode}") try: parsed = plistlib.loads(done.stdout) except Exception as exc: # noqa: BLE001 - any parse failure is unreadable - raise _Unreadable(f"{source.id}: defaults output is not a plist") from exc + raise _Unreadable( + f"{source.id}: defaults output is not a plist" + ) from exc if not isinstance(parsed, dict): raise _Unreadable(f"{source.id}: defaults output is not a dictionary") domain = parsed @@ -337,7 +339,9 @@ def _read_registry(self, source: WindowsRegistrySource) -> dict[str, Any]: reg = self._winreg() except _Unreadable as exc: raise _Unreadable(f"{source.id}: {exc}") from exc - hive = getattr(reg, "HKEY_CURRENT_USER" if source.hive == "HKCU" else "HKEY_LOCAL_MACHINE") + hive = getattr( + reg, "HKEY_CURRENT_USER" if source.hive == "HKCU" else "HKEY_LOCAL_MACHINE" + ) record: dict[str, Any] = {"id": source.id, "type": source.type} try: with reg.OpenKey(hive, source.path, 0, reg.KEY_READ) as key: diff --git a/packages/flow/scripts/desktop/qualify_local_state.py b/packages/flow/scripts/desktop/qualify_local_state.py index 44a52c49d9..3e28b12fb0 100644 --- a/packages/flow/scripts/desktop/qualify_local_state.py +++ b/packages/flow/scripts/desktop/qualify_local_state.py @@ -100,7 +100,7 @@ def reset(self, lab: winrm_lab.WinRMLab) -> None: timeout_s=90.0, ) lab.launch_interactive( - rf'cmd.exe /c start "" /max notepad.exe "%USERPROFILE%\openadapt-examples\note.txt"', + r'cmd.exe /c start "" /max notepad.exe "%USERPROFILE%\openadapt-examples\note.txt"', name="OAFlowLSC", ) time.sleep(6) @@ -128,7 +128,9 @@ def demonstrate(self, rec: Any, viewport: tuple[int, int]) -> None: def unreadable_verify(self, verify: dict[str, Any]) -> dict[str, Any]: doc = json.loads(json.dumps(verify)) - doc["verifier"]["local_state"][0]["path"] = "~/openadapt-examples-missing/note.txt" + doc["verifier"]["local_state"][0]["path"] = ( + "~/openadapt-examples-missing/note.txt" + ) return doc @@ -165,12 +167,20 @@ def _guest_check( lab.push_file(work / name, rf"{g}\{name}") env = f"$env:PYTHONPATH='{GUEST_PATH}'; $env:OPENADAPT_FLOW_PLAINTEXT_AT_REST='lab: synthetic text'; " base = f"& '{GUEST_PY}' -m openadapt_flow verify-run --verify '{g}\\verify.json' --params '{g}\\params.json'" - return {"guest_dir": g, "env": env, "base": base, "work": work, "baseline": baseline} + return { + "guest_dir": g, + "env": env, + "base": base, + "work": work, + "baseline": baseline, + } def _capture_baseline(lab: winrm_lab.WinRMLab, ctx: dict[str, Any]) -> str: done = lab.run_ps( - ctx["env"] + ctx["base"] + f" --capture-baseline '{ctx['guest_dir']}\\baseline.json'", + ctx["env"] + + ctx["base"] + + f" --capture-baseline '{ctx['guest_dir']}\\baseline.json'", check=False, ) return (done.stdout or "") + (done.stderr or "") @@ -200,7 +210,9 @@ def _verify(lab: winrm_lab.WinRMLab, ctx: dict[str, Any]) -> dict[str, Any]: (ctx["work"] / "effect-receipt.json").write_text(json.dumps(doc, indent=2)) # write_result stores {"receipt": ..., "evidence": ...}. receipt = doc.get("receipt", doc) - receipt["readback_effects"] = doc.get("evidence", {}).get("readback", {}).get("effects") + receipt["readback_effects"] = ( + doc.get("evidence", {}).get("readback", {}).get("effects") + ) receipt["frame_status"] = doc.get("evidence", {}).get("frame", {}).get("status") exit_line = [ln for ln in text.splitlines() if ln.startswith("EXIT=")] return { @@ -210,8 +222,12 @@ def _verify(lab: winrm_lab.WinRMLab, ctx: dict[str, Any]) -> dict[str, Any]: "verification_tier": receipt and receipt.get("verification_tier"), "checked_how": receipt and receipt.get("checked_how"), "frame_status": receipt and receipt.get("frame_status"), - "effects": receipt and [ - {k: e.get(k) for k in ("kind", "verdict", "substrate", "flow_verification_tier")} + "effects": receipt + and [ + { + k: e.get(k) + for k in ("kind", "verdict", "substrate", "flow_verification_tier") + } for e in receipt.get("readback_effects") or [] ], "log_tail": text.strip().splitlines()[-6:], @@ -229,7 +245,9 @@ def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: from openadapt_flow.compiler import compile_recording from openadapt_flow.runtime import Replayer - verify = _load_yaml(FLOW / "examples" / "local_state" / example.name / "verify.yaml") + verify = _load_yaml( + FLOW / "examples" / "local_state" / example.name / "verify.yaml" + ) lab = winrm_lab.WinRMLab() prefix = lab.profile.prefix row.update( @@ -253,13 +271,20 @@ def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: # 1. Record. example.reset(lab) rec_check = _guest_check( - lab, out, "record", verify, example.params_recorded, baseline=True, + lab, + out, + "record", + verify, + example.params_recorded, + baseline=True, run_record={"executor_kind": "human", "executor_id": "lab-demonstration"}, ) row["record_baseline"] = _capture_baseline(lab, rec_check)[-300:] example.bring_to_front(agent, viewport) t0 = time.monotonic() - recording = record_desktop_demo(agent, out / "recording", lambda r: example.demonstrate(r, viewport)) + recording = record_desktop_demo( + agent, out / "recording", lambda r: example.demonstrate(r, viewport) + ) row["record_s"] = round(time.monotonic() - t0, 1) row["record_check"] = _verify(lab, rec_check) @@ -277,8 +302,16 @@ def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: # 3. Replay with a new value, then check. example.reset(lab) run_check = _guest_check( - lab, out, "replay", verify, example.params_replayed, baseline=True, - run_record={"executor_kind": "flow_replay", "executor_id": f"lab-{example.name}"}, + lab, + out, + "replay", + verify, + example.params_replayed, + baseline=True, + run_record={ + "executor_kind": "flow_replay", + "executor_id": f"lab-{example.name}", + }, ) row["replay_baseline"] = _capture_baseline(lab, run_check)[-300:] example.bring_to_front(agent, viewport) @@ -293,7 +326,11 @@ def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: row["replay"] = { "success": report.success, "steps": [ - {"step": r.step_id, "status": getattr(r, "status", None), "reason": (getattr(r, "reason", "") or "")[:160]} + { + "step": r.step_id, + "status": getattr(r, "status", None), + "reason": (getattr(r, "reason", "") or "")[:160], + } for r in report.results ], # What the replay itself says about checking, with no effect declared. @@ -305,7 +342,12 @@ def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: # 4. Negative control: reset, no replay, same check. example.reset(lab) neg = _guest_check( - lab, out, "no-replay", verify, example.params_replayed, baseline=True, + lab, + out, + "no-replay", + verify, + example.params_replayed, + baseline=True, run_record={"executor_kind": "flow_replay", "executor_id": "lab-skipped"}, ) _capture_baseline(lab, neg) @@ -313,13 +355,19 @@ def run_trial(example: Example, out: Path, row: dict[str, Any]) -> None: # 5. Unreadable: the same contract on state that cannot be read. bad = _guest_check( - lab, out, "unreadable", example.unreadable_verify(verify), example.params_replayed, + lab, + out, + "unreadable", + example.unreadable_verify(verify), + example.params_replayed, baseline=False, run_record={"executor_kind": "flow_replay", "executor_id": "lab-unreadable"}, ) row["unreadable"] = _verify(lab, bad) lab.stop_interactive("OAFlowLSC") - lab.run_ps("Stop-Process -Name notepad -Force -ErrorAction SilentlyContinue", check=False) + lab.run_ps( + "Stop-Process -Name notepad -Force -ErrorAction SilentlyContinue", check=False + ) row["accepted"] = bool( row["record_check"]["outcome"] == "verified" @@ -338,7 +386,9 @@ def _load_yaml(path: Path) -> dict[str, Any]: def main() -> int: - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0], allow_abbrev=False) + parser = argparse.ArgumentParser( + description=__doc__.splitlines()[0], allow_abbrev=False + ) parser.add_argument("example", choices=sorted(EXAMPLES)) parser.add_argument("--out", type=Path, required=True) args = parser.parse_args() @@ -351,7 +401,9 @@ def main() -> int: row["failure"] = f"{type(exc).__name__}: {str(exc)[:400]}" (args.out / "traceback.txt").write_text(traceback.format_exc()) row["completed_at"] = datetime.now(timezone.utc).isoformat() - (args.out / "evidence.json").write_text(json.dumps(row, indent=2, sort_keys=True, default=str) + "\n") + (args.out / "evidence.json").write_text( + json.dumps(row, indent=2, sort_keys=True, default=str) + "\n" + ) print(json.dumps(row, indent=2, sort_keys=True, default=str)) return 0 if row.get("accepted") else 1 diff --git a/packages/flow/tests/test_local_state_verifier.py b/packages/flow/tests/test_local_state_verifier.py index 8f6eaf65b8..5b4fc5cd60 100644 --- a/packages/flow/tests/test_local_state_verifier.py +++ b/packages/flow/tests/test_local_state_verifier.py @@ -26,8 +26,8 @@ WindowsRegistrySource, value_text, ) -from openadapt_flow.verify_run import VerifyConfig, capture_baseline, verify_run from openadapt_flow.verification import VerificationTier +from openadapt_flow.verify_run import VerifyConfig, capture_baseline, verify_run RUN_RECORD = {"executor_kind": "flow_replay", "executor_id": "test-replay"} @@ -110,7 +110,9 @@ def test_reading_never_changes_the_file(tmp_path: Path) -> None: class _Defaults: """Stands in for ``defaults export -``.""" - def __init__(self, domains: dict[str, dict[str, Any]], rc: int = 0, raw: bytes = b"") -> None: + def __init__( + self, domains: dict[str, dict[str, Any]], rc: int = 0, raw: bytes = b"" + ) -> None: self.domains = domains self.rc = rc self.raw = raw @@ -126,7 +128,9 @@ def _mac(runner: _Defaults, *sources: Any) -> LocalStateVerifier: return LocalStateVerifier(list(sources), runner=runner, platform="darwin") -APPEARANCE = MacosDefaultsSource(id="appearance", domain="-g", key="AppleInterfaceStyle") +APPEARANCE = MacosDefaultsSource( + id="appearance", domain="-g", key="AppleInterfaceStyle" +) def test_defaults_value_and_absent_key() -> None: @@ -158,7 +162,11 @@ def test_defaults_reads_each_domain_once_per_read() -> None: @pytest.mark.parametrize( "runner", - [_Defaults({}, rc=1), _Defaults({}, raw=b"not a plist"), _Defaults({}, raw=plistlib.dumps([1]))], + [ + _Defaults({}, rc=1), + _Defaults({}, raw=b"not a plist"), + _Defaults({}, raw=plistlib.dumps([1])), + ], ids=["nonzero-exit", "not-a-plist", "not-a-dict"], ) def test_defaults_failure_is_unreadable_not_absent(runner: _Defaults) -> None: @@ -212,7 +220,11 @@ class _Winreg: REG_SZ = 1 REG_DWORD = 4 - def __init__(self, keys: dict[tuple[str, str], dict[str, tuple[Any, int]]], error: type[OSError] | None = None) -> None: + def __init__( + self, + keys: dict[tuple[str, str], dict[str, tuple[Any, int]]], + error: type[OSError] | None = None, + ) -> None: self.keys = keys self.error = error self.opened: list[tuple[Any, str, int, int]] = [] @@ -232,7 +244,9 @@ def QueryValueEx(self, key: _Key, name: str) -> tuple[Any, int]: # noqa: N802 PERSONALIZE = r"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize" -THEME = WindowsRegistrySource(id="apps_theme", hive="HKCU", path=PERSONALIZE, name="AppsUseLightTheme") +THEME = WindowsRegistrySource( + id="apps_theme", hive="HKCU", path=PERSONALIZE, name="AppsUseLightTheme" +) def test_registry_value_absent_and_read_only_access() -> None: @@ -293,9 +307,7 @@ def test_sources_need_distinct_ids_and_at_least_one(tmp_path: Path) -> None: with pytest.raises(ValueError): LocalStateVerifier([]) with pytest.raises(ValueError, match="distinct"): - LocalStateVerifier( - [FileSource(id="a", path="x"), FileSource(id="a", path="y")] - ) + LocalStateVerifier([FileSource(id="a", path="x"), FileSource(id="a", path="y")]) def test_tier_is_independent_system() -> None: @@ -313,7 +325,13 @@ def test_effects_config_builds_and_refuses_free_form_commands(tmp_path: Path) -> "local_state": [ {"type": "file", "id": "note", "path": str(tmp_path / "n.txt")}, {"type": "macos_defaults", "id": "a", "domain": "-g", "key": "K"}, - {"type": "windows_registry", "id": "r", "hive": "HKCU", "path": "S", "name": "v"}, + { + "type": "windows_registry", + "id": "r", + "hive": "HKCU", + "path": "S", + "name": "v", + }, ], } ) @@ -326,11 +344,19 @@ def test_effects_config_builds_and_refuses_free_form_commands(tmp_path: Path) -> ] with pytest.raises(ValidationError): EffectsConfig.model_validate( - {"kind": "local-state", "local_state": [{"type": "command", "id": "x", "argv": ["sh"]}]} + { + "kind": "local-state", + "local_state": [{"type": "command", "id": "x", "argv": ["sh"]}], + } ) with pytest.raises(ValidationError): EffectsConfig.model_validate( - {"kind": "local-state", "local_state": [{"type": "file", "id": "x", "path": "p", "command": "sh"}]} + { + "kind": "local-state", + "local_state": [ + {"type": "file", "id": "x", "path": "p", "command": "sh"} + ], + } ) with pytest.raises(ValueError, match="requires effects.local_state"): build_effect_verifier(EffectsConfig(kind="local-state")) From f56df098d79a744869676b8fcc0a1b2cf5332519 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:45:12 -0500 Subject: [PATCH 05/11] docs: local-state lab results in CAPABILITIES, doc and harness --- CAPABILITIES.md | 2 +- llms-full.txt | 1 + packages/flow/docs/LOCAL_STATE_CHECKS.md | 8 ++++---- packages/flow/scripts/desktop/qualify_local_state.py | 8 ++++++-- 4 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 77f5970460..d415d5f09d 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -156,7 +156,7 @@ improvising or retrying when something is off. | Qualify against a rule the app itself enforces: verify.yaml `business_rules` seed the conflicting record (an existing chart for the same person, checked in the read-back), and the certified bundle must stop at the rule's check before the save with nothing written on every trial, or certification is withdrawn | On main | Unit tests; the OpenEMR fixture's verify.yaml declares the existing-duplicate rule | [QUALIFY_A_WORKFLOW.md](packages/flow/docs/QUALIFY_A_WORKFLOW.md) | | Right-record check before any write (structure, then OCR, then pixels) | Released | Real app and synthetic | [RESOLUTION_LADDER.md](packages/flow/docs/RESOLUTION_LADDER.md), `runtime/identity.py` | | Read the saved record back from the system of record (API, database, FHIR, separate session) | Released | Real app (OpenEMR 12 of 12 fields) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md), `runtime/effects/` | -| Check a change that no app database holds: a saved file (contents and SHA-256), a macOS preference key (`defaults export`) or a Windows registry value (`winreg`, read-only), declared as typed sources in `verify.yaml` (`kind: local-state`); a missing key is a state, any other failed read halts | On main | Real app, lab: Windows 11 Notepad on the zenbook, recorded with the desktop recorder over the lab agent, compiled, replayed with a new note and checked inside the guest by `verify-run`: 3 of 3 trials `verified` (tier 1), each with a skipped-replay control `REFUTED` and an unreadable path `INDETERMINATE`; Notepad needs its status bar off for replay to confirm the typing. Windows dark mode: the check reads the registry, but Settings can't change the mode on the unactivated lab Windows, so no end-to-end run. TextEdit and macOS Dark Mode: not run (the macOS VM lacked disk). Night Shift and Notes can't be checked | [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `runtime/effects/local_state.py`, `examples/local_state/` | +| Check a change that no app database holds: a saved file (contents and SHA-256), a macOS preference key (`defaults export`) or a Windows registry value (`winreg`, read-only), declared as typed sources in `verify.yaml` (`kind: local-state`); a missing key is a state, any other failed read halts | On main | Real app, lab: Windows 11 Notepad on the zenbook, recorded with the desktop recorder over the lab agent, compiled, replayed with a new note and checked inside the guest by `verify-run`: on the final harness 3 of 4 trials `verified` (tier 1), each with a skipped-replay control `REFUTED` and an unreadable path `INDETERMINATE`; the fourth stopped at a lab SSH timeout before replay. Notepad needs its status bar off for replay to confirm the typing. Windows dark mode, check only: real registry reads confirm dark and refute light, and a held-out value (`sShortDate`) and an absent value read correctly, but Settings can't change the mode on the unactivated lab Windows, so no end-to-end run. TextEdit and macOS Dark Mode: not run (the macOS VM lacked disk). Night Shift and Notes can't be checked | [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `runtime/effects/local_state.py`, `examples/local_state/` | | Read values out of an app as a workflow step (READ), with a records format, a signed review queue and export to CSV or a database | Released ([#1229](https://github.com/OpenAdaptAI/OpenAdapt/pull/1229), [#1215](https://github.com/OpenAdaptAI/OpenAdapt/pull/1215), [#1218](https://github.com/OpenAdaptAI/OpenAdapt/pull/1218)–[#1224](https://github.com/OpenAdaptAI/OpenAdapt/pull/1224)) | Synthetic (mock desktop apps) | `openadapt_flow/interchange/` | | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | diff --git a/llms-full.txt b/llms-full.txt index 336d9b6236..cb1c3902cf 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -590,6 +590,7 @@ improvising or retrying when something is off. | Qualify against a rule the app itself enforces: verify.yaml `business_rules` seed the conflicting record (an existing chart for the same person, checked in the read-back), and the certified bundle must stop at the rule's check before the save with nothing written on every trial, or certification is withdrawn | On main | Unit tests; the OpenEMR fixture's verify.yaml declares the existing-duplicate rule | [QUALIFY_A_WORKFLOW.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/QUALIFY_A_WORKFLOW.md) | | Right-record check before any write (structure, then OCR, then pixels) | Released | Real app and synthetic | [RESOLUTION_LADDER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RESOLUTION_LADDER.md), `runtime/identity.py` | | Read the saved record back from the system of record (API, database, FHIR, separate session) | Released | Real app (OpenEMR 12 of 12 fields) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md), `runtime/effects/` | +| Check a change that no app database holds: a saved file (contents and SHA-256), a macOS preference key (`defaults export`) or a Windows registry value (`winreg`, read-only), declared as typed sources in `verify.yaml` (`kind: local-state`); a missing key is a state, any other failed read halts | On main | Real app, lab: Windows 11 Notepad on the zenbook, recorded with the desktop recorder over the lab agent, compiled, replayed with a new note and checked inside the guest by `verify-run`: on the final harness 3 of 4 trials `verified` (tier 1), each with a skipped-replay control `REFUTED` and an unreadable path `INDETERMINATE`; the fourth stopped at a lab SSH timeout before replay. Notepad needs its status bar off for replay to confirm the typing. Windows dark mode, check only: real registry reads confirm dark and refute light, and a held-out value (`sShortDate`) and an absent value read correctly, but Settings can't change the mode on the unactivated lab Windows, so no end-to-end run. TextEdit and macOS Dark Mode: not run (the macOS VM lacked disk). Night Shift and Notes can't be checked | [LOCAL_STATE_CHECKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LOCAL_STATE_CHECKS.md), `runtime/effects/local_state.py`, `examples/local_state/` | | Read values out of an app as a workflow step (READ), with a records format, a signed review queue and export to CSV or a database | Released ([#1229](https://github.com/OpenAdaptAI/OpenAdapt/pull/1229), [#1215](https://github.com/OpenAdaptAI/OpenAdapt/pull/1215), [#1218](https://github.com/OpenAdaptAI/OpenAdapt/pull/1218)–[#1224](https://github.com/OpenAdaptAI/OpenAdapt/pull/1224)) | Synthetic (mock desktop apps) | `openadapt_flow/interchange/` | | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md) | diff --git a/packages/flow/docs/LOCAL_STATE_CHECKS.md b/packages/flow/docs/LOCAL_STATE_CHECKS.md index 985d9f6739..4415497f01 100644 --- a/packages/flow/docs/LOCAL_STATE_CHECKS.md +++ b/packages/flow/docs/LOCAL_STATE_CHECKS.md @@ -79,10 +79,10 @@ The examples live in [`examples/local_state/`](../examples/local_state/). | Example | State | Status | | --- | --- | --- | -| `notepad-save` | `~/openadapt-examples/note.txt`, text equals the note | See CAPABILITIES.md for the lab evidence | -| `textedit-save` | The same file, saved from TextEdit as plain text | See CAPABILITIES.md | -| `windows-dark-mode` | `HKCU\...\Themes\Personalize` `AppsUseLightTheme` and `SystemUsesLightTheme` are `0` | Check only; see below | -| `macos-dark-mode` | `NSGlobalDomain` `AppleInterfaceStyle` is `Dark` | Check only; see below | +| `notepad-save` | `~/openadapt-examples/note.txt`, text equals the note | End to end on Windows 11 (lab): record, compile, replay, check `verified`. Turn Notepad's status bar off (View > Status bar) so replay can confirm the typing | +| `textedit-save` | The same file, saved from TextEdit as plain text | Not run yet | +| `windows-dark-mode` | `HKCU\...\Themes\Personalize` `AppsUseLightTheme` and `SystemUsesLightTheme` are `0` | Check only (real registry reads); see below | +| `macos-dark-mode` | `NSGlobalDomain` `AppleInterfaceStyle` is `Dark` | Not run yet | ## What it can't check, and why diff --git a/packages/flow/scripts/desktop/qualify_local_state.py b/packages/flow/scripts/desktop/qualify_local_state.py index 3e28b12fb0..32e4146aa0 100644 --- a/packages/flow/scripts/desktop/qualify_local_state.py +++ b/packages/flow/scripts/desktop/qualify_local_state.py @@ -19,8 +19,12 @@ The guest needs the checker installed at ``C:\\oa\\lsc`` (``venv`` with ``pydantic pyyaml cryptography httpx idna``, and the worktree's -``packages/flow`` and ``packages/types`` under ``src``); this script prints -what is missing. +``packages/flow`` and ``packages/types`` under ``src``, on ``PYTHONPATH``). Install it before a run: the script +doesn't check. + +Notepad needs its status bar off (View > Status bar) on the lab host: its +editor exposes no readable UIA value, so replay confirms typing by OCR of +the whole screen, and the status bar's character count is other new text. Usage, from packages/flow:: From 3935cd4a191bdb4b61c3edde69e26d485c7b7d48 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:49:53 -0500 Subject: [PATCH 06/11] fix(flow): a missing registry key or empty preferences domain is unreadable; trim docs to what ran --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/docs/EFFECT_KIT.md | 2 +- packages/flow/docs/LOCAL_STATE_CHECKS.md | 40 +++++++++++++------ .../local_state/macos-dark-mode/verify.yaml | 21 ---------- .../local_state/textedit-save/verify.yaml | 20 ---------- .../runtime/effects/local_state.py | 29 +++++++++++--- .../scripts/desktop/qualify_local_state.py | 18 ++++++--- .../flow/tests/test_local_state_verifier.py | 17 ++++++-- 9 files changed, 80 insertions(+), 71 deletions(-) delete mode 100644 packages/flow/examples/local_state/macos-dark-mode/verify.yaml delete mode 100644 packages/flow/examples/local_state/textedit-save/verify.yaml diff --git a/CAPABILITIES.md b/CAPABILITIES.md index d415d5f09d..96f4c8e0f1 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -156,7 +156,7 @@ improvising or retrying when something is off. | Qualify against a rule the app itself enforces: verify.yaml `business_rules` seed the conflicting record (an existing chart for the same person, checked in the read-back), and the certified bundle must stop at the rule's check before the save with nothing written on every trial, or certification is withdrawn | On main | Unit tests; the OpenEMR fixture's verify.yaml declares the existing-duplicate rule | [QUALIFY_A_WORKFLOW.md](packages/flow/docs/QUALIFY_A_WORKFLOW.md) | | Right-record check before any write (structure, then OCR, then pixels) | Released | Real app and synthetic | [RESOLUTION_LADDER.md](packages/flow/docs/RESOLUTION_LADDER.md), `runtime/identity.py` | | Read the saved record back from the system of record (API, database, FHIR, separate session) | Released | Real app (OpenEMR 12 of 12 fields) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md), `runtime/effects/` | -| Check a change that no app database holds: a saved file (contents and SHA-256), a macOS preference key (`defaults export`) or a Windows registry value (`winreg`, read-only), declared as typed sources in `verify.yaml` (`kind: local-state`); a missing key is a state, any other failed read halts | On main | Real app, lab: Windows 11 Notepad on the zenbook, recorded with the desktop recorder over the lab agent, compiled, replayed with a new note and checked inside the guest by `verify-run`: on the final harness 3 of 4 trials `verified` (tier 1), each with a skipped-replay control `REFUTED` and an unreadable path `INDETERMINATE`; the fourth stopped at a lab SSH timeout before replay. Notepad needs its status bar off for replay to confirm the typing. Windows dark mode, check only: real registry reads confirm dark and refute light, and a held-out value (`sShortDate`) and an absent value read correctly, but Settings can't change the mode on the unactivated lab Windows, so no end-to-end run. TextEdit and macOS Dark Mode: not run (the macOS VM lacked disk). Night Shift and Notes can't be checked | [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `runtime/effects/local_state.py`, `examples/local_state/` | +| Check a change that no app database holds: a saved file (contents and SHA-256), a Windows registry value (`winreg`, read-only) or a macOS preference key (`defaults export`), declared as typed sources in `verify.yaml` (`kind: local-state`); a missing value is a state, a failed read halts | On main | Real app in the lab: Windows 11 Notepad, recorded, compiled, replayed with a new note and checked by `verify-run` in the guest, 3 of 4 final trials `verified` (the fourth hit a lab timeout before replay), each with a skipped-replay control refuted; Windows registry reads checked on the same machine. The macOS source is unit-tested only | [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `runtime/effects/local_state.py`, `examples/local_state/` | | Read values out of an app as a workflow step (READ), with a records format, a signed review queue and export to CSV or a database | Released ([#1229](https://github.com/OpenAdaptAI/OpenAdapt/pull/1229), [#1215](https://github.com/OpenAdaptAI/OpenAdapt/pull/1215), [#1218](https://github.com/OpenAdaptAI/OpenAdapt/pull/1218)–[#1224](https://github.com/OpenAdaptAI/OpenAdapt/pull/1224)) | Synthetic (mock desktop apps) | `openadapt_flow/interchange/` | | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](packages/flow/docs/VERIFICATION.md) | diff --git a/llms-full.txt b/llms-full.txt index cb1c3902cf..9a3cc9e2f4 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -590,7 +590,7 @@ improvising or retrying when something is off. | Qualify against a rule the app itself enforces: verify.yaml `business_rules` seed the conflicting record (an existing chart for the same person, checked in the read-back), and the certified bundle must stop at the rule's check before the save with nothing written on every trial, or certification is withdrawn | On main | Unit tests; the OpenEMR fixture's verify.yaml declares the existing-duplicate rule | [QUALIFY_A_WORKFLOW.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/QUALIFY_A_WORKFLOW.md) | | Right-record check before any write (structure, then OCR, then pixels) | Released | Real app and synthetic | [RESOLUTION_LADDER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RESOLUTION_LADDER.md), `runtime/identity.py` | | Read the saved record back from the system of record (API, database, FHIR, separate session) | Released | Real app (OpenEMR 12 of 12 fields) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md), `runtime/effects/` | -| Check a change that no app database holds: a saved file (contents and SHA-256), a macOS preference key (`defaults export`) or a Windows registry value (`winreg`, read-only), declared as typed sources in `verify.yaml` (`kind: local-state`); a missing key is a state, any other failed read halts | On main | Real app, lab: Windows 11 Notepad on the zenbook, recorded with the desktop recorder over the lab agent, compiled, replayed with a new note and checked inside the guest by `verify-run`: on the final harness 3 of 4 trials `verified` (tier 1), each with a skipped-replay control `REFUTED` and an unreadable path `INDETERMINATE`; the fourth stopped at a lab SSH timeout before replay. Notepad needs its status bar off for replay to confirm the typing. Windows dark mode, check only: real registry reads confirm dark and refute light, and a held-out value (`sShortDate`) and an absent value read correctly, but Settings can't change the mode on the unactivated lab Windows, so no end-to-end run. TextEdit and macOS Dark Mode: not run (the macOS VM lacked disk). Night Shift and Notes can't be checked | [LOCAL_STATE_CHECKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LOCAL_STATE_CHECKS.md), `runtime/effects/local_state.py`, `examples/local_state/` | +| Check a change that no app database holds: a saved file (contents and SHA-256), a Windows registry value (`winreg`, read-only) or a macOS preference key (`defaults export`), declared as typed sources in `verify.yaml` (`kind: local-state`); a missing value is a state, a failed read halts | On main | Real app in the lab: Windows 11 Notepad, recorded, compiled, replayed with a new note and checked by `verify-run` in the guest, 3 of 4 final trials `verified` (the fourth hit a lab timeout before replay), each with a skipped-replay control refuted; Windows registry reads checked on the same machine. The macOS source is unit-tested only | [LOCAL_STATE_CHECKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LOCAL_STATE_CHECKS.md), `runtime/effects/local_state.py`, `examples/local_state/` | | Read values out of an app as a workflow step (READ), with a records format, a signed review queue and export to CSV or a database | Released ([#1229](https://github.com/OpenAdaptAI/OpenAdapt/pull/1229), [#1215](https://github.com/OpenAdaptAI/OpenAdapt/pull/1215), [#1218](https://github.com/OpenAdaptAI/OpenAdapt/pull/1218)–[#1224](https://github.com/OpenAdaptAI/OpenAdapt/pull/1224)) | Synthetic (mock desktop apps) | `openadapt_flow/interchange/` | | Stop before the effect instead of improvising (`HALTED_BEFORE_EFFECT`) | Released | Real app and synthetic | `runtime/replayer.py` | | Never retry an uncertain save (`RECONCILIATION_REQUIRED`) | Released | Synthetic (fault server) | [VERIFICATION.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFICATION.md) | diff --git a/packages/flow/docs/EFFECT_KIT.md b/packages/flow/docs/EFFECT_KIT.md index f7ed2f99ac..f4c92da2c4 100644 --- a/packages/flow/docs/EFFECT_KIT.md +++ b/packages/flow/docs/EFFECT_KIT.md @@ -151,7 +151,7 @@ environment-assigned surrogate key is the right choice for it. | `email` | `MaildirDeliveryVerifier` | maildir / SMTP-capture directory → one record per message (`to`, `subject`, `message_id`, body probe, freshness); verifies delivery TO THE CAPTURE POINT, not end-to-end receipt | **contract-proven in CI against maildir/tmp-dir fixtures** (wrong recipient, duplicate send, leak-to-other-recipient collateral hook) -- not live-proven against a production MTA | | `document` | `DocumentArrivalVerifier` | report arrival + **parseable-content assertion**: each candidate parses (JSON dotted paths or named-regex groups) into judgeable fields; a corrupt report REFUTEs a `parseable: True` contract | **contract-proven in CI against temp-dir fixtures** (corrupt report, wrong entity, duplicates, stale mtime) | | `document-hash` | `DocumentHashVerifier` | SHA-256 of each document in a store | live in CI (no external service) | -| `local-state` | `LocalStateVerifier` | typed, read-only sources on this computer: a file (contents, SHA-256), a macOS preference key, a Windows registry value; one record per source ([LOCAL_STATE_CHECKS.md](LOCAL_STATE_CHECKS.md)) | unit tests with stand-ins in CI; lab-proven on Windows 11 (Notepad file save, registry read) | +| `local-state` | `LocalStateVerifier` | typed, read-only sources on this computer: a file (contents, SHA-256), a macOS preference key, a Windows registry value; one record per source ([LOCAL_STATE_CHECKS.md](LOCAL_STATE_CHECKS.md)) | unit tests with stand-ins in CI; lab-proven on Windows 11 (Notepad file save, registry reads); macOS source unit-tested only | All substrates share one judge (`runtime/effects/_common.py`), so at-most-once counting, idempotency-key de-duplication, field read-back, diff --git a/packages/flow/docs/LOCAL_STATE_CHECKS.md b/packages/flow/docs/LOCAL_STATE_CHECKS.md index 4415497f01..fc692a9f29 100644 --- a/packages/flow/docs/LOCAL_STATE_CHECKS.md +++ b/packages/flow/docs/LOCAL_STATE_CHECKS.md @@ -15,18 +15,27 @@ rules. It never runs a command you supply, and it never writes. | Source `type` | What it reads | How | Record fields | | --- | --- | --- | --- | | `file` | A file's contents | Ordinary read-only file I/O | `present`, `size`, `sha256`, `text` (UTF-8, files up to 1 MiB) | -| `macos_defaults` | One key in a preferences domain | `/usr/bin/defaults export -` (goes through `cfprefsd`, so it sees the current value) | `present`, `value`, `value_type` | +| `macos_defaults` | One key in a preferences domain | `/usr/bin/defaults export -` (goes through `cfprefsd`, so it sees the current value). Unit-tested only so far; not yet run on a real Mac | `present`, `value`, `value_type` | | `windows_registry` | One registry value under `HKCU` or `HKLM` | `winreg` with `KEY_READ` access only | `present`, `value`, `value_type` | Each source becomes one record with the source's `id`, judged by the same effect kinds every other record check uses (`field_equals`, `record_written`). A value is compared as text: numbers in decimal, booleans as `true`/`false`. -A missing file, key or value is a real state (`present: False`). Light Mode -on macOS, for example, is the absence of `AppleInterfaceStyle`. Any other -failed read (the wrong operating system, permission denied, `defaults` -failing, a missing folder) makes the read unreadable: the verdict is -`INDETERMINATE` and the run stops. The check never guesses a value. +A missing file, preference key or registry value is a real state +(`present: False`). Light Mode on macOS, for example, is the absence of +`AppleInterfaceStyle`. Absence counts only inside a container that exists: +the file's folder, a preferences domain with at least one key, a registry +key. A missing folder, an empty domain (`defaults export` prints an empty +dictionary for a domain that doesn't exist, so a typo would look like +"absent") or a missing registry key is unreadable, like any other failed +read (the wrong operating system, permission denied, `defaults` failing). +Then the verdict is `INDETERMINATE` and the run stops. The check never +guesses a value. + +The receipt records the verdict, the source's identity and digests. It +doesn't copy a file's text, but the baseline file `verify-run` writes before +the run holds the raw read (mode 0600), as it does for every record check. The check is tier 1 (`independent-system`): it reads the store the state lives in, through a separate process or API, not the screen that showed the @@ -60,15 +69,18 @@ change, so a save would show `sha256` and `size` as unexpected changes and the receipt would say `reconciliation_required`. List every field the change is allowed to move; a change to any other source still fails the check. +Check a run with `verify-run`: read the state before the run, run the +program, then read it again and rule. + ```bash openadapt-flow verify-run --verify verify.yaml --params task.json --capture-baseline before.json -openadapt-flow replay bundle/ --param note="synthetic note 9022" +# ... run the program with the task's values ... openadapt-flow verify-run --verify verify.yaml --params task.json \ --run-record run.json --authorization-ref local --baseline before.json --out receipt/ ``` -The same `verifier:` keys work as the `effects:` section of a deployment -YAML, so a `run` can check each step as it goes. +The lab runs drove the program with Flow's replayer through the Windows +agent and ran both `verify-run` steps on the Windows machine. Run the check on the computer whose state changed. It reads only that computer. @@ -79,10 +91,12 @@ The examples live in [`examples/local_state/`](../examples/local_state/). | Example | State | Status | | --- | --- | --- | -| `notepad-save` | `~/openadapt-examples/note.txt`, text equals the note | End to end on Windows 11 (lab): record, compile, replay, check `verified`. Turn Notepad's status bar off (View > Status bar) so replay can confirm the typing | -| `textedit-save` | The same file, saved from TextEdit as plain text | Not run yet | -| `windows-dark-mode` | `HKCU\...\Themes\Personalize` `AppsUseLightTheme` and `SystemUsesLightTheme` are `0` | Check only (real registry reads); see below | -| `macos-dark-mode` | `NSGlobalDomain` `AppleInterfaceStyle` is `Dark` | Not run yet | +| `notepad-save` | `~/openadapt-examples/note.txt`, text equals the note | End to end on Windows 11 in the lab: record, compile, replay, check `verified`. Turn Notepad's status bar off (View > Status bar) so replay can confirm the typing | +| `windows-dark-mode` | `HKCU\...\Themes\Personalize` `AppsUseLightTheme` and `SystemUsesLightTheme` are `0` | Check only, on the real registry; see below | + +TextEdit and macOS Dark Mode follow the same pattern (a `file` source; a +`macos_defaults` source on `NSGlobalDomain` `AppleInterfaceStyle`). They have +no example yet because they haven't been run on a Mac. ## What it can't check, and why diff --git a/packages/flow/examples/local_state/macos-dark-mode/verify.yaml b/packages/flow/examples/local_state/macos-dark-mode/verify.yaml deleted file mode 100644 index 548d532457..0000000000 --- a/packages/flow/examples/local_state/macos-dark-mode/verify.yaml +++ /dev/null @@ -1,21 +0,0 @@ -# Dark Mode (macOS): System Settings > Appearance > Dark. -# The check reads the appearance preference through the preferences system -# (`defaults export NSGlobalDomain -`): Dark Mode stores -# AppleInterfaceStyle = Dark; Light Mode removes the key. -schema_version: openadapt.verify/v1 -minimum_effect_strength: independent_system_of_record -verifier: - kind: local-state - local_state: - - type: macos_defaults - id: appearance - domain: NSGlobalDomain - key: AppleInterfaceStyle -frame: - target_fields: [present, value, value_type] -effects: - - kind: field_equals - match: {id: appearance} - field: value - value: Dark - timeout_s: 5 diff --git a/packages/flow/examples/local_state/textedit-save/verify.yaml b/packages/flow/examples/local_state/textedit-save/verify.yaml deleted file mode 100644 index 702467b50d..0000000000 --- a/packages/flow/examples/local_state/textedit-save/verify.yaml +++ /dev/null @@ -1,20 +0,0 @@ -# TextEdit (macOS, plain text): type a note into a text file and save it. -# The check reads the saved file back from disk: its text must be exactly -# the note this run was asked to type. Synthetic text only. -schema_version: openadapt.verify/v1 -minimum_effect_strength: independent_system_of_record -verifier: - kind: local-state - local_state: - - type: file - id: note - path: ~/openadapt-examples/note.txt -# Saving rewrites the file, so its hash and size change with its text. -frame: - target_fields: [present, text, sha256, size] -effects: - - kind: field_equals - match: {id: note} - field: text - value: {param: note} - timeout_s: 5 diff --git a/packages/flow/openadapt_flow/runtime/effects/local_state.py b/packages/flow/openadapt_flow/runtime/effects/local_state.py index dcc7c72e34..73ce14a65d 100644 --- a/packages/flow/openadapt_flow/runtime/effects/local_state.py +++ b/packages/flow/openadapt_flow/runtime/effects/local_state.py @@ -39,11 +39,14 @@ field: text value: {param: note} -A missing file, key or value is a real, readable state (``present: False``): -an expected state of "this setting is off" can be the key's absence. A read -that fails for any other reason (wrong operating system, permission denied, -``defaults`` exiting non-zero, output that does not parse) makes the whole -read unreadable, so the verdict is INDETERMINATE and the run halts. The +A missing file, preference key or registry value is a real, readable state +(``present: False``): an expected state of "this setting is off" can be the +key's absence. Absence counts only inside a container that exists: a file's +folder, a non-empty preferences domain (``defaults export`` prints an empty +dictionary for a domain that doesn't exist), a registry key. Otherwise, and +for any other failure (wrong operating system, permission denied, +``defaults`` exiting non-zero, output that does not parse), the whole read is +unreadable, so the verdict is INDETERMINATE and the run halts. The verifier never guesses a value it could not read. The tier is ``INDEPENDENT_SYSTEM``: the read goes to the store the state @@ -311,6 +314,11 @@ def _read_defaults( ) from exc if not isinstance(parsed, dict): raise _Unreadable(f"{source.id}: defaults output is not a dictionary") + if not parsed: + # `defaults export` prints an empty dictionary, exit 0, for a + # domain that doesn't exist, so a mistyped domain would + # confirm "absent". An empty domain is unreadable instead. + raise _Unreadable(f"{source.id}: preferences domain is empty") domain = parsed cache[source.domain] = domain record: dict[str, Any] = {"id": source.id, "type": source.type} @@ -344,7 +352,16 @@ def _read_registry(self, source: WindowsRegistrySource) -> dict[str, Any]: ) record: dict[str, Any] = {"id": source.id, "type": source.type} try: - with reg.OpenKey(hive, source.path, 0, reg.KEY_READ) as key: + key = reg.OpenKey(hive, source.path, 0, reg.KEY_READ) + except FileNotFoundError as exc: + # A missing key is a mistyped path as often as a real state, so + # it can't confirm "absent". Only a missing value under a key + # that exists is a readable absence. + raise _Unreadable(f"{source.id}: registry key does not exist") from exc + except OSError as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + try: + with key: value, kind = reg.QueryValueEx(key, source.name) except FileNotFoundError: record.update(present=False, value=None, value_type=None) diff --git a/packages/flow/scripts/desktop/qualify_local_state.py b/packages/flow/scripts/desktop/qualify_local_state.py index 32e4146aa0..daf6fa828c 100644 --- a/packages/flow/scripts/desktop/qualify_local_state.py +++ b/packages/flow/scripts/desktop/qualify_local_state.py @@ -56,6 +56,11 @@ GUEST_PATH = rf"{LSC}\src\packages\flow;{LSC}\src\packages\types" #: Where the examples' files live in the guest (``~`` in their verify.yaml). EXAMPLE_DIR = r"$env:USERPROFILE\openadapt-examples" +#: Notepad's restored-tab store (Windows 11 Notepad, Store package). +NOTEPAD_TABS = ( + r"$env:LOCALAPPDATA\Packages\Microsoft.WindowsNotepad_8wekyb3d8bbwe" + r"\LocalState\TabState" +) # -- the examples' lab steps (fixtures, not engine code) ----------------------- @@ -93,11 +98,14 @@ def reset(self, lab: winrm_lab.WinRMLab) -> None: # Close what would cover the app: a vendor screensaver blocks capture. "Get-Process | Where-Object { $_.ProcessName -like '*Screensaver*' } | " "Stop-Process -Force -ErrorAction SilentlyContinue; " - # Notepad restores unsaved tabs after it is closed; start clean - # (the lab backed the original tab state up to C:\\oa\\lsc first). - "Start-Sleep 1; Remove-Item -Recurse -Force " - "$env:LOCALAPPDATA\\Packages\\Microsoft.WindowsNotepad_8wekyb3d8bbwe\\LocalState\\TabState\\* " - "-ErrorAction SilentlyContinue; " + # Notepad restores unsaved tabs after it is closed; start clean. + # The first reset keeps a copy of the original tab state in + # C:\\oa\\lsc\\tabstate-backup, so the lab can put it back. + "Start-Sleep 1; " + f'$ts = "{NOTEPAD_TABS}"; ' + f"if ((Test-Path $ts) -and -not (Test-Path '{LSC}\\tabstate-backup')) " + f"{{ Copy-Item -Recurse $ts '{LSC}\\tabstate-backup' }}; " + 'Remove-Item -Recurse -Force "$ts\\*" -ErrorAction SilentlyContinue; ' f"New-Item -ItemType Directory -Force {EXAMPLE_DIR} | Out-Null; " f"Set-Content -NoNewline -Encoding ascii -Path {EXAMPLE_DIR}\\note.txt -Value ''", check=False, diff --git a/packages/flow/tests/test_local_state_verifier.py b/packages/flow/tests/test_local_state_verifier.py index 5b4fc5cd60..d3e1f6e911 100644 --- a/packages/flow/tests/test_local_state_verifier.py +++ b/packages/flow/tests/test_local_state_verifier.py @@ -140,7 +140,7 @@ def test_defaults_value_and_absent_key() -> None: # The read is the fixed, read-only argv; -g is normalized. assert dark.calls[0] == [DEFAULTS_BINARY, "export", "NSGlobalDomain", "-"] - light = _mac(_Defaults({"NSGlobalDomain": {}}), APPEARANCE) + light = _mac(_Defaults({"NSGlobalDomain": {"AppleLocale": "en_US"}}), APPEARANCE) (record,) = light.read() or [] assert record["present"] is False and record["value"] is None assert _judge(light, _field("appearance", "present", "False")) is Verdict.CONFIRMED @@ -176,6 +176,17 @@ def test_defaults_failure_is_unreadable_not_absent(runner: _Defaults) -> None: assert verdict.verdict is Verdict.INDETERMINATE +def test_an_empty_or_unknown_domain_is_unreadable() -> None: + # `defaults export` prints an empty dictionary, exit 0, for a domain that + # doesn't exist; a mistyped domain must not confirm "absent". + v = _mac( + _Defaults({}), + MacosDefaultsSource(id="x", domain="com.example.misspelled", key="k"), + ) + assert v.read() is None + assert "empty" in (v.last_error or "") + + def test_defaults_on_another_os_is_unreadable() -> None: runner = _Defaults({"NSGlobalDomain": {"AppleInterfaceStyle": "Dark"}}) v = LocalStateVerifier([APPEARANCE], runner=runner, platform="win32") @@ -261,9 +272,9 @@ def test_registry_value_absent_and_read_only_access() -> None: missing_value = _Winreg({("HKCU", PERSONALIZE): {}}) (rec,) = LocalStateVerifier([THEME], registry=missing_value).read() or [] assert rec["present"] is False + # A missing key could be a mistyped path, so it never confirms absence. missing_key = _Winreg({}) - (rec,) = LocalStateVerifier([THEME], registry=missing_key).read() or [] - assert rec["present"] is False + assert LocalStateVerifier([THEME], registry=missing_key).read() is None def test_registry_permission_error_is_unreadable() -> None: From f4db48fddd77acd54de985e412933f608d92b783 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 21:36:43 -0500 Subject: [PATCH 07/11] fix(local-state): refuse non-regular files; keep the import layers and budgets Review blocker (fail-open class: unbounded-read-as-evidence): a file source that is a FIFO, a device or a link to one could block the open or never reach EOF and hang the run. A file source is now read only when it is a regular file: it is checked before the open, opened with O_NONBLOCK, and fstat-checked after. Anything else is unreadable, as is a file over 256 MiB (also while it grows during the read). Tests cover a FIFO, a link to it, /dev/null and the size cap. CI: deployment imported up into runtime.effects.local_state, and the eager runtime.effects export loaded one more module for ir and receipt than their budgets allow. The typed source models move to openadapt_flow/local_state_sources.py (policy layer, and added to the protected-path manifest beside runtime/effects/**). The verifier is a lazy export of openadapt_flow.runtime, like Replayer. local_state reads sys.platform without binding the sys namespace, so the lazy export is no new import-layer debt site. No budget or debt row changed. The deployment schema snapshot is regenerated on Pydantic 2.13.4 for the new effects.local_state field (#2424). --- .github/agent-safety-manifest.json | 1 + packages/flow/import_layers.json | 1 + packages/flow/openadapt_flow/deployment.py | 4 +- .../openadapt_flow/local_state_sources.py | 96 +++++++ .../flow/openadapt_flow/runtime/__init__.py | 9 + .../runtime/effects/__init__.py | 9 +- .../runtime/effects/local_state.py | 112 ++------ .../openadapt_flow.deployment.json | 256 ++++++++++++++++++ .../flow/tests/test_finite_lazy_loaders.py | 5 + .../flow/tests/test_local_state_verifier.py | 27 ++ 10 files changed, 429 insertions(+), 91 deletions(-) create mode 100644 packages/flow/openadapt_flow/local_state_sources.py diff --git a/.github/agent-safety-manifest.json b/.github/agent-safety-manifest.json index e438c4d33a..5b1db71ba8 100644 --- a/.github/agent-safety-manifest.json +++ b/.github/agent-safety-manifest.json @@ -16,6 +16,7 @@ "packages/flow/openadapt_flow/ir.py", "packages/flow/openadapt_flow/runtime/replayer.py", "packages/flow/openadapt_flow/runtime/effects/**", + "packages/flow/openadapt_flow/local_state_sources.py", "packages/flow/tests/test_verify_run.py", "packages/flow/tests/test_verify_tools.py" ] diff --git a/packages/flow/import_layers.json b/packages/flow/import_layers.json index ea85e8a5d9..71f8fce6f0 100644 --- a/packages/flow/import_layers.json +++ b/packages/flow/import_layers.json @@ -66,6 +66,7 @@ "openadapt_flow.deployment", "openadapt_flow.form_tx.receipt", "openadapt_flow.key_rotation", + "openadapt_flow.local_state_sources", "openadapt_flow.offline_seal", "openadapt_flow.policy", "openadapt_flow.production_qualification", diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index 23602e2e39..8f93a38d48 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -39,6 +39,7 @@ model_validator, ) +from openadapt_flow.local_state_sources import LocalStateSource from openadapt_flow.lookup_capabilities import ( DeclaredSurface, declared_surface_problem, @@ -55,7 +56,6 @@ from openadapt_flow.runtime.effects.effect import Region, ValueExpr from openadapt_flow.runtime.effects.frame import FrameAttribution, FrameDatabase from openadapt_flow.runtime.effects.fresh_session import FreshSessionSpec -from openadapt_flow.runtime.effects.local_state import LocalStateSource from openadapt_flow.runtime.effects.smart_auth import SmartBackendConfig from openadapt_flow.runtime.effects.ui_readback import UiReadbackSpec @@ -2657,7 +2657,7 @@ def _build_effect_verifier_unredacted( "effects.kind 'local-state' requires effects.local_state " "(the files or settings to read)" ) - from openadapt_flow.runtime.effects import LocalStateVerifier + from openadapt_flow.runtime import LocalStateVerifier return LocalStateVerifier( list(cfg.local_state), poll_interval_s=cfg.poll_interval_s diff --git a/packages/flow/openadapt_flow/local_state_sources.py b/packages/flow/openadapt_flow/local_state_sources.py new file mode 100644 index 0000000000..b4a00595b0 --- /dev/null +++ b/packages/flow/openadapt_flow/local_state_sources.py @@ -0,0 +1,96 @@ +"""The typed, read-only sources a ``kind: local-state`` check reads. + +These are configuration models, kept below the runtime layer so that +:mod:`openadapt_flow.deployment` can validate ``effects.local_state`` without +importing the verifier. The verifier is +:mod:`openadapt_flow.runtime.effects.local_state`, which re-exports them. +""" + +from __future__ import annotations + +import re +from typing import Literal, Union + +from pydantic import BaseModel, ConfigDict, Field, field_validator + +__all__ = [ + "FileSource", + "LocalStateSource", + "MacosDefaultsSource", + "WindowsRegistrySource", +] + +#: A source id: what an effect's ``match: {id: ...}`` names. +_SOURCE_ID = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,63}") +#: A preferences domain: ``NSGlobalDomain`` or a reverse-DNS bundle id. A +#: leading ``-`` is refused, so a domain can never become a ``defaults`` flag. +_DEFAULTS_DOMAIN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,254}") + + +class _Source(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + id: str + + @field_validator("id") + @classmethod + def _check_id(cls, value: str) -> str: + if not _SOURCE_ID.fullmatch(value): + raise ValueError( + "local-state source id must start with a letter and use only " + "letters, digits, '_', '.' or '-' (at most 64 characters)" + ) + return value + + +class FileSource(_Source): + """A file on this computer: its contents and SHA-256.""" + + type: Literal["file"] = "file" + #: The file's path. ``~`` and environment variables are expanded. + path: str = Field(min_length=1) + + +class MacosDefaultsSource(_Source): + """One key in a macOS preferences domain.""" + + type: Literal["macos_defaults"] = "macos_defaults" + #: ``NSGlobalDomain`` (``-g`` is accepted and means the same) or a bundle id. + domain: str + key: str = Field(min_length=1, max_length=255) + + @field_validator("domain") + @classmethod + def _check_domain(cls, value: str) -> str: + if value == "-g": + return "NSGlobalDomain" + if not _DEFAULTS_DOMAIN.fullmatch(value): + raise ValueError( + "macos_defaults domain must be NSGlobalDomain or a bundle id " + "(letters, digits, '.', '_' or '-'; not starting with '-')" + ) + return value + + +class WindowsRegistrySource(_Source): + """One value in the Windows registry.""" + + type: Literal["windows_registry"] = "windows_registry" + hive: Literal["HKCU", "HKLM"] + #: The key path under the hive, with backslashes (no leading backslash). + path: str = Field(min_length=1, max_length=1024) + #: The value's name. An empty string is the key's default value. + name: str = Field(default="", max_length=16383) + + @field_validator("path") + @classmethod + def _check_path(cls, value: str) -> str: + if value.startswith("\\") or "\x00" in value: + raise ValueError( + "windows_registry path is relative to the hive and must not " + "start with a backslash" + ) + return value + + +LocalStateSource = Union[FileSource, MacosDefaultsSource, WindowsRegistrySource] diff --git a/packages/flow/openadapt_flow/runtime/__init__.py b/packages/flow/openadapt_flow/runtime/__init__.py index c5fd962555..ae83416ccc 100644 --- a/packages/flow/openadapt_flow/runtime/__init__.py +++ b/packages/flow/openadapt_flow/runtime/__init__.py @@ -35,6 +35,7 @@ "RUNG_ORDER": "openadapt_flow.runtime.resolver", "is_below_ocr": "openadapt_flow.runtime.resolver", "resolve": "openadapt_flow.runtime.resolver", + "LocalStateVerifier": "openadapt_flow.runtime.effects.local_state", } @@ -55,6 +56,7 @@ RUNG_ORDER: Any is_below_ocr: Any resolve: Any +LocalStateVerifier: Any def __getattr__(name: str) -> Any: @@ -73,6 +75,7 @@ def __getattr__(name: str) -> Any: global RUNG_ORDER global is_below_ocr global resolve + global LocalStateVerifier # Literal imports retain deferred loading even when an export shadows # its submodule (for example durable.resume). Named globals keep @@ -132,6 +135,11 @@ def __getattr__(name: str) -> Any: if name == "resolve": resolve = import_module("openadapt_flow.runtime.resolver").resolve return resolve + if name == "LocalStateVerifier": + LocalStateVerifier = import_module( + "openadapt_flow.runtime.effects.local_state" + ).LocalStateVerifier + return LocalStateVerifier raise AttributeError(f"module {__name__!r} has no attribute {name!r}") @@ -140,6 +148,7 @@ def __getattr__(name: str) -> Any: "FallbackGrounder", "Grounder", "GrounderMatch", + "LocalStateVerifier", "NullGrounder", "OCRAnchorGrounder", "Replayer", diff --git a/packages/flow/openadapt_flow/runtime/effects/__init__.py b/packages/flow/openadapt_flow/runtime/effects/__init__.py index 2d3cf74da8..0eca8e8d43 100644 --- a/packages/flow/openadapt_flow/runtime/effects/__init__.py +++ b/packages/flow/openadapt_flow/runtime/effects/__init__.py @@ -24,9 +24,8 @@ :class:`SqlRecordVerifier` (read-only SQL, enforced whitelist), :class:`FileArrivalVerifier` (file / SFTP arrival), :class:`MaildirDeliveryVerifier` (maildir / SMTP-capture email delivery), - :class:`DocumentArrivalVerifier` (report arrival + parseable content), - :class:`DocumentHashVerifier` (filesystem document store), and - :class:`LocalStateVerifier` (files and OS settings on this computer). + :class:`DocumentArrivalVerifier` (report arrival + parseable content), and + :class:`DocumentHashVerifier` (filesystem document store). - The adapter platform (:mod:`openadapt_flow.runtime.effects.adapter`): :class:`VerifierAdapter` / :class:`VerifierAdapterBase` (lifecycle: configure -> test-connection -> capture-before -> capture-after -> @@ -127,9 +126,6 @@ GraphQLRecordVerifier, assert_read_only_graphql, ) -from openadapt_flow.runtime.effects.local_state import ( # noqa: F401 - LocalStateVerifier, -) from openadapt_flow.runtime.effects.rest import ( # noqa: F401 RestRecordVerifier, ) @@ -211,7 +207,6 @@ "capture_table_counts", "FileArrivalVerifier", "ArrivalTransport", - "LocalStateVerifier", "SeparateSessionReadbackVerifier", "UiReadbackSpec", "DesktopReadbackSpec", diff --git a/packages/flow/openadapt_flow/runtime/effects/local_state.py b/packages/flow/openadapt_flow/runtime/effects/local_state.py index 73ce14a65d..da06f4beb4 100644 --- a/packages/flow/openadapt_flow/runtime/effects/local_state.py +++ b/packages/flow/openadapt_flow/runtime/effects/local_state.py @@ -62,14 +62,18 @@ import json import os import plistlib -import re +import stat import subprocess -import sys from pathlib import Path -from typing import Any, Callable, Literal, Optional, Union - -from pydantic import BaseModel, ConfigDict, Field, field_validator - +from sys import platform as _SYS_PLATFORM +from typing import Any, Callable, Optional + +from openadapt_flow.local_state_sources import ( # noqa: F401 - re-exported + FileSource, + LocalStateSource, + MacosDefaultsSource, + WindowsRegistrySource, +) from openadapt_flow.runtime.effects.adapter import ( VerifierAdapterBase, poll_until_settled, @@ -83,16 +87,13 @@ #: A file larger than this many bytes is hashed, but its ``text`` is ``None``. TEXT_LIMIT = 1 << 20 # 1 MiB +# A local store larger than this is not read: it is unreadable, not absent. +FILE_LIMIT = 256 * 1024 * 1024 #: The supported macOS preferences reader. An absolute path, so ``PATH`` #: cannot substitute another program. DEFAULTS_BINARY = "/usr/bin/defaults" -#: A source id: what an effect's ``match: {id: ...}`` names. -_SOURCE_ID = re.compile(r"[A-Za-z][A-Za-z0-9_.-]{0,63}") -#: A preferences domain: ``NSGlobalDomain`` or a reverse-DNS bundle id. A -#: leading ``-`` is refused, so a domain can never become a ``defaults`` flag. -_DEFAULTS_DOMAIN = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,254}") #: Registry hives a source may read. Per-user settings and machine settings; #: nothing else is needed for read-back. REGISTRY_HIVES = ("HKCU", "HKLM") @@ -100,75 +101,6 @@ Runner = Callable[[list[str]], "subprocess.CompletedProcess[bytes]"] -class _Source(BaseModel): - model_config = ConfigDict(extra="forbid", frozen=True) - - id: str - - @field_validator("id") - @classmethod - def _check_id(cls, value: str) -> str: - if not _SOURCE_ID.fullmatch(value): - raise ValueError( - "local-state source id must start with a letter and use only " - "letters, digits, '_', '.' or '-' (at most 64 characters)" - ) - return value - - -class FileSource(_Source): - """A file on this computer: its contents and SHA-256.""" - - type: Literal["file"] = "file" - #: The file's path. ``~`` and environment variables are expanded. - path: str = Field(min_length=1) - - -class MacosDefaultsSource(_Source): - """One key in a macOS preferences domain.""" - - type: Literal["macos_defaults"] = "macos_defaults" - #: ``NSGlobalDomain`` (``-g`` is accepted and means the same) or a bundle id. - domain: str - key: str = Field(min_length=1, max_length=255) - - @field_validator("domain") - @classmethod - def _check_domain(cls, value: str) -> str: - if value == "-g": - return "NSGlobalDomain" - if not _DEFAULTS_DOMAIN.fullmatch(value): - raise ValueError( - "macos_defaults domain must be NSGlobalDomain or a bundle id " - "(letters, digits, '.', '_' or '-'; not starting with '-')" - ) - return value - - -class WindowsRegistrySource(_Source): - """One value in the Windows registry.""" - - type: Literal["windows_registry"] = "windows_registry" - hive: Literal["HKCU", "HKLM"] - #: The key path under the hive, with backslashes (no leading backslash). - path: str = Field(min_length=1, max_length=1024) - #: The value's name. An empty string is the key's default value. - name: str = Field(default="", max_length=16383) - - @field_validator("path") - @classmethod - def _check_path(cls, value: str) -> str: - if value.startswith("\\") or "\x00" in value: - raise ValueError( - "windows_registry path is relative to the hive and must not " - "start with a backslash" - ) - return value - - -LocalStateSource = Union[FileSource, MacosDefaultsSource, WindowsRegistrySource] - - class _Unreadable(Exception): """A source could not be read. The whole read is then unreadable.""" @@ -257,7 +189,7 @@ def __init__( self.poll_interval_s = poll_interval_s self._runner = runner or _run self._registry = registry - self._platform = platform or sys.platform + self._platform = platform or _SYS_PLATFORM #: Why the last read was unreadable, for the verdict's detail. self.last_error: Optional[str] = None @@ -267,14 +199,30 @@ def _read_file(self, source: FileSource) -> dict[str, Any]: path = Path(os.path.expandvars(os.path.expanduser(source.path))) record: dict[str, Any] = {"id": source.id, "type": source.type} try: + # Only a regular file is a store. A device, FIFO or socket (or a + # link to one) could block the open or never reach EOF, so it is + # unreadable. O_NONBLOCK keeps a FIFO swapped in after the stat + # from blocking the open; fstat then checks the opened file. + if not stat.S_ISREG(path.stat().st_mode): + raise _Unreadable(f"{source.id}: not a regular file") # O_RDONLY only: the read never creates or truncates the file. - with path.open("rb") as fh: + fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0)) + with os.fdopen(fd, "rb") as fh: + opened = os.fstat(fh.fileno()) + if not stat.S_ISREG(opened.st_mode): + raise _Unreadable(f"{source.id}: not a regular file") + if opened.st_size > FILE_LIMIT: + raise _Unreadable(f"{source.id}: larger than {FILE_LIMIT} bytes") data = fh.read(TEXT_LIMIT + 1) digest = hashlib.sha256(data) size = len(data) for block in iter(lambda: fh.read(1 << 16), b""): digest.update(block) size += len(block) + if size > FILE_LIMIT: # grew while being read + raise _Unreadable( + f"{source.id}: larger than {FILE_LIMIT} bytes" + ) except FileNotFoundError: if not path.parent.is_dir(): # The folder that should hold the file is gone: that is not diff --git a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json index a1878aeed8..6e47f52400 100644 --- a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json +++ b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json @@ -2408,6 +2408,31 @@ "title": "Glob", "type": "string" }, + "local_state": { + "items": { + "discriminator": { + "mapping": { + "file": "#/$defs/FileSource", + "macos_defaults": "#/$defs/MacosDefaultsSource", + "windows_registry": "#/$defs/WindowsRegistrySource" + }, + "propertyName": "type" + }, + "oneOf": [ + { + "$ref": "#/$defs/FileSource" + }, + { + "$ref": "#/$defs/MacosDefaultsSource" + }, + { + "$ref": "#/$defs/WindowsRegistrySource" + } + ] + }, + "title": "Local State", + "type": "array" + }, "options": { "additionalProperties": true, "title": "Options", @@ -2483,6 +2508,33 @@ "title": "FieldReader", "type": "object" }, + "FileSource": { + "additionalProperties": false, + "description": "A file on this computer: its contents and SHA-256.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "file", + "default": "file", + "title": "Type", + "type": "string" + }, + "path": { + "minLength": 1, + "title": "Path", + "type": "string" + } + }, + "required": [ + "id", + "path" + ], + "title": "FileSource", + "type": "object" + }, "FinalCheck": { "additionalProperties": false, "description": "Make the first read provisional and settle it with a later read.", @@ -3176,6 +3228,39 @@ "title": "IdentitySection", "type": "object" }, + "MacosDefaultsSource": { + "additionalProperties": false, + "description": "One key in a macOS preferences domain.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_defaults", + "default": "macos_defaults", + "title": "Type", + "type": "string" + }, + "domain": { + "title": "Domain", + "type": "string" + }, + "key": { + "maxLength": 255, + "minLength": 1, + "title": "Key", + "type": "string" + } + }, + "required": [ + "id", + "domain", + "key" + ], + "title": "MacosDefaultsSource", + "type": "object" + }, "OpenStep": { "additionalProperties": false, "description": "Open the record from a results list: the one row showing the identity.", @@ -4707,6 +4792,49 @@ "title": "ValueExpr", "type": "object" }, + "WindowsRegistrySource": { + "additionalProperties": false, + "description": "One value in the Windows registry.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "windows_registry", + "default": "windows_registry", + "title": "Type", + "type": "string" + }, + "hive": { + "enum": [ + "HKCU", + "HKLM" + ], + "title": "Hive", + "type": "string" + }, + "path": { + "maxLength": 1024, + "minLength": 1, + "title": "Path", + "type": "string" + }, + "name": { + "default": "", + "maxLength": 16383, + "title": "Name", + "type": "string" + } + }, + "required": [ + "id", + "hive", + "path" + ], + "title": "WindowsRegistrySource", + "type": "object" + }, "WorklistAccount": { "additionalProperties": false, "description": "One signed-in session for a parallel worklist worker.\n\nHolds env var NAMES only, never a credential value.", @@ -5981,6 +6109,31 @@ "title": "Glob", "type": "string" }, + "local_state": { + "items": { + "discriminator": { + "mapping": { + "file": "#/$defs/FileSource", + "macos_defaults": "#/$defs/MacosDefaultsSource", + "windows_registry": "#/$defs/WindowsRegistrySource" + }, + "propertyName": "type" + }, + "oneOf": [ + { + "$ref": "#/$defs/FileSource" + }, + { + "$ref": "#/$defs/MacosDefaultsSource" + }, + { + "$ref": "#/$defs/WindowsRegistrySource" + } + ] + }, + "title": "Local State", + "type": "array" + }, "options": { "additionalProperties": true, "title": "Options", @@ -6056,6 +6209,33 @@ "title": "FieldReader", "type": "object" }, + "FileSource": { + "additionalProperties": false, + "description": "A file on this computer: its contents and SHA-256.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "file", + "default": "file", + "title": "Type", + "type": "string" + }, + "path": { + "minLength": 1, + "title": "Path", + "type": "string" + } + }, + "required": [ + "id", + "path" + ], + "title": "FileSource", + "type": "object" + }, "FinalCheck": { "additionalProperties": false, "description": "Make the first read provisional and settle it with a later read.", @@ -6345,6 +6525,39 @@ "title": "HistoryView", "type": "object" }, + "MacosDefaultsSource": { + "additionalProperties": false, + "description": "One key in a macOS preferences domain.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_defaults", + "default": "macos_defaults", + "title": "Type", + "type": "string" + }, + "domain": { + "title": "Domain", + "type": "string" + }, + "key": { + "maxLength": 255, + "minLength": 1, + "title": "Key", + "type": "string" + } + }, + "required": [ + "id", + "domain", + "key" + ], + "title": "MacosDefaultsSource", + "type": "object" + }, "OpenStep": { "additionalProperties": false, "description": "Open the record from a results list: the one row showing the identity.", @@ -7204,6 +7417,49 @@ }, "title": "ValueExpr", "type": "object" + }, + "WindowsRegistrySource": { + "additionalProperties": false, + "description": "One value in the Windows registry.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "windows_registry", + "default": "windows_registry", + "title": "Type", + "type": "string" + }, + "hive": { + "enum": [ + "HKCU", + "HKLM" + ], + "title": "Hive", + "type": "string" + }, + "path": { + "maxLength": 1024, + "minLength": 1, + "title": "Path", + "type": "string" + }, + "name": { + "default": "", + "maxLength": 16383, + "title": "Name", + "type": "string" + } + }, + "required": [ + "id", + "hive", + "path" + ], + "title": "WindowsRegistrySource", + "type": "object" } }, "$ref": "#/$defs/EffectsConfig" diff --git a/packages/flow/tests/test_finite_lazy_loaders.py b/packages/flow/tests/test_finite_lazy_loaders.py index 93e2d28b9f..8cc6662291 100644 --- a/packages/flow/tests/test_finite_lazy_loaders.py +++ b/packages/flow/tests/test_finite_lazy_loaders.py @@ -29,6 +29,11 @@ ("openadapt_flow.runtime", "RUNG_ORDER", "openadapt_flow.runtime.resolver"), ("openadapt_flow.runtime", "is_below_ocr", "openadapt_flow.runtime.resolver"), ("openadapt_flow.runtime", "resolve", "openadapt_flow.runtime.resolver"), + ( + "openadapt_flow.runtime", + "LocalStateVerifier", + "openadapt_flow.runtime.effects.local_state", + ), ( "openadapt_flow.runtime.durable", "ApprovalRecord", diff --git a/packages/flow/tests/test_local_state_verifier.py b/packages/flow/tests/test_local_state_verifier.py index d3e1f6e911..f3deab3f5e 100644 --- a/packages/flow/tests/test_local_state_verifier.py +++ b/packages/flow/tests/test_local_state_verifier.py @@ -8,6 +8,7 @@ from __future__ import annotations import hashlib +import os import plistlib import subprocess from pathlib import Path @@ -81,6 +82,32 @@ def test_missing_folder_is_unreadable(tmp_path: Path) -> None: assert "does not exist" in verdict.reason +@pytest.mark.skipif(not hasattr(os, "mkfifo"), reason="needs a FIFO") +def test_a_fifo_or_device_source_is_unreadable_and_never_blocks(tmp_path: Path) -> None: + fifo = tmp_path / "pipe" + os.mkfifo(fifo) + link = tmp_path / "link.txt" + link.symlink_to(fifo) + for path in (fifo, link, Path(os.devnull)): + v = LocalStateVerifier([FileSource(id="note", path=str(path))]) + assert v.read() is None + verdict = v.verify(_field("note", "present", "True"), v.capture_pre_state()) + assert verdict.verdict is Verdict.INDETERMINATE + assert "not a regular file" in verdict.reason + + +def test_a_file_over_the_read_limit_is_unreadable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from openadapt_flow.runtime.effects import local_state + + monkeypatch.setattr(local_state, "FILE_LIMIT", 8) + big = tmp_path / "big.txt" + big.write_bytes(b"x" * 9) + v = LocalStateVerifier([FileSource(id="note", path=str(big))]) + assert v.read() is None + + def test_large_or_binary_file_has_no_text_but_a_hash(tmp_path: Path) -> None: blob = tmp_path / "blob.bin" blob.write_bytes(b"\xff\xfe\x00" * 10) From f5f4b426d4645bcea40d2824d28b4ab319994b3f Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 12:26:26 -0500 Subject: [PATCH 08/11] fix(local-state): preserve legacy verifier identity hashes and update public artifact inventory --- packages/flow/openadapt_flow/deployment.py | 7 +++++++ packages/flow/public-artifacts.json | 2 ++ 2 files changed, 9 insertions(+) diff --git a/packages/flow/openadapt_flow/deployment.py b/packages/flow/openadapt_flow/deployment.py index 3173b9ab42..ee399e86e3 100644 --- a/packages/flow/openadapt_flow/deployment.py +++ b/packages/flow/openadapt_flow/deployment.py @@ -692,6 +692,8 @@ def _serialize_compatible(self, handler: Any) -> dict[str, Any]: ): if data.get(added, "") is None: data.pop(added, None) + if not data.get("local_state"): + data.pop("local_state", None) return data @model_validator(mode="after") @@ -2354,6 +2356,11 @@ def sanitized(value: Any, *, key: str = "") -> Any: ): if isinstance(candidate, dict) and candidate.get(added) is None: candidate.pop(added, None) + # ``local_state`` defaults to an empty list; omit it unless configured so + # existing verifier identities stay unchanged. + for holder in [config, *(config.get("candidates") or [])]: + if isinstance(holder, dict) and not holder.get("local_state"): + holder.pop("local_state", None) # The same rule one level down: ``ui_readback.reference`` came later. for holder in [config, *(config.get("candidates") or [])]: section = holder.get("ui_readback") if isinstance(holder, dict) else None diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index 6272396124..f6ec2e9f73 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -1440,6 +1440,8 @@ "examples/claude-code-demo/policy.yaml", "examples/legacy_records/answers.demo.json", "examples/legacy_records/answers.ledger.demo.json", + "examples/local_state/notepad-save/verify.yaml", + "examples/local_state/windows-dark-mode/verify.yaml", "import_direction_debt.json", "import_layers.json", "import_layers_debt.json", From 443cbbc1b94ac091d9e2cb20a1e3019121c76f5a Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 09:59:14 -0500 Subject: [PATCH 09/11] feat(flow,quickstart): add read-only Night Shift/Light and Calendar probes + everyday quickstart tasks --- ...-built-in-os-everyday-tasks-night-shift.md | 1 + openadapt/cli.py | 100 ++++ openadapt/quickstart/everyday.py | 341 ++++++++++++++ packages/flow/docs/LOCAL_STATE_CHECKS.md | 29 +- .../macos-calendar-block/verify.yaml | 19 + .../local_state/macos-night-shift/verify.yaml | 17 + .../windows-night-light/verify.yaml | 17 + .../openadapt_flow/local_state_sources.py | 56 ++- .../runtime/effects/local_state.py | 280 ++++++++++- packages/flow/public-artifacts.json | 3 + .../openadapt_flow.deployment.json | 196 +++++++- .../tests/test_everyday_local_state_probes.py | 439 ++++++++++++++++++ tests/test_everyday_quickstart.py | 191 ++++++++ 13 files changed, 1673 insertions(+), 16 deletions(-) create mode 100644 capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md create mode 100644 openadapt/quickstart/everyday.py create mode 100644 packages/flow/examples/local_state/macos-calendar-block/verify.yaml create mode 100644 packages/flow/examples/local_state/macos-night-shift/verify.yaml create mode 100644 packages/flow/examples/local_state/windows-night-light/verify.yaml create mode 100644 packages/flow/tests/test_everyday_local_state_probes.py create mode 100644 tests/test_everyday_quickstart.py diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md b/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md new file mode 100644 index 0000000000..9c12de20a5 --- /dev/null +++ b/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md @@ -0,0 +1 @@ +| Verify built-in OS everyday tasks with zero sample apps or logins: `macos_night_shift` (read-only `CoreBrightness` `CBBlueLightClient`), `windows_night_light` (read-only `HKCU` CloudStore `Data` byte 18 `0x15`/`0x13`), and `macos_calendar_event` (fixed read-only AppleScript probe matching calendar, title, and start time), wired into `openadapt quickstart --task night-shift` and `--task calendar-block` with parameterized inputs and revert verification contracts; unreadable or unsupported hosts fail closed as `INDETERMINATE` | Experimental | Unit-tested across all 3 probes (enabled/disabled, malformed bytes, missing keys/calendars, wrong OS -> fail-closed `INDETERMINATE`), parameterized calendar compilation, revert contracts, and live read-only `macos_night_shift` probe on macOS | `openadapt quickstart --task`, [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `openadapt/quickstart/everyday.py`, `runtime/effects/local_state.py` | diff --git a/openadapt/cli.py b/openadapt/cli.py index bf64846eb6..e9aea48e88 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -880,6 +880,52 @@ def ask(prompt: str) -> str: default=None, help="With --own: your web app's address. Recording opens a browser window.", ) +@click.option( + "--task", + type=click.Choice(["night-shift", "calendar-block"]), + default=None, + help=( + "Built-in OS everyday task (no sample app, no login): " + "night-shift (macOS Night Shift / Windows Night Light) or " + "calendar-block (parameterized recurring Calendar block)." + ), +) +@click.option( + "--title", + default=None, + help="With --task calendar-block: Calendar event title.", +) +@click.option( + "--calendar", + "calendar_name", + default=None, + help="With --task calendar-block: macOS Calendar name (default: Calendar).", +) +@click.option( + "--start", + "start_iso", + default=None, + help="With --task calendar-block: ISO-8601 start timestamp.", +) +@click.option( + "--duration", + "duration_minutes", + type=int, + default=None, + help="With --task calendar-block: duration in minutes (default: 30).", +) +@click.option( + "--recurrence", + type=click.Choice(["none", "daily", "weekly", "weekdays"]), + default=None, + help="With --task calendar-block: recurrence cadence (default: weekly).", +) +@click.option( + "--revert/--no-revert", + default=True, + show_default=True, + help="With --task: emit a revert/undo verification contract to leave the machine clean.", +) @click.option("--headed", is_flag=True, hidden=True) @click.option("--headless", is_flag=True, hidden=True) @click.option("--break-it", "break_it", is_flag=True, hidden=True) @@ -895,6 +941,13 @@ def quickstart( more: bool, own: bool, url: Optional[str], + task: Optional[str], + title: Optional[str], + calendar_name: Optional[str], + start_iso: Optional[str], + duration_minutes: Optional[int], + recurrence: Optional[str], + revert: bool, headed: bool, headless: bool, break_it: bool, @@ -923,6 +976,53 @@ def quickstart( _require_supported_python() if url is not None and not own: raise click.UsageError("--url works with --own.") + calendar_opts_used = any( + opt is not None + for opt in (title, calendar_name, start_iso, duration_minutes, recurrence) + ) + if calendar_opts_used and task != "calendar-block": + raise click.UsageError( + "--title, --calendar, --start, --duration, and --recurrence require " + "--task calendar-block." + ) + if task is not None: + if own: + raise click.UsageError("--task cannot be combined with --own.") + from openadapt.quickstart.everyday import ( + DEFAULT_CALENDAR_NAME, + DEFAULT_CALENDAR_TITLE, + DEFAULT_DURATION_MINUTES, + DEFAULT_RECURRENCE, + EverydayTaskError, + run_everyday_task, + ) + + root = _quickstart_root(out) + try: + run_everyday_task( + task, + root, + title=title if title is not None else DEFAULT_CALENDAR_TITLE, + calendar_name=( + calendar_name + if calendar_name is not None + else DEFAULT_CALENDAR_NAME + ), + start_iso=start_iso, + duration_minutes=( + duration_minutes + if duration_minutes is not None + else DEFAULT_DURATION_MINUTES + ), + recurrence=( + recurrence if recurrence is not None else DEFAULT_RECURRENCE + ), + revert=revert, + say=click.echo, + ) + except EverydayTaskError as error: + raise click.ClickException(str(error)) from error + return if own: _quickstart_own(_quickstart_root(out), url, watch or headed) return diff --git a/openadapt/quickstart/everyday.py b/openadapt/quickstart/everyday.py new file mode 100644 index 0000000000..75739cdfb4 --- /dev/null +++ b/openadapt/quickstart/everyday.py @@ -0,0 +1,341 @@ +"""Built-in everyday OS quickstart tasks (zero sample apps, zero logins). + +Provides parameterized task definitions and read-only ``local-state`` verification +contracts (including optional revert/undo contracts) for: + +1. ``night-shift``: Toggle macOS Night Shift (``macos_night_shift``) or Windows + Night Light (``windows_night_light``). +2. ``calendar-block``: Schedule a recurring Calendar block with parameterized + title, start/end time, duration, and recurrence (``macos_calendar_event``). + +Nothing in this module mutates OS settings or Calendar data; probes are strictly +read-only and fail closed when unreadable. +""" + +from __future__ import annotations + +import json +import sys +from dataclasses import dataclass +from datetime import datetime, timedelta +from pathlib import Path +from typing import Any, Callable, Optional + +import yaml # type: ignore[import-untyped] + +EVERYDAY_TASKS = ("night-shift", "calendar-block") +VALID_RECURRENCES = ("none", "daily", "weekly", "weekdays") +DEFAULT_CALENDAR_TITLE = "OpenAdapt Focus Block" +DEFAULT_CALENDAR_NAME = "Calendar" +DEFAULT_DURATION_MINUTES = 30 +DEFAULT_RECURRENCE = "weekly" + + +class EverydayTaskError(Exception): + """Raised when an everyday quickstart task cannot be configured on this host.""" + + +@dataclass(frozen=True) +class EverydayTaskBundle: + """Generated contracts and read-only baseline snapshot for an everyday task.""" + + task: str + platform: str + out_dir: Path + verify_path: Path + revert_verify_path: Optional[Path] + params_path: Path + baseline_state: Optional[dict[str, Any]] + params: dict[str, Any] + revert: bool + + +def default_start_iso(now: Optional[datetime] = None) -> str: + """Return the next top-of-the-hour local timestamp as an ISO-8601 string.""" + ref = now or datetime.now() + next_hour = ref.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) + return next_hour.isoformat(timespec="seconds") + + +def _parse_iso(value: str) -> datetime: + normalized = value[:-1] + "+00:00" if value.endswith("Z") else value + try: + return datetime.fromisoformat(normalized) + except ValueError as exc: + raise EverydayTaskError( + f"--start must be a valid ISO-8601 timestamp (got {value!r})" + ) from exc + + +def build_night_shift_contracts( + *, + platform: str, + baseline_enabled: Optional[bool] = None, + revert: bool = True, +) -> tuple[dict[str, Any], Optional[dict[str, Any]], dict[str, Any]]: + """Build forward and optional revert ``verify.yaml`` contracts for Night Shift/Light.""" + if platform == "darwin": + source_type = "macos_night_shift" + source_id = "night_shift" + label = "macOS Night Shift" + elif platform == "win32": + source_type = "windows_night_light" + source_id = "night_light" + label = "Windows Night Light" + else: + raise EverydayTaskError( + f"night-shift task supports macOS (Night Shift) and Windows (Night Light); " + f"unsupported platform {platform!r}" + ) + + target_enabled = (not baseline_enabled) if baseline_enabled is not None else True + restore_enabled = ( + baseline_enabled if baseline_enabled is not None else (not target_enabled) + ) + + def _contract(expected_enabled: bool) -> dict[str, Any]: + return { + "schema_version": "openadapt.verify/v1", + "minimum_effect_strength": "independent_system_of_record", + "verifier": { + "kind": "local-state", + "local_state": [{"type": source_type, "id": source_id}], + }, + "frame": {"target_fields": ["enabled", "value"]}, + "effects": [ + { + "kind": "field_equals", + "match": {"id": source_id}, + "field": "value", + "value": "true" if expected_enabled else "false", + } + ], + } + + forward = _contract(target_enabled) + revert_contract = _contract(restore_enabled) if revert else None + params: dict[str, Any] = { + "task": "night-shift", + "label": label, + "platform": platform, + "source_type": source_type, + "baseline_enabled": baseline_enabled, + "target_enabled": "true" if target_enabled else "false", + "restore_enabled": "true" if restore_enabled else "false", + "revert": revert, + } + return forward, revert_contract, params + + +def build_calendar_block_contracts( + *, + title: str = DEFAULT_CALENDAR_TITLE, + calendar_name: str = DEFAULT_CALENDAR_NAME, + start_iso: Optional[str] = None, + duration_minutes: int = DEFAULT_DURATION_MINUTES, + recurrence: str = DEFAULT_RECURRENCE, + platform: str = "darwin", + revert: bool = True, +) -> tuple[dict[str, Any], Optional[dict[str, Any]], dict[str, Any]]: + """Build parameterized forward and optional revert contracts for a Calendar block.""" + if platform != "darwin": + raise EverydayTaskError( + f"calendar-block local-state probe currently supports macOS Calendar; " + f"unsupported platform {platform!r}" + ) + if not title or not title.strip(): + raise EverydayTaskError("--title must be non-empty") + if not calendar_name or not calendar_name.strip(): + raise EverydayTaskError("--calendar must be non-empty") + if duration_minutes < 1 or duration_minutes > 480: + raise EverydayTaskError("--duration must be between 1 and 480 minutes") + if recurrence not in VALID_RECURRENCES: + raise EverydayTaskError( + f"--recurrence must be one of {', '.join(VALID_RECURRENCES)}" + ) + + resolved_start = start_iso or default_start_iso() + start_dt = _parse_iso(resolved_start) + end_dt = start_dt + timedelta(minutes=duration_minutes) + end_iso = end_dt.isoformat(timespec="seconds") + + source_spec = { + "type": "macos_calendar_event", + "id": "calendar_block", + "calendar_name": calendar_name.strip(), + "title": title.strip(), + "start_iso": resolved_start, + } + + def _contract(expected_exists: bool) -> dict[str, Any]: + return { + "schema_version": "openadapt.verify/v1", + "minimum_effect_strength": "independent_system_of_record", + "verifier": { + "kind": "local-state", + "local_state": [source_spec], + }, + "frame": {"target_fields": ["present", "exists", "value"]}, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "calendar_block"}, + "field": "value", + "value": "true" if expected_exists else "false", + } + ], + } + + forward = _contract(True) + revert_contract = _contract(False) if revert else None + params: dict[str, Any] = { + "task": "calendar-block", + "platform": platform, + "calendar_name": calendar_name.strip(), + "title": title.strip(), + "start_iso": resolved_start, + "end_iso": end_iso, + "duration_minutes": duration_minutes, + "recurrence": recurrence, + "revert": revert, + } + return forward, revert_contract, params + + +def _probe_baseline( + verify_doc: dict[str, Any], + *, + platform: str, + verifier_factory: Optional[Callable[..., Any]] = None, +) -> tuple[Optional[dict[str, Any]], Optional[str]]: + """Run the read-only ``local-state`` probe once without mutating OS state.""" + from openadapt_flow.runtime.effects.local_state import LocalStateVerifier + from openadapt_flow.verify_run import VerifyConfig + + cfg = VerifyConfig.model_validate(verify_doc) + sources = list(cfg.verifier.local_state or []) + if verifier_factory is not None: + verifier = verifier_factory(sources, platform=platform) + else: + verifier = LocalStateVerifier(sources, platform=platform) + records = verifier.read() + if records is None or not records: + return None, getattr(verifier, "last_error", "unreadable") + return records[0], None + + +def run_everyday_task( + task: str, + root: Path, + *, + title: str = DEFAULT_CALENDAR_TITLE, + calendar_name: str = DEFAULT_CALENDAR_NAME, + start_iso: Optional[str] = None, + duration_minutes: int = DEFAULT_DURATION_MINUTES, + recurrence: str = DEFAULT_RECURRENCE, + revert: bool = True, + platform: Optional[str] = None, + say: Callable[[str], None] = print, + verifier_factory: Optional[Callable[..., Any]] = None, +) -> EverydayTaskBundle: + """Prepare and baseline-probe a built-in everyday OS task into ``root``.""" + if task not in EVERYDAY_TASKS: + raise EverydayTaskError( + f"Unknown task {task!r}. Expected one of: {', '.join(EVERYDAY_TASKS)}" + ) + + active_platform = platform or sys.platform + baseline_state: Optional[dict[str, Any]] = None + probe_error: Optional[str] = None + + if task == "night-shift": + # Probe baseline first so the forward target flips the actual current state. + probe_doc, _, _ = build_night_shift_contracts( + platform=active_platform, baseline_enabled=None, revert=revert + ) + baseline_state, probe_error = _probe_baseline( + probe_doc, platform=active_platform, verifier_factory=verifier_factory + ) + baseline_enabled = ( + bool(baseline_state["enabled"]) + if baseline_state is not None + and isinstance(baseline_state.get("enabled"), bool) + else None + ) + forward, revert_doc, params = build_night_shift_contracts( + platform=active_platform, + baseline_enabled=baseline_enabled, + revert=revert, + ) + else: + forward, revert_doc, params = build_calendar_block_contracts( + title=title, + calendar_name=calendar_name, + start_iso=start_iso, + duration_minutes=duration_minutes, + recurrence=recurrence, + platform=active_platform, + revert=revert, + ) + baseline_state, probe_error = _probe_baseline( + forward, platform=active_platform, verifier_factory=verifier_factory + ) + + root.mkdir(parents=True, exist_ok=True) + verify_path = root / "verify.yaml" + verify_path.write_text(yaml.safe_dump(forward, sort_keys=False), encoding="utf-8") + + revert_verify_path: Optional[Path] = None + if revert_doc is not None: + revert_verify_path = root / "revert_verify.yaml" + revert_verify_path.write_text( + yaml.safe_dump(revert_doc, sort_keys=False), encoding="utf-8" + ) + + params_path = root / "task.json" + params_path.write_text( + json.dumps(params, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + say(f"Everyday task: {task} ({active_platform})") + if baseline_state is not None: + say( + f" Baseline probe (read-only): {baseline_state['type']} -> " + f"value={baseline_state.get('value')}" + ) + else: + say( + f" Baseline probe (read-only): INDETERMINATE ({probe_error or 'unavailable'})" + ) + say(f" Verify contract: {verify_path}") + if revert_verify_path is not None: + say(f" Revert contract: {revert_verify_path} (leaves machine clean)") + say(f" Task parameters: {params_path}") + + return EverydayTaskBundle( + task=task, + platform=active_platform, + out_dir=root, + verify_path=verify_path, + revert_verify_path=revert_verify_path, + params_path=params_path, + baseline_state=baseline_state, + params=params, + revert=revert, + ) + + +__all__ = [ + "DEFAULT_CALENDAR_NAME", + "DEFAULT_CALENDAR_TITLE", + "DEFAULT_DURATION_MINUTES", + "DEFAULT_RECURRENCE", + "EVERYDAY_TASKS", + "EverydayTaskBundle", + "EverydayTaskError", + "VALID_RECURRENCES", + "build_calendar_block_contracts", + "build_night_shift_contracts", + "default_start_iso", + "run_everyday_task", +] diff --git a/packages/flow/docs/LOCAL_STATE_CHECKS.md b/packages/flow/docs/LOCAL_STATE_CHECKS.md index fc692a9f29..da651eca9f 100644 --- a/packages/flow/docs/LOCAL_STATE_CHECKS.md +++ b/packages/flow/docs/LOCAL_STATE_CHECKS.md @@ -17,6 +17,9 @@ rules. It never runs a command you supply, and it never writes. | `file` | A file's contents | Ordinary read-only file I/O | `present`, `size`, `sha256`, `text` (UTF-8, files up to 1 MiB) | | `macos_defaults` | One key in a preferences domain | `/usr/bin/defaults export -` (goes through `cfprefsd`, so it sees the current value). Unit-tested only so far; not yet run on a real Mac | `present`, `value`, `value_type` | | `windows_registry` | One registry value under `HKCU` or `HKLM` | `winreg` with `KEY_READ` access only | `present`, `value`, `value_type` | +| `macos_night_shift` | Current macOS Night Shift enabled state | Read-only `CBBlueLightClient.getBlueLightStatus:` via `CoreBrightness` (`ctypes`/`libobjc`). Fails closed (`INDETERMINATE`) if unavailable | `present`, `enabled`, `value` (`"true"`/`"false"`), `value_type` | +| `windows_night_light` | Current Windows Night Light enabled state | Read-only `winreg` (`KEY_READ`) read of `HKCU\...\bluelightreductionstate` `Data` bytes (byte 18 `0x15` enabled vs `0x13` disabled). Fails closed on missing or unexpected bytes | `present`, `enabled`, `value` (`"true"`/`"false"`), `value_type` | +| `macos_calendar_event` | Whether a macOS Calendar event matching `(calendar_name, title, start_iso)` exists | Fixed read-only AppleScript via `/usr/bin/osascript` with argv parameters (never mutates Calendar). Fails closed if the calendar is missing or permission is denied | `present`, `exists`, `calendar_name`, `title`, `start_iso`, `value` (`"true"`/`"false"`), `value_type` | Each source becomes one record with the source's `id`, judged by the same effect kinds every other record check uses (`field_equals`, `record_written`). @@ -93,6 +96,9 @@ The examples live in [`examples/local_state/`](../examples/local_state/). | --- | --- | --- | | `notepad-save` | `~/openadapt-examples/note.txt`, text equals the note | End to end on Windows 11 in the lab: record, compile, replay, check `verified`. Turn Notepad's status bar off (View > Status bar) so replay can confirm the typing | | `windows-dark-mode` | `HKCU\...\Themes\Personalize` `AppsUseLightTheme` and `SystemUsesLightTheme` are `0` | Check only, on the real registry; see below | +| `macos-night-shift` | macOS Night Shift `enabled` state via `CoreBrightness` | Read-only probe verified on macOS; fail-closed unit-tested across platforms | +| `windows-night-light` | Windows Night Light `Data` byte 18 (`0x15` vs `0x13`) | Unit-tested against CloudStore blobs; fail-closed on missing or unexpected bytes | +| `macos-calendar-block` | macOS Calendar event matching `(calendar_name, title, start_iso)` | Fixed read-only AppleScript probe; unit-tested with fail-closed missing-calendar/error checks | TextEdit and macOS Dark Mode follow the same pattern (a `file` source; a `macos_defaults` source on `NSGlobalDomain` `AppleInterfaceStyle`). They have @@ -100,18 +106,17 @@ no example yet because they haven't been run on a Mac. ## What it can't check, and why -- **Night Shift (macOS).** Its state lives in CoreBrightness, a private - framework. There is no public API and no preference key that reliably - shows whether Night Shift is on now (the stored schedule is in a root-only - file and is not the current state). OpenAdapt can't check it, so there is - no Night Shift example. -- **Notes (macOS).** The supported ways to read a note are AppleScript and - Shortcuts. Both are scripts, not a typed read, and both need an Automation - consent prompt per app. The Notes database is private and protected by - Full Disk Access. There is no Notes source. -- **Calendar (macOS).** EventKit is a supported, public read API. It needs a - Calendar permission prompt and a PyObjC dependency that OpenAdapt doesn't - ship today. It is a candidate source, not built. +- **Notes (macOS).** The Notes database is private and protected by Full Disk + Access, and reading arbitrary note bodies via AppleScript needs per-app + Automation consent without a typed schema. There is no Notes source. +- **Calendar (macOS) without Automation permission.** `macos_calendar_event` + uses a fixed read-only AppleScript probe; if Calendar Automation consent is + not granted or the named calendar does not exist, it fails closed as + `INDETERMINATE`. +- **Night Shift (macOS) on unsupported displays.** `macos_night_shift` reads + the private `CoreBrightness` framework (`CBBlueLightClient`); if the + framework or display capability is unavailable, it fails closed as + `INDETERMINATE`. - **Windows dark mode on an unactivated Windows.** Windows locks the Personalization pages until it is activated, so the setting can't be demonstrated through Settings there. The check itself reads the registry diff --git a/packages/flow/examples/local_state/macos-calendar-block/verify.yaml b/packages/flow/examples/local_state/macos-calendar-block/verify.yaml new file mode 100644 index 0000000000..d726f7bff1 --- /dev/null +++ b/packages/flow/examples/local_state/macos-calendar-block/verify.yaml @@ -0,0 +1,19 @@ +# Check a macOS Calendar event through a fixed, read-only AppleScript probe. +# Verifies whether an event matching (calendar_name, title, start_iso) exists. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: macos_calendar_event + id: calendar_block + calendar_name: Calendar + title: OpenAdapt Focus Block + start_iso: "2026-11-24T10:00:00" +frame: + target_fields: [present, exists, value] +effects: + - kind: field_equals + match: {id: calendar_block} + field: value + value: "true" diff --git a/packages/flow/examples/local_state/macos-night-shift/verify.yaml b/packages/flow/examples/local_state/macos-night-shift/verify.yaml new file mode 100644 index 0000000000..68ff947e4d --- /dev/null +++ b/packages/flow/examples/local_state/macos-night-shift/verify.yaml @@ -0,0 +1,17 @@ +# Check a macOS Night Shift toggle through CoreBrightness (read-only). +# Compare the `value` field ("true" or "false") after toggling Night Shift +# in System Settings or Control Center. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: macos_night_shift + id: night_shift +frame: + target_fields: [enabled, value] +effects: + - kind: field_equals + match: {id: night_shift} + field: value + value: {param: target_enabled} diff --git a/packages/flow/examples/local_state/windows-night-light/verify.yaml b/packages/flow/examples/local_state/windows-night-light/verify.yaml new file mode 100644 index 0000000000..5a569029b6 --- /dev/null +++ b/packages/flow/examples/local_state/windows-night-light/verify.yaml @@ -0,0 +1,17 @@ +# Check a Windows Night Light toggle through the HKCU CloudStore registry blob. +# Byte 18 is 0x15 when enabled and 0x13 when disabled; unexpected or missing +# bytes fail closed as INDETERMINATE. +schema_version: openadapt.verify/v1 +minimum_effect_strength: independent_system_of_record +verifier: + kind: local-state + local_state: + - type: windows_night_light + id: night_light +frame: + target_fields: [enabled, value] +effects: + - kind: field_equals + match: {id: night_light} + field: value + value: {param: target_enabled} diff --git a/packages/flow/openadapt_flow/local_state_sources.py b/packages/flow/openadapt_flow/local_state_sources.py index b4a00595b0..185d6f10db 100644 --- a/packages/flow/openadapt_flow/local_state_sources.py +++ b/packages/flow/openadapt_flow/local_state_sources.py @@ -9,6 +9,7 @@ from __future__ import annotations import re +from datetime import datetime from typing import Literal, Union from pydantic import BaseModel, ConfigDict, Field, field_validator @@ -16,7 +17,10 @@ __all__ = [ "FileSource", "LocalStateSource", + "MacosCalendarEventSource", "MacosDefaultsSource", + "MacosNightShiftSource", + "WindowsNightLightSource", "WindowsRegistrySource", ] @@ -93,4 +97,54 @@ def _check_path(cls, value: str) -> str: return value -LocalStateSource = Union[FileSource, MacosDefaultsSource, WindowsRegistrySource] +class MacosNightShiftSource(_Source): + """Current macOS Night Shift enabled state via CoreBrightness (read-only).""" + + type: Literal["macos_night_shift"] = "macos_night_shift" + + +class WindowsNightLightSource(_Source): + """Current Windows Night Light enabled state via CloudStore registry Data bytes.""" + + type: Literal["windows_night_light"] = "windows_night_light" + + +class MacosCalendarEventSource(_Source): + """Read-only check for a macOS Calendar event matching calendar, title, and start.""" + + type: Literal["macos_calendar_event"] = "macos_calendar_event" + calendar_name: str = Field(min_length=1, max_length=255) + title: str = Field(min_length=1, max_length=255) + #: ISO-8601 start timestamp (e.g. ``2026-11-24T10:00:00``). + start_iso: str = Field(min_length=10, max_length=64) + + @field_validator("calendar_name", "title") + @classmethod + def _check_safe_text(cls, value: str) -> str: + if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in value): + raise ValueError( + "macos_calendar_event text fields must not contain control characters" + ) + return value + + @field_validator("start_iso") + @classmethod + def _check_start_iso(cls, value: str) -> str: + normalized = value[:-1] + "+00:00" if value.endswith("Z") else value + try: + datetime.fromisoformat(normalized) + except ValueError as exc: + raise ValueError( + "macos_calendar_event start_iso must be a valid ISO-8601 timestamp" + ) from exc + return value + + +LocalStateSource = Union[ + FileSource, + MacosDefaultsSource, + WindowsRegistrySource, + MacosNightShiftSource, + WindowsNightLightSource, + MacosCalendarEventSource, +] diff --git a/packages/flow/openadapt_flow/runtime/effects/local_state.py b/packages/flow/openadapt_flow/runtime/effects/local_state.py index da06f4beb4..28988e5a87 100644 --- a/packages/flow/openadapt_flow/runtime/effects/local_state.py +++ b/packages/flow/openadapt_flow/runtime/effects/local_state.py @@ -58,12 +58,14 @@ from __future__ import annotations +import ctypes import hashlib import json import os import plistlib import stat import subprocess +from datetime import datetime from pathlib import Path from sys import platform as _SYS_PLATFORM from typing import Any, Callable, Optional @@ -71,7 +73,10 @@ from openadapt_flow.local_state_sources import ( # noqa: F401 - re-exported FileSource, LocalStateSource, + MacosCalendarEventSource, MacosDefaultsSource, + MacosNightShiftSource, + WindowsNightLightSource, WindowsRegistrySource, ) from openadapt_flow.runtime.effects.adapter import ( @@ -94,11 +99,153 @@ #: cannot substitute another program. DEFAULTS_BINARY = "/usr/bin/defaults" +#: The supported macOS AppleScript runner, used only with a fixed read-only +#: script and argv parameters (never interpolated user strings). +OSASCRIPT_BINARY = "/usr/bin/osascript" + +#: Fixed HKCU registry path holding Windows 10/11 Night Light CloudStore state. +WINDOWS_NIGHT_LIGHT_REG_PATH = ( + r"Software\Microsoft\Windows\CurrentVersion\CloudStore\Store" + r"\DefaultAccount\Current" + r"\default$windows.data.bluelightreduction.bluelightreductionstate" + r"\windows.data.bluelightreduction.bluelightreductionstate" +) +WINDOWS_NIGHT_LIGHT_VALUE_NAME = "Data" +_WINDOWS_NIGHT_LIGHT_STATE_BYTE_INDEX = 18 +_WINDOWS_NIGHT_LIGHT_ENABLED_BYTE = 0x15 +_WINDOWS_NIGHT_LIGHT_DISABLED_BYTE = 0x13 + +# Fixed read-only AppleScript: receives (calendar_name, title, year, month, +# day, hour, minute) via argv and never creates, modifies, or deletes events. +_MACOS_CALENDAR_READ_SCRIPT = """ +on run argv + set calName to item 1 of argv + set targetTitle to item 2 of argv + set targetYear to (item 3 of argv) as integer + set targetMonth to (item 4 of argv) as integer + set targetDay to (item 5 of argv) as integer + set targetHour to (item 6 of argv) as integer + set targetMinute to (item 7 of argv) as integer + tell application "Calendar" + if not (exists calendar calName) then + return "NO_CALENDAR" + end if + set matchingEvents to (every event of calendar calName whose summary is targetTitle) + repeat with ev in matchingEvents + set sd to start date of ev + if ((year of sd) is targetYear) and (((month of sd) as integer) is targetMonth) and ((day of sd) is targetDay) and ((hours of sd) is targetHour) and ((minutes of sd) is targetMinute) then + return "FOUND" + end if + end repeat + return "NOT_FOUND" + end tell +end run +""".strip() + #: Registry hives a source may read. Per-user settings and machine settings; #: nothing else is needed for read-back. REGISTRY_HIVES = ("HKCU", "HKLM") Runner = Callable[[list[str]], "subprocess.CompletedProcess[bytes]"] +NightShiftReader = Callable[[], bool] + + +def parse_windows_night_light_bytes(raw: Any) -> bool: + """Decode Windows Night Light ``Data`` bytes into ``True``/``False``. + + Windows 10/11 stores the Night Light state in byte 18 of the CloudStore + ``Data`` blob: ``0x15`` when enabled, ``0x13`` when disabled. Any missing, + truncated, non-bytes, or unexpected byte pattern raises ``_Unreadable`` + (fail-closed). + """ + if not isinstance(raw, (bytes, bytearray)): + raise _Unreadable("windows_night_light Data value is not binary bytes") + if len(raw) <= _WINDOWS_NIGHT_LIGHT_STATE_BYTE_INDEX: + raise _Unreadable(f"windows_night_light Data blob too short ({len(raw)} bytes)") + state_byte = raw[_WINDOWS_NIGHT_LIGHT_STATE_BYTE_INDEX] + if state_byte == _WINDOWS_NIGHT_LIGHT_ENABLED_BYTE: + return True + if state_byte == _WINDOWS_NIGHT_LIGHT_DISABLED_BYTE: + return False + raise _Unreadable(f"windows_night_light unexpected state byte 0x{state_byte:02x}") + + +def _read_core_brightness_night_shift() -> bool: + """Read macOS Night Shift enabled state via CoreBrightness (read-only). + + Uses ``CBBlueLightClient.getBlueLightStatus:`` through ``libobjc.A.dylib`` + with zero writes and zero third-party dependencies. Raises ``_Unreadable`` + if the framework, class, or status query is unavailable. + """ + + class _CBTime(ctypes.Structure): + _fields_ = [("hour", ctypes.c_int), ("minute", ctypes.c_int)] + + class _CBSchedule(ctypes.Structure): + _fields_ = [("fromTime", _CBTime), ("toTime", _CBTime)] + + class _CBStatusData(ctypes.Structure): + _fields_ = [ + ("active", ctypes.c_bool), + ("enabled", ctypes.c_bool), + ("sunSchedulePermitted", ctypes.c_bool), + ("mode", ctypes.c_int), + ("schedule", _CBSchedule), + ("disableFlags", ctypes.c_ulonglong), + ("available", ctypes.c_bool), + ] + + try: + objc = ctypes.cdll.LoadLibrary("/usr/lib/libobjc.A.dylib") + ctypes.cdll.LoadLibrary( + "/System/Library/PrivateFrameworks/CoreBrightness.framework/CoreBrightness" + ) + except OSError as exc: + raise _Unreadable(f"CoreBrightness unavailable: {exc}") from exc + + objc.objc_getClass.argtypes = [ctypes.c_char_p] + objc.objc_getClass.restype = ctypes.c_void_p + objc.sel_registerName.argtypes = [ctypes.c_char_p] + objc.sel_registerName.restype = ctypes.c_void_p + + cls = objc.objc_getClass(b"CBBlueLightClient") + if not cls: + raise _Unreadable("CBBlueLightClient class not found") + + msg_send_id = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p)( + ("objc_msgSend", objc) + ) + msg_send_status = ctypes.CFUNCTYPE( + ctypes.c_bool, + ctypes.c_void_p, + ctypes.c_void_p, + ctypes.POINTER(_CBStatusData), + )(("objc_msgSend", objc)) + msg_send_void = ctypes.CFUNCTYPE(None, ctypes.c_void_p, ctypes.c_void_p)( + ("objc_msgSend", objc) + ) + + alloc_sel = objc.sel_registerName(b"alloc") + init_sel = objc.sel_registerName(b"init") + get_sel = objc.sel_registerName(b"getBlueLightStatus:") + release_sel = objc.sel_registerName(b"release") + + allocated = msg_send_id(cls, alloc_sel) + if not allocated: + raise _Unreadable("CBBlueLightClient alloc returned null") + client = msg_send_id(allocated, init_sel) + if not client: + raise _Unreadable("CBBlueLightClient init returned null") + try: + status = _CBStatusData() + ok = bool(msg_send_status(client, get_sel, ctypes.byref(status))) + if not ok: + raise _Unreadable("CBBlueLightClient.getBlueLightStatus: returned false") + if not status.available: + raise _Unreadable("Night Shift is not available on this display") + return bool(status.enabled) + finally: + msg_send_void(client, release_sel) class _Unreadable(Exception): @@ -175,6 +322,7 @@ def __init__( runner: Optional[Runner] = None, registry: Any = None, platform: Optional[str] = None, + night_shift_reader: Optional[NightShiftReader] = None, session: Any = None, ) -> None: if not sources: @@ -190,6 +338,9 @@ def __init__( self._runner = runner or _run self._registry = registry self._platform = platform or _SYS_PLATFORM + self._night_shift_reader = ( + night_shift_reader or _read_core_brightness_night_shift + ) #: Why the last read was unreadable, for the verdict's detail. self.last_error: Optional[str] = None @@ -333,6 +484,120 @@ def _read_registry(self, source: WindowsRegistrySource) -> dict[str, Any]: ) return record + def _read_macos_night_shift(self, source: MacosNightShiftSource) -> dict[str, Any]: + if self._platform != "darwin": + raise _Unreadable(f"{source.id}: macos_night_shift needs macOS") + try: + enabled = self._night_shift_reader() + except _Unreadable as exc: + raise _Unreadable(f"{source.id}: {exc}") from exc + except Exception as exc: # noqa: BLE001 - fail closed on any probe error + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + if not isinstance(enabled, bool): + raise _Unreadable(f"{source.id}: night shift reader did not return a bool") + return { + "id": source.id, + "type": source.type, + "present": True, + "enabled": enabled, + "value": value_text(enabled), + "value_type": "boolean", + } + + def _read_windows_night_light( + self, source: WindowsNightLightSource + ) -> dict[str, Any]: + try: + reg = self._winreg() + except _Unreadable as exc: + raise _Unreadable(f"{source.id}: {exc}") from exc + hive = reg.HKEY_CURRENT_USER + try: + key = reg.OpenKey(hive, WINDOWS_NIGHT_LIGHT_REG_PATH, 0, reg.KEY_READ) + except FileNotFoundError as exc: + raise _Unreadable( + f"{source.id}: Windows Night Light registry key does not exist" + ) from exc + except OSError as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + try: + with key: + value, _kind = reg.QueryValueEx(key, WINDOWS_NIGHT_LIGHT_VALUE_NAME) + except FileNotFoundError as exc: + raise _Unreadable( + f"{source.id}: Windows Night Light Data value missing" + ) from exc + except OSError as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + try: + enabled = parse_windows_night_light_bytes(value) + except _Unreadable as exc: + raise _Unreadable(f"{source.id}: {exc}") from exc + return { + "id": source.id, + "type": source.type, + "present": True, + "enabled": enabled, + "value": value_text(enabled), + "value_type": "boolean", + } + + def _read_macos_calendar_event( + self, source: MacosCalendarEventSource + ) -> dict[str, Any]: + if self._platform != "darwin": + raise _Unreadable(f"{source.id}: macos_calendar_event needs macOS") + normalized = ( + source.start_iso[:-1] + "+00:00" + if source.start_iso.endswith("Z") + else source.start_iso + ) + try: + start_dt = datetime.fromisoformat(normalized) + except ValueError as exc: + raise _Unreadable(f"{source.id}: invalid start_iso") from exc + argv = [ + OSASCRIPT_BINARY, + "-e", + _MACOS_CALENDAR_READ_SCRIPT, + "--", + source.calendar_name, + source.title, + str(start_dt.year), + str(start_dt.month), + str(start_dt.day), + str(start_dt.hour), + str(start_dt.minute), + ] + try: + done = self._runner(argv) + except (OSError, subprocess.SubprocessError) as exc: + raise _Unreadable(f"{source.id}: {type(exc).__name__}") from exc + if done.returncode != 0: + raise _Unreadable(f"{source.id}: osascript exited {done.returncode}") + output = done.stdout.decode("utf-8", errors="replace").strip() + if output == "NO_CALENDAR": + raise _Unreadable( + f"{source.id}: calendar {source.calendar_name!r} does not exist" + ) + if output == "FOUND": + exists = True + elif output == "NOT_FOUND": + exists = False + else: + raise _Unreadable(f"{source.id}: unexpected osascript output {output!r}") + return { + "id": source.id, + "type": source.type, + "present": exists, + "exists": exists, + "calendar_name": source.calendar_name, + "title": source.title, + "start_iso": source.start_iso, + "value": value_text(exists), + "value_type": "boolean", + } + def read(self) -> Optional[list[dict[str, Any]]]: """One read of every source, or ``None`` when any source is unreadable.""" cache: dict[str, dict[str, Any]] = {} @@ -343,8 +608,14 @@ def read(self) -> Optional[list[dict[str, Any]]]: records.append(self._read_file(source)) elif isinstance(source, MacosDefaultsSource): records.append(self._read_defaults(source, cache)) - else: + elif isinstance(source, WindowsRegistrySource): records.append(self._read_registry(source)) + elif isinstance(source, MacosNightShiftSource): + records.append(self._read_macos_night_shift(source)) + elif isinstance(source, WindowsNightLightSource): + records.append(self._read_windows_night_light(source)) + else: + records.append(self._read_macos_calendar_event(source)) except _Unreadable as exc: self.last_error = str(exc) return None @@ -392,9 +663,16 @@ def verify( "FileSource", "LocalStateSource", "LocalStateVerifier", + "MacosCalendarEventSource", "MacosDefaultsSource", + "MacosNightShiftSource", + "OSASCRIPT_BINARY", "REGISTRY_HIVES", "TEXT_LIMIT", + "WINDOWS_NIGHT_LIGHT_REG_PATH", + "WINDOWS_NIGHT_LIGHT_VALUE_NAME", + "WindowsNightLightSource", "WindowsRegistrySource", + "parse_windows_night_light_bytes", "value_text", ] diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index c26f3bfd4b..d3d0e8fdc7 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -1441,8 +1441,11 @@ "examples/claude-code-demo/policy.yaml", "examples/legacy_records/answers.demo.json", "examples/legacy_records/answers.ledger.demo.json", + "examples/local_state/macos-calendar-block/verify.yaml", + "examples/local_state/macos-night-shift/verify.yaml", "examples/local_state/notepad-save/verify.yaml", "examples/local_state/windows-dark-mode/verify.yaml", + "examples/local_state/windows-night-light/verify.yaml", "import_direction_debt.json", "import_layers.json", "import_layers_debt.json", diff --git a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json index 465fd41c4a..70311c3595 100644 --- a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json +++ b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json @@ -1069,7 +1069,7 @@ "type": "object" }, "AuthRef": { - "description": "A reference to an HTTP credential held OUTSIDE the config.\n\nExactly one auth style may be set:\n\n- ``bearer_env`` -- name of an env var holding a bearer token; resolves to\n ``Authorization: Bearer ``.\n- ``header`` + ``value_env`` -- an arbitrary auth header (e.g.\n ``X-API-Key``) whose VALUE comes from the named env var. Frappe-style\n ``Authorization: token :`` fits here too (put the whole\n value in the env var).\n- ``basic_env`` -- name of an env var holding ``user:password``; resolves\n to ``Authorization: Basic ``.\n\nNo field ever holds the secret itself -- only the env var NAME.", + "description": "A reference to an HTTP credential held OUTSIDE the config.\n\nExactly one auth style may be set:\n\n- ``bearer_env`` -- name of an env var holding a bearer token; resolves to\n ``Authorization: Bearer ``.\n- ``header`` + ``value_env`` -- an arbitrary auth header (e.g.\n ``X-API-Key``) whose VALUE comes from the named env var. Token-pair\n ``Authorization: token :`` fits here too (put the whole\n value in the env var).\n- ``basic_env`` -- name of an env var holding ``user:password``; resolves\n to ``Authorization: Basic ``.\n\nNo field ever holds the secret itself -- only the env var NAME.", "properties": { "bearer_env": { "anyOf": [ @@ -2413,7 +2413,10 @@ "discriminator": { "mapping": { "file": "#/$defs/FileSource", + "macos_calendar_event": "#/$defs/MacosCalendarEventSource", "macos_defaults": "#/$defs/MacosDefaultsSource", + "macos_night_shift": "#/$defs/MacosNightShiftSource", + "windows_night_light": "#/$defs/WindowsNightLightSource", "windows_registry": "#/$defs/WindowsRegistrySource" }, "propertyName": "type" @@ -2427,6 +2430,15 @@ }, { "$ref": "#/$defs/WindowsRegistrySource" + }, + { + "$ref": "#/$defs/MacosNightShiftSource" + }, + { + "$ref": "#/$defs/WindowsNightLightSource" + }, + { + "$ref": "#/$defs/MacosCalendarEventSource" } ] }, @@ -3247,6 +3259,48 @@ "title": "IdentitySection", "type": "object" }, + "MacosCalendarEventSource": { + "additionalProperties": false, + "description": "Read-only check for a macOS Calendar event matching calendar, title, and start.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_calendar_event", + "default": "macos_calendar_event", + "title": "Type", + "type": "string" + }, + "calendar_name": { + "maxLength": 255, + "minLength": 1, + "title": "Calendar Name", + "type": "string" + }, + "title": { + "maxLength": 255, + "minLength": 1, + "title": "Title", + "type": "string" + }, + "start_iso": { + "maxLength": 64, + "minLength": 10, + "title": "Start Iso", + "type": "string" + } + }, + "required": [ + "id", + "calendar_name", + "title", + "start_iso" + ], + "title": "MacosCalendarEventSource", + "type": "object" + }, "MacosDefaultsSource": { "additionalProperties": false, "description": "One key in a macOS preferences domain.", @@ -3280,6 +3334,27 @@ "title": "MacosDefaultsSource", "type": "object" }, + "MacosNightShiftSource": { + "additionalProperties": false, + "description": "Current macOS Night Shift enabled state via CoreBrightness (read-only).", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_night_shift", + "default": "macos_night_shift", + "title": "Type", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "MacosNightShiftSource", + "type": "object" + }, "OpenStep": { "additionalProperties": false, "description": "Open the record from a results list: the one row showing the identity.", @@ -4811,6 +4886,27 @@ "title": "ValueExpr", "type": "object" }, + "WindowsNightLightSource": { + "additionalProperties": false, + "description": "Current Windows Night Light enabled state via CloudStore registry Data bytes.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "windows_night_light", + "default": "windows_night_light", + "title": "Type", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "WindowsNightLightSource", + "type": "object" + }, "WindowsRegistrySource": { "additionalProperties": false, "description": "One value in the Windows registry.", @@ -5110,7 +5206,7 @@ "validation": { "$defs": { "AuthRef": { - "description": "A reference to an HTTP credential held OUTSIDE the config.\n\nExactly one auth style may be set:\n\n- ``bearer_env`` -- name of an env var holding a bearer token; resolves to\n ``Authorization: Bearer ``.\n- ``header`` + ``value_env`` -- an arbitrary auth header (e.g.\n ``X-API-Key``) whose VALUE comes from the named env var. Frappe-style\n ``Authorization: token :`` fits here too (put the whole\n value in the env var).\n- ``basic_env`` -- name of an env var holding ``user:password``; resolves\n to ``Authorization: Basic ``.\n\nNo field ever holds the secret itself -- only the env var NAME.", + "description": "A reference to an HTTP credential held OUTSIDE the config.\n\nExactly one auth style may be set:\n\n- ``bearer_env`` -- name of an env var holding a bearer token; resolves to\n ``Authorization: Bearer ``.\n- ``header`` + ``value_env`` -- an arbitrary auth header (e.g.\n ``X-API-Key``) whose VALUE comes from the named env var. Token-pair\n ``Authorization: token :`` fits here too (put the whole\n value in the env var).\n- ``basic_env`` -- name of an env var holding ``user:password``; resolves\n to ``Authorization: Basic ``.\n\nNo field ever holds the secret itself -- only the env var NAME.", "properties": { "bearer_env": { "anyOf": [ @@ -6133,7 +6229,10 @@ "discriminator": { "mapping": { "file": "#/$defs/FileSource", + "macos_calendar_event": "#/$defs/MacosCalendarEventSource", "macos_defaults": "#/$defs/MacosDefaultsSource", + "macos_night_shift": "#/$defs/MacosNightShiftSource", + "windows_night_light": "#/$defs/WindowsNightLightSource", "windows_registry": "#/$defs/WindowsRegistrySource" }, "propertyName": "type" @@ -6147,6 +6246,15 @@ }, { "$ref": "#/$defs/WindowsRegistrySource" + }, + { + "$ref": "#/$defs/MacosNightShiftSource" + }, + { + "$ref": "#/$defs/WindowsNightLightSource" + }, + { + "$ref": "#/$defs/MacosCalendarEventSource" } ] }, @@ -6563,6 +6671,48 @@ "title": "HistoryView", "type": "object" }, + "MacosCalendarEventSource": { + "additionalProperties": false, + "description": "Read-only check for a macOS Calendar event matching calendar, title, and start.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_calendar_event", + "default": "macos_calendar_event", + "title": "Type", + "type": "string" + }, + "calendar_name": { + "maxLength": 255, + "minLength": 1, + "title": "Calendar Name", + "type": "string" + }, + "title": { + "maxLength": 255, + "minLength": 1, + "title": "Title", + "type": "string" + }, + "start_iso": { + "maxLength": 64, + "minLength": 10, + "title": "Start Iso", + "type": "string" + } + }, + "required": [ + "id", + "calendar_name", + "title", + "start_iso" + ], + "title": "MacosCalendarEventSource", + "type": "object" + }, "MacosDefaultsSource": { "additionalProperties": false, "description": "One key in a macOS preferences domain.", @@ -6596,6 +6746,27 @@ "title": "MacosDefaultsSource", "type": "object" }, + "MacosNightShiftSource": { + "additionalProperties": false, + "description": "Current macOS Night Shift enabled state via CoreBrightness (read-only).", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "macos_night_shift", + "default": "macos_night_shift", + "title": "Type", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "MacosNightShiftSource", + "type": "object" + }, "OpenStep": { "additionalProperties": false, "description": "Open the record from a results list: the one row showing the identity.", @@ -7456,6 +7627,27 @@ "title": "ValueExpr", "type": "object" }, + "WindowsNightLightSource": { + "additionalProperties": false, + "description": "Current Windows Night Light enabled state via CloudStore registry Data bytes.", + "properties": { + "id": { + "title": "Id", + "type": "string" + }, + "type": { + "const": "windows_night_light", + "default": "windows_night_light", + "title": "Type", + "type": "string" + } + }, + "required": [ + "id" + ], + "title": "WindowsNightLightSource", + "type": "object" + }, "WindowsRegistrySource": { "additionalProperties": false, "description": "One value in the Windows registry.", diff --git a/packages/flow/tests/test_everyday_local_state_probes.py b/packages/flow/tests/test_everyday_local_state_probes.py new file mode 100644 index 0000000000..8c8271e9b6 --- /dev/null +++ b/packages/flow/tests/test_everyday_local_state_probes.py @@ -0,0 +1,439 @@ +"""Unit tests for read-only everyday OS local-state probes. + +Covers: +1. ``macos_night_shift`` (CoreBrightness ``CBBlueLightClient`` read-only probe) +2. ``windows_night_light`` (HKCU CloudStore ``Data`` bytes ``0x15`` vs ``0x13``) +3. ``macos_calendar_event`` (fixed read-only AppleScript probe via argv) + +Every probe is verified for valid states, malformed/missing inputs, and wrong-OS +fail-closed ``INDETERMINATE`` behavior. +""" + +from __future__ import annotations + +import subprocess +import sys +from pathlib import Path +from typing import Any + +import pytest + +from openadapt_flow.local_state_sources import ( + MacosCalendarEventSource, + MacosNightShiftSource, + WindowsNightLightSource, +) +from openadapt_flow.runtime.effects.effect import Effect, EffectKind, Verdict +from openadapt_flow.runtime.effects.local_state import ( + OSASCRIPT_BINARY, + WINDOWS_NIGHT_LIGHT_REG_PATH, + WINDOWS_NIGHT_LIGHT_VALUE_NAME, + LocalStateVerifier, + _Unreadable, + parse_windows_night_light_bytes, +) +from openadapt_flow.verify_run import VerifyConfig + + +class _FakeKey: + def __init__(self, values: dict[str, tuple[Any, int]]) -> None: + self._values = values + + def __enter__(self) -> "_FakeKey": + return self + + def __exit__(self, *args: object) -> None: + return None + + +class _FakeWinReg: + HKEY_CURRENT_USER = 1 + HKEY_LOCAL_MACHINE = 2 + KEY_READ = 0x20019 + REG_BINARY = 3 + + def __init__(self, tree: dict[tuple[int, str], dict[str, tuple[Any, int]]]) -> None: + self._tree = tree + + def OpenKey(self, hive: int, path: str, _reserved: int, access: int) -> _FakeKey: + assert access == self.KEY_READ, "registry reads must use KEY_READ only" + key = (hive, path) + if key not in self._tree: + raise FileNotFoundError(path) + return _FakeKey(self._tree[key]) + + def QueryValueEx(self, key: _FakeKey, name: str) -> tuple[Any, int]: + if name not in key._values: + raise FileNotFoundError(name) + return key._values[name] + + +def _make_cloudstore_blob(state_byte: int, length: int = 43) -> bytes: + buf = bytearray(length) + buf[0:4] = b"\x43\x42\x01\x00" + buf[18] = state_byte + if state_byte == 0x15 and length >= 25: + buf[23:25] = b"\x10\x00" + return bytes(buf) + + +# --- macos_night_shift ------------------------------------------------------ + + +def test_macos_night_shift_reads_enabled_and_disabled() -> None: + src = MacosNightShiftSource(id="ns") + v_on = LocalStateVerifier([src], platform="darwin", night_shift_reader=lambda: True) + rec_on = v_on.read() + assert rec_on == [ + { + "id": "ns", + "type": "macos_night_shift", + "present": True, + "enabled": True, + "value": "true", + "value_type": "boolean", + } + ] + + v_off = LocalStateVerifier( + [src], platform="darwin", night_shift_reader=lambda: False + ) + rec_off = v_off.read() + assert rec_off is not None + assert rec_off[0]["enabled"] is False + assert rec_off[0]["value"] == "false" + + +@pytest.mark.parametrize("bad_platform", ["linux", "win32"]) +def test_macos_night_shift_fails_closed_on_wrong_os(bad_platform: str) -> None: + src = MacosNightShiftSource(id="ns") + v = LocalStateVerifier( + [src], platform=bad_platform, night_shift_reader=lambda: True + ) + before = v.capture_pre_state() + assert before.reachable is False + assert v.read() is None + assert v.last_error is not None and "needs macOS" in v.last_error + + +def test_macos_night_shift_fails_closed_when_probe_unavailable() -> None: + src = MacosNightShiftSource(id="ns") + + def _boom() -> bool: + raise _Unreadable("CoreBrightness unavailable") + + v = LocalStateVerifier([src], platform="darwin", night_shift_reader=_boom) + before = v.capture_pre_state() + assert before.reachable is False + verdict = v.verify( + Effect( + kind=EffectKind.FIELD_EQUALS, + match={"id": "ns"}, + field="value", + value="true", + settle_timeout_s=0.0, + ), + before, + ) + assert verdict.confirmed is False + assert verdict.verdict == Verdict.INDETERMINATE + + +@pytest.mark.skipif(sys.platform != "darwin", reason="macOS-only live read-only probe") +def test_macos_night_shift_live_readonly_probe_on_mac() -> None: + """Exercise the real CoreBrightness ctypes reader read-only on macOS.""" + src = MacosNightShiftSource(id="ns") + v = LocalStateVerifier([src], platform="darwin") + records = v.read() + if records is None: + # On headless Macs without Night Shift hardware, probe must fail closed cleanly. + assert v.last_error is not None + else: + assert len(records) == 1 + assert isinstance(records[0]["enabled"], bool) + assert records[0]["value"] in ("true", "false") + + +# --- windows_night_light ---------------------------------------------------- + + +def test_parse_windows_night_light_bytes_valid_and_invalid() -> None: + assert parse_windows_night_light_bytes(_make_cloudstore_blob(0x15, 43)) is True + assert parse_windows_night_light_bytes(_make_cloudstore_blob(0x13, 41)) is False + + for bad in (b"", b"\x15" * 18, _make_cloudstore_blob(0x00, 41), "not-bytes", 123): + with pytest.raises(_Unreadable): + parse_windows_night_light_bytes(bad) + + +def test_windows_night_light_reads_enabled_and_disabled() -> None: + src = WindowsNightLightSource(id="nl") + reg_on = _FakeWinReg( + { + (_FakeWinReg.HKEY_CURRENT_USER, WINDOWS_NIGHT_LIGHT_REG_PATH): { + WINDOWS_NIGHT_LIGHT_VALUE_NAME: ( + _make_cloudstore_blob(0x15, 43), + _FakeWinReg.REG_BINARY, + ) + } + } + ) + v_on = LocalStateVerifier([src], platform="win32", registry=reg_on) + rec_on = v_on.read() + assert rec_on == [ + { + "id": "nl", + "type": "windows_night_light", + "present": True, + "enabled": True, + "value": "true", + "value_type": "boolean", + } + ] + + reg_off = _FakeWinReg( + { + (_FakeWinReg.HKEY_CURRENT_USER, WINDOWS_NIGHT_LIGHT_REG_PATH): { + WINDOWS_NIGHT_LIGHT_VALUE_NAME: ( + _make_cloudstore_blob(0x13, 41), + _FakeWinReg.REG_BINARY, + ) + } + } + ) + v_off = LocalStateVerifier([src], platform="win32", registry=reg_off) + rec_off = v_off.read() + assert rec_off is not None + assert rec_off[0]["enabled"] is False + assert rec_off[0]["value"] == "false" + + +def test_windows_night_light_fails_closed_on_missing_key_value_malformed_and_wrong_os() -> ( + None +): + src = WindowsNightLightSource(id="nl") + + # Wrong OS without injected registry + v_wrong_os = LocalStateVerifier([src], platform="darwin") + assert v_wrong_os.read() is None + + # Missing registry key + v_no_key = LocalStateVerifier([src], platform="win32", registry=_FakeWinReg({})) + assert v_no_key.read() is None + assert v_no_key.last_error is not None and "does not exist" in v_no_key.last_error + + # Missing Data value + v_no_val = LocalStateVerifier( + [src], + platform="win32", + registry=_FakeWinReg( + {(_FakeWinReg.HKEY_CURRENT_USER, WINDOWS_NIGHT_LIGHT_REG_PATH): {}} + ), + ) + assert v_no_val.read() is None + assert v_no_val.last_error is not None and "missing" in v_no_val.last_error + + # Malformed bytes -> INDETERMINATE + v_bad_bytes = LocalStateVerifier( + [src], + platform="win32", + registry=_FakeWinReg( + { + (_FakeWinReg.HKEY_CURRENT_USER, WINDOWS_NIGHT_LIGHT_REG_PATH): { + WINDOWS_NIGHT_LIGHT_VALUE_NAME: ( + _make_cloudstore_blob(0x99, 41), + _FakeWinReg.REG_BINARY, + ) + } + } + ), + ) + before = v_bad_bytes.capture_pre_state() + assert before.reachable is False + verdict = v_bad_bytes.verify( + Effect( + kind=EffectKind.FIELD_EQUALS, + match={"id": "nl"}, + field="value", + value="true", + settle_timeout_s=0.0, + ), + before, + ) + assert verdict.confirmed is False + assert verdict.verdict == Verdict.INDETERMINATE + + +# --- macos_calendar_event --------------------------------------------------- + + +def test_macos_calendar_event_found_and_not_found_and_argv_safety() -> None: + captured_argv: list[list[str]] = [] + + def _runner_found(argv: list[str]) -> subprocess.CompletedProcess[bytes]: + captured_argv.append(argv) + return subprocess.CompletedProcess(argv, 0, b"FOUND\n", b"") + + src = MacosCalendarEventSource( + id="cal", + calendar_name="Work", + title='Focus "Block" & Sync', + start_iso="2026-11-24T10:30:00", + ) + v_found = LocalStateVerifier([src], platform="darwin", runner=_runner_found) + rec = v_found.read() + assert rec == [ + { + "id": "cal", + "type": "macos_calendar_event", + "present": True, + "exists": True, + "calendar_name": "Work", + "title": 'Focus "Block" & Sync', + "start_iso": "2026-11-24T10:30:00", + "value": "true", + "value_type": "boolean", + } + ] + # Verify absolute osascript path and argv isolation (no string interpolation) + assert captured_argv[0][0] == OSASCRIPT_BINARY + assert captured_argv[0][3:] == [ + "--", + "Work", + 'Focus "Block" & Sync', + "2026", + "11", + "24", + "10", + "30", + ] + assert 'Focus "Block" & Sync' not in captured_argv[0][2] + + def _runner_not_found(argv: list[str]) -> subprocess.CompletedProcess[bytes]: + return subprocess.CompletedProcess(argv, 0, b"NOT_FOUND\n", b"") + + v_missing = LocalStateVerifier([src], platform="darwin", runner=_runner_not_found) + rec_missing = v_missing.read() + assert rec_missing is not None + assert rec_missing[0]["present"] is False + assert rec_missing[0]["exists"] is False + assert rec_missing[0]["value"] == "false" + + +def test_macos_calendar_event_fails_closed_on_errors_and_wrong_os() -> None: + src = MacosCalendarEventSource( + id="cal", + calendar_name="Calendar", + title="Standup", + start_iso="2026-11-24T09:00:00", + ) + + # Wrong OS + v_wrong = LocalStateVerifier( + [src], + platform="win32", + runner=lambda argv: subprocess.CompletedProcess(argv, 0, b"FOUND\n", b""), + ) + assert v_wrong.read() is None + + # Missing calendar container + v_no_cal = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess(argv, 0, b"NO_CALENDAR\n", b""), + ) + assert v_no_cal.read() is None + assert v_no_cal.last_error is not None and "does not exist" in v_no_cal.last_error + + # osascript error (e.g. Automation permission denied) + v_err = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess(argv, 1, b"", b"denied"), + ) + assert v_err.read() is None + + # Unexpected stdout + v_weird = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess(argv, 0, b"MAYBE\n", b""), + ) + assert v_weird.read() is None + + +def test_macos_calendar_event_validation_rejects_bad_inputs() -> None: + with pytest.raises(ValueError, match="control characters"): + MacosCalendarEventSource( + id="cal", + calendar_name="Calendar\nBad", + title="Ok", + start_iso="2026-11-24T09:00:00", + ) + with pytest.raises(ValueError, match="ISO-8601"): + MacosCalendarEventSource( + id="cal", + calendar_name="Calendar", + title="Ok", + start_iso="not-a-timestamp", + ) + + +def test_verify_config_accepts_all_three_new_source_types(tmp_path: Path) -> None: + for doc in ( + { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "local-state", + "local_state": [{"type": "macos_night_shift", "id": "ns"}], + }, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "ns"}, + "field": "value", + "value": "true", + } + ], + }, + { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "local-state", + "local_state": [{"type": "windows_night_light", "id": "nl"}], + }, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "nl"}, + "field": "value", + "value": "false", + } + ], + }, + { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "local-state", + "local_state": [ + { + "type": "macos_calendar_event", + "id": "cal", + "calendar_name": "Calendar", + "title": "Deep Work", + "start_iso": "2026-11-24T10:00:00", + } + ], + }, + "effects": [ + { + "kind": "field_equals", + "match": {"id": "cal"}, + "field": "value", + "value": "true", + } + ], + }, + ): + cfg = VerifyConfig.model_validate(doc) + assert cfg.verifier.kind == "local-state" diff --git a/tests/test_everyday_quickstart.py b/tests/test_everyday_quickstart.py new file mode 100644 index 0000000000..9a7a66e9c7 --- /dev/null +++ b/tests/test_everyday_quickstart.py @@ -0,0 +1,191 @@ +"""Tests for ``openadapt quickstart --task night-shift`` and ``--task calendar-block``.""" + +from __future__ import annotations + +import json +import subprocess +from pathlib import Path + +import pytest +import yaml +from click.testing import CliRunner +from openadapt_flow.runtime.effects.local_state import LocalStateVerifier +from openadapt_flow.verify_run import VerifyConfig + +from openadapt.cli import main +from openadapt.quickstart.everyday import ( + EverydayTaskError, + build_calendar_block_contracts, + build_night_shift_contracts, + run_everyday_task, +) + + +def test_build_night_shift_contracts_macos_and_windows_with_revert() -> None: + fwd_mac, rev_mac, params_mac = build_night_shift_contracts( + platform="darwin", baseline_enabled=False, revert=True + ) + assert fwd_mac["verifier"]["local_state"][0]["type"] == "macos_night_shift" + assert fwd_mac["effects"][0]["value"] == "true" + assert rev_mac is not None + assert rev_mac["effects"][0]["value"] == "false" + assert params_mac["target_enabled"] == "true" + assert params_mac["restore_enabled"] == "false" + VerifyConfig.model_validate(fwd_mac) + VerifyConfig.model_validate(rev_mac) + + fwd_win, rev_win, params_win = build_night_shift_contracts( + platform="win32", baseline_enabled=True, revert=False + ) + assert fwd_win["verifier"]["local_state"][0]["type"] == "windows_night_light" + assert fwd_win["effects"][0]["value"] == "false" + assert rev_win is None + assert params_win["revert"] is False + VerifyConfig.model_validate(fwd_win) + + with pytest.raises(EverydayTaskError, match="unsupported platform"): + build_night_shift_contracts(platform="linux") + + +def test_build_calendar_block_contracts_parameterized_and_revert() -> None: + fwd, rev, params = build_calendar_block_contracts( + title="Weekly Architecture Review", + calendar_name="Engineering", + start_iso="2026-11-24T14:00:00", + duration_minutes=45, + recurrence="weekly", + platform="darwin", + revert=True, + ) + src = fwd["verifier"]["local_state"][0] + assert src["type"] == "macos_calendar_event" + assert src["calendar_name"] == "Engineering" + assert src["title"] == "Weekly Architecture Review" + assert src["start_iso"] == "2026-11-24T14:00:00" + assert fwd["effects"][0]["value"] == "true" + assert rev is not None + assert rev["effects"][0]["value"] == "false" + assert params["end_iso"] == "2026-11-24T14:45:00" + assert params["duration_minutes"] == 45 + assert params["recurrence"] == "weekly" + VerifyConfig.model_validate(fwd) + VerifyConfig.model_validate(rev) + + with pytest.raises(EverydayTaskError, match="duration"): + build_calendar_block_contracts(duration_minutes=0, platform="darwin") + with pytest.raises(EverydayTaskError, match="recurrence"): + build_calendar_block_contracts(recurrence="yearly", platform="darwin") + with pytest.raises(EverydayTaskError, match="unsupported platform"): + build_calendar_block_contracts(platform="linux") + + +def test_run_everyday_task_night_shift_writes_contracts_and_probes_baseline( + tmp_path: Path, +) -> None: + lines: list[str] = [] + bundle = run_everyday_task( + "night-shift", + tmp_path / "ns", + platform="darwin", + revert=True, + say=lines.append, + verifier_factory=lambda sources, platform: LocalStateVerifier( + sources, platform=platform, night_shift_reader=lambda: False + ), + ) + assert bundle.baseline_state is not None + assert bundle.baseline_state["enabled"] is False + assert bundle.verify_path.is_file() + assert bundle.revert_verify_path is not None and bundle.revert_verify_path.is_file() + assert bundle.params_path.is_file() + + fwd = yaml.safe_load(bundle.verify_path.read_text(encoding="utf-8")) + rev = yaml.safe_load(bundle.revert_verify_path.read_text(encoding="utf-8")) + assert fwd["effects"][0]["value"] == "true" + assert rev["effects"][0]["value"] == "false" + assert any("Baseline probe (read-only)" in line for line in lines) + + +def test_run_everyday_task_calendar_block_writes_parameterized_bundle( + tmp_path: Path, +) -> None: + bundle = run_everyday_task( + "calendar-block", + tmp_path / "cal", + title="Focus Sprint", + calendar_name="Work", + start_iso="2026-11-24T11:00:00", + duration_minutes=60, + recurrence="weekdays", + revert=True, + platform="darwin", + say=lambda _msg: None, + verifier_factory=lambda sources, platform: LocalStateVerifier( + sources, + platform=platform, + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b"NOT_FOUND\n", b"" + ), + ), + ) + assert bundle.baseline_state is not None + assert bundle.baseline_state["exists"] is False + params = json.loads(bundle.params_path.read_text(encoding="utf-8")) + assert params["title"] == "Focus Sprint" + assert params["calendar_name"] == "Work" + assert params["end_iso"] == "2026-11-24T12:00:00" + assert params["recurrence"] == "weekdays" + assert bundle.revert_verify_path is not None and bundle.revert_verify_path.is_file() + + +def test_cli_quickstart_task_validation_and_invocation( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + runner = CliRunner() + + # Calendar flags without --task calendar-block are rejected + bad = runner.invoke(main, ["quickstart", "--title", "Standup"]) + assert bad.exit_code != 0 + assert "--task calendar-block" in bad.output + + # --task combined with --own is rejected + bad_own = runner.invoke(main, ["quickstart", "--own", "--task", "night-shift"]) + assert bad_own.exit_code != 0 + assert "cannot be combined" in bad_own.output + + # Stub baseline probe so CLI invocation is deterministic on any OS + monkeypatch.setattr( + "openadapt.quickstart.everyday._probe_baseline", + lambda doc, platform, verifier_factory=None: ( + {"type": "macos_calendar_event", "value": "false", "exists": False}, + None, + ), + ) + monkeypatch.setattr("openadapt.quickstart.everyday.sys.platform", "darwin") + + out_dir = tmp_path / "cli-cal" + ok = runner.invoke( + main, + [ + "quickstart", + "--task", + "calendar-block", + "--title", + "Deep Work", + "--duration", + "45", + "--recurrence", + "daily", + "--start", + "2026-11-24T15:00:00", + "--out", + str(out_dir), + ], + ) + assert ok.exit_code == 0, ok.output + assert (out_dir / "verify.yaml").is_file() + assert (out_dir / "revert_verify.yaml").is_file() + params = json.loads((out_dir / "task.json").read_text(encoding="utf-8")) + assert params["title"] == "Deep Work" + assert params["end_iso"] == "2026-11-24T15:45:00" + assert params["recurrence"] == "daily" From 3b4c46c4dd5ad53c7f7bc69012c3eca30cc8571a Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 10:39:47 -0500 Subject: [PATCH 10/11] fix(flow,quickstart): EventKit OS probe (no app name), local-tz conversion, opt-in baseline, withhold unknown revert, honest docs --- ...-built-in-os-everyday-tasks-night-shift.md | 2 +- openadapt/cli.py | 22 +- openadapt/quickstart/everyday.py | 86 +++++-- packages/flow/docs/LOCAL_STATE_CHECKS.md | 22 +- .../macos-calendar-block/verify.yaml | 8 +- .../openadapt_flow/local_state_sources.py | 65 +++++- .../runtime/effects/local_state.py | 213 ++++++++++++++---- .../openadapt_flow.deployment.json | 82 ++++++- .../tests/test_everyday_local_state_probes.py | 105 +++++++-- tests/test_everyday_quickstart.py | 82 ++++++- 10 files changed, 578 insertions(+), 109 deletions(-) diff --git a/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md b/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md index 9c12de20a5..7e042f20b7 100644 --- a/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md +++ b/capabilities/04-the-core-a-checked-entry-every-time/0096-verify-built-in-os-everyday-tasks-night-shift.md @@ -1 +1 @@ -| Verify built-in OS everyday tasks with zero sample apps or logins: `macos_night_shift` (read-only `CoreBrightness` `CBBlueLightClient`), `windows_night_light` (read-only `HKCU` CloudStore `Data` byte 18 `0x15`/`0x13`), and `macos_calendar_event` (fixed read-only AppleScript probe matching calendar, title, and start time), wired into `openadapt quickstart --task night-shift` and `--task calendar-block` with parameterized inputs and revert verification contracts; unreadable or unsupported hosts fail closed as `INDETERMINATE` | Experimental | Unit-tested across all 3 probes (enabled/disabled, malformed bytes, missing keys/calendars, wrong OS -> fail-closed `INDETERMINATE`), parameterized calendar compilation, revert contracts, and live read-only `macos_night_shift` probe on macOS | `openadapt quickstart --task`, [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `openadapt/quickstart/everyday.py`, `runtime/effects/local_state.py` | +| Generate read-only OS `local-state` verification contracts for built-in everyday tasks (`macos_night_shift` via private `CoreBrightness`, `windows_night_light` via `HKCU` CloudStore `Data` byte 18 heuristic, and `macos_calendar_event` via EventKit `EKEventStore` matching exact title, local-timezone start/end, recurrence, and optional `event_uid`), wired into `openadapt quickstart --task night-shift` and `--task calendar-block` (with opt-in `--probe-baseline` and withheld revert contract when baseline is unreadable); unreadable or unsupported hosts fail closed as `INDETERMINATE` | Experimental | Unit-tested across all 3 probes (enabled/disabled, malformed bytes, missing/ambiguous calendars, unauthorized EventKit, aware timezone conversion, wrong OS -> fail-closed `INDETERMINATE`) and contract generation; live Windows and end-to-end macOS toggle runs not yet recorded | `openadapt quickstart --task`, [LOCAL_STATE_CHECKS.md](packages/flow/docs/LOCAL_STATE_CHECKS.md), `openadapt/quickstart/everyday.py`, `runtime/effects/local_state.py` | diff --git a/openadapt/cli.py b/openadapt/cli.py index e9aea48e88..ebd7d3df6c 100644 --- a/openadapt/cli.py +++ b/openadapt/cli.py @@ -924,7 +924,19 @@ def ask(prompt: str) -> str: "--revert/--no-revert", default=True, show_default=True, - help="With --task: emit a revert/undo verification contract to leave the machine clean.", + help=( + "With --task: write a revert_verify.yaml check file to run after undoing " + "the change (withheld if Night Shift baseline is unreadable)." + ), +) +@click.option( + "--probe-baseline", + is_flag=True, + default=False, + help=( + "With --task calendar-block: run an opt-in read-only macOS EventKit " + "baseline check (requires Calendars privacy permission)." + ), ) @click.option("--headed", is_flag=True, hidden=True) @click.option("--headless", is_flag=True, hidden=True) @@ -948,6 +960,7 @@ def quickstart( duration_minutes: Optional[int], recurrence: Optional[str], revert: bool, + probe_baseline: bool, headed: bool, headless: bool, break_it: bool, @@ -980,10 +993,10 @@ def quickstart( opt is not None for opt in (title, calendar_name, start_iso, duration_minutes, recurrence) ) - if calendar_opts_used and task != "calendar-block": + if (calendar_opts_used or probe_baseline) and task != "calendar-block": raise click.UsageError( - "--title, --calendar, --start, --duration, and --recurrence require " - "--task calendar-block." + "--title, --calendar, --start, --duration, --recurrence, and " + "--probe-baseline require --task calendar-block." ) if task is not None: if own: @@ -1018,6 +1031,7 @@ def quickstart( recurrence if recurrence is not None else DEFAULT_RECURRENCE ), revert=revert, + probe_baseline=probe_baseline, say=click.echo, ) except EverydayTaskError as error: diff --git a/openadapt/quickstart/everyday.py b/openadapt/quickstart/everyday.py index 75739cdfb4..6258bfab87 100644 --- a/openadapt/quickstart/everyday.py +++ b/openadapt/quickstart/everyday.py @@ -1,15 +1,19 @@ """Built-in everyday OS quickstart tasks (zero sample apps, zero logins). -Provides parameterized task definitions and read-only ``local-state`` verification -contracts (including optional revert/undo contracts) for: +Generates parameterized task definitions and read-only ``local-state`` +verification contract files (``verify.yaml`` and, when baseline state is known, +``revert_verify.yaml``) for: 1. ``night-shift``: Toggle macOS Night Shift (``macos_night_shift``) or Windows Night Light (``windows_night_light``). -2. ``calendar-block``: Schedule a recurring Calendar block with parameterized - title, start/end time, duration, and recurrence (``macos_calendar_event``). - -Nothing in this module mutates OS settings or Calendar data; probes are strictly -read-only and fail closed when unreadable. +2. ``calendar-block``: Schedule a Calendar block with parameterized title, + start/end time, duration, and recurrence (``macos_calendar_event`` via + macOS EventKit). + +This module only writes contract/parameter files (it does not mutate OS +settings or Calendar data, and does not run the change or revert itself). +For ``calendar-block``, baseline probing is opt-in (``probe_baseline=True``) +so running quickstart never queries EventKit without explicit user intent. """ from __future__ import annotations @@ -89,8 +93,9 @@ def build_night_shift_contracts( ) target_enabled = (not baseline_enabled) if baseline_enabled is not None else True - restore_enabled = ( - baseline_enabled if baseline_enabled is not None else (not target_enabled) + # Never invent a revert baseline when the prior state is unreadable. + restore_enabled: Optional[bool] = ( + baseline_enabled if baseline_enabled is not None else None ) def _contract(expected_enabled: bool) -> dict[str, Any]: @@ -113,7 +118,9 @@ def _contract(expected_enabled: bool) -> dict[str, Any]: } forward = _contract(target_enabled) - revert_contract = _contract(restore_enabled) if revert else None + revert_contract = ( + _contract(restore_enabled) if (revert and restore_enabled is not None) else None + ) params: dict[str, Any] = { "task": "night-shift", "label": label, @@ -121,9 +128,15 @@ def _contract(expected_enabled: bool) -> dict[str, Any]: "source_type": source_type, "baseline_enabled": baseline_enabled, "target_enabled": "true" if target_enabled else "false", - "restore_enabled": "true" if restore_enabled else "false", + "restore_enabled": ( + ("true" if restore_enabled else "false") + if restore_enabled is not None + else None + ), "revert": revert, } + if revert and restore_enabled is None: + params["revert_withheld_reason"] = "baseline_indeterminate" return forward, revert_contract, params @@ -134,13 +147,14 @@ def build_calendar_block_contracts( start_iso: Optional[str] = None, duration_minutes: int = DEFAULT_DURATION_MINUTES, recurrence: str = DEFAULT_RECURRENCE, + event_uid: Optional[str] = None, platform: str = "darwin", revert: bool = True, ) -> tuple[dict[str, Any], Optional[dict[str, Any]], dict[str, Any]]: """Build parameterized forward and optional revert contracts for a Calendar block.""" if platform != "darwin": raise EverydayTaskError( - f"calendar-block local-state probe currently supports macOS Calendar; " + f"calendar-block local-state probe currently supports macOS EventKit; " f"unsupported platform {platform!r}" ) if not title or not title.strip(): @@ -159,13 +173,17 @@ def build_calendar_block_contracts( end_dt = start_dt + timedelta(minutes=duration_minutes) end_iso = end_dt.isoformat(timespec="seconds") - source_spec = { + source_spec: dict[str, Any] = { "type": "macos_calendar_event", "id": "calendar_block", "calendar_name": calendar_name.strip(), "title": title.strip(), "start_iso": resolved_start, + "end_iso": end_iso, + "recurrence": recurrence, } + if event_uid is not None and event_uid.strip(): + source_spec["event_uid"] = event_uid.strip() def _contract(expected_exists: bool) -> dict[str, Any]: return { @@ -175,7 +193,7 @@ def _contract(expected_exists: bool) -> dict[str, Any]: "kind": "local-state", "local_state": [source_spec], }, - "frame": {"target_fields": ["present", "exists", "value"]}, + "frame": {"target_fields": ["present", "exists", "event_uid", "value"]}, "effects": [ { "kind": "field_equals", @@ -197,6 +215,7 @@ def _contract(expected_exists: bool) -> dict[str, Any]: "end_iso": end_iso, "duration_minutes": duration_minutes, "recurrence": recurrence, + "event_uid": event_uid.strip() if event_uid and event_uid.strip() else None, "revert": revert, } return forward, revert_contract, params @@ -234,11 +253,12 @@ def run_everyday_task( duration_minutes: int = DEFAULT_DURATION_MINUTES, recurrence: str = DEFAULT_RECURRENCE, revert: bool = True, + probe_baseline: bool = False, platform: Optional[str] = None, say: Callable[[str], None] = print, verifier_factory: Optional[Callable[..., Any]] = None, ) -> EverydayTaskBundle: - """Prepare and baseline-probe a built-in everyday OS task into ``root``.""" + """Write parameterized verify/revert contracts for a built-in everyday OS task into ``root``.""" if task not in EVERYDAY_TASKS: raise EverydayTaskError( f"Unknown task {task!r}. Expected one of: {', '.join(EVERYDAY_TASKS)}" @@ -247,6 +267,7 @@ def run_everyday_task( active_platform = platform or sys.platform baseline_state: Optional[dict[str, Any]] = None probe_error: Optional[str] = None + probe_skipped = False if task == "night-shift": # Probe baseline first so the forward target flips the actual current state. @@ -277,9 +298,19 @@ def run_everyday_task( platform=active_platform, revert=revert, ) - baseline_state, probe_error = _probe_baseline( - forward, platform=active_platform, verifier_factory=verifier_factory - ) + if probe_baseline: + baseline_state, probe_error = _probe_baseline( + forward, platform=active_platform, verifier_factory=verifier_factory + ) + if baseline_state is not None and baseline_state.get("exists") is True: + raise EverydayTaskError( + "Refusing to generate calendar-block contracts: a matching event " + f"({title!r} at {params['start_iso']} in {calendar_name!r}) already " + "exists in the baseline. Choose a different --title or --start so " + "the revert check cannot target a pre-existing user event." + ) + else: + probe_skipped = True root.mkdir(parents=True, exist_ok=True) verify_path = root / "verify.yaml" @@ -298,7 +329,12 @@ def run_everyday_task( ) say(f"Everyday task: {task} ({active_platform})") - if baseline_state is not None: + if probe_skipped: + say( + " Baseline probe: skipped by default for calendar-block " + "(pass --probe-baseline to read macOS EventKit; requires Calendars permission)" + ) + elif baseline_state is not None: say( f" Baseline probe (read-only): {baseline_state['type']} -> " f"value={baseline_state.get('value')}" @@ -307,9 +343,17 @@ def run_everyday_task( say( f" Baseline probe (read-only): INDETERMINATE ({probe_error or 'unavailable'})" ) - say(f" Verify contract: {verify_path}") + say(f" Verify contract written: {verify_path} (run via openadapt-flow verify-run)") if revert_verify_path is not None: - say(f" Revert contract: {revert_verify_path} (leaves machine clean)") + say( + f" Revert contract written: {revert_verify_path} " + "(run via openadapt-flow verify-run after undoing the change)" + ) + elif revert and task == "night-shift": + say( + " Revert contract withheld: baseline was INDETERMINATE " + "(will not invent a prior Night Shift state)" + ) say(f" Task parameters: {params_path}") return EverydayTaskBundle( diff --git a/packages/flow/docs/LOCAL_STATE_CHECKS.md b/packages/flow/docs/LOCAL_STATE_CHECKS.md index da651eca9f..a5c5cf72f5 100644 --- a/packages/flow/docs/LOCAL_STATE_CHECKS.md +++ b/packages/flow/docs/LOCAL_STATE_CHECKS.md @@ -17,9 +17,9 @@ rules. It never runs a command you supply, and it never writes. | `file` | A file's contents | Ordinary read-only file I/O | `present`, `size`, `sha256`, `text` (UTF-8, files up to 1 MiB) | | `macos_defaults` | One key in a preferences domain | `/usr/bin/defaults export -` (goes through `cfprefsd`, so it sees the current value). Unit-tested only so far; not yet run on a real Mac | `present`, `value`, `value_type` | | `windows_registry` | One registry value under `HKCU` or `HKLM` | `winreg` with `KEY_READ` access only | `present`, `value`, `value_type` | -| `macos_night_shift` | Current macOS Night Shift enabled state | Read-only `CBBlueLightClient.getBlueLightStatus:` via `CoreBrightness` (`ctypes`/`libobjc`). Fails closed (`INDETERMINATE`) if unavailable | `present`, `enabled`, `value` (`"true"`/`"false"`), `value_type` | -| `windows_night_light` | Current Windows Night Light enabled state | Read-only `winreg` (`KEY_READ`) read of `HKCU\...\bluelightreductionstate` `Data` bytes (byte 18 `0x15` enabled vs `0x13` disabled). Fails closed on missing or unexpected bytes | `present`, `enabled`, `value` (`"true"`/`"false"`), `value_type` | -| `macos_calendar_event` | Whether a macOS Calendar event matching `(calendar_name, title, start_iso)` exists | Fixed read-only AppleScript via `/usr/bin/osascript` with argv parameters (never mutates Calendar). Fails closed if the calendar is missing or permission is denied | `present`, `exists`, `calendar_name`, `title`, `start_iso`, `value` (`"true"`/`"false"`), `value_type` | +| `macos_night_shift` | Current macOS Night Shift enabled state | Read-only `CBBlueLightClient.getBlueLightStatus:` via private `CoreBrightness` (`ctypes`/`libobjc`). Fails closed (`INDETERMINATE`) if unavailable; note private struct layout may change across macOS releases | `present`, `enabled`, `value` (`"true"`/`"false"`), `value_type` | +| `windows_night_light` | Current Windows Night Light enabled state | Read-only `winreg` (`KEY_READ`) read of `HKCU\...\bluelightreductionstate` `Data` bytes (byte 18 `0x15` enabled vs `0x13` disabled heuristic, unit-tested on synthetic blobs). Fails closed on missing or unexpected bytes | `present`, `enabled`, `value` (`"true"`/`"false"`), `value_type` | +| `macos_calendar_event` | Whether a macOS EventKit calendar event matching `(calendar_name, exact title, local start/end, recurrence, optional event_uid)` exists | Fixed read-only EventKit (`EKEventStore`) JXA probe via `/usr/bin/osascript -l JavaScript` with argv parameters (never launches or mutates Calendar.app). Fails closed if EventKit is unauthorized, calendar is missing, or multiple calendars share the name | `present`, `exists`, `event_uid`, `calendar_name`, `title`, `start_iso`, `end_iso`, `recurrence`, `value` (`"true"`/`"false"`), `value_type` | Each source becomes one record with the source's `id`, judged by the same effect kinds every other record check uses (`field_equals`, `record_written`). @@ -96,9 +96,9 @@ The examples live in [`examples/local_state/`](../examples/local_state/). | --- | --- | --- | | `notepad-save` | `~/openadapt-examples/note.txt`, text equals the note | End to end on Windows 11 in the lab: record, compile, replay, check `verified`. Turn Notepad's status bar off (View > Status bar) so replay can confirm the typing | | `windows-dark-mode` | `HKCU\...\Themes\Personalize` `AppsUseLightTheme` and `SystemUsesLightTheme` are `0` | Check only, on the real registry; see below | -| `macos-night-shift` | macOS Night Shift `enabled` state via `CoreBrightness` | Read-only probe verified on macOS; fail-closed unit-tested across platforms | -| `windows-night-light` | Windows Night Light `Data` byte 18 (`0x15` vs `0x13`) | Unit-tested against CloudStore blobs; fail-closed on missing or unexpected bytes | -| `macos-calendar-block` | macOS Calendar event matching `(calendar_name, title, start_iso)` | Fixed read-only AppleScript probe; unit-tested with fail-closed missing-calendar/error checks | +| `macos-night-shift` | macOS Night Shift `enabled` state via private `CoreBrightness` | Unit-tested across platforms (fail-closed when unavailable); not yet recorded across an end-to-end toggle run | +| `windows-night-light` | Windows Night Light `Data` byte 18 (`0x15` vs `0x13`) | Unit-tested against synthetic CloudStore blobs; fail-closed on missing or unexpected bytes; not yet recorded on a live Windows host | +| `macos-calendar-block` | macOS EventKit event matching `(calendar_name, title, start_iso, end_iso, recurrence, event_uid)` | Fixed read-only EventKit JXA probe; unit-tested with fail-closed unauthorized/missing/ambiguous-calendar and timezone checks | TextEdit and macOS Dark Mode follow the same pattern (a `file` source; a `macos_defaults` source on `NSGlobalDomain` `AppleInterfaceStyle`). They have @@ -109,10 +109,12 @@ no example yet because they haven't been run on a Mac. - **Notes (macOS).** The Notes database is private and protected by Full Disk Access, and reading arbitrary note bodies via AppleScript needs per-app Automation consent without a typed schema. There is no Notes source. -- **Calendar (macOS) without Automation permission.** `macos_calendar_event` - uses a fixed read-only AppleScript probe; if Calendar Automation consent is - not granted or the named calendar does not exist, it fails closed as - `INDETERMINATE`. +- **Calendar (macOS) without EventKit permission.** `macos_calendar_event` + uses a fixed read-only EventKit (`EKEventStore`) probe without launching + Calendar.app; if macOS Calendars privacy permission is not granted, the named + calendar does not exist, or multiple calendars share the name, it fails + closed as `INDETERMINATE`. In `openadapt quickstart --task calendar-block`, + baseline probing is opt-in (`--probe-baseline`). - **Night Shift (macOS) on unsupported displays.** `macos_night_shift` reads the private `CoreBrightness` framework (`CBBlueLightClient`); if the framework or display capability is unavailable, it fails closed as diff --git a/packages/flow/examples/local_state/macos-calendar-block/verify.yaml b/packages/flow/examples/local_state/macos-calendar-block/verify.yaml index d726f7bff1..e7cfc75cbd 100644 --- a/packages/flow/examples/local_state/macos-calendar-block/verify.yaml +++ b/packages/flow/examples/local_state/macos-calendar-block/verify.yaml @@ -1,5 +1,5 @@ -# Check a macOS Calendar event through a fixed, read-only AppleScript probe. -# Verifies whether an event matching (calendar_name, title, start_iso) exists. +# Check a macOS EventKit calendar event through a fixed, read-only EventKit probe. +# Verifies an event matching (calendar_name, exact title, start_iso, end_iso, recurrence). schema_version: openadapt.verify/v1 minimum_effect_strength: independent_system_of_record verifier: @@ -10,8 +10,10 @@ verifier: calendar_name: Calendar title: OpenAdapt Focus Block start_iso: "2026-11-24T10:00:00" + end_iso: "2026-11-24T10:30:00" + recurrence: weekly frame: - target_fields: [present, exists, value] + target_fields: [present, exists, event_uid, value] effects: - kind: field_equals match: {id: calendar_block} diff --git a/packages/flow/openadapt_flow/local_state_sources.py b/packages/flow/openadapt_flow/local_state_sources.py index 185d6f10db..8d238ac8ff 100644 --- a/packages/flow/openadapt_flow/local_state_sources.py +++ b/packages/flow/openadapt_flow/local_state_sources.py @@ -12,7 +12,7 @@ from datetime import datetime from typing import Literal, Union -from pydantic import BaseModel, ConfigDict, Field, field_validator +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator __all__ = [ "FileSource", @@ -110,13 +110,24 @@ class WindowsNightLightSource(_Source): class MacosCalendarEventSource(_Source): - """Read-only check for a macOS Calendar event matching calendar, title, and start.""" + """Read-only check for a macOS EventKit calendar event. + + Matches exact calendar name (rejecting ambiguous duplicates), case-sensitive + title, local-timezone start/end time to the minute, recurrence cadence, and + optional ``event_uid``. + """ type: Literal["macos_calendar_event"] = "macos_calendar_event" calendar_name: str = Field(min_length=1, max_length=255) title: str = Field(min_length=1, max_length=255) - #: ISO-8601 start timestamp (e.g. ``2026-11-24T10:00:00``). + #: ISO-8601 start timestamp (e.g. ``2026-11-24T10:00:00`` or aware ``...Z``). start_iso: str = Field(min_length=10, max_length=64) + #: Optional ISO-8601 end timestamp; when set, end time must also match to the minute. + end_iso: str | None = Field(default=None, min_length=10, max_length=64) + #: Expected recurrence cadence (``none``, ``daily``, ``weekly``, or ``weekdays``). + recurrence: Literal["none", "daily", "weekly", "weekdays"] = "none" + #: Optional EventKit event identifier to bind verification to one created event. + event_uid: str | None = Field(default=None, min_length=1, max_length=255) @field_validator("calendar_name", "title") @classmethod @@ -127,6 +138,17 @@ def _check_safe_text(cls, value: str) -> str: ) return value + @field_validator("event_uid") + @classmethod + def _check_event_uid(cls, value: str | None) -> str | None: + if value is None: + return None + if any(ord(ch) < 0x20 or ord(ch) == 0x7F for ch in value): + raise ValueError( + "macos_calendar_event event_uid must not contain control characters" + ) + return value + @field_validator("start_iso") @classmethod def _check_start_iso(cls, value: str) -> str: @@ -139,6 +161,43 @@ def _check_start_iso(cls, value: str) -> str: ) from exc return value + @field_validator("end_iso") + @classmethod + def _check_end_iso(cls, value: str | None) -> str | None: + if value is None: + return None + normalized = value[:-1] + "+00:00" if value.endswith("Z") else value + try: + datetime.fromisoformat(normalized) + except ValueError as exc: + raise ValueError( + "macos_calendar_event end_iso must be a valid ISO-8601 timestamp" + ) from exc + return value + + @model_validator(mode="after") + def _check_end_after_start(self) -> "MacosCalendarEventSource": + if self.end_iso is not None: + s_norm = ( + self.start_iso[:-1] + "+00:00" + if self.start_iso.endswith("Z") + else self.start_iso + ) + e_norm = ( + self.end_iso[:-1] + "+00:00" + if self.end_iso.endswith("Z") + else self.end_iso + ) + s_dt = datetime.fromisoformat(s_norm) + e_dt = datetime.fromisoformat(e_norm) + if (s_dt.tzinfo is None) != (e_dt.tzinfo is None): + raise ValueError( + "macos_calendar_event start_iso and end_iso must both be naive or both be timezone-aware" + ) + if e_dt <= s_dt: + raise ValueError("macos_calendar_event end_iso must be after start_iso") + return self + LocalStateSource = Union[ FileSource, diff --git a/packages/flow/openadapt_flow/runtime/effects/local_state.py b/packages/flow/openadapt_flow/runtime/effects/local_state.py index 28988e5a87..1b624142bc 100644 --- a/packages/flow/openadapt_flow/runtime/effects/local_state.py +++ b/packages/flow/openadapt_flow/runtime/effects/local_state.py @@ -115,31 +115,117 @@ _WINDOWS_NIGHT_LIGHT_ENABLED_BYTE = 0x15 _WINDOWS_NIGHT_LIGHT_DISABLED_BYTE = 0x13 -# Fixed read-only AppleScript: receives (calendar_name, title, year, month, -# day, hour, minute) via argv and never creates, modifies, or deletes events. -_MACOS_CALENDAR_READ_SCRIPT = """ -on run argv - set calName to item 1 of argv - set targetTitle to item 2 of argv - set targetYear to (item 3 of argv) as integer - set targetMonth to (item 4 of argv) as integer - set targetDay to (item 5 of argv) as integer - set targetHour to (item 6 of argv) as integer - set targetMinute to (item 7 of argv) as integer - tell application "Calendar" - if not (exists calendar calName) then - return "NO_CALENDAR" - end if - set matchingEvents to (every event of calendar calName whose summary is targetTitle) - repeat with ev in matchingEvents - set sd to start date of ev - if ((year of sd) is targetYear) and (((month of sd) as integer) is targetMonth) and ((day of sd) is targetDay) and ((hours of sd) is targetHour) and ((minutes of sd) is targetMinute) then - return "FOUND" - end if - end repeat - return "NOT_FOUND" - end tell -end run +# Fixed read-only EventKit (OS framework) JXA script: receives +# (calendar_name, title, start_y, start_m, start_d, start_h, start_min, +# end_y, end_m, end_d, end_h, end_min, recurrence, event_uid) via argv. +# Reads the OS EKEventStore directly without naming or launching any app, and +# fails closed when EventKit access is not authorized or calendar names collide. +_MACOS_EVENTKIT_READ_SCRIPT = """ +ObjC.import('EventKit'); +ObjC.import('Foundation'); +function run(argv) { + var calName = argv[0]; + var targetTitle = argv[1]; + var sYear = parseInt(argv[2], 10); + var sMonth = parseInt(argv[3], 10); + var sDay = parseInt(argv[4], 10); + var sHour = parseInt(argv[5], 10); + var sMin = parseInt(argv[6], 10); + var hasEnd = argv[7] !== ''; + var eYear = hasEnd ? parseInt(argv[7], 10) : 0; + var eMonth = hasEnd ? parseInt(argv[8], 10) : 0; + var eDay = hasEnd ? parseInt(argv[9], 10) : 0; + var eHour = hasEnd ? parseInt(argv[10], 10) : 0; + var eMin = hasEnd ? parseInt(argv[11], 10) : 0; + var recurrence = argv[12] || 'none'; + var targetUid = argv[13] || ''; + + var auth = $.EKEventStore.authorizationStatusForEntityType(0); + if (auth !== 3 && auth !== 4) { + return JSON.stringify({status: 'UNAUTHORIZED'}); + } + var store = $.EKEventStore.alloc.init; + var cals = store.calendarsForEntityType(0); + var matchedCals = []; + for (var i = 0; i < cals.count; i++) { + var c = cals.objectAtIndex(i); + if (ObjC.unwrap(c.title) === calName) { + matchedCals.push(c); + } + } + if (matchedCals.length === 0) { + return JSON.stringify({status: 'NO_CALENDAR'}); + } + if (matchedCals.length > 1) { + return JSON.stringify({status: 'AMBIGUOUS_CALENDAR'}); + } + + var startJs = new Date(sYear, sMonth - 1, sDay, sHour, sMin, 0); + var endJs = hasEnd + ? new Date(eYear, eMonth - 1, eDay, eHour, eMin, 0) + : new Date(startJs.getTime() + 3600000); + var winStart = $.NSDate.dateWithTimeIntervalSince1970((startJs.getTime() - 60000) / 1000.0); + var winEnd = $.NSDate.dateWithTimeIntervalSince1970((endJs.getTime() + 60000) / 1000.0); + var calArr = $.NSArray.arrayWithObject(matchedCals[0]); + var pred = store.predicateForEventsWithStartDateEndDateCalendars(winStart, winEnd, calArr); + var events = store.eventsMatchingPredicate(pred); + + function matchesRecurrence(ev, expected) { + var hasRules = Boolean(ev.hasRecurrenceRules); + if (expected === 'none') return !hasRules; + if (!hasRules) return false; + var rules = ev.recurrenceRules; + if (!rules || rules.count === 0) return false; + var rule = rules.objectAtIndex(0); + var freq = rule.frequency; + if (expected === 'daily') return freq === 0; + if (expected === 'weekly') return freq === 1; + if (expected === 'weekdays') { + if (freq !== 1) return false; + var days = rule.daysOfTheWeek; + if (!days || days.count !== 5) return false; + var seen = {}; + for (var d = 0; d < days.count; d++) { + seen[days.objectAtIndex(d).dayOfTheWeek] = true; + } + return Boolean(seen[2] && seen[3] && seen[4] && seen[5] && seen[6]); + } + return false; + } + + for (var j = 0; j < events.count; j++) { + var ev = events.objectAtIndex(j); + var title = ObjC.unwrap(ev.title); + if (title !== targetTitle) continue; + var uid = ObjC.unwrap(ev.eventIdentifier) || ''; + if (targetUid && uid !== targetUid) continue; + var sd = new Date(ev.startDate.timeIntervalSince1970 * 1000.0); + if ( + sd.getFullYear() !== sYear || + sd.getMonth() + 1 !== sMonth || + sd.getDate() !== sDay || + sd.getHours() !== sHour || + sd.getMinutes() !== sMin + ) { + continue; + } + if (hasEnd) { + var ed = new Date(ev.endDate.timeIntervalSince1970 * 1000.0); + if ( + ed.getFullYear() !== eYear || + ed.getMonth() + 1 !== eMonth || + ed.getDate() !== eDay || + ed.getHours() !== eHour || + ed.getMinutes() !== eMin + ) { + continue; + } + } + if (!matchesRecurrence(ev, recurrence)) continue; + return JSON.stringify({status: 'FOUND', event_uid: uid}); + } + return JSON.stringify({status: 'NOT_FOUND', event_uid: null}); +} """.strip() #: Registry hives a source may read. Per-user settings and machine settings; @@ -547,19 +633,33 @@ def _read_macos_calendar_event( ) -> dict[str, Any]: if self._platform != "darwin": raise _Unreadable(f"{source.id}: macos_calendar_event needs macOS") - normalized = ( - source.start_iso[:-1] + "+00:00" - if source.start_iso.endswith("Z") - else source.start_iso + + def _parse_local(iso_text: str, field_name: str) -> datetime: + normalized = ( + iso_text[:-1] + "+00:00" if iso_text.endswith("Z") else iso_text + ) + try: + parsed = datetime.fromisoformat(normalized) + except ValueError as exc: + raise _Unreadable(f"{source.id}: invalid {field_name}") from exc + # Convert timezone-aware timestamps to local system time so EventKit + # local wall-clock comparisons match regardless of input offset. + if parsed.tzinfo is not None: + parsed = parsed.astimezone() + return parsed + + start_dt = _parse_local(source.start_iso, "start_iso") + end_dt = ( + _parse_local(source.end_iso, "end_iso") + if source.end_iso is not None + else None ) - try: - start_dt = datetime.fromisoformat(normalized) - except ValueError as exc: - raise _Unreadable(f"{source.id}: invalid start_iso") from exc argv = [ OSASCRIPT_BINARY, + "-l", + "JavaScript", "-e", - _MACOS_CALENDAR_READ_SCRIPT, + _MACOS_EVENTKIT_READ_SCRIPT, "--", source.calendar_name, source.title, @@ -568,6 +668,13 @@ def _read_macos_calendar_event( str(start_dt.day), str(start_dt.hour), str(start_dt.minute), + str(end_dt.year) if end_dt is not None else "", + str(end_dt.month) if end_dt is not None else "", + str(end_dt.day) if end_dt is not None else "", + str(end_dt.hour) if end_dt is not None else "", + str(end_dt.minute) if end_dt is not None else "", + source.recurrence, + source.event_uid or "", ] try: done = self._runner(argv) @@ -576,24 +683,48 @@ def _read_macos_calendar_event( if done.returncode != 0: raise _Unreadable(f"{source.id}: osascript exited {done.returncode}") output = done.stdout.decode("utf-8", errors="replace").strip() - if output == "NO_CALENDAR": + try: + payload = json.loads(output) + except json.JSONDecodeError as exc: + raise _Unreadable( + f"{source.id}: unexpected EventKit probe output {output!r}" + ) from exc + if not isinstance(payload, dict): + raise _Unreadable( + f"{source.id}: EventKit probe output is not a JSON object" + ) + status = payload.get("status") + if status == "UNAUTHORIZED": + raise _Unreadable( + f"{source.id}: macOS EventKit calendar access not authorized" + ) + if status == "NO_CALENDAR": raise _Unreadable( f"{source.id}: calendar {source.calendar_name!r} does not exist" ) - if output == "FOUND": + if status == "AMBIGUOUS_CALENDAR": + raise _Unreadable( + f"{source.id}: multiple calendars named {source.calendar_name!r}; refusing ambiguous match" + ) + if status == "FOUND": exists = True - elif output == "NOT_FOUND": + elif status == "NOT_FOUND": exists = False else: - raise _Unreadable(f"{source.id}: unexpected osascript output {output!r}") + raise _Unreadable(f"{source.id}: unexpected EventKit status {status!r}") + raw_uid = payload.get("event_uid") + event_uid = str(raw_uid) if isinstance(raw_uid, str) and raw_uid else None return { "id": source.id, "type": source.type, "present": exists, "exists": exists, + "event_uid": event_uid, "calendar_name": source.calendar_name, "title": source.title, "start_iso": source.start_iso, + "end_iso": source.end_iso, + "recurrence": source.recurrence, "value": value_text(exists), "value_type": "boolean", } @@ -614,8 +745,12 @@ def read(self) -> Optional[list[dict[str, Any]]]: records.append(self._read_macos_night_shift(source)) elif isinstance(source, WindowsNightLightSource): records.append(self._read_windows_night_light(source)) - else: + elif isinstance(source, MacosCalendarEventSource): records.append(self._read_macos_calendar_event(source)) + else: + raise _Unreadable( + f"unsupported local-state source type: {type(source).__name__}" + ) except _Unreadable as exc: self.last_error = str(exc) return None diff --git a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json index 70311c3595..fb17d062c5 100644 --- a/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json +++ b/packages/flow/tests/fixtures/schema_surface/openadapt_flow.deployment.json @@ -3261,7 +3261,7 @@ }, "MacosCalendarEventSource": { "additionalProperties": false, - "description": "Read-only check for a macOS Calendar event matching calendar, title, and start.", + "description": "Read-only check for a macOS EventKit calendar event.\n\nMatches exact calendar name (rejecting ambiguous duplicates), case-sensitive\ntitle, local-timezone start/end time to the minute, recurrence cadence, and\noptional ``event_uid``.", "properties": { "id": { "title": "Id", @@ -3290,6 +3290,45 @@ "minLength": 10, "title": "Start Iso", "type": "string" + }, + "end_iso": { + "anyOf": [ + { + "maxLength": 64, + "minLength": 10, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "End Iso" + }, + "recurrence": { + "default": "none", + "enum": [ + "none", + "daily", + "weekly", + "weekdays" + ], + "title": "Recurrence", + "type": "string" + }, + "event_uid": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Event Uid" } }, "required": [ @@ -6673,7 +6712,7 @@ }, "MacosCalendarEventSource": { "additionalProperties": false, - "description": "Read-only check for a macOS Calendar event matching calendar, title, and start.", + "description": "Read-only check for a macOS EventKit calendar event.\n\nMatches exact calendar name (rejecting ambiguous duplicates), case-sensitive\ntitle, local-timezone start/end time to the minute, recurrence cadence, and\noptional ``event_uid``.", "properties": { "id": { "title": "Id", @@ -6702,6 +6741,45 @@ "minLength": 10, "title": "Start Iso", "type": "string" + }, + "end_iso": { + "anyOf": [ + { + "maxLength": 64, + "minLength": 10, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "End Iso" + }, + "recurrence": { + "default": "none", + "enum": [ + "none", + "daily", + "weekly", + "weekdays" + ], + "title": "Recurrence", + "type": "string" + }, + "event_uid": { + "anyOf": [ + { + "maxLength": 255, + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "title": "Event Uid" } }, "required": [ diff --git a/packages/flow/tests/test_everyday_local_state_probes.py b/packages/flow/tests/test_everyday_local_state_probes.py index 8c8271e9b6..7ea31a5997 100644 --- a/packages/flow/tests/test_everyday_local_state_probes.py +++ b/packages/flow/tests/test_everyday_local_state_probes.py @@ -11,8 +11,11 @@ from __future__ import annotations +import json +import os import subprocess import sys +from datetime import datetime from pathlib import Path from typing import Any @@ -139,7 +142,10 @@ def _boom() -> bool: assert verdict.verdict == Verdict.INDETERMINATE -@pytest.mark.skipif(sys.platform != "darwin", reason="macOS-only live read-only probe") +@pytest.mark.skipif( + sys.platform != "darwin" or os.environ.get("OPENADAPT_LIVE_OS_PROBES") != "1", + reason="opt-in macOS-only live CoreBrightness probe (set OPENADAPT_LIVE_OS_PROBES=1)", +) def test_macos_night_shift_live_readonly_probe_on_mac() -> None: """Exercise the real CoreBrightness ctypes reader read-only on macOS.""" src = MacosNightShiftSource(id="ns") @@ -267,18 +273,26 @@ def test_windows_night_light_fails_closed_on_missing_key_value_malformed_and_wro # --- macos_calendar_event --------------------------------------------------- -def test_macos_calendar_event_found_and_not_found_and_argv_safety() -> None: +def test_macos_calendar_event_found_not_found_timezone_and_argv_safety() -> None: captured_argv: list[list[str]] = [] def _runner_found(argv: list[str]) -> subprocess.CompletedProcess[bytes]: captured_argv.append(argv) - return subprocess.CompletedProcess(argv, 0, b"FOUND\n", b"") + return subprocess.CompletedProcess( + argv, + 0, + json.dumps({"status": "FOUND", "event_uid": "evt-uid-1"}).encode(), + b"", + ) src = MacosCalendarEventSource( id="cal", calendar_name="Work", title='Focus "Block" & Sync', start_iso="2026-11-24T10:30:00", + end_iso="2026-11-24T11:00:00", + recurrence="weekly", + event_uid="evt-uid-1", ) v_found = LocalStateVerifier([src], platform="darwin", runner=_runner_found) rec = v_found.read() @@ -288,16 +302,21 @@ def _runner_found(argv: list[str]) -> subprocess.CompletedProcess[bytes]: "type": "macos_calendar_event", "present": True, "exists": True, + "event_uid": "evt-uid-1", "calendar_name": "Work", "title": 'Focus "Block" & Sync', "start_iso": "2026-11-24T10:30:00", + "end_iso": "2026-11-24T11:00:00", + "recurrence": "weekly", "value": "true", "value_type": "boolean", } ] - # Verify absolute osascript path and argv isolation (no string interpolation) - assert captured_argv[0][0] == OSASCRIPT_BINARY - assert captured_argv[0][3:] == [ + # Verify absolute osascript path, JXA EventKit (zero app names), and argv isolation + assert captured_argv[0][0:4] == [OSASCRIPT_BINARY, "-l", "JavaScript", "-e"] + assert 'tell application "Calendar"' not in captured_argv[0][4] + assert 'Focus "Block" & Sync' not in captured_argv[0][4] + assert captured_argv[0][5:] == [ "--", "Work", 'Focus "Block" & Sync', @@ -306,18 +325,50 @@ def _runner_found(argv: list[str]) -> subprocess.CompletedProcess[bytes]: "24", "10", "30", + "2026", + "11", + "24", + "11", + "0", + "weekly", + "evt-uid-1", ] - assert 'Focus "Block" & Sync' not in captured_argv[0][2] - def _runner_not_found(argv: list[str]) -> subprocess.CompletedProcess[bytes]: - return subprocess.CompletedProcess(argv, 0, b"NOT_FOUND\n", b"") + # Timezone-aware UTC timestamp must be converted to local system time before argv + utc_src = MacosCalendarEventSource( + id="cal_tz", + calendar_name="Work", + title="UTC Block", + start_iso="2026-11-24T15:00:00Z", + end_iso="2026-11-24T15:30:00Z", + ) + tz_argv: list[list[str]] = [] + + def _runner_tz(argv: list[str]) -> subprocess.CompletedProcess[bytes]: + tz_argv.append(argv) + return subprocess.CompletedProcess( + argv, + 0, + json.dumps({"status": "NOT_FOUND", "event_uid": None}).encode(), + b"", + ) - v_missing = LocalStateVerifier([src], platform="darwin", runner=_runner_not_found) - rec_missing = v_missing.read() + v_tz = LocalStateVerifier([utc_src], platform="darwin", runner=_runner_tz) + rec_missing = v_tz.read() assert rec_missing is not None assert rec_missing[0]["present"] is False assert rec_missing[0]["exists"] is False assert rec_missing[0]["value"] == "false" + expected_local_start = datetime.fromisoformat( + "2026-11-24T15:00:00+00:00" + ).astimezone() + assert tz_argv[0][8:13] == [ + str(expected_local_start.year), + str(expected_local_start.month), + str(expected_local_start.day), + str(expected_local_start.hour), + str(expected_local_start.minute), + ] def test_macos_calendar_event_fails_closed_on_errors_and_wrong_os() -> None: @@ -332,20 +383,46 @@ def test_macos_calendar_event_fails_closed_on_errors_and_wrong_os() -> None: v_wrong = LocalStateVerifier( [src], platform="win32", - runner=lambda argv: subprocess.CompletedProcess(argv, 0, b"FOUND\n", b""), + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"FOUND","event_uid":"u1"}\n', b"" + ), ) assert v_wrong.read() is None + # Unauthorized EventKit + v_unauth = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"UNAUTHORIZED"}\n', b"" + ), + ) + assert v_unauth.read() is None + assert v_unauth.last_error is not None and "not authorized" in v_unauth.last_error + # Missing calendar container v_no_cal = LocalStateVerifier( [src], platform="darwin", - runner=lambda argv: subprocess.CompletedProcess(argv, 0, b"NO_CALENDAR\n", b""), + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"NO_CALENDAR"}\n', b"" + ), ) assert v_no_cal.read() is None assert v_no_cal.last_error is not None and "does not exist" in v_no_cal.last_error - # osascript error (e.g. Automation permission denied) + # Ambiguous duplicate calendar names + v_ambig = LocalStateVerifier( + [src], + platform="darwin", + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"AMBIGUOUS_CALENDAR"}\n', b"" + ), + ) + assert v_ambig.read() is None + assert v_ambig.last_error is not None and "multiple calendars" in v_ambig.last_error + + # osascript error v_err = LocalStateVerifier( [src], platform="darwin", diff --git a/tests/test_everyday_quickstart.py b/tests/test_everyday_quickstart.py index 9a7a66e9c7..8db1f1d9df 100644 --- a/tests/test_everyday_quickstart.py +++ b/tests/test_everyday_quickstart.py @@ -43,6 +43,14 @@ def test_build_night_shift_contracts_macos_and_windows_with_revert() -> None: assert params_win["revert"] is False VerifyConfig.model_validate(fwd_win) + # Unreadable baseline (None) must NOT invent a revert baseline + _fwd_unk, rev_unk, params_unk = build_night_shift_contracts( + platform="darwin", baseline_enabled=None, revert=True + ) + assert rev_unk is None + assert params_unk["restore_enabled"] is None + assert params_unk["revert_withheld_reason"] == "baseline_indeterminate" + with pytest.raises(EverydayTaskError, match="unsupported platform"): build_night_shift_contracts(platform="linux") @@ -106,12 +114,22 @@ def test_run_everyday_task_night_shift_writes_contracts_and_probes_baseline( assert any("Baseline probe (read-only)" in line for line in lines) -def test_run_everyday_task_calendar_block_writes_parameterized_bundle( +def test_run_everyday_task_calendar_block_opt_in_probe_and_refuses_preexisting( tmp_path: Path, ) -> None: - bundle = run_everyday_task( + # 1. Default (probe_baseline=False) never invokes the EventKit probe + probe_called = False + + def _should_not_run(*_args: object, **_kwargs: object) -> object: + nonlocal probe_called + probe_called = True + raise AssertionError( + "baseline probe must not run by default for calendar-block" + ) + + bundle_default = run_everyday_task( "calendar-block", - tmp_path / "cal", + tmp_path / "cal-default", title="Focus Sprint", calendar_name="Work", start_iso="2026-11-24T11:00:00", @@ -120,22 +138,62 @@ def test_run_everyday_task_calendar_block_writes_parameterized_bundle( revert=True, platform="darwin", say=lambda _msg: None, + verifier_factory=_should_not_run, + ) + assert probe_called is False + assert bundle_default.baseline_state is None + params = json.loads(bundle_default.params_path.read_text(encoding="utf-8")) + assert params["title"] == "Focus Sprint" + assert params["end_iso"] == "2026-11-24T12:00:00" + assert params["recurrence"] == "weekdays" + assert bundle_default.revert_verify_path is not None + + # 2. Opt-in probe_baseline=True with NOT_FOUND succeeds + bundle_probed = run_everyday_task( + "calendar-block", + tmp_path / "cal-probed", + title="Focus Sprint", + calendar_name="Work", + start_iso="2026-11-24T11:00:00", + duration_minutes=60, + recurrence="weekdays", + revert=True, + probe_baseline=True, + platform="darwin", + say=lambda _msg: None, verifier_factory=lambda sources, platform: LocalStateVerifier( sources, platform=platform, runner=lambda argv: subprocess.CompletedProcess( - argv, 0, b"NOT_FOUND\n", b"" + argv, 0, b'{"status":"NOT_FOUND","event_uid":null}\n', b"" ), ), ) - assert bundle.baseline_state is not None - assert bundle.baseline_state["exists"] is False - params = json.loads(bundle.params_path.read_text(encoding="utf-8")) - assert params["title"] == "Focus Sprint" - assert params["calendar_name"] == "Work" - assert params["end_iso"] == "2026-11-24T12:00:00" - assert params["recurrence"] == "weekdays" - assert bundle.revert_verify_path is not None and bundle.revert_verify_path.is_file() + assert bundle_probed.baseline_state is not None + assert bundle_probed.baseline_state["exists"] is False + + # 3. Opt-in probe_baseline=True when matching event ALREADY EXISTS refuses! + with pytest.raises(EverydayTaskError, match="already exists in the baseline"): + run_everyday_task( + "calendar-block", + tmp_path / "cal-existing", + title="Existing Meeting", + calendar_name="Work", + start_iso="2026-11-24T11:00:00", + duration_minutes=60, + recurrence="weekdays", + revert=True, + probe_baseline=True, + platform="darwin", + say=lambda _msg: None, + verifier_factory=lambda sources, platform: LocalStateVerifier( + sources, + platform=platform, + runner=lambda argv: subprocess.CompletedProcess( + argv, 0, b'{"status":"FOUND","event_uid":"existing-1"}\n', b"" + ), + ), + ) def test_cli_quickstart_task_validation_and_invocation( From bdbf657acc183311dba7ad5fcc80b10162e4b2c1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 17:15:05 -0500 Subject: [PATCH 11/11] fix(quickstart): guard optional local_state import against released openadapt-flow --- openadapt/quickstart/everyday.py | 10 ++++++++-- tests/test_everyday_quickstart.py | 29 ++++++++++++++++++++++------- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/openadapt/quickstart/everyday.py b/openadapt/quickstart/everyday.py index 9a28db819c..a45e3d9847 100644 --- a/openadapt/quickstart/everyday.py +++ b/openadapt/quickstart/everyday.py @@ -228,8 +228,14 @@ def _probe_baseline( verifier_factory: Optional[Callable[..., Any]] = None, ) -> tuple[Optional[dict[str, Any]], Optional[str]]: """Run the read-only ``local-state`` probe once without mutating OS state.""" - from openadapt_flow.runtime.effects.local_state import LocalStateVerifier - from openadapt_flow.verify_run import VerifyConfig + try: + from openadapt_flow.runtime.effects.local_state import LocalStateVerifier + from openadapt_flow.verify_run import VerifyConfig + except ImportError as exc: + return ( + None, + f"local_state verifier unavailable in installed openadapt-flow: {exc}", + ) cfg = VerifyConfig.model_validate(verify_doc) sources = list(cfg.verifier.local_state or []) diff --git a/tests/test_everyday_quickstart.py b/tests/test_everyday_quickstart.py index 1efa4abec0..fe02c9e575 100644 --- a/tests/test_everyday_quickstart.py +++ b/tests/test_everyday_quickstart.py @@ -9,8 +9,6 @@ import pytest import yaml from click.testing import CliRunner -from openadapt_flow.runtime.effects.local_state import LocalStateVerifier -from openadapt_flow.verify_run import VerifyConfig from openadapt.cli import main from openadapt.quickstart.everyday import ( @@ -20,6 +18,18 @@ run_everyday_task, ) +try: + from openadapt_flow.runtime.effects.local_state import LocalStateVerifier + from openadapt_flow.verify_run import VerifyConfig +except ImportError: # launcher CI installs released openadapt-flow without local_state + LocalStateVerifier = None # type: ignore[assignment] + VerifyConfig = None # type: ignore[assignment] + +_REQUIRES_LOCAL_STATE = pytest.mark.skipif( + LocalStateVerifier is None, + reason="openadapt_flow.runtime.effects.local_state not in installed openadapt-flow", +) + def test_build_night_shift_contracts_macos_and_windows_with_revert() -> None: fwd_mac, rev_mac, params_mac = build_night_shift_contracts( @@ -31,8 +41,9 @@ def test_build_night_shift_contracts_macos_and_windows_with_revert() -> None: assert rev_mac["effects"][0]["value"] == "false" assert params_mac["target_enabled"] == "true" assert params_mac["restore_enabled"] == "false" - VerifyConfig.model_validate(fwd_mac) - VerifyConfig.model_validate(rev_mac) + if LocalStateVerifier is not None and VerifyConfig is not None: + VerifyConfig.model_validate(fwd_mac) + VerifyConfig.model_validate(rev_mac) fwd_win, rev_win, params_win = build_night_shift_contracts( platform="win32", baseline_enabled=True, revert=False @@ -41,7 +52,8 @@ def test_build_night_shift_contracts_macos_and_windows_with_revert() -> None: assert fwd_win["effects"][0]["value"] == "false" assert rev_win is None assert params_win["revert"] is False - VerifyConfig.model_validate(fwd_win) + if LocalStateVerifier is not None and VerifyConfig is not None: + VerifyConfig.model_validate(fwd_win) # Unreadable baseline (None) must NOT invent a revert baseline _fwd_unk, rev_unk, params_unk = build_night_shift_contracts( @@ -76,8 +88,9 @@ def test_build_calendar_block_contracts_parameterized_and_revert() -> None: assert params["end_iso"] == "2026-11-24T14:45:00" assert params["duration_minutes"] == 45 assert params["recurrence"] == "weekly" - VerifyConfig.model_validate(fwd) - VerifyConfig.model_validate(rev) + if LocalStateVerifier is not None and VerifyConfig is not None: + VerifyConfig.model_validate(fwd) + VerifyConfig.model_validate(rev) with pytest.raises(EverydayTaskError, match="duration"): build_calendar_block_contracts(duration_minutes=0, platform="darwin") @@ -87,6 +100,7 @@ def test_build_calendar_block_contracts_parameterized_and_revert() -> None: build_calendar_block_contracts(platform="linux") +@_REQUIRES_LOCAL_STATE def test_run_everyday_task_night_shift_writes_contracts_and_probes_baseline( tmp_path: Path, ) -> None: @@ -114,6 +128,7 @@ def test_run_everyday_task_night_shift_writes_contracts_and_probes_baseline( assert any("Baseline probe (read-only)" in line for line in lines) +@_REQUIRES_LOCAL_STATE def test_run_everyday_task_calendar_block_opt_in_probe_and_refuses_preexisting( tmp_path: Path, ) -> None: