From f0b77e0fac542be61550b28f2af88c4fee420f7b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:08:52 -0500 Subject: [PATCH 1/5] refactor(flow): move the replayer's settling concern to a mixin, unchanged --- packages/flow/docs/design/DECOMPOSITION.md | 2 +- .../openadapt_flow/runtime/replay/settling.py | 666 ++++++++++++++++++ .../flow/openadapt_flow/runtime/replayer.py | 550 +-------------- 3 files changed, 674 insertions(+), 544 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/replay/settling.py diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 2baa1c3f58..32028d90ec 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -605,7 +605,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 19229 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 18693 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6830 | diff --git a/packages/flow/openadapt_flow/runtime/replay/settling.py b/packages/flow/openadapt_flow/runtime/replay/settling.py new file mode 100644 index 0000000000..27ae5cb7c2 --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/replay/settling.py @@ -0,0 +1,666 @@ +# mypy: disable-error-code="empty-body" +"""Moved replayer code. + +Moved verbatim from ``openadapt_flow.runtime.replayer.Replayer`` by +scripts/extract_mixin.py (docs/design/DECOMPOSITION.md, section 4.1). +``_SettlingAndInterstitialsHost`` declares, for mypy only, what this code reads from the +Replayer it is mixed into. +""" + +from __future__ import annotations + +import hashlib +from contextlib import ExitStack +from datetime import datetime, timezone +from typing import TYPE_CHECKING, Any, Literal, Optional # noqa: F401 + +from openadapt_flow.backend import FreshActuationRequired, StructuralResolutionRefused +from openadapt_flow.interruptions import ( + LabelChangedDuringClick, + class_texts, + dismiss_label, + whole_interruption_error, +) +from openadapt_flow.ir import ( + ActionDeliveryUncertainty, + Interstitial, + InterstitialActionResult, + Resolution, +) +from openadapt_flow.runtime.effect_watch import EffectWatchReport, watch_effects +from openadapt_flow.runtime.replay._shared import _frame_viewport +from openadapt_flow.runtime.resolver import resolve +from openadapt_flow.runtime.step_timing import timed_span + +if TYPE_CHECKING: + from pathlib import Path + from typing import Callable, Mapping + + from openadapt_flow.backend import Backend + from openadapt_flow.ir import ( + Predicate, + Step, + StepResult, + StructuralHandle, + StructuralLocator, + Workflow, + ) + from openadapt_flow.runtime.authorization import RuntimeParamScalar + from openadapt_flow.runtime.effects import EffectVerifier + from openadapt_flow.runtime.replay._shared import _DeliveryResultT + + +class _SettlingAndInterstitialsHost: + _active_delivery_acknowledgers: tuple[Any, ...] + _asset_bytes: Any + + @staticmethod + def _canonical_interstitial_snapshot( + declarations: Any, + ) -> tuple[tuple[Interstitial, ...], tuple[str, ...]]: ... + def _deliver_backend_call( + self, result: StepResult, call: Callable[[], _DeliveryResultT] + ) -> _DeliveryResultT: ... + def _deliver_guarded_dismissal( + self, + result: StepResult, + event: InterstitialActionResult, + locator: StructuralLocator, + handle: Optional[StructuralHandle], + native_act: Callable[..., Any], + ) -> None: ... + def _delivery_authorization_refusal( + self, + workflow: Workflow, + params: Mapping[str, RuntimeParamScalar], + step: Step, + result: StepResult, + *, + interstitial: bool = False, + api_delivery: bool = False, + ) -> Optional[str]: ... + @staticmethod + def _describe_predicate(pred: Predicate) -> str: ... + + _durable_continuation_guard: Optional[Any] + _governed_asset_mutation: Optional[str] + + def _interruption_control_error( + self, it: Interstitial, resolution: Optional[Resolution] + ) -> Optional[str]: ... + + _interstitials: Any + + def _predicate_holds( + self, + pred: Predicate, + frame_png: bytes, + bundle_dir: Path, + params: Mapping[str, RuntimeParamScalar], + *, + workflow: Optional[Workflow] = None, + ) -> bool: ... + + _require_qualification_environment_current: Any + _runtime_interstitial_snapshot: Any + _runtime_interstitial_snapshot_error: Optional[str] + _runtime_interstitial_source: Any + _settle_seed: Optional[tuple[Any, int]] + _workflow_interstitial_snapshot: tuple[str, ...] + _workflow_interstitial_snapshot_error: Optional[str] + _workflow_interstitials: tuple[Interstitial, ...] + backend: Backend + effect_verifier: Optional[EffectVerifier] + poll_interval_s: float + settle_readiness_timeout_s: float + use_structural: bool + vision: Any + + +if TYPE_CHECKING: + _Base = _SettlingAndInterstitialsHost +else: + _Base = object + + +class SettlingAndInterstitials(_Base): + """Moved replayer code.""" + + @timed_span("settle") + def _settle_seeded(self) -> bytes: + """``vision.wait_settled`` that can extend the last settled run. + + Same contract as ``vision.wait_settled``: a fresh frame is always + captured and returned, and it counts as settled only after a run of + identical frames polled at the normal interval. When the previous + settle on this backend ended settled and no input was delivered since + (every input crosses ``_deliver_backend_call``, which bumps the + epoch), an identical fresh frame extends that already-observed run + instead of starting a new one, saving one poll interval. A changed + frame starts over exactly as before. + """ + + seed_entry = getattr(self, "_settle_seed", None) + self._settle_seed = None + epoch = getattr(self, "_actuation_epoch", 0) + seeded = getattr(self.vision, "wait_settled_seeded", None) + seed_type = getattr(self.vision, "SettleSeed", None) + if seeded is None or seed_type is None: + return self.vision.wait_settled(self.backend) + seed = None + if seed_entry is not None and seed_entry[1] == epoch: + seed = seed_entry[0] + result = seeded(self.backend, seed) + if result.settled and result.phash: + seed_kwargs: dict[str, Any] = {} + if getattr(result, "mode", "pixel") == "page": + seed_kwargs["png"] = result.png + self._settle_seed = ( + seed_type( + phash=result.phash, + stable_frames=result.stable_frames, + captured_at=result.captured_at, + **seed_kwargs, + ), + epoch, + ) + return result.png + + def _interstitial_declaration_mutation( + self, workflow: Optional[Workflow] + ) -> Optional[str]: + """Return a refusal when caller-owned declarations changed mid-run.""" + + snapshot_error = ( + self._runtime_interstitial_snapshot_error + or self._workflow_interstitial_snapshot_error + ) + if snapshot_error is not None: + return f"{snapshot_error} - refusing to emit an action; run aborted." + try: + _runtime, runtime_snapshot = self._canonical_interstitial_snapshot( + self._runtime_interstitial_source + ) + workflow_snapshot: tuple[str, ...] = () + if workflow is not None: + _workflow, workflow_snapshot = self._canonical_interstitial_snapshot( + workflow.interstitials + ) + except Exception as exc: + return ( + "Interstitial declarations changed after admission and are no " + f"longer valid ({type(exc).__name__}) - refusing to emit an " + "action; run aborted." + ) + if ( + runtime_snapshot != self._runtime_interstitial_snapshot + or workflow_snapshot != self._workflow_interstitial_snapshot + ): + return ( + "Interstitial declarations changed after admission - refusing " + "to emit an action under a stale authorization; run aborted." + ) + return None + + def _resettle_after_interstitial( + self, before_png: bytes + ) -> tuple[bytes, Optional[str]]: + """Require a settled frame after every automatic dismissal. + + Interstitial handling is itself opt-in, so unlike the legacy entry-frame + behavior there is no backwards-compatibility reason to accept a + proceed-anyway settle timeout here. A transient blank frame could make a + ``TEXT_ABSENT`` clearance pass immediately before the overlay returned. + """ + fn = getattr(self.vision, "wait_settled_result", None) + if not callable(fn): + return before_png, ( + "The configured vision facade cannot verify that the screen " + "settled after an interstitial dismissal - refusing to act; " + "run aborted." + ) + try: + result = fn( + self.backend, + interval_s=self.poll_interval_s, + timeout_s=self.settle_readiness_timeout_s, + ) + frame = result.png + settled = result.settled + if not isinstance(frame, bytes) or not isinstance(settled, bool): + raise TypeError("invalid settle result") + except Exception as exc: + return before_png, ( + "The screen readiness check failed after dismissing an " + f"interstitial ({type(exc).__name__}) - refusing to act; run " + "aborted." + ) + if not settled: + return frame, ( + "The screen did not settle after the interstitial dismissal " + f"within {self.settle_readiness_timeout_s:.1f}s - refusing to " + "verify clearance on a mid-transition frame or act beneath it; " + "run aborted." + ) + return frame, None + + @timed_span("postcondition") + def _handle_interstitials( + self, + step: Step, + before_png: bytes, + bundle_dir: Path, + params: Mapping[str, RuntimeParamScalar], + result: StepResult, + audit_events: list[InterstitialActionResult], + workflow: Optional[Workflow], + ) -> tuple[bytes, Optional[str]]: + """Detect + handle KNOWN interstitials on the entry frame (model-free). + + A detected interstitial with an explicitly reversible, + non-consequential dismissal (``dismiss_key`` / ``dismiss_anchor``) gets + one audited action followed by its declared visual clearance check. A + delivery/clearance failure, persistent detection, or a detected + interstitial with NO dismissal HALTs the run GRACEFULLY naming it. Returns + ``(frame, None)`` when the screen is clear, else ``(frame, halt_reason)``. + + Unknown / undeclared overlays are NOT guessed at here: one that covers + the step's target still HALTs safely downstream (the anchor does not + resolve). This method only automates the RECURRING, declared ones so + they do not force a babysit-the-queue halt every time they appear. + """ + mutation_error = self._interstitial_declaration_mutation(workflow) + if mutation_error is not None: + return before_png, mutation_error + interstitials = [*self._workflow_interstitials, *self._interstitials] + if not interstitials: + return before_png, None + + # Revalidate serialized values at the point of use. Pydantic validates + # construction/load, but models are intentionally mutable; an in-memory + # edit or model_construct must not bypass affirmative detection, visual + # clearance, Escape-only, or reversible/non-consequential policy. + validated: list[Interstitial] = [] + for candidate in interstitials: + try: + validated.append( + Interstitial.model_validate(candidate.model_dump(mode="python")) + ) + except Exception as exc: + return before_png, ( + f"Interstitial '{candidate.name}' has an invalid automatic " + f"dismissal declaration ({type(exc).__name__}) - refusing " + "to emit an action; run aborted." + ) + interstitials = validated + + handled_indices: set[int] = set() + while True: + mutation_error = self._interstitial_declaration_mutation(workflow) + if mutation_error is not None: + return before_png, mutation_error + active_index = next( + ( + index + for index, candidate in enumerate(interstitials) + if self._predicate_holds( + candidate.detect, + before_png, + bundle_dir, + params, + workflow=workflow, + ) + ), + None, + ) + # Detection invokes vision and can therefore cross a callback + # boundary. Recheck the caller-owned declarations before trusting + # its result or preparing an action. + mutation_error = self._interstitial_declaration_mutation(workflow) + if mutation_error is not None: + return before_png, mutation_error + if active_index is None: + return before_png, None + it = interstitials[active_index] + if active_index in handled_indices: + return before_png, ( + f"Interstitial '{it.name}' reappeared after a verified " + "dismissal in the same step - refusing an automatic retry; " + "run aborted." + ) + if len(handled_indices) >= len(interstitials): + return before_png, ( + "The interstitial dismissal bound was exhausted before the " + "step entry state became clear - refusing further automatic " + "actions; run aborted." + ) + if it.dismiss_key is None and it.dismiss_anchor is None: + # A known BLOCKING interstitial with no safe auto-dismissal. + return before_png, ( + f"Known blocking interstitial '{it.name}' is on screen " + f"({self._describe_predicate(it.detect)}) and declares no " + "automatic dismissal - refusing to act beneath it; run " + "aborted (handle it, then re-run)." + ) + if ( + it.risk != "reversible" + or it.consequential is not False + or it.clearance is None + or (it.dismiss_key is not None and it.dismiss_key != "Escape") + ): + # Defensive runtime check in addition to Pydantic validation: + # model_construct/in-memory mutation must never turn this into + # an ungoverned consequential or unverifiable action. + return before_png, ( + f"Interstitial '{it.name}' does not declare an automatic " + "dismissal that is reversible, non-consequential, and " + "visually verifiable - refusing to emit an action; run " + "aborted." + ) + + resolution: Optional[Resolution] = None + action: Literal["key", "click"] + if it.dismiss_key is not None: + action = "key" + else: + assert it.dismiss_anchor is not None + structural_only = ( + not it.dismiss_anchor.template.strip() + and it.dismiss_anchor.structural is not None + ) + structural = ( + self.backend + if self.use_structural + and hasattr(self.backend, "locate_structural") + else None + ) + if structural_only and structural is None: + return before_png, ( + f"Interstitial '{it.name}' requires a structural-only " + "dismissal, but this backend cannot perform structural " + "resolution - refusing an OCR/geometry/coordinate " + "downgrade; run aborted." + ) + template_png = self._asset_bytes( + bundle_dir, + it.dismiss_anchor.template, + workflow=workflow, + ) + if self._governed_asset_mutation is not None: + return before_png, self._governed_asset_mutation + res = resolve( + it.dismiss_anchor, + before_png, + self.vision, + None, # NEVER ground a dismissal: stay model-free + it.name, + template_png=template_png, + viewport=_frame_viewport(before_png), + structural=structural, + ) + if res is None: + return before_png, ( + f"Interstitial '{it.name}' detected " + f"({self._describe_predicate(it.detect)}) but its dismiss " + "control did not resolve on screen - refusing to act; run " + "aborted." + ) + resolution, _region = res + if structural_only and resolution.rung != "structural": + return before_png, ( + f"Interstitial '{it.name}' structural dismissal did not " + "resolve uniquely - refusing an OCR/geometry/coordinate " + "downgrade; run aborted." + ) + action = "click" + + # Resolution can invoke vision or a structural backend. A callback + # must not be able to replace the declaration between authorization + # and the audit-before-delivery boundary. + mutation_error = self._interstitial_declaration_mutation(workflow) + if mutation_error is not None: + return before_png, mutation_error + if it.effect_watch: + # Classify the whole interruption, never its button word: a + # business question dressed as a session prompt halts here, + # before any input. + reader = getattr(self.backend, "interruption_text", None) + locator = ( + it.dismiss_anchor.structural + if it.dismiss_anchor is not None + else None + ) + try: + whole = ( + reader(locator, class_texts(it)) if callable(reader) else None + ) + except Exception: # noqa: BLE001 - unreadable means unproven + whole = None + class_error = whole_interruption_error(it, whole) + if class_error is None and it.dismiss_anchor is not None: + # The declared label proves nothing until the control + # that will be clicked is shown to carry it. + class_error = self._interruption_control_error(it, resolution) + if class_error is not None: + return before_png, ( + f"Interruption '{it.name}' was not cleared: {class_error} " + "- refusing to act beneath it; run aborted." + ) + # Append BEFORE delivery: a backend exception can never create an + # unreported key/click attempt. The event carries the exact admitted + # policy and expected visual outcome. + event = InterstitialActionResult( + control_label=dismiss_label(it), + interstitial=it.name, + action=action, + key=it.dismiss_key, + expected_clearance=it.clearance, + resolution=resolution, + before_frame_sha256=hashlib.sha256(before_png).hexdigest(), + ) + audit_events.append(event) + handled_indices.add(active_index) + if workflow is not None: + authorization_error = self._delivery_authorization_refusal( + workflow, params, step, result, interstitial=True + ) + if authorization_error is not None: + event.error = authorization_error + return before_png, authorization_error + elif self._durable_continuation_guard is not None: + # Normal replay always supplies ``workflow``. Keep the shared + # continuation fence fail-closed for direct helper/test use as + # well: every backend input edge must cross the same lease. + try: + self._durable_continuation_guard.before_delivery() + self._active_delivery_acknowledgers = ( + self._durable_continuation_guard, + ) + except Exception as exc: # noqa: BLE001 - fencing boundary + result.failure_category = "continuation_preempted" + result.safety_halt = True + event.error = ( + f"durable continuation was preempted before delivery: {exc}" + ) + return before_png, event.error + watch_stack = ExitStack() + watch: Optional[EffectWatchReport] = None + if it.effect_watch: + # An interruption class is cleared only when the dismissal is + # proven write-free: every watcher this run has is up around + # it, or nothing is sent. + watched: list[EffectWatchReport] = [] + + def _record_watch() -> None: + # Registered first, so it runs after the watchers close + # on every exit, a failed delivery included. + if watched: + event.effect_watchers = list(watched[0].watchers) + event.write_attempts = list(watched[0].attempts) + event.requests_seen = list(watched[0].requests) + + watch_stack.callback(_record_watch) + watch = watch_stack.enter_context( + watch_effects(self.backend, self.effect_verifier) + ) + watched.append(watch) + if watch.refusal is not None: + watch_stack.close() + event.error = f"dismissal not watched: {watch.refusal}" + return before_png, ( + f"Interruption '{it.name}' can't be cleared: " + f"{watch.refusal} - refusing to act beneath it; run " + "aborted." + ) + with watch_stack: + try: + if it.dismiss_key is not None: + self._require_qualification_environment_current() + self._deliver_backend_call( + result, + lambda: self.backend.press(it.dismiss_key or "Escape"), + ) + else: + assert resolution is not None + assert it.dismiss_anchor is not None + if resolution.rung == "structural": + native_act = getattr(self.backend, "act_structural", None) + structural_anchor = it.dismiss_anchor.structural + if ( + not callable(native_act) + or resolution.structural_handle is None + or structural_anchor is None + ): + raise StructuralResolutionRefused( + "structural dismissal cannot be delivered " + "natively without a stable element handle" + ) + if it.effect_watch: + # Again at the last no-input boundary: the + # label may have changed since the check. + control_error = self._interruption_control_error( + it, resolution + ) + if control_error is not None: + raise StructuralResolutionRefused(control_error) + self._require_qualification_environment_current() + self._deliver_guarded_dismissal( + result, + event, + structural_anchor, + resolution.structural_handle, + native_act, + ) + else: + self._require_qualification_environment_current() + self._deliver_backend_call( + result, + lambda: native_act( + structural_anchor, + resolution.structural_handle, + ), + ) + else: + self._require_qualification_environment_current() + self._deliver_backend_call( + result, + lambda: self.backend.click( + int(resolution.point[0]), int(resolution.point[1]) + ), + ) + event.delivered = True + except Exception as exc: + if isinstance(exc, LabelChangedDuringClick): + # The press reached the page's guard, which blocked + # it: delivery was attempted, and nothing beneath + # the label change is trusted. + event.delivered = True + event.label_violations = list(exc.violations) + result.safety_halt = True + if not isinstance( + exc, (FreshActuationRequired, StructuralResolutionRefused) + ): + target_fingerprint = None + if ( + resolution is not None + and resolution.structural_handle is not None + ): + target_fingerprint = ( + resolution.structural_handle.target_fingerprint + ) + result.delivery_uncertainty = ActionDeliveryUncertainty( + operation="interstitial_dismiss", + native=( + resolution is not None + and resolution.rung == "structural" + ), + target_fingerprint=target_fingerprint, + observed_at=datetime.now(timezone.utc).isoformat(), + cause_type=type(exc).__name__, + ) + event.error = ( + "dismissal delivery failed " + f"({type(exc).__name__}); outcome is unknown" + ) + if it.effect_watch and str(exc): + event.error += f": {exc}" + return before_png, ( + f"Interstitial '{it.name}' dismissal delivery failed " + f"({type(exc).__name__}" + + (f": {exc}" if it.effect_watch and str(exc) else "") + + ") - refusing to act beneath it; run aborted." + ) + + before_png, settle_error = self._resettle_after_interstitial(before_png) + if watch is not None: + if watch.attempts: + event.after_frame_sha256 = hashlib.sha256(before_png).hexdigest() + event.error = "the dismissal tried to write" + result.safety_halt = True + return before_png, ( + f"Interruption '{it.name}': its dismissal tried to " + f"write ({'; '.join(watch.attempts)}) - it is not a " + "benign interruption; refusing to continue; run aborted." + ) + event.after_frame_sha256 = hashlib.sha256(before_png).hexdigest() + if settle_error is not None: + event.error = settle_error + return before_png, settle_error + + clearance_holds = self._predicate_holds( + it.clearance, + before_png, + bundle_dir, + params, + workflow=workflow, + ) + if self._governed_asset_mutation is not None: + event.clearance_ok = False + event.error = self._governed_asset_mutation + return before_png, self._governed_asset_mutation + still_detected = False + if clearance_holds: + still_detected = self._predicate_holds( + it.detect, + before_png, + bundle_dir, + params, + workflow=workflow, + ) + if self._governed_asset_mutation is not None: + event.clearance_ok = False + event.error = self._governed_asset_mutation + return before_png, self._governed_asset_mutation + event.clearance_ok = clearance_holds and not still_detected + event.ok = event.delivered and event.clearance_ok + if not event.ok: + event.error = ( + "declared visual clearance did not hold" + if not clearance_holds + else "interstitial remained detected after dismissal" + ) + return before_png, ( + f"Interstitial '{it.name}' did not satisfy its declared " + "visual clearance after one dismissal - refusing a blind " + "retry or action beneath it; run aborted." + ) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 4e7c5054da..0ec215ccbe 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -49,7 +49,7 @@ import time import uuid from collections import Counter -from contextlib import ExitStack +from contextlib import ExitStack # noqa: F401 from copy import deepcopy from dataclasses import dataclass # noqa: F401 from datetime import datetime, timezone @@ -101,7 +101,7 @@ normalize_signal_text, parameterize_identity_text, ) -from openadapt_flow.interruptions import ( +from openadapt_flow.interruptions import ( # noqa: F401 LabelChangedDuringClick, class_texts, dismiss_label, @@ -227,7 +227,7 @@ from openadapt_flow.runtime.durable.program_checkpoint import ( history_hash as _history_hash, ) -from openadapt_flow.runtime.effect_watch import EffectWatchReport, watch_effects +from openadapt_flow.runtime.effect_watch import EffectWatchReport, watch_effects # noqa: F401 from openadapt_flow.runtime.effects import ( Effect, EffectState, @@ -347,9 +347,12 @@ from openadapt_flow.runtime.replay.qualification_faults import ( QualificationFaultInjection, ) +from openadapt_flow.runtime.replay.settling import SettlingAndInterstitials -class Replayer(QualificationFaultInjection, AssetsHealingAndEvidence): +class Replayer( + QualificationFaultInjection, AssetsHealingAndEvidence, SettlingAndInterstitials +): """Replays a Workflow against a Backend using injected vision. Args: @@ -11495,46 +11498,6 @@ def _resolve_drag_end( ) return resolution, region, error - @timed_span("settle") - def _settle_seeded(self) -> bytes: - """``vision.wait_settled`` that can extend the last settled run. - - Same contract as ``vision.wait_settled``: a fresh frame is always - captured and returned, and it counts as settled only after a run of - identical frames polled at the normal interval. When the previous - settle on this backend ended settled and no input was delivered since - (every input crosses ``_deliver_backend_call``, which bumps the - epoch), an identical fresh frame extends that already-observed run - instead of starting a new one, saving one poll interval. A changed - frame starts over exactly as before. - """ - - seed_entry = getattr(self, "_settle_seed", None) - self._settle_seed = None - epoch = getattr(self, "_actuation_epoch", 0) - seeded = getattr(self.vision, "wait_settled_seeded", None) - seed_type = getattr(self.vision, "SettleSeed", None) - if seeded is None or seed_type is None: - return self.vision.wait_settled(self.backend) - seed = None - if seed_entry is not None and seed_entry[1] == epoch: - seed = seed_entry[0] - result = seeded(self.backend, seed) - if result.settled and result.phash: - seed_kwargs: dict[str, Any] = {} - if getattr(result, "mode", "pixel") == "page": - seed_kwargs["png"] = result.png - self._settle_seed = ( - seed_type( - phash=result.phash, - stable_frames=result.stable_frames, - captured_at=result.captured_at, - **seed_kwargs, - ), - epoch, - ) - return result.png - def _deliver_backend_call( self, result: StepResult, @@ -13935,42 +13898,6 @@ def _interruption_control_error( ) return live_control_error(it, self.backend, resolution.structural_handle) - def _interstitial_declaration_mutation( - self, workflow: Optional[Workflow] - ) -> Optional[str]: - """Return a refusal when caller-owned declarations changed mid-run.""" - - snapshot_error = ( - self._runtime_interstitial_snapshot_error - or self._workflow_interstitial_snapshot_error - ) - if snapshot_error is not None: - return f"{snapshot_error} - refusing to emit an action; run aborted." - try: - _runtime, runtime_snapshot = self._canonical_interstitial_snapshot( - self._runtime_interstitial_source - ) - workflow_snapshot: tuple[str, ...] = () - if workflow is not None: - _workflow, workflow_snapshot = self._canonical_interstitial_snapshot( - workflow.interstitials - ) - except Exception as exc: - return ( - "Interstitial declarations changed after admission and are no " - f"longer valid ({type(exc).__name__}) - refusing to emit an " - "action; run aborted." - ) - if ( - runtime_snapshot != self._runtime_interstitial_snapshot - or workflow_snapshot != self._workflow_interstitial_snapshot - ): - return ( - "Interstitial declarations changed after admission - refusing " - "to emit an action under a stale authorization; run aborted." - ) - return None - @timed_span("settle") def _wait_starting_state_settled( self, before_png: bytes @@ -14257,469 +14184,6 @@ def _require_locale_invariants_before_keyboard( return exc.reason return None - def _resettle_after_interstitial( - self, before_png: bytes - ) -> tuple[bytes, Optional[str]]: - """Require a settled frame after every automatic dismissal. - - Interstitial handling is itself opt-in, so unlike the legacy entry-frame - behavior there is no backwards-compatibility reason to accept a - proceed-anyway settle timeout here. A transient blank frame could make a - ``TEXT_ABSENT`` clearance pass immediately before the overlay returned. - """ - fn = getattr(self.vision, "wait_settled_result", None) - if not callable(fn): - return before_png, ( - "The configured vision facade cannot verify that the screen " - "settled after an interstitial dismissal - refusing to act; " - "run aborted." - ) - try: - result = fn( - self.backend, - interval_s=self.poll_interval_s, - timeout_s=self.settle_readiness_timeout_s, - ) - frame = result.png - settled = result.settled - if not isinstance(frame, bytes) or not isinstance(settled, bool): - raise TypeError("invalid settle result") - except Exception as exc: - return before_png, ( - "The screen readiness check failed after dismissing an " - f"interstitial ({type(exc).__name__}) - refusing to act; run " - "aborted." - ) - if not settled: - return frame, ( - "The screen did not settle after the interstitial dismissal " - f"within {self.settle_readiness_timeout_s:.1f}s - refusing to " - "verify clearance on a mid-transition frame or act beneath it; " - "run aborted." - ) - return frame, None - - @timed_span("postcondition") - def _handle_interstitials( - self, - step: Step, - before_png: bytes, - bundle_dir: Path, - params: Mapping[str, RuntimeParamScalar], - result: StepResult, - audit_events: list[InterstitialActionResult], - workflow: Optional[Workflow], - ) -> tuple[bytes, Optional[str]]: - """Detect + handle KNOWN interstitials on the entry frame (model-free). - - A detected interstitial with an explicitly reversible, - non-consequential dismissal (``dismiss_key`` / ``dismiss_anchor``) gets - one audited action followed by its declared visual clearance check. A - delivery/clearance failure, persistent detection, or a detected - interstitial with NO dismissal HALTs the run GRACEFULLY naming it. Returns - ``(frame, None)`` when the screen is clear, else ``(frame, halt_reason)``. - - Unknown / undeclared overlays are NOT guessed at here: one that covers - the step's target still HALTs safely downstream (the anchor does not - resolve). This method only automates the RECURRING, declared ones so - they do not force a babysit-the-queue halt every time they appear. - """ - mutation_error = self._interstitial_declaration_mutation(workflow) - if mutation_error is not None: - return before_png, mutation_error - interstitials = [*self._workflow_interstitials, *self._interstitials] - if not interstitials: - return before_png, None - - # Revalidate serialized values at the point of use. Pydantic validates - # construction/load, but models are intentionally mutable; an in-memory - # edit or model_construct must not bypass affirmative detection, visual - # clearance, Escape-only, or reversible/non-consequential policy. - validated: list[Interstitial] = [] - for candidate in interstitials: - try: - validated.append( - Interstitial.model_validate(candidate.model_dump(mode="python")) - ) - except Exception as exc: - return before_png, ( - f"Interstitial '{candidate.name}' has an invalid automatic " - f"dismissal declaration ({type(exc).__name__}) - refusing " - "to emit an action; run aborted." - ) - interstitials = validated - - handled_indices: set[int] = set() - while True: - mutation_error = self._interstitial_declaration_mutation(workflow) - if mutation_error is not None: - return before_png, mutation_error - active_index = next( - ( - index - for index, candidate in enumerate(interstitials) - if self._predicate_holds( - candidate.detect, - before_png, - bundle_dir, - params, - workflow=workflow, - ) - ), - None, - ) - # Detection invokes vision and can therefore cross a callback - # boundary. Recheck the caller-owned declarations before trusting - # its result or preparing an action. - mutation_error = self._interstitial_declaration_mutation(workflow) - if mutation_error is not None: - return before_png, mutation_error - if active_index is None: - return before_png, None - it = interstitials[active_index] - if active_index in handled_indices: - return before_png, ( - f"Interstitial '{it.name}' reappeared after a verified " - "dismissal in the same step - refusing an automatic retry; " - "run aborted." - ) - if len(handled_indices) >= len(interstitials): - return before_png, ( - "The interstitial dismissal bound was exhausted before the " - "step entry state became clear - refusing further automatic " - "actions; run aborted." - ) - if it.dismiss_key is None and it.dismiss_anchor is None: - # A known BLOCKING interstitial with no safe auto-dismissal. - return before_png, ( - f"Known blocking interstitial '{it.name}' is on screen " - f"({self._describe_predicate(it.detect)}) and declares no " - "automatic dismissal - refusing to act beneath it; run " - "aborted (handle it, then re-run)." - ) - if ( - it.risk != "reversible" - or it.consequential is not False - or it.clearance is None - or (it.dismiss_key is not None and it.dismiss_key != "Escape") - ): - # Defensive runtime check in addition to Pydantic validation: - # model_construct/in-memory mutation must never turn this into - # an ungoverned consequential or unverifiable action. - return before_png, ( - f"Interstitial '{it.name}' does not declare an automatic " - "dismissal that is reversible, non-consequential, and " - "visually verifiable - refusing to emit an action; run " - "aborted." - ) - - resolution: Optional[Resolution] = None - action: Literal["key", "click"] - if it.dismiss_key is not None: - action = "key" - else: - assert it.dismiss_anchor is not None - structural_only = ( - not it.dismiss_anchor.template.strip() - and it.dismiss_anchor.structural is not None - ) - structural = ( - self.backend - if self.use_structural - and hasattr(self.backend, "locate_structural") - else None - ) - if structural_only and structural is None: - return before_png, ( - f"Interstitial '{it.name}' requires a structural-only " - "dismissal, but this backend cannot perform structural " - "resolution - refusing an OCR/geometry/coordinate " - "downgrade; run aborted." - ) - template_png = self._asset_bytes( - bundle_dir, - it.dismiss_anchor.template, - workflow=workflow, - ) - if self._governed_asset_mutation is not None: - return before_png, self._governed_asset_mutation - res = resolve( - it.dismiss_anchor, - before_png, - self.vision, - None, # NEVER ground a dismissal: stay model-free - it.name, - template_png=template_png, - viewport=_frame_viewport(before_png), - structural=structural, - ) - if res is None: - return before_png, ( - f"Interstitial '{it.name}' detected " - f"({self._describe_predicate(it.detect)}) but its dismiss " - "control did not resolve on screen - refusing to act; run " - "aborted." - ) - resolution, _region = res - if structural_only and resolution.rung != "structural": - return before_png, ( - f"Interstitial '{it.name}' structural dismissal did not " - "resolve uniquely - refusing an OCR/geometry/coordinate " - "downgrade; run aborted." - ) - action = "click" - - # Resolution can invoke vision or a structural backend. A callback - # must not be able to replace the declaration between authorization - # and the audit-before-delivery boundary. - mutation_error = self._interstitial_declaration_mutation(workflow) - if mutation_error is not None: - return before_png, mutation_error - if it.effect_watch: - # Classify the whole interruption, never its button word: a - # business question dressed as a session prompt halts here, - # before any input. - reader = getattr(self.backend, "interruption_text", None) - locator = ( - it.dismiss_anchor.structural - if it.dismiss_anchor is not None - else None - ) - try: - whole = ( - reader(locator, class_texts(it)) if callable(reader) else None - ) - except Exception: # noqa: BLE001 - unreadable means unproven - whole = None - class_error = whole_interruption_error(it, whole) - if class_error is None and it.dismiss_anchor is not None: - # The declared label proves nothing until the control - # that will be clicked is shown to carry it. - class_error = self._interruption_control_error(it, resolution) - if class_error is not None: - return before_png, ( - f"Interruption '{it.name}' was not cleared: {class_error} " - "- refusing to act beneath it; run aborted." - ) - # Append BEFORE delivery: a backend exception can never create an - # unreported key/click attempt. The event carries the exact admitted - # policy and expected visual outcome. - event = InterstitialActionResult( - control_label=dismiss_label(it), - interstitial=it.name, - action=action, - key=it.dismiss_key, - expected_clearance=it.clearance, - resolution=resolution, - before_frame_sha256=hashlib.sha256(before_png).hexdigest(), - ) - audit_events.append(event) - handled_indices.add(active_index) - if workflow is not None: - authorization_error = self._delivery_authorization_refusal( - workflow, params, step, result, interstitial=True - ) - if authorization_error is not None: - event.error = authorization_error - return before_png, authorization_error - elif self._durable_continuation_guard is not None: - # Normal replay always supplies ``workflow``. Keep the shared - # continuation fence fail-closed for direct helper/test use as - # well: every backend input edge must cross the same lease. - try: - self._durable_continuation_guard.before_delivery() - self._active_delivery_acknowledgers = ( - self._durable_continuation_guard, - ) - except Exception as exc: # noqa: BLE001 - fencing boundary - result.failure_category = "continuation_preempted" - result.safety_halt = True - event.error = ( - f"durable continuation was preempted before delivery: {exc}" - ) - return before_png, event.error - watch_stack = ExitStack() - watch: Optional[EffectWatchReport] = None - if it.effect_watch: - # An interruption class is cleared only when the dismissal is - # proven write-free: every watcher this run has is up around - # it, or nothing is sent. - watched: list[EffectWatchReport] = [] - - def _record_watch() -> None: - # Registered first, so it runs after the watchers close - # on every exit, a failed delivery included. - if watched: - event.effect_watchers = list(watched[0].watchers) - event.write_attempts = list(watched[0].attempts) - event.requests_seen = list(watched[0].requests) - - watch_stack.callback(_record_watch) - watch = watch_stack.enter_context( - watch_effects(self.backend, self.effect_verifier) - ) - watched.append(watch) - if watch.refusal is not None: - watch_stack.close() - event.error = f"dismissal not watched: {watch.refusal}" - return before_png, ( - f"Interruption '{it.name}' can't be cleared: " - f"{watch.refusal} - refusing to act beneath it; run " - "aborted." - ) - with watch_stack: - try: - if it.dismiss_key is not None: - self._require_qualification_environment_current() - self._deliver_backend_call( - result, - lambda: self.backend.press(it.dismiss_key or "Escape"), - ) - else: - assert resolution is not None - assert it.dismiss_anchor is not None - if resolution.rung == "structural": - native_act = getattr(self.backend, "act_structural", None) - structural_anchor = it.dismiss_anchor.structural - if ( - not callable(native_act) - or resolution.structural_handle is None - or structural_anchor is None - ): - raise StructuralResolutionRefused( - "structural dismissal cannot be delivered " - "natively without a stable element handle" - ) - if it.effect_watch: - # Again at the last no-input boundary: the - # label may have changed since the check. - control_error = self._interruption_control_error( - it, resolution - ) - if control_error is not None: - raise StructuralResolutionRefused(control_error) - self._require_qualification_environment_current() - self._deliver_guarded_dismissal( - result, - event, - structural_anchor, - resolution.structural_handle, - native_act, - ) - else: - self._require_qualification_environment_current() - self._deliver_backend_call( - result, - lambda: native_act( - structural_anchor, - resolution.structural_handle, - ), - ) - else: - self._require_qualification_environment_current() - self._deliver_backend_call( - result, - lambda: self.backend.click( - int(resolution.point[0]), int(resolution.point[1]) - ), - ) - event.delivered = True - except Exception as exc: - if isinstance(exc, LabelChangedDuringClick): - # The press reached the page's guard, which blocked - # it: delivery was attempted, and nothing beneath - # the label change is trusted. - event.delivered = True - event.label_violations = list(exc.violations) - result.safety_halt = True - if not isinstance( - exc, (FreshActuationRequired, StructuralResolutionRefused) - ): - target_fingerprint = None - if ( - resolution is not None - and resolution.structural_handle is not None - ): - target_fingerprint = ( - resolution.structural_handle.target_fingerprint - ) - result.delivery_uncertainty = ActionDeliveryUncertainty( - operation="interstitial_dismiss", - native=( - resolution is not None - and resolution.rung == "structural" - ), - target_fingerprint=target_fingerprint, - observed_at=datetime.now(timezone.utc).isoformat(), - cause_type=type(exc).__name__, - ) - event.error = ( - "dismissal delivery failed " - f"({type(exc).__name__}); outcome is unknown" - ) - if it.effect_watch and str(exc): - event.error += f": {exc}" - return before_png, ( - f"Interstitial '{it.name}' dismissal delivery failed " - f"({type(exc).__name__}" - + (f": {exc}" if it.effect_watch and str(exc) else "") - + ") - refusing to act beneath it; run aborted." - ) - - before_png, settle_error = self._resettle_after_interstitial(before_png) - if watch is not None: - if watch.attempts: - event.after_frame_sha256 = hashlib.sha256(before_png).hexdigest() - event.error = "the dismissal tried to write" - result.safety_halt = True - return before_png, ( - f"Interruption '{it.name}': its dismissal tried to " - f"write ({'; '.join(watch.attempts)}) - it is not a " - "benign interruption; refusing to continue; run aborted." - ) - event.after_frame_sha256 = hashlib.sha256(before_png).hexdigest() - if settle_error is not None: - event.error = settle_error - return before_png, settle_error - - clearance_holds = self._predicate_holds( - it.clearance, - before_png, - bundle_dir, - params, - workflow=workflow, - ) - if self._governed_asset_mutation is not None: - event.clearance_ok = False - event.error = self._governed_asset_mutation - return before_png, self._governed_asset_mutation - still_detected = False - if clearance_holds: - still_detected = self._predicate_holds( - it.detect, - before_png, - bundle_dir, - params, - workflow=workflow, - ) - if self._governed_asset_mutation is not None: - event.clearance_ok = False - event.error = self._governed_asset_mutation - return before_png, self._governed_asset_mutation - event.clearance_ok = clearance_holds and not still_detected - event.ok = event.delivered and event.clearance_ok - if not event.ok: - event.error = ( - "declared visual clearance did not hold" - if not clearance_holds - else "interstitial remained detected after dismissal" - ) - return before_png, ( - f"Interstitial '{it.name}' did not satisfy its declared " - "visual clearance after one dismissal - refusing a blind " - "retry or action beneath it; run aborted." - ) - # -- Workflow-program IR gates: guard + wait_until -------------------------- def _apply_step_gates( From 6c809f549e71e627adab5621cf4c38bbb5ce1a7c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:09:22 -0500 Subject: [PATCH 2/5] refactor(flow): move the replayer's effects concern to a mixin, unchanged --- packages/flow/docs/design/DECOMPOSITION.md | 2 +- .../openadapt_flow/runtime/replay/effects.py | 912 ++++++++++++++++++ .../flow/openadapt_flow/runtime/replayer.py | 845 +--------------- 3 files changed, 925 insertions(+), 834 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/replay/effects.py diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 32028d90ec..4dfe67a693 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -605,7 +605,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 18693 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 17872 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6830 | diff --git a/packages/flow/openadapt_flow/runtime/replay/effects.py b/packages/flow/openadapt_flow/runtime/replay/effects.py new file mode 100644 index 0000000000..be4cf6310a --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/replay/effects.py @@ -0,0 +1,912 @@ +# mypy: disable-error-code="empty-body" +"""Moved replayer code. + +Moved verbatim from ``openadapt_flow.runtime.replayer.Replayer`` by +scripts/extract_mixin.py (docs/design/DECOMPOSITION.md, section 4.1). +``_EffectChecksHost`` declares, for mypy only, what this code reads from the +Replayer it is mixed into. +""" + +from __future__ import annotations + +import hashlib +import threading +from types import SimpleNamespace +from typing import TYPE_CHECKING, Any, Optional # noqa: F401 + +from openadapt_flow.assurance import effect_read_wording as _effect_read_wording +from openadapt_flow.ir import EffectVerificationEvidence, HaltObservation, StepResult +from openadapt_flow.qualification_faults import effect_verifier_input_sha256 +from openadapt_flow.runtime.authorization import runtime_param_text +from openadapt_flow.runtime.durable.first_local_runtime import ( + placeholder_effect_refusal, +) +from openadapt_flow.runtime.effects import EffectState, reconcile_or_escalate +from openadapt_flow.runtime.effects.adapter import _probe_adapter_connection +from openadapt_flow.runtime.effects.adapter import ( + verifier_identity as effect_verifier_identity, +) +from openadapt_flow.runtime.effects.pipeline_safety import _pipeline_safe_verifier +from openadapt_flow.runtime.replay._shared import ( + _MAX_SERVER_RESPONSES, + effect_endpoint_scope, + effect_field_checks, +) +from openadapt_flow.runtime.step_timing import timed_span +from openadapt_flow.verification import ( + EffectContractMutationError, + verifier_effect_tier, + verify_effect_without_mutation, +) + +if TYPE_CHECKING: + from typing import Literal, Mapping + + from openadapt_flow.backend import Backend + from openadapt_flow.ir import Region, RunReport, Step, Workflow + from openadapt_flow.qualification_faults import ( + FaultMutationReceipt, + QualificationFaultGate, + ) + from openadapt_flow.runtime.authorization import ( + GovernedRunAuthorization, + RuntimeParamScalar, + ) + from openadapt_flow.runtime.effects import Effect, EffectVerifier + from openadapt_flow.runtime.readback_pipeline import ( + PipelinedReadback, + ReadbackPipeline, + ) + + +class _EffectChecksHost: + _durable_continuation_guard: Optional[Any] + _pipelined_readback: Optional["PipelinedReadback"] + _qualification_fault_context: Any + _qualification_fault_mutations: list[FaultMutationReceipt] + _readback_verifier: Any + _require_current_fault_driver_binding: Any + _run_id: str + _validate_fault_mutation: Any + backend: Backend + checkpoint_key: Optional[str] + durable: bool + effect_compensator: Optional[Any] + effect_verifier: Optional[EffectVerifier] + governed_authorization: Optional[GovernedRunAuthorization] + readback_pipeline: Optional["ReadbackPipeline"] + + +if TYPE_CHECKING: + _Base = _EffectChecksHost +else: + _Base = object + + +class EffectChecks(_Base): + """Moved replayer code.""" + + def _may_pipeline_readback( + self, verifier: Any, step: Optional[Step] = None + ) -> bool: + """Whether this effect's read-back may run on the side thread. + + A durable run defers the record check only when the durable pause + can hold it (docs/THROUGHPUT.md): a linear run, an encrypted + checkpoint store, and the item's last step, so nothing else in the + item waits on the check. + """ + + pipeline = getattr(self, "readback_pipeline", None) + if pipeline is None: + return False + reason = None + if getattr(self, "_program_durable", None) is not None: + reason = "durable program runs verify inline" + elif self.durable and self._durable_continuation_guard is not None: + reason = "a resumed durable run verifies inline" + elif self.durable and not self.checkpoint_key: + reason = ( + "a durable run without an encrypted checkpoint store verifies " + "inline (the deferred check keeps record rows)" + ) + elif self.durable and ( + step is None or step.id != getattr(self, "_linear_final_step_id", None) + ): + reason = ( + "a durable run defers only its last step's record check; this " + "one verifies inline" + ) + elif getattr(self, "idempotency_ledger", None) is not None: + reason = "idempotency-ledger runs verify inline" + elif getattr(self, "_pipelined_readback", None) is not None: + reason = "an earlier read-back in this item is still pending" + else: + target = verifier if verifier is not None else self.effect_verifier + if not _pipeline_safe_verifier(target): + reason = ( + "only REST, FHIR, GraphQL and SQL read-backs run alongside " + "the next item; this one verifies inline" + ) + pipeline.inline_reason = reason + return reason is None + + def _defer_readback( + self, + step: Step, + before: EffectState, + result: StepResult, + *, + effects: Optional[list["Effect"]], + verifier: Any, + actuation: Literal["gui", "api"] = "gui", + ) -> None: + assert self.readback_pipeline is not None + scratch = StepResult(step_id=step.id, intent=step.intent, ok=True) + # A durable run's check starts only once the durable pause holds it, + # so a crash in between can't leave a sent save without its pause. + # Whatever waits on the check also starts it. + start = threading.Event() + if not self.durable: + start.set() + + def verify() -> Optional[str]: + start.wait() + return self._verify_effects( + step, before, scratch, effects=effects, verifier=verifier + ) + + entry = self.readback_pipeline.submit(step.id, verify) + entry.start = start # type: ignore[attr-defined] + entry.scratch = scratch # type: ignore[attr-defined] + entry.result = result # type: ignore[attr-defined] + entry.intent = step.intent # type: ignore[attr-defined] + # What a durable pause needs to re-run this check after a crash. + entry.step = step # type: ignore[attr-defined] + entry.before = before # type: ignore[attr-defined] + entry.actuation = actuation # type: ignore[attr-defined] + entry.durable_run = None # type: ignore[attr-defined] + result.effect_verified = None + result.effect_results.append("[pipelined] system-of-record read-back pending") + self._pipelined_readback = entry + + def _join_pipelined_readback(self, *, keep: bool = False) -> Optional[str]: + """Wait for a pending read-back, apply it to its step, return its error.""" + + entry = getattr(self, "_pipelined_readback", None) + if entry is None: + return None + start = getattr(entry, "start", None) + if start is not None: + start.set() + try: + error = entry.verdict.result() + except Exception as exc: # noqa: BLE001 - a raising verifier fails closed + error = f"read-back raised {type(exc).__name__}; reconciliation is required" + self._copy_pipelined_evidence(entry, error) + if not keep: + self._pipelined_readback = None + return error + + def _copy_pipelined_evidence(self, entry: Any, error: Optional[str]) -> None: + result: StepResult = entry.result + scratch: StepResult = entry.scratch + result.effect_results = [ + r for r in result.effect_results if not r.startswith("[pipelined]") + ] + result.effect_results.extend(scratch.effect_results) + result.effect_evidence.extend(scratch.effect_evidence) + result.effect_field_checks.extend(scratch.effect_field_checks) + result.effect_verified = scratch.effect_verified + if scratch.failure_category is not None: + result.failure_category = scratch.failure_category + if error is not None: + result.ok = False + result.error = error + result.safety_halt = True + if result.failure_category is None: + result.failure_category = ( + "governed_refusal" + if self.governed_authorization is not None + else "safety_halt" + ) + else: + result.safety_halt = result.safety_halt or scratch.safety_halt + + def _apply_pipelined_verdict( + self, + report: RunReport, + error: Optional[str], + *, + entry: Optional["PipelinedReadback"] = None, + ) -> None: + if error is None: + return + report.success = False + report.execution_completed = False + report.terminal_outcome = "halt" + report.results.append( + StepResult( + step_id="", + intent="program halt", + ok=False, + error=error, + safety_halt=True, + ) + ) + if entry is None: + entry = getattr(self, "_pipelined_readback", None) + report.halt = HaltObservation( + state_id=getattr(entry, "step_id", "") or "", + intent=getattr(entry, "intent", "") or "", + reason=error, + outcome="halt", + # The screen now belongs to the next item; nothing is probed. + observed_texts=[], + completed_intents=[ + r.intent for r in report.results if r.ok and not r.skipped + ], + ) + + def recheck_deferred_readback( + self, + workflow: Workflow, + deferred: Any, + *, + params: Mapping[str, RuntimeParamScalar], + run_id: str, + read_only: bool = False, + ) -> StepResult: + """Re-run a durable pause's deferred record check; send nothing. + + The check runs against the snapshot of the system of record taken + before the save, with this replayer's system-of-record verifier. + Returns the save's result with the verdict applied: ``ok`` when the + record check confirmed the save. + """ + + from openadapt_flow.policy import effects_for_actuation + from openadapt_flow.runtime.durable.approval import StateDiverged + + step = workflow.steps[deferred.step_index] + if step.id != deferred.step_id: + raise StateDiverged( + "the deferred record check names a different step than the bundle" + ) + verifier = self.effect_verifier + if verifier is None or not _pipeline_safe_verifier(verifier): + raise StateDiverged( + "re-running a deferred record check needs the run's REST, FHIR, " + "GraphQL or SQL record checker" + ) + self._run_id = run_id + effects = self._resolve_effects( + list(effects_for_actuation(step, deferred.actuation)), params + ) + before = EffectState.model_validate(deferred.before) + result = deferred.result.model_copy(deep=True) + scratch = StepResult(step_id=step.id, intent=step.intent, ok=True) + try: + error = self._verify_effects( + step, + before, + scratch, + effects=effects, + verifier=verifier, + read_only=read_only, + ) + except Exception as exc: # noqa: BLE001 - a raising verifier fails closed + error = f"read-back raised {type(exc).__name__}; reconciliation is required" + self._copy_pipelined_evidence( + SimpleNamespace(result=result, scratch=scratch), error + ) + return result + + def _apply_effect_fault_mutation( + self, + *, + gate: QualificationFaultGate, + step: Step, + actuation_path: Literal["gui", "api"], + effect_verifier: Any, + effects: tuple[Any, ...], + ) -> Any: + if self._qualification_fault_mutations: + return effect_verifier + before_sha256 = effect_verifier_input_sha256(effect_verifier, effects) + context = self._qualification_fault_context( + gate=gate, + step=step, + actuation_path=actuation_path, + before_input_sha256=before_sha256, + effect_verifier=effect_verifier, + effects=effects, + ) + if context is None: + return effect_verifier + driver = self._require_current_fault_driver_binding() + mutation = driver.mutate(context) + if mutation is None: + return effect_verifier + if not mutation.replace_effect_verifier: + raise RuntimeError("qualification_effect_fault_did_not_replace_verifier") + after_sha256 = effect_verifier_input_sha256( + mutation.effect_verifier, + effects, + ) + self._validate_fault_mutation( + context, + mutation.receipt, + after_input_sha256=after_sha256, + ) + return mutation.effect_verifier + + def _resolve_effects( + self, effects: list["Effect"], params: Mapping[str, RuntimeParamScalar] + ) -> list["Effect"]: + """Bind each effect's ``ValueExpr`` contract to THIS run's params (P0-3). + + Mirrors how an ``ApiBinding``'s ``{param}`` templates are filled at + actuation time: the effect a PARAMETERIZED workflow verifies must + describe the record IT WROTE THIS RUN, not the demonstration's. The + reserved ``__run_id__`` param exposes the stable-per-run identity so an + idempotency key can be bound per-run. A pure-literal (v1) effect is + returned value-identical -- ``resolve`` is a no-op for it. + """ + namespace = { + **{name: runtime_param_text(value) for name, value in params.items()}, + "__run_id__": self._run_id, + } + run_id_sha256 = hashlib.sha256(self._run_id.encode("utf-8")).hexdigest() + return [ + effect.resolve( + namespace, + opaque_param_sha256={"__run_id__": run_id_sha256}, + ) + for effect in effects + ] + + @staticmethod + def _capture_effect_pre_state(verifier: Any, effects: list["Effect"]) -> Any: + """Capture the pre-action baseline for resolved effect contracts. + + Multi-candidate deployments select an adapter per resolved effect. A + normal verifier keeps the established single snapshot behavior. + """ + capture_for_effects = getattr(verifier, "capture_pre_state_for_effects", None) + if callable(capture_for_effects): + return capture_for_effects(effects) + if getattr(verifier, "_openadapt_requires_preflight", False): + probe = _probe_adapter_connection(verifier) + if not probe.ok: + raise ValueError( + "the selected effect verifier failed its read-only connection " + f"preflight ({probe.substrate}: {probe.reason})" + ) + return verifier.capture_pre_state() + + def _keep_undo_prior_state( + self, + workflow: Workflow, + step: Step, + before: Any, + effects: Optional[list["Effect"]], + params: Mapping[str, Any], + ) -> None: + """Keep what a locating or restoring undo of ``step`` needs. + + Reads only the pre-action baseline already captured; never raises and + never changes the step's result (``after_stop.keep_prior_state``). + """ + run_dir = getattr(self, "_undo_prior_run_dir", None) + if run_dir is None or not workflow.undo_steps or not effects: + return + try: + state = self._effect_pre_state_for(before, effects[0]) + except Exception: # noqa: BLE001 - bookkeeping never stops a run + return + if getattr(state, "reachable", None) is not True: + return + from openadapt_flow.after_stop import keep_prior_state + + keep_prior_state( + workflow, step, list(getattr(state, "records", []) or []), params, run_dir + ) + + @staticmethod + def _effect_pre_state_for(before: Any, effect: "Effect") -> Any: + """Return one selected effect baseline, or a normal shared baseline.""" + selected = getattr(before, "for_effect", None) + if callable(selected): + return selected(effect).state + return before + + @staticmethod + def _effect_binding_for( + verifier: Any, before: Any, effect: "Effect" + ) -> tuple[Any, Any, Optional[Any], str]: + """Return the exact adapter, state, tier, and identity bound to an effect.""" + + selected = getattr(before, "for_effect", None) + if callable(selected): + binding = selected(effect) + return ( + binding.verifier, + binding.state, + binding.tier, + binding.verifier_identity, + ) + return ( + verifier, + before, + verifier_effect_tier(verifier, effect), + effect_verifier_identity(verifier), + ) + + @staticmethod + def _candidate_binding_refusal( + before: Any, effects: list["Effect"] + ) -> Optional[str]: + """Refuse a candidate whose identity or tier changed after selection.""" + + selected = getattr(before, "for_effect", None) + if not callable(selected): + return None + for effect in effects: + binding = selected(effect) + current_tier = verifier_effect_tier(binding.verifier, effect) + current_identity = effect_verifier_identity(binding.verifier) + if ( + current_tier != binding.tier + or current_identity != binding.verifier_identity + ): + return ( + "the selected effect verifier identity or evidence tier changed " + "after pre-action binding; refusing to use a different proof" + ) + return None + + @staticmethod + def _verify_current_effect( + verifier: Any, effect: "Effect", current: EffectState + ) -> Any: + """Use an adapter's current-state path without inventing a new baseline.""" + + candidate = effect.model_copy(deep=True) + original = candidate.model_dump(mode="json") + callback = getattr(verifier, "verify_current_state", None) + if callable(callback): + verdict = callback(candidate, current) + else: + from openadapt_flow.runtime.effects._common import judge_records + + # An effect whose CLAIM is a delta (``exact_new_set``) cannot be + # judged against a synthesized empty baseline: every record in + # scope would read as an addition, so the verdict would be + # fabricated rather than proved. Mark the synthetic baseline + # UNREACHABLE for those effects and let the judge return its own + # structured INDETERMINATE refusal. Every pre-existing kind keeps + # the readable empty baseline and is judged exactly as before. + needs_baseline = bool(candidate.requires_baseline) + detail: dict[str, Any] = {"current_state_readback": True} + if needs_baseline: + detail["baseline_unavailable_for_delta"] = True + baseline = EffectState( + substrate=current.substrate, + reachable=not needs_baseline, + records=[], + detail=detail, + ) + verdict = judge_records( + candidate, + baseline, + current.records if current.reachable is True else None, + substrate=current.substrate, + ) + if candidate.model_dump(mode="json") != original: + raise EffectContractMutationError( + "effect verifier changed the resolved effect contract" + ) + return verdict + + @classmethod + def _required_effect_pre_state_unreadable( + cls, verifier: Any, before: Any, effects: list["Effect"] + ) -> bool: + """Return true only when a selected effect needs, but lacks, a baseline. + + Different-path on-screen read-back proves persistence after input and + deliberately has no readable pre-action state. Delta, duplicate, and + collateral checks still require their selected verifier baseline. + """ + requirement = getattr(verifier, "requires_readable_pre_state_for", None) + selected = getattr(before, "for_effect", None) + missing_reachability = object() + for effect in effects: + if callable(selected): + required = bool(selected(effect).requires_readable_pre_state) + else: + required = ( + bool(requirement(effect)) + if callable(requirement) + else bool(effect.requires_baseline or effect.forbid_collateral_loss) + ) + state = cls._effect_pre_state_for(before, effect) + # Legacy in-process verifiers may retain an opaque pre-state for + # their own verify implementation. Their established verification + # path decides whether it is usable. If a legacy state exposes + # reachability, it must state exactly True; None, falsey values, + # and truthy non-bools are not evidence that its baseline is + # readable. Candidate deployments are stricter: their verifier + # accepts only EffectState, so a missing reachability value cannot + # bypass its pre-actuation guard. + reachable = getattr(state, "reachable", missing_reachability) + if ( + required + and reachable is not missing_reachability + and reachable is not True + ): + return True + return False + + def _profile_effect_tier_refusal( + self, + workflow: Workflow, + step: Step, + actuation_path: Literal["gui", "api"], + effects: list["Effect"], + verifier: object, + ) -> Optional[str]: + """Recheck effect strength immediately before governed actuation.""" + + authorization = self.governed_authorization + if authorization is None or authorization.execution_profile is None: + return None + from openadapt_flow.execution_profiles import required_effect_tier + from openadapt_flow.verification import VerificationTier + + minimum = ( + VerificationTier(authorization.minimum_effect_tier) + if authorization.minimum_effect_tier is not None + else required_effect_tier(workflow, authorization.execution_profile) + ) + if minimum is None: + return None + requirements = authorization.effect_requirements(step.id, actuation_path) + if requirements: + from openadapt_flow.policy import effects_for_actuation + + declared = effects_for_actuation( + step, "api" if actuation_path == "api" else "guarded_coordinate" + ) + if len(requirements) != len(declared) or len(effects) != len(declared): + return ( + "Qualified effect requirements changed after admission — " + "refusing to actuate; run aborted" + ) + for index, requirement in enumerate(requirements): + if ( + requirement.effect_index != index + or requirement.effect_contract_hash + != declared[index].contract_hash() + ): + return ( + "Qualified effect contract changed after admission — " + "refusing to actuate; run aborted" + ) + weak = [] + for index, effect in enumerate(effects): + required = ( + VerificationTier(requirements[index].minimum_tier) + if requirements + else minimum + ) + actual = verifier_effect_tier(verifier, effect) + if actual is None or not actual.satisfies(required): + weak.append("untyped" if actual is None else actual.name.lower()) + if not weak: + return None + observed = ", ".join(sorted(set(weak))) + return ( + "Effect verifier strength changed after admission: " + f"{observed} evidence cannot satisfy the required " + "qualified effect tier — refusing to actuate; run aborted" + ) + + def _all_default_readback(self, effects: list["Effect"]) -> bool: + """Whether EVERY declared effect is an auto-derived DIFFERENT-PATH + on-screen read-back that may be verified out of the box with no + connector (measured false-CONFIRM ~0). A same-surface read-back or any + structured system-of-record effect makes this False — those still + require a configured verifier (fail-safe).""" + from openadapt_flow.runtime.effects.onscreen import is_default_readback_effect + + return bool(effects) and all(is_default_readback_effect(e) for e in effects) + + def _auto_readback_verifier(self) -> Any: + """The backend-bound on-screen read-back verifier for the no-connector + default path (built once, reused across steps).""" + verifier = getattr(self, "_readback_verifier", None) + if verifier is None: + from openadapt_flow.runtime.effects.onscreen import ( + OnScreenReadbackVerifier, + ) + + verifier = OnScreenReadbackVerifier(backend=self.backend) + self._readback_verifier = verifier + return verifier + + def _server_response_mark(self) -> Optional[int]: + """Where the backend's server-answer log stands, or None when the + backend doesn't see server answers (every non-browser backend).""" + + mark = getattr(self.backend, "server_response_mark", None) + if not callable(mark): + return None + try: + return int(mark()) + except Exception: # noqa: BLE001 - evidence only, never a failure + return None + + def _collect_server_responses(self, result: StepResult, mark: int) -> None: + since = getattr(self.backend, "server_responses_since", None) + if not callable(since): + return + try: + responses = list(since(mark)) + except Exception: # noqa: BLE001 - evidence only, never a failure + return + result.server_responses = responses[:_MAX_SERVER_RESPONSES] + + @timed_span("readback") + def _verify_effects( + self, + step: Step, + before: EffectState, + result: StepResult, + effects: Optional[list["Effect"]] = None, + verifier: Any = None, + *, + read_only: bool = False, + ) -> Optional[str]: + """Verify each declared Effect against the system of record; HALT on + any non-CONFIRMED verdict. + + Runs AFTER the action and its screen postconditions (for a GUI write), + or immediately after an API actuation. For each effect the configured + verifier rules CONFIRMED / REFUTED / INDETERMINATE against the REAL + record (an API/DB read, never the screen). A CONFIRMED effect proceeds; + a non-CONFIRMED effect halts, except that an IRREVERSIBLE effect is + first routed through ``reconcile_or_escalate`` -- a duplicate the + configured compensator can undo is RECONCILED (proceed), everything else + ESCALATEs (halt). Every verdict is recorded on ``result.effect_results`` + for the audit trail. Makes ZERO model calls (the $0 runtime guarantee). + + Args: + step: The step being verified (for the audit/error text). + before: The pre-action snapshot of the system of record. + result: The step result to record verdicts on. + effects: The effects to verify; defaults to ``step.effects`` (the + GUI path). The API tier passes ``api_binding.effects`` only. + + Returns an error string (HALT) or None (all effects confirmed or + reconciled). + """ + # ``verifier`` is the configured one by default, but the caller may pass + # the auto-wired backend-bound read-back verifier (the no-connector + # default path) for a step whose effects are different-path read-backs. + if verifier is None: + verifier = self.effect_verifier + assert verifier is not None # guaranteed by the caller + if effects is None: + effects = step.effects + for effect in effects: + refusal = placeholder_effect_refusal(step, effect, result) + if refusal is not None: + return refusal + try: + verdict = verify_effect_without_mutation(verifier, effect, before) + scope = effect_endpoint_scope(verifier) + selected_pre_state = getattr(before, "for_effect", None) + if callable(selected_pre_state): + # Candidate selection and its evidence strength are pinned + # before input. Do not recompute the tier after delivery: + # a stateful plugin must not change the receipt contract. + binding = selected_pre_state(effect) + tier = binding.tier + identity = binding.verifier_identity + scope = effect_endpoint_scope(binding.verifier) + if ( + verifier_effect_tier(binding.verifier, effect) != tier + or effect_verifier_identity(binding.verifier) != identity + ): + result.effect_verified = False + result.safety_halt = True + result.failure_category = "governed_refusal" + result.effect_results.append( + "selected effect verifier identity or evidence tier " + "changed after input; HALT" + ) + return ( + f"Effect verifier binding changed after input for step " + f"'{step.id}' — refusing evidence from a different " + "adapter or tier; reconciliation is required" + ) + else: + tier = verifier_effect_tier(verifier, effect) + identity = effect_verifier_identity(verifier) + except EffectContractMutationError: + result.effect_verified = False + result.safety_halt = True + result.failure_category = "governed_refusal" + result.effect_results.append( + "effect verifier changed the resolved effect contract; HALT" + ) + return ( + f"Effect verifier changed the resolved contract for step " + f"'{step.id}' — refusing mutable verification evidence; " + "run aborted" + ) + result.effect_field_checks.extend( + effect_field_checks(effect, verdict, tier) + ) + if verdict.confirmed: + result.effect_evidence.append( + EffectVerificationEvidence( + effect_contract_hash=effect.contract_hash(), + substrate=verdict.substrate, + verifier_identity=identity, + verification_tier=(int(tier) if tier is not None else None), + initial_verdict=verdict.verdict.value, + final_verdict=verdict.verdict.value, + observed_effect=verdict.observed_effect, + endpoint_scope=scope, + read_evidence=verdict.read_evidence, + ) + ) + result.effect_results.append( + f"[{verdict.substrate}] {effect.kind.value}: CONFIRMED" + + (f" — {verdict.reason}" if verdict.reason else "") + ) + continue + + # Non-CONFIRMED: never proceed on an unverified/contradicted write. + # An irreversible effect gets one reconcile-or-escalate pass (a + # compensable duplicate is fixable; missing / partial / collateral + # loss / INDETERMINATE always escalate). A reversible effect just + # halts. Either way the run stops -- this is the same + # refuse-rather-than-guess posture as the identity gate. + if effect.risk == "irreversible" and not read_only: + comp = reconcile_or_escalate( + effect, + verdict, + verifier=verifier, + before=before, + compensator=self.effect_compensator, + ) + if comp.proceed: + final_verdict = comp.final_verdict or verdict + result.effect_evidence.append( + EffectVerificationEvidence( + effect_contract_hash=effect.contract_hash(), + substrate=final_verdict.substrate, + verifier_identity=identity, + verification_tier=(int(tier) if tier is not None else None), + initial_verdict=verdict.verdict.value, + final_verdict=final_verdict.verdict.value, + observed_effect=final_verdict.observed_effect, + endpoint_scope=scope, + read_evidence=final_verdict.read_evidence, + reconciliation_completed=True, + reconciliation_actions=comp.actions_taken, + ) + ) + result.effect_results.append( + f"[{verdict.substrate}] {effect.kind.value}: " + f"{verdict.verdict.value.upper()} → RECONCILED " + f"({comp.actions_taken} action(s)) — {comp.reason}" + ) + continue + result.effect_verified = False + final_verdict = comp.final_verdict or verdict + result.effect_evidence.append( + EffectVerificationEvidence( + effect_contract_hash=effect.contract_hash(), + substrate=final_verdict.substrate, + verifier_identity=identity, + verification_tier=(int(tier) if tier is not None else None), + initial_verdict=verdict.verdict.value, + final_verdict=final_verdict.verdict.value, + observed_effect=final_verdict.observed_effect, + endpoint_scope=scope, + read_evidence=final_verdict.read_evidence, + reconciliation_actions=comp.actions_taken, + deferred_check=verdict.deferred_check, + ) + ) + result.effect_results.append( + f"[{verdict.substrate}] {effect.kind.value}: " + f"{verdict.verdict.value.upper()} → " + f"{comp.outcome.value.upper()} — {comp.reason}" + ) + prefix, read = _effect_read_wording(tier) + return ( + f"{prefix} HALTED step " + f"'{step.id}' ({step.intent}): {effect.kind.value} " + f"{verdict.verdict.value} against the {verdict.substrate} " + f"{read} and could not be reconciled " + f"({comp.outcome.value}) — " + f"{comp.escalation or comp.reason} — run aborted" + ) + + result.effect_verified = False + result.effect_evidence.append( + EffectVerificationEvidence( + effect_contract_hash=effect.contract_hash(), + substrate=verdict.substrate, + verifier_identity=identity, + verification_tier=(int(tier) if tier is not None else None), + initial_verdict=verdict.verdict.value, + final_verdict=verdict.verdict.value, + observed_effect=verdict.observed_effect, + endpoint_scope=scope, + read_evidence=verdict.read_evidence, + deferred_check=verdict.deferred_check, + ) + ) + result.effect_results.append( + f"[{verdict.substrate}] {effect.kind.value}: " + f"{verdict.verdict.value.upper()} — {verdict.reason}" + ) + prefix, read = _effect_read_wording(tier) + return ( + f"{prefix} HALTED step " + f"'{step.id}' ({step.intent}): {effect.kind.value} " + f"{verdict.verdict.value} against the {verdict.substrate} " + f"{read} (the screen indicated completion but the " + f"declared outcome is contradicted or unverifiable) — " + f"{verdict.reason} — run aborted" + ) + + result.effect_verified = True + return None + + @staticmethod + def _mapped_selection_readback_region( + recorded_target: Region, + recorded_readback: Region, + live_target: Region, + frame_png: bytes, + ) -> Optional[Region]: + """Map the recorded readback band onto a fresh live target. + + Absolute recording coordinates never drive verification. The mapping + preserves the band's target-relative offsets while allowing the + already-qualified target geometry to translate or scale modestly, then + clamps it to the exact final frame. + """ + + from openadapt_flow.vision import imgops + + frame = imgops.decode_bgr(frame_png) + if frame is None: + return None + frame_h, frame_w = frame.shape[:2] + target_x, target_y, target_w, target_h = recorded_target + read_x, read_y, read_w, read_h = recorded_readback + live_x, live_y, live_w, live_h = live_target + if min(target_w, target_h, read_w, read_h, live_w, live_h) <= 0: + return None + scale_x = live_w / target_w + scale_y = live_h / target_h + mapped_x = round(live_x + (read_x - target_x) * scale_x) + mapped_y = round(live_y + (read_y - target_y) * scale_y) + mapped_w = max(1, round(read_w * scale_x)) + mapped_h = max(1, round(read_h * scale_y)) + left = max(0, mapped_x) + top = max(0, mapped_y) + right = min(frame_w, mapped_x + mapped_w) + bottom = min(frame_h, mapped_y + mapped_h) + if right <= left or bottom <= top: + return None + return (left, top, right - left, bottom - top) diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index 0ec215ccbe..69a97053f2 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -54,7 +54,7 @@ from dataclasses import dataclass # noqa: F401 from datetime import datetime, timezone from pathlib import Path -from types import SimpleNamespace +from types import SimpleNamespace # noqa: F401 from typing import ( # noqa: F401 TYPE_CHECKING, Any, @@ -70,7 +70,7 @@ from urllib.parse import urlsplit from openadapt_flow import sealed_set as _sealed -from openadapt_flow.assurance import effect_read_wording as _effect_read_wording +from openadapt_flow.assurance import effect_read_wording as _effect_read_wording # noqa: F401 from openadapt_flow.backend import ( ActionDeliveryUncertain, Backend, @@ -204,7 +204,7 @@ from openadapt_flow.runtime.durable import program_runtime as _program_runtime from openadapt_flow.runtime.durable.approval import StateDiverged from openadapt_flow.runtime.durable.first_local_delivery import FirstLocalDeliveryHeld -from openadapt_flow.runtime.durable.first_local_runtime import ( +from openadapt_flow.runtime.durable.first_local_runtime import ( # noqa: F401 FirstLocalDeliveryStep, arm_first_local_delivery, first_local_effect_refusal, @@ -228,19 +228,19 @@ history_hash as _history_hash, ) from openadapt_flow.runtime.effect_watch import EffectWatchReport, watch_effects # noqa: F401 -from openadapt_flow.runtime.effects import ( +from openadapt_flow.runtime.effects import ( # noqa: F401 Effect, EffectState, EffectVerifier, reconcile_or_escalate, ) -from openadapt_flow.runtime.effects.adapter import ( +from openadapt_flow.runtime.effects.adapter import ( # noqa: F401 _probe_adapter_connection, ) from openadapt_flow.runtime.effects.adapter import ( verifier_identity as effect_verifier_identity, ) -from openadapt_flow.runtime.effects.pipeline_safety import _pipeline_safe_verifier +from openadapt_flow.runtime.effects.pipeline_safety import _pipeline_safe_verifier # noqa: F401 from openadapt_flow.runtime.known_ids import ( lookalike_class as known_ids_lookalike_class, ) @@ -270,7 +270,7 @@ secret_env_var, secret_env_vars, ) -from openadapt_flow.verification import ( +from openadapt_flow.verification import ( # noqa: F401 EffectContractMutationError, verifier_effect_tier, verify_effect_without_mutation, @@ -343,6 +343,7 @@ effect_field_checks, identity_read_contradicts, ) +from openadapt_flow.runtime.replay.effects import EffectChecks from openadapt_flow.runtime.replay.evidence import AssetsHealingAndEvidence from openadapt_flow.runtime.replay.qualification_faults import ( QualificationFaultInjection, @@ -351,7 +352,10 @@ class Replayer( - QualificationFaultInjection, AssetsHealingAndEvidence, SettlingAndInterstitials + QualificationFaultInjection, + AssetsHealingAndEvidence, + SettlingAndInterstitials, + EffectChecks, ): """Replays a Workflow against a Backend using injected vision. @@ -3014,168 +3018,6 @@ def _settle(error: Optional[str]) -> RunReport: # -- pipelined read-back (runtime/readback_pipeline.py) ------------------ - def _may_pipeline_readback( - self, verifier: Any, step: Optional[Step] = None - ) -> bool: - """Whether this effect's read-back may run on the side thread. - - A durable run defers the record check only when the durable pause - can hold it (docs/THROUGHPUT.md): a linear run, an encrypted - checkpoint store, and the item's last step, so nothing else in the - item waits on the check. - """ - - pipeline = getattr(self, "readback_pipeline", None) - if pipeline is None: - return False - reason = None - if getattr(self, "_program_durable", None) is not None: - reason = "durable program runs verify inline" - elif self.durable and self._durable_continuation_guard is not None: - reason = "a resumed durable run verifies inline" - elif self.durable and not self.checkpoint_key: - reason = ( - "a durable run without an encrypted checkpoint store verifies " - "inline (the deferred check keeps record rows)" - ) - elif self.durable and ( - step is None or step.id != getattr(self, "_linear_final_step_id", None) - ): - reason = ( - "a durable run defers only its last step's record check; this " - "one verifies inline" - ) - elif getattr(self, "idempotency_ledger", None) is not None: - reason = "idempotency-ledger runs verify inline" - elif getattr(self, "_pipelined_readback", None) is not None: - reason = "an earlier read-back in this item is still pending" - else: - target = verifier if verifier is not None else self.effect_verifier - if not _pipeline_safe_verifier(target): - reason = ( - "only REST, FHIR, GraphQL and SQL read-backs run alongside " - "the next item; this one verifies inline" - ) - pipeline.inline_reason = reason - return reason is None - - def _defer_readback( - self, - step: Step, - before: EffectState, - result: StepResult, - *, - effects: Optional[list["Effect"]], - verifier: Any, - actuation: Literal["gui", "api"] = "gui", - ) -> None: - assert self.readback_pipeline is not None - scratch = StepResult(step_id=step.id, intent=step.intent, ok=True) - # A durable run's check starts only once the durable pause holds it, - # so a crash in between can't leave a sent save without its pause. - # Whatever waits on the check also starts it. - start = threading.Event() - if not self.durable: - start.set() - - def verify() -> Optional[str]: - start.wait() - return self._verify_effects( - step, before, scratch, effects=effects, verifier=verifier - ) - - entry = self.readback_pipeline.submit(step.id, verify) - entry.start = start # type: ignore[attr-defined] - entry.scratch = scratch # type: ignore[attr-defined] - entry.result = result # type: ignore[attr-defined] - entry.intent = step.intent # type: ignore[attr-defined] - # What a durable pause needs to re-run this check after a crash. - entry.step = step # type: ignore[attr-defined] - entry.before = before # type: ignore[attr-defined] - entry.actuation = actuation # type: ignore[attr-defined] - entry.durable_run = None # type: ignore[attr-defined] - result.effect_verified = None - result.effect_results.append("[pipelined] system-of-record read-back pending") - self._pipelined_readback = entry - - def _join_pipelined_readback(self, *, keep: bool = False) -> Optional[str]: - """Wait for a pending read-back, apply it to its step, return its error.""" - - entry = getattr(self, "_pipelined_readback", None) - if entry is None: - return None - start = getattr(entry, "start", None) - if start is not None: - start.set() - try: - error = entry.verdict.result() - except Exception as exc: # noqa: BLE001 - a raising verifier fails closed - error = f"read-back raised {type(exc).__name__}; reconciliation is required" - self._copy_pipelined_evidence(entry, error) - if not keep: - self._pipelined_readback = None - return error - - def _copy_pipelined_evidence(self, entry: Any, error: Optional[str]) -> None: - result: StepResult = entry.result - scratch: StepResult = entry.scratch - result.effect_results = [ - r for r in result.effect_results if not r.startswith("[pipelined]") - ] - result.effect_results.extend(scratch.effect_results) - result.effect_evidence.extend(scratch.effect_evidence) - result.effect_field_checks.extend(scratch.effect_field_checks) - result.effect_verified = scratch.effect_verified - if scratch.failure_category is not None: - result.failure_category = scratch.failure_category - if error is not None: - result.ok = False - result.error = error - result.safety_halt = True - if result.failure_category is None: - result.failure_category = ( - "governed_refusal" - if self.governed_authorization is not None - else "safety_halt" - ) - else: - result.safety_halt = result.safety_halt or scratch.safety_halt - - def _apply_pipelined_verdict( - self, - report: RunReport, - error: Optional[str], - *, - entry: Optional["PipelinedReadback"] = None, - ) -> None: - if error is None: - return - report.success = False - report.execution_completed = False - report.terminal_outcome = "halt" - report.results.append( - StepResult( - step_id="", - intent="program halt", - ok=False, - error=error, - safety_halt=True, - ) - ) - if entry is None: - entry = getattr(self, "_pipelined_readback", None) - report.halt = HaltObservation( - state_id=getattr(entry, "step_id", "") or "", - intent=getattr(entry, "intent", "") or "", - reason=error, - outcome="halt", - # The screen now belongs to the next item; nothing is probed. - observed_texts=[], - completed_intents=[ - r.intent for r in report.results if r.ok and not r.skipped - ], - ) - def _settle_pipelined_readback( self, report: RunReport, @@ -3213,60 +3055,6 @@ def _settle_pipelined_readback( report.save(run_dir) return report - def recheck_deferred_readback( - self, - workflow: Workflow, - deferred: Any, - *, - params: Mapping[str, RuntimeParamScalar], - run_id: str, - read_only: bool = False, - ) -> StepResult: - """Re-run a durable pause's deferred record check; send nothing. - - The check runs against the snapshot of the system of record taken - before the save, with this replayer's system-of-record verifier. - Returns the save's result with the verdict applied: ``ok`` when the - record check confirmed the save. - """ - - from openadapt_flow.policy import effects_for_actuation - from openadapt_flow.runtime.durable.approval import StateDiverged - - step = workflow.steps[deferred.step_index] - if step.id != deferred.step_id: - raise StateDiverged( - "the deferred record check names a different step than the bundle" - ) - verifier = self.effect_verifier - if verifier is None or not _pipeline_safe_verifier(verifier): - raise StateDiverged( - "re-running a deferred record check needs the run's REST, FHIR, " - "GraphQL or SQL record checker" - ) - self._run_id = run_id - effects = self._resolve_effects( - list(effects_for_actuation(step, deferred.actuation)), params - ) - before = EffectState.model_validate(deferred.before) - result = deferred.result.model_copy(deep=True) - scratch = StepResult(step_id=step.id, intent=step.intent, ok=True) - try: - error = self._verify_effects( - step, - before, - scratch, - effects=effects, - verifier=verifier, - read_only=read_only, - ) - except Exception as exc: # noqa: BLE001 - a raising verifier fails closed - error = f"read-back raised {type(exc).__name__}; reconciliation is required" - self._copy_pipelined_evidence( - SimpleNamespace(result=result, scratch=scratch), error - ) - return result - def _settle_durable_readback( self, entry: Any, error: Optional[str] ) -> Optional[str]: @@ -6664,45 +6452,6 @@ def _qualification_fault_driver_refusal(self, workflow: Workflow) -> Optional[st self._qualification_fault_public_key = trusted return None - def _apply_effect_fault_mutation( - self, - *, - gate: QualificationFaultGate, - step: Step, - actuation_path: Literal["gui", "api"], - effect_verifier: Any, - effects: tuple[Any, ...], - ) -> Any: - if self._qualification_fault_mutations: - return effect_verifier - before_sha256 = effect_verifier_input_sha256(effect_verifier, effects) - context = self._qualification_fault_context( - gate=gate, - step=step, - actuation_path=actuation_path, - before_input_sha256=before_sha256, - effect_verifier=effect_verifier, - effects=effects, - ) - if context is None: - return effect_verifier - driver = self._require_current_fault_driver_binding() - mutation = driver.mutate(context) - if mutation is None: - return effect_verifier - if not mutation.replace_effect_verifier: - raise RuntimeError("qualification_effect_fault_did_not_replace_verifier") - after_sha256 = effect_verifier_input_sha256( - mutation.effect_verifier, - effects, - ) - self._validate_fault_mutation( - context, - mutation.receipt, - after_input_sha256=after_sha256, - ) - return mutation.effect_verifier - # -- multi-surface routing (docs/MULTI_SURFACE.md) ----------------------- def _begin_surfaces( @@ -9448,536 +9197,6 @@ def _set_api_unavailable_refusal( # -- system-of-record effect verification ----------------------------------- - def _resolve_effects( - self, effects: list["Effect"], params: Mapping[str, RuntimeParamScalar] - ) -> list["Effect"]: - """Bind each effect's ``ValueExpr`` contract to THIS run's params (P0-3). - - Mirrors how an ``ApiBinding``'s ``{param}`` templates are filled at - actuation time: the effect a PARAMETERIZED workflow verifies must - describe the record IT WROTE THIS RUN, not the demonstration's. The - reserved ``__run_id__`` param exposes the stable-per-run identity so an - idempotency key can be bound per-run. A pure-literal (v1) effect is - returned value-identical -- ``resolve`` is a no-op for it. - """ - namespace = { - **{name: runtime_param_text(value) for name, value in params.items()}, - "__run_id__": self._run_id, - } - run_id_sha256 = hashlib.sha256(self._run_id.encode("utf-8")).hexdigest() - return [ - effect.resolve( - namespace, - opaque_param_sha256={"__run_id__": run_id_sha256}, - ) - for effect in effects - ] - - @staticmethod - def _capture_effect_pre_state(verifier: Any, effects: list["Effect"]) -> Any: - """Capture the pre-action baseline for resolved effect contracts. - - Multi-candidate deployments select an adapter per resolved effect. A - normal verifier keeps the established single snapshot behavior. - """ - capture_for_effects = getattr(verifier, "capture_pre_state_for_effects", None) - if callable(capture_for_effects): - return capture_for_effects(effects) - if getattr(verifier, "_openadapt_requires_preflight", False): - probe = _probe_adapter_connection(verifier) - if not probe.ok: - raise ValueError( - "the selected effect verifier failed its read-only connection " - f"preflight ({probe.substrate}: {probe.reason})" - ) - return verifier.capture_pre_state() - - def _keep_undo_prior_state( - self, - workflow: Workflow, - step: Step, - before: Any, - effects: Optional[list["Effect"]], - params: Mapping[str, Any], - ) -> None: - """Keep what a locating or restoring undo of ``step`` needs. - - Reads only the pre-action baseline already captured; never raises and - never changes the step's result (``after_stop.keep_prior_state``). - """ - run_dir = getattr(self, "_undo_prior_run_dir", None) - if run_dir is None or not workflow.undo_steps or not effects: - return - try: - state = self._effect_pre_state_for(before, effects[0]) - except Exception: # noqa: BLE001 - bookkeeping never stops a run - return - if getattr(state, "reachable", None) is not True: - return - from openadapt_flow.after_stop import keep_prior_state - - keep_prior_state( - workflow, step, list(getattr(state, "records", []) or []), params, run_dir - ) - - @staticmethod - def _effect_pre_state_for(before: Any, effect: "Effect") -> Any: - """Return one selected effect baseline, or a normal shared baseline.""" - selected = getattr(before, "for_effect", None) - if callable(selected): - return selected(effect).state - return before - - @staticmethod - def _effect_binding_for( - verifier: Any, before: Any, effect: "Effect" - ) -> tuple[Any, Any, Optional[Any], str]: - """Return the exact adapter, state, tier, and identity bound to an effect.""" - - selected = getattr(before, "for_effect", None) - if callable(selected): - binding = selected(effect) - return ( - binding.verifier, - binding.state, - binding.tier, - binding.verifier_identity, - ) - return ( - verifier, - before, - verifier_effect_tier(verifier, effect), - effect_verifier_identity(verifier), - ) - - @staticmethod - def _candidate_binding_refusal( - before: Any, effects: list["Effect"] - ) -> Optional[str]: - """Refuse a candidate whose identity or tier changed after selection.""" - - selected = getattr(before, "for_effect", None) - if not callable(selected): - return None - for effect in effects: - binding = selected(effect) - current_tier = verifier_effect_tier(binding.verifier, effect) - current_identity = effect_verifier_identity(binding.verifier) - if ( - current_tier != binding.tier - or current_identity != binding.verifier_identity - ): - return ( - "the selected effect verifier identity or evidence tier changed " - "after pre-action binding; refusing to use a different proof" - ) - return None - - @staticmethod - def _verify_current_effect( - verifier: Any, effect: "Effect", current: EffectState - ) -> Any: - """Use an adapter's current-state path without inventing a new baseline.""" - - candidate = effect.model_copy(deep=True) - original = candidate.model_dump(mode="json") - callback = getattr(verifier, "verify_current_state", None) - if callable(callback): - verdict = callback(candidate, current) - else: - from openadapt_flow.runtime.effects._common import judge_records - - # An effect whose CLAIM is a delta (``exact_new_set``) cannot be - # judged against a synthesized empty baseline: every record in - # scope would read as an addition, so the verdict would be - # fabricated rather than proved. Mark the synthetic baseline - # UNREACHABLE for those effects and let the judge return its own - # structured INDETERMINATE refusal. Every pre-existing kind keeps - # the readable empty baseline and is judged exactly as before. - needs_baseline = bool(candidate.requires_baseline) - detail: dict[str, Any] = {"current_state_readback": True} - if needs_baseline: - detail["baseline_unavailable_for_delta"] = True - baseline = EffectState( - substrate=current.substrate, - reachable=not needs_baseline, - records=[], - detail=detail, - ) - verdict = judge_records( - candidate, - baseline, - current.records if current.reachable is True else None, - substrate=current.substrate, - ) - if candidate.model_dump(mode="json") != original: - raise EffectContractMutationError( - "effect verifier changed the resolved effect contract" - ) - return verdict - - @classmethod - def _required_effect_pre_state_unreadable( - cls, verifier: Any, before: Any, effects: list["Effect"] - ) -> bool: - """Return true only when a selected effect needs, but lacks, a baseline. - - Different-path on-screen read-back proves persistence after input and - deliberately has no readable pre-action state. Delta, duplicate, and - collateral checks still require their selected verifier baseline. - """ - requirement = getattr(verifier, "requires_readable_pre_state_for", None) - selected = getattr(before, "for_effect", None) - missing_reachability = object() - for effect in effects: - if callable(selected): - required = bool(selected(effect).requires_readable_pre_state) - else: - required = ( - bool(requirement(effect)) - if callable(requirement) - else bool(effect.requires_baseline or effect.forbid_collateral_loss) - ) - state = cls._effect_pre_state_for(before, effect) - # Legacy in-process verifiers may retain an opaque pre-state for - # their own verify implementation. Their established verification - # path decides whether it is usable. If a legacy state exposes - # reachability, it must state exactly True; None, falsey values, - # and truthy non-bools are not evidence that its baseline is - # readable. Candidate deployments are stricter: their verifier - # accepts only EffectState, so a missing reachability value cannot - # bypass its pre-actuation guard. - reachable = getattr(state, "reachable", missing_reachability) - if ( - required - and reachable is not missing_reachability - and reachable is not True - ): - return True - return False - - def _profile_effect_tier_refusal( - self, - workflow: Workflow, - step: Step, - actuation_path: Literal["gui", "api"], - effects: list["Effect"], - verifier: object, - ) -> Optional[str]: - """Recheck effect strength immediately before governed actuation.""" - - authorization = self.governed_authorization - if authorization is None or authorization.execution_profile is None: - return None - from openadapt_flow.execution_profiles import required_effect_tier - from openadapt_flow.verification import VerificationTier - - minimum = ( - VerificationTier(authorization.minimum_effect_tier) - if authorization.minimum_effect_tier is not None - else required_effect_tier(workflow, authorization.execution_profile) - ) - if minimum is None: - return None - requirements = authorization.effect_requirements(step.id, actuation_path) - if requirements: - from openadapt_flow.policy import effects_for_actuation - - declared = effects_for_actuation( - step, "api" if actuation_path == "api" else "guarded_coordinate" - ) - if len(requirements) != len(declared) or len(effects) != len(declared): - return ( - "Qualified effect requirements changed after admission — " - "refusing to actuate; run aborted" - ) - for index, requirement in enumerate(requirements): - if ( - requirement.effect_index != index - or requirement.effect_contract_hash - != declared[index].contract_hash() - ): - return ( - "Qualified effect contract changed after admission — " - "refusing to actuate; run aborted" - ) - weak = [] - for index, effect in enumerate(effects): - required = ( - VerificationTier(requirements[index].minimum_tier) - if requirements - else minimum - ) - actual = verifier_effect_tier(verifier, effect) - if actual is None or not actual.satisfies(required): - weak.append("untyped" if actual is None else actual.name.lower()) - if not weak: - return None - observed = ", ".join(sorted(set(weak))) - return ( - "Effect verifier strength changed after admission: " - f"{observed} evidence cannot satisfy the required " - "qualified effect tier — refusing to actuate; run aborted" - ) - - def _all_default_readback(self, effects: list["Effect"]) -> bool: - """Whether EVERY declared effect is an auto-derived DIFFERENT-PATH - on-screen read-back that may be verified out of the box with no - connector (measured false-CONFIRM ~0). A same-surface read-back or any - structured system-of-record effect makes this False — those still - require a configured verifier (fail-safe).""" - from openadapt_flow.runtime.effects.onscreen import is_default_readback_effect - - return bool(effects) and all(is_default_readback_effect(e) for e in effects) - - def _auto_readback_verifier(self) -> Any: - """The backend-bound on-screen read-back verifier for the no-connector - default path (built once, reused across steps).""" - verifier = getattr(self, "_readback_verifier", None) - if verifier is None: - from openadapt_flow.runtime.effects.onscreen import ( - OnScreenReadbackVerifier, - ) - - verifier = OnScreenReadbackVerifier(backend=self.backend) - self._readback_verifier = verifier - return verifier - - def _server_response_mark(self) -> Optional[int]: - """Where the backend's server-answer log stands, or None when the - backend doesn't see server answers (every non-browser backend).""" - - mark = getattr(self.backend, "server_response_mark", None) - if not callable(mark): - return None - try: - return int(mark()) - except Exception: # noqa: BLE001 - evidence only, never a failure - return None - - def _collect_server_responses(self, result: StepResult, mark: int) -> None: - since = getattr(self.backend, "server_responses_since", None) - if not callable(since): - return - try: - responses = list(since(mark)) - except Exception: # noqa: BLE001 - evidence only, never a failure - return - result.server_responses = responses[:_MAX_SERVER_RESPONSES] - - @timed_span("readback") - def _verify_effects( - self, - step: Step, - before: EffectState, - result: StepResult, - effects: Optional[list["Effect"]] = None, - verifier: Any = None, - *, - read_only: bool = False, - ) -> Optional[str]: - """Verify each declared Effect against the system of record; HALT on - any non-CONFIRMED verdict. - - Runs AFTER the action and its screen postconditions (for a GUI write), - or immediately after an API actuation. For each effect the configured - verifier rules CONFIRMED / REFUTED / INDETERMINATE against the REAL - record (an API/DB read, never the screen). A CONFIRMED effect proceeds; - a non-CONFIRMED effect halts, except that an IRREVERSIBLE effect is - first routed through ``reconcile_or_escalate`` -- a duplicate the - configured compensator can undo is RECONCILED (proceed), everything else - ESCALATEs (halt). Every verdict is recorded on ``result.effect_results`` - for the audit trail. Makes ZERO model calls (the $0 runtime guarantee). - - Args: - step: The step being verified (for the audit/error text). - before: The pre-action snapshot of the system of record. - result: The step result to record verdicts on. - effects: The effects to verify; defaults to ``step.effects`` (the - GUI path). The API tier passes ``api_binding.effects`` only. - - Returns an error string (HALT) or None (all effects confirmed or - reconciled). - """ - # ``verifier`` is the configured one by default, but the caller may pass - # the auto-wired backend-bound read-back verifier (the no-connector - # default path) for a step whose effects are different-path read-backs. - if verifier is None: - verifier = self.effect_verifier - assert verifier is not None # guaranteed by the caller - if effects is None: - effects = step.effects - for effect in effects: - refusal = placeholder_effect_refusal(step, effect, result) - if refusal is not None: - return refusal - try: - verdict = verify_effect_without_mutation(verifier, effect, before) - scope = effect_endpoint_scope(verifier) - selected_pre_state = getattr(before, "for_effect", None) - if callable(selected_pre_state): - # Candidate selection and its evidence strength are pinned - # before input. Do not recompute the tier after delivery: - # a stateful plugin must not change the receipt contract. - binding = selected_pre_state(effect) - tier = binding.tier - identity = binding.verifier_identity - scope = effect_endpoint_scope(binding.verifier) - if ( - verifier_effect_tier(binding.verifier, effect) != tier - or effect_verifier_identity(binding.verifier) != identity - ): - result.effect_verified = False - result.safety_halt = True - result.failure_category = "governed_refusal" - result.effect_results.append( - "selected effect verifier identity or evidence tier " - "changed after input; HALT" - ) - return ( - f"Effect verifier binding changed after input for step " - f"'{step.id}' — refusing evidence from a different " - "adapter or tier; reconciliation is required" - ) - else: - tier = verifier_effect_tier(verifier, effect) - identity = effect_verifier_identity(verifier) - except EffectContractMutationError: - result.effect_verified = False - result.safety_halt = True - result.failure_category = "governed_refusal" - result.effect_results.append( - "effect verifier changed the resolved effect contract; HALT" - ) - return ( - f"Effect verifier changed the resolved contract for step " - f"'{step.id}' — refusing mutable verification evidence; " - "run aborted" - ) - result.effect_field_checks.extend( - effect_field_checks(effect, verdict, tier) - ) - if verdict.confirmed: - result.effect_evidence.append( - EffectVerificationEvidence( - effect_contract_hash=effect.contract_hash(), - substrate=verdict.substrate, - verifier_identity=identity, - verification_tier=(int(tier) if tier is not None else None), - initial_verdict=verdict.verdict.value, - final_verdict=verdict.verdict.value, - observed_effect=verdict.observed_effect, - endpoint_scope=scope, - read_evidence=verdict.read_evidence, - ) - ) - result.effect_results.append( - f"[{verdict.substrate}] {effect.kind.value}: CONFIRMED" - + (f" — {verdict.reason}" if verdict.reason else "") - ) - continue - - # Non-CONFIRMED: never proceed on an unverified/contradicted write. - # An irreversible effect gets one reconcile-or-escalate pass (a - # compensable duplicate is fixable; missing / partial / collateral - # loss / INDETERMINATE always escalate). A reversible effect just - # halts. Either way the run stops -- this is the same - # refuse-rather-than-guess posture as the identity gate. - if effect.risk == "irreversible" and not read_only: - comp = reconcile_or_escalate( - effect, - verdict, - verifier=verifier, - before=before, - compensator=self.effect_compensator, - ) - if comp.proceed: - final_verdict = comp.final_verdict or verdict - result.effect_evidence.append( - EffectVerificationEvidence( - effect_contract_hash=effect.contract_hash(), - substrate=final_verdict.substrate, - verifier_identity=identity, - verification_tier=(int(tier) if tier is not None else None), - initial_verdict=verdict.verdict.value, - final_verdict=final_verdict.verdict.value, - observed_effect=final_verdict.observed_effect, - endpoint_scope=scope, - read_evidence=final_verdict.read_evidence, - reconciliation_completed=True, - reconciliation_actions=comp.actions_taken, - ) - ) - result.effect_results.append( - f"[{verdict.substrate}] {effect.kind.value}: " - f"{verdict.verdict.value.upper()} → RECONCILED " - f"({comp.actions_taken} action(s)) — {comp.reason}" - ) - continue - result.effect_verified = False - final_verdict = comp.final_verdict or verdict - result.effect_evidence.append( - EffectVerificationEvidence( - effect_contract_hash=effect.contract_hash(), - substrate=final_verdict.substrate, - verifier_identity=identity, - verification_tier=(int(tier) if tier is not None else None), - initial_verdict=verdict.verdict.value, - final_verdict=final_verdict.verdict.value, - observed_effect=final_verdict.observed_effect, - endpoint_scope=scope, - read_evidence=final_verdict.read_evidence, - reconciliation_actions=comp.actions_taken, - deferred_check=verdict.deferred_check, - ) - ) - result.effect_results.append( - f"[{verdict.substrate}] {effect.kind.value}: " - f"{verdict.verdict.value.upper()} → " - f"{comp.outcome.value.upper()} — {comp.reason}" - ) - prefix, read = _effect_read_wording(tier) - return ( - f"{prefix} HALTED step " - f"'{step.id}' ({step.intent}): {effect.kind.value} " - f"{verdict.verdict.value} against the {verdict.substrate} " - f"{read} and could not be reconciled " - f"({comp.outcome.value}) — " - f"{comp.escalation or comp.reason} — run aborted" - ) - - result.effect_verified = False - result.effect_evidence.append( - EffectVerificationEvidence( - effect_contract_hash=effect.contract_hash(), - substrate=verdict.substrate, - verifier_identity=identity, - verification_tier=(int(tier) if tier is not None else None), - initial_verdict=verdict.verdict.value, - final_verdict=verdict.verdict.value, - observed_effect=verdict.observed_effect, - endpoint_scope=scope, - read_evidence=verdict.read_evidence, - deferred_check=verdict.deferred_check, - ) - ) - result.effect_results.append( - f"[{verdict.substrate}] {effect.kind.value}: " - f"{verdict.verdict.value.upper()} — {verdict.reason}" - ) - prefix, read = _effect_read_wording(tier) - return ( - f"{prefix} HALTED step " - f"'{step.id}' ({step.intent}): {effect.kind.value} " - f"{verdict.verdict.value} against the {verdict.substrate} " - f"{read} (the screen indicated completion but the " - f"declared outcome is contradicted or unverifiable) — " - f"{verdict.reason} — run aborted" - ) - - result.effect_verified = True - return None - def _identity_band_still_changing( self, step: Step, resolution: Resolution, read_png: bytes ) -> bool: @@ -17156,46 +16375,6 @@ def _selection_target_continuous( and abs(refreshed[1] - focused[1]) <= qualified_h * 0.25 ) - @staticmethod - def _mapped_selection_readback_region( - recorded_target: Region, - recorded_readback: Region, - live_target: Region, - frame_png: bytes, - ) -> Optional[Region]: - """Map the recorded readback band onto a fresh live target. - - Absolute recording coordinates never drive verification. The mapping - preserves the band's target-relative offsets while allowing the - already-qualified target geometry to translate or scale modestly, then - clamps it to the exact final frame. - """ - - from openadapt_flow.vision import imgops - - frame = imgops.decode_bgr(frame_png) - if frame is None: - return None - frame_h, frame_w = frame.shape[:2] - target_x, target_y, target_w, target_h = recorded_target - read_x, read_y, read_w, read_h = recorded_readback - live_x, live_y, live_w, live_h = live_target - if min(target_w, target_h, read_w, read_h, live_w, live_h) <= 0: - return None - scale_x = live_w / target_w - scale_y = live_h / target_h - mapped_x = round(live_x + (read_x - target_x) * scale_x) - mapped_y = round(live_y + (read_y - target_y) * scale_y) - mapped_w = max(1, round(read_w * scale_x)) - mapped_h = max(1, round(read_h * scale_y)) - left = max(0, mapped_x) - top = max(0, mapped_y) - right = min(frame_w, mapped_x + mapped_w) - bottom = min(frame_h, mapped_y + mapped_h) - if right <= left or bottom <= top: - return None - return (left, top, right - left, bottom - top) - # -- closed-loop scroll ------------------------------------------------------ @timed_span("resolve") From 3f4dad0fedee93d8b903ff707197d555c05a900d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:09:50 -0500 Subject: [PATCH 3/5] refactor(flow): move the replayer's confirming concern to a mixin, unchanged --- packages/flow/docs/design/DECOMPOSITION.md | 2 +- .../runtime/replay/confirming.py | 1210 +++++++++++++++++ .../flow/openadapt_flow/runtime/replayer.py | 1054 +------------- 3 files changed, 1217 insertions(+), 1049 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/replay/confirming.py diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 4dfe67a693..380edf5b17 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -605,7 +605,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 17872 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 16830 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6830 | diff --git a/packages/flow/openadapt_flow/runtime/replay/confirming.py b/packages/flow/openadapt_flow/runtime/replay/confirming.py new file mode 100644 index 0000000000..24fc516891 --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/replay/confirming.py @@ -0,0 +1,1210 @@ +# mypy: disable-error-code="empty-body" +"""Moved replayer code. + +Moved verbatim from ``openadapt_flow.runtime.replayer.Replayer`` by +scripts/extract_mixin.py (docs/design/DECOMPOSITION.md, section 4.1). +``_ConfirmingHost`` declares, for mypy only, what this code reads from the +Replayer it is mixed into. +""" + +from __future__ import annotations + +import time +from collections import Counter +from datetime import datetime, timezone +from typing import TYPE_CHECKING, Any, Optional # noqa: F401 + +from openadapt_flow.backend import NativeSelectBackend, StructuralBackend +from openadapt_flow.ir import ActionDeliveryUncertainty, ActionKind, Region +from openadapt_flow.runtime import identity as identity_mod +from openadapt_flow.runtime.authorization import runtime_params_for_gui +from openadapt_flow.runtime.program_predicates import evaluate_program_predicate +from openadapt_flow.runtime.replay._shared import ( + _PAGE_SCALE_BAND, + FIELD_REGION_HEIGHT, + FIELD_REGION_PAD, + MASKED_FIELD_REGION_WIDTH, + MASKED_MIN_CONFIDENCE, + MASKED_NEW_TEXT_SLACK, + MASKED_REPEAT_FRACTION, + PC_STRUCTURAL_TEMPLATE_THRESHOLD, + PC_TEMPLATE_SEARCH_PAD, + PC_TEMPLATE_THRESHOLD, + _frame_viewport, + _uniform_page_scale, +) +from openadapt_flow.runtime.resolver import pad_region +from openadapt_flow.runtime.step_timing import timed_span +from openadapt_flow.runtime.typed_echo import read_typed_echo + +if TYPE_CHECKING: + from pathlib import Path + from typing import Callable, Mapping + + from openadapt_flow.backend import Backend + from openadapt_flow.ir import ( + Point, + Predicate, + Resolution, + Step, + StepResult, + Workflow, + ) + from openadapt_flow.runtime.authorization import ( + GovernedRunAuthorization, + RuntimeParamScalar, + ) + from openadapt_flow.runtime.replay._shared import _DeliveryResultT + + +class _ConfirmingHost: + _asset_bytes: Any + + def _cancel_guarded_keyboard(self) -> None: ... + def _deliver_backend_call( + self, result: StepResult, call: Callable[[], _DeliveryResultT] + ) -> _DeliveryResultT: ... + def _delivery_authorization_refusal( + self, + workflow: Workflow, + params: Mapping[str, RuntimeParamScalar], + step: Step, + result: StepResult, + *, + interstitial: bool = False, + api_delivery: bool = False, + ) -> Optional[str]: ... + def _describe_postcondition(self, pc: Any) -> str: ... + @staticmethod + def _describe_predicate(pred: Predicate) -> str: ... + def _exact_text_holds(self, text: str, frame_png: bytes) -> bool: ... + def _fresh_actuation_authorization_refusal( + self, workflow: Workflow, params: Mapping[str, RuntimeParamScalar], step: Step + ) -> Optional[str]: ... + + _governed_asset_mutation: Optional[str] + _handle_interstitials: Any + _mapped_selection_readback_region: Any + _pc_page_scale: Any + _pc_scaled_match: Any + + def _poll_postconditions( + self, + step: Step, + frame_png: bytes, + bundle_dir: Path, + start_state: dict[str, Any], + ) -> tuple[bool, bytes]: ... + @staticmethod + def _postcondition_confirms_a_write( + step: Step, workflow: Optional[Workflow] + ) -> bool: ... + def _postcondition_passes( + self, + pc: Any, + frame_png: bytes, + bundle_dir: Path, + start_state: Optional[dict[str, Any]] = None, + ) -> bool: ... + def _profile_runtime_refusal(self, workflow: Workflow) -> Optional[str]: ... + def _record_dry_run_preconditions(self, step: Step, result: StepResult) -> None: ... + def _require_locale_invariants_before_keyboard( + self, workflow: Workflow + ) -> Optional[str]: ... + + _require_qualification_environment_current: Any + + def _resolve_step( + self, + step: Step, + screen_png: bytes, + bundle_dir: Path, + workflow: Workflow, + *, + allow_grounder: bool = True, + allow_target_ocr: bool = True, + ) -> tuple[Optional[Resolution], Optional[Region], Optional[str]]: ... + def _revalidate_consequential_actuation( + self, + step: Step, + resolution: Optional[Resolution], + matched_region: Optional[Region], + before_png: bytes, + params: Mapping[str, RuntimeParamScalar], + workflow: Workflow, + bundle_dir: Path, + result: StepResult, + *, + run_dir: Path, + arm_keyboard: bool = False, + ) -> tuple[Optional[Resolution], Optional[Region], bytes, Optional[str]]: ... + + _settle_seeded: Any + + def _stamp_duplicate_check(self, result: Any, failed_pcs: Any) -> None: ... + def _step_needs_consequential_revalidation( + self, step: Step, workflow: Workflow + ) -> bool: ... + def _wait_starting_state_settled( + self, before_png: bytes + ) -> tuple[bytes, Optional[str], Optional[bool]]: ... + + backend: Backend + governed_authorization: Optional[GovernedRunAuthorization] + poll_interval_s: float + state_verifier: Optional[Any] + vision: Any + + +if TYPE_CHECKING: + _Base = _ConfirmingHost +else: + _Base = object + + +class Confirming(_Base): + """Moved replayer code.""" + + def _apply_step_gates( + self, + step: Step, + before_png: bytes, + bundle_dir: Path, + params: Mapping[str, RuntimeParamScalar], + result: StepResult, + workflow: Optional[Workflow] = None, + ) -> tuple[bool, Optional[str], bytes]: + """Evaluate readiness, interstitials, guard, then wait_until before acting. + + Runs in state-dependency order, all model-free: + + 1. **readiness** (``require_settled``) - refuse to act on a frame that + never settled (still-loading / mid-transition); HALT gracefully. + 2. **interstitials** - a KNOWN reversible, non-consequential overlay on + the entry frame gets one audited dismissal plus declared clearance + verification, or HALTs before the workflow action. + 3. **guard** (precondition) on the entry frame - unmet HALTs (default) + or SKIPs (``on_unmet="skip"``). + 4. **wait_until** (readiness predicate) - polled, bounded, HALT on + timeout (never proceed-anyway). + + Returns ``(proceed, error, before_png)``: + + - ``(True, None, frame)`` - proceed to resolve/act (frame may have been + re-settled while polling a wait_until predicate). + - ``(False, None, frame)`` - the guard was unmet with ``on_unmet="skip"``: + the step is a no-op success (caller marks it ``skipped``). + - ``(False, error, frame)`` - HALT: an un-ready screen, a blocking / + undismissable interstitial, an unmet ``halt`` guard, or a + ``wait_until`` predicate that never held within its bound (fail-safe; + the run NEVER proceeds-anyway on an unmet readiness predicate). + + Model-free: predicates are evaluated by :meth:`_predicate_holds`. + """ + if workflow is not None: + profile_refusal = self._profile_runtime_refusal(workflow) + if profile_refusal is not None: + result.safety_halt = True + result.failure_category = "governed_refusal" + return ( + False, + f"{profile_refusal} at the actuation boundary — refusing " + "to act; run aborted", + before_png, + ) + # (1) Readiness: never act on a frame that never settled. + before_png, readiness_error, settled = self._wait_starting_state_settled( + before_png + ) + result.starting_state_settled = settled + if readiness_error is not None: + # Like an interstitial refusal, a not-ready starting state is a + # safety halt. A program on_exception edge must not convert the + # explicit refusal into a successful terminal outcome. + result.safety_halt = True + return False, readiness_error, before_png + + # (2) Interstitials: dismiss a KNOWN overlay, or HALT gracefully. + before_png, interstitial_error = self._handle_interstitials( + step, + before_png, + bundle_dir, + params, + result, + result.interstitial_actions, + workflow, + ) + if interstitial_error is not None: + # An interstitial refusal is a state-safety halt, not an ordinary + # workflow exception a program on_exception edge may turn into a + # successful outcome after an uncertain/blocked pre-action state. + result.safety_halt = True + return False, interstitial_error, before_png + + # Guard (precondition) on the entry frame. + guard_holds = step.guard is None or self._predicate_holds( + step.guard.predicate, + before_png, + bundle_dir, + params, + workflow=workflow, + ) + if self._governed_asset_mutation is not None: + return False, self._governed_asset_mutation, before_png + if not guard_holds: + assert step.guard is not None + if step.guard.on_unmet == "skip": + return False, None, before_png + return ( + False, + ( + f"Guard precondition for step '{step.id}' ({step.intent}) is " + f"unmet on the current screen " + f"({self._describe_predicate(step.guard.predicate)}) — " + "refusing to act; run aborted" + ), + before_png, + ) + + # wait_until (readiness). SCROLL consumes its own predicate as the stop + # condition of its closed loop (_act_scroll), so it is skipped here. + if step.wait_until is not None and step.action is not ActionKind.SCROLL: + pred = step.wait_until + deadline = time.monotonic() + pred.timeout_s + while True: + if self._predicate_holds( + pred, + before_png, + bundle_dir, + params, + workflow=workflow, + ): + self._record_dry_run_preconditions(step, result) + return True, None, before_png + if time.monotonic() >= deadline: + return ( + False, + ( + f"wait_until predicate for step '{step.id}' " + f"({step.intent}) did not hold within " + f"{pred.timeout_s:.1f}s " + f"({self._describe_predicate(pred)}) — readiness never " + "reached; refusing to proceed-anyway; run aborted" + ), + before_png, + ) + time.sleep(self.poll_interval_s) + before_png = self.vision.wait_settled(self.backend) + + self._record_dry_run_preconditions(step, result) + return True, None, before_png + + def _predicate_holds( + self, + pred: Predicate, + frame_png: bytes, + bundle_dir: Path, + params: Mapping[str, RuntimeParamScalar], + *, + workflow: Optional[Workflow] = None, + ) -> bool: + """Evaluate a Predicate against the current frame / run params. + + Deterministic and ZERO model calls (the $0 runtime guarantee): + ``anchor_resolves`` runs the resolution ladder with NO grounder, + ``text_present`` / ``text_absent`` use the tolerant OCR presence check, + ``param_equals`` is a string compare, and ``and`` / ``or`` / ``not`` + compose. An unknown kind fails safe (does not hold). An exact + ``text_present`` uses :meth:`_exact_text_holds` (OCR, then the DOM). + """ + kind = pred.kind.value if hasattr(pred.kind, "value") else pred.kind + if kind == "text_present" and pred.exact: + return bool(pred.text and self._exact_text_holds(pred.text, frame_png)) + return evaluate_program_predicate( + pred, + frame_png, + runtime_params_for_gui(params), + vision=self.vision, + viewport=_frame_viewport(frame_png), + asset_loader=lambda rel: self._asset_bytes( + bundle_dir, + rel, + workflow=workflow, + ), + ) + + def _field_region( + self, + field_point: Optional[Point], + structural_region: Optional[Region] = None, + *, + masked: bool = False, + ) -> Optional[Region]: + """Region to observe for typed input, or None for the whole frame.""" + vw, vh = self.backend.viewport + if structural_region is not None: + sx, sy, sw, sh = structural_region + x = max(0, sx - FIELD_REGION_PAD) + y = max(0, sy - FIELD_REGION_PAD) + right = min(vw, sx + sw + FIELD_REGION_PAD) + bottom = min(vh, sy + sh + FIELD_REGION_PAD) + if right > x and bottom > y: + return (x, y, right - x, bottom - y) + if field_point is None: + return None + w = min(MASKED_FIELD_REGION_WIDTH, vw) if masked else vw + h = min(FIELD_REGION_HEIGHT, vh) + x = min(max(0, field_point[0] - w // 2), max(0, vw - w)) + y = min(max(0, field_point[1] - h // 2), max(0, vh - h)) + return (x, y, w, h) + + def _ocr_squashed(self, png: bytes, region: Optional[Region]) -> str: + """Squashed OCR text of a (region of a) frame.""" + lines = self.vision.ocr(png, region=region) + return identity_mod.comparison_squash(" ".join(line.text for line in lines)) + + def _readable_chars(self, png: bytes, region: Optional[Region]) -> int: + """Confidently readable alphanumeric characters in a region. + + The masked-acceptance metric (see ``MASKED_NEW_TEXT_SLACK``): + password dots OCR as nothing, low-confidence noise, punctuation + runs, or — on some platform renderers — confident homogeneous + digit runs, while a dialog adds confident words. Counting only + alphanumeric characters of confident, non-homogeneous lines is + also invariant to OCR merging or splitting the same text into + different boxes between frames. + """ + total = 0 + for line in self.vision.ocr(png, region=region): + if getattr(line, "confidence", 1.0) < MASKED_MIN_CONFIDENCE: + continue + alnum = [ch for ch in line.text if ch.isalnum()] + if not alnum: + continue + most_common = max(alnum.count(ch) for ch in set(alnum)) + if len(alnum) >= 4 and most_common / len(alnum) >= MASKED_REPEAT_FRACTION: + continue # homogeneous glyph run: masked-dot misread + total += len(alnum) + return total + + def _text_value_at(self, field_point: Optional[Point]) -> Optional[str]: + """Read an exact editable value when the backend can expose one. + + ``None`` means the substrate cannot make this observation. Empty text + is returned as ``""`` and remains distinguishable from unavailable. + Exceptions fail closed into the visual verifier rather than escaping. + """ + reader = getattr( + self.backend, + "text_value_at" if field_point is not None else "focused_text_value", + None, + ) + if not callable(reader): + return None + try: + value = reader(*field_point) if field_point is not None else reader() + except Exception: + return None + return value if isinstance(value, str) else None + + def _typed_input_landed( + self, + text: str, + field_point: Optional[Point], + baseline_png: bytes, + *, + field_region: Optional[Region] = None, + baseline_field_value: Optional[str] = None, + allow_masked: bool = False, + ) -> tuple[bool, bool]: + """Did the just-typed ``text`` visibly land? + + Exact structural readback is authoritative when the backend exposes + it. Otherwise the complete lowercased, whitespace-squashed value must + match the field's new OCR text (retried at 2x resolution), including + short values. + Whole unchanged context lines may be excluded. Pixel-only acceptance + is restricted to steps declared ``secret``: masked password dots may + render no readable text. A dialog + painting over the region or an unreadable ordinary field must never + count as "input landed". + + Returns: + ``(landed, changed)`` — the verdict, and whether the field + region's pixels changed at all (the caller's retry decision: + retyping is only safe when nothing changed). + """ + after_png = self._settle_seeded() + # Masked input has no readable value: keep its pixel-only change + # evidence local, so an unrelated change elsewhere cannot confirm it. + region = self._field_region(field_point, field_region, masked=allow_masked) + if baseline_field_value is not None: + expected = baseline_field_value + text + after_at_point = ( + self._text_value_at(field_point) if field_point is not None else None + ) + after_focused = self._text_value_at(None) + + # Focus-bound readback is the strongest confirmation. A full-page + # cover can hide the field from hit-testing while leaving that + # exact editable element focused, so focused readback also + # preserves the intended safe-halt-at-the-next-action behavior. + if after_focused == expected: + return True, expected != baseline_field_value + + # If hit-testing can read the value but focus moved elsewhere, an + # interstitial/dialog stole focus after delivery. That is an + # unknown state, not a success: the value could belong to an + # obscured/replaced control. + if after_at_point == expected: + return False, True + + observed = [ + value for value in (after_at_point, after_focused) if value is not None + ] + if observed and all(value == baseline_field_value for value in observed): + return False, False + if observed: + # A partial/different value is an unknown state and must halt + # without destructive select-all. + return False, True + # A structurally readable field disappearing after delivery means + # it was covered, replaced, or navigated away. Do not downgrade to + # OCR, which could read the intended text elsewhere on the screen. + return False, True + changed = self.vision.pixels_changed(baseline_png, after_png, region=region) + # Dropdown: typing selects the option whose label matches. When the + # focused at the field point now shows exactly the typed - # label (whitespace-squashed, case-insensitive), the input landed. - # Any other answer falls through to the visual check, unchanged. - if field_point is not None and not allow_masked: - reader = getattr(self.backend, "focused_select_label_at", None) - label: Optional[str] = None - if callable(reader): - try: - label = reader(int(field_point[0]), int(field_point[1])) - except Exception: - label = None - if ( - isinstance(label, str) - and identity_mod.comparison_squash(text) - and identity_mod.comparison_squash(label).casefold() - == identity_mod.comparison_squash(text).casefold() - ): - return True, True - if not changed: - return False, False - needle = identity_mod.comparison_squash(text) - - def exact_ocr_value( - before: bytes, after: bytes, crop: Optional[Region] - ) -> bool: - observed = [ - identity_mod.comparison_squash(line.text) - for line in self.vision.ocr(after, region=crop) - if identity_mod.comparison_squash(line.text) - ] - if needle and "".join(observed) == needle: - return True - if allow_masked or not needle: - return False - # The readback window may include unchanged labels beside the - # field. Remove whole unchanged OCR lines, with multiplicity; - # every remaining character must belong to the complete value. - previous = Counter( - identity_mod.comparison_squash(line.text) - for line in self.vision.ocr(before, region=crop) - ) - added = [] - for value in observed: - if previous[value]: - previous[value] -= 1 - else: - added.append(value) - return "".join(added) == needle - - if exact_ocr_value(baseline_png, after_png, region): - return True, changed - if region is not None: - upscaled = identity_mod.upscale_crop(after_png, region) - before_upscaled = identity_mod.upscale_crop(baseline_png, region) - if upscaled is not None and before_upscaled is not None: - if exact_ocr_value(before_upscaled, upscaled, None): - return True, changed - # Pixels changed but the value is unreadable: masked rendering is - # the only acceptable explanation, and masked rendering adds no - # confidently readable alphanumeric text (dot glyphs OCR as - # nothing, noise, or punctuation — platform-dependent). Anything - # else (a dialog over the field, another widget's text) must fail - # the verdict. - if not allow_masked: - return False, changed - landed = ( - self._readable_chars(after_png, region) - <= self._readable_chars(baseline_png, region) + MASKED_NEW_TEXT_SLACK - ) - return landed, changed - - @timed_span("postcondition") - def _verify_typed_input( - self, - step: Step, - text: str, - field_point: Optional[Point], - baseline_png: bytes, - result: StepResult, - *, - workflow: Workflow, - params: Mapping[str, RuntimeParamScalar], - bundle_dir: Path, - run_dir: Path, - resolution: Optional[Resolution], - field_region: Optional[Region] = None, - baseline_field_value: Optional[str] = None, - allow_masked: bool = False, - allow_retry: bool = True, - ) -> Optional[str]: - """Verify TYPE; retry input only after exact unchanged-field proof. - - Bounded read-only observations live in ``typed_echo``. A changed but - unreadable field always halts; remaining browser/structural guards - decide whether an unchanged field permits one refocus/retype. - """ - landed, changed = read_typed_echo( - lambda: self._typed_input_landed( - text, - field_point, - baseline_png, - field_region=field_region, - baseline_field_value=baseline_field_value, - allow_masked=allow_masked, - ) - ) - if landed: - result.input_verified = True - return None - if changed: - result.input_verified = False - return ( - f"Typed input could not be verified for step '{step.id}' " - f"({step.intent}): the field region changed but the typed " - "value is not readable there (something else rendered over " - "or instead of the input) — retyping is unsafe in this " - "state; run aborted" - ) - can_retry = ( - allow_retry - and workflow.surface in (None, "web") - and isinstance(self.backend, StructuralBackend) - and bool(self.backend.url) - and baseline_field_value is not None - ) - if not can_retry: - result.input_verified = False - # This is a halt, not a new delivery edge: recheck authority - # without consuming a durable fence or an approval permit. - refusal = self._fresh_actuation_authorization_refusal( - workflow, params, step - ) - if refusal is not None: - result.safety_halt = True - result.failure_category = ( - "governed_refusal" - if self.governed_authorization is not None - else "safety_halt" - ) - return refusal - return ( - f"Typed input could not be verified for step '{step.id}' " - f"({step.intent}): the target field showed no confirmed change; " - "refusing an unleased refocus/retype retry after possibly stray input" - ) - result.input_retried = True - retry_resolution = resolution - retry_region = field_region - retry_frame = baseline_png - needs_revalidation = self._step_needs_consequential_revalidation(step, workflow) - if field_point is not None: - if needs_revalidation: - ( - retry_resolution, - retry_region, - retry_frame, - retry_error, - ) = self._revalidate_consequential_actuation( - step, - retry_resolution, - retry_region, - retry_frame, - params, - workflow, - bundle_dir, - result, - run_dir=run_dir, - ) - if retry_error is not None: - result.input_verified = False - return retry_error - if retry_resolution is None: - result.input_verified = False - return ( - f"Typed input retry for step '{step.id}' ({step.intent}) " - "could not freshly resolve its field; run aborted" - ) - field_point = retry_resolution.point - refusal = self._delivery_authorization_refusal( - workflow, params, step, result - ) - if refusal is not None: - result.input_verified = False - return refusal - self._require_qualification_environment_current() - self._deliver_backend_call( - result, - lambda: self.backend.click(*field_point), - ) - # Replace, don't append: if the first attempt DID land but was - # not visible to the diff/OCR, retyping raw would double it. - if needs_revalidation: - ( - retry_resolution, - retry_region, - retry_frame, - retry_error, - ) = self._revalidate_consequential_actuation( - step, - retry_resolution, - retry_region, - retry_frame, - params, - workflow, - bundle_dir, - result, - run_dir=run_dir, - arm_keyboard=True, - ) - if retry_error is not None: - result.input_verified = False - return retry_error - if retry_resolution is None or retry_resolution.point != field_point: - self._cancel_guarded_keyboard() - result.input_verified = False - return ( - f"Typed input retry for step '{step.id}' ({step.intent}) " - "resolved to a different field after refocus; run aborted" - ) - refusal = self._delivery_authorization_refusal( - workflow, params, step, result - ) - if refusal is not None: - result.input_verified = False - return refusal - self._require_qualification_environment_current() - self._deliver_backend_call( - result, - lambda: self.backend.press("ControlOrMeta+a"), - ) - - # The refocus click and select-all key each consume an opaque remote - # lease. Acquire and validate one more exact frame for the retype edge. - if needs_revalidation: - ( - retry_resolution, - retry_region, - retry_baseline, - retry_error, - ) = self._revalidate_consequential_actuation( - step, - retry_resolution, - retry_region, - retry_frame, - params, - workflow, - bundle_dir, - result, - run_dir=run_dir, - arm_keyboard=True, - ) - if retry_error is not None: - result.input_verified = False - return retry_error - else: - retry_baseline = self.backend.screenshot() - if ( - needs_revalidation - and field_point is not None - and (retry_resolution is None or retry_resolution.point != field_point) - ): - self._cancel_guarded_keyboard() - result.input_verified = False - return ( - f"Typed input retry for step '{step.id}' ({step.intent}) " - "resolved to a different field before retyping; run aborted" - ) - refusal = self._delivery_authorization_refusal(workflow, params, step, result) - if refusal is not None: - result.input_verified = False - return refusal - locale_refusal = self._require_locale_invariants_before_keyboard(workflow) - if locale_refusal is not None: - result.input_verified = False - result.safety_halt = True - result.failure_category = "safety_halt" - return locale_refusal - self._require_qualification_environment_current() - self._deliver_backend_call(result, lambda: self.backend.type_text(text)) - landed, _changed = self._typed_input_landed( - text, - field_point, - retry_baseline, - field_region=retry_region, - # Select-all means the retry's expected exact value is ``text`` - # regardless of what the field contained before replacement. - baseline_field_value="" if baseline_field_value is not None else None, - allow_masked=allow_masked, - ) - if landed: - result.input_verified = True - return None - result.input_verified = False - return ( - f"Typed input could not be verified for step '{step.id}' " - f"({step.intent}): the screen did not change where the text " - "should have appeared and OCR could not find the typed value, " - "after one refocus-and-retype retry — keystrokes likely fell on " - "a non-input target (focus lost); run aborted" - ) - - @timed_span("postcondition") - def _verify_selected_option( - self, - step: Step, - text: str, - after_png: bytes, - bundle_dir: Path, - workflow: Workflow, - result: StepResult, - ) -> Optional[str]: - """Require the option value on the final settled, re-resolved field. - - Unlike ordinary TYPE verification, selection never accepts pixel - change alone and never retries: the commit key may already have changed - the control. Structural readback must equal the intended option, or OCR - must recover one complete exactly normalized line inside only the final - live field region. The compiled region qualifies geometry but never - supplies runtime coordinates. This method does not settle again: its - caller passes the one final frame used by all post-action checks. - """ - - if step.choice is not None: - confirm = getattr(self.backend, "confirm_choice", None) - cause_type = "choice_unverified" - try: - result.input_verified = bool(callable(confirm) and confirm()) - except Exception as exc: - result.input_verified = False - cause_type = type(exc).__name__ - if result.input_verified: - return None - if ( - result.delivery_uncertainty is None - and result.delivery_attempted is not False - ): - result.delivery_uncertainty = ActionDeliveryUncertainty( - operation=( - "choice_select" - if step.choice.kind == "native_select" - else "choice_click" - ), - native=False, - observed_at=datetime.now(timezone.utc).isoformat(), - cause_type=cause_type, - ) - result.safety_halt = True - result.failure_category = "safety_halt" - return ( - f"Chosen option for step '{step.id}' no longer shows on its " - "control after the page settled (choice_unverified); run aborted" - ) - if step.native_selection is not None: - result.input_verified = False - resolution, _region, error = self._resolve_step( - step, after_png, bundle_dir, workflow, allow_grounder=False - ) - if ( - error is None - and resolution is not None - and resolution.rung == "structural" - and isinstance(self.backend, NativeSelectBackend) - ): - observed = self.backend.native_selected_option_at(*resolution.point) - contract = step.native_selection - if ( - isinstance(observed, dict) - and observed.get("value") == contract.value - and observed.get("label") == contract.label - and observed.get("options") - == [option.model_dump(mode="json") for option in contract.options] - ): - result.input_verified = True - return None - result.safety_halt = True - result.failure_category = "governed_refusal" - return ( - f"Native selected option for step '{step.id}' could not be verified " - "on the same committed control; refusing continuation without retry" - ) - qualified_readback = step.selection_region - qualified_target = step.anchor.region if step.anchor is not None else None - if qualified_readback is None or qualified_target is None: - result.input_verified = False - return f"Option selection for step '{step.id}' has no field region" - resolution, live_region, resolve_error = self._resolve_step( - step, - after_png, - bundle_dir, - workflow, - # Final option verification is exact retained-evidence work. A - # model may propose a governed repair after a halt, but it cannot - # supply the target region that certifies the committed value. - allow_grounder=False, - ) - if ( - resolve_error is not None - or resolution is None - or not self._selection_region_compatible(qualified_target, live_region) - ): - result.input_verified = False - result.safety_halt = True - result.failure_category = "governed_refusal" - return ( - f"Selected option field could not be re-resolved with compatible " - f"geometry on the final settled frame for step '{step.id}' " - f"({step.intent}); the run halted" - ) - assert live_region is not None - live_readback = self._mapped_selection_readback_region( - qualified_target, - qualified_readback, - live_region, - after_png, - ) - if live_readback is None: - result.input_verified = False - result.safety_halt = True - result.failure_category = "governed_refusal" - return ( - f"Selected option readback region could not be mapped onto the " - f"final settled frame for step '{step.id}' ({step.intent}); the " - "run halted" - ) - exact = self._text_value_at(resolution.point) - if exact is not None: - verified = identity_mod.comparison_squash( - exact - ) == identity_mod.comparison_squash(text) - else: - needle = identity_mod.comparison_squash(text) - verified = any( - getattr(line, "confidence", 1.0) >= 0.5 - and identity_mod.comparison_squash(line.text) == needle - for line in self.vision.ocr(after_png, region=live_readback) - ) - if not verified: - upscaled = identity_mod.upscale_crop(after_png, live_readback) - if upscaled is not None: - verified = any( - getattr(line, "confidence", 1.0) >= 0.5 - and identity_mod.comparison_squash(line.text) == needle - for line in self.vision.ocr(upscaled, region=None) - ) - result.input_verified = verified - if verified: - return None - result.safety_halt = True - result.failure_category = "governed_refusal" - return ( - f"Selected option could not be verified for step '{step.id}' " - f"({step.intent}) inside its exact live re-resolved field region; the " - "commit may have selected a different value, so the run halted" - ) - - @staticmethod - def _selection_region_compatible( - qualified: Region, - live: Optional[Region], - ) -> bool: - """Check live field shape without treating recorded coordinates as truth. - - Remote drift may translate the field, so x/y intentionally do not - participate. A resolution rung that returns no region, flips the field - orientation, or changes either dimension by more than 25% cannot safely - inherit the recorded option-selection contract. - """ - - if live is None: - return False - _, _, qualified_w, qualified_h = qualified - _, _, live_w, live_h = live - if min(qualified_w, qualified_h, live_w, live_h) <= 0: - return False - if (qualified_w >= qualified_h) != (live_w >= live_h): - return False - return ( - 0.75 <= live_w / qualified_w <= 1.25 - and 0.75 <= live_h / qualified_h <= 1.25 - ) - - @staticmethod - def _selection_target_continuous( - qualified: Region, - focused: Point, - refreshed: Point, - ) -> bool: - """Require both select phases to name the same focused field. - - Reuse the selection contract's 25% size tolerance for point drift. - This permits small OCR/template jitter but refuses a second control. - """ - - _, _, qualified_w, qualified_h = qualified - if qualified_w <= 0 or qualified_h <= 0: - return False - return ( - abs(refreshed[0] - focused[0]) <= qualified_w * 0.25 - and abs(refreshed[1] - focused[1]) <= qualified_h * 0.25 - ) - # -- closed-loop scroll ------------------------------------------------------ @timed_span("resolve") @@ -16804,23 +15996,6 @@ def _next_anchored_step(workflow: Workflow, step_index: int) -> Optional[Step]: # -- postconditions -------------------------------------------------------- - def _structural_state(self) -> dict[str, Any]: - """Structural observations the backend can provide right now. - - Backends MAY expose ``url`` / ``page_title`` / ``page_count`` (see - ``openadapt_flow.backend.StructuralBackend``). Missing observations - are simply absent from the dict. - """ - state: dict[str, Any] = {} - for key in ("url", "page_title", "page_count"): - try: - value = getattr(self.backend, key, None) - except Exception: - value = None - if value is not None: - state[key] = value - return state - def _attended_transition_observation(self) -> Any: """Capture ephemeral browser structure for a signed pause baseline. @@ -16840,92 +16015,6 @@ def _attended_transition_observation(self) -> Any: page_count=page_count if isinstance(page_count, int) else None, ) - def _structural_changed( - self, key: str, start_state: dict[str, Any] - ) -> Optional[bool]: - """Whether structural observation ``key`` differs from step start. - - Returns None when the observation is unavailable on either side — - the caller treats that as an honestly-unverifiable pass (a bundle - recorded on a structural backend may replay on one that is not; - see docs/LIMITS.md). - """ - try: - current = getattr(self.backend, key, None) - except Exception: - current = None - start = start_state.get(key) - if current is None or start is None: - return None - return current != start - - @timed_span("postcondition") - def _check_postconditions( - self, - step: Step, - frame_png: bytes, - bundle_dir: Path, - start_state: dict[str, Any], - result: Optional[StepResult] = None, - *, - workflow: Optional[Workflow] = None, - ) -> tuple[bool, bytes, list[str]]: - """Poll postconditions until each passes or times out. - - Each postcondition is polled (fresh screenshots) up to its own - ``timeout_s``. If any fails, the screen is re-settled once and all - postconditions are re-checked a single time. If a VLM state-verifier - is configured, a render-drift-sensitive postcondition that still failed - gets one last drift-oracle pass (see :meth:`_drift_oracle_rescue`), - but never on a step that can leave a business effect behind (see - :meth:`_postcondition_confirms_a_write`). ``workflow`` lets a qualified - operator risk decision count; without it the classification is the - stricter step-only one. - - Returns: - (ok, last_frame, failed) — the frame the final verdict was based - on, plus human-readable descriptions of the postconditions that - failed the final check (empty when ok). - """ - self._pc_page_scale = _uniform_page_scale(step, result) - self._pc_scaled_match = False - try: - ok, frame_png = self._poll_postconditions( - step, frame_png, bundle_dir, start_state - ) - if ok: - self._note_page_scale(result) - return True, frame_png, [] - # One re-settle retry. - frame_png = self.vision.wait_settled(self.backend) - failed_pcs = [ - pc - for pc in step.expect - if not self._postcondition_passes( - pc, frame_png, bundle_dir, start_state - ) - ] - if not failed_pcs: - self._note_page_scale(result) - finally: - self._pc_page_scale = None - if ( - failed_pcs - and self.state_verifier is not None - and not self._postcondition_confirms_a_write(step, workflow) - ): - failed_pcs = self._drift_oracle_rescue(failed_pcs, frame_png, result) - self._stamp_duplicate_check(result, failed_pcs) - failed = [self._describe_postcondition(pc) for pc in failed_pcs] - return not failed_pcs, frame_png, failed - - def _note_page_scale(self, result: Optional[StepResult]) -> None: - """Record on ``result`` the page scale a passing check needed.""" - - scale = getattr(self, "_pc_page_scale", None) - if result is not None and scale is not None and self._pc_scaled_match: - result.postcondition_page_scale = scale - @staticmethod def _postcondition_confirms_a_write( step: Step, workflow: Optional[Workflow] @@ -16955,63 +16044,6 @@ def _postcondition_confirms_a_write( return True return is_consequential(step, workflow) - def _drift_oracle_rescue( - self, - failed_pcs: list[Any], - frame_png: bytes, - result: Optional[StepResult], - ) -> list[Any]: - """Give each deterministically-failed, render-drift-sensitive - postcondition one confirmation pass through the VLM state-verifier. - - VETO-SAFE by construction: - - * The caller never invokes this on an irreversible or effect-bearing - step (see :meth:`_postcondition_confirms_a_write`). - * Only ``text_present`` and ``region_stable`` are eligible — the kinds - a theme/scale/font re-render can legitimately break. Structural - postconditions (``url_changed`` etc.) and ``text_absent`` are NEVER - rescued: those failures are real, not render drift. - * A postcondition is rescued ONLY on a confident ``"yes"``; ``"no"``, - ``"uncertain"``, and any appliance outage keep it failed (halt). - * Every call and every rescue is recorded on ``result`` for the report - (and counted as a model call), so a rescue is auditable, never silent. - - Returns the postconditions that remain failed after the pass. - """ - assert self.state_verifier is not None # guaranteed by the caller (line ~2618) - survivors: list[Any] = [] - for pc in failed_pcs: - expected = self._expected_state_text(pc) - if expected is None: # not a drift-rescuable kind - survivors.append(pc) - continue - if result is not None: - result.drift_oracle_calls += 1 - try: - confirmed = self.state_verifier.holds(frame_png, expected) - except Exception: - confirmed = False # fail-safe: any error keeps the halt - if confirmed: - if result is not None: - result.postcondition_drift_rescues.append( - self._describe_postcondition(pc) - ) - else: - survivors.append(pc) - return survivors - - @staticmethod - def _expected_state_text(pc: Any) -> Optional[str]: - """A natural-language expected-state for the drift-oracle, or None if - the postcondition kind is not render-drift-rescuable.""" - kind = pc.kind.value if hasattr(pc.kind, "value") else pc.kind - if kind == "text_present" and pc.text and not pc.text_clock: - return f"the text {pc.text!r} is visible on the screen" - if kind == "region_stable": - return "the content recorded in the highlighted region is present" - return None - def _local_edit_held(self, pc: Any, start_state: dict[str, Any]) -> bool: """A compiler-classified local edit stayed local (fail closed). @@ -17481,58 +16513,6 @@ def _postcondition_passes( return distance <= pc.phash_tolerance return False - def _scaled_region_match( - self, frame_png: bytes, template_png: bytes, region: tuple[int, ...] - ) -> bool: - """The recorded content, at the page scale this step's click showed. - - A whole-page zoom (browser zoom, or an app's own scale) grows every - element and moves it away from the top-left corner by the same - factor, so the recorded region falls outside the search window and - its content outside the matcher's scale band. When this step's own - click landed at the recorded point times one uniform factor - (:func:`_uniform_page_scale`), look for the same template at that - factor (within one percent), at the recorded region times that - factor. Thresholds are the unscaled check's: a modal, a missing panel or another layout still - fails. - """ - - scale = getattr(self, "_pc_page_scale", None) - if scale is None: - return False - x, y, w, h = region - scaled = ( - int(round(x * scale)), - int(round(y * scale)), - int(round(w * scale)), - int(round(h * scale)), - ) - search = pad_region(scaled, PC_TEMPLATE_SEARCH_PAD, _frame_viewport(frame_png)) - matchers = [ - (self.vision.find_template, PC_TEMPLATE_THRESHOLD), - ( - getattr(self.vision, "find_structural_template", None), - PC_STRUCTURAL_TEMPLATE_THRESHOLD, - ), - ] - for matcher, threshold in matchers: - if not callable(matcher): - continue - try: - match = matcher( - frame_png, - template_png, - search_region=search, - scales=tuple(round(scale * f, 4) for f in _PAGE_SCALE_BAND), - threshold=threshold, - ) - except TypeError: # a vision stand-in with no scale band - return False - if match is not None: - self._pc_scaled_match = True - return True - return False - def _exact_text_holds(self, text: str, frame_png: bytes) -> bool: """An exact text check (``Postcondition.exact``, ``Predicate.exact``). @@ -17552,28 +16532,6 @@ def _exact_text_holds(self, text: str, frame_png: bytes) -> bool: return True return count == 0 and self._dom_text_visible(text) - def _dom_text_visible(self, text: str) -> bool: - """True only when the backend proves ``text`` is visibly rendered. - - Optional backend seam ``visible_text_present`` (browser DOM). Any - other answer, a missing seam, or an error is "not proven" -> False, - so the caller keeps its visual check. - """ - reader = getattr(self.backend, "visible_text_present", None) - if not callable(reader): - return False - try: - return reader(text) is True - except Exception: - return False - - def _postcondition_template(self, pc: Any, bundle_dir: Path) -> Optional[bytes]: - """Bytes of a REGION_STABLE postcondition's template crop, if any.""" - rel = getattr(pc, "template", None) - if not rel: - return None - return self._asset_bytes(bundle_dir, rel) - def _layout_drift_on(self, workflow: Workflow) -> bool: if self.layout_drift is not None: return self.layout_drift From 4960574c771aad774b83e8fe859e2b8603bae382 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:12:07 -0500 Subject: [PATCH 4/5] test: patch the resolver in its new settling module too --- packages/flow/tests/test_replayer.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/flow/tests/test_replayer.py b/packages/flow/tests/test_replayer.py index 52405aaba7..0e9991c85a 100644 --- a/packages/flow/tests/test_replayer.py +++ b/packages/flow/tests/test_replayer.py @@ -2342,6 +2342,12 @@ def scripted_resolve(*args, **kwargs): "openadapt_flow.runtime.replayer.resolve", scripted_resolve, ) + # Interstitial handling moved to runtime/replay/settling.py and reads its + # own ``resolve``; patch it too so every resolver call stays scripted. + monkeypatch.setattr( + "openadapt_flow.runtime.replay.settling.resolve", + scripted_resolve, + ) backend = FakeBackend() workflow = Workflow(name="wf", steps=[scroll_step(), click_step()]) From 10d091f9eb27fca589634cdd4bb7dfe83687eae7 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 07:14:59 -0500 Subject: [PATCH 5/5] refactor(flow): move the replayer's consequential-delivery checks to a mixin, unchanged --- packages/flow/docs/design/DECOMPOSITION.md | 2 +- .../openadapt_flow/runtime/replay/delivery.py | 1098 +++++++++++++++++ .../flow/openadapt_flow/runtime/replayer.py | 964 +-------------- 3 files changed, 1102 insertions(+), 962 deletions(-) create mode 100644 packages/flow/openadapt_flow/runtime/replay/delivery.py diff --git a/packages/flow/docs/design/DECOMPOSITION.md b/packages/flow/docs/design/DECOMPOSITION.md index 380edf5b17..288881d503 100644 --- a/packages/flow/docs/design/DECOMPOSITION.md +++ b/packages/flow/docs/design/DECOMPOSITION.md @@ -605,7 +605,7 @@ PR #2295 raised `replayer.py`, `ir.py`, `interactive_recorder.py` and `playwrigh | File | Line budget | |---|---:| -| `packages/flow/openadapt_flow/runtime/replayer.py` | 16830 | +| `packages/flow/openadapt_flow/runtime/replayer.py` | 15872 | | `packages/flow/openadapt_flow/__main__.py` | 14331 | | `packages/flow/openadapt_flow/qualification.py` | 5963 | | `packages/flow/openadapt_flow/ir.py` | 6830 | diff --git a/packages/flow/openadapt_flow/runtime/replay/delivery.py b/packages/flow/openadapt_flow/runtime/replay/delivery.py new file mode 100644 index 0000000000..2d4684b49a --- /dev/null +++ b/packages/flow/openadapt_flow/runtime/replay/delivery.py @@ -0,0 +1,1098 @@ +# mypy: disable-error-code="empty-body" +"""Moved replayer code. + +Moved verbatim from ``openadapt_flow.runtime.replayer.Replayer`` by +scripts/extract_mixin.py (docs/design/DECOMPOSITION.md, section 4.1). +``_ConsequentialDeliveryHost`` declares, for mypy only, what this code reads from the +Replayer it is mixed into. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Literal, Optional, cast # noqa: F401 + +from openadapt_flow.backend import ( + ChoiceBackend, + ChoiceRefused, + FocusedElementActuationLeaseBackend, + FreshActuationRequired, + GuardedCoordinateActionBackend, + GuardedDragActionBackend, + GuardedKeyboardActionBackend, + NativeSelectBackend, + PreparedPointerActuationBackend, + RemoteActuationBackend, + RemoteFrameContractBackend, + SelectOptionBackend, + StructuralResolutionRefused, + SubmitBindingBackend, +) +from openadapt_flow.ir import ActionKind, Point, Region, SafetyRefusalEvidence, Step +from openadapt_flow.privacy import scrub_text as _scrub_phi +from openadapt_flow.qualification_faults import sha256_bytes +from openadapt_flow.run_gate import is_consequential +from openadapt_flow.runtime.authorization import runtime_inputs_digest +from openadapt_flow.runtime.replay._shared import ( + _NotActionableError, + _within_hover_jitter, +) +from openadapt_flow.runtime.step_timing import timed_span +from openadapt_flow.vision.ocr import OcrResolutionRefused + +if TYPE_CHECKING: + from pathlib import Path + from typing import Any, Callable, Mapping + + from openadapt_flow.backend import Backend + from openadapt_flow.ir import ( + ExecutionTargetKind, + Resolution, + StepResult, + Workflow, + ) + from openadapt_flow.production_qualification import ProductionQualificationGuard + from openadapt_flow.qualification_environment import ( + QualificationEnvironmentObserver, + ) + from openadapt_flow.qualification_faults import QualificationFaultDriver + from openadapt_flow.runtime.authorization import ( + GovernedRunAuthorization, + RuntimeParamScalar, + ) + from openadapt_flow.runtime.replay._shared import _DeliveryResultT + + +class _ConsequentialDeliveryHost: + _active_delivery_acknowledgers: tuple[Any, ...] + _active_delivery_region: Optional[Region] + _active_delivery_resolution: Optional[Resolution] + + def _active_program_frame_refusal( + self, + workflow: Workflow, + params: Mapping[str, RuntimeParamScalar], + step: Step, + base_params: Mapping[str, RuntimeParamScalar], + ) -> Optional[str]: ... + + _active_runtime_worklists: Optional[dict[str, list[dict[str, str]]]] + + def _active_surface_binding( + self, workflow: Workflow + ) -> tuple[Optional[ExecutionTargetKind], Optional[str]]: ... + def _active_surface_is_external_remote(self, workflow: Workflow) -> bool: ... + + _actuation_epoch: Any + _governed_asset_mutation: Optional[str] + + def _governed_authorization_snapshot_refusal(self) -> Optional[str]: ... + + _governed_base_params: Optional[dict[str, RuntimeParamScalar]] + + def _identity_gate_error( + self, + step: Step, + resolution: Resolution, + frame_png: bytes, + params: Mapping[str, RuntimeParamScalar], + workflow: Workflow, + bundle_dir: Path, + result: StepResult, + *, + evidence_run_dir: Optional[Path] = None, + ) -> Optional[str]: ... + + _interstitials: Any + + def _native_keyboard_lease_required(self, step: Step) -> bool: ... + def _profile_runtime_refusal(self, workflow: Workflow) -> Optional[str]: ... + def _resolve_step( + self, + step: Step, + screen_png: bytes, + bundle_dir: Path, + workflow: Workflow, + *, + allow_grounder: bool = True, + allow_target_ocr: bool = True, + ) -> tuple[Optional[Resolution], Optional[Region], Optional[str]]: ... + + _settle_seed: Optional[tuple[Any, int]] + + def _workflow_snapshot_refusal(self, workflow: Workflow) -> Optional[str]: ... + + backend: Backend + governed_authorization: Optional[GovernedRunAuthorization] + production_qualification_guard: Optional["ProductionQualificationGuard"] + qualification_environment_observer: Optional[QualificationEnvironmentObserver] + qualification_fault_driver: Optional[QualificationFaultDriver] + + +if TYPE_CHECKING: + _Base = _ConsequentialDeliveryHost +else: + _Base = object + + +class ConsequentialDelivery(_Base): + """Moved replayer code.""" + + def _step_is_consequential(self, step: Step, workflow: Workflow) -> bool: + authorization = self.governed_authorization + return is_consequential(step, workflow) or ( + authorization is not None + and authorization.requires_verified_identity(step.id) + ) + + def _step_requires_remote_identity_binding( + self, step: Step, workflow: Workflow + ) -> bool: + """Whether an external opaque-remote step needs an identity lease. + + ``identity_armed`` says that the remote action must remain bound to the + identity that was verified on the exact live frame. It does not change + the business-risk classification of the action on browser or native + surfaces. + """ + + return ( + step.identity_armed is True + and self._active_surface_is_external_remote(workflow) + and isinstance(self.backend, RemoteActuationBackend) + ) + + def _step_requires_remote_guarded_actuation( + self, step: Step, workflow: Workflow + ) -> bool: + """Whether a remote input edge must use the fresh-frame guard path.""" + + return isinstance(self.backend, RemoteActuationBackend) and ( + self._step_is_consequential(step, workflow) + or self._step_requires_remote_identity_binding(step, workflow) + or self.qualification_fault_driver is not None + ) + + def _selection_contract_error( + self, step: Step, workflow: Workflow + ) -> Optional[str]: + """Return a fail-closed error for an unusable composite selection.""" + + if step.action is not ActionKind.SELECT_OPTION: + return None + if step.choice is not None: + if ( + self._typed_remote_receipt_required() + or self.production_qualification_guard is not None + or self.qualification_environment_observer is not None + ): + return ( + f"Step '{step.id}' chooses a dropdown option without a typed " + "delivery receipt; refusing before input" + ) + kind, _mode = self._active_surface_binding(workflow) + if ( + kind not in (None, "web") + or isinstance(self.backend, RemoteActuationBackend) + or not isinstance(self.backend, ChoiceBackend) + ): + return ( + f"Step '{step.id}' chooses a dropdown option, which needs " + "a browser surface whose backend can read the page; " + "refusing input" + ) + return None + if step.native_selection is not None: + try: + Step.model_validate(step.model_dump(mode="json")) + except Exception: + return f"Step '{step.id}' has an invalid native selection contract" + kind, _mode = self._active_surface_binding(workflow) + if ( + kind not in (None, "web") + or isinstance(self.backend, RemoteActuationBackend) + or not isinstance(self.backend, NativeSelectBackend) + ): + return ( + f"Step '{step.id}' requires an exact native HTML selection " + "capability on a browser surface; refusing input" + ) + return None + if step.selection_region is None or step.selection_commit_key is None: + return ( + f"Step '{step.id}' ({step.intent}) has an incomplete exact " + "option-selection contract; refusing input" + ) + if not self._active_surface_is_external_remote(workflow) or not isinstance( + self.backend, RemoteActuationBackend + ): + return ( + f"Step '{step.id}' ({step.intent}) carries a remote " + "option-selection contract outside its qualified external " + "opaque remote surface; refusing input" + ) + if not isinstance(self.backend, SelectOptionBackend): + return ( + f"Step '{step.id}' ({step.intent}) requires atomic option " + "selection, but this backend cannot bind type-ahead and " + "commit under one input lease" + ) + return None + + def _step_has_identity_contract(self, step: Step, workflow: Workflow) -> bool: + """Whether this step carries identity evidence or an explicit mandate.""" + authorization = self.governed_authorization + if authorization is not None and authorization.requires_verified_identity( + step.id + ): + return True + qualification = workflow.qualification + if qualification is not None and step.id in qualification.identity_policies: + return True + # A submit binding ties an unlabeled control to the record the run + # entered; it must be verified on the guarded path like any identity. + if step.submit_binding is not None: + return True + anchor = step.anchor + return anchor is not None and bool( + anchor.context_text + or anchor.structured_identity + or anchor.identity_template + or anchor.identifier_crop + or anchor.form_identity + ) + + def _unbound_submit_refusal( + self, step: Step, workflow: Workflow, result: StepResult + ) -> Optional[str]: + """Refuse a consequential click the compiler could not bind. + + The compiler records ``submit_binding_unbound_reason`` when the + demonstrated click on an unlabeled control could not be tied to the + form it submits (for example, two unlabeled controls follow the + filled fields). Such a click has no record tie at all, so it is + refused before input whatever identity evidence the step carries. + """ + + if ( + step.submit_binding_unbound_reason is None + or step.action not in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK) + or not self._step_is_consequential(step, workflow) + ): + return None + result.safety_halt = True + result.failure_category = "safety_halt" + return ( + f"Step '{step.id}' ({step.intent}) clicks an unlabeled control that " + "could not be tied to the record this run entered: " + f"{step.submit_binding_unbound_reason} — refusing to act; run aborted" + ) + + def _step_needs_consequential_revalidation( + self, step: Step, workflow: Workflow + ) -> bool: + """Whether delivery needs a second, immediately fresh observation. + + Opaque remote surfaces always use the two-phase lease for a + consequential action. Browser/native surfaces use the same pre-delivery + refresh when identity is part of the action contract. + """ + if ( + step.action is ActionKind.SELECT_OPTION + and self._active_surface_is_external_remote(workflow) + and isinstance(self.backend, RemoteActuationBackend) + ): + # A selection is a composite focus -> typeahead -> commit gesture. + # It always needs an exact fresh-frame lease before the focus click + # and another after focus before text+commit, independent of a + # generic risk classifier's opinion of the TYPE step. + return True + if ( + self.qualification_fault_driver is not None + and step.action + in { + ActionKind.CLICK, + ActionKind.DOUBLE_CLICK, + ActionKind.RIGHT_CLICK, + ActionKind.DRAG, + } + and isinstance(self.backend, RemoteActuationBackend) + ): + # Exact fault-prefix proof includes read-only prior actions. Arm a + # fresh remote lease for those actions only during the fault run, + # so ordinary demo replay keeps its reversible fast path. + return True + if self._native_keyboard_lease_required(step): + return True + if self._step_requires_remote_guarded_actuation(step, workflow): + return True + return self._step_is_consequential( + step, workflow + ) and self._step_has_identity_contract(step, workflow) + + def _requires_atomic_identity_pointer(self, step: Step, workflow: Workflow) -> bool: + """Whether a pointer edge may not cross an unleased identity boundary. + + An anchored TYPE has a focusing click before keyboard delivery. That + first input edge needs the same target/record lease as a consequential + CLICK; otherwise a visually identical replacement can receive its + handler before the later keyboard lease notices the change. + """ + + return ( + step.action + in ( + ActionKind.CLICK, + ActionKind.DOUBLE_CLICK, + ActionKind.RIGHT_CLICK, + ActionKind.DRAG, + ActionKind.TYPE, + ActionKind.SELECT_OPTION, + ) + and ( + self._step_is_consequential(step, workflow) + or self._step_requires_remote_identity_binding(step, workflow) + ) + and self._step_has_identity_contract(step, workflow) + ) + + def _requires_atomic_identity_keyboard( + self, step: Step, workflow: Workflow + ) -> bool: + """Whether keyboard delivery must stay bound to the verified focus.""" + + return self._native_keyboard_lease_required(step) or ( + step.action + in ( + ActionKind.KEY, + ActionKind.HOTKEY, + ActionKind.TYPE, + ActionKind.SELECT_OPTION, + ) + and ( + self._step_is_consequential(step, workflow) + or self._step_requires_remote_identity_binding(step, workflow) + ) + and self._step_has_identity_contract(step, workflow) + ) + + def _typed_remote_receipt_required(self) -> bool: + """Whether a remote pointer edge must carry a typed delivery receipt. + + :class:`RemoteActuationBackend` already owns the exact-frame contract: + after ``acquire_actuation_frame`` the backend captures once more under + its own input lock and refuses *before the first input edge* when the + window/session, dimensions, readiness, or exact frame content changed. + :class:`GuardedRemotePointerActionBackend` adds an explicit + expected-frame hash plus a typed, target-bound receipt on top of that + contract; its absence is therefore missing *evidence*, not a missing + safety property. + + A governed (Standard/Regulated) run and an exact qualification-fault + proof both consume that receipt as retained evidence, so they must + refuse before delivery rather than actuate without it. Ordinary replay + keeps the documented lease path — refusing there over-halts every + conforming opaque remote backend, including a pixel-only no-DOM canvas + that can only expose the lease. Such a result stays unlabeled, which + the outcome classifier already maps to ``COMPLETED_UNVERIFIED`` instead + of a production-eligible success. + """ + + return ( + self.governed_authorization is not None + or self.qualification_fault_driver is not None + ) + + def _cancel_guarded_coordinate(self) -> None: + """Clean an unconsumed local coordinate lease, if one was armed.""" + + if isinstance(self.backend, GuardedCoordinateActionBackend): + self.backend.cancel_guarded_coordinate() + + def _cancel_guarded_keyboard(self) -> None: + """Clean an unconsumed local focused-element lease, if one was armed.""" + + if isinstance(self.backend, GuardedKeyboardActionBackend): + self.backend.cancel_guarded_keyboard() + if isinstance(self.backend, FocusedElementActuationLeaseBackend): + self.backend.cancel_focused_element_lease() + + def _local_atomic_capability_error( + self, + step: Step, + resolution: Optional[Resolution], + workflow: Workflow, + *, + arm_keyboard: bool, + ) -> Optional[str]: + """Refuse before input when a local identity lease cannot be enforced. + + Consequential TYPE has two input edges: its optional focusing click and + the subsequent keyboard delivery. The first revalidation must prove + both local seams are available before it focuses anything. The second + revalidation (``arm_keyboard=True``) only needs the keyboard seam. + Structural focusing actions already carry a native target fingerprint; + visual/coordinate focusing actions require the coordinate guard. + """ + + if ( + step.submit_binding is not None + and step.action in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK) + and not isinstance(self.backend, SubmitBindingBackend) + ): + return ( + f"Step '{step.id}' ({step.intent}) clicks an unlabeled control " + "whose only record tie is its recorded submit binding, but this " + "backend cannot read the page structure to verify it — refusing " + "input; run aborted" + ) + + if isinstance(self.backend, RemoteActuationBackend): + return None + + requires_keyboard = self._requires_atomic_identity_keyboard(step, workflow) + if requires_keyboard and not isinstance( + self.backend, GuardedKeyboardActionBackend + ): + return ( + f"Step '{step.id}' ({step.intent}) is a consequential " + "identity-gated keyboard action, but this backend cannot bind " + "the verified focus and execution context to the same input " + "operation — refusing unguarded keyboard delivery; run aborted" + ) + + requires_pointer = self._requires_atomic_identity_pointer(step, workflow) + pointer_edge_pending = step.action in ( + ActionKind.CLICK, + ActionKind.DOUBLE_CLICK, + ActionKind.RIGHT_CLICK, + ActionKind.DRAG, + ) or ( + step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION) + and not arm_keyboard + ) + structural_pointer = bool( + step.action in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK) + and resolution is not None + and resolution.rung == "structural" + and resolution.structural_handle is not None + and resolution.structural_handle.target_fingerprint is not None + and step.anchor is not None + and step.anchor.structural is not None + and callable(getattr(self.backend, "act_structural", None)) + ) + if ( + requires_pointer + and pointer_edge_pending + and resolution is not None + and not structural_pointer + and not isinstance(self.backend, GuardedCoordinateActionBackend) + ): + return ( + f"Step '{step.id}' ({step.intent}) is a consequential " + "identity-gated pointer action, but this backend cannot bind " + "target and context verification to the same actuation operation " + "— refusing raw coordinate delivery; run aborted" + ) + if ( + requires_pointer + and step.action is ActionKind.DRAG + and not isinstance(self.backend, RemoteActuationBackend) + and not isinstance(self.backend, GuardedDragActionBackend) + ): + return ( + f"Step '{step.id}' ({step.intent}) is a consequential drag, " + "but this backend cannot bind both endpoints to the fresh " + "identity-verified frame — refusing input; run aborted" + ) + return None + + def _guarded_keyboard_revalidation( + self, step: Step, workflow: Workflow, *, arm_keyboard: bool + ) -> bool: + return bool( + arm_keyboard + and self._requires_atomic_identity_keyboard(step, workflow) + and not isinstance(self.backend, RemoteActuationBackend) + and isinstance(self.backend, GuardedKeyboardActionBackend) + ) + + def _guarded_type_pointer_revalidation( + self, step: Step, workflow: Workflow + ) -> bool: + return bool( + step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION) + and self._requires_atomic_identity_pointer(step, workflow) + and not isinstance(self.backend, RemoteActuationBackend) + and isinstance(self.backend, GuardedCoordinateActionBackend) + and isinstance(self.backend, GuardedKeyboardActionBackend) + ) + + def _guarded_click_pointer_revalidation( + self, step: Step, workflow: Workflow + ) -> bool: + return bool( + step.action + in ( + ActionKind.CLICK, + ActionKind.DOUBLE_CLICK, + ActionKind.RIGHT_CLICK, + ActionKind.DRAG, + ) + and self._requires_atomic_identity_pointer(step, workflow) + and not isinstance(self.backend, RemoteActuationBackend) + and isinstance(self.backend, GuardedCoordinateActionBackend) + and isinstance(self.backend, GuardedKeyboardActionBackend) + ) + + def _revalidation_frame_capture( + self, step: Step, workflow: Workflow, *, arm_keyboard: bool + ) -> Optional[Callable[[], bytes]]: + """The capture a local revalidation takes its fresh frame with. + + ``None`` means the ordinary screenshot. A remote backend's actuation + frame arms a lease, so it is never taken outside the revalidation. + """ + + if isinstance(self.backend, RemoteActuationBackend): + return None + if ( + self._guarded_keyboard_revalidation( + step, workflow, arm_keyboard=arm_keyboard + ) + or self._guarded_type_pointer_revalidation(step, workflow) + or self._guarded_click_pointer_revalidation(step, workflow) + ): + return cast( + GuardedKeyboardActionBackend, self.backend + ).guarded_keyboard_frame + return None + + @timed_span("identity") + def _revalidate_consequential_actuation( + self, + step: Step, + resolution: Optional[Resolution], + matched_region: Optional[Region], + before_png: bytes, + params: Mapping[str, RuntimeParamScalar], + workflow: Workflow, + bundle_dir: Path, + result: StepResult, + *, + run_dir: Path, + arm_keyboard: bool = False, + ) -> tuple[ + Optional[Resolution], + Optional[Region], + bytes, + Optional[str], + ]: + """Freshly re-resolve and identity-check a consequential GUI step. + + Browser/native backends provide a fresh screenshot immediately before + delivery. ``RemoteActuationBackend`` additionally arms a one-shot + exact-frame lease and refuses if pixels change before the first input + edge. Reversible actions retain the ordinary replay path. + """ + if not self._step_needs_consequential_revalidation(step, workflow): + return resolution, matched_region, before_png, None + + capability_error = self._local_atomic_capability_error( + step, + resolution, + workflow, + arm_keyboard=arm_keyboard, + ) + if capability_error is not None: + result.safety_halt = True + result.failure_category = "safety_halt" + return resolution, matched_region, before_png, capability_error + + # The ordinary resolution pass may have armed a one-shot structural + # handle. Consequential revalidation deliberately replaces that + # observation with a fresh resolve immediately before delivery. Drop + # the stale handle first: on browser backends, binding a second token + # mutates the target node, which correctly invalidates the first + # MutationObserver; if the old observer remains live, its cleanup + # mutation can in turn invalidate the new guard and falsely refuse an + # unchanged target. + cancel_stale_structural = getattr( + self.backend, + "cancel_pending_structural_guards", + None, + ) + if callable(cancel_stale_structural): + cancel_stale_structural() + + guarded_keyboard_backend = self._guarded_keyboard_revalidation( + step, workflow, arm_keyboard=arm_keyboard + ) + focused_element_backend = ( + arm_keyboard + and ( + self._step_is_consequential(step, workflow) + or self._step_requires_remote_identity_binding(step, workflow) + ) + and isinstance(self.backend, RemoteActuationBackend) + and isinstance(self.backend, FocusedElementActuationLeaseBackend) + ) + guarded_type_pointer_backend = self._guarded_type_pointer_revalidation( + step, workflow + ) + guarded_click_pointer_backend = self._guarded_click_pointer_revalidation( + step, workflow + ) + prepared_pointer: Optional[Point] = None + pointer_edge_pending = step.action in ( + ActionKind.CLICK, + ActionKind.DOUBLE_CLICK, + ActionKind.RIGHT_CLICK, + ActionKind.DRAG, + ) or ( + step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION) + and resolution is not None + and not arm_keyboard + ) + # A remote codec can re-render the hovered target a pixel or two from + # where it matched before the hover. Re-prepare once at the fresh point + # and require an exact match there; every point stays reproducible. + pointer_target = resolution.point if resolution is not None else None + for jitter_attempt in range(2): + if ( + pointer_edge_pending + and resolution is not None + and isinstance(self.backend, RemoteActuationBackend) + and isinstance(self.backend, PreparedPointerActuationBackend) + ): + prepared_pointer = pointer_target or resolution.point + try: + self.backend.prepare_pointer_actuation(*prepared_pointer) + except Exception as exc: # noqa: BLE001 - backend boundary must halt + if self.governed_authorization is not None: + result.safety_halt = True + detail = _scrub_phi(str(exc)) or type(exc).__name__ + return ( + resolution, + matched_region, + before_png, + "Pointer preflight HALTED before final target resolution for " + f"step '{step.id}' ({step.intent}): {detail}", + ) + try: + fresh_png = ( + self.backend.acquire_actuation_frame() + if isinstance(self.backend, RemoteActuationBackend) + else ( + cast( + GuardedKeyboardActionBackend, + self.backend, + ).guarded_keyboard_frame() + if ( + guarded_keyboard_backend + or guarded_type_pointer_backend + or guarded_click_pointer_backend + ) + else self.backend.screenshot() + ) + ) + except Exception as exc: # noqa: BLE001 - backend boundary must halt + if self.governed_authorization is not None: + result.safety_halt = True + detail = _scrub_phi(str(exc)) or type(exc).__name__ + return ( + resolution, + matched_region, + before_png, + "Actuation preflight HALTED before input for step " + f"'{step.id}' ({step.intent}): {detail}", + ) + + try: + fresh_resolution, fresh_region, error = self._resolve_step( + step, + fresh_png, + bundle_dir, + workflow, + # Opening an opaque select control can repeat its current value + # in the option popup. That text is valid target evidence before + # the focusing click, but it is no longer unique afterward. The + # second phase therefore requires the retained template or + # independent relational landmarks. + allow_target_ocr=not ( + arm_keyboard and step.action is ActionKind.SELECT_OPTION + ), + ) + except (OcrResolutionRefused, StructuralResolutionRefused) as exc: + result.safety_halt = True + result.safety_refusal_evidence = SafetyRefusalEvidence( + stage="actuation_revalidation", + code="actuation_observation_changed", + detector_input_sha256=sha256_bytes(fresh_png), + ) + return ( + None, + None, + fresh_png, + "Actuation preflight HALTED because the fresh target was " + f"ambiguous for step '{step.id}' ({step.intent}): {exc}", + ) + if isinstance(error, _NotActionableError): + # Something covered the target between resolution and input. + result.safety_halt = True + result.safety_refusal_evidence = SafetyRefusalEvidence( + stage="actuation_revalidation", + code="target_not_actionable", + detector_input_sha256=sha256_bytes(fresh_png), + ) + return None, None, fresh_png, error + if error is not None: + if self.governed_authorization is not None: + result.safety_halt = True + return fresh_resolution, fresh_region, fresh_png, error + if ( + jitter_attempt == 0 + and prepared_pointer is not None + and fresh_resolution is not None + and fresh_resolution.point != prepared_pointer + and _within_hover_jitter( + fresh_resolution.point, prepared_pointer, fresh_region + ) + ): + pointer_target = fresh_resolution.point + continue + break + if ( + prepared_pointer is not None + and fresh_resolution is not None + and fresh_resolution.point != prepared_pointer + ): + result.safety_halt = True + result.failure_category = "safety_halt" + return ( + fresh_resolution, + fresh_region, + fresh_png, + f"Step '{step.id}' ({step.intent}) resolved to " + f"{fresh_resolution.point!r} after remote pointer hover, not " + f"the prepared point {prepared_pointer!r}; refusing a click " + "whose target moved before actuation", + ) + identity_required = ( + self.governed_authorization is not None + and self.governed_authorization.requires_verified_identity(step.id) + ) or ( + workflow.qualification is not None + and step.id in workflow.qualification.identity_policies + ) + if fresh_resolution is None and identity_required: + error = ( + f"Step '{step.id}' ({step.intent}) requires verified identity " + "but no exact target observation was available immediately " + "before actuation — refusing to act; run aborted" + ) + elif ( + fresh_resolution is not None + and step.submit_binding is not None + and ( + fresh_resolution.rung == "structural" + or isinstance(self.backend, RemoteActuationBackend) + or not isinstance(self.backend, GuardedCoordinateActionBackend) + ) + ): + error = ( + f"Step '{step.id}' ({step.intent}) carries a submit binding, which " + "is verified only on the guarded visual path of a DOM backend; " + "this observation would bypass it — refusing to act; run aborted" + ) + result.safety_halt = True + result.failure_category = "safety_halt" + elif fresh_resolution is not None: + guarded_coordinate = ( + self._requires_atomic_identity_pointer(step, workflow) + and not ( + arm_keyboard + and step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION) + ) + # CLICK/DOUBLE_CLICK consume the native DOM/UIA handle when + # structural resolution wins. RIGHT_CLICK has no native + # structural actuator, so bind its resolved point to the + # identity-verified target instead. DRAG is armed only after + # its independently resolved destination is known below. + and step.action is not ActionKind.DRAG + and ( + fresh_resolution.rung != "structural" + or step.action is ActionKind.RIGHT_CLICK + ) + and not isinstance(self.backend, RemoteActuationBackend) + and isinstance(self.backend, GuardedCoordinateActionBackend) + ) + if guarded_coordinate: + coordinate_backend = cast(GuardedCoordinateActionBackend, self.backend) + if step.action is ActionKind.RIGHT_CLICK: + cancel_structural = getattr( + self.backend, + "cancel_pending_structural_guards", + None, + ) + if callable(cancel_structural): + cancel_structural() + editable_arm = getattr( + coordinate_backend, + "arm_guarded_editable_coordinate", + None, + ) + if step.action in ( + ActionKind.TYPE, + ActionKind.SELECT_OPTION, + ) and callable(editable_arm): + editable_arm(*fresh_resolution.point) + elif step.submit_binding is not None: + # No row identity exists for an unlabeled control outside + # any row. Its record tie is the recorded binding to the + # form this run filled; the backend verifies it live and + # leases the exact observation until delivery, or raises. + try: + cast( + SubmitBindingBackend, coordinate_backend + ).arm_guarded_submit_coordinate( + *fresh_resolution.point, binding=step.submit_binding + ) + except StructuralResolutionRefused: + result.submit_binding_verified = False + raise + result.submit_binding_verified = True + else: + coordinate_backend.arm_guarded_coordinate(*fresh_resolution.point) + guarded_keyboard = guarded_keyboard_backend + if guarded_keyboard: + cast(GuardedKeyboardActionBackend, self.backend).arm_guarded_keyboard( + *fresh_resolution.point + ) + if focused_element_backend: + cast( + FocusedElementActuationLeaseBackend, + self.backend, + ).arm_focused_element_lease(*fresh_resolution.point) + try: + error = self._identity_gate_error( + step, + fresh_resolution, + fresh_png, + params, + workflow, + bundle_dir, + result, + evidence_run_dir=run_dir, + ) + if error is not None and result.identity is not None: + code: Literal["identity_conflict", "identity_unverifiable"] = ( + "identity_conflict" + if result.identity.status == "mismatch" + else "identity_unverifiable" + ) + result.safety_refusal_evidence = SafetyRefusalEvidence( + stage="identity_verification", + code=code, + detector_input_sha256=sha256_bytes(fresh_png), + ) + except Exception: + if guarded_coordinate: + self._cancel_guarded_coordinate() + if guarded_keyboard: + self._cancel_guarded_keyboard() + if focused_element_backend: + self._cancel_guarded_keyboard() + raise + if error is not None and guarded_coordinate: + self._cancel_guarded_coordinate() + if error is not None and guarded_keyboard: + self._cancel_guarded_keyboard() + if error is not None and focused_element_backend: + self._cancel_guarded_keyboard() + if error is None and isinstance(self.backend, RemoteFrameContractBackend): + protected: list[Region] = list( + fresh_resolution.resolution_evidence_regions + if fresh_resolution is not None + else () + ) + if fresh_region is not None: + protected.append(fresh_region) + elif fresh_resolution is not None: + x, y = fresh_resolution.point + protected.append((x - 1, y - 1, 3, 3)) + protected.extend( + pc.region for pc in step.expect if pc.region is not None + ) + if workflow.qualification is not None: + policy = workflow.qualification.identity_policies.get(step.id) + if policy is not None: + protected.extend( + s.region for s in policy.signals if s.region is not None + ) + try: + self.backend.arm_remote_frame_contract( + protected_regions=tuple(protected) + ) + except Exception as exc: + return ( + fresh_resolution, + fresh_region, + fresh_png, + ( + "Actuation preflight HALTED because the remote frame mask " + f"overlaps protected evidence: {type(exc).__name__}" + ), + ) + # Retain the exact observation that authorizes the next input edge. + # Composite TYPE/SELECT_OPTION and retry paths can re-resolve inside + # ``_act`` after the outer scope captured its initial geometry. A typed + # zero-input mismatch must describe this live edge, not the stale + # pre-focus target. + self._active_delivery_resolution = fresh_resolution + self._active_delivery_region = fresh_region + return fresh_resolution, fresh_region, fresh_png, error + + def _deliver_backend_call( + self, + result: StepResult, + call: Callable[[], _DeliveryResultT], + ) -> _DeliveryResultT: + """Call one backend delivery boundary with exact attempt reporting. + + A typed pre-mutation choice refusal, fresh-frame mismatch or structural + refusal proves this call emitted no input edge, preserving prior delivery + state. Every other exception is conservative: the boundary may have + been crossed and the step must not enter the pre-delivery retry loop. + """ + + self._actuation_epoch = getattr(self, "_actuation_epoch", 0) + 1 + self._settle_seed = None + attempted_before = result.delivery_attempted + acknowledgers = self._active_delivery_acknowledgers + self._active_delivery_acknowledgers = () + from openadapt_flow.runtime.delivery_freshness import recheck_pending_delivery + + recheck_pending_delivery(self, acknowledgers, result) + try: + delivered = call() + except ChoiceRefused: + result.delivery_attempted = ( + attempted_before if attempted_before is not None else False + ) + raise + except (FreshActuationRequired, StructuralResolutionRefused): + result.delivery_attempted = attempted_before + raise + except Exception: + result.delivery_attempted = True + raise + result.delivery_attempted = True + for guard in acknowledgers: + guard.acknowledge_delivery() + return delivered + + @staticmethod + def _regions_intersect(left: Region, right: Region) -> bool: + left_x, left_y, left_width, left_height = left + right_x, right_y, right_width, right_height = right + return not ( + left_x + left_width <= right_x + or right_x + right_width <= left_x + or left_y + left_height <= right_y + or right_y + right_height <= left_y + ) + + @staticmethod + def _translate_recorded_region( + step: Step, + resolution: Optional[Resolution], + region: Region, + ) -> Region: + """Map recorded anchor-relative geometry onto the live target point.""" + + if step.anchor is None or resolution is None: + return region + recorded_x, recorded_y = step.anchor.click_point + live_x, live_y = resolution.point + x, y, width, height = region + return ( + live_x + x - recorded_x, + live_y + y - recorded_y, + width, + height, + ) + + @classmethod + def _fresh_actuation_identity_regions( + cls, + step: Step, + workflow: Workflow, + resolution: Optional[Resolution], + ) -> list[Region]: + regions: list[Region] = [] + if step.anchor is not None and step.anchor.identifier_region is not None: + regions.append( + cls._translate_recorded_region( + step, resolution, step.anchor.identifier_region + ) + ) + if workflow.qualification is not None: + policy = workflow.qualification.identity_policies.get(step.id) + if policy is not None: + regions.extend( + cls._translate_recorded_region(step, resolution, signal.region) + for signal in policy.signals + if signal.region is not None + ) + return regions + + def _fresh_actuation_authorization_refusal( + self, + workflow: Workflow, + params: Mapping[str, RuntimeParamScalar], + step: Step, + ) -> Optional[str]: + """Recheck exact governed authority and inputs before fresh input.""" + + snapshot_refusal = self._workflow_snapshot_refusal(workflow) + if snapshot_refusal is not None: + return snapshot_refusal + authorization_snapshot_refusal = self._governed_authorization_snapshot_refusal() + if authorization_snapshot_refusal is not None: + return authorization_snapshot_refusal + profile_refusal = self._profile_runtime_refusal(workflow) + if profile_refusal is not None: + return profile_refusal + base_params = self._governed_base_params + if base_params is None: + if self.governed_authorization is not None or workflow.program is not None: + return "runtime lost its admitted parameter scope before input" + return self._governed_asset_mutation + authorization = self.governed_authorization + if authorization is not None: + authorization_refusal = authorization.validate_workflow(workflow) + if authorization_refusal is not None: + return authorization_refusal + actual_inputs = runtime_inputs_digest( + workflow, + base_params, + self._active_runtime_worklists, + interstitials=list(self._interstitials), + ) + if actual_inputs != authorization.runtime_inputs_digest: + return ( + "governed run authorization no longer matches the current " + "runtime inputs" + ) + try: + frame_refusal = self._active_program_frame_refusal( + workflow, params, step, base_params + ) + except Exception as exc: # noqa: BLE001 - mutated interpreter boundary + frame_refusal = ( + "program frame validation failed closed before input " + f"({type(exc).__name__})" + ) + if frame_refusal is not None: + return frame_refusal + return self._governed_asset_mutation diff --git a/packages/flow/openadapt_flow/runtime/replayer.py b/packages/flow/openadapt_flow/runtime/replayer.py index fe42024b2b..95f0443124 100644 --- a/packages/flow/openadapt_flow/runtime/replayer.py +++ b/packages/flow/openadapt_flow/runtime/replayer.py @@ -187,7 +187,7 @@ from openadapt_flow.runtime import identity_census as census_mod from openadapt_flow.runtime import identity_looks as looks_mod from openadapt_flow.runtime import keyboard_delivery as keyboard_delivery_mod -from openadapt_flow.runtime.authorization import ( +from openadapt_flow.runtime.authorization import ( # noqa: F401 GovernedRunAuthorization, RuntimeParamScalar, runtime_inputs_digest, @@ -344,6 +344,7 @@ identity_read_contradicts, ) from openadapt_flow.runtime.replay.confirming import Confirming +from openadapt_flow.runtime.replay.delivery import ConsequentialDelivery from openadapt_flow.runtime.replay.effects import EffectChecks from openadapt_flow.runtime.replay.evidence import AssetsHealingAndEvidence from openadapt_flow.runtime.replay.qualification_faults import ( @@ -358,6 +359,7 @@ class Replayer( SettlingAndInterstitials, EffectChecks, Confirming, + ConsequentialDelivery, ): """Replays a Workflow against a Backend using injected vision. @@ -9703,156 +9705,6 @@ def _retain_visual_resolution_evidence( } ) - def _step_is_consequential(self, step: Step, workflow: Workflow) -> bool: - authorization = self.governed_authorization - return is_consequential(step, workflow) or ( - authorization is not None - and authorization.requires_verified_identity(step.id) - ) - - def _step_requires_remote_identity_binding( - self, step: Step, workflow: Workflow - ) -> bool: - """Whether an external opaque-remote step needs an identity lease. - - ``identity_armed`` says that the remote action must remain bound to the - identity that was verified on the exact live frame. It does not change - the business-risk classification of the action on browser or native - surfaces. - """ - - return ( - step.identity_armed is True - and self._active_surface_is_external_remote(workflow) - and isinstance(self.backend, RemoteActuationBackend) - ) - - def _step_requires_remote_guarded_actuation( - self, step: Step, workflow: Workflow - ) -> bool: - """Whether a remote input edge must use the fresh-frame guard path.""" - - return isinstance(self.backend, RemoteActuationBackend) and ( - self._step_is_consequential(step, workflow) - or self._step_requires_remote_identity_binding(step, workflow) - or self.qualification_fault_driver is not None - ) - - def _selection_contract_error( - self, step: Step, workflow: Workflow - ) -> Optional[str]: - """Return a fail-closed error for an unusable composite selection.""" - - if step.action is not ActionKind.SELECT_OPTION: - return None - if step.choice is not None: - if ( - self._typed_remote_receipt_required() - or self.production_qualification_guard is not None - or self.qualification_environment_observer is not None - ): - return ( - f"Step '{step.id}' chooses a dropdown option without a typed " - "delivery receipt; refusing before input" - ) - kind, _mode = self._active_surface_binding(workflow) - if ( - kind not in (None, "web") - or isinstance(self.backend, RemoteActuationBackend) - or not isinstance(self.backend, ChoiceBackend) - ): - return ( - f"Step '{step.id}' chooses a dropdown option, which needs " - "a browser surface whose backend can read the page; " - "refusing input" - ) - return None - if step.native_selection is not None: - try: - Step.model_validate(step.model_dump(mode="json")) - except Exception: - return f"Step '{step.id}' has an invalid native selection contract" - kind, _mode = self._active_surface_binding(workflow) - if ( - kind not in (None, "web") - or isinstance(self.backend, RemoteActuationBackend) - or not isinstance(self.backend, NativeSelectBackend) - ): - return ( - f"Step '{step.id}' requires an exact native HTML selection " - "capability on a browser surface; refusing input" - ) - return None - if step.selection_region is None or step.selection_commit_key is None: - return ( - f"Step '{step.id}' ({step.intent}) has an incomplete exact " - "option-selection contract; refusing input" - ) - if not self._active_surface_is_external_remote(workflow) or not isinstance( - self.backend, RemoteActuationBackend - ): - return ( - f"Step '{step.id}' ({step.intent}) carries a remote " - "option-selection contract outside its qualified external " - "opaque remote surface; refusing input" - ) - if not isinstance(self.backend, SelectOptionBackend): - return ( - f"Step '{step.id}' ({step.intent}) requires atomic option " - "selection, but this backend cannot bind type-ahead and " - "commit under one input lease" - ) - return None - - def _step_has_identity_contract(self, step: Step, workflow: Workflow) -> bool: - """Whether this step carries identity evidence or an explicit mandate.""" - authorization = self.governed_authorization - if authorization is not None and authorization.requires_verified_identity( - step.id - ): - return True - qualification = workflow.qualification - if qualification is not None and step.id in qualification.identity_policies: - return True - # A submit binding ties an unlabeled control to the record the run - # entered; it must be verified on the guarded path like any identity. - if step.submit_binding is not None: - return True - anchor = step.anchor - return anchor is not None and bool( - anchor.context_text - or anchor.structured_identity - or anchor.identity_template - or anchor.identifier_crop - or anchor.form_identity - ) - - def _unbound_submit_refusal( - self, step: Step, workflow: Workflow, result: StepResult - ) -> Optional[str]: - """Refuse a consequential click the compiler could not bind. - - The compiler records ``submit_binding_unbound_reason`` when the - demonstrated click on an unlabeled control could not be tied to the - form it submits (for example, two unlabeled controls follow the - filled fields). Such a click has no record tie at all, so it is - refused before input whatever identity evidence the step carries. - """ - - if ( - step.submit_binding_unbound_reason is None - or step.action not in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK) - or not self._step_is_consequential(step, workflow) - ): - return None - result.safety_halt = True - result.failure_category = "safety_halt" - return ( - f"Step '{step.id}' ({step.intent}) clicks an unlabeled control that " - "could not be tied to the record this run entered: " - f"{step.submit_binding_unbound_reason} — refusing to act; run aborted" - ) - def _native_keyboard_lease_required(self, step: Step) -> bool: return bool( step.action in (ActionKind.TYPE, ActionKind.KEY, ActionKind.HOTKEY) @@ -9861,671 +9713,6 @@ def _native_keyboard_lease_required(self, step: Step) -> bool: and self.backend.native_keyboard_lease_available() ) - def _step_needs_consequential_revalidation( - self, step: Step, workflow: Workflow - ) -> bool: - """Whether delivery needs a second, immediately fresh observation. - - Opaque remote surfaces always use the two-phase lease for a - consequential action. Browser/native surfaces use the same pre-delivery - refresh when identity is part of the action contract. - """ - if ( - step.action is ActionKind.SELECT_OPTION - and self._active_surface_is_external_remote(workflow) - and isinstance(self.backend, RemoteActuationBackend) - ): - # A selection is a composite focus -> typeahead -> commit gesture. - # It always needs an exact fresh-frame lease before the focus click - # and another after focus before text+commit, independent of a - # generic risk classifier's opinion of the TYPE step. - return True - if ( - self.qualification_fault_driver is not None - and step.action - in { - ActionKind.CLICK, - ActionKind.DOUBLE_CLICK, - ActionKind.RIGHT_CLICK, - ActionKind.DRAG, - } - and isinstance(self.backend, RemoteActuationBackend) - ): - # Exact fault-prefix proof includes read-only prior actions. Arm a - # fresh remote lease for those actions only during the fault run, - # so ordinary demo replay keeps its reversible fast path. - return True - if self._native_keyboard_lease_required(step): - return True - if self._step_requires_remote_guarded_actuation(step, workflow): - return True - return self._step_is_consequential( - step, workflow - ) and self._step_has_identity_contract(step, workflow) - - def _requires_atomic_identity_pointer(self, step: Step, workflow: Workflow) -> bool: - """Whether a pointer edge may not cross an unleased identity boundary. - - An anchored TYPE has a focusing click before keyboard delivery. That - first input edge needs the same target/record lease as a consequential - CLICK; otherwise a visually identical replacement can receive its - handler before the later keyboard lease notices the change. - """ - - return ( - step.action - in ( - ActionKind.CLICK, - ActionKind.DOUBLE_CLICK, - ActionKind.RIGHT_CLICK, - ActionKind.DRAG, - ActionKind.TYPE, - ActionKind.SELECT_OPTION, - ) - and ( - self._step_is_consequential(step, workflow) - or self._step_requires_remote_identity_binding(step, workflow) - ) - and self._step_has_identity_contract(step, workflow) - ) - - def _requires_atomic_identity_keyboard( - self, step: Step, workflow: Workflow - ) -> bool: - """Whether keyboard delivery must stay bound to the verified focus.""" - - return self._native_keyboard_lease_required(step) or ( - step.action - in ( - ActionKind.KEY, - ActionKind.HOTKEY, - ActionKind.TYPE, - ActionKind.SELECT_OPTION, - ) - and ( - self._step_is_consequential(step, workflow) - or self._step_requires_remote_identity_binding(step, workflow) - ) - and self._step_has_identity_contract(step, workflow) - ) - - def _typed_remote_receipt_required(self) -> bool: - """Whether a remote pointer edge must carry a typed delivery receipt. - - :class:`RemoteActuationBackend` already owns the exact-frame contract: - after ``acquire_actuation_frame`` the backend captures once more under - its own input lock and refuses *before the first input edge* when the - window/session, dimensions, readiness, or exact frame content changed. - :class:`GuardedRemotePointerActionBackend` adds an explicit - expected-frame hash plus a typed, target-bound receipt on top of that - contract; its absence is therefore missing *evidence*, not a missing - safety property. - - A governed (Standard/Regulated) run and an exact qualification-fault - proof both consume that receipt as retained evidence, so they must - refuse before delivery rather than actuate without it. Ordinary replay - keeps the documented lease path — refusing there over-halts every - conforming opaque remote backend, including a pixel-only no-DOM canvas - that can only expose the lease. Such a result stays unlabeled, which - the outcome classifier already maps to ``COMPLETED_UNVERIFIED`` instead - of a production-eligible success. - """ - - return ( - self.governed_authorization is not None - or self.qualification_fault_driver is not None - ) - - def _cancel_guarded_coordinate(self) -> None: - """Clean an unconsumed local coordinate lease, if one was armed.""" - - if isinstance(self.backend, GuardedCoordinateActionBackend): - self.backend.cancel_guarded_coordinate() - - def _cancel_guarded_keyboard(self) -> None: - """Clean an unconsumed local focused-element lease, if one was armed.""" - - if isinstance(self.backend, GuardedKeyboardActionBackend): - self.backend.cancel_guarded_keyboard() - if isinstance(self.backend, FocusedElementActuationLeaseBackend): - self.backend.cancel_focused_element_lease() - - def _local_atomic_capability_error( - self, - step: Step, - resolution: Optional[Resolution], - workflow: Workflow, - *, - arm_keyboard: bool, - ) -> Optional[str]: - """Refuse before input when a local identity lease cannot be enforced. - - Consequential TYPE has two input edges: its optional focusing click and - the subsequent keyboard delivery. The first revalidation must prove - both local seams are available before it focuses anything. The second - revalidation (``arm_keyboard=True``) only needs the keyboard seam. - Structural focusing actions already carry a native target fingerprint; - visual/coordinate focusing actions require the coordinate guard. - """ - - if ( - step.submit_binding is not None - and step.action in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK) - and not isinstance(self.backend, SubmitBindingBackend) - ): - return ( - f"Step '{step.id}' ({step.intent}) clicks an unlabeled control " - "whose only record tie is its recorded submit binding, but this " - "backend cannot read the page structure to verify it — refusing " - "input; run aborted" - ) - - if isinstance(self.backend, RemoteActuationBackend): - return None - - requires_keyboard = self._requires_atomic_identity_keyboard(step, workflow) - if requires_keyboard and not isinstance( - self.backend, GuardedKeyboardActionBackend - ): - return ( - f"Step '{step.id}' ({step.intent}) is a consequential " - "identity-gated keyboard action, but this backend cannot bind " - "the verified focus and execution context to the same input " - "operation — refusing unguarded keyboard delivery; run aborted" - ) - - requires_pointer = self._requires_atomic_identity_pointer(step, workflow) - pointer_edge_pending = step.action in ( - ActionKind.CLICK, - ActionKind.DOUBLE_CLICK, - ActionKind.RIGHT_CLICK, - ActionKind.DRAG, - ) or ( - step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION) - and not arm_keyboard - ) - structural_pointer = bool( - step.action in (ActionKind.CLICK, ActionKind.DOUBLE_CLICK) - and resolution is not None - and resolution.rung == "structural" - and resolution.structural_handle is not None - and resolution.structural_handle.target_fingerprint is not None - and step.anchor is not None - and step.anchor.structural is not None - and callable(getattr(self.backend, "act_structural", None)) - ) - if ( - requires_pointer - and pointer_edge_pending - and resolution is not None - and not structural_pointer - and not isinstance(self.backend, GuardedCoordinateActionBackend) - ): - return ( - f"Step '{step.id}' ({step.intent}) is a consequential " - "identity-gated pointer action, but this backend cannot bind " - "target and context verification to the same actuation operation " - "— refusing raw coordinate delivery; run aborted" - ) - if ( - requires_pointer - and step.action is ActionKind.DRAG - and not isinstance(self.backend, RemoteActuationBackend) - and not isinstance(self.backend, GuardedDragActionBackend) - ): - return ( - f"Step '{step.id}' ({step.intent}) is a consequential drag, " - "but this backend cannot bind both endpoints to the fresh " - "identity-verified frame — refusing input; run aborted" - ) - return None - - def _guarded_keyboard_revalidation( - self, step: Step, workflow: Workflow, *, arm_keyboard: bool - ) -> bool: - return bool( - arm_keyboard - and self._requires_atomic_identity_keyboard(step, workflow) - and not isinstance(self.backend, RemoteActuationBackend) - and isinstance(self.backend, GuardedKeyboardActionBackend) - ) - - def _guarded_type_pointer_revalidation( - self, step: Step, workflow: Workflow - ) -> bool: - return bool( - step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION) - and self._requires_atomic_identity_pointer(step, workflow) - and not isinstance(self.backend, RemoteActuationBackend) - and isinstance(self.backend, GuardedCoordinateActionBackend) - and isinstance(self.backend, GuardedKeyboardActionBackend) - ) - - def _guarded_click_pointer_revalidation( - self, step: Step, workflow: Workflow - ) -> bool: - return bool( - step.action - in ( - ActionKind.CLICK, - ActionKind.DOUBLE_CLICK, - ActionKind.RIGHT_CLICK, - ActionKind.DRAG, - ) - and self._requires_atomic_identity_pointer(step, workflow) - and not isinstance(self.backend, RemoteActuationBackend) - and isinstance(self.backend, GuardedCoordinateActionBackend) - and isinstance(self.backend, GuardedKeyboardActionBackend) - ) - - def _revalidation_frame_capture( - self, step: Step, workflow: Workflow, *, arm_keyboard: bool - ) -> Optional[Callable[[], bytes]]: - """The capture a local revalidation takes its fresh frame with. - - ``None`` means the ordinary screenshot. A remote backend's actuation - frame arms a lease, so it is never taken outside the revalidation. - """ - - if isinstance(self.backend, RemoteActuationBackend): - return None - if ( - self._guarded_keyboard_revalidation( - step, workflow, arm_keyboard=arm_keyboard - ) - or self._guarded_type_pointer_revalidation(step, workflow) - or self._guarded_click_pointer_revalidation(step, workflow) - ): - return cast( - GuardedKeyboardActionBackend, self.backend - ).guarded_keyboard_frame - return None - - @timed_span("identity") - def _revalidate_consequential_actuation( - self, - step: Step, - resolution: Optional[Resolution], - matched_region: Optional[Region], - before_png: bytes, - params: Mapping[str, RuntimeParamScalar], - workflow: Workflow, - bundle_dir: Path, - result: StepResult, - *, - run_dir: Path, - arm_keyboard: bool = False, - ) -> tuple[ - Optional[Resolution], - Optional[Region], - bytes, - Optional[str], - ]: - """Freshly re-resolve and identity-check a consequential GUI step. - - Browser/native backends provide a fresh screenshot immediately before - delivery. ``RemoteActuationBackend`` additionally arms a one-shot - exact-frame lease and refuses if pixels change before the first input - edge. Reversible actions retain the ordinary replay path. - """ - if not self._step_needs_consequential_revalidation(step, workflow): - return resolution, matched_region, before_png, None - - capability_error = self._local_atomic_capability_error( - step, - resolution, - workflow, - arm_keyboard=arm_keyboard, - ) - if capability_error is not None: - result.safety_halt = True - result.failure_category = "safety_halt" - return resolution, matched_region, before_png, capability_error - - # The ordinary resolution pass may have armed a one-shot structural - # handle. Consequential revalidation deliberately replaces that - # observation with a fresh resolve immediately before delivery. Drop - # the stale handle first: on browser backends, binding a second token - # mutates the target node, which correctly invalidates the first - # MutationObserver; if the old observer remains live, its cleanup - # mutation can in turn invalidate the new guard and falsely refuse an - # unchanged target. - cancel_stale_structural = getattr( - self.backend, - "cancel_pending_structural_guards", - None, - ) - if callable(cancel_stale_structural): - cancel_stale_structural() - - guarded_keyboard_backend = self._guarded_keyboard_revalidation( - step, workflow, arm_keyboard=arm_keyboard - ) - focused_element_backend = ( - arm_keyboard - and ( - self._step_is_consequential(step, workflow) - or self._step_requires_remote_identity_binding(step, workflow) - ) - and isinstance(self.backend, RemoteActuationBackend) - and isinstance(self.backend, FocusedElementActuationLeaseBackend) - ) - guarded_type_pointer_backend = self._guarded_type_pointer_revalidation( - step, workflow - ) - guarded_click_pointer_backend = self._guarded_click_pointer_revalidation( - step, workflow - ) - prepared_pointer: Optional[Point] = None - pointer_edge_pending = step.action in ( - ActionKind.CLICK, - ActionKind.DOUBLE_CLICK, - ActionKind.RIGHT_CLICK, - ActionKind.DRAG, - ) or ( - step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION) - and resolution is not None - and not arm_keyboard - ) - # A remote codec can re-render the hovered target a pixel or two from - # where it matched before the hover. Re-prepare once at the fresh point - # and require an exact match there; every point stays reproducible. - pointer_target = resolution.point if resolution is not None else None - for jitter_attempt in range(2): - if ( - pointer_edge_pending - and resolution is not None - and isinstance(self.backend, RemoteActuationBackend) - and isinstance(self.backend, PreparedPointerActuationBackend) - ): - prepared_pointer = pointer_target or resolution.point - try: - self.backend.prepare_pointer_actuation(*prepared_pointer) - except Exception as exc: # noqa: BLE001 - backend boundary must halt - if self.governed_authorization is not None: - result.safety_halt = True - detail = _scrub_phi(str(exc)) or type(exc).__name__ - return ( - resolution, - matched_region, - before_png, - "Pointer preflight HALTED before final target resolution for " - f"step '{step.id}' ({step.intent}): {detail}", - ) - try: - fresh_png = ( - self.backend.acquire_actuation_frame() - if isinstance(self.backend, RemoteActuationBackend) - else ( - cast( - GuardedKeyboardActionBackend, - self.backend, - ).guarded_keyboard_frame() - if ( - guarded_keyboard_backend - or guarded_type_pointer_backend - or guarded_click_pointer_backend - ) - else self.backend.screenshot() - ) - ) - except Exception as exc: # noqa: BLE001 - backend boundary must halt - if self.governed_authorization is not None: - result.safety_halt = True - detail = _scrub_phi(str(exc)) or type(exc).__name__ - return ( - resolution, - matched_region, - before_png, - "Actuation preflight HALTED before input for step " - f"'{step.id}' ({step.intent}): {detail}", - ) - - try: - fresh_resolution, fresh_region, error = self._resolve_step( - step, - fresh_png, - bundle_dir, - workflow, - # Opening an opaque select control can repeat its current value - # in the option popup. That text is valid target evidence before - # the focusing click, but it is no longer unique afterward. The - # second phase therefore requires the retained template or - # independent relational landmarks. - allow_target_ocr=not ( - arm_keyboard and step.action is ActionKind.SELECT_OPTION - ), - ) - except (OcrResolutionRefused, StructuralResolutionRefused) as exc: - result.safety_halt = True - result.safety_refusal_evidence = SafetyRefusalEvidence( - stage="actuation_revalidation", - code="actuation_observation_changed", - detector_input_sha256=sha256_bytes(fresh_png), - ) - return ( - None, - None, - fresh_png, - "Actuation preflight HALTED because the fresh target was " - f"ambiguous for step '{step.id}' ({step.intent}): {exc}", - ) - if isinstance(error, _NotActionableError): - # Something covered the target between resolution and input. - result.safety_halt = True - result.safety_refusal_evidence = SafetyRefusalEvidence( - stage="actuation_revalidation", - code="target_not_actionable", - detector_input_sha256=sha256_bytes(fresh_png), - ) - return None, None, fresh_png, error - if error is not None: - if self.governed_authorization is not None: - result.safety_halt = True - return fresh_resolution, fresh_region, fresh_png, error - if ( - jitter_attempt == 0 - and prepared_pointer is not None - and fresh_resolution is not None - and fresh_resolution.point != prepared_pointer - and _within_hover_jitter( - fresh_resolution.point, prepared_pointer, fresh_region - ) - ): - pointer_target = fresh_resolution.point - continue - break - if ( - prepared_pointer is not None - and fresh_resolution is not None - and fresh_resolution.point != prepared_pointer - ): - result.safety_halt = True - result.failure_category = "safety_halt" - return ( - fresh_resolution, - fresh_region, - fresh_png, - f"Step '{step.id}' ({step.intent}) resolved to " - f"{fresh_resolution.point!r} after remote pointer hover, not " - f"the prepared point {prepared_pointer!r}; refusing a click " - "whose target moved before actuation", - ) - identity_required = ( - self.governed_authorization is not None - and self.governed_authorization.requires_verified_identity(step.id) - ) or ( - workflow.qualification is not None - and step.id in workflow.qualification.identity_policies - ) - if fresh_resolution is None and identity_required: - error = ( - f"Step '{step.id}' ({step.intent}) requires verified identity " - "but no exact target observation was available immediately " - "before actuation — refusing to act; run aborted" - ) - elif ( - fresh_resolution is not None - and step.submit_binding is not None - and ( - fresh_resolution.rung == "structural" - or isinstance(self.backend, RemoteActuationBackend) - or not isinstance(self.backend, GuardedCoordinateActionBackend) - ) - ): - error = ( - f"Step '{step.id}' ({step.intent}) carries a submit binding, which " - "is verified only on the guarded visual path of a DOM backend; " - "this observation would bypass it — refusing to act; run aborted" - ) - result.safety_halt = True - result.failure_category = "safety_halt" - elif fresh_resolution is not None: - guarded_coordinate = ( - self._requires_atomic_identity_pointer(step, workflow) - and not ( - arm_keyboard - and step.action in (ActionKind.TYPE, ActionKind.SELECT_OPTION) - ) - # CLICK/DOUBLE_CLICK consume the native DOM/UIA handle when - # structural resolution wins. RIGHT_CLICK has no native - # structural actuator, so bind its resolved point to the - # identity-verified target instead. DRAG is armed only after - # its independently resolved destination is known below. - and step.action is not ActionKind.DRAG - and ( - fresh_resolution.rung != "structural" - or step.action is ActionKind.RIGHT_CLICK - ) - and not isinstance(self.backend, RemoteActuationBackend) - and isinstance(self.backend, GuardedCoordinateActionBackend) - ) - if guarded_coordinate: - coordinate_backend = cast(GuardedCoordinateActionBackend, self.backend) - if step.action is ActionKind.RIGHT_CLICK: - cancel_structural = getattr( - self.backend, - "cancel_pending_structural_guards", - None, - ) - if callable(cancel_structural): - cancel_structural() - editable_arm = getattr( - coordinate_backend, - "arm_guarded_editable_coordinate", - None, - ) - if step.action in ( - ActionKind.TYPE, - ActionKind.SELECT_OPTION, - ) and callable(editable_arm): - editable_arm(*fresh_resolution.point) - elif step.submit_binding is not None: - # No row identity exists for an unlabeled control outside - # any row. Its record tie is the recorded binding to the - # form this run filled; the backend verifies it live and - # leases the exact observation until delivery, or raises. - try: - cast( - SubmitBindingBackend, coordinate_backend - ).arm_guarded_submit_coordinate( - *fresh_resolution.point, binding=step.submit_binding - ) - except StructuralResolutionRefused: - result.submit_binding_verified = False - raise - result.submit_binding_verified = True - else: - coordinate_backend.arm_guarded_coordinate(*fresh_resolution.point) - guarded_keyboard = guarded_keyboard_backend - if guarded_keyboard: - cast(GuardedKeyboardActionBackend, self.backend).arm_guarded_keyboard( - *fresh_resolution.point - ) - if focused_element_backend: - cast( - FocusedElementActuationLeaseBackend, - self.backend, - ).arm_focused_element_lease(*fresh_resolution.point) - try: - error = self._identity_gate_error( - step, - fresh_resolution, - fresh_png, - params, - workflow, - bundle_dir, - result, - evidence_run_dir=run_dir, - ) - if error is not None and result.identity is not None: - code: Literal["identity_conflict", "identity_unverifiable"] = ( - "identity_conflict" - if result.identity.status == "mismatch" - else "identity_unverifiable" - ) - result.safety_refusal_evidence = SafetyRefusalEvidence( - stage="identity_verification", - code=code, - detector_input_sha256=sha256_bytes(fresh_png), - ) - except Exception: - if guarded_coordinate: - self._cancel_guarded_coordinate() - if guarded_keyboard: - self._cancel_guarded_keyboard() - if focused_element_backend: - self._cancel_guarded_keyboard() - raise - if error is not None and guarded_coordinate: - self._cancel_guarded_coordinate() - if error is not None and guarded_keyboard: - self._cancel_guarded_keyboard() - if error is not None and focused_element_backend: - self._cancel_guarded_keyboard() - if error is None and isinstance(self.backend, RemoteFrameContractBackend): - protected: list[Region] = list( - fresh_resolution.resolution_evidence_regions - if fresh_resolution is not None - else () - ) - if fresh_region is not None: - protected.append(fresh_region) - elif fresh_resolution is not None: - x, y = fresh_resolution.point - protected.append((x - 1, y - 1, 3, 3)) - protected.extend( - pc.region for pc in step.expect if pc.region is not None - ) - if workflow.qualification is not None: - policy = workflow.qualification.identity_policies.get(step.id) - if policy is not None: - protected.extend( - s.region for s in policy.signals if s.region is not None - ) - try: - self.backend.arm_remote_frame_contract( - protected_regions=tuple(protected) - ) - except Exception as exc: - return ( - fresh_resolution, - fresh_region, - fresh_png, - ( - "Actuation preflight HALTED because the remote frame mask " - f"overlaps protected evidence: {type(exc).__name__}" - ), - ) - # Retain the exact observation that authorizes the next input edge. - # Composite TYPE/SELECT_OPTION and retry paths can re-resolve inside - # ``_act`` after the outer scope captured its initial geometry. A typed - # zero-input mismatch must describe this live edge, not the stale - # pre-focus target. - self._active_delivery_resolution = fresh_resolution - self._active_delivery_region = fresh_region - return fresh_resolution, fresh_region, fresh_png, error - def _sealed_step(self, step: Step) -> Step: """The program's own step for one the runtime rebound to a run value. @@ -10719,100 +9906,6 @@ def _resolve_drag_end( ) return resolution, region, error - def _deliver_backend_call( - self, - result: StepResult, - call: Callable[[], _DeliveryResultT], - ) -> _DeliveryResultT: - """Call one backend delivery boundary with exact attempt reporting. - - A typed pre-mutation choice refusal, fresh-frame mismatch or structural - refusal proves this call emitted no input edge, preserving prior delivery - state. Every other exception is conservative: the boundary may have - been crossed and the step must not enter the pre-delivery retry loop. - """ - - self._actuation_epoch = getattr(self, "_actuation_epoch", 0) + 1 - self._settle_seed = None - attempted_before = result.delivery_attempted - acknowledgers = self._active_delivery_acknowledgers - self._active_delivery_acknowledgers = () - from openadapt_flow.runtime.delivery_freshness import recheck_pending_delivery - - recheck_pending_delivery(self, acknowledgers, result) - try: - delivered = call() - except ChoiceRefused: - result.delivery_attempted = ( - attempted_before if attempted_before is not None else False - ) - raise - except (FreshActuationRequired, StructuralResolutionRefused): - result.delivery_attempted = attempted_before - raise - except Exception: - result.delivery_attempted = True - raise - result.delivery_attempted = True - for guard in acknowledgers: - guard.acknowledge_delivery() - return delivered - - @staticmethod - def _regions_intersect(left: Region, right: Region) -> bool: - left_x, left_y, left_width, left_height = left - right_x, right_y, right_width, right_height = right - return not ( - left_x + left_width <= right_x - or right_x + right_width <= left_x - or left_y + left_height <= right_y - or right_y + right_height <= left_y - ) - - @staticmethod - def _translate_recorded_region( - step: Step, - resolution: Optional[Resolution], - region: Region, - ) -> Region: - """Map recorded anchor-relative geometry onto the live target point.""" - - if step.anchor is None or resolution is None: - return region - recorded_x, recorded_y = step.anchor.click_point - live_x, live_y = resolution.point - x, y, width, height = region - return ( - live_x + x - recorded_x, - live_y + y - recorded_y, - width, - height, - ) - - @classmethod - def _fresh_actuation_identity_regions( - cls, - step: Step, - workflow: Workflow, - resolution: Optional[Resolution], - ) -> list[Region]: - regions: list[Region] = [] - if step.anchor is not None and step.anchor.identifier_region is not None: - regions.append( - cls._translate_recorded_region( - step, resolution, step.anchor.identifier_region - ) - ) - if workflow.qualification is not None: - policy = workflow.qualification.identity_policies.get(step.id) - if policy is not None: - regions.extend( - cls._translate_recorded_region(step, resolution, signal.region) - for signal in policy.signals - if signal.region is not None - ) - return regions - def _fresh_actuation_event( self, exc: FreshActuationRequired, @@ -10956,57 +10049,6 @@ def _active_program_frame_refusal( ) return None - def _fresh_actuation_authorization_refusal( - self, - workflow: Workflow, - params: Mapping[str, RuntimeParamScalar], - step: Step, - ) -> Optional[str]: - """Recheck exact governed authority and inputs before fresh input.""" - - snapshot_refusal = self._workflow_snapshot_refusal(workflow) - if snapshot_refusal is not None: - return snapshot_refusal - authorization_snapshot_refusal = self._governed_authorization_snapshot_refusal() - if authorization_snapshot_refusal is not None: - return authorization_snapshot_refusal - profile_refusal = self._profile_runtime_refusal(workflow) - if profile_refusal is not None: - return profile_refusal - base_params = self._governed_base_params - if base_params is None: - if self.governed_authorization is not None or workflow.program is not None: - return "runtime lost its admitted parameter scope before input" - return self._governed_asset_mutation - authorization = self.governed_authorization - if authorization is not None: - authorization_refusal = authorization.validate_workflow(workflow) - if authorization_refusal is not None: - return authorization_refusal - actual_inputs = runtime_inputs_digest( - workflow, - base_params, - self._active_runtime_worklists, - interstitials=list(self._interstitials), - ) - if actual_inputs != authorization.runtime_inputs_digest: - return ( - "governed run authorization no longer matches the current " - "runtime inputs" - ) - try: - frame_refusal = self._active_program_frame_refusal( - workflow, params, step, base_params - ) - except Exception as exc: # noqa: BLE001 - mutated interpreter boundary - frame_refusal = ( - "program frame validation failed closed before input " - f"({type(exc).__name__})" - ) - if frame_refusal is not None: - return frame_refusal - return self._governed_asset_mutation - def _install_execution_snapshots(self, workflow: Workflow) -> None: """Copy caller-owned workflow and authorization before any callback."""