From df7bb7602c021353f45c1cca41e9263d0e945dcf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 00:05:50 -0500 Subject: [PATCH 1/8] 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 2/8] 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 3/8] 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 4/8] 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 5/8] 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 6/8] 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 7/8] 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 8/8] 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",