diff --git a/src/fathom/constants/localization.py b/src/fathom/constants/localization.py index a1f0ad10..a1dfef18 100644 --- a/src/fathom/constants/localization.py +++ b/src/fathom/constants/localization.py @@ -13,6 +13,19 @@ class LocalizationGridScale(IntEnum): MAXIMUM = 1000 +class GroundingPolicy(StrEnum): + """ + Whether the localization cascade may dispatch planner bounds that nothing corroborated. + + ``PERMISSIVE`` preserves the historical fallback: when every grounding stage abstains, the + planner's own visual estimate is dispatched verbatim. ``STRICT`` refuses that dispatch so an + ungrounded action fails visibly instead of tapping an unverified coordinate. + """ + + STRICT = "STRICT" + PERMISSIVE = "PERMISSIVE" + + class RegionalEvidenceDecision(StrEnum): """ Decision taken by ``RegionalEvidenceMatcher`` for one evaluation call. diff --git a/src/fathom/core/agent/action.py b/src/fathom/core/agent/action.py index 34c623bf..c371eebb 100644 --- a/src/fathom/core/agent/action.py +++ b/src/fathom/core/agent/action.py @@ -3,9 +3,11 @@ from typing import Optional from fathom.constants import ActionType, StepEvent +from fathom.core.exceptions import ToolValidationError from fathom.core.services.normalizer import Normalizer from fathom.schemas.actions import Action, Bounds, CoordinateSource, CoordinateSystem from fathom.schemas.gemini_tools import ExecuteAction +from fathom.schemas.results import ToolErrorFeedback from fathom.schemas.tools import AcceptedCommand @@ -76,7 +78,18 @@ def __bounds(cls, *, data: ExecuteAction) -> Optional[Bounds]: coordinate_system=CoordinateSystem.from_legacy(data.bbox.coordinate_system), ) if bounds.has_normalized_extent_violation(): - return bounds.model_copy(update={"system": CoordinateSystem.LOGICAL}) + raise ToolValidationError( + ToolErrorFeedback( + tool_call_id=None, + tool_name="execute_ui", + error_kind="validation", + message=( + "bbox uses coordinate_system='normalized' but its values exceed the " + "published 0-1000 grid. Re-emit the action with a valid normalized " + "bbox, or use coordinate_system='pixel' for screenshot-space values." + ), + ) + ) return bounds diff --git a/src/fathom/core/perception/localization.py b/src/fathom/core/perception/localization.py index e7c3cf11..7faa293c 100644 --- a/src/fathom/core/perception/localization.py +++ b/src/fathom/core/perception/localization.py @@ -4,6 +4,7 @@ from typing import Any, Dict, Optional from fathom.constants import SWIPE_ACTIONS +from fathom.constants.localization import GroundingPolicy from fathom.core.capability.catalog import CommandCatalog from fathom.core.localization.ensemble import EnsembleLocalizerService from fathom.core.localization.matcher import OcrPhraseMatcher @@ -40,14 +41,16 @@ def __init__( phrase_matcher: Optional[OcrPhraseMatcher] = None, ensemble: Optional[EnsembleLocalizerService] = None, regional_matcher: Optional[RegionalEvidenceMatcher] = None, + grounding: GroundingPolicy = GroundingPolicy.STRICT, ) -> None: """ - Initialize the localizer with optional ensemble layer, phrase + regional matchers, and run - context; omitted matchers default to the Domain implementations. + Initialize the localizer with optional ensemble layer, phrase + regional matchers, run + context, and grounding policy; omitted matchers default to the Domain implementations. """ self.__catalog = catalog self.__ensemble = ensemble + self.__grounding = grounding self.__workflow_id = workflow_id self.__phrase_matcher = phrase_matcher if phrase_matcher is not None else OcrPhraseMatcher() @@ -171,6 +174,9 @@ async def localize( if ensemble_result.status == LocalizationStatus.RESOLVED: return ensemble_result + if self.__grounding is GroundingPolicy.STRICT: + return self.__refused_blind_dispatch(action=action, activity=observation.activity) + blind_result = self.__by_blind_model_bounds(action=action) self.__log_localization_result( action=action, @@ -657,6 +663,28 @@ def __by_regional_evidence( reason=f"Regional evidence abstained: {verdict.decision.value}.", ) + def __refused_blind_dispatch(self, *, action: Action, activity: str) -> LocalizationResult: + """ + Refuse the planner-bounds fallback so an ungrounded action fails instead of tapping blind. + """ + + logger.warning( + "Blind dispatch refused under the strict grounding policy", + extra={ + **self.__log_context(action=action, activity=activity), + "event": "localization.blind_model_bounds.refused", + "grounding.policy": self.__grounding.value, + }, + ) + return LocalizationResult( + confidence=0.0, + status=LocalizationStatus.UNRESOLVED, + reason=( + "Every grounding stage abstained and the strict grounding policy forbids " + "dispatching uncorroborated planner bounds." + ), + ) + def __by_blind_model_bounds(self, *, action: Action) -> LocalizationResult: """ Dispatch planner bounds verbatim when every other stage abstained. diff --git a/src/fathom/schemas/cli.py b/src/fathom/schemas/cli.py index bc082d30..4455eb31 100644 --- a/src/fathom/schemas/cli.py +++ b/src/fathom/schemas/cli.py @@ -113,7 +113,10 @@ class RunCommandInput(LocalCommandInput): description="Optional workspace boundary inside the tenant; " "falls back to FATHOM_CLI_WORKSPACE if absent.", ) - use_xml: bool = Field(default=False) + use_xml: bool = Field( + default=True, + description="Use Android/iOS accessibility hierarchy grounding when available.", + ) signal: Literal["interactive", "socket"] = Field(default="interactive") diff --git a/src/fathom/schemas/configuration.py b/src/fathom/schemas/configuration.py index c26dbe91..9246daec 100644 --- a/src/fathom/schemas/configuration.py +++ b/src/fathom/schemas/configuration.py @@ -14,6 +14,7 @@ DEFAULT_PRIORITY_WINDOW, InferencePriorityMode, ) +from fathom.constants.localization import GroundingPolicy from fathom.constants.platform import ( DeviceConnectionType, DevicePlatform, @@ -535,7 +536,17 @@ class IntentConfiguration(BaseModel): description="Per-kind retry caps; nested so new retry kinds are additive without changing call sites.", ) - use_xml_grounding: bool = Field(default=False, description="Enable structured XML analysis") + use_xml_grounding: bool = Field( + default=True, + description="Enable structured XML/accessibility analysis for intent runs", + ) + grounding_policy: GroundingPolicy = Field( + default=GroundingPolicy.STRICT, + description=( + "Grounding policy for spatial actions. STRICT refuses uncorroborated planner " + "coordinates; PERMISSIVE is an explicit legacy escape hatch." + ), + ) prompt_user_if_stuck: bool = Field( default=True, description="If True and in interactive mode, prompt the user for help when the agent detects a loop.", diff --git a/src/fathom/strategies/graph/context.py b/src/fathom/strategies/graph/context.py index 717609d9..4886e367 100644 --- a/src/fathom/strategies/graph/context.py +++ b/src/fathom/strategies/graph/context.py @@ -379,6 +379,7 @@ def __init__( catalog=self.__catalog, workflow_id=workflow_id, ensemble=self.__ensemble, + grounding=configuration.intent.grounding_policy, ) self.__abort_detector = abort_detector or AbortDetectorFactory.build(llm=llm) diff --git a/src/fathom/strategies/graph/intent/nodes/observe.py b/src/fathom/strategies/graph/intent/nodes/observe.py index 8d6c51db..870f2835 100644 --- a/src/fathom/strategies/graph/intent/nodes/observe.py +++ b/src/fathom/strategies/graph/intent/nodes/observe.py @@ -317,17 +317,14 @@ def __step_success( if action_execution_kind is not ActionExecutionKind.DEVICE: return False - if ( - self.__provider.context.catalog.is_gesture(action_type=action_type) - and action_effect.status is ActionEffectStatus.NO_PROGRESS - ): + if action_effect.status is ActionEffectStatus.NO_PROGRESS: logger.info( - "Gesture execution success overridden by no-progress effect", + "Device execution success overridden by no-progress effect", extra={ "component": "graph.intent.observe", "action.type": action_type.value, "execution.success": execution_success, - "override.reason": "gesture_no_progress", + "override.reason": "device_no_progress", "effect.status": action_effect.status.value, "event": "observe.step.success.overridden", "effect.phash_distance": action_effect.phash_distance, diff --git a/tests/unit/core/agent/test_action_builder.py b/tests/unit/core/agent/test_action_builder.py index 6b5d2703..87213451 100644 --- a/tests/unit/core/agent/test_action_builder.py +++ b/tests/unit/core/agent/test_action_builder.py @@ -4,6 +4,7 @@ from fathom.constants import ActionType, StepEvent from fathom.core.agent.action import ActionBuilder +from fathom.core.exceptions import ToolValidationError from fathom.schemas.actions import CoordinateSystem from fathom.schemas.gemini_tools import ExecuteAction, GeminiBBox from fathom.schemas.tools import AcceptedCommand @@ -14,32 +15,30 @@ class ActionBuilderTest(unittest.TestCase): Covers deterministic action materialization after command acceptance. """ - def test_coerces_malformed_normalized_bbox_to_logical(self) -> None: + def test_rejects_malformed_normalized_bbox(self) -> None: """ - Pixel-scale bbox values mislabeled as normalized must not survive materialization. + Pixel-scale bbox values mislabeled as normalized must be rejected at the action boundary. """ - action = ActionBuilder().build( - command=AcceptedCommand( - action_type=ActionType.SWIPE_UP, - payload=ExecuteAction( - action_type="swipe_up", - target_name="Restaurant list area", - scroll_target="Restaurant list area", - confidence=0.84, - bbox=GeminiBBox( - x=0, - y=858, - width=1206, - height=1396, - coordinate_system="normalized", + with self.assertRaises(ToolValidationError): + ActionBuilder().build( + command=AcceptedCommand( + action_type=ActionType.SWIPE_UP, + payload=ExecuteAction( + action_type="swipe_up", + target_name="Restaurant list area", + scroll_target="Restaurant list area", + confidence=0.84, + bbox=GeminiBBox( + x=0, + y=858, + width=1206, + height=1396, + coordinate_system="normalized", + ), ), - ), + ) ) - ) - - assert action.bounds is not None - self.assertEqual(action.bounds.system, CoordinateSystem.LOGICAL) def test_keeps_valid_normalized_bbox_normalized(self) -> None: """ diff --git a/tests/unit/core/perception/test_localization.py b/tests/unit/core/perception/test_localization.py index d4459896..afeda0bf 100644 --- a/tests/unit/core/perception/test_localization.py +++ b/tests/unit/core/perception/test_localization.py @@ -4,12 +4,13 @@ from typing import Tuple from fathom.constants import ActionType +from fathom.constants.localization import GroundingPolicy from fathom.constants.observation import KeyboardVisibility from fathom.core.capability.catalog import CommandCatalogProvider from fathom.core.perception.localization import TargetLocalizationService from fathom.schemas.actions import Action, Bounds, CoordinateSource, CoordinateSystem from fathom.schemas.budgets import LocalizationBudget -from fathom.schemas.localization import LocalizationStatus +from fathom.schemas.localization import LocalizationResult, LocalizationStatus from fathom.schemas.observation import ( ElementRole, ElementSource, @@ -109,7 +110,9 @@ async def test_resolved_method_logs_selected_element_for_rca(self) -> None: """ service = TargetLocalizationService( - catalog=CommandCatalogProvider().build(), workflow_id="wf-localization" + catalog=CommandCatalogProvider().build(), + workflow_id="wf-localization", + grounding=GroundingPolicy.PERMISSIVE, ) element = self.__element( @@ -173,7 +176,10 @@ async def test_model_bounds_without_perceived_overlap_dispatched_blindly(self) - Model bounds with no perception overlap dispatch and tag the result ``MODEL``. """ - service = TargetLocalizationService(catalog=CommandCatalogProvider().build()) + service = TargetLocalizationService( + catalog=CommandCatalogProvider().build(), + grounding=GroundingPolicy.PERMISSIVE, + ) element = self.__element( identifier="cv_1", bounds=Bounds( @@ -217,7 +223,10 @@ async def test_swipe_without_label_resolves_as_gesture(self) -> None: Free viewport gestures do not require element localization. """ - service = TargetLocalizationService(catalog=CommandCatalogProvider().build()) + service = TargetLocalizationService( + catalog=CommandCatalogProvider().build(), + grounding=GroundingPolicy.PERMISSIVE, + ) action = Action( target="page", @@ -240,7 +249,10 @@ async def test_generic_container_snap_outcome_skips_label_and_uses_model_bbox(se GENERIC_CONTAINER upstream snap outcome bypasses identifier match and lands on bbox. """ - service = TargetLocalizationService(catalog=CommandCatalogProvider().build()) + service = TargetLocalizationService( + catalog=CommandCatalogProvider().build(), + grounding=GroundingPolicy.PERMISSIVE, + ) element = self.__element( identifier="13", bounds=Bounds( @@ -486,5 +498,113 @@ async def test_full_phrase_target_resolves_via_ocr_phrase_fallback(self) -> None self.assertEqual(phrase.__dict__["observation.ocr_token_count"], 5) +class BlindDispatchGroundingPolicyTest(unittest.IsolatedAsyncioTestCase): + """ + When every grounding stage abstains, the strict policy refuses the planner's uncorroborated + bounds instead of tapping an unverified coordinate. + + Regression: an ungrounded gpt-4.1 tap was dispatched blind and landed ~750px off target, and + nothing in the run rejected it. + """ + + @staticmethod + def __service(*, grounding: GroundingPolicy) -> TargetLocalizationService: + """ + Build a localizer with no ensemble, so every grounding stage abstains. + """ + + return TargetLocalizationService( + catalog=CommandCatalogProvider().build(), + grounding=grounding, + ) + + @staticmethod + def __action() -> Action: + """ + A targetless spatial action carrying only planner-estimated bounds. + """ + + return Action( + action_type=ActionType.TAP, + target="Settings app icon", + rationale="Tap the Settings icon to open the app.", + confidence=0.9, + bounds=Bounds( + x=825, + y=933, + width=125, + height=117, + source=CoordinateSource.MODEL, + coordinate_system=CoordinateSystem.NORMALIZED, + ), + ) + + @staticmethod + def __observation() -> ScreenObservation: + """ + An empty observation so no element, OCR, or regional evidence can resolve the target. + """ + + return ScreenObservation( + activity="com.google.android.apps.nexuslauncher", + elements=(), + hashes=ScreenHashBundle( + xml_hash="0" * 16, + visual_hash="0" * 16, + interaction_hash="0" * 16, + ), + keyboard=KeyboardObservation(visibility=KeyboardVisibility.HIDDEN), + ) + + async def __localize(self, *, grounding: GroundingPolicy) -> LocalizationResult: + """ + Drive one localization pass under the supplied grounding policy. + """ + + return await self.__service(grounding=grounding).localize( + image=b"", + action=self.__action(), + budget=LocalizationBudget(local=120, vision=False, attempts=0, threshold=0.72), + observation=self.__observation(), + ) + + async def test_strict_policy_refuses_uncorroborated_planner_bounds(self) -> None: + """ + Strict grounding yields UNRESOLVED with no point, so no blind tap can be dispatched. + """ + + result = await self.__localize(grounding=GroundingPolicy.STRICT) + + self.assertEqual(result.status, LocalizationStatus.UNRESOLVED) + self.assertIsNone(result.point) + self.assertEqual(result.confidence, 0.0) + self.assertIn("strict grounding policy", result.reason) + + async def test_permissive_policy_preserves_the_existing_fallback(self) -> None: + """ + The explicit legacy policy still dispatches planner bounds. + """ + + result = await self.__localize(grounding=GroundingPolicy.PERMISSIVE) + + self.assertEqual(result.status, LocalizationStatus.RESOLVED) + self.assertIsNotNone(result.point) + + async def test_default_policy_is_strict(self) -> None: + """ + Direct localizer construction must fail closed unless permissive mode is explicit. + """ + + service = TargetLocalizationService(catalog=CommandCatalogProvider().build()) + result = await service.localize( + image=b"", + action=self.__action(), + budget=LocalizationBudget(local=120, vision=False, attempts=0, threshold=0.72), + observation=self.__observation(), + ) + + self.assertEqual(result.status, LocalizationStatus.UNRESOLVED) + + if __name__ == "__main__": unittest.main() diff --git a/tests/unit/schemas/test_configuration.py b/tests/unit/schemas/test_configuration.py index 05813313..443c1bf8 100644 --- a/tests/unit/schemas/test_configuration.py +++ b/tests/unit/schemas/test_configuration.py @@ -13,6 +13,7 @@ DEFAULT_PRIORITY_WINDOW, InferencePriorityMode, ) +from fathom.constants.localization import GroundingPolicy from fathom.constants.qualification import ( DEFAULT_QUALIFIER_MAX_RETRIES, DEFAULT_QUALIFIER_MODEL, @@ -29,6 +30,7 @@ ) from fathom.schemas.configuration import ( InferenceConfiguration, + IntentConfiguration, LLMConfiguration, PostgresInteractionConfiguration, PriorityInferenceConfiguration, @@ -37,6 +39,22 @@ ) +class IntentConfigurationGroundingDefaultsTest(unittest.TestCase): + """ + Intent runs default to evidence-backed spatial execution. + """ + + def test_xml_and_strict_grounding_are_enabled_by_default(self) -> None: + """ + A normal run must collect the accessibility manifest and refuse blind coordinates. + """ + + configuration = IntentConfiguration() + + self.assertTrue(configuration.use_xml_grounding) + self.assertIs(configuration.grounding_policy, GroundingPolicy.STRICT) + + class InferenceConfigurationContractTest(unittest.TestCase): """ InferenceConfiguration has no defaults; parent configs own defaults. diff --git a/tests/unit/strategies/graph/intent/nodes/test_observe.py b/tests/unit/strategies/graph/intent/nodes/test_observe.py index 0241b833..56cf3963 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_observe.py +++ b/tests/unit/strategies/graph/intent/nodes/test_observe.py @@ -101,9 +101,9 @@ def test_gesture_no_progress_is_not_recorded_as_success(self) -> None: self.assertFalse(result) - def test_non_gesture_success_keeps_execution_result(self) -> None: + def test_tap_no_progress_is_not_recorded_as_success(self) -> None: """ - Non-gesture device actions still use the adapter execution result. + A tap that leaves the screen unchanged must fail the recorded step too. """ effect = ActionEffect( @@ -119,7 +119,7 @@ def test_non_gesture_success_keeps_execution_result(self) -> None: execution_success=True, ) - self.assertTrue(result) + self.assertFalse(result) def test_control_command_success_ignores_screen_change(self) -> None: """