Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/fathom/constants/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
15 changes: 14 additions & 1 deletion src/fathom/core/agent/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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

Expand Down
32 changes: 30 additions & 2 deletions src/fathom/core/perception/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
5 changes: 4 additions & 1 deletion src/fathom/schemas/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")

Expand Down
13 changes: 12 additions & 1 deletion src/fathom/schemas/configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
DEFAULT_PRIORITY_WINDOW,
InferencePriorityMode,
)
from fathom.constants.localization import GroundingPolicy
from fathom.constants.platform import (
DeviceConnectionType,
DevicePlatform,
Expand Down Expand Up @@ -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.",
Expand Down
1 change: 1 addition & 0 deletions src/fathom/strategies/graph/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 3 additions & 6 deletions src/fathom/strategies/graph/intent/nodes/observe.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
41 changes: 20 additions & 21 deletions tests/unit/core/agent/test_action_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
"""
Expand Down
Loading
Loading