diff --git a/logs.txt b/logs.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/pyrightconfig.json b/pyrightconfig.json new file mode 100644 index 00000000..448e424a --- /dev/null +++ b/pyrightconfig.json @@ -0,0 +1,15 @@ +{ + "pythonVersion": "3.11", + "typeCheckingMode": "standard", + "executionEnvironments": [ + { + "root": "tests", + "reportGeneralTypeIssues": "none", + "reportArgumentType": "none", + "reportIndexIssue": "none", + "reportOptionalMemberAccess": "none", + "reportAttributeAccessIssue": "none" + }, + { "root": "src" } + ] +} diff --git a/src/fathom/adapters/artifact/cloud.py b/src/fathom/adapters/artifact/cloud.py index 78e2d8cd..01968310 100644 --- a/src/fathom/adapters/artifact/cloud.py +++ b/src/fathom/adapters/artifact/cloud.py @@ -17,7 +17,7 @@ class CloudSink(ArtifactSinkPort): Sink that uploads to the configured :class:`StoragePort` and requests local cleanup when the upload succeeds. On any upload failure (network, throttling, auth), the sink reports ``local_cleanup=False`` - so the pipeline leaves the EFS file in place. The next process's ``replay()`` will pick it up. + so the pipeline leaves the local copy in place. The next process's ``replay()`` will pick it up. """ def __init__( @@ -42,10 +42,8 @@ async def persist( """ Upload the artifact and report whether local cleanup is safe. - When the upload fails (exception or empty identifier returned by - the underlying composite storage) we set ``local_cleanup=False`` - so the pipeline preserves the EFS copy for replay and the - operator sees the artifact route on the next run. + On failure (an exception, or an empty identifier that means the storage backend dropped the + write) we set ``local_cleanup=False`` so the pipeline keeps the local copy for a later replay. """ started = time.monotonic() diff --git a/src/fathom/adapters/artifact/efs.py b/src/fathom/adapters/artifact/efs.py index 0ba86519..5fd9d761 100644 --- a/src/fathom/adapters/artifact/efs.py +++ b/src/fathom/adapters/artifact/efs.py @@ -6,10 +6,11 @@ class EfsSink(ArtifactSinkPort): """ - Sink that explicitly retains the EFS-staged copy. + Sink that keeps the locally staged copy as the durable artifact. - The pipeline stages bytes to EFS before invoking any sink. This sink reports success without doing any remote work and asks the pipeline to keep the local file, - distinguishing the "local-only by design" path from :class:`NoopSink` (which represents "drop everything; tests don't care about artifacts"). + The pipeline stages bytes to local disk before any sink runs; this sink does no remote work + and asks the pipeline to keep that file, marking the local-only-by-design path. + It differs from :class:`NoopSink`, whose empty receipt means no durable artifact is kept. """ async def persist( diff --git a/src/fathom/adapters/artifact/noop.py b/src/fathom/adapters/artifact/noop.py index cb4ec6bf..1427db75 100644 --- a/src/fathom/adapters/artifact/noop.py +++ b/src/fathom/adapters/artifact/noop.py @@ -6,11 +6,10 @@ class NoopSink(ArtifactSinkPort): """ - Sink that performs no remote persistence. + Sink that persists nothing and keeps the locally staged copy. - Returns a receipt that asks the pipeline to keep the staged EFS - copy — useful for development, fixture-replay loops, and tests - where cloud upload is not desired. + The receipt carries an empty identifier, so the pipeline records no durable artifact. + Use it in development, fixture-replay loops, and tests where cloud upload is not wanted. """ async def persist( diff --git a/src/fathom/adapters/checkpoint/sqlite.py b/src/fathom/adapters/checkpoint/sqlite.py index e993e1b6..319ea370 100644 --- a/src/fathom/adapters/checkpoint/sqlite.py +++ b/src/fathom/adapters/checkpoint/sqlite.py @@ -1,13 +1,3 @@ -""" -Per-workflow SQLite-backed LangGraph checkpoint store adapter. - -This adapter carries the production fix for the shared-checkpoint hang. The -CheckpointStore port alone changes nothing without this implementation: it -isolates each workflow into its own database file, applies fail-fast SQLite -pragmas, discards files on workflow completion, and sweeps orphans on a -throttled schedule. -""" - from __future__ import annotations import re diff --git a/src/fathom/adapters/device/local/adb.py b/src/fathom/adapters/device/local/adb.py index 279ca61a..737a4ebb 100644 --- a/src/fathom/adapters/device/local/adb.py +++ b/src/fathom/adapters/device/local/adb.py @@ -47,7 +47,8 @@ def __init__( configuration: Optional[ADBConfiguration] = None, ) -> None: """ - Initialize ADB device adapter. + Bind an explicit :class:`ADBConfiguration` when given, or derive one from ``serial`` or defaults, + then precompute the device runtime configuration. """ if configuration: @@ -97,7 +98,7 @@ def __init__( @property def configuration(self) -> DeviceRuntimeConfiguration: """ - Returns the tool configuration. + The resolved device runtime configuration. """ return self.__runtime_configuration @@ -212,7 +213,8 @@ async def swipe( speed: Optional[SwipeSpeed] = None, ) -> ActionResult: """ - Execute swipe gesture. + Execute a swipe gesture. ADB exposes no speed control, so ``speed`` is ignored; + ``duration`` alone drives the gesture. """ if speed is not None: @@ -289,18 +291,10 @@ async def __abandon_unkillable_subprocess( """ Bounded post-kill reap of a still-running subprocess. - ``__run_safe_subprocess`` enforces a wall-clock per-command timeout - via :func:`asyncio.wait_for`. Its ``finally`` block sends SIGKILL, - then awaits the process to reap. When the host has wedged IO - (emulator qcow2 backing exhausted, NFS hang, etc.) the kernel - cannot deliver SIGKILL because the process sits in an - uninterruptible-IO state; the await would block indefinitely and - the entire workflow would stall. - - This helper caps that reap with ``subprocess_cleanup_timeout`` and - abandons the process (logging at WARNING) rather than waiting - forever. The leaked subprocess will be reaped by the OS once the - underlying IO unwedges. + When the host has wedged IO the kernel cannot deliver SIGKILL — the process sits in + uninterruptible-IO state and the reap await would block forever, stalling the workflow. This + helper caps the reap with ``subprocess_cleanup_timeout`` and abandons the process (logging at + WARNING); the OS reaps the leak once the underlying IO unw-edges. """ try: @@ -750,7 +744,6 @@ async def get_snapshot(self) -> Tuple[bytes, Optional[str]]: return image, xml - # Helper methods copied from original tool async def __shell(self, command: str, *, capture_output: bool = False) -> ActionResult: """ Execute ADB shell command with terminal logging. @@ -795,7 +788,7 @@ async def __keyevent(self, keycode: int) -> ActionResult: def __build_arguments(self, parts: List[str]) -> List[str]: """ - Builds full command list. + Assemble the adb argv: the executable, an optional ``-s ``, then the command parts. """ cmd = [self.__configuration.executable_path] @@ -807,7 +800,7 @@ def __build_arguments(self, parts: List[str]) -> List[str]: def __escape(self, text: str) -> str: """ - Escapes text for ADB. + Escape backslashes and double quotes, and encode spaces as ``%s`` for ``input text``. """ return text.replace("\\", "\\\\").replace('"', '\\"').replace(" ", "%s") diff --git a/src/fathom/adapters/device/local/ios.py b/src/fathom/adapters/device/local/ios.py index 94f70bfd..62c08abc 100644 --- a/src/fathom/adapters/device/local/ios.py +++ b/src/fathom/adapters/device/local/ios.py @@ -44,7 +44,7 @@ def __init__( configuration: Optional[IOSConfiguration] = None, ) -> None: """ - Initialize native iOS adapter configuration. + Store configuration, build the automation gateway, and precompute the runtime configuration. """ self.__configuration = configuration or IOSConfiguration() @@ -654,7 +654,7 @@ def __resolve_pixel_scale( async def close(self) -> None: """ - Close adapter resources. + No-op; the adapter holds no persistent resources to close. """ return None diff --git a/src/fathom/adapters/device/remote/adb.py b/src/fathom/adapters/device/remote/adb.py index 6d71d0ce..417c2bc9 100644 --- a/src/fathom/adapters/device/remote/adb.py +++ b/src/fathom/adapters/device/remote/adb.py @@ -43,7 +43,7 @@ class ADBRemoteDeviceAdapter(DevicePort): """ - Adapter for controlling devices hosted on remote providers (e.g., Enricher). + Adapter for controlling devices hosted on a remote device farm. Implements the standard Fathom Remote Device Protocol. """ @@ -51,7 +51,8 @@ class ADBRemoteDeviceAdapter(DevicePort): def __init__(self, configuration: DeviceConfiguration) -> None: """ - Initialize remote device adapter. + Validate the remote coordinates, build the runtime configuration, and open the HTTP/2 client + bound to the session's interaction base URL. """ remote = configuration.remote @@ -110,7 +111,8 @@ def __init__(self, configuration: DeviceConfiguration) -> None: ) async def __execute_request(self, method: str, path: str, **kwargs: Any) -> httpx.Response: """ - Executes an HTTP request with automatic retries for transient errors (5xx, timeouts). Immediately raises on 4xx errors. + Execute an HTTP request, retrying transient failures like 5xx responses and timeouts; + 4xx responses raise immediately. """ if self.__client.is_closed: @@ -476,20 +478,20 @@ def __parse_response(self, response_data: Dict[str, Any]) -> Dict[str, Any]: Standardized JSend payload extractor. """ - # 1. Check for standard JSend 'data' field + # JSend success envelope: unwrap the "data" object. if "data" in response_data and isinstance(response_data["data"], dict): return cast("Dict[str, Any]", response_data["data"]) - # 2. Fallback to legacy 'content' field + # Older providers wrapped the payload in "content" instead. if "content" in response_data and isinstance(response_data["content"], dict): return cast("Dict[str, Any]", response_data["content"]) - # 3. Return the root if neither is present (direct response) + # No wrapper present: treat the body itself as the payload. return response_data async def __send_command(self, request: RemoteInteractionRequest) -> ActionResult: """ - Helper to transmit interaction request. + Send one interaction request and map the provider's status envelope to an :class:`ActionResult`. """ start = time.time() @@ -523,7 +525,7 @@ async def __send_command(self, request: RemoteInteractionRequest) -> ActionResul async def close(self) -> None: """ - Cleanup HTTP client. + Close the underlying HTTP client. """ await self.__client.aclose() diff --git a/src/fathom/adapters/device/remote/ios.py b/src/fathom/adapters/device/remote/ios.py index 18e487d3..df96994d 100644 --- a/src/fathom/adapters/device/remote/ios.py +++ b/src/fathom/adapters/device/remote/ios.py @@ -26,7 +26,7 @@ def __init__( delegate: Optional[ADBRemoteDeviceAdapter] = None, ) -> None: """ - Initialize the remote iOS adapter. + Wrap a remote ADB delegate for transport, constructing one from configuration when none is given. """ self.__delegate = delegate or ADBRemoteDeviceAdapter(configuration=configuration) diff --git a/src/fathom/adapters/interaction/noop.py b/src/fathom/adapters/interaction/noop.py index c1a9aaf4..646bfd20 100644 --- a/src/fathom/adapters/interaction/noop.py +++ b/src/fathom/adapters/interaction/noop.py @@ -83,14 +83,10 @@ class NoopInteraction(InteractionPort): """ Interaction adapter that swallows writes and returns empty reads. - Selected when a host explicitly disables conversation recording. Writes - that carry all fields in their request return synthesized entity echoes - so callers and the recorder treat them as successful. Writes that depend - on prior persisted state (sanitize, finish-task, finish-job) raise - InteractionError because there is no state to read; the recorder's - failure-suppression layer handles this without crashing the run. - - Reads return None or empty collections. + Selected when a host disables conversation recording. Self-contained writes return synthesized entity + echoes so callers treat them as successful; writes depending on prior persisted state (sanitize, + finish-task, finish-job) raise InteractionError, which the recorder's failure-suppression layer + absorbs without crashing the run. Reads return None or empty collections. """ async def initialize(self) -> None: diff --git a/src/fathom/adapters/ios/gateway.py b/src/fathom/adapters/ios/gateway.py index 325fd898..21471809 100644 --- a/src/fathom/adapters/ios/gateway.py +++ b/src/fathom/adapters/ios/gateway.py @@ -19,7 +19,7 @@ class IOSAutomationGateway: def __init__(self, *, configuration: IOSConfiguration) -> None: """ - Initialize iOS automation gateway configuration. + Bind the WebDriverAgent configuration used to build each request. """ self.__configuration = configuration diff --git a/src/fathom/adapters/knowledge/sqlite.py b/src/fathom/adapters/knowledge/sqlite.py index 118664f5..703f13f1 100644 --- a/src/fathom/adapters/knowledge/sqlite.py +++ b/src/fathom/adapters/knowledge/sqlite.py @@ -27,7 +27,8 @@ def __init__( database_path: str = "assets/memory/knowledge.db", ) -> None: """ - Initialize SQLite knowledge adapter. + Resolve the database path (a shared path manager overrides the default), create its parent + directory, and start with an empty in-memory graph. """ if path_manager: @@ -60,7 +61,6 @@ async def __initialize(self) -> None: ) await db.commit() - # Load graph from database await self.__load_graph() self.__initialized = True @@ -104,7 +104,6 @@ async def add_screen(self, *, screen_id: str, metadata: Dict[str, Any]) -> None: await self.__initialize() - # Add to database async with aiosqlite.connect(self.__path) as db: await db.execute( "INSERT OR REPLACE INTO screens (screen_id, metadata) VALUES (?, ?)", @@ -112,7 +111,6 @@ async def add_screen(self, *, screen_id: str, metadata: Dict[str, Any]) -> None: ) await db.commit() - # Add to in-memory graph if screen_id not in self.__screen_to_node: if self.__graph is None: raise RuntimeError("Knowledge graph not initialized") @@ -127,14 +125,12 @@ async def add_transition(self, *, from_screen: str, to_screen: str, action: Acti await self.__initialize() - # Ensure both screens exist if from_screen not in self.__screen_to_node: await self.add_screen(screen_id=from_screen, metadata={}) if to_screen not in self.__screen_to_node: await self.add_screen(screen_id=to_screen, metadata={}) - # Add to database async with aiosqlite.connect(self.__path) as db: await db.execute( "INSERT INTO transitions (from_screen, to_screen, action_json) VALUES (?, ?, ?)", @@ -142,7 +138,6 @@ async def add_transition(self, *, from_screen: str, to_screen: str, action: Acti ) await db.commit() - # Add to in-memory graph to_index = self.__screen_to_node[to_screen] from_index = self.__screen_to_node[from_screen] @@ -165,7 +160,6 @@ async def find_path(self, *, from_screen: str, to_screen: str) -> Optional[List[ from_index = self.__screen_to_node[from_screen] try: - # Use Dijkstra's algorithm to find shortest path if self.__graph is None: raise RuntimeError("Knowledge graph not initialized") @@ -176,7 +170,6 @@ async def find_path(self, *, from_screen: str, to_screen: str) -> Optional[List[ if to_index not in path_indices: return None - # Extract actions from path actions = [] path = path_indices[to_index] diff --git a/src/fathom/adapters/llm/cache.py b/src/fathom/adapters/llm/cache.py index 3b16fcc6..920a1e32 100644 --- a/src/fathom/adapters/llm/cache.py +++ b/src/fathom/adapters/llm/cache.py @@ -15,7 +15,8 @@ class CacheService: """ - Service for managing LLM context caching with key hashing and stats. + Creates and reuses provider-side context caches keyed by a content hash, skipping content below + the provider's minimum token count and bounding how many caches are retained. """ # Gemini context caching has a provider-side minimum of ~1024 input @@ -34,13 +35,7 @@ def __init__( max_entries: int = 2, ) -> None: """ - Initialize CacheService. - - Args: - client: The GenAI client instance. - model_name: The model name to cache for. - ttl_minutes: Time-to-live for cached content in minutes. - max_entries: Maximum number of distinct cache entries retained. + Bind the provider client and model, and set the cache TTL and the retained-entry cap (floored at one). """ self.__client = client @@ -59,15 +54,8 @@ async def get_cached_content( self, system_instruction: str, tools: Optional[List[Dict[str, Any]]] = None ) -> Optional[str]: """ - Creates or retrieves a cached content object. - Invalidates the cache if the content hash changes. - - Args: - system_instruction: The system prompt/instruction to cache. - tools: Optional list of tool declarations to include in cache. - - Returns: - The name of the cached content object, or None if caching failed/skipped. + Return the name of a cached-content object for this system instruction and tool set, creating one + when absent; returns None when the content is too small to cache or the create call fails. """ current_hash = self.__compute_hash(instruction=system_instruction, tools=tools) @@ -76,10 +64,8 @@ async def get_cached_content( if current_hash in self.__undersized_hashes: return None - # Pre-flight size gate: under-threshold prompts cannot be cached - # by the provider, so don't pay an RPC to find that out. The - # exporter system instruction is the canonical small payload that - # used to spend one create() call per export to be rejected. + # Pre-flight size gate: under-threshold prompts cannot be cached by the provider, so + # don't spend an RPC to discover that. approximate_size = len(system_instruction) if tools: approximate_size += len(json.dumps(tools, sort_keys=True)) @@ -154,7 +140,7 @@ async def get_cached_content( async def delete_cache(self) -> None: """ - Deletes the current cache if it exists. + Evict all tracked cache entries. """ await self.__evict_all() @@ -197,14 +183,8 @@ async def __evict_hash(self, *, content_hash: str) -> None: @staticmethod def __compute_hash(instruction: str, tools: Optional[List[Dict[str, Any]]] = None) -> str: """ - Computes a deterministic hash of the cache key content. - - Args: - instruction: System instruction text. - tools: Tool declarations list. - - Returns: - Hex digest of the hash. + Return a deterministic SHA-256 digest over the instruction and sorted tool declarations, + truncated to the visual-hash length. """ payload = instruction diff --git a/src/fathom/adapters/llm/gemini.py b/src/fathom/adapters/llm/gemini.py index f574c7e7..b5ae7cb3 100644 --- a/src/fathom/adapters/llm/gemini.py +++ b/src/fathom/adapters/llm/gemini.py @@ -55,7 +55,7 @@ class GeminiLLM(LLMPort): """ - Gemini adapter for LLM interactions. + Gemini implementation of :class:`LLMPort`. """ def __init__( @@ -66,7 +66,7 @@ def __init__( configuration: Optional[LLMConfiguration] = None, ) -> None: """ - Initialize Gemini LLM adapter. + Resolve configuration, set up the priority policy and parser, then build the SDK client and cache. """ if configuration: @@ -113,7 +113,7 @@ def client(self) -> Any: def __initialize(self) -> None: """ - Initialize client. + Resolve service-account credentials when configured, then build the SDK client and context cache. """ project = self.__configuration.project_id @@ -196,7 +196,7 @@ def __get_generation_configuration( structured_output: Optional[StructuredOutput] = None, ) -> types.GenerateContentConfig: """ - Constructs the GenerateContentConfig using current configuration. + Assemble the SDK ``GenerateContentConfig`` from the current inference settings. """ media_resolution_map = { @@ -338,7 +338,8 @@ async def generate( conversation_history: Optional[Sequence[ConversationTurn]] = None, ) -> GenerateResult: """ - Main handler for LLM interaction. + Run one generation: reuse or skip the context cache, build SDK contents from the prompt and + history, then call Gemini under a per-attempt timeout with adaptive-priority retry. """ if not self.__client: @@ -658,7 +659,7 @@ async def prewarm( async def cleanup(self) -> None: """ - Cleanup resources. + Delete the provider cache, then close the SDK client. """ try: diff --git a/src/fathom/adapters/localization/document/layout.py b/src/fathom/adapters/localization/document/layout.py index 142c8dec..9c0d2638 100644 --- a/src/fathom/adapters/localization/document/layout.py +++ b/src/fathom/adapters/localization/document/layout.py @@ -26,7 +26,7 @@ def __init__( matcher: Optional[OcrPhraseMatcher] = None, ) -> None: """ - Initialize the layout localizer with optional run context and matcher. + Bind optional run context and an OCR phrase matcher, defaulting to a fresh matcher. """ self.__workflow_id = workflow_id diff --git a/src/fathom/adapters/ocr/document/adapter.py b/src/fathom/adapters/ocr/document/adapter.py index 0a22dd99..12cb7fbd 100644 --- a/src/fathom/adapters/ocr/document/adapter.py +++ b/src/fathom/adapters/ocr/document/adapter.py @@ -158,35 +158,16 @@ def __pixel_dimensions(*, capture: ScreenCapture) -> tuple[int, int]: """ Recover the true pixel resolution of ``capture.image``. - Document AI is handed the raw PNG bytes and reports ``normalized_vertices`` - in 0..1 of *that image*. :class:`DocumentAiMapper` multiplies those by the - width/height it is given and stamps the result ``DEVICE_PIXEL``, so the - dimensions passed in must be the image's own pixel size. - - ``ScreenCapture.width``/``height`` cannot be relied on for that: they hold - the dispatch-space dimensions, which are device pixels for some adapters - (the local iOS one reads them straight off the PNG header) and logical - points for others — ``ScreenObservation.__capture_dimension_system`` - resolves which at runtime. Where they are logical, a 2x retina device makes - them exactly half the image, so passing that pair produced bounds already - in logical space but labelled ``DEVICE_PIXEL``. ``to_logical_dispatch`` - then divided them by the scale a second time and every OCR-resolved tap - landed at 1/scale of its correct distance from the top-left origin. - - Decoding the image sidesteps the ambiguity entirely: it yields the true - pixel size whichever convention the adapter used, and is a no-op for the - adapters that already report pixels. - - Live incident 2026-08-06 (MatrixCare, iPad Air 4, logical 1180x820 / - pixel 2360x1640): OCR located "Add Visit" at (936, 631) — dead on the - button — and the tap was dispatched to (485, 318), ~590px away in the - middle of the calendar. Reproduced identically in runs HXPBk, HawUV and - QgzIM. Near the origin the error is a few pixels and goes unnoticed; - at the bottom-right of the screen it misses entirely. - - Mirrors ``ActionExecutor.__resolve_pixel_dimensions``. Falls back to the - logical pair when the bytes cannot be decoded — that is the pre-existing - behaviour and is correct for 1x devices, where the two are equal anyway. + Document AI reports ``normalized_vertices`` in 0..1 of the raw PNG; :class:`DocumentAiMapper` + multiplies by the given width/height and stamps ``DEVICE_PIXEL``, so the dimensions must be the + image's own pixel size. ``ScreenCapture.width``/``height`` hold dispatch-space dimensions — + device pixels for some adapters, logical points for others — so on a retina device a logical + pair is doubly divided by the scale in ``to_logical_dispatch`` and every OCR tap lands at + 1/scale of its true offset from the origin. Decoding the image yields the true pixel size + whichever convention the adapter used, and is a no-op for adapters that already report pixels. + + Mirrors ``ActionExecutor.__resolve_pixel_dimensions``. Falls back to the logical pair when the + bytes cannot be decoded — correct for 1x devices, where the two are equal anyway. """ if not capture.image: diff --git a/src/fathom/adapters/perception/android.py b/src/fathom/adapters/perception/android.py index 9da7da3a..7879ba2d 100644 --- a/src/fathom/adapters/perception/android.py +++ b/src/fathom/adapters/perception/android.py @@ -21,7 +21,7 @@ class AndroidPerceptionAdapter(PerceptionPort): def __init__(self, *, device: DevicePort, include_hierarchy: bool) -> None: """ - Initialize Android perception adapter. + Bind the device adapter, whether to include the hierarchy dump, and a fresh hierarchy breaker. """ self.__device = device diff --git a/src/fathom/adapters/perception/ios.py b/src/fathom/adapters/perception/ios.py index f641d6af..addf006e 100644 --- a/src/fathom/adapters/perception/ios.py +++ b/src/fathom/adapters/perception/ios.py @@ -20,7 +20,7 @@ class IOSNativePerceptionAdapter(PerceptionPort): def __init__(self, *, device: DevicePort) -> None: """ - Initialize native iOS perception adapter. + Bind the iOS device adapter used for screenshot capture. """ self.__device = device @@ -83,7 +83,7 @@ class IOSEnhancedPerceptionAdapter(PerceptionPort): def __init__(self, *, device: DevicePort) -> None: """ - Initialize enhanced iOS perception adapter. + Bind the iOS device adapter and a fresh hierarchy breaker. """ self.__device = device diff --git a/src/fathom/adapters/perception/remote.py b/src/fathom/adapters/perception/remote.py index 47017460..1d6ea917 100644 --- a/src/fathom/adapters/perception/remote.py +++ b/src/fathom/adapters/perception/remote.py @@ -23,7 +23,7 @@ class RemotePerceptionAdapter(PerceptionPort): def __init__(self, *, device: DevicePort, include_hierarchy: bool) -> None: """ - Initialize the remote perception adapter. + Bind the remote device adapter, whether to include the hierarchy dump, and a fresh hierarchy breaker. """ self.__device = device diff --git a/src/fathom/adapters/signal/interactive.py b/src/fathom/adapters/signal/interactive.py index 47566c9d..31cf8c1b 100644 --- a/src/fathom/adapters/signal/interactive.py +++ b/src/fathom/adapters/signal/interactive.py @@ -48,11 +48,10 @@ async def get(self) -> str: class InteractiveSignal(SignalPort): """ - High-performance, event-driven HITL signal adapter. + Event-driven HITL signal adapter. - Architecture: - - Zero-Thread Multiplexing: Uses `loop.add_reader` on `sys.stdin` for O(1) kernel-level notifications. - - Singleton Input Bus: Broadcasts input to all active listeners (preventing theft). + Uses ``loop.add_reader`` on ``sys.stdin`` for thread-free kernel-level notifications, and a singleton + input bus that broadcasts each line to every active listener so no listener steals another's input. """ # Global input bus for all concurrent instances @@ -61,7 +60,7 @@ class InteractiveSignal(SignalPort): def __init__(self) -> None: """ - Initialize high-scale interactive signal adapter. + Reset pause and context state, register the shared stdin listener, and print the HITL instructions. """ self.__pause_requested = False @@ -243,7 +242,7 @@ async def ask(self, *, prompt: str) -> str: def __render_instructions(self) -> None: """ - Log Instructions + Print the HITL controls panel to the console. """ console.print("\n[bold cyan]HITL Mode Active[/bold cyan]") @@ -258,7 +257,7 @@ def __render_instructions(self) -> None: def __render_pause_menu(self) -> None: """ - Render Menu (For Pause) + Render the paused-execution banner and any pending injected context. """ console.print( @@ -269,7 +268,7 @@ def __render_pause_menu(self) -> None: def __render_options(self) -> None: """ - Renders HITL Options + Render the resume/inject/cancel choice prompt. """ console.print("[1] Resume | [2] Inject Context | [3] Cancel\n[bold]Choice:[/bold] ", end="") @@ -277,7 +276,7 @@ def __render_options(self) -> None: def __handle_resume(self) -> None: """ - Handler For Resume Event + Clear the pause flag and print the resume banner. """ logger.info(f"InteractiveSignal: Clearing pause flag (was: {self.__pause_requested})") @@ -286,7 +285,7 @@ def __handle_resume(self) -> None: async def __handle_injection(self) -> None: """ - Handler For Injection Event + Read one injected instruction from the input bus and queue it. """ console.print("\n[bold]Enter instruction:[/bold]") @@ -299,7 +298,7 @@ async def __handle_injection(self) -> None: def __del__(self) -> None: """ - Cleanup singleton listener if this was the last instance (Optional). + No-op finalizer; listener teardown is handled elsewhere. """ return None diff --git a/src/fathom/adapters/signal/socket.py b/src/fathom/adapters/signal/socket.py index 332313f9..1a870fa2 100644 --- a/src/fathom/adapters/signal/socket.py +++ b/src/fathom/adapters/signal/socket.py @@ -26,10 +26,7 @@ class SocketSignal(SignalPort): def __init__(self, socket_path: str = "/tmp/fathom.sock") -> None: # nosec B108 """ - Initialize socket listener. - - Args: - socket_path: Path for UDS (Unix) or host:port for TCP. + Bind the control endpoint (a Unix socket path or ``host:port``) and start the async socket server. """ self.__socket_path = socket_path @@ -89,7 +86,7 @@ def __setup_server(self) -> None: async def __start_serving(self) -> None: """ - Internal server starter. + Bind the Unix socket server and serve until it is closed. """ self.__server = await asyncio.start_unix_server( @@ -128,7 +125,7 @@ async def __process_payload( self, payload: Dict[str, Any], writer: asyncio.StreamWriter ) -> None: """ - Dispatches commands with zero-latency notifications. + Dispatch one control command (pause/resume/inject/answer/cancel) and reply with a status line. """ cmd = payload.get("cmd", "").lower() @@ -266,8 +263,6 @@ async def ask(self, *, prompt: str) -> str: while True: cmd_data = await self.__command_queue.get() if cmd_data.get("cmd") == "answer": - # Ensure we return a string, not Any/None return str(cmd_data.get("data", "")) - # Should be unreachable, but satisfies mypy return "" diff --git a/src/fathom/adapters/signal/temporal.py b/src/fathom/adapters/signal/temporal.py index cddc47c4..d7b095f4 100644 --- a/src/fathom/adapters/signal/temporal.py +++ b/src/fathom/adapters/signal/temporal.py @@ -21,7 +21,7 @@ class TemporalSignalAdapter(SignalPort): Signal adapter backed by in-process shared state. Workflow signal handlers mirror state into a shared WorkflowSignalState - via SignalStateRegistry. This adapter reads from that mirror, eliminating billable Temporal queries entirely. + via SignalStateRegistry. This adapter reads from that mirror instead of issuing workflow queries. """ def __init__(self, *, workflow_id: str, deadline: float = SignalDeadline.ASK) -> None: @@ -54,10 +54,7 @@ def supports_interruption(self) -> bool: async def check_signal(self) -> Optional[str]: """ - Check for active control signal. - - Returns: - SignalType value if present, else None. + Return the active control signal (cancelled takes precedence over paused), or None when running. """ self.__state.metrics.signal_checks += 1 diff --git a/src/fathom/adapters/storage/cloud.py b/src/fathom/adapters/storage/cloud.py index 3eb3321b..526f1444 100644 --- a/src/fathom/adapters/storage/cloud.py +++ b/src/fathom/adapters/storage/cloud.py @@ -17,7 +17,7 @@ class CloudStorage(StoragePort): def __init__(self, storage: IImageStorage) -> None: """ - Initialize cloud storage adapter with injected storage infrastructure. + Bind the adapter to the injected image-storage backend. """ self.__storage = storage diff --git a/src/fathom/adapters/storage/composite.py b/src/fathom/adapters/storage/composite.py index 278eac5f..f0360d16 100644 --- a/src/fathom/adapters/storage/composite.py +++ b/src/fathom/adapters/storage/composite.py @@ -17,7 +17,7 @@ class CompositeStorage(StoragePort): def __init__(self, storages: List[StoragePort]) -> None: """ - Initialize composite storage adapter. + Bind the ordered list of storage ports to fan writes out to. """ self.__storages = storages diff --git a/src/fathom/adapters/storage/local.py b/src/fathom/adapters/storage/local.py index 33f8da7f..3d39c00c 100644 --- a/src/fathom/adapters/storage/local.py +++ b/src/fathom/adapters/storage/local.py @@ -14,7 +14,7 @@ class LocalStorage(StoragePort): def __init__(self, path_manager: SharedPathManager) -> None: """ - Initialize local storage adapter. + Build the local image-storage backend from the shared path manager. """ self.__storage = LocalImageStorage(path_manager=path_manager) diff --git a/src/fathom/adapters/summarization/llm.py b/src/fathom/adapters/summarization/llm.py index 4f530326..e1cf8461 100644 --- a/src/fathom/adapters/summarization/llm.py +++ b/src/fathom/adapters/summarization/llm.py @@ -12,31 +12,23 @@ class LLMSummarizer(SummarizationPort): """ - Uses an LLM with structured tool calling to semantically compress execution traces. + Compresses an execution trace into a structured milestone via LLM tool calling. - Produces structured milestones that capture: - - What was accomplished (outcomes) - - How it was done (key actions) - - What challenges were faced (failures/retries) - - Uses tool calling for speed and structured output. + The milestone captures what was accomplished (outcomes), the key actions that got there, + and any challenges (failures or retries). """ def __init__(self, llm: LLMPort) -> None: """ - Initialize with an LLM provider. + Bind the LLM port used for summarization. """ self.__llm = llm async def summarize_trace(self, trace: List[Dict[str, Any]]) -> str: """ - Generates a structured semantic summary using tool calling. - - Returns a formatted milestone string that includes: - - Main accomplishment - - Key actions taken - - Challenges faced (if any) + Build a milestone summary of the trace via tool calling: the accomplishment, the key actions, + and any challenges, falling back to plain content or a counts line when no tool call returns. """ if not trace: diff --git a/src/fathom/adapters/telemetry/console.py b/src/fathom/adapters/telemetry/console.py index 1afdee48..b1820d1d 100644 --- a/src/fathom/adapters/telemetry/console.py +++ b/src/fathom/adapters/telemetry/console.py @@ -21,7 +21,7 @@ def __init__( console: Optional[Console] = None, ) -> None: """ - Initialize console telemetry with a wrapped telemetry adapter. + Wrap an inner telemetry adapter and bind a Rich console for CLI rendering. """ self.__inner = inner diff --git a/src/fathom/adapters/telemetry/redis.py b/src/fathom/adapters/telemetry/redis.py index ea43ce45..baee2e89 100644 --- a/src/fathom/adapters/telemetry/redis.py +++ b/src/fathom/adapters/telemetry/redis.py @@ -77,7 +77,7 @@ async def __publish( context: Dict[str, Any], ) -> None: """ - Publish log event to Redis matching the farm-wrap gateway schema. + Publish log event to Redis matching the gateway schema. """ try: @@ -156,7 +156,7 @@ def __error_context( async def debug(self, message: str, **context: Any) -> None: """ - Publishes DEBUG Logs + Log at debug level and publish to the telemetry channel. """ self.__logger.debug(message, extra=context) @@ -164,7 +164,7 @@ async def debug(self, message: str, **context: Any) -> None: async def info(self, message: str, **context: Any) -> None: """ - Publishes INFO Logs + Log at info level and publish to the telemetry channel. """ self.__logger.info(message, extra=context) @@ -172,7 +172,7 @@ async def info(self, message: str, **context: Any) -> None: async def warning(self, message: str, **context: Any) -> None: """ - Publishes WARNING Logs + Log at warning level and publish to the telemetry channel. """ self.__logger.warning(message, extra=context) @@ -180,7 +180,7 @@ async def warning(self, message: str, **context: Any) -> None: async def error(self, message: str, **context: Any) -> None: """ - Publishes ERROR Logs + Log at error level and publish to the telemetry channel. """ self.__logger.error(message, extra=context) diff --git a/src/fathom/adapters/telemetry/structlog.py b/src/fathom/adapters/telemetry/structlog.py index 4f0441e2..d89727ae 100644 --- a/src/fathom/adapters/telemetry/structlog.py +++ b/src/fathom/adapters/telemetry/structlog.py @@ -14,7 +14,7 @@ class StructlogAdapter(TelemetryPort): def __init__(self, *, logger_name: str = "fathom") -> None: """ - Initialize structlog adapter. + Bind a standard-library logger under the given name. """ self.__logger = getLogger(name=logger_name) diff --git a/src/fathom/constants/collaboration.py b/src/fathom/constants/collaboration.py index e556025d..3fca90ad 100644 --- a/src/fathom/constants/collaboration.py +++ b/src/fathom/constants/collaboration.py @@ -8,7 +8,8 @@ DEFAULT_OPERATOR: Final[str] = "operator" # Canonical agent actor identifiers used by the recorder and CLI principal resolver. -# Other runtimes (host-driven REST/Temporal hosts) may supply their own ids; these defaults exist so the CLI never silently invents one. +# Other runtimes (host-driven REST/Temporal hosts) may supply their own ids; these defaults +# exist so the CLI never silently invents one. DEFAULT_AGENT_ID: Final[str] = "agent:fathom" DEFAULT_PLANNER_AGENT_ID: Final[str] = "agent:planner" DEFAULT_EXECUTOR_AGENT_ID: Final[str] = "agent:executor" diff --git a/src/fathom/constants/conversation.py b/src/fathom/constants/conversation.py index dcd70213..5a2815ea 100644 --- a/src/fathom/constants/conversation.py +++ b/src/fathom/constants/conversation.py @@ -12,7 +12,7 @@ REQUEST_EXPIRY_DAYS: Final[int] = 30 -# These are build-time defaults, NOT deployment-tunable's: +# These are build-time defaults, NOT deployment-tunables: TIMELINE_MAX_LIMIT: Final[int] = 500 TIMELINE_DEFAULT_LIMIT: Final[int] = 100 @@ -63,7 +63,8 @@ SHA256_HEX_LENGTH: Final[int] = 64 -# Default retention windows used by the conversation cleanup service. Hosts override these per-tenant via CleanupRequest fields. +# Default retention windows used by the conversation cleanup service. +# Hosts override these per-tenant via CleanupRequest fields. # Stored as timedelta so the unit is encoded in the type rather than the identifier suffix. CLEANUP_DEFAULT_BATCH_LIMIT: Final[int] = 1_000 CLEANUP_DEFAULT_EVENT_RETENTION: Final[timedelta] = timedelta(days=90) diff --git a/src/fathom/constants/graph.py b/src/fathom/constants/graph.py index e657de4b..2202655a 100644 --- a/src/fathom/constants/graph.py +++ b/src/fathom/constants/graph.py @@ -2,7 +2,9 @@ class NodeName(StrEnum): - """Standardized names for graph nodes.""" + """ + Standardized names for graph nodes. + """ END = "__end__" SCAN = "scan" @@ -18,7 +20,9 @@ class NodeName(StrEnum): class RouteCause(StrEnum): - """Reasons emitted by graph routing decisions for structured observability.""" + """ + Reasons emitted by graph routing decisions for structured observability. + """ DEFAULT = "default" CANCELLED = "cancelled" diff --git a/src/fathom/constants/platform.py b/src/fathom/constants/platform.py index 35a19c95..4225193a 100644 --- a/src/fathom/constants/platform.py +++ b/src/fathom/constants/platform.py @@ -51,6 +51,7 @@ class AndroidClearStrategy(IntEnum): ANDROID_UIAUTOMATION_ACTIVE_MARKER = "Ui Automation[" ANDROID_UIAUTOMATION_DUMP_PATH = "/data/local/tmp/window_dump.xml" ANDROID_UIAUTOMATION_INSTRUMENTATION_MARKER = "com.android.commands.am.Am instrument" + ANDROID_UIAUTOMATION_PROCESS_NAME = "app_process" ANDROID_UIAUTOMATION_TIMEOUT_MARKER = "timed out" ANDROID_UIAUTOMATION_UIAUTOMATOR_MARKER = "com.android.commands.uiautomator" diff --git a/src/fathom/constants/qualification.py b/src/fathom/constants/qualification.py index 173bd9e5..9dcfe7bc 100644 --- a/src/fathom/constants/qualification.py +++ b/src/fathom/constants/qualification.py @@ -12,12 +12,9 @@ f"See {FATHOM_DOCS_URL} for help and examples." ) -# Eval-validated qualifier inference defaults (see scripts/qualifier_model_eval.py). -# gemini-2.5-flash-lite — Google's "fastest, most budget-friendly multimodal model"; -# avg 0.79s / max 1.48s on the 73-case qualifier corpus, 73/73 accurate. +# Qualifier inference defaults. DEFAULT_QUALIFIER_MODEL: str = "gemini-2.5-flash-lite" -# Per-attempt wall-clock cap. With eval p95 of ~1.12s, 5s gives ~4x headroom while -# preventing the preview-model unbounded tail latency we saw in production. +# Per-attempt wall-clock cap that bounds tail latency. DEFAULT_QUALIFIER_TIMEOUT: float = 5.0 # Retries after the initial attempt; adapter handles backoff + jitter. DEFAULT_QUALIFIER_MAX_RETRIES: int = 2 diff --git a/src/fathom/constants/reasoning.py b/src/fathom/constants/reasoning.py index 60086437..0f842047 100644 --- a/src/fathom/constants/reasoning.py +++ b/src/fathom/constants/reasoning.py @@ -6,13 +6,8 @@ # Ratio threshold for keyword-based completion match. RATIONALE_KEYWORD_MATCH_THRESHOLD: float = 0.72 -# Floor below which similarity is too low for keyword-based rationale verification. -# Raised from 0.10 to 0.35: the old floor accepted any rationale that mentioned -# a generic completion keyword (``done``, ``complete``, ``finished``…) with as -# little as 10% string overlap against the target. That admitted unrelated -# narrations that happened to use a completion word, causing false rationale -# verifications. 0.35 still admits paraphrases (good) but rejects rationales -# that share virtually nothing with the target text (the regression mode). +# Floor below which similarity is too low for keyword-based rationale verification; +# admits paraphrases of the target while rejecting rationales that barely overlap it. RATIONALE_MIN_SIMILARITY_FLOOR: float = 0.35 # Below this rationale-to-sub-goal similarity an asserted claim is flagged as lateral credit; observe-only. @@ -34,14 +29,9 @@ # permanent imperative on later screens. USER_GUIDANCE_ANALYZE_TTL: int = 3 -# Number of consecutive ``validate`` + ``flagged_complete`` emits the planner -# may produce against a non-validate directive before the completion gate -# accepts the divergence as an implicit-completion claim. Bridges the gap -# between (a) the original validate-shortcut bug (one stray validate must NOT -# bypass a tap directive) and (b) genuine app-flow variance where the app -# skips an intermediate screen and the named action is no longer reachable. -# Threshold of 2 means: first validate is rejected (keeps the LLM honest); -# second consecutive validate is accepted (lets stale sub-goals resolve). +# Consecutive ``validate`` + ``flagged_complete`` emits against a non-validate +# directive before the completion gate accepts the divergence as an implicit +# completion. At 2, the first validate is rejected and the second is accepted. IMPLICIT_COMPLETION_THRESHOLD: int = 2 # Action confidence floor; below this the action is rejected outright. diff --git a/src/fathom/constants/runtime.py b/src/fathom/constants/runtime.py index b275550a..ec062fe4 100644 --- a/src/fathom/constants/runtime.py +++ b/src/fathom/constants/runtime.py @@ -20,8 +20,8 @@ DEFAULT_LOOP_WINDOW: Final[int] = 10 DEFAULT_LOOP_THRESHOLD: Final[int] = 3 -# Minimum identical consecutive (action, NO_PROGRESS) pairs that count as an "inert repetition". -# Raised from 2 to 3 so a single misfired tap + planner retry does not immediately trigger a loop. +# Minimum identical consecutive (action, NO_PROGRESS) pairs that count as an "inert repetition"; +# a single misfired tap plus a planner retry stays below this and does not trigger a loop. DEFAULT_INERT_REPETITION_THRESHOLD: Final[int] = 3 DEFAULT_MAX_STEPS: Final[int] = 20 diff --git a/src/fathom/constants/state.py b/src/fathom/constants/state.py index 57dbafef..e3ca8cdf 100644 --- a/src/fathom/constants/state.py +++ b/src/fathom/constants/state.py @@ -52,8 +52,10 @@ class VerifyMode(StrEnum): PENDING_FINAL_COMMIT = "PENDING_FINAL_COMMIT" -# Completion reasons that must terminate the graph immediately (route to END, never to VERIFY) and surface as ``RunOutcome.FAILED`` to callers. -# The router in ``builder.py`` and the outcome assembler in ``intent.py`` MUST both consult this single source so new fatal reasons cannot be missed in one place but not the other. +# Completion reasons that must terminate the graph immediately (route to END, never to VERIFY) +# and surface as ``RunOutcome.FAILED`` to callers. +# The router in ``builder.py`` and the outcome assembler in ``intent.py`` MUST both consult this single source +# so new fatal reasons cannot be missed in one place but not the other. TERMINAL_COMPLETION_REASONS: Final[Tuple[str, ...]] = ( CompletionReason.STUCK.value, CompletionReason.FAILED.value, diff --git a/src/fathom/constants/storage.py b/src/fathom/constants/storage.py index dfdd6608..016f1eb8 100644 --- a/src/fathom/constants/storage.py +++ b/src/fathom/constants/storage.py @@ -97,6 +97,7 @@ class RetentionClass(StrEnum): # wildcards in user-supplied search prefixes (e.g. `%`, `_`) remain literal. INTERACTION_SQL_LIKE_ESCAPE_CHARACTER: Final[str] = "\\" -# SQL LIKE wildcard characters that must be neutralized when user-supplied substrings reach the predicate as literal matchers. +# SQL LIKE wildcard characters that must be neutralized when user-supplied substrings +# reach the predicate as literal matchers. SQL_LIKE_WILDCARD_PERCENT: Final[str] = "%" SQL_LIKE_WILDCARD_UNDERSCORE: Final[str] = "_" diff --git a/src/fathom/constants/subgoal.py b/src/fathom/constants/subgoal.py index 3275edfa..4697858e 100644 --- a/src/fathom/constants/subgoal.py +++ b/src/fathom/constants/subgoal.py @@ -3,9 +3,8 @@ from enum import StrEnum from typing import Final -# Default per-sub-goal step budget. The agent gets this many ANALYZE -> EXECUTE -# -> RECORD cycles per sub-goal before the planner must choose another path. -# Temporarily raised 8 -> 12 so multi-action sub-goals (e.g. "add 3 items") fit; revisit with decomposition. +# Default per-sub-goal step budget: ANALYZE -> EXECUTE -> RECORD cycles allowed +# per sub-goal before the planner must choose another path. DEFAULT_SUB_GOAL_MAX_STEPS: Final[int] = 12 SCROLL_SUB_GOAL_MAX_STEPS: Final[int] = 25 TAP_SUB_GOAL_MAX_STEPS: Final[int] = 3 diff --git a/src/fathom/core/agent/escalation_gate.py b/src/fathom/core/agent/escalation_gate.py index da65f9a3..c7075554 100644 --- a/src/fathom/core/agent/escalation_gate.py +++ b/src/fathom/core/agent/escalation_gate.py @@ -109,13 +109,9 @@ def decide( ) if passive_run == 0: - # No positive evidence of a passive-only pattern in the contributing - # tail. The loop detector classified the window as stuck for some - # other reason (screen repetition without recorded effects, action - # repetition with UNCERTAIN effects). Per the reviewer's "be - # conservative about not suppressing forever, not about fabricating - # no-progress evidence" rule, allow escalation rather than defer - # on absent evidence. + # No positive evidence of a passive-only pattern in the contributing tail. The loop detector + # classified the window as stuck for some other reason (screen repetition without recorded effects, + # action repetition with UNCERTAIN effects), so allow escalation rather than defer on absent evidence. return EscalationDecision( allow=True, reason=EscalationReason.ACTIVE_STALL, diff --git a/src/fathom/core/agent/ladder.py b/src/fathom/core/agent/ladder.py index b752ad1f..5b5bf4e3 100644 --- a/src/fathom/core/agent/ladder.py +++ b/src/fathom/core/agent/ladder.py @@ -23,8 +23,9 @@ class LoopActionLadder: The full rung sequence is BACK -> SCROLL -> HOME. Rungs whose action type is not supported by the active device (per :class:`DeviceCapability`) are filtered out at construction so the - ladder only ever emits actions the device can execute. SCROLL is additionally suppressed at runtime - when the detector evidence already came from a scroll-like action, to avoid a no-op recovery on an already-scrolling stuck signal. + ladder only ever emits actions the device can execute. SCROLL is additionally suppressed at + runtime when the detector evidence already came from a scroll-like action, to avoid a no-op + recovery on an already-scrolling stuck signal. """ def __init__(self, *, device: Optional[DeviceCapability] = None) -> None: diff --git a/src/fathom/core/agent/loop.py b/src/fathom/core/agent/loop.py index 34be994b..ea055689 100644 --- a/src/fathom/core/agent/loop.py +++ b/src/fathom/core/agent/loop.py @@ -33,10 +33,9 @@ class LoopDetector(BaseModel): """ - Detects when agent is stuck in a loop using multi-strategy pattern analysis. + Detects when the agent is stuck in a loop using multi-strategy pattern analysis. - Note: stateful. Designed for single-threaded asyncio access — coordinator - instances are scoped per agent run, so cross-task mutation does not occur under the current execution model. + Stateful and single-threaded: instances are scoped per agent run, so no cross-task mutation occurs. """ max_recovery: int = Field( @@ -163,15 +162,10 @@ def observe_screen(self, *, previous: Optional[ScreenState], current: ScreenStat """ Tell the detector a new screen was seen. - Advances the loop-detection window only when the new screen is - *genuinely* distinct from the previous one — hamming greater than - :data:`SCREEN_PROGRESS_HAMMING_THRESHOLD`. The progress threshold - is deliberately much higher than the near-duplicate threshold - used by the stuck detectors below, so cosmetic differences - (status-bar tick, suggestion-count increment, anti-aliasing - noise) do not trip ``advance()`` and wipe accumulating evidence. - That distinction is what enables the scroll-loop detection to - actually fire on long sequences of near-identical screens. + Advances the window only when the screen is genuinely distinct — hamming above + :data:`SCREEN_PROGRESS_HAMMING_THRESHOLD`, set much higher than the stuck detectors' + near-duplicate threshold so cosmetic diffs don't ``advance()`` and wipe accumulating + evidence (which is what lets scroll-loop detection fire on near-identical screens). """ progressed = current.has_visual_progress_from( @@ -213,9 +207,8 @@ def is_stuck(self) -> bool: } logger.info("LoopDetector.is_stuck evaluating", extra=snapshot) - # 0. Inert-action repetition fires at the tightest threshold so - # the planner can pivot after one wasted action — independent - # of how much screen / action history has accumulated. + # Inert-action repetition fires at the tightest threshold so the planner can pivot after one wasted + # action — independent of how much screen / action history has accumulated. if self.__detect_inert_repetition(): logger.info( "LoopDetector.is_stuck=True via inert_repetition", @@ -239,9 +232,7 @@ def is_stuck(self) -> bool: ) return False - # Screen-based detectors require sufficient screen history. if has_enough_screens: - # 1. Direct Repetition (screen + action counts) if self.__detect_repetition(): logger.info( "LoopDetector.is_stuck=True via screen_repetition", @@ -249,7 +240,7 @@ def is_stuck(self) -> bool: ) return True - # 2. Near-duplicate Visual Repetition (visual pHash only). + # Near-duplicate visual repetition (visual pHash only). # Catches the case where DOM micro-changes (overlay animation frames, # map redraws, transient spinners) flip ``xml_hash``/``interaction_hash`` # and force ``is_same_screen`` to return False even though the screen @@ -266,7 +257,6 @@ def is_stuck(self) -> bool: ) return True - # 3. State Oscillation (A-B-A-B or A-B-C-A) if self.__detect_oscillation(): logger.info( "LoopDetector.is_stuck=True via oscillation", @@ -274,7 +264,6 @@ def is_stuck(self) -> bool: ) return True - # 4. Scroll Stalling (Repetitive scrolling with minimal progress) if self.__detect_scroll_stall(): logger.info( "LoopDetector.is_stuck=True via scroll_stall", @@ -282,7 +271,6 @@ def is_stuck(self) -> bool: ) return True - # 5. Action Velocity (Rapid firing with no progress) if self.__detect_action_velocity_loop(): logger.info( "LoopDetector.is_stuck=True via action_velocity", @@ -328,11 +316,9 @@ def __detect_inert_repetition(self) -> bool: """ Detect identical action descriptors paired with trailing NO_PROGRESS effects. - Fires when the last ``inert_repetition_threshold`` action - descriptors are identical AND the matching trailing effect - statuses are all ``NO_PROGRESS``. Both conditions must hold - so cosmetic same-action retries on a screen that *did* change - don't false-fire (the planner explores during real scrolling and that's not stuck). + Fires when the last ``inert_repetition_threshold`` action descriptors are identical AND the + matching trailing effect statuses are all ``NO_PROGRESS`` — both required so same-action + retries on a screen that did change (e.g. real scrolling) don't false-fire. """ if len(self.__recent_actions) < self.inert_repetition_threshold: @@ -367,15 +353,8 @@ def __detect_repetition(self) -> bool: """ Detect simple screen repetition. - The previous implementation carved out scroll/swipe/flick action - sequences entirely on the assumption that scrolling legitimately - produces same-looking screens. That assumption breaks the moment - scrolling no longer advances content (a non-scrollable list, an - already-revealed CTA, an exhausted feed), so the carve-out is - replaced with a screen-convergence check: if action diversity is - high we still treat that as legitimate exploration, but identical - screens with similar actions and converging visual hashes are - flagged as stuck regardless of action kind. + High action diversity is treated as legitimate exploration; identical screens with similar actions + and converging visual hashes are flagged as stuck regardless of action kind. """ for index in range(len(self.__recent_screens)): @@ -427,14 +406,12 @@ def __detect_repetition(self) -> bool: def __detect_near_duplicate_visual_repetition(self) -> bool: """ - Detect screens whose visual pHash is within a tight hamming threshold - of one another, ignoring structural and interaction hashes. + Detect screens whose visual pHash lies within a tight hamming threshold, ignoring + structural and interaction hashes. - Distinct from ``__detect_repetition`` (which uses ``is_same_screen``): - that path returns False as soon as ``xml_hash`` or ``interaction_hash`` disagree, which masks overlay-animation and map-redraw loops. - - The visual-only check is intentionally narrow (threshold = pHash hamming) - and only counts repetition when the same near-duplicate appears at least ``self.threshold`` times in the window. + Unlike ``__detect_repetition`` (``is_same_screen``), this survives ``xml_hash`` / + ``interaction_hash`` flips that mask overlay-animation and map-redraw loops; counts a + near-duplicate only when it recurs at least ``self.threshold`` times in the window. """ hashes = [hash for hash in self.__recent_hashes if hash] @@ -465,19 +442,10 @@ def __detect_action_repetition(self) -> bool: """ Detect repeated identical actions regardless of screen state. - Survives screen resets (advance) so it can catch loops where each - action produces a visually-different screen (e.g. tapping a - counter button that increments a number). - - Scroll-like actions (swipe / scroll / flick) used to be carved - out entirely. That's wrong when the scroll target has nothing - left to reveal — scrolling produces near-duplicate screens and - the agent loops indefinitely. Replace the carve-out with a - screen-convergence check: scroll-like actions only suppress - repetition detection when the screens they produced are still - diverging (productive scroll). When the screens converge into a - near-duplicate cluster (stuck scroll) they trip stuck like any - other repeated action. + Survives screen resets (advance) so it catches loops where each action produces a visually-different + screen (e.g. tapping a counter button that increments a number). Scroll-like actions suppress detection + only while the screens they produce keep diverging (productive scroll); once those screens converge into + a near-duplicate cluster (stuck scroll) they trip stuck like any other repeated action. """ action_counts: Dict[str, int] = {} @@ -512,12 +480,10 @@ def __detect_action_repetition(self) -> bool: def __recent_hashes_are_converging(self) -> bool: """ - Return True when the most recent ``self.threshold`` visual - hashes all lie within :data:`LOOP_HASH_CLUSTER_HAMMING_THRESHOLD` - of one another. + Return True when the most recent ``self.threshold`` visual hashes all lie within + :data:`LOOP_HASH_CLUSTER_HAMMING_THRESHOLD` of one another. - Used by the scroll-repetition guard to distinguish productive - scrolling (screens diverging through fresh content) from stuck + Distinguishes productive scrolling (screens diverging through fresh content) from stuck scrolling (screens converging into a near-duplicate cluster). """ @@ -542,16 +508,9 @@ def has_repeated_action_on_same_screen( repeat_threshold: int = 3, ) -> bool: """ - Check if the same tap/type action has been executed N+ times on the same screen. - Excludes swipe/scroll actions which legitimately repeat on the same screen. - - Args: - action_description: The action being proposed. - screen_hash: Visual hash of the current screen. - repeat_threshold: Number of repeats before triggering (default 3). + Whether the same tap/type action has run at or above ``repeat_threshold`` times on this screen. - Returns: - True if the action has been repeated on this screen at or above threshold. + Swipe/scroll actions are excluded — they legitimately repeat on the same screen. """ action_lower = action_description.lower() @@ -653,12 +612,9 @@ def __detect_scroll_stall(self) -> bool: streak_hashes = [hash_ for hash_ in list(self.__recent_hashes)[streak_start:] if hash_] distance = ScreenState.hamming_distance(left_hash=first_hash, right_hash=last_hash) - # Stall must show both low net movement AND all streak hashes - # clustered tightly around the anchor. The previous - # ``unique_hash_count <= 2`` check was too strict: pHash jitter - # routinely produces 3+ unique short hashes even when the screen - # is visually identical, so it never fired in practice. The - # cluster-hamming check is jitter-tolerant. + # Stall must show both low net movement AND all streak hashes clustered tightly around the anchor. + # The cluster-hamming check is jitter-tolerant: pHash jitter routinely produces 3+ unique short hashes + # even when the screen is visually identical. all_clustered = True if streak_hashes: anchor = streak_hashes[0] @@ -786,11 +742,9 @@ def evidence(self) -> LoopEvidence: """ Typed read-only snapshot consumed by the escalation gate. - ``reason`` identifies which detection strategy classified the window as - stuck (or ``NOT_STUCK``). ``since_progress`` is the trailing slice of - turns starting after the most recent PROGRESS effect — that is the - only span the gate is allowed to consider, because older turns belong - to a prior recovery cycle and must not unlock escalation on their own. + ``reason`` identifies which detection strategy classified the window as stuck (or + ``NOT_STUCK``). ``since_progress`` is the trailing slice after the most recent PROGRESS + effect — the only span the gate may consider, since older turns belong to a prior cycle. """ reason = self.__classify_reason() diff --git a/src/fathom/core/agent/planner/coordinator.py b/src/fathom/core/agent/planner/coordinator.py index b9fb029f..f637034c 100644 --- a/src/fathom/core/agent/planner/coordinator.py +++ b/src/fathom/core/agent/planner/coordinator.py @@ -34,7 +34,7 @@ class StepPlanner: """ - Plans and prepares steps for execution. + Produces the next planned step for a turn from the current screen and goal. """ def __init__( diff --git a/src/fathom/core/agent/planner/escalation.py b/src/fathom/core/agent/planner/escalation.py index 5fd4b0cd..1d37b9b3 100644 --- a/src/fathom/core/agent/planner/escalation.py +++ b/src/fathom/core/agent/planner/escalation.py @@ -19,8 +19,8 @@ from fathom.schemas.results import AnalysisResult, PlanDecision, PlannerRetry, PlanResult from fathom.schemas.screens import ScreenCapture -# Generic recovery hint injected when the escalation gate defers HITL. The -# model is told what the graph observed and what behaviors are still safe; +# Generic recovery hint injected when the escalation gate defers HITL. +# The model is told what the graph observed and what behaviors are still safe; # we deliberately avoid any app-specific suggestions. ESCALATION_DEFERRED_GUIDANCE: str = ( "The graph detected a possible loop, but recent no-progress actions were " diff --git a/src/fathom/core/agent/reasoner.py b/src/fathom/core/agent/reasoner.py index 8a57efb7..577ace20 100644 --- a/src/fathom/core/agent/reasoner.py +++ b/src/fathom/core/agent/reasoner.py @@ -61,7 +61,6 @@ def analyze_completion( evidence_list: List[str] = [] action = self.__require_action(analysis=analysis) - # Determine what we're checking completion for target_goal = (current_sub_goal or self.__intent).lower() goal_type = "sub-goal" if current_sub_goal else "intent" @@ -71,16 +70,12 @@ def analyze_completion( f"action_type={action.action_type}" ) - # 1. Primary Signal: LLM Flag (Zero Cost - already computed) if analysis.is_goal_complete: evidence_list.append(f"LLM explicitly flagged {goal_type} completion") - # 2. Secondary Signal: Action Type (Zero Cost) if action.action_type == ActionType.COMPLETE: evidence_list.append(f"Agent recommended COMPLETE action for {goal_type}") - # 3. Tertiary Signal: Fast Fuzzy Match - # We check if the reasoning text semantically overlaps with the target goal context = f"{analysis.reasoning} {screen_description or ''}".lower() similarity = SequenceMatcher(None, target_goal, context).ratio() @@ -91,21 +86,15 @@ def analyze_completion( keyword_match = similarity >= RATIONALE_KEYWORD_MATCH_THRESHOLD action_indicates_complete = action.action_type == ActionType.COMPLETE - # 4. Additional Signal for Sub-Goals: Action Execution on Non-Opening Tasks - # If we're checking a sub-goal like "Open X" and the LLM is DOING something - # (not just planning), it means "Open X" is likely ALREADY complete action_suggests_next_phase = False if ( current_sub_goal and self.__opener_policy.advanced(action_type=action.action_type) and any(word in target_goal for word in OPENER_GOAL_WORDS) ): - # LLM is actively performing actions. If the current sub-goal is an opener - # (contains "open", "launch", "navigate to", "go to"), then performing - # a tap/type suggests we're past the opening phase. - # Check if reasoning suggests we're at a next phase + # An opener sub-goal ("open", "launch", "navigate to", "go to") is likely already past its opening + # phase once the model performs a tap/type, so a next-phase keyword in the rationale confirms it. reasoning_lower = analysis.reasoning.lower() - # More flexible keyword matching - check for partial matches if any(keyword in reasoning_lower for keyword in NEXT_PHASE_KEYWORDS): evidence_list.append( f"LLM performing next-phase action ({action.action_type.value})" @@ -202,10 +191,8 @@ def __verify_rationale( similarity, ) - # Surface the rejection mode for observability: a completion - # keyword landed in the rationale but the rationale text shares - # too little with the target to be trusted as evidence. This is - # the regression mode the similarity floor was raised to catch. + # Surface the rejection mode for observability: a completion keyword landed in the rationale but the + # rationale text shares too little with the target to be trusted as evidence. if keywords_found and similarity < RATIONALE_MIN_SIMILARITY_FLOOR: logger.info( "Rationale rejected: completion keyword present but similarity below floor", diff --git a/src/fathom/core/agent/shadow.py b/src/fathom/core/agent/shadow.py index 3f8cb01d..29760f9e 100644 --- a/src/fathom/core/agent/shadow.py +++ b/src/fathom/core/agent/shadow.py @@ -13,7 +13,7 @@ class ShadowAssessor: """ Records how a shadow visual assessment diverges from live behavior and the goal's evidence source. - Slice 2 is observe-and-record only: the live action still executes and no goal advances from this. + This is observe-and-record only: the live action still executes and no goal advances from this. The host — not the model schema — enforces which goals may carry a visual assessment and that a bound target's foreground package is present and exactly equal before a satisfied verdict may count. """ diff --git a/src/fathom/core/agent/state.py b/src/fathom/core/agent/state.py index cd4752dc..838ec6ae 100644 --- a/src/fathom/core/agent/state.py +++ b/src/fathom/core/agent/state.py @@ -48,15 +48,7 @@ class AgentState: """ - Stateful agent context for planning and execution. - - Manages: - - Screen state history with deduplication - - Action history with success/failure tracking - - Interaction tracking for behavioral constraints - - Loop detection with recovery strategies - - Thread-safe for async operations. Serializable for checkpointing. + Stateful agent context for planning and execution; serializable for checkpointing. """ def __init__( @@ -184,7 +176,7 @@ def is_complete(self) -> bool: @property def completion_reason(self) -> Optional[str]: """ - Returns Completion Reason + Why the run is considered complete, if set. """ return self.__completion_reason @@ -217,9 +209,8 @@ def loop_evidence(self) -> LoopEvidence: """ Typed read-only snapshot of the loop detector for the escalation gate. - Exposed on :class:`AgentState` so domain components do not reach into - the private runtime path. Returns the detector's :class:`LoopEvidence` - snapshot: stuck flag, reason, full recent window, and ``since_progress``. + Returns the detector's :class:`LoopEvidence`: stuck flag, reason, full recent + window, and ``since_progress``. """ return self.__runtime.screen.detector.evidence() @@ -425,13 +416,7 @@ def __is_new_screen(self, screen: ScreenState) -> bool: def update_screen(self, screen: ScreenState) -> bool: """ - Update current screen state. - - Args: - screen: New screen state. - - Returns: - True if this is a new screen, False if seen before. + Record the observed screen and return whether it is one not seen before this run. """ previous_screen = self.__runtime.screen.current @@ -516,10 +501,7 @@ def get_history(self, limit: int = 5) -> List[Dict[str, Any]]: def record_step(self, result: StepResult) -> None: """ - Record a completed step. - - Args: - result: Result of the executed step. + Record a completed step and fold its outcome into the run's counters and history. """ self.__step_count += 1 @@ -575,11 +557,8 @@ def record_attempt(self, *, action: Action, reason: str) -> None: """ Record an attempted (but not dispatched) action against the loop detector. - Used at planner / supervise rejection sites so the agent's *intent* to - repeat the same action enters the LoopDetector window even when the - attempt is rejected before reaching the executor. Without this, - successive same-target attempts that are rejected upstream stay - invisible to ``action_repetition`` and the agent can loop silently. + Feeds a rejected repeat-intent into the LoopDetector window so ``action_repetition`` + sees same-target attempts rejected upstream; without it the agent can loop silently. """ action_type = action.action_type.value @@ -648,10 +627,7 @@ def __assign_last_action( def mark_complete(self, reason: str) -> None: """ - Mark the intent as complete. - - Args: - reason: Why the intent is considered complete. + Mark the intent complete with the given reason. """ self.__is_complete = True @@ -678,10 +654,8 @@ def record_complete_deferral(self) -> int: """ Increment and return the consecutive complete-deferral counter. - The router invokes this when it routes an ``is_complete=True`` - ANALYZE verdict back to GROUND because sub-goals are still - open. Returning the post-increment value lets the caller - decide whether to escalate. + The router calls this when it routes an ``is_complete=True`` verdict back to GROUND with + sub-goals still open; the post-increment value lets the caller decide whether to escalate. """ self.__consecutive_complete_deferrals += 1 @@ -691,10 +665,7 @@ def reset_complete_deferrals(self) -> None: """ Zero the consecutive complete-deferral counter. - Called on real progress: a non-complete plan, a successful - sub-goal advancement, or a verifier pass. Without the reset, - a single late deferral would forever bias the bounded-retry - threshold against the planner. + Called on real progress — a non-complete plan, a sub-goal advancement, or a verifier pass. """ self.__consecutive_complete_deferrals = 0 @@ -749,10 +720,7 @@ def clear_verification_loop(self) -> None: def set_sub_goals(self, sub_goals: List[SubGoal]) -> None: """ - Set the decomposed sub-goals for this intent. - - Args: - sub_goals: List of sequential sub-goals to execute. + Set the decomposed sub-goals and activate the first one as in-progress. """ self.__sub_goals = [GoalState(goal=goal) for goal in sub_goals] @@ -771,10 +739,7 @@ def set_sub_goals(self, sub_goals: List[SubGoal]) -> None: def get_current_sub_goal(self) -> Optional[GoalState]: """ - Get the currently active sub-goal. - - Returns: - Current sub-goal or None if no sub-goals defined. + Return the active sub-goal, or None when none are defined or the cursor is past the end. """ if not self.__sub_goals or self.__current_sub_goal_index >= len(self.__sub_goals): @@ -791,10 +756,7 @@ def has_active_final_sub_goal(self) -> bool: def set_current_sub_goal_index(self, index: int) -> None: """ - Set the current sub-goal index (used for checkpoint restore). - - Args: - index: Index to set (will be clamped to valid range) + Set the active sub-goal index (clamped to range) and mark it in-progress; used by checkpoint restore. """ if self.__sub_goals: @@ -948,10 +910,7 @@ def current_sub_goal_over_budget(self) -> bool: def all_sub_goals_complete(self) -> bool: """ - Check if all sub-goals have been completed. - - Returns: - True if all sub-goals are complete or no sub-goals defined. + Whether every sub-goal is complete; True when none are defined. """ if not self.__sub_goals: @@ -961,10 +920,7 @@ def all_sub_goals_complete(self) -> bool: def get_sub_goal_progress(self) -> Tuple[int, int]: """ - Get current progress through sub-goals. - - Returns: - Tuple of (current_index, total_count). + Return progress through the sub-goals as ``(current_index, total_count)``. """ if not self.__sub_goals: @@ -974,20 +930,14 @@ def get_sub_goal_progress(self) -> Tuple[int, int]: def get_all_sub_goals(self) -> List[GoalState]: """ - Get all sub-goals. - - Returns: - List of all sub-goals. + Return a copy of the full sub-goal list. """ return self.__sub_goals.copy() def has_sub_goals(self) -> bool: """ - Check if sub-goals are defined. - - Returns: - True if sub-goals exist. + Whether any sub-goals are defined. """ return len(self.__sub_goals) > 0 @@ -1048,14 +998,10 @@ def reset_loop_detector(self) -> None: def record_action_effect(self, *, effect: ActionEffect) -> None: """ - Append a structured action-effect outcome to the rolling - trajectory window. + Append a structured action-effect outcome to the rolling trajectory window. - Called from EXECUTE after each step using - :meth:`ActionEffect.from_screen_diff` against the post-action - :class:`ScreenDiff`. The window is bounded by - ``ACTION_EFFECT_TRAJECTORY_WINDOW`` so the prompt size stays - stable regardless of run length. + Called from EXECUTE via :meth:`ActionEffect.from_screen_diff` on the post-action + :class:`ScreenDiff`; the window is bounded by ``ACTION_EFFECT_TRAJECTORY_WINDOW``. """ self.__runtime.effects.record_effect(effect=effect) @@ -1078,24 +1024,11 @@ def get_last_action_effect(self) -> Optional[ActionEffect]: def build_loop_observation(self) -> Optional[LoopObservation]: """ - Construct a :class:`LoopObservation` summarizing the current - stuck evidence, or ``None`` when the agent is not stuck. - - The observation is the structured input the ANALYZE prompt - renders into ````. Built here (not in the - prompt assembler) so the rules for *when* to inject — and what - evidence to surface — live with the state that produced the - evidence. - - Returns ``None`` when: - - - The loop detector hasn't fired (``is_stuck`` is False) AND - - The action-effect trajectory hasn't crossed the no-progress - recovery threshold. + Construct a :class:`LoopObservation` summarizing the current stuck evidence, or ``None`` + when the agent is not stuck. - In either of those branches the agent receives no - ``SYSTEM_OBSERVATION`` block — the runtime tells the agent - nothing when there's nothing reliable to tell. + Feeds the ANALYZE prompt's ```` block. Returns ``None`` unless the loop + detector fired or the action-effect trajectory crossed the no-progress recovery threshold. """ stuck = self.is_stuck @@ -1159,10 +1092,8 @@ def consecutive_no_progress_count(self) -> int: """ Number of trailing actions classified as ``NO_PROGRESS``. - Used by the RECORD node to decide whether to emit the - ``NO_PROGRESS`` recovery trigger. Counts only the contiguous - tail of the trajectory window — a single ``PROGRESS`` step - resets the counter. + Counts only the contiguous tail of the trajectory window; a single ``PROGRESS`` step resets + the counter. Read by RECORD to decide whether to emit the ``NO_PROGRESS`` recovery trigger. """ return self.__runtime.effects.consecutive_no_progress() @@ -1192,13 +1123,7 @@ def build_context(self) -> Dict[str, object]: def should_avoid_action(self, action: Action) -> bool: """ - Check if an action should be avoided due to recent failures. - - Args: - action: Proposed action. - - Returns: - True if action has failed recently. + Whether the action has failed recently enough to be worth avoiding. """ return self.__action_history.has_repeated_failure(action=action) @@ -1329,10 +1254,8 @@ def record_blocked_action( """ Record a deterministically blocked action as failure context. - Also feeds the LoopDetector window via :meth:`record_attempt` so the agent's *intent* to repeat the same blocked action - becomes visible to ``action_repetition``. Without this, the planner-side block path returned ``should_retry=True`` - while the LoopDetector never saw the rejected attempt — so ``is_stuck`` never tripped, the planner's escalation gate never fired ``ASK_USER``, - and the workflow looped silently until ``max_steps``. + Also feeds the block into the LoopDetector via :meth:`record_attempt` so ``action_repetition`` + sees the repeat-intent; without it ``is_stuck`` never trips and the workflow loops silently. """ activity = ( @@ -1349,13 +1272,7 @@ def record_blocked_action( def is_action_repeating_on_screen(self, action: Action) -> bool: """ - Check if a tap/type action has been executed 3+ times on the current screen. - - Args: - action: Proposed action. - - Returns: - True if the same action has been repeated 3+ times on the current screen. + Whether this tap/type action has already run 3+ times on the current screen. """ if (current := self.__runtime.screen.current) is None: @@ -1368,10 +1285,7 @@ def is_action_repeating_on_screen(self, action: Action) -> bool: def to_checkpoint(self) -> Dict[str, object]: """ - Serialize state for checkpointing. - - Returns: - Dictionary suitable for JSON serialization. + Serialize the full agent state into a JSON-ready checkpoint dictionary. """ return { diff --git a/src/fathom/core/agent/stuck_source.py b/src/fathom/core/agent/stuck_source.py index a2e9825c..74770584 100644 --- a/src/fathom/core/agent/stuck_source.py +++ b/src/fathom/core/agent/stuck_source.py @@ -10,15 +10,10 @@ class StuckSourceResolver: """ Resolve the canonical "stuck" source that warrants escalation. - Pure read-only over :class:`AgentState`. Returns ``None`` when no source is - active so callers can short-circuit without invoking the gate. Priority - order is deterministic: budget exhaustion beats loop detection because - budget is an unambiguous hard signal whereas the loop detector is a - probabilistic classifier over a sliding window. - - Global ``max_steps`` is not modelled here — the analyze node already - terminates the workflow when it is hit, so a source for it would be - unreachable and would also overlap a code path with different semantics. + Pure read-only over :class:`AgentState`; returns ``None`` when no source is active so callers + skip the gate. Priority is deterministic — budget exhaustion (a hard signal) beats the loop + detector (a probabilistic sliding-window classifier). Global ``max_steps`` is not modelled + here: the analyze node already terminates the workflow when it is hit. """ def resolve(self, *, agent_state: AgentState) -> Optional[StuckSource]: diff --git a/src/fathom/core/artifact/drawing/box.py b/src/fathom/core/artifact/drawing/box.py index 64b3694b..bd9b4a33 100644 --- a/src/fathom/core/artifact/drawing/box.py +++ b/src/fathom/core/artifact/drawing/box.py @@ -13,15 +13,9 @@ class BoxDrawer: """ Single shared primitive for drawing labelled boxes on annotated artifacts. - Owns font, font size, outline width, label format, and the - source-keyed colour palette so every annotated-artifact renderer - (manifest, perception, per-source perception) draws boxes in a - consistent visual style. - - Label priority is numeric ``label_id`` first, then visible text, - then role — the planner reads numeric labels off the manifest, so - keeping numeric labels visible on every annotated image is the - fastest mental round-trip for human review. + Owns font, font size, outline width, label format, and the source-keyed colour palette so every + annotated-artifact renderer draws in a consistent style. Label priority is numeric ``label_id`` + first, then visible text, then role — matching the numeric labels the planner reads off the manifest. """ __SOURCE_COLOURS: Final[Mapping[ElementSource, str]] = { @@ -99,29 +93,26 @@ def __compose_label( role: Optional[str], ) -> str: """ - Pick the most informative label without falling back to noise. - - Numeric label_id is preferred because it matches what the LLM - sees in the manifest. Visible text is the next-best identifier - for human reviewers. Role is the last-resort marker so empty - boxes never go un-labelled. + Pick the most informative label: numeric ``label_id`` (matches the manifest the LLM sees), + else visible text, else role as a last-resort marker so empty boxes never go un-labelled. """ if label_id: return label_id + if text and text.strip(): return text.strip()[:32] + if role: return role + return "" @staticmethod def __label_position(*, bounds: Tuple[int, int, int, int]) -> Tuple[int, int]: """ - Anchor the label at the top-left interior of the box. - - Drawing inside the box keeps labels readable on dense screens - where boxes are stacked and outside-labels overlap each other. + Anchor the label at the top-left interior of the box; drawing inside keeps labels readable on + dense screens where stacked boxes make outside labels overlap. """ x1, y1, _x2, _y2 = bounds @@ -133,12 +124,8 @@ def __label_position(*, bounds: Tuple[int, int, int, int]) -> Tuple[int, int]: @classmethod def __resolve_font(cls, *, size: int) -> ImageFont.ImageFont: """ - Load a TrueType font at the requested size, falling back to the - Pillow default when no system font is available. - - ``ImageFont.load_default()`` is used as a guaranteed fallback so - rendering never crashes when the runtime environment lacks the - usual platform font paths. + Load a TrueType font at the requested size, falling back to the Pillow default + (``ImageFont.load_default()``) so rendering never crashes when no system font path exists. """ for path in cls.__FONT_SEARCH_PATHS: @@ -147,4 +134,5 @@ def __resolve_font(cls, *, size: int) -> ImageFont.ImageFont: return ImageFont.truetype(path, size) except OSError: continue + return ImageFont.load_default() diff --git a/src/fathom/core/artifact/pipeline.py b/src/fathom/core/artifact/pipeline.py index de92c2b9..ad582c15 100644 --- a/src/fathom/core/artifact/pipeline.py +++ b/src/fathom/core/artifact/pipeline.py @@ -29,7 +29,7 @@ class ArtifactPipeline: Centralized observer for every artifact-producing lifecycle stage. Producers (perception, action, hierarchy, verification, script) call ``emit(record=...)`` - and the pipeline takes ownership of: staging bytes onto the EFS-backed :class:`SharedPathManager` + and the pipeline takes ownership of: staging bytes onto the local-disk-backed :class:`SharedPathManager` synchronously (the durability boundary), dispatching the metadata + bytes to the :class:`ArtifactSinkPort` in a background task, and draining pending work at shutdown. """ @@ -60,7 +60,7 @@ async def emit(self, *, record: ArtifactRecord) -> Optional[Path]: """ Stage durably and enqueue background upload; never raises. - Returns the EFS payload path on success so producers can wire the same path into downstream metadata (``storage_id``, ``capture.metadata["path"]``) + Returns the staged payload path on success so producers can wire the same path into downstream metadata (``storage_id``, ``capture.metadata["path"]``) without performing a second write against :class:`StoragePort`. Returns ``None`` when the record was rejected or the renderer raised. """ @@ -149,7 +149,7 @@ def __stage_to_efs( metadata: ArtifactMetadata, ) -> Path: """ - Synchronously write the payload bytes to EFS and return the path. + Synchronously write the payload bytes to local disk and return the path. """ payload_path = self.__path_manager.get_artifact_path( @@ -271,7 +271,7 @@ def __log_staged(self, *, metadata: ArtifactMetadata, payload_path: Path) -> Non @staticmethod def __unlink(*, payload_path: Path) -> None: """ - Remove the EFS payload after a successful upload. + Remove the staged payload after a successful upload. """ with contextlib.suppress(FileNotFoundError): diff --git a/src/fathom/core/artifact/renderer.py b/src/fathom/core/artifact/renderer.py index 884cc24a..f5a73a7f 100644 --- a/src/fathom/core/artifact/renderer.py +++ b/src/fathom/core/artifact/renderer.py @@ -35,13 +35,10 @@ class PassthroughRenderer(ArtifactRendererPort): """ - Renderer for kinds whose payloads are already in their final byte form. + Renderer for kinds whose payloads are already in final byte form. - Handles :class:`ScreenshotPayload`, :class:`HierarchyXmlPayload`, - :class:`ScriptPayload`, and :class:`AnnotatedPayload` (the screen - capture's ``annotated_image`` is already PNG bytes upstream). The - bound :class:`ArtifactKind` is fixed at construction so the renderers - map stays statically typed. + Handles :class:`ScreenshotPayload`, :class:`HierarchyXmlPayload`, :class:`ScriptPayload`, and + :class:`AnnotatedPayload` (the capture's ``annotated_image`` is already PNG bytes upstream). """ def __init__(self, *, kind: ArtifactKind) -> None: @@ -89,11 +86,8 @@ class PerceptionRenderer(ArtifactRendererPort): """ Renders the merged-perception debug image. - Draws every :class:`PerceivedElement` in the observation through the - shared :class:`BoxDrawer`, plus overlay rectangles and - call-to-action boxes. Source colour, font, outline, and label - formatting are owned by :class:`BoxDrawer` so this renderer cannot - drift from the per-source renderers. + Draws every :class:`PerceivedElement`, plus overlay rectangles and call-to-action boxes, + through the shared :class:`BoxDrawer`, which owns colour, font, outline, and label formatting. """ def __init__(self, *, drawer: Optional[BoxDrawer] = None) -> None: @@ -205,14 +199,9 @@ class SourceFilteredPerceptionRenderer(ArtifactRendererPort): """ Renders a single-source slice of the observation. - Parameterised by :class:`ArtifactKind` (the discriminator the - pipeline routes on) and :class:`ElementSource` (the projection - filter), so OCR / CV / icon / vision images share the same - rendering primitive and styling. - - Overlay-only artifacts are handled by :class:`OverlayPerceptionRenderer` - since overlays are not perceived elements; they live on - ``observation.overlays`` and have a different shape. + Parameterised by :class:`ArtifactKind` (routing discriminator) and :class:`ElementSource` + (projection filter) so OCR / CV / icon / vision images share one primitive. Overlay-only + artifacts go through :class:`OverlayPerceptionRenderer` since overlays are not perceived elements. """ def __init__( diff --git a/src/fathom/core/context/engines/gcc.py b/src/fathom/core/context/engines/gcc.py index c42e5b6c..5e034860 100644 --- a/src/fathom/core/context/engines/gcc.py +++ b/src/fathom/core/context/engines/gcc.py @@ -25,19 +25,12 @@ class GitContextEngine(ContextEngine): 3. Background task summarizes the segment and creates a milestone 4. commit() keeps last N items in shadow_buffer for continuity 5. LLM sees: Milestones (semantic) + Shadow Buffer (recent details) + Active Log (current) - - This design scales to 100+ step workflows while maintaining context continuity. """ def __init__(self, *, context_window: int = 7) -> None: """ - Initialize the Git engine with a default main branch. - - Args: - context_window: - Number of recent items to keep in shadow_buffer after commit. - Balances context continuity with memory efficiency. - Default: 7 (provides ~7 steps of recent detailed history for better continuity) + Start on the ``main`` branch; ``context_window`` is how many recent trace items the shadow + buffer keeps after each commit, trading memory for cross-commit reasoning continuity. """ self.__current_branch: str = "main" diff --git a/src/fathom/core/context/manager.py b/src/fathom/core/context/manager.py index c2c228cd..195ddb99 100644 --- a/src/fathom/core/context/manager.py +++ b/src/fathom/core/context/manager.py @@ -23,13 +23,9 @@ class ContextManager: """ - Coordinator for the agent context and memory lifecycle. - - Responsibilities: - - HITL guidance injection. - - Distributed state persistence (via MemoryPort). - - Background summarization management (Zero Latency). - - Delegation of versioning/branching to a ContextEngine. + Coordinates the agent's context and memory lifecycle: human-in-the-loop guidance injection, + state persistence through the :class:`MemoryPort`, non-blocking background summarization, and + delegation of versioning and branching to a :class:`ContextEngine`. """ def __init__( @@ -41,13 +37,8 @@ def __init__( summarizer: Optional[SummarizationPort] = None, ) -> None: """ - Initialize the manager. - - Args: - memory: Distributed persistence port. - workflow_id: Unique session identifier. - engine: Memory construction strategy (defaults to GCC). - summarizer: Intelligence port for semantic compression. + Wire the manager to its persistence port and, when omitted, default the context engine to + GCC; ``summarizer`` supplies the semantic-compression backend for background distillation. """ self.__memory = memory @@ -73,15 +64,11 @@ def __init__( # Async Lifecycle self.__background_tasks: Set[asyncio.Task[None]] = set() - # Persistence Queue for Non-Blocking I/O. - # Currently DISABLED: GCC context is not persisted to Ledger (see - # __persistence_worker docstring). Fields kept so call sites and - # shutdown logic stay valid; re-enable by uncommenting the spawn below. + # Persistence queue for non-blocking I/O. Currently disabled: GCC context is not persisted to Ledger + # (see __persistence_worker). Fields kept so call sites and shutdown logic stay valid. self.__persistence_task: Optional[asyncio.Task[None]] = None self.__persist_queue: asyncio.Queue[Dict[str, Any]] = asyncio.Queue() - # self.__start_persistence_loop() - def __start_persistence_loop(self) -> None: """ Starts the background worker for state persistence. @@ -90,22 +77,13 @@ def __start_persistence_loop(self) -> None: loop = asyncio.get_running_loop() self.__persistence_task = loop.create_task(self.__persistence_worker()) - # self.__background_tasks.add(self.__persistence_task) - # self.__persistence_task.add_done_callback(self.__background_tasks.discard) - async def __persistence_worker(self) -> None: """ Background worker that drains the persistence queue. - NOTE: GCC context persistence to Ledger is DISABLED. - - Rationale: - - GCC context is internal system state, not user-actionable memory - - Storing it in Ledger causes memory pollution (thousands of tokens) - - GCC context is already available in-memory via get_full_context() - - If persistence is needed, use separate storage mechanism (not Ledger) - - The queue draining logic is kept for potential future use with separate context storage. + GCC-context persistence to Ledger is disabled: it is internal system state, not + user-actionable memory, and storing it there pollutes memory with thousands of tokens. + Drain logic is kept for a possible future separate context store. """ while True: @@ -115,10 +93,8 @@ async def __persistence_worker(self) -> None: break try: - # GCC context is NOT persisted to Ledger by design. - # Ledger is reserved for user-actionable memory only. - # If you need GCC persistence, implement separate context storage - # by replacing the no-op below with serialization + memory.set. + # GCC context is not persisted to Ledger by design; Ledger is reserved for user-actionable + # memory only. To add GCC persistence, serialize state_data into a separate context store. logger.info( "[ContextManager] skipping GCC persistence to Ledger", extra={ @@ -128,12 +104,6 @@ async def __persistence_worker(self) -> None: "state_keys": list(state_data.keys()), }, ) - # Reference implementation for when separate context storage is added: - # json_data = await asyncio.to_thread(json.dumps, state_data) - # await self.__memory.set( - # key=f"context:v3:{self.__workflow_id}", - # value=json_data, - # ) except Exception as exception: logger.error( "[ContextManager] background persistence failure", @@ -151,102 +121,57 @@ async def __persistence_worker(self) -> None: async def hydrate(self) -> None: """ - Restores the entire context hierarchy from the distributed store. - - NOTE: GCC context hydration from Ledger is DISABLED. + Restore the context hierarchy from the distributed store. - Rationale: - - GCC context is NOT stored in Ledger (see __persistence_worker) - - Each session starts with fresh GCC context - - If persistence is needed, implement separate context storage + GCC-context hydration from Ledger is disabled (it is never stored there); each session + starts with fresh GCC context. """ - # GCC context is NOT loaded from Ledger - # Each session starts fresh, If GCC persistence is required, implement separate context storage - + # GCC context is not loaded from Ledger; each session starts fresh. If GCC persistence is required, + # implement a separate context store. logger.info( f"[ContextManager] Starting fresh session | " f"workflow_id={self.__workflow_id} | " f"gcc_persistence=disabled" ) - """ - try: - if state_raw := await self.__memory.get(key=f"context:v3:{self.__workflow_id}"): - data = await asyncio.to_thread(json.loads, state_raw) - self.__roadmap_intent = data.get("intent", "unknown") - self.__user_guidance = [ - UserGuidance(**guidance) for guidance in data.get("guidance", []) - ] - # Delegate engine hydration - await self.__engine.hydrate(data=data.get("engine", {})) - - logger.info(f"Context: Hydrated session {self.__workflow_id}") - except Exception as exception: - logger.error(f"Context: Hydration failure: {exception}") - """ - async def __enqueue_persist(self) -> None: """ - Captures a snapshot of the current state and queues it for persistence. - This operation is O(1) in-memory and non-blocking. + Snapshot current state and queue it for persistence (O(1), non-blocking). - DISABLED: persistence worker is not spawned (see __init__). Returning - early avoids growing __persist_queue unbounded with snapshots that no - consumer will drain. Re-enable in lockstep with __start_persistence_loop. + Disabled: the persistence worker is not spawned, so this returns early to avoid growing + ``__persist_queue`` unbounded; re-enable in lockstep with ``__start_persistence_loop``. """ return - # Reference snapshot composition for when persistence is re-enabled: - # try: - # state_data = { - # "intent": self.__roadmap_intent, - # "engine": self.__engine.dehydrate(), - # "guidance": [g.model_dump() for g in self.__user_guidance], - # } - # self.__persist_queue.put_nowait(state_data) - # except Exception as exception: - # logger.error( - # "[ContextManager] failed to enqueue persistence", - # extra={ - # "component": "context", - # "event": "enqueue_failed", - # "workflow_id": self.__workflow_id, - # "error": str(exception), - # }, - # ) async def commit(self, *, observation: str, thought: str, action: Action) -> None: """ Record an atomic reasoning cycle. """ - # Clean action dump action_data = action.model_dump() if hasattr(action, "model_dump") else {"raw": str(action)} await self.__engine.record(observation=observation, thought=thought, action=action_data) - # Log trace length after record trace_len = len(self.__engine.get_context().get("trace", [])) logger.info(f"[ContextManager] After record: trace_length={trace_len}") - # Non-blocking persist await self.__enqueue_persist() async def branch(self) -> None: """ - Triggers non-blocking semantic compression (The GCC COMMIT logic). - Offloads summarization to a background task to maintain Zero Latency (P0). + Trigger non-blocking semantic compression (the GCC commit logic), offloading + summarization to a background task to keep foreground latency low. """ logger.info( f"[ContextManager] branch() called, trace_length_before={len(self.__engine.get_context().get('trace', []))}" ) - # 1. Prepare engine for background work - # (GitContextEngine moves active log to shadow buffer) + # GitContextEngine moves the active log to the shadow buffer for background summarization. if not hasattr(self.__engine, "prepare_summarization"): - # If engine doesn't support semantic branching, we do nothing or simple commit + # Engines without semantic branching skip compression entirely. return engine_with_summarization = cast("Any", self.__engine) @@ -258,10 +183,8 @@ async def branch(self) -> None: f"[ContextManager] After prepare_summarization: segment_length={len(segment)}, trace_length={len(self.__engine.get_context().get('trace', []))}" ) - # 2. Persist structural change immediately (non-blocking) await self.__enqueue_persist() - # 3. Offload intelligence if not self.__summarizer: await self.__engine.commit(summary=f"Captured {len(segment)} steps.") logger.info( @@ -424,7 +347,6 @@ async def shutdown(self) -> None: Gracefully shuts down all background tasks and the persistence worker. """ - # 1. Wait for in-flight summarization tasks with bounded timeout pending = [task for task in self.__background_tasks if not task.done()] if pending: logger.info( @@ -443,7 +365,6 @@ async def shutdown(self) -> None: if not task.done(): task.cancel() - # 2. Drain the persistence queue if self.__persistence_task: if not self.__persist_queue.empty(): try: diff --git a/src/fathom/core/exceptions.py b/src/fathom/core/exceptions.py index 160b3c24..86c3f437 100644 --- a/src/fathom/core/exceptions.py +++ b/src/fathom/core/exceptions.py @@ -452,7 +452,8 @@ def thread(self) -> str: class ThreadConflictError(InteractionError): """ - Error raised when a thread create request collides with an existing thread of the same identifier but different content + Error raised when a thread create request collides with an existing thread of the same + identifier but different content. """ def __init__(self, *, thread: str, message: str) -> None: diff --git a/src/fathom/core/execution/engine.py b/src/fathom/core/execution/engine.py index 44bd133c..bffb6d25 100644 --- a/src/fathom/core/execution/engine.py +++ b/src/fathom/core/execution/engine.py @@ -62,7 +62,6 @@ def __init__( self.__max_retries = max_retries self.__stability_wait = stability_wait - # Initialize Domain Services self.__perception_service = PerceptionService( storage=storage, perception=perception, @@ -92,10 +91,8 @@ async def execute_step( start_time = time.time() try: - # Phase 1: Signal Check injected_context = await self.__check_signal() - # Phase 2: Perceive (capture pre-action state) if pre_capture is None: pre_capture = await self.__perception_service.perceive( session_id=session_id, @@ -104,7 +101,6 @@ async def execute_step( pre_hash = self.__perception_service.compute_visual_hash(capture=pre_capture) - # Phase 3: Reason (Implicit) if injected_context: step = step.model_copy( update={ @@ -112,7 +108,6 @@ async def execute_step( } ) - # Phase 4: Act result = await self.__action_executor.act( step=step, session_id=session_id, @@ -128,14 +123,12 @@ async def execute_step( ) post_hash = self.__perception_service.compute_visual_hash(capture=post_capture) - # Phase 5: Learn await self.__learn( action=step.action, visual_hash=pre_hash, success=result.success, ) - # Phase 6: Checkpoint duration = int((time.time() - start_time) * 1000) screen_changed = ( ScreenState.hamming_distance( @@ -187,7 +180,7 @@ async def execute_step( async def __check_signal(self) -> Optional[str]: """ - Phase 1: Check for HITL control signals. + Check for HITL control signals. """ signal = await self.__signal.check_signal() @@ -213,7 +206,7 @@ async def __check_signal(self) -> Optional[str]: async def __learn(self, visual_hash: str, action: Action, success: bool) -> None: """ - Phase 5: Store experience in memory. + Store experience in memory. """ try: @@ -230,7 +223,7 @@ async def __learn(self, visual_hash: str, action: Action, success: bool) -> None async def __checkpoint(self, step_result: StepResult) -> None: """ - Phase 6: Log execution state. + Log execution state. """ await self.__telemetry.info( diff --git a/src/fathom/core/localization/matcher.py b/src/fathom/core/localization/matcher.py index b7144839..e41e68e6 100644 --- a/src/fathom/core/localization/matcher.py +++ b/src/fathom/core/localization/matcher.py @@ -25,7 +25,7 @@ def __init__(self, *, configuration: Optional[LayoutMatchConfiguration] = None) @property def configuration(self) -> LayoutMatchConfiguration: """ - Expose the immutable configuration so callers can log tunable's alongside matches. + Expose the immutable configuration so callers can log tunables alongside matches. """ return self.__configuration @@ -52,8 +52,9 @@ def find_best_match_within( """ Return the highest-scoring phrase cluster restricted to OCR elements whose centroid lies inside ``bounds``. - The region pre-filter is the matcher's spatial gate when the planner already provided a target region: - the F1 threshold is intentionally bypassed here so the caller (``RegionalEvidenceMatcher``) can apply a recall-weighted decision on the returned cluster. + The region pre-filter is the matcher's spatial gate when the planner already provided a target + region: the F1 threshold is intentionally bypassed here so the caller (``RegionalEvidenceMatcher``) + can apply a recall-weighted decision on the returned cluster. """ if not (target_words := self.__words(value=target)): diff --git a/src/fathom/core/perception/localization.py b/src/fathom/core/perception/localization.py index 0ef8bd6a..e7c3cf11 100644 --- a/src/fathom/core/perception/localization.py +++ b/src/fathom/core/perception/localization.py @@ -42,9 +42,8 @@ def __init__( regional_matcher: Optional[RegionalEvidenceMatcher] = None, ) -> None: """ - Initialize the localizer with optional ensemble layer, phrase + regional - matchers, and run context. Defaults instantiate the Domain matchers so - unit tests and minimal compositions need not wire them explicitly. + Initialize the localizer with optional ensemble layer, phrase + regional matchers, and run + context; omitted matchers default to the Domain implementations. """ self.__catalog = catalog @@ -281,12 +280,9 @@ def __log_localization_result( result: LocalizationResult, ) -> None: """ - Emit one structured record for each localization decision point. - - These records are intentionally verbose enough to reconstruct a - wrong-label RCA from logs alone: action target, planner metadata, - method, selected element text/role/source/bounds, candidate count, - and the final bounds that would reach execution. + Emit one structured record for each localization decision point, verbose enough to + reconstruct a wrong-label RCA from logs alone: action target, planner metadata, method, + selected element text/role/source/bounds, candidate count, and the bounds reaching execution. """ selected = self.__selected_element(result=result) diff --git a/src/fathom/core/perception/observation.py b/src/fathom/core/perception/observation.py index c29eee86..9b927e37 100644 --- a/src/fathom/core/perception/observation.py +++ b/src/fathom/core/perception/observation.py @@ -283,13 +283,11 @@ async def __emit_perception_artifact( observation: ScreenObservation, ) -> None: """ - Hand perception evidence to the artifact pipeline, but only the - artifacts whose source actually contributed elements. + Hand perception evidence to the artifact pipeline, emitting each artifact only when its + source actually contributed elements. - Saving a merged perception image when observation contains only - manifest/accessibility elements produces a second copy of the - annotated hierarchy with no additional signal. We emit the - merged artifact only when a true enrichment source contributed. + The merged image is emitted only when a true enrichment source (CV/OCR/icon/vision) + contributed; otherwise it would just duplicate the annotated hierarchy with no added signal. """ if self.__pipeline is None: @@ -516,7 +514,9 @@ def __overlaps_existing( def __element_from_token(self, *, token: OcrToken, index: int) -> PerceivedElement: """ Convert one OCR token into a perceived element. - The Document AI layout level is woven into the identifier so production traces attribute snaps to the level the merge structure came from. + + The Document AI layout level is woven into the identifier so production traces + attribute snaps to the level the merge structure came from. """ return PerceivedElement( @@ -853,9 +853,8 @@ def __overlays( """ Return at most one element-level overlay observation per screen. - Stacked qualifying elements are intentionally collapsed: the supervisor - only needs a single BLOCKING signal, and surfacing N overlays for N - layered dialogs produced duplicate downstream effects. + Stacked qualifying elements are collapsed: the supervisor needs only a single BLOCKING + signal, and surfacing one overlay per layered dialog produced duplicate downstream effects. """ screen_area = max(1, capture.width * capture.height) diff --git a/src/fathom/core/prompts/base.py b/src/fathom/core/prompts/base.py index a4eec7cd..669d3393 100644 --- a/src/fathom/core/prompts/base.py +++ b/src/fathom/core/prompts/base.py @@ -7,11 +7,15 @@ class PromptBuilder(ABC): - """Abstract base class for building model-specific system prompts.""" + """ + Model-specific prompt builder: a stable tool-scoped system prompt plus a dynamic user context. + """ @abstractmethod def build(self, *, tools: AllowedTools) -> str: - """Construct the stable system instruction string scoped to the allowed tools.""" + """ + Construct the stable system instruction string scoped to the allowed tools. + """ raise NotImplementedError @@ -22,6 +26,8 @@ def build_user_context( memory: Optional[Dict[str, str]] = None, **kwargs: Any, ) -> str: - """Construct the dynamic user context string.""" + """ + Construct the dynamic user context string. + """ raise NotImplementedError diff --git a/src/fathom/core/prompts/factory.py b/src/fathom/core/prompts/factory.py index dad2ff13..ef5d0ca1 100644 --- a/src/fathom/core/prompts/factory.py +++ b/src/fathom/core/prompts/factory.py @@ -29,7 +29,8 @@ class PromptFactory: @classmethod def get_builder(cls, model_name: str) -> PromptBuilder: """ - Returns a concrete builder instance. + Resolve the system-prompt builder for the model. Only Gemini is wired today; + gpt and claude are placeholders that fall back to the Gemini builder. """ kind = "gemini" @@ -46,7 +47,7 @@ def get_builder(cls, model_name: str) -> PromptBuilder: @staticmethod def resolve_version(model_name: str, use_xml: bool) -> str: """ - Determines the optimal prompt version based on model capabilities. + Pick the prompt variant "{tier}_{strategy}": flash or pro by model name, xml or vision by grounding. """ is_flash = "flash" in model_name.lower() @@ -59,7 +60,8 @@ def resolve_version(model_name: str, use_xml: bool) -> str: @classmethod def get_export_builder(cls, model_name: str) -> ExportPromptBuilder: """ - Returns a concrete export prompt builder instance. + Resolve the export-prompt builder for the model. Only Gemini is wired today; + gpt and claude are placeholders that fall back to the Gemini builder. """ kind = "gemini" @@ -76,7 +78,8 @@ def get_export_builder(cls, model_name: str) -> ExportPromptBuilder: @classmethod def get_decomposition_builder(cls, model_name: str) -> DecompositionPromptBuilder: """ - Returns a concrete decomposition prompt builder instance. + Resolve the decomposition-prompt builder for the model. Only Gemini is wired today; + gpt and claude are placeholders that fall back to the Gemini builder. """ kind = "gemini" diff --git a/src/fathom/core/prompts/gemini.py b/src/fathom/core/prompts/gemini.py index 60e78f24..38328a1a 100644 --- a/src/fathom/core/prompts/gemini.py +++ b/src/fathom/core/prompts/gemini.py @@ -23,7 +23,9 @@ class GeminiPromptBuilder(PromptBuilder): """ def build(self, *, tools: AllowedTools) -> str: - """Build the stable system prompt scoped to the allowed tools.""" + """ + Build the stable system prompt scoped to the allowed tools. + """ parts = [ self.__get_persona(), @@ -80,12 +82,11 @@ def build_user_context( parts = [] - # Runtime task metadata previously embedded in system prompt (kept dynamic for cache stability). + # Runtime task metadata kept in the dynamic user payload for cache stability. if runtime_brief := self.__build_runtime_brief(intent=intent, hints=hints): parts.append(runtime_brief) - # 1a. Sub-goal Progress (if sequential intent execution is active) - SINGLE FOCUS MODE - # Only pass current sub-goal, no remaining steps list + # Single-focus mode: expose only the current sub-goal, never the remaining-steps list. sub_goal_info = kwargs.get("sub_goal_info") if sub_goal_info and isinstance(sub_goal_info, dict): index = sub_goal_info.get("index") @@ -142,7 +143,6 @@ def build_user_context( f"task={(description or '')[:50]}" ) - # 1a-bis. App Launch Semantics (when package is known) if hints and hints.get("package_name") and hints.get("package_name") != "unknown": pkg = hints.get("package_name") parts.append( @@ -156,7 +156,6 @@ def build_user_context( ) logger.info(f"[H3] App Launch Semantics | package={pkg}") - # 1. Memory Ledger (Factual Memory - PERSISTENT ACROSS SCREENS) if ledger := self.__get_ledger_segment(memory=memory): parts.append( f"\n" @@ -168,13 +167,11 @@ def build_user_context( else: logger.info("[H3] No Memory Ledger | memory is empty or None") - # 2. Roadmap & Milestones (Tier 2 Context) if milestones := context.get("milestones", []): parts.append( "\n" + "\n".join(f"- {text}" for text in milestones) + "\n" ) - # 3. Execution Trace (Tier 3 Context - The Hot Suffix) trace = context.get("trace", []) current_screen_hash: Optional[str] = kwargs.get("current_screen_hash") @@ -183,10 +180,9 @@ def build_user_context( ): parts.append(f"\n{interaction_context}\n") - # 3a. Screen Change Notice — belt-and-suspenders signal when the current - # screen no longer matches the most recent trace observation. This helps - # the LLM break out of stale-context loops (e.g. "Verify Identity" screen - # persisting in the trace after the user has already dismissed it). + # Extra signal for when the current screen no longer matches the most recent trace observation; it helps + # the LLM break out of stale-context loops (e.g. a "Verify Identity" screen lingering in the trace after + # the user already dismissed it). if current_screen_hash and trace: last_obs = trace[-1].get("observation", "") if last_obs.startswith("Screen: "): @@ -201,7 +197,6 @@ def build_user_context( "" ) - # 4. User Override (real human instructions — MUST comply) if guidance := context.get("guidance", []): instructions = [f"- {item}" for item in guidance] parts.append( @@ -216,7 +211,6 @@ def build_user_context( "" ) - # 5. Verifier Feedback (VERIFY-node rejection — adjust the next action) if verifier_feedback := context.get("verifier_feedback", []): entries = [ f"- {str(item)[:MAX_VERIFIER_FEEDBACK_PROMPT_CHARS]}" for item in verifier_feedback @@ -238,7 +232,6 @@ def build_user_context( "" ) - # 5b. Completion Feedback (post-action vision refuted the sub-goal — correct the approach) if completion_feedback := context.get("completion_feedback", []): notes = [ f"- {str(item)[:MAX_VERIFIER_FEEDBACK_PROMPT_CHARS]}" @@ -253,8 +246,7 @@ def build_user_context( + "\n" ) - # 6. Interaction Cadence (Deterministic Repetition Tracking) - # Placed LAST to ensure maximum recency bias and adherence when stuck + # Placed last so the repetition-tracking alert carries maximum recency bias when the agent is stuck. if tracking_note: parts.append(f"\nCRITICAL: {tracking_note}\n") @@ -338,15 +330,12 @@ def __get_conditional_notes(self, intent: str, hints: Optional[Dict[str, Any]]) notes.append("- SEARCH FLOW: If suggestions are visible, type then tap suggestion.") notes.append("- COMPLETE CHECK: If goal appears fully achieved, verify goal explicitly.") - # notes.append( - # "- DISABLED ELEMENTS: Do NOT interact with elements marked as '[DISABLED]' in the manifest." - # ) return "NOTES:\n" + "\n".join(notes) def __get_ledger_segment(self, memory: Optional[Dict[str, str]]) -> str: """ - High-density ledger memory. + Render the memory ledger, dropping internal context keys to keep the payload compact. """ if not memory: diff --git a/src/fathom/core/prompts/qualifier.py b/src/fathom/core/prompts/qualifier.py index a6172d96..db856283 100644 --- a/src/fathom/core/prompts/qualifier.py +++ b/src/fathom/core/prompts/qualifier.py @@ -65,7 +65,7 @@ def build_system_instruction(self) -> str: " these with passive declarative's — see the NOT_EXECUTABLE\n" " bullet below for that contrast.\n" " - the same kind of command phrased politely as a question\n" - " ('Can you open Swiggy?', 'Could you scroll down?', 'Can\n" + " ('Can you open Food-delivery?', 'Could you scroll down?', 'Can\n" " you tap Continue?'). Polite question form ≠ answer-seeking.\n" "\n" "NOT_EXECUTABLE\n" @@ -90,7 +90,7 @@ def build_system_instruction(self) -> str: "QUESTION-FORM HEURISTIC (important)\n" " A question mark does NOT mean block. Read past politeness and\n" " look for an operative UI verb + object pair:\n" - " - 'Can you open Swiggy and search for Biryani?' → operative\n" + " - 'Can you open Maps and search for a cafe?' → operative\n" " verb is 'open' / 'search' → EXECUTABLE.\n" " - 'What should I do next?' → operative verb is 'should I do'\n" " (asks for an answer, not for an action) → NOT_EXECUTABLE.\n" @@ -132,7 +132,7 @@ def build_user_prompt(self, *, intent: str) -> str: "\n" "ANCHOR EXAMPLES\n" "\n" - 'Intent: "Open Swiggy and search for Biryani"\n' + 'Intent: "Open Maps and search for a cafe"\n' '{"label": "EXECUTABLE", "confidence": 0.97, ' '"rationale": {"category": "ui_task", ' '"reasoning": "App + search query both named; clear UI flow."}}\n' @@ -142,7 +142,7 @@ def build_user_prompt(self, *, intent: str) -> str: '"rationale": {"category": "ui_task", ' '"reasoning": "Recognized UI gesture meaningful on any screen."}}\n' "\n" - 'Intent: "Search for McPuff"\n' + 'Intent: "Search for headphones"\n' '{"label": "EXECUTABLE", "confidence": 0.92, ' '"rationale": {"category": "ui_task", ' '"reasoning": "Concrete search query; the agent uses whatever search field is on screen."}}\n' diff --git a/src/fathom/core/prompts/templates.py b/src/fathom/core/prompts/templates.py index 6fcb59ad..a89e31e8 100644 --- a/src/fathom/core/prompts/templates.py +++ b/src/fathom/core/prompts/templates.py @@ -192,7 +192,9 @@ def build_tool_guidance(*, tools: AllowedTools) -> str: - """Render the TOOL SELECTION + PROGRESS SAFETY + MEMORY STRATEGY block for the allowed tools.""" + """ + Render the TOOL SELECTION + PROGRESS SAFETY + MEMORY STRATEGY block for the allowed tools. + """ tool_lines = [ TOOL_DESCRIPTIONS[name] for name in _TOOL_DESCRIPTIONS_RAW if tools.contains(name=name) diff --git a/src/fathom/core/runtime/emitter.py b/src/fathom/core/runtime/emitter.py index c60ebe81..23867525 100644 --- a/src/fathom/core/runtime/emitter.py +++ b/src/fathom/core/runtime/emitter.py @@ -43,10 +43,8 @@ async def emit( """ Build a :class:`RuntimeEvent` and dispatch it to the journal. - ``correlation_id`` is the idempotency key for retried emissions: - when the caller passes a stable value, repeated calls produce the - same event identifier so the journal can deduplicate. When the - caller leaves it ``None`` a fresh uuid4 is generated. + ``correlation_id`` is the idempotency key for retried emissions: a stable value yields the + same event identifier so the journal can deduplicate; ``None`` generates a fresh uuid4. """ identifier = correlation_id if correlation_id is not None else str(uuid.uuid4()) diff --git a/src/fathom/core/safety/classifier.py b/src/fathom/core/safety/classifier.py index 493b562c..0ed04a0a 100644 --- a/src/fathom/core/safety/classifier.py +++ b/src/fathom/core/safety/classifier.py @@ -12,9 +12,8 @@ class IntentSafetyVerdict(BaseModel): """ Outcome of an intent-level safety review performed before workflow start. - ``safe`` is the executable signal; ``matched_keyword`` is populated only - when ``safe`` is ``False`` so callers can compose an actionable - operator-facing message without re-running the scan. + ``safe`` is the executable signal; ``matched_keyword`` is populated only when ``safe`` is + ``False`` so callers can compose an operator-facing message without re-running the scan. """ model_config = ConfigDict(frozen=True, extra="forbid") @@ -28,12 +27,10 @@ class IntentSafetyVerdict(BaseModel): class IntentSafetyClassifier: """ - Classifies the user's high-level intent against destructive keywords - before the LangGraph workflow starts. + Classifies the user's high-level intent against destructive keywords before the workflow starts. - Sits at the outer boundary so destructive intents never enter the - runtime path; per-step safety scanning is intentionally not consulted - during execution. + Sits at the outer boundary so destructive intents never enter the runtime path; per-step safety + scanning is not consulted during execution. """ def classify(self, *, intent: str) -> IntentSafetyVerdict: diff --git a/src/fathom/core/services/action.py b/src/fathom/core/services/action.py index 83699e2f..e7b3b522 100644 --- a/src/fathom/core/services/action.py +++ b/src/fathom/core/services/action.py @@ -484,7 +484,8 @@ async def __execute_back( ) -> PrimitiveExecution: """ Execute back action. - Adapters that cannot dispatch a system back (e.g. iOS, which has no OS-level back gesture) raise :class:`NotImplementedError` + Adapters that cannot dispatch a system back (e.g. iOS, which has no OS-level back gesture) + raise :class:`NotImplementedError`. """ try: @@ -552,7 +553,7 @@ async def __execute_tap( converter: CoordinateConverter, ) -> PrimitiveExecution: """ - Helper Method To Execute `TAP` Command + Execute a `TAP` command at the action bounds or screen center. """ if action.bounds: @@ -1064,7 +1065,7 @@ async def __execute_long_press( converter: CoordinateConverter, ) -> PrimitiveExecution: """ - Helper Method To Execute `LONG_PRESS` Command + Execute a `LONG_PRESS` command at the action bounds or screen center. """ if action.bounds: diff --git a/src/fathom/core/services/artifacts.py b/src/fathom/core/services/artifacts.py index f18f9dbf..291bbba6 100644 --- a/src/fathom/core/services/artifacts.py +++ b/src/fathom/core/services/artifacts.py @@ -17,8 +17,9 @@ class ArtifactCatalog: """ Stateless artifact discovery and classification over the shared path manager. - Both the workflow runner and the graph nodes use this to find generated files for one workflow, and to classify each one for recording into the interaction layer. - Discovery is sorted by capture time (file mtime) so the timeline reflects the order in which the host adapter wrote the files. + Both the workflow runner and the graph nodes use this to find generated files for one workflow, + and to classify each one for recording into the interaction layer. Discovery is sorted by capture + time (file mtime) so the timeline reflects the order in which the host adapter wrote the files. """ __STEP_PATTERN: Final[re.Pattern[str]] = re.compile(r"(?:^|_)step_([0-9]+)(?:_|\.)") diff --git a/src/fathom/core/services/audit.py b/src/fathom/core/services/audit.py index b21fb739..6235d8ba 100644 --- a/src/fathom/core/services/audit.py +++ b/src/fathom/core/services/audit.py @@ -12,7 +12,7 @@ class AuditService: """ - Handles logging and console visualization of agent execution. + Renders per-step execution audits, prompts, and context to a Rich console. """ def __init__(self, *, console: Optional[Any] = None) -> None: @@ -31,7 +31,6 @@ def log_context(self, manager: ContextManager) -> None: full_context = manager.get_full_context() Panel, Table, escape = self.__rich_types() - # 1. Build Roadmap Table roadmap = full_context.get("roadmap") roadmap_table = Table.grid(padding=(0, 1)) roadmap_table.add_column(style="bold blue") @@ -40,7 +39,6 @@ def log_context(self, manager: ContextManager) -> None: intent = getattr(roadmap, "intent", "Unknown") roadmap_table.add_row("Intent:", escape(str(intent))) - # 2. Build Guidance Block if guidance := manager.get_user_guidance(): guidance_panel = Table.grid(padding=(0, 1)) for instruction in guidance: @@ -58,7 +56,6 @@ def log_context(self, manager: ContextManager) -> None: ) ) - # 3. Build Milestones/Trace summary summary = Table.grid(padding=(0, 1)) summary.add_column(style="dim") summary.add_column() @@ -150,7 +147,6 @@ def log_step( if is_stuck: audit_grid.add_row("[bold red]STUCK:[/bold red]", "YES") - # Duration metrics audit_grid.add_row("Grounding:", self.__format_ms(seconds=grounding_duration)) if hierarchy_duration > 0: @@ -162,7 +158,6 @@ def log_step( "LLM Analysis:", self.__format_ms(seconds=plan.metrics["llm_analysis"]) ) - # Token usage prompt_t = int(plan.metrics.get("prompt_tokens", 0)) completion_t = int(plan.metrics.get("completion_tokens", 0)) @@ -170,7 +165,6 @@ def log_step( token_info = f"{prompt_t + completion_t:,} (P:{prompt_t:,} | C:{completion_t:,})" audit_grid.add_row("Tokens:", f"[dim]{token_info}[/dim]") - # Add confidence score if plan.step and plan.step.action: confidence_pct = plan.step.action.confidence * 100 confidence_color = ( @@ -200,12 +194,10 @@ def log_step( ) ) - # Reasoning Output action_info = Table.grid(padding=(0, 2)) action_info.add_column(style="bold yellow") action_info.add_column() - # Use NLP description for the action action_info.add_row("Action:", escape(str(result.action_description or result.action_type))) action_info.add_row("Target:", escape(str(result.natural_language_target or result.target))) @@ -218,7 +210,7 @@ def log_step( def __format_ms(self, seconds: float = 0, milliseconds: float = 0) -> str: """ - Format time elegantly. + Format a duration as seconds with a bracketed millisecond value. """ total_ms = (seconds * 1000) + milliseconds diff --git a/src/fathom/core/services/comparator.py b/src/fathom/core/services/comparator.py index a86f32b0..0611d0eb 100644 --- a/src/fathom/core/services/comparator.py +++ b/src/fathom/core/services/comparator.py @@ -82,9 +82,8 @@ def compare( scroll_start = time.time() scroll: Optional[ScreenScrollTranslation] if self.__frames_effectively_identical(ssim_score=ssim_score, pixel_diff=pixel_diff): - # Phase correlation on near-identical frames returns small - # DC-noise shifts (~0.5 px). Short-circuit to zero translation - # so no-op actions do not produce bogus scroll evidence. + # Phase correlation on near-identical frames returns small DC-noise shifts (~0.5 px). + # Short-circuit to zero translation so no-op actions do not produce bogus scroll evidence. scroll = ScreenScrollTranslation(dx=0.0, dy=0.0) else: scroll = self.__compute_scroll_translation(after=after.image, before=before.image) @@ -403,12 +402,11 @@ def __frames_effectively_identical( pixel_diff: Optional[float], ) -> bool: """ - Whether two captures are so similar that a non-zero scroll - translation can only be DC-noise from phase correlation. + Whether two captures are so similar that a non-zero scroll translation can only be DC-noise + from phase correlation. - Returns ``False`` when either signal is unavailable — without - both, we cannot prove identity, so the scroll computation must - run as the unbiased fallback. + Returns ``False`` when either signal is unavailable — without both, we cannot prove identity, + so the scroll computation must run as the unbiased fallback. """ if ssim_score is None or pixel_diff is None: diff --git a/src/fathom/core/services/conversation/service.py b/src/fathom/core/services/conversation/service.py index e056fc1b..da6656d5 100644 --- a/src/fathom/core/services/conversation/service.py +++ b/src/fathom/core/services/conversation/service.py @@ -52,7 +52,9 @@ def __init__( ) -> None: """ Initialize the service with explicit durable ledger ports and a signer. - Hosts that deploy without object storage construct NoopSigner at the composition root and pass it here; the service no longer carries an adapter default. + + Hosts that deploy without object storage construct a NoopSigner at the composition root + and pass it here; the signer is a required port with no adapter default. """ self.__ports = ports @@ -249,13 +251,10 @@ def __classified_content( labels: Tuple[Label, ...], ) -> InteractionSchemas.Content: """ - Build message content with classifier labels + sanitizer stamping. + Build message content with classifier labels and sanitizer stamping. - Every persisted message is run through the sanitizer pipeline so the - `sanitized_at` / `sanitizer` columns are always populated. The default - sanitizer profile is a no-op (`noop@1`) that returns the body verbatim - but records that the pipeline ran; swapping in a PII-redacting profile - flows through every write path without touching call sites. + Every message runs through the sanitizer so ``sanitized_at`` / ``sanitizer`` are always + populated; the default ``noop@1`` profile returns the body verbatim while recording the run. """ classified = self.__classifier.classify(body=body, existing=labels) @@ -1019,8 +1018,8 @@ async def __signed_timeline_entry( entry: ConversationSchemas.EntryView, ) -> ConversationSchemas.EntryView: """ - Sign URIs embedded inside artifact-kind timeline entry payloads - and annotate the payload with typed status fields. Non-artifact entries pass through untouched. + Sign URIs embedded inside artifact-kind timeline entry payloads and annotate the payload + with typed status fields; non-artifact entries pass through untouched. """ if entry.kind != EntryKind.ARTIFACT or not isinstance(entry.payload, dict): diff --git a/src/fathom/core/services/decomposer.py b/src/fathom/core/services/decomposer.py index 2e3849af..b48ca6ce 100644 --- a/src/fathom/core/services/decomposer.py +++ b/src/fathom/core/services/decomposer.py @@ -1,5 +1,3 @@ -"""Intent decomposition service for sequential sub-goal execution.""" - from __future__ import annotations from typing import List, Optional, Sequence, Tuple @@ -19,8 +17,8 @@ class DecompositionAugmentation: """ - Optional caller-supplied hooks that enrich a decomposition prompt with - extra context. All hooks default to empty so subclasses override only what they need. + Optional caller-supplied hooks that enrich a decomposition prompt with extra context. All hooks + default to empty so subclasses override only what they need. """ def system_addendum(self) -> str: diff --git a/src/fathom/core/services/generation/normalizer.py b/src/fathom/core/services/generation/normalizer.py index 5c54cc75..6f4e920a 100644 --- a/src/fathom/core/services/generation/normalizer.py +++ b/src/fathom/core/services/generation/normalizer.py @@ -99,7 +99,7 @@ def __transition(self, *, target: str, steps: List[int]) -> NormalizedEntry: def __package(self, *, activity: Optional[str]) -> Optional[str]: """ - Extract the package base from an 'package/Activity' string, or None when absent. + Extract the package base from a 'package/Activity' string, or None when absent. """ if not activity: diff --git a/src/fathom/core/services/hierarchy.py b/src/fathom/core/services/hierarchy.py index d332928f..1630a03b 100644 --- a/src/fathom/core/services/hierarchy.py +++ b/src/fathom/core/services/hierarchy.py @@ -34,7 +34,7 @@ class HierarchyService: """ - Service responsible for UI hierarchy analysis. Optimized for high-speed grounding. + Parses UI-hierarchy XML into labeled interactive elements and annotated captures for grounding. """ def __init__( @@ -186,7 +186,7 @@ async def process_xml_and_screen( def __save_file(self, *, path: Path, data: bytes, mode: str = "wb") -> None: """ - Helper to save file. + Write bytes to the given path using the requested file mode. """ with path.open(mode) as handle: diff --git a/src/fathom/core/services/history.py b/src/fathom/core/services/history.py index 7657a843..76b05575 100644 --- a/src/fathom/core/services/history.py +++ b/src/fathom/core/services/history.py @@ -44,7 +44,7 @@ class HistoryService: """ - Service responsible for persisting execution history and generating scripts. + Persists execution history and generates automation scripts. All outputs are saved to assets/history/{date}/{package}/{session}/ directory. """ @@ -957,11 +957,8 @@ async def __emit_script_artifact( review_reason: Optional[str] = None, ) -> None: """ - Hand the generated automation script to the artifact pipeline. - - Replaces the legacy ``__storage.save(category="history", ...)`` - direct upload — the pipeline owns durable EFS staging, async - cloud upload, and replay-on-crash for every artifact kind. + Hand the generated automation script to the artifact pipeline, which owns durable staging, + async cloud upload, and replay-on-crash for every artifact kind. """ if self.__pipeline is None: diff --git a/src/fathom/core/services/hitl.py b/src/fathom/core/services/hitl.py index 16b323d5..8d13e739 100644 --- a/src/fathom/core/services/hitl.py +++ b/src/fathom/core/services/hitl.py @@ -98,7 +98,7 @@ async def get_injected_context(self, *, step: int) -> Optional[str]: """ context = await self.__signal.get_injected_context() - logger.info(f"Injected context for step number: {step} is {context}") + logger.info(f"Injected context for step number: {step}") if context: await self.__telemetry.info( @@ -141,7 +141,7 @@ async def ask(self, *, prompt: str, step: int) -> str: ) response = await self.__signal.ask(prompt=prompt) - logger.info(f"Received HITL response: {response} from user") + logger.info("Received HITL response from user") await self.__telemetry.info( message="Got it — continuing.", diff --git a/src/fathom/core/services/manifest.py b/src/fathom/core/services/manifest.py index c475ca96..24533c56 100644 --- a/src/fathom/core/services/manifest.py +++ b/src/fathom/core/services/manifest.py @@ -78,18 +78,13 @@ def merge( observation: ScreenObservation, ) -> ManifestMergeResult: """ - Return a :class:`ManifestMergeResult` with the enriched label - map and the list of newly appended perception entries. - - The input ``label_map`` is not mutated. When no perception - elements qualify (empty observation, no text, or all overlap - the XML manifest), the result carries a shallow copy of the - input and an empty ``appended`` tuple. - - Returning the appended entries explicitly lets the overlay - renderer draw matching boxes onto the LLM-facing annotated - image without diffing pre/post maps or re-parsing the - ``[x1,y1][x2,y2]`` bounds string. + Return a :class:`ManifestMergeResult` with the enriched label map and the newly appended + perception entries. + + The input ``label_map`` is not mutated; when no perception element qualifies (empty + observation, no text, or all overlap the XML manifest), the result carries a shallow copy + and an empty ``appended`` tuple. The appended entries are returned explicitly so the overlay + renderer draws boxes without diffing maps or re-parsing the ``[x1,y1][x2,y2]`` bounds string. """ enriched: Dict[str, Any] = dict(label_map) diff --git a/src/fathom/core/services/normalizer.py b/src/fathom/core/services/normalizer.py index 34599430..21b4dd7d 100644 --- a/src/fathom/core/services/normalizer.py +++ b/src/fathom/core/services/normalizer.py @@ -6,7 +6,7 @@ class Normalizer: """ - Service for normalizing and cleaning natural language text. + Normalizes freeform text and builds canonical action/validation descriptions with stable grammar. """ __MULTISPACE_RE = re.compile(pattern=r"\s+") @@ -14,7 +14,9 @@ class Normalizer: @staticmethod def clean(text: Optional[str]) -> str: - """Normalize whitespace and trim text.""" + """ + Normalize whitespace and trim text. + """ if not text: return "" @@ -39,7 +41,9 @@ def is_generic_target_name(name: Optional[str]) -> bool: @staticmethod def sentence(text: Optional[str]) -> str: - """Apply lightweight sentence-case normalization.""" + """ + Apply lightweight sentence-case normalization. + """ cleaned = Normalizer.clean(text=text) if not cleaned: @@ -51,7 +55,9 @@ def sentence(text: Optional[str]) -> str: @staticmethod def reasoning(text: Optional[str]) -> str: - """Normalize freeform reasoning/evidence text without changing semantics.""" + """ + Normalize freeform reasoning/evidence text without changing semantics. + """ return Normalizer.sentence(text=text) @@ -63,7 +69,9 @@ def action( wait_duration: Optional[int | float] = None, validation_subject: Optional[str] = None, ) -> str: - """Build canonical action descriptions with stable grammar.""" + """ + Build canonical action descriptions with stable grammar. + """ kind = Normalizer.clean(text=action_type).lower() cleaned_target = Normalizer.clean(text=target) @@ -122,7 +130,9 @@ def action( @staticmethod def validation(target: str, *, explicit: bool = False, complete: bool = False) -> str: - """Build explicit validation descriptions.""" + """ + Build explicit validation descriptions. + """ cleaned_target = Normalizer.clean(text=target) or "Goal State" diff --git a/src/fathom/core/services/parsing.py b/src/fathom/core/services/parsing.py index 96657d25..26466330 100644 --- a/src/fathom/core/services/parsing.py +++ b/src/fathom/core/services/parsing.py @@ -106,7 +106,6 @@ def parse(self, response: GenerateResult) -> AnalysisResult: if not primary_call: primary_call = non_command_calls.pop(0) if non_command_calls else function_calls[0] - # Parse primary tool call result = self.__dispatch_parse(name=primary_call.name, arguments=primary_call.args) result.metadata["tool_name"] = primary_call.name result.metadata["tool_args"] = self.__metadata_args( @@ -555,7 +554,7 @@ def __parse_delta_telemetry(self, args: ExecuteUIArgs) -> Optional[DeltaSignal]: normalized_confidence = None confidence_source = None - # For now, we treat delta_observed as already boolean-normalized by the schema. + # delta_observed is already boolean-normalized by the schema. normalized_observed: Optional[bool] = raw_observed return DeltaSignal( diff --git a/src/fathom/core/services/perception.py b/src/fathom/core/services/perception.py index 854cd1c2..53cf4f5c 100644 --- a/src/fathom/core/services/perception.py +++ b/src/fathom/core/services/perception.py @@ -87,7 +87,7 @@ async def __emit_screenshot_artifact( step_number: int, ) -> Optional[Path]: """ - Stage the screen capture through the artifact pipeline and return the EFS-staged path. + Stage the screen capture through the artifact pipeline and return the locally staged path. Caller stamps the path onto ``capture.screenshot_uri`` so downstream consumers read bytes from local disk. """ @@ -129,12 +129,9 @@ async def __fallback_persist_capture( """ Persist via :class:`StoragePort` when no artifact pipeline is wired. - Production runs always have the pipeline configured; this branch - exists so unit tests and minimal embeddings that omit the - pipeline still produce a usable storage identifier. The remote - identifier returned by :class:`StoragePort` is a stable handle - and is stamped onto ``screenshot_uri`` (a typed field) so - downstream consumers do not need to peek into ``metadata``. + Serves tests and minimal embeddings that omit the pipeline; the stable identifier from + :class:`StoragePort` is stamped onto the typed ``screenshot_uri`` field so downstream + consumers need not peek into ``metadata``. """ storage_id = await self.__storage.save( diff --git a/src/fathom/core/services/projector.py b/src/fathom/core/services/projector.py index 59b48fb3..b455d439 100644 --- a/src/fathom/core/services/projector.py +++ b/src/fathom/core/services/projector.py @@ -74,8 +74,8 @@ async def __paginated_messages(self, *, job: Job) -> AsyncIterator[Message]: """ Walk every page of task messages so long tasks are projected fully. - The previous implementation read only the first page and silently - truncated long task histories. We loop until the underlying cursor is exhausted. + Loops until the underlying cursor is exhausted; reading only the first page would silently + truncate long task histories. """ cursor: str | None = None diff --git a/src/fathom/core/services/qualifier/gate.py b/src/fathom/core/services/qualifier/gate.py index 3ad7445b..17bf9919 100644 --- a/src/fathom/core/services/qualifier/gate.py +++ b/src/fathom/core/services/qualifier/gate.py @@ -17,9 +17,8 @@ def __init__(self, *, configuration: QualifierConfiguration) -> None: """ Accept the qualifier configuration for symmetry with caller wiring. - The configuration is intentionally unused at decision time — the gate - has no threshold. Kept as a constructor parameter so callers don't - have to special-case construction when they already hold a config. + Unused at decision time — the gate has no threshold; kept as a parameter so callers holding a + config need not special-case construction. """ _ = configuration diff --git a/src/fathom/core/services/qualifier/llm.py b/src/fathom/core/services/qualifier/llm.py index 7d4634d2..d63c5cfc 100644 --- a/src/fathom/core/services/qualifier/llm.py +++ b/src/fathom/core/services/qualifier/llm.py @@ -47,8 +47,9 @@ async def qualify(self, *, intent: str) -> QualificationVerdict: """ Classify the intent's executability and return a verdict. - Fail-open semantics: any LLM, parse, or schema failure yields an EXECUTABLE verdict tagged with QUALIFIER_ERROR - so the gate explicitly passes the run through; the qualifier can never cause a false rejection. + Fail-open semantics: any LLM, parse, or schema failure yields an EXECUTABLE verdict tagged + with QUALIFIER_ERROR so the gate explicitly passes the run through; the qualifier can never + cause a false rejection. """ normalized = intent.strip() if intent else "" diff --git a/src/fathom/core/services/recorder.py b/src/fathom/core/services/recorder.py index 288c5c9e..959449c6 100644 --- a/src/fathom/core/services/recorder.py +++ b/src/fathom/core/services/recorder.py @@ -90,12 +90,9 @@ class RecorderHealth: """ - Tracks recorder activity so the first durable-write failure suppresses - subsequent writes for the lifetime of the run. - - The recorder is best-effort by design: a broken interaction port should - never crash a Fathom run. After the first InteractionError, the recorder - no-ops and emits one error event so the host can surface the outage. + Track recorder activity so the first durable-write failure suppresses subsequent writes for the + run; after the first InteractionError the recorder no-ops and emits one error event so the host + can surface the outage. """ def __init__(self) -> None: @@ -116,7 +113,8 @@ def is_active(self) -> bool: def record_failure(self) -> bool: """ Mark a failure. - Return True for the first failure (caller emits one error event); False for subsequent failures (silent suppression). + Return True for the first failure (caller emits one error event); + False for subsequent failures (silent suppression). """ first = self.__active @@ -145,8 +143,9 @@ def failure_count(self) -> int: class ConversationRecorder: """ - Host-neutral recorder that translates runtime facts into conversation - use cases. Every durable write is paired with a structured telemetry event so live clients can render activity without polling. + Host-neutral recorder that translates runtime facts into conversation use cases. Every durable + write is paired with a structured telemetry event so live clients can render activity without + polling. """ def __init__( @@ -359,12 +358,11 @@ async def __guard( envelope_for: Callable[[T], TelemetryEnvelope], ) -> Optional[T]: """ - Run a recorder operation, suppressing further writes after the first - durable-write failure and emitting one structured telemetry event per successful write. + Run a recorder operation, suppressing further writes after the first durable-write failure and + emitting one structured telemetry event per successful write. - The recorder is best-effort: a broken interaction port (locked DB, filesystem error, integrity violation, network blip on a remote adapter) - must never crash a Fathom run. We catch every Exception from the interaction port. InteractionError preserves the typed message; - any other exception is wrapped into a generic disabled notice so the host can alert without losing the run. + Best-effort: every Exception from the interaction port is caught so a broken port never crashes + a run; InteractionError keeps its typed message, any other error becomes a generic disabled notice. """ if not self.__health.is_active(): @@ -692,12 +690,9 @@ async def __ensure_requester(self, *, run: Run, members: Members) -> None: """ Create or join the requesting actor for the run thread. - Two concurrent runs starting in the same conversation can race on - thread creation: both observe "no thread", both call create_thread, - and the second collides on the threads PRIMARY KEY. We catch only - the typed ThreadConflictError (one specific case from create_thread) - and fall through to the existing-thread path. Any other failure - from get_thread or create_thread propagates so the recorder's failure-suppression layer can disable cleanly. + Two concurrent runs can race on thread creation and collide on the threads PRIMARY KEY; only + the typed ThreadConflictError is caught, falling through to the existing-thread path, while any + other failure propagates so the failure-suppression layer can disable cleanly. """ thread_existed = await self.__thread_exists(run=run) @@ -815,7 +810,8 @@ def __title_context(*, run: Run) -> TitleContext: async def __thread_exists(self, *, run: Run) -> bool: """ Probe whether the run's thread already exists. Returns False on the - typed ThreadNotFoundError; any other failure propagates so the recorder's failure-suppression layer can disable cleanly. + typed ThreadNotFoundError; any other failure propagates so the recorder's + failure-suppression layer can disable cleanly. """ return await self.__conversation.internal_exists( diff --git a/src/fathom/core/services/resolution.py b/src/fathom/core/services/resolution.py index b495f5d7..83ca804a 100644 --- a/src/fathom/core/services/resolution.py +++ b/src/fathom/core/services/resolution.py @@ -43,7 +43,8 @@ def __init__( self.__ref_pattern: Pattern[str] = re.compile(r"\$(memory|env)\.([a-zA-Z0-9_]+)") # Regex to parse bounds string: [x1,y1][x2,y2]. Accepts negative coordinates (off-viewport scroll containers etc.) - # The clamp step in :meth:`__snap_to_label` is responsible for bringing them back into the viewport before they reach an executor. + # The clamp step in :meth:`__snap_to_label` is responsible for bringing them back into the viewport + # before they reach an executor. self.__bounds_pattern: Pattern[str] = re.compile( r"^\[(-?\d+),(-?\d+)\]\[(-?\d+),(-?\d+)\]$" ) @@ -688,7 +689,6 @@ async def __resolve_string(self, text: str) -> str: if not text or "$" not in text: return text - # Find all matches matches = self.__ref_pattern.findall(text) if not matches: return text @@ -698,10 +698,9 @@ async def __resolve_string(self, text: str) -> str: for source, key in matches: value = await self.__fetch_value(source=source, key=key) if value: - # Replace strict match $source.key token = f"${source}.{key}" resolved_text = resolved_text.replace(token, str(value)) - logger.info(f"Resolved reference '{token}' to '{value}'") + logger.info(f"Resolved reference '{token}'") else: logger.warning(f"Could not resolve reference: ${source}.{key}") diff --git a/src/fathom/core/services/telemetry/announcer.py b/src/fathom/core/services/telemetry/announcer.py index 398da310..99ca18f2 100644 --- a/src/fathom/core/services/telemetry/announcer.py +++ b/src/fathom/core/services/telemetry/announcer.py @@ -29,8 +29,8 @@ def __init__(self, *, kind: PhaseKind, intent: str) -> None: class PhaseAnnouncer: """ - Emits client-facing phase events through the telemetry port and keeps a - single background heartbeat alive while the most recently announced phase is still in flight. + Emits client-facing phase events through the telemetry port and keeps a single background + heartbeat alive while the most recently announced phase is still in flight. """ def __init__(self, *, message: PhaseMessage, telemetry: TelemetryPort) -> None: @@ -229,8 +229,8 @@ async def __close_locked(self) -> None: async def __heartbeat(self, *, kind: PhaseKind, intent: str) -> None: """ - Emit the heartbeat message at the configured cadence, bounded by the - configured beat limit; cancellation stops the loop immediately. + Emit the heartbeat message at the configured cadence, bounded by the configured beat limit; + cancellation stops the loop immediately. """ budget = self.__message.heartbeat diff --git a/src/fathom/core/services/vision.py b/src/fathom/core/services/vision.py index d76a1db4..c13f315e 100644 --- a/src/fathom/core/services/vision.py +++ b/src/fathom/core/services/vision.py @@ -65,7 +65,9 @@ def __init__( session_id: str = "", auditor: Optional[AuditService] = None, ) -> None: - """Initialize vision service with the live runtime capabilities.""" + """ + Initialize vision service with the live runtime capabilities. + """ self.__llm = llm self.__memory = memory @@ -134,15 +136,14 @@ async def analyze( prior_rejection_history: Optional[List[ConversationTurn]] = None, ) -> AnalysisResult: """ - Coordinates the analysis flow mirroring GeminiVisionTool strictly. + Run one planner turn: assemble the ANALYZE prompt from memory and context, generate with + multi-turn schema-repair, and parse the tool call into an AnalysisResult. """ analyze_start = time.time() - # Note: Screenshot persistence is now handled upstream by PerceptionService. - # No background persistence needed here. + # Screenshot persistence is handled upstream by PerceptionService; none is needed here. - # 1. BRAIN RETRIEVAL fingerprint = self.__resolve_capture_fingerprint(capture=capture, visual_hash=visual_hash) prompt_image = self.__resolve_prompt_image(capture=capture) @@ -160,7 +161,6 @@ async def analyze( if not key.startswith(("context:", "ctx_v3:", "ctx_")) } - # Log filtered entries for debugging filtered_count = len(all_memory_raw) - len(all_memory) if filtered_count > 0: filtered_keys = [key for key in all_memory_raw if key not in all_memory] @@ -172,7 +172,6 @@ async def analyze( retrieval = time.time() - start - # Log memory stats memory_store = knowledge.get("memory_store", {}) prev_actions = knowledge.get("previous_actions", []) @@ -186,7 +185,6 @@ async def analyze( f"duration={retrieval:.3f}s" ) - # 2. PROMPT & TOOL SCOPING # Dynamic context from ContextManager (GCC-Inspired) full_context = context_manager.get_full_context() guidance = full_context.get("guidance") @@ -284,7 +282,6 @@ async def analyze( allowed_tools = ToolRegistry.definitions(names=tools.names) tool_scope_duration = time.time() - tool_scope_start - # 3. CONTENT ASSEMBLY manifest_start = time.time() manifest = self.__format_elements(elements=elements) manifest_duration = time.time() - manifest_start @@ -301,7 +298,6 @@ async def analyze( ) payload_duration = time.time() - payload_start - # Log assembly performance logger.info( f"[VISION] Assembly | Manifest: {manifest_duration:.3f}s | Payload: {payload_duration:.3f}s" ) @@ -314,11 +310,8 @@ async def analyze( payload=self.__sanitize_recursive(data=payload), ) - # Log prompt context for console visibility self.__auditor.log_prompt(payload=payload, instruction=instruction) - # 4. EXECUTION WITH MULTI-TURN FEEDBACK LOOP - # # Instead of appending error text to a flat prompt (stateless retry), we use # Gemini's native multi-turn conversation: on rejection, the model sees its own # rejected tool call as a prior model turn, followed by a user turn explaining @@ -348,14 +341,12 @@ async def analyze( ) duration = time.time() - commence - # Log Raw LLM output raw_text = response.content[:200].replace("\n", " ") if response.content else "No text" logger.info( f"[VISION] LLM Response | Duration: {duration:.3f}s | " f"Model: {self.__llm.model_name} | Raw: {raw_text}..." ) - # 5. PARSE & ENRICH parse_start = time.time() try: analysis = self.__parser.parse(response) @@ -416,7 +407,6 @@ async def analyze( if analysis is None or response is None: raise VisionError("Vision analysis did not produce a valid result.", retryable=False) - # Update metrics & metadata if response.metrics: analysis.metrics.update(response.metrics) @@ -446,7 +436,6 @@ async def analyze( analysis.metrics["llm_analysis_ms"] = duration * 1000 analysis.metrics["memory_retrieval_ms"] = retrieval * 1000 - # 6. BRAIN UPDATE (Store observation) await self.__memory.store_observation( screen=ScreenState( activity=capture.activity, @@ -511,12 +500,11 @@ def build_rejection_history_from_analysis( rejection_reason: str, ) -> List[ConversationTurn]: """ - Build multi-turn rejection history from an AnalysisResult for cross-iteration - feedback. The planner calls this when rejecting a repeated action so the next - vision.analyze() cycle can pass it as conversation_history. + Build multi-turn rejection history from an AnalysisResult for cross-iteration feedback. - Returns provider-neutral ConversationTurn objects representing the model's - rejected tool call and the rejection reason. + The planner calls this when rejecting a repeated action so the next ``vision.analyze()`` + cycle can pass it as ``conversation_history``; returns the model's rejected tool call and + the rejection reason as provider-neutral ConversationTurns. """ # Model turn: reconstruct the rejected tool call @@ -550,13 +538,8 @@ def __build_rejection_history( """ Build a multi-turn conversation history from a rejected LLM response. - Returns a list of ConversationTurn objects representing: - 1. Original user turn (prompt + image) - 2. Model's rejected response (its own tool call) - 3. (The next user turn with correction will be sent as the current prompt) - - This gives the LLM full visibility into what it proposed and why it was wrong, - enabling genuine self-correction rather than stateless retry. + Returns two ConversationTurns: the original user turn (prompt + image) and the model's + rejected tool call; the correction is sent separately as the next user prompt. """ # Turn 1: Original user prompt @@ -642,7 +625,7 @@ def __build_payload( failures: Optional[List[str]] = None, ) -> List[Any]: """ - Assembles request with token-locality (strictly mirrored). + Assemble the ordered prompt parts, placing the screenshot last for KV-cache locality. """ payload: List[Any] = [] @@ -683,14 +666,10 @@ def __build_payload( def __render_loop_observation(self, *, observation: LoopObservation) -> str: """ - Render a :class:`LoopObservation` as a structured block in the - ANALYZE prompt. + Render a :class:`LoopObservation` as a structured block in the ANALYZE prompt. - The block is deliberately framed as an observation, not as an - instruction. The agent reads it, may consult it when choosing - the next action, and is free to disagree if it has reason. The - runtime enforces nothing here; loop-breaking remains a planner - concern, not a prompt contract. + The block is framed as an observation, not an instruction: the runtime enforces nothing + and loop-breaking stays a planner decision. """ progress = ( @@ -771,15 +750,13 @@ def __render_screen_observation(self, *, observation: ScreenObservation) -> str: def __format_elements(self, elements: Optional[Dict[str, Any]]) -> str: """ - Convert the drawer label map into a grounding manifest the - planner can bind ``label_id`` references against. + Convert the drawer label map into a grounding manifest the planner can bind ``label_id`` + references against. - Reads attribute keys from both platform vocabularies — Android - (``class``, ``text``, ``content-desc``) and iOS / XCUITest - (``type``, ``name``, ``label``, ``value``) — so an element - coming out of :class:`IOSParser` (which keeps its raw XML - attribute names) renders with its real semantic label instead - of an anonymous ``View``. + Reads both platform vocabularies — Android (``class``, ``text``, ``content-desc``) and + iOS / XCUITest (``type``, ``name``, ``label``, ``value``) — so an :class:`IOSParser` element, + which keeps its raw XML attribute names, renders with its real semantic label instead of an + anonymous ``View``. """ logger.info(f"Converting {len(elements) if elements else 0} elements into manifest") diff --git a/src/fathom/infrastructure/interaction/orm/repositories/actors.py b/src/fathom/infrastructure/interaction/orm/repositories/actors.py index 2472e79c..99a5cdcd 100644 --- a/src/fathom/infrastructure/interaction/orm/repositories/actors.py +++ b/src/fathom/infrastructure/interaction/orm/repositories/actors.py @@ -19,7 +19,7 @@ class ActorRepository: """ - persistent-store backed repository for actor identities. + Persistent-store backed repository for actor identities. """ def __init__(self, *, transaction: "TransactionScope") -> None: diff --git a/src/fathom/infrastructure/interaction/orm/repositories/lifecycle.py b/src/fathom/infrastructure/interaction/orm/repositories/lifecycle.py index 31f23a43..4902f44e 100644 --- a/src/fathom/infrastructure/interaction/orm/repositories/lifecycle.py +++ b/src/fathom/infrastructure/interaction/orm/repositories/lifecycle.py @@ -69,7 +69,7 @@ def next(self) -> str: class RawConnectionAdapter: """ - Adapts an store connection client to the raw SQL executor protocol. + Adapts a store connection client to the raw SQL executor protocol. """ def __init__(self, *, connection: DatabaseConnection) -> None: diff --git a/src/fathom/infrastructure/interaction/orm/repositories/memberships.py b/src/fathom/infrastructure/interaction/orm/repositories/memberships.py index 08e9b7c7..6997106f 100644 --- a/src/fathom/infrastructure/interaction/orm/repositories/memberships.py +++ b/src/fathom/infrastructure/interaction/orm/repositories/memberships.py @@ -30,7 +30,7 @@ class MembershipRepository: """ - persistent-store backed repository for actor membership in conversation threads. + Persistent-store backed repository for actor membership in conversation threads. """ def __init__(self, *, lifecycle: LifecycleRecorder, transaction: TransactionScope) -> None: diff --git a/src/fathom/infrastructure/interaction/orm/repositories/messages.py b/src/fathom/infrastructure/interaction/orm/repositories/messages.py index e5e50e96..51688841 100644 --- a/src/fathom/infrastructure/interaction/orm/repositories/messages.py +++ b/src/fathom/infrastructure/interaction/orm/repositories/messages.py @@ -53,7 +53,7 @@ class MessageRepository: """ - persistent-store backed repository for durable conversation messages. + Persistent-store backed repository for durable conversation messages. """ def __init__( diff --git a/src/fathom/infrastructure/interaction/orm/repositories/tasks.py b/src/fathom/infrastructure/interaction/orm/repositories/tasks.py index 260fc660..9296f42c 100644 --- a/src/fathom/infrastructure/interaction/orm/repositories/tasks.py +++ b/src/fathom/infrastructure/interaction/orm/repositories/tasks.py @@ -42,7 +42,7 @@ class TaskRepository: """ - persistent-store backed repository for durable conversation tasks. + Persistent-store backed repository for durable conversation tasks. """ __FINISH_EVENT_KINDS: Dict[TaskState, EventKind] = { @@ -336,7 +336,8 @@ async def get_task(self, *, query: TaskOneQuery) -> Optional[Task]: async def recent_task(self, *, query: TaskQuery) -> Optional[Task]: """ - Load the most-recently-created task in the thread using a bounded single-row query, honoring the caller's deletion filter. + Load the most-recently-created task in the thread using a bounded single-row query, + honoring the caller's deletion filter. """ row = ( diff --git a/src/fathom/infrastructure/interaction/orm/repositories/threads.py b/src/fathom/infrastructure/interaction/orm/repositories/threads.py index 79b531d3..f56a847c 100644 --- a/src/fathom/infrastructure/interaction/orm/repositories/threads.py +++ b/src/fathom/infrastructure/interaction/orm/repositories/threads.py @@ -52,7 +52,7 @@ class ThreadRepository: """ - persistent-store backed repository for durable conversation threads. + Persistent-store backed repository for durable conversation threads. """ def __init__(self, *, lifecycle: LifecycleRecorder, transaction: TransactionScope) -> None: diff --git a/src/fathom/infrastructure/memory/ledger.py b/src/fathom/infrastructure/memory/ledger.py index 4127327d..9408d942 100644 --- a/src/fathom/infrastructure/memory/ledger.py +++ b/src/fathom/infrastructure/memory/ledger.py @@ -14,13 +14,12 @@ class Ledger(ILedger): """ - Persistent Key-Value storage using SQLite. - Separated from the core Knowledge Graph logic. + Persistent key-value storage backed by SQLite. """ def __init__(self, database_path: Path) -> None: """ - Initialize ledger with explicit database path. + Store the database path and create its parent directory if missing. """ self.__initialized = False @@ -29,7 +28,7 @@ def __init__(self, database_path: Path) -> None: async def __initialize(self) -> None: """ - Initializes the ledger table. + Create the ledger table if it does not exist. """ if self.__initialized: @@ -45,12 +44,7 @@ async def __initialize(self) -> None: async def set(self, key: str, value: str) -> None: """ - Stores a ledger entry. - - NOTE: System state keys are REJECTED to prevent memory pollution. - - Ledger is reserved for user-actionable memory only. - System state (GCC context, internal state) should use separate storage. + Store a user-actionable ledger entry; system-state key prefixes are rejected. """ if not key or not isinstance(key, str): @@ -61,7 +55,6 @@ async def set(self, key: str, value: str) -> None: logger.error(f"[LEDGER] Invalid value type for key={key}: {type(value)}") raise ValueError(f"Value must be a string, got: {type(value)}") - # DEFENSIVE: Reject system state keys to prevent pollution SYSTEM_KEY_PREFIXES = ("context:", "ctx_v3:", "ctx_") if key.startswith(SYSTEM_KEY_PREFIXES): logger.warning( @@ -92,7 +85,7 @@ async def set(self, key: str, value: str) -> None: async def get(self, key: str) -> Optional[str]: """ - Retrieves a value by key. + Retrieve a value by key. """ await self.__initialize() @@ -109,7 +102,7 @@ async def get(self, key: str) -> Optional[str]: async def get_all(self) -> Dict[str, str]: """ - Retrieves all ledger entries. + Retrieve all ledger entries. """ await self.__initialize() @@ -127,25 +120,22 @@ async def get_all(self) -> Dict[str, str]: async def health_check(self) -> Dict[str, Any]: """ - Performs a health check on the ledger. Returns diagnostic information. + Run a health check and return diagnostic information. """ await self.__initialize() try: async with aiosqlite.connect(self.__path) as db: - # Check table exists async with db.execute( "SELECT name FROM sqlite_master WHERE type='table' AND name='entries'" ) as cursor: table_exists = await cursor.fetchone() is not None - # Count entries async with db.execute("SELECT COUNT(*) FROM entries") as cursor: row = await cursor.fetchone() entry_count = row[0] if row else 0 - # Get oldest and newest timestamps async with db.execute( "SELECT MIN(updated_at), MAX(updated_at) FROM entries" ) as cursor: diff --git a/src/fathom/infrastructure/memory/sqlite.py b/src/fathom/infrastructure/memory/sqlite.py index a677b350..d2abf9ae 100644 --- a/src/fathom/infrastructure/memory/sqlite.py +++ b/src/fathom/infrastructure/memory/sqlite.py @@ -16,13 +16,12 @@ class SQLiteMemoryProvider(IMemoryProvider): """ - SQLite implementation of the persistent memory layer. - Handles raw database operations for the Knowledge Graph. + SQLite-backed persistent memory layer for the knowledge graph. """ def __init__(self, database_path: Path) -> None: """ - Initialize provider with explicit database path. + Store the database path and create its parent directory if missing. """ self.__initialized = False @@ -121,7 +120,6 @@ async def retrieve_knowledge(self, visual_hash: str) -> Dict[str, Any]: } async with aiosqlite.connect(self.__path) as db: - # 1. Get screen description async with db.execute( "SELECT activity, description FROM screens WHERE visual_hash = ?", (visual_hash,) ) as cursor: @@ -132,7 +130,6 @@ async def retrieve_knowledge(self, visual_hash: str) -> Dict[str, Any]: return knowledge knowledge["description"] = row[1] - # 2. Get recent experiences (last 5) async with db.execute( "SELECT action_json, success FROM experience WHERE visual_hash = ? ORDER BY timestamp DESC LIMIT 5", (visual_hash,), @@ -161,7 +158,6 @@ async def get_all_knowledge(self) -> Dict[str, Any]: summary: Dict[str, Any] = {"screens": [], "experience_count": 0} async with aiosqlite.connect(self.__path) as db: - # Get screens async with db.execute( "SELECT visual_hash, activity, description FROM screens ORDER BY last_seen DESC" ) as cursor: @@ -170,7 +166,6 @@ async def get_all_knowledge(self) -> Dict[str, Any]: {"hash": row[0], "activity": row[1], "description": row[2]} ) - # Get total experience count async with db.execute("SELECT COUNT(*) FROM experience") as cursor: count = await cursor.fetchone() summary["experience_count"] = count[0] if count else 0 diff --git a/src/fathom/infrastructure/storage/cloud.py b/src/fathom/infrastructure/storage/cloud.py index 45e23805..96081c9a 100644 --- a/src/fathom/infrastructure/storage/cloud.py +++ b/src/fathom/infrastructure/storage/cloud.py @@ -23,7 +23,7 @@ class GCSImageStorage(IImageStorage): def __init__(self, configuration: StorageConfiguration) -> None: """ - Initialize GCS storage with configuration and credentials. + Retain the storage configuration; GCS clients are built per upload. """ self.__configuration = configuration @@ -54,7 +54,6 @@ def __upload_sync() -> str: client = storage.Client.from_service_account_info(credentials, **client_kwargs) else: - # Use positional argument for project if available client = storage.Client(project=project) if project else storage.Client() meta = extract_metadata(metadata or {}) diff --git a/src/fathom/infrastructure/storage/metadata.py b/src/fathom/infrastructure/storage/metadata.py index 0ec64c64..762675be 100644 --- a/src/fathom/infrastructure/storage/metadata.py +++ b/src/fathom/infrastructure/storage/metadata.py @@ -6,7 +6,10 @@ def sanitize_path_component(value: str) -> str: - """Remove characters that are unsafe for filenames/path segments.""" + """ + Remove characters that are unsafe for filenames/path segments. + """ + sanitized = "".join(char for char in value if char.isalnum() or char in "._-") # Reject empty or directory traversal segments like "." and ".." if sanitized in {"", ".", ".."}: @@ -15,7 +18,9 @@ def sanitize_path_component(value: str) -> str: class StorageMetadata(BaseModel): - """Validated and sanitized storage metadata extracted from a raw dict.""" + """ + Validated and sanitized storage metadata extracted from a raw dict. + """ model_config = ConfigDict(frozen=True) diff --git a/src/fathom/infrastructure/temporal/state.py b/src/fathom/infrastructure/temporal/state.py index 9ac23419..c44bef75 100644 --- a/src/fathom/infrastructure/temporal/state.py +++ b/src/fathom/infrastructure/temporal/state.py @@ -17,7 +17,7 @@ class WorkflowSignalState: Workflow signal handlers and the activity-side TemporalSignalAdapter share the same worker process. This class lets the adapter read signal state - without issuing billable Temporal queries. + without issuing Temporal queries. Workflow signal handlers write via mark_* / enqueue_context. The adapter reads via properties and waits on threading.Condition. diff --git a/src/fathom/interfaces/artifact.py b/src/fathom/interfaces/artifact.py index f8b7c22f..97ac8dd9 100644 --- a/src/fathom/interfaces/artifact.py +++ b/src/fathom/interfaces/artifact.py @@ -14,7 +14,8 @@ class ArtifactRendererPort(ABC): """ Strategy that turns one typed :class:`ArtifactRecord` into byte form. - One concrete renderer per :class:`ArtifactKind`. Adding a new kind means adding one renderer and registering it at the composition root no existing renderer needs to change. + One concrete renderer per :class:`ArtifactKind`. Adding a new kind means adding one renderer + and registering it at the composition root; no existing renderer needs to change. """ @property @@ -37,11 +38,10 @@ def render(self, *, record: ArtifactRecord) -> bytes: class ArtifactSinkPort(ABC): """ - Persistence boundary for artifact bytes that have already been - staged onto EFS by the pipeline. + Persistence boundary for artifact bytes already staged onto local disk by the pipeline. - Sinks receive the metadata slice — never the bytes-heavy typed payload - so the persistence boundary stays cheap to serialize and the same contract works for image, XML, and text artifacts alike. + Sinks receive the metadata slice, never the bytes-heavy typed payload, so the boundary stays + cheap to serialize and one contract covers image, XML, and text artifacts alike. """ @abstractmethod diff --git a/src/fathom/interfaces/checkpoint.py b/src/fathom/interfaces/checkpoint.py index d3a3660a..a317d2f4 100644 --- a/src/fathom/interfaces/checkpoint.py +++ b/src/fathom/interfaces/checkpoint.py @@ -79,5 +79,6 @@ async def discard(self, *, workflow_id: str) -> None: async def sweep_stale(self) -> list[str]: """ - Remove orphaned checkpoint state older than the configured retention; return removed workflow identifiers. + Remove orphaned checkpoint state older than the configured retention; + return removed workflow identifiers. """ diff --git a/src/fathom/interfaces/context.py b/src/fathom/interfaces/context.py index eb07792f..a8c2dd27 100644 --- a/src/fathom/interfaces/context.py +++ b/src/fathom/interfaces/context.py @@ -6,8 +6,10 @@ class ContextEngine(ABC): """ - Abstract base class for memory construction strategies. - Supports atomic operations for trace recording, branching, and context assembly. + Port for the versioned reasoning memory that feeds each planner turn. + + Records are appended cheaply during a step and periodically compressed into versioned units, + so the planner reads a bounded multi-tier view instead of the full raw trace. """ @abstractmethod diff --git a/src/fathom/interfaces/device.py b/src/fathom/interfaces/device.py index b463cc22..e55a3b02 100644 --- a/src/fathom/interfaces/device.py +++ b/src/fathom/interfaces/device.py @@ -13,7 +13,7 @@ class DevicePort(ABC): """ - Abstract interface for environment action execution. + Port for driving a target device: dispatch input gestures and capture screen state. """ @property diff --git a/src/fathom/interfaces/graph.py b/src/fathom/interfaces/graph.py index 0b4addee..4a76e517 100644 --- a/src/fathom/interfaces/graph.py +++ b/src/fathom/interfaces/graph.py @@ -9,8 +9,7 @@ class GraphBuilder(ABC): """ - Abstract base class for building LangGraph workflows. - Enforces dependency injection and consistent assembly patterns. + Port for assembling a runnable LangGraph workflow from injected ports. """ @abstractmethod @@ -20,14 +19,10 @@ def build( checkpointer: Optional[BaseCheckpointSaver] = None, ) -> CompiledStateGraph: """ - Builds and compiles the graph. + Wire the injected nodes into a compiled, runnable graph. - Args: - checkpointer: Optional persistence layer for state. - interrupt_before: List of node names to interrupt before. - - Returns: - CompiledStateGraph: The ready-to-execute graph. + ``interrupt_before`` lists nodes where the run pauses for human-in-the-loop control, + and ``checkpointer`` persists graph state so an interrupted run resumes across restarts. """ raise NotImplementedError diff --git a/src/fathom/interfaces/knowledge.py b/src/fathom/interfaces/knowledge.py index 76d288b8..5875c2af 100644 --- a/src/fathom/interfaces/knowledge.py +++ b/src/fathom/interfaces/knowledge.py @@ -8,7 +8,7 @@ class KnowledgePort(ABC): """ - Abstract interface for application knowledge graph. + Port for the app knowledge graph of screens and the actions that connect them. """ @abstractmethod diff --git a/src/fathom/interfaces/lifecycle.py b/src/fathom/interfaces/lifecycle.py index 87ea7cdc..9c614f0d 100644 --- a/src/fathom/interfaces/lifecycle.py +++ b/src/fathom/interfaces/lifecycle.py @@ -6,15 +6,11 @@ @runtime_checkable class RunnerLifecycle(Protocol): """ - Minimum runtime lifecycle a composition root needs to manage a runner. + Lifecycle-only view of a runner: the cleanup and cancel a composition root drives. - Used by RunnerComposition.runner so the schema layer can stay decoupled - from the concrete FathomRunner implementation while still expressing the - cleanup / cancel contract the composition root relies on. - - Runtime callers that need richer surface (run_intent, run_exploration, - device access) must keep the concrete FathomRunner reference at their - own layer; this protocol intentionally exposes only lifecycle methods. + Lets RunnerComposition.runner stay decoupled from the concrete FathomRunner. Callers needing richer + surface (run_intent, run_exploration, device access) must keep their own concrete FathomRunner + reference; this protocol intentionally exposes only lifecycle methods. """ async def cleanup(self) -> None: diff --git a/src/fathom/interfaces/llm.py b/src/fathom/interfaces/llm.py index 97bb7e60..71a991c2 100644 --- a/src/fathom/interfaces/llm.py +++ b/src/fathom/interfaces/llm.py @@ -16,7 +16,7 @@ class LLMPort(ABC): """ - Abstract interface for language model interactions. + Provider-neutral port for language-model generation. """ @property @@ -40,20 +40,11 @@ async def generate( structured_output: Optional[StructuredOutput] = None, ) -> GenerateResult: """ - Generate response from LLM. - - Args: - prompt: List of text parts and image bytes - system_instruction: Optional system prompt - tools: Optional tool definitions - conversation_history: Optional prior turns for multi-turn feedback loops. - Each entry is a provider-neutral ConversationTurn. - When provided, prompt is appended as the final user turn. - structured_output: Optional vendor-neutral constrained-decoding contract. - Adapters translate it into their provider's structured-output API. - - Returns: - GenerateResult with content and tool calls + Generate one response, optionally constrained by a structured-output contract. + + conversation_history supplies provider-neutral prior turns for multi-turn feedback + loops; when present, prompt is appended as the final user turn. structured_output is + a vendor-neutral constrained-decoding contract that adapters map to their provider's API. """ raise NotImplementedError diff --git a/src/fathom/interfaces/memory.py b/src/fathom/interfaces/memory.py index c1d3df3b..a9b17cbf 100644 --- a/src/fathom/interfaces/memory.py +++ b/src/fathom/interfaces/memory.py @@ -10,7 +10,7 @@ class MemoryPort(ABC): """ - Abstract interface for session state and cross-run memory. + Session key-value store plus cross-run recall of screen observations and action outcomes. """ @abstractmethod diff --git a/src/fathom/interfaces/oracle.py b/src/fathom/interfaces/oracle.py index f479e322..4f47bb6a 100644 --- a/src/fathom/interfaces/oracle.py +++ b/src/fathom/interfaces/oracle.py @@ -7,7 +7,7 @@ class OraclePort(ABC): """ - Abstract interface for reading a criterion against a settled screen capture. + Reads one pass/fail criterion against a settled screen capture. """ @abstractmethod diff --git a/src/fathom/interfaces/perception.py b/src/fathom/interfaces/perception.py index 6ebcd49e..a1fa3a5a 100644 --- a/src/fathom/interfaces/perception.py +++ b/src/fathom/interfaces/perception.py @@ -11,7 +11,7 @@ class PerceptionPort(ABC): """ - Abstract interface for runtime perception and screen-state capture. + Captures screen state and probes soft-keyboard visibility for the runtime. """ @property diff --git a/src/fathom/interfaces/qualifier.py b/src/fathom/interfaces/qualifier.py index 257833d7..58ff102c 100644 --- a/src/fathom/interfaces/qualifier.py +++ b/src/fathom/interfaces/qualifier.py @@ -9,9 +9,9 @@ class IntentQualifierPort(ABC): """ Domain contract for deciding whether an intent describes an executable UI task. - The port carries exactly one method. Resource lifecycle (LLM construction, teardown of dedicated infrastructure) - is the composition root's concern and deliberately does NOT live on this port — see runtime/qualifier/composer.py - and the QualifierComposition / RunnerComposition schemas for how owned resources are tracked at the runtime layer. + Carries exactly one method. Resource lifecycle (LLM construction, teardown) is the composition root's + concern and deliberately does NOT live here; see runtime/qualifier/composer.py and the + QualifierComposition / RunnerComposition schemas. """ @abstractmethod diff --git a/src/fathom/interfaces/signal.py b/src/fathom/interfaces/signal.py index c97620fc..227aba64 100644 --- a/src/fathom/interfaces/signal.py +++ b/src/fathom/interfaces/signal.py @@ -6,13 +6,15 @@ class SignalPort(ABC): """ - Abstract interface for control signals. - Defines the contract for external interruptions and context injection. + Control-signal channel for external pause/resume interruptions and human context injection. """ @property def is_interactive(self) -> bool: - """Whether this signal adapter supports interactive (human-in-the-loop) control.""" + """ + Whether this signal adapter supports interactive (human-in-the-loop) control. + """ + return True @abstractmethod @@ -26,10 +28,7 @@ def supports_interruption(self) -> bool: @abstractmethod async def check_signal(self) -> Optional[str]: """ - Non-blocking check for an active signal. - - Returns: - SignalType value (str) if present, else None. + Non-blocking check for an active signal; returns the SignalType value as a string, or None. """ raise NotImplementedError @@ -98,13 +97,7 @@ async def has_injected_context(self) -> bool: @abstractmethod async def ask(self, *, prompt: str) -> str: """ - Request specific input from the human. - - Args: - prompt: The question to ask. - - Returns: - The user's response. + Ask the human a question and block until they respond. """ raise NotImplementedError diff --git a/src/fathom/interfaces/storage.py b/src/fathom/interfaces/storage.py index eea4dfac..424b16d2 100644 --- a/src/fathom/interfaces/storage.py +++ b/src/fathom/interfaces/storage.py @@ -6,20 +6,13 @@ class StoragePort(ABC): """ - Abstract interface for artifact persistence. + Persists artifact bytes and returns a retrieval identifier. """ @abstractmethod async def save(self, *, data: bytes, metadata: Optional[Dict[str, Any]] = None) -> str: """ - Save artifact and return identifier. - - Args: - data: Binary data to store - metadata: Optional metadata for organizing storage - - Returns: - Storage identifier (path, URL, etc.) + Persist the bytes, optionally tagged with metadata, and return a retrieval identifier. """ raise NotImplementedError diff --git a/src/fathom/interfaces/summarization.py b/src/fathom/interfaces/summarization.py index c5243224..773b5813 100644 --- a/src/fathom/interfaces/summarization.py +++ b/src/fathom/interfaces/summarization.py @@ -6,19 +6,13 @@ class SummarizationPort(ABC): """ - Abstract interface for semantic compression of execution traces. + Semantic compression of execution traces into a one-sentence progress summary. """ @abstractmethod async def summarize_trace(self, trace: List[Dict[str, Any]]) -> str: """ - Compresses a list of trace entries into a concise semantic summary. - - Args: - trace: List of OTA (Observation-Thought-Action) dictionaries. - - Returns: - A single sentence summarizing the progress and state change. + Compress a trace of OTA (Observation-Thought-Action) entries into one summarizing sentence. """ raise NotImplementedError diff --git a/src/fathom/interfaces/telemetry.py b/src/fathom/interfaces/telemetry.py index 33ff8c2a..463c4380 100644 --- a/src/fathom/interfaces/telemetry.py +++ b/src/fathom/interfaces/telemetry.py @@ -8,7 +8,7 @@ class TelemetryPort(ABC): """ - Abstract interface for telemetry and observability. + Leveled structured-logging and observability sink. """ @abstractmethod diff --git a/src/fathom/processing/annotator.py b/src/fathom/processing/annotator.py index 91b9f660..98ab9884 100644 --- a/src/fathom/processing/annotator.py +++ b/src/fathom/processing/annotator.py @@ -428,23 +428,14 @@ def overlay_perception_boxes( box_thickness: int = 2, ) -> Optional[bytes]: """ - Draw perception-source bounding boxes on top of an existing - annotated image and return the new PNG bytes. - - Used when :class:`fathom.core.services.manifest.ManifestMerger` - appends OCR / Icon / Vision elements onto the XML manifest: - the LLM-facing image must show a box for every numeric label - the LLM sees in the manifest, otherwise the model is being - asked to ground against labels it cannot visually verify - (a documented hallucination regime). - - ``entries`` are :class:`AppendedManifestEntry` tuples carrying - ``(label_id, source, text, bounds)`` — colours come from the - :class:`SourceColor` palette so OCR boxes are green, Icon - amber, Vision pink, distinguishable from the blue XML and - purple CV boxes already on the image. Styling (font size, - stroke width, label positioning) matches :meth:`annotate` - exactly so the combined image reads as one consistent pass. + Draw perception-source bounding boxes on top of an existing annotated image, returning new PNG bytes. + + Used when :class:`fathom.core.services.manifest.ManifestMerger` appends OCR / Icon / Vision + elements: the LLM-facing image must carry a box for every numeric label in the manifest, else the + model grounds against labels it cannot visually verify (a documented hallucination regime). + ``entries`` are :class:`AppendedManifestEntry` tuples ``(label_id, source, text, bounds)``; colours + come from :class:`SourceColor` (OCR green, Icon amber, Vision pink) to distinguish them from the + blue XML and purple CV boxes, and styling matches :meth:`annotate` so the passes read as one. """ if not entries: diff --git a/src/fathom/runtime/adapters.py b/src/fathom/runtime/adapters.py index bf6057d5..ac0d60d8 100644 --- a/src/fathom/runtime/adapters.py +++ b/src/fathom/runtime/adapters.py @@ -88,10 +88,8 @@ def perception_configuration(self) -> PerceptionConfiguration: """ Expose the loaded perception configuration to downstream wiring. - Strategies that need to thread perception toggles into domain - services (e.g. ``cv_enabled`` for :class:`HierarchyService`) - read this rather than rebuilding the configuration from the - loader. + Strategies read this to thread perception toggles (e.g. ``cv_enabled`` for + :class:`HierarchyService`) into domain services rather than rebuilding it from the loader. """ return self.__perception @@ -135,9 +133,8 @@ def icons(self) -> IconDetectorPort: """ Build the icon detector when explicitly enabled; otherwise noop. - The template registry ships empty until a future entry populates - it, so a "default-on" icon detector adds latency without value. - Gated behind :attr:`IconConfiguration.enabled` so the original XML+LLM flow runs without it. + Gated behind :attr:`IconConfiguration.enabled` because the template registry ships empty, + so a default-on detector would only add latency to the XML+LLM flow. """ if not self.__perception.icon.enabled: @@ -230,11 +227,9 @@ def pipeline( """ Build the artifact pipeline wired against the configured backends. - When ``"CLOUD"`` is enabled and a bucket is configured, the - pipeline uploads to the cloud :class:`StoragePort` and clears - the EFS-staged copy on success. Otherwise the pipeline retains - the EFS-staged copy via :class:`EfsSink` — the local copy IS - the durable artifact in that mode. + With ``"CLOUD"`` enabled and a bucket configured, it uploads to the cloud :class:`StoragePort` + and clears the locally staged copy on success; otherwise :class:`EfsSink` retains that local + copy as the durable artifact. """ sink = self.__resolve_sink(configuration=storage_configuration) @@ -320,8 +315,8 @@ def __build_member(self, *, name: EnsembleMemberName) -> Optional[TargetLocalize """ Build one ensemble member by its typed name. - ``DOCUMENT_AI_LAYOUT`` is a downstream consumer of OCR tokens — it has nothing to localize against when OCR is disabled or un-configured. - Drop it at composition so the ensemble never carries a member that can only ever return ``None``. + ``DOCUMENT_AI_LAYOUT`` consumes OCR tokens, so it is dropped at composition when OCR is + disabled or un-configured rather than carrying a member that can only ever return ``None``. """ if name == EnsembleMemberName.GEMINI_VISION: @@ -348,14 +343,11 @@ def __resolve_sink(self, *, configuration: StorageConfiguration) -> ArtifactSink """ Pick the artifact sink based on the configured storage backends. - Cloud-enabled deployments upload via :class:`CloudSink` wrapping - a fresh cloud-only :class:`StoragePort` — wrapping the runtime's - composite storage instead would re-write the same local file the - producer just wrote and race downstream readers. - - Local-only deployments fall back to :class:`EfsSink`, which - keeps the EFS-staged copy as the durable artifact and reports - no remote cleanup so the pipeline never deletes the local file. + Cloud-enabled deployments upload via :class:`CloudSink` over a fresh cloud-only + :class:`StoragePort`; wrapping the runtime's composite storage would re-write the file the + producer just wrote and race downstream readers. Local-only deployments fall back to + :class:`EfsSink`, which keeps the staged copy as the durable artifact and reports no remote + cleanup so the pipeline never deletes the local file. """ if self.__cloud_enabled(configuration=configuration): diff --git a/src/fathom/runtime/builder.py b/src/fathom/runtime/builder.py index 39dccb3a..70682086 100644 --- a/src/fathom/runtime/builder.py +++ b/src/fathom/runtime/builder.py @@ -53,10 +53,7 @@ class FathomBuilder: def __init__(self, path_manager: Optional[SharedPathManager] = None) -> None: """ - Initialize builder with no ports configured. - - Args: - path_manager: Optional shared path manager instance + Initialize the builder with no ports configured. """ self.__device: Optional[DevicePort] = None @@ -102,17 +99,12 @@ def __init__(self, path_manager: Optional[SharedPathManager] = None) -> None: def with_runtime_configuration(self, loader: RuntimeConfigLoader) -> FathomBuilder: """ - Attach a pre-bound :class:`RuntimeConfigLoader` so its settings - ride all the way down to :class:`AdapterAssembly` inside the - strategy. Required for any deployment whose env-var names - differ from fathom's own ``FATHOM_*`` / - ``GOOGLE_APPLICATION_CREDENTIALS_JSON`` aliases (e.g. - genymotion's ``DRIZZ_`` prefix). - - The loader is an Application-layer object. The caller (e.g. - Temporal worker registry) constructs it as - ``RuntimeConfigLoader(settings=settings)`` and the raw - :class:`FathomSettings` never crosses this boundary — keeping + Attach a pre-bound :class:`RuntimeConfigLoader` so its settings reach + :class:`AdapterAssembly` inside the strategy. + + Required when a deployment's env-var names differ from fathom's own ``FATHOM_*`` / + ``GOOGLE_APPLICATION_CREDENTIALS_JSON`` aliases (e.g. a ``DRIZZ_`` prefix). The caller binds + settings into the loader; the raw :class:`FathomSettings` never crosses this boundary, keeping SA credentials and other secrets confined to caller scope. """ @@ -121,13 +113,7 @@ def with_runtime_configuration(self, loader: RuntimeConfigLoader) -> FathomBuild def with_device(self, port: DevicePort) -> FathomBuilder: """ - Configure device port. - - Args: - port: Device port implementation - - Returns: - Builder instance for chaining + Register the device port used to drive the target. """ self.__device = port @@ -135,13 +121,7 @@ def with_device(self, port: DevicePort) -> FathomBuilder: def with_llm(self, port: LLMPort) -> FathomBuilder: """ - Configure LLM port. - - Args: - port: LLM port implementation - - Returns: - Builder instance for chaining + Register the planner LLM port that drives step decisions. """ self.__llm = port @@ -149,13 +129,7 @@ def with_llm(self, port: LLMPort) -> FathomBuilder: def with_perception(self, port: PerceptionPort) -> FathomBuilder: """ - Configure perception port. - - Args: - port: Perception port implementation - - Returns: - Builder instance for chaining + Register the perception port that reads on-screen state. """ self.__perception = port @@ -163,13 +137,7 @@ def with_perception(self, port: PerceptionPort) -> FathomBuilder: def with_memory(self, port: MemoryPort) -> FathomBuilder: """ - Configure memory port. - - Args: - port: Memory port implementation - - Returns: - Builder instance for chaining + Register the memory port backing durable run knowledge. """ self.__memory = port @@ -177,13 +145,7 @@ def with_memory(self, port: MemoryPort) -> FathomBuilder: def with_interaction(self, port: InteractionPort) -> FathomBuilder: """ - Configure interaction port. - - Args: - port: Interaction port implementation - - Returns: - Builder instance for chaining + Register the interaction-storage port for conversation records. """ self.__interaction = port @@ -191,13 +153,7 @@ def with_interaction(self, port: InteractionPort) -> FathomBuilder: def with_knowledge(self, port: KnowledgePort) -> FathomBuilder: """ - Configure knowledge port. - - Args: - port: Knowledge port implementation - - Returns: - Builder instance for chaining + Register the knowledge port holding learned screen data. """ self.__knowledge = port @@ -205,13 +161,7 @@ def with_knowledge(self, port: KnowledgePort) -> FathomBuilder: def with_signal(self, port: SignalPort) -> FathomBuilder: """ - Configure signal port. - - Args: - port: Signal port implementation - - Returns: - Builder instance for chaining + Register the signal port carrying pause, resume, and cancel. """ self.__signal = port @@ -233,13 +183,7 @@ def with_storage( def with_telemetry(self, port: TelemetryPort) -> FathomBuilder: """ - Configure telemetry port. - - Args: - port: Telemetry port implementation - - Returns: - Builder instance for chaining + Register the telemetry port for client-facing run events. """ self.__telemetry = port @@ -247,13 +191,7 @@ def with_telemetry(self, port: TelemetryPort) -> FathomBuilder: def with_summarizer(self, port: SummarizationPort) -> FathomBuilder: """ - Configure summarization port. - - Args: - port: Summarization port implementation - - Returns: - Builder instance for chaining + Register the summarization port for run digests. """ self.__summarizer = port @@ -261,13 +199,7 @@ def with_summarizer(self, port: SummarizationPort) -> FathomBuilder: def with_config(self, configuration: FathomConfiguration) -> FathomBuilder: """ - Configure Fathom settings. - - Args: - configuration: Complete Fathom configuration - - Returns: - Builder instance for chaining + Replace the full Fathom configuration. """ self.__config = configuration @@ -275,13 +207,7 @@ def with_config(self, configuration: FathomConfiguration) -> FathomBuilder: def with_execution_config(self, configuration: ExecutionConfiguration) -> FathomBuilder: """ - Configure execution engine settings. - - Args: - configuration: Execution configuration - - Returns: - Builder instance for chaining + Set the execution engine configuration. """ self.__config.engine = configuration @@ -289,13 +215,7 @@ def with_execution_config(self, configuration: ExecutionConfiguration) -> Fathom def with_intent_config(self, configuration: IntentConfiguration) -> FathomBuilder: """ - Configure intent strategy settings. - - Args: - configuration: Intent configuration - - Returns: - Builder instance for chaining + Set the intent strategy configuration. """ self.__config.intent = configuration @@ -303,13 +223,7 @@ def with_intent_config(self, configuration: IntentConfiguration) -> FathomBuilde def with_exploration_config(self, configuration: ExplorationConfiguration) -> FathomBuilder: """ - Configure exploration strategy settings. - - Args: - configuration: Exploration configuration - - Returns: - Builder instance for chaining + Set the exploration strategy configuration. """ self.__config.exploration = configuration @@ -326,13 +240,7 @@ def with_qualifier_config(self, configuration: QualifierConfiguration) -> Fathom def with_qualifier(self, port: IntentQualifierPort) -> FathomBuilder: """ - Configure intent qualifier port. - - Args: - port: Intent qualifier port implementation - - Returns: - Builder instance for chaining + Register a pre-built intent qualifier port, bypassing composition. """ self.__qualifier = port @@ -345,25 +253,11 @@ def with_assembly( llm_factory: Optional[LLMFactoryPort] = None, ) -> FathomBuilder: """ - Wire the bits the qualifier composer needs to build a dedicated - qualifier LLM (separate from the planner LLM passed to .with_llm). + Bind a dedicated qualifier LLM, separate from the planner LLM, for ``build()`` to construct. - When supplied, build() resolves the qualifier's model / timeout / - retries through `assembly.build_qualifier_model_configuration(...)` - and constructs a fresh LLM via `llm_factory.create(...)` — so the - eval-tuned defaults in QualifierConfiguration.inference actually - take effect for direct SDK callers (Enricher, integration tests, - notebooks). When omitted, the qualifier falls back to running on - the caller-supplied planner LLM and inference.* settings are - ignored — preserves existing behavior for callers that don't opt in. - - Args: - assembly: RunAssemblyBuilder bound to settings the qualifier - LLM should resolve credentials and project from. - llm_factory: Optional LLM factory. Defaults to LLMFactory(). - - Returns: - Builder instance for chaining. + When set, ``build()`` resolves the qualifier's model/timeout/retries from the assembly and + builds a fresh LLM so ``QualifierConfiguration.inference`` applies; when omitted, the qualifier + runs on the planner LLM and ``inference.*`` is ignored. """ self.__assembly = assembly @@ -372,13 +266,7 @@ def with_assembly( def with_realignment(self, policy: RealignmentPolicy) -> FathomBuilder: """ - Configure realignment policy. - - Args: - policy: Realignment policy instance - - Returns: - Builder instance for chaining + Register the realignment policy governing context re-evaluation. """ self.__realignment = policy @@ -386,12 +274,7 @@ def with_realignment(self, policy: RealignmentPolicy) -> FathomBuilder: def build(self) -> FathomRunner: """ - Build configured Fathom instance. - - Validates required ports and applies defaults. - - Returns: - FathomRunner instance with all ports configured + Validate the configured ports, apply defaults, and construct the runner. Raises: ConfigurationError: If required ports (device, llm) are not configured @@ -475,25 +358,13 @@ def build(self) -> FathomRunner: def __compose_qualifier(self) -> tuple[IntentQualifierPort, List[LLMPort]]: """ - Construct the qualifier port and any resources the runner must own. - - Two paths: - - assembly supplied (.with_assembly): build a dedicated qualifier LLM - via the assembly's qualifier-model configuration. The dedicated LLM - is returned alongside the qualifier so the runner can clean it up. - inference.{model, timeout, max_retries, ...} take effect here. - - assembly NOT supplied: fall back to the planner LLM. inference.* is - stored on the config but ignored — preserves the pre-with_assembly - behavior for direct callers that haven't opted in. + Build the qualifier port and any LLM the runner must own (sync counterpart of + :meth:`QualifierComposer.compose`). - This is the sync equivalent of QualifierComposer.compose(). Diverges - only in cleanup-on-failure: if IntentQualifierFactory.create raises - AFTER the dedicated LLM is built, the LLM is not awaited-closed (the - builder is a startup-time call; on construction failure the process - typically dies and the OS reclaims connections). Temporal / CLI paths - use the proper async QualifierComposer with full cleanup; this sync - version exists so direct SDK callers don't need to make build() - async. + With an assembly, builds a dedicated qualifier LLM (returned so the runner can close it) and + ``inference.*`` applies; without one, falls back to the planner LLM and ignores ``inference.*``. + Unlike the async composer it does not close the dedicated LLM if the factory raises after it is + built — acceptable because this runs at startup, where a construction failure ends the process. """ # build() raises ConfigurationError before reaching here if self.__llm is None; @@ -532,12 +403,6 @@ class Fathom: def builder(path_manager: Optional[SharedPathManager] = None) -> FathomBuilder: """ Create a new builder instance. - - Args: - path_manager: Optional shared path manager - - Returns: - New FathomBuilder instance """ return FathomBuilder(path_manager=path_manager) diff --git a/src/fathom/runtime/command/executor.py b/src/fathom/runtime/command/executor.py index b469dfa8..a8d9e4fe 100644 --- a/src/fathom/runtime/command/executor.py +++ b/src/fathom/runtime/command/executor.py @@ -145,16 +145,10 @@ async def __create_runner( """ Build configured runtime runner and bundle it with owned resources. - Returns a RunnerComposition so the caller can drain the dedicated - qualifier LLM (or any other infrastructure the composer creates) - alongside runner cleanup. - - Build-time cleanup: every adapter is registered on a local list before - the next step runs. If any step fails (composer auth refusal, telemetry - connection error, builder.build() raising), every registered adapter is - drained in reverse-creation order before re-raising — no resource leaks - before a RunnerComposition exists. The runner's own cleanup path takes - over once builder.build() succeeds. + Returns a :class:`RunnerComposition` so the caller can drain the dedicated qualifier LLM + (or other composer-created infrastructure) alongside runner cleanup. If any step fails, every + adapter registered so far is drained in reverse-creation order before re-raising; the runner's + own cleanup takes over once ``builder.build()`` succeeds. """ path_manager = SharedPathManager(settings=self.__settings) diff --git a/src/fathom/runtime/executor.py b/src/fathom/runtime/executor.py index fa765432..01dd13bd 100644 --- a/src/fathom/runtime/executor.py +++ b/src/fathom/runtime/executor.py @@ -37,7 +37,7 @@ def __init__( invalidate_on_injection: bool = True, ) -> None: """ - Initialize executor. + Bind the graph, context, thread id, and interrupt/injection policy for one run. """ self.__graph = graph @@ -68,10 +68,9 @@ async def __run(self) -> None: Drive the graph to completion, autonomously or under the interactive pause/resume loop. """ - # Validate state consistency before execution await self.__validate_state_sync("run_start") - # For autonomous mode (no interrupts), run graph to completion in one call + # Autonomous mode has no interrupts, so run the graph to completion in one call. if not self.__has_interrupts: logger.info("Executor: Running in autonomous mode (no interrupts)") @@ -81,7 +80,6 @@ async def __run(self) -> None: logger.warning("Executor: Workflow cancelled during execution") break - # Log node transitions if isinstance(event, dict): for node, _output in event.items(): logger.info(f"Executor: Node '{node}' completed") @@ -123,12 +121,10 @@ async def __run_interactive(self) -> None: current_input: Optional[Dict[str, Any]] = {} while True: - # Check cancellation before starting any graph execution if await self.__stop_for_cancellation(phase="before execution"): return - # Race Condition: Run Graph vs Wait for Pause - # We wrap the graph stream in a task to allow cancellation. + # Race the graph stream against a pause request; wrapping the stream in a task lets us cancel it. stream_task = self.__create_task( operation=self.__stream_graph(input_value=current_input) ) @@ -154,23 +150,20 @@ async def __run_interactive(self) -> None: if await self.__stop_for_cancellation(phase="after execution"): return - # Check Graph State if not (await self.__graph.aget_state(self.__config)).next: return - # Handle Interrupt (Breakpoint reached naturally) - # Check for HITL signals one last time. + # A naturally reached breakpoint: check for HITL signals one last time. await self.__handle_interrupt(source="breakpoint") if await self.__stop_for_cancellation(phase="after interrupt handling"): return - # Resume Execution current_input = None async def __stream_graph(self, *, input_value: Optional[Dict[str, Any]]) -> None: """ - Wrapper to stream graph events. + Stream graph events, stopping early when the run is cancelled. """ async for event in self.__graph.astream(input_value, config=self.__config): @@ -178,7 +171,6 @@ async def __stream_graph(self, *, input_value: Optional[Dict[str, Any]]) -> None logger.warning("Executor: Workflow cancelled during stream") break - # Log node transitions for visibility if isinstance(event, dict): for node, _output in event.items(): logger.info(f"Executor: Node '{node}' completed") @@ -360,10 +352,7 @@ async def __handle_interrupt(self, source: str) -> None: await self.__guarded_phase_shutdown(reason="operator_context_abort") return - # Inject into system (resets loop state internally) await self.__inject_context(content=context) - - # Explicitly consume await self.__context.hitl.consume_context() if processed_count > 0: diff --git a/src/fathom/runtime/runner.py b/src/fathom/runtime/runner.py index b76add90..c7ca34be 100644 --- a/src/fathom/runtime/runner.py +++ b/src/fathom/runtime/runner.py @@ -124,14 +124,9 @@ class FathomRunner: """ Executes Fathom workflows with configured ports. - This is the main execution orchestrator that wires together all ports - and coordinates the execution of automation workflows using hexagonal architecture. - - The runner: - - Wires ExecutionEngine and ContextManager - - Manages execution lifecycle - - Delegates to strategy implementations - - Returns results compatible with CLI expectations + Main execution orchestrator: wires the :class:`ExecutionEngine` and :class:`ContextManager`, + manages the execution lifecycle, delegates to strategy implementations, and returns + CLI-compatible results. """ def __init__( @@ -196,7 +191,6 @@ def __init__( message=self.__config.telemetry.phase, ) - # Wire core components self.__catalog = CommandCatalogProvider().build() self.__capture_store = CaptureStore() self.__engine = ExecutionEngine( @@ -420,11 +414,9 @@ async def run_intent( # isolated by workflow id. namespace = thread if context_scope == ContextScope.CONVERSATION else workflow_id - # Initialize context self.__context_manager = ContextManager(memory=self.__memory, workflow_id=namespace) self.__context_manager.set_roadmap(intent=intent) - # Create and execute strategy strategy = IntentStrategy( intent=intent, tenant=tenant, @@ -458,18 +450,14 @@ async def run_intent( self.__current_strategy = strategy try: - # Execute strategy execution_result = await strategy.execute() - # Get progress info progress = strategy.get_progress() - # Get subgoal execution audit trail executed_subgoals, skipped_subgoals, subgoal_count = ( strategy.get_subgoal_execution_audit() ) - # Collect metrics from strategy - use to_report_dict() for proper format strategy_metrics = strategy.get_metrics() metrics = strategy_metrics.to_report_dict() if strategy_metrics else {} @@ -482,7 +470,6 @@ async def run_intent( memory_summary: Dict[str, JsonValue] = raw_memory_summary if raw_memory_summary else {} - # Build IntentResult duration = time.time() - start_time is_cancelled = execution_result.is_cancelled @@ -672,7 +659,6 @@ async def run_exploration( self.__sync_telemetry_identity(workflow=workflow_id) - # Use provided package name or fetch from device if not package_name: package_name = await self.__device.get_current_package() @@ -720,7 +706,6 @@ async def run_exploration( identity = InteractionIdentity(execution=execution_id) - # Initialize context self.__context_manager = ContextManager(memory=self.__memory, workflow_id=workflow_id) self.__context_manager.set_roadmap(intent=intent) @@ -750,18 +735,15 @@ async def run_exploration( self.__current_strategy = strategy try: - # Execute strategy execution_result = await strategy.execute() - # Get progress info progress = strategy.get_progress() stats = progress.get("stats", {}) - # Extract discovered activities from graph graph = strategy.graph discovered_activities = list({node.activity for node in graph.nodes.values()}) - # Calculate coverage (percentage of screens explored vs total discovered) + # Coverage is the fraction of discovered screens that were actually explored. unexplored = stats.get("unexplored", 0) unique_screens = stats.get("unique_screens", 0) @@ -771,10 +753,8 @@ async def run_exploration( else 0.0 ) - # Export graph structure screen_graph = await self.__export_graph(graph=graph) - # Build ExplorationResult duration = time.time() - start_time result = ExplorationResult( diff --git a/src/fathom/runtime/temporal/activities.py b/src/fathom/runtime/temporal/activities.py index 64f24f73..19fcc262 100644 --- a/src/fathom/runtime/temporal/activities.py +++ b/src/fathom/runtime/temporal/activities.py @@ -45,16 +45,10 @@ def __init__(self, settings: Optional[FathomSettings] = None) -> None: """ Initialize activities with runtime settings. - The :class:`FathomSettings` reference stays scoped to this - activity instance — it never crosses the runner / strategy - seam as a raw object. Instead we bind it to a - :class:`RuntimeConfigLoader` (Application layer) here, and - only the loader flows downstream via - :meth:`FathomBuilder.with_runtime_configuration`. This keeps SA - credentials, API keys, and other secrets confined to the - worker process scope — they cannot be passed as Temporal - activity arguments, cannot land in workflow history, and - cannot be logged by anything beneath this seam. + :class:`FathomSettings` stays scoped to this activity: it is bound to a + :class:`RuntimeConfigLoader` here and only the loader flows downstream via + :meth:`FathomBuilder.with_runtime_configuration`, so SA credentials, API keys, and other + secrets never cross into Temporal activity arguments or workflow history. """ self.__settings = settings or FathomSettings() @@ -98,21 +92,13 @@ async def __build_runner(self, *, workflow_id: str, request: RunRequest) -> Runn """ Build the Fathom runner and bundle it with any owned infrastructure. - Whether a qualifier is attached is derived from the request itself — - intent runs whose configuration enables qualification get a dedicated - composed qualifier; exploration runs and disabled-qualifier intent runs - fall back to the builder's default permissive qualifier. - - Returns a RunnerComposition so the composition root can drain any owned - resources (e.g. the dedicated qualifier LLM) alongside runner cleanup. - - Build-time cleanup: every adapter created here is registered onto a - local list before the next step runs. If any step after creation fails - (composer auth refusal, telemetry connection error, builder.build() - raising), every registered adapter is drained in reverse-creation - order before re-raising — no resource leaks before a RunnerComposition - exists. The runner's own cleanup path takes over once builder.build() - succeeds. + Whether a qualifier is attached is derived from the request: qualification-enabled intent + runs get a dedicated composed qualifier, while exploration and disabled-qualifier intent runs + fall back to the builder's default permissive one. Returns a :class:`RunnerComposition` so the + composition root can drain owned resources (e.g. the dedicated qualifier LLM) alongside runner + cleanup. If any step after creation fails, every adapter registered so far is drained in + reverse-creation order before re-raising; the runner's own cleanup takes over once + ``builder.build()`` succeeds. """ device_configuration = self.__assembly.build_device_configuration(request=request) diff --git a/src/fathom/schemas/actions.py b/src/fathom/schemas/actions.py index 0c812c33..f1967c06 100644 --- a/src/fathom/schemas/actions.py +++ b/src/fathom/schemas/actions.py @@ -321,7 +321,7 @@ def to_coordinates(self) -> Tuple[int, int, int, int]: class Action(BaseModel): """ - Represents an atomic action to be performed on the mobile device. + A single planned device interaction: its type, grounding target, and execution parameters. """ action_type: ActionType = Field(description="The type of interaction to perform") diff --git a/src/fathom/schemas/artifact.py b/src/fathom/schemas/artifact.py index 33abbec6..1b75ef0d 100644 --- a/src/fathom/schemas/artifact.py +++ b/src/fathom/schemas/artifact.py @@ -97,8 +97,8 @@ class LocalArtifactPolicy(BaseModel): description=( "Whether the pipeline unlinks the EFS-staged file after the sink " "acknowledges cleanup. Hosts that read the staged path after the " - "sink ack (e.g. enricher's healing bridge queueing a delayed " - "Cloudinary upload) disable this and own a fallback sweep." + "sink ack (e.g. a host queueing a delayed remote upload) " + "disable this and own a fallback sweep." ), ) diff --git a/src/fathom/schemas/composition.py b/src/fathom/schemas/composition.py index 62d77408..12e02e52 100644 --- a/src/fathom/schemas/composition.py +++ b/src/fathom/schemas/composition.py @@ -13,11 +13,9 @@ class QualifierComposition(BaseModel): """ Value object returned by the qualifier composer. - Bundles the qualifier port with any infrastructure resources the composer created on the caller's behalf. - The composition root owns the resources and must close them when the run finishes — the qualifier itself never owns its LLM. - - `resources` is a tuple so the ownership view is genuinely immutable; - frozen=True alone blocks field reassignment but would still let callers mutate a list via append/extend. + Bundles the qualifier port with the infrastructure resources the composer created; the composition + root owns those and must close them when the run finishes — the qualifier itself never owns its LLM. + ``resources`` is a tuple so the ownership view is genuinely immutable, not just reassignment-frozen. """ model_config = ConfigDict(arbitrary_types_allowed=True, frozen=True) @@ -38,15 +36,11 @@ class RunnerComposition(BaseModel): """ Value object returned by the activity / executor builder. - Pairs the runner with the resources that need explicit teardown alongside - the runner itself. Keeps lifecycle bookkeeping out of the runner contract - and inside a typed object the composition root can drain. - - The `runner` field is typed against RunnerLifecycle — a small structural - protocol exposing just cleanup() and cancel(). That's all the composition - root needs from this object; richer call sites (activity / CLI executor) - keep their own typed reference to the concrete FathomRunner. - `resources` is a tuple so the ownership view is genuinely immutable. + Pairs the runner with the resources needing explicit teardown, keeping lifecycle bookkeeping in a + typed object the composition root can drain. ``runner`` is typed against RunnerLifecycle — a + structural protocol of just cleanup() and cancel(), all the composition root needs; richer call + sites keep their own reference to the concrete FathomRunner. ``resources`` is a tuple so the + ownership view is genuinely immutable. """ model_config = ConfigDict(arbitrary_types_allowed=True, frozen=True) diff --git a/src/fathom/schemas/configuration.py b/src/fathom/schemas/configuration.py index 6fc37402..c26dbe91 100644 --- a/src/fathom/schemas/configuration.py +++ b/src/fathom/schemas/configuration.py @@ -147,7 +147,7 @@ class LLMConfiguration(BaseModel): description=( "Vision token density. 'high' gives Gemini more vertical resolution " "and is required for accurate bbox grounding on tall mobile screenshots. " - "Lower values trade latency for spatial accuracy on the failure path; for live agents the oss-of-grounding cost dominates." + "Lower values trade latency for spatial accuracy on the failure path; for live agents the loss-of-grounding cost dominates." ), ) @@ -178,14 +178,14 @@ class StorageConfiguration(BaseModel): backends: Set[StorageBackend] = Field( default={StorageBackend.LOCAL}, description=( - "Storage backends to enable. Defaults to LOCAL only so unconfigured " + "Storage backends to enable. Defaults to LOCAL only so un-configured " "local runs do not attempt cloud uploads without ADC credentials. " - "Deployments that want CLOUD uploads pass ``backends={LOCAL, CLOUD}`` " - "explicitly (see ``services/crawler/manager.py``)." + "Deployments that want CLOUD uploads pass ``backends={LOCAL, CLOUD}`` explicitly." ), ) storage_bucket: Optional[str] = Field( - default="drizz-dev-crawler-artifacts", description="Cloud storage bucket name" + default=None, + description="Cloud storage bucket name (required when the CLOUD backend is enabled)", ) project_id: Optional[str] = Field( default=None, description="Project identifier for cloud storage" @@ -256,14 +256,8 @@ class SwipeInteractionPolicy(BaseModel): class _DeprecatedAdaptivePolicy(BaseModel): """ - Inert backwards-compatibility stub for the deleted adaptive-scroll subsystem. - - The adaptive-scroll runtime was removed when the swipe coordinator replaced - it. Older host callers (enricher / healing bridge) still construct - ``ScrollInteractionPolicy.AdaptivePolicy(...)``; this stub accepts the - legacy kwargs without applying any behavior so those hosts continue to - boot while they migrate. Emit a deprecation warning per construction so - the migration is visible. + Inert stub for the removed adaptive-scroll subsystem: accepts the legacy + ``AdaptivePolicy(...)`` kwargs without effect and warns once per construction so callers migrate. """ model_config = ConfigDict(extra="ignore", frozen=True) @@ -597,11 +591,10 @@ class QualifierConfiguration(BaseModel): """ Configuration for the intent executability qualifier. - Owns all qualifier-specific tuning defaults via `default_factory`. Each field of the inference block is set explicitly - from the constants module so a future generic InferenceConfiguration consumer cannot accidentally inherit qualifier-flavored values. - - Use `QualifierConfiguration.evolve(...)` to override individual inference fields while keeping the rest at the eval-validated defaults; - see method docstring for the rationale (avoids the verbose "respecify every field" boilerplate that strict-no-defaults forces on callers). + Owns all qualifier tuning defaults via ``default_factory``, each inference field set explicitly from + the constants module so a future generic InferenceConfiguration consumer cannot inherit + qualifier-flavored values. Use ``evolve(...)`` to override individual inference fields while keeping + the rest at the eval-validated defaults. """ model_config = ConfigDict(extra="forbid") @@ -625,12 +618,11 @@ class QualifierConfiguration(BaseModel): @classmethod def evolve(cls, **inference_overrides: Any) -> "QualifierConfiguration": """ - Build a QualifierConfiguration replacing only the named inference fields, - keeping all other qualifier-tuned defaults. + Build a QualifierConfiguration replacing only the named inference fields, keeping the rest. - Implementation routes the merged kwargs through the InferenceConfiguration constructor (not model_copy(update=...)) - so the nested schema's `extra="forbid"` policy enforces field names. Typos in `inference_overrides` raise ValidationError - instead of being silently dropped onto the model's data dict. + Routes the merged kwargs through the InferenceConfiguration constructor (not + ``model_copy(update=...)``) so its ``extra="forbid"`` policy rejects a mistyped override with + ValidationError instead of silently dropping it. """ base = cls() @@ -741,7 +733,7 @@ class TelemetryConfiguration(BaseModel): ) topic: Optional[str] = Field( default=None, - description="Topic or channel pattern (e.g., enricher:commands:v1:logs:{session_id})", + description="Topic or channel pattern (e.g., commands:v1:logs:{session_id})", ) session_id: Optional[str] = Field( default=None, description="Session ID for channel interpolation" diff --git a/src/fathom/schemas/decomposition.py b/src/fathom/schemas/decomposition.py index 734b45f9..3046e4b9 100644 --- a/src/fathom/schemas/decomposition.py +++ b/src/fathom/schemas/decomposition.py @@ -1,5 +1,3 @@ -"""Schemas for LLM-backed intent decomposition.""" - from __future__ import annotations from typing import List diff --git a/src/fathom/schemas/effect.py b/src/fathom/schemas/effect.py index a610f998..fc42bde9 100644 --- a/src/fathom/schemas/effect.py +++ b/src/fathom/schemas/effect.py @@ -69,14 +69,9 @@ class ActionEffect(BaseModel): """ Structured outcome of one executed action. - Carries both the deterministic ``status`` classifier and the raw - metrics that produced it. The status is the load-bearing signal for - the prompt; raw numbers are diagnostic context, not the contract. - - The classifier thresholds (see ``constants/screen.py``) are - fixture-pinned against real run traces so the boundary between - progress and no-progress matches observed reality, not author - intuition. + Carries the deterministic ``status`` classifier — the load-bearing signal for the prompt — plus the + raw metrics that produced it, which are diagnostic context, not the contract. The classifier + thresholds (see ``constants/screen.py``) are fixture-pinned against real run traces. """ model_config = ConfigDict(frozen=True) diff --git a/src/fathom/schemas/exploration.py b/src/fathom/schemas/exploration.py index 8af49f59..9374cda3 100644 --- a/src/fathom/schemas/exploration.py +++ b/src/fathom/schemas/exploration.py @@ -14,8 +14,7 @@ class BFSQueueEntry(BaseModel): """ - Entry in the BFS exploration queue. - Represents a screen to explore with its parent and path information. + A screen enqueued for breadth-first exploration, with the action and path that reached it. """ screen_hash: str @@ -28,8 +27,7 @@ class BFSQueueEntry(BaseModel): class ScreenNode: """ - Node in the screen graph representing a unique screen state. - Tracks visits, actions, and transitions for a discovered screen. + A discovered screen in the exploration graph, tracking its visits, tried actions, and transitions. """ def __init__(self, fingerprint: str, activity: str) -> None: @@ -48,7 +46,7 @@ def __init__(self, fingerprint: str, activity: str) -> None: @property def fingerprint(self) -> str: """ - Returns Unique identifier for this screen state. + Stable fingerprint identifying this screen state. """ return self.__fingerprint @@ -56,7 +54,7 @@ def fingerprint(self) -> str: @property def activity(self) -> str: """ - Returns Activity name for this screen. + Android activity name for this screen. """ return self.__activity @@ -64,7 +62,7 @@ def activity(self) -> str: @property def visits(self) -> int: """ - Returns Number of times this screen has been visited. + Number of times this screen has been visited. """ return self.__visits @@ -72,7 +70,7 @@ def visits(self) -> int: @property def actions(self) -> Set[str]: """ - Returns Actions that can be performed from this screen. + Action descriptions already recorded from this screen. """ return self.__actions @@ -80,7 +78,7 @@ def actions(self) -> Set[str]: @property def transitions(self) -> Dict[str, str]: """ - Returns Dictionary mapping action descriptions to destination hashes + Maps each recorded action description to its destination screen hash. """ return self.__transitions @@ -111,14 +109,12 @@ def should_explore(self, limit: int = 5) -> bool: class ExplorationGraph: """ - Graph of discovered screens and transitions. - Maintains the complete exploration state including all discovered screens and the transitions between them. + Graph of discovered screens and the transitions between them. """ def __init__(self) -> None: """ - Initialize empty exploration graph. - Creates empty nodes and edges collections. + Initialize an empty exploration graph. """ self.__nodes: Dict[str, ScreenNode] = {} @@ -127,7 +123,7 @@ def __init__(self) -> None: @property def nodes(self) -> Dict[str, ScreenNode]: """ - Returns All discovered screen nodes. + All discovered screen nodes, keyed by visual hash. """ return self.__nodes @@ -135,7 +131,7 @@ def nodes(self) -> Dict[str, ScreenNode]: @property def edges(self) -> List[Tuple[str, str, str]]: """ - Returns All transitions between screens. + All recorded transitions as (origin, action, destination) triples. """ return self.__edges @@ -185,8 +181,7 @@ def get_stats(self) -> Dict[str, Any]: class ActionGenerator: """ - Generates exploratory actions for unknown UI states. - Uses heuristics to select appropriate exploratory actions based on screen visit history and exploration state. + Generates exploratory actions, escalating tap to scroll to back as a screen's visit count grows. """ def __init__( diff --git a/src/fathom/schemas/gcc.py b/src/fathom/schemas/gcc.py index 78e26a82..da236de6 100644 --- a/src/fathom/schemas/gcc.py +++ b/src/fathom/schemas/gcc.py @@ -11,8 +11,7 @@ class CommitNode(BaseModel): """ - Tier 2: A versioned unit of memory. - Encapsulates a summarized segment of the execution log. + A versioned commit that summarizes one segment of the execution log and links to its parent. """ parent_id: Optional[str] = None @@ -25,7 +24,7 @@ class CommitNode(BaseModel): class BranchState(BaseModel): """ - Represents the state of a specific reasoning branch. + One reasoning branch: its head commit plus the uncommitted records logged since that head. """ name: str diff --git a/src/fathom/schemas/gemini_tools.py b/src/fathom/schemas/gemini_tools.py index 80fde06c..1dedb937 100644 --- a/src/fathom/schemas/gemini_tools.py +++ b/src/fathom/schemas/gemini_tools.py @@ -36,16 +36,10 @@ class GeminiDeltaTelemetry(BaseModel): """ Semantic delta signal schema used by Gemini tools at the raw tool boundary. - This model: - - Preserves raw provider values (including the case where the model omits - delta fields entirely). - - Performs only light type coercion (e.g., parsing floats, normalizing - anchor lists). - - Defers all semantic normalization (e.g., defaulting, score clamping) to - the core parser layer so that downstream code can distinguish: - * "Model says delta" (delta_observed is True/False) - * "Model is unsure/low conf" (delta_confidence in [0, 1] but small) - * "Model said nothing" (both fields are None) + Preserves raw provider values (including omitted delta fields) with only light coercion, deferring all + semantic normalization to the core parser so downstream code can distinguish three cases: + "model says delta" (``delta_observed`` True/False), "model is unsure" (``delta_confidence`` small but + in [0, 1]), and "model said nothing" (both fields None). """ previous_screen_summary: Optional[str] = None diff --git a/src/fathom/schemas/localization.py b/src/fathom/schemas/localization.py index a72d504b..6e53ae13 100644 --- a/src/fathom/schemas/localization.py +++ b/src/fathom/schemas/localization.py @@ -363,7 +363,7 @@ def resolved(self) -> bool: class LayoutMatchConfiguration(BaseModel): """ - Tunable's governing phrase clustering and target matching in the layout localizer. + Tunables governing phrase clustering and target matching in the layout localizer. """ model_config = ConfigDict(frozen=True, extra="forbid") diff --git a/src/fathom/schemas/observation.py b/src/fathom/schemas/observation.py index ed650374..85eae5e9 100644 --- a/src/fathom/schemas/observation.py +++ b/src/fathom/schemas/observation.py @@ -33,18 +33,12 @@ class ScreenRelation(StrEnum): class LoopObservation(BaseModel): """ - Structured loop-observation handed to the agent through the - ANALYZE prompt when the deterministic LoopDetector has accumulated - enough evidence to call the current sub-goal stuck. - - **Information, not control.** The observation is rendered into the - prompt as a system note. The agent decides whether to try a - different target or call ``ask_user``. The system does not override - the agent's next action. - - The schema is intentionally minimal — only what the agent needs to - reason about its trajectory. Raw timestamps, full screen hashes, - and other forensic detail stay in telemetry. + Structured loop-observation surfaced to the agent in the ANALYZE prompt once the deterministic + LoopDetector has enough evidence to call the current sub-goal stuck. + + Information, not control: rendered as a system note, it never overrides the agent's next action — the + agent decides whether to retarget or call ``ask_user``. Intentionally minimal; raw timestamps, full + screen hashes, and other forensic detail stay in telemetry. """ model_config = ConfigDict(frozen=True) diff --git a/src/fathom/schemas/orchestration.py b/src/fathom/schemas/orchestration.py index 5e4e2b88..bb6ffcff 100644 --- a/src/fathom/schemas/orchestration.py +++ b/src/fathom/schemas/orchestration.py @@ -60,13 +60,8 @@ class ExecutionContext(BaseModel): """ Context for tracking workflow execution. - Provides: - - Run-level metadata (workflow_id, run_id, timestamps) - - Step tracking with timing - - Serializable state for checkpointing - - Correlation IDs for distributed tracing - - Thread-safe for async operations. + Carries run-level metadata, timed step tracking, correlation IDs for tracing, + and serializable state for checkpointing. """ workflow_id: str = Field(..., description="ID of the workflow being executed") @@ -239,7 +234,7 @@ def from_checkpoint(cls, data: Dict[str, Any]) -> "ExecutionContext": class ExecutionRoadmap(BaseModel): """ - Roadmap for intent-based execution. + An intent paired with the ordered high-level steps planned to achieve it. """ intent: str = Field(..., description="Goal intent") @@ -248,7 +243,7 @@ class ExecutionRoadmap(BaseModel): class RunnerConfig(BaseModel): """ - Configuration for workflow runner. + Workflow runner settings: whether to checkpoint state and the callback that persists it. """ model_config = ConfigDict(frozen=True) diff --git a/src/fathom/schemas/perception.py b/src/fathom/schemas/perception.py index 83d9f84c..d7e90fa1 100644 --- a/src/fathom/schemas/perception.py +++ b/src/fathom/schemas/perception.py @@ -11,13 +11,10 @@ class DocumentAiCredentials(BaseModel): """ Provider credentials for the Document AI OCR adapter loaded from env vars. - ``credentials`` carries the same service-account material that the - Gemini adapter consumes (either an inline dict from - ``GOOGLE_APPLICATION_CREDENTIALS_JSON`` or a file path from - ``GOOGLE_APPLICATION_CREDENTIALS``). The adapter materializes it - into a :class:`google.oauth2.service_account.Credentials` instance - so Document AI authenticates against the same identity as Gemini — - no reliance on ambient ``gcloud`` ADC or GCE metadata. + ``credentials`` carries the same service-account material the Gemini adapter consumes — an inline dict + from ``GOOGLE_APPLICATION_CREDENTIALS_JSON`` or a path from ``GOOGLE_APPLICATION_CREDENTIALS`` — which + the adapter materializes into a :class:`google.oauth2.service_account.Credentials` so Document AI + authenticates as the same identity as Gemini, never via ambient ``gcloud`` ADC or GCE metadata. """ model_config = ConfigDict(frozen=True, extra="forbid") @@ -131,14 +128,12 @@ class JournalConfiguration(BaseModel): class PerceptionConfiguration(BaseModel): """ - Boot-time configuration for the perception layer (OCR, CV, icon, overlay). + Boot-time configuration for the perception layer. - Every perception subsystem is opt-in. When all four flags are False - the runtime falls back to the original XML+LLM-only flow: drawer - extracts elements from the platform XML, LLM grounds against that - manifest, snap-to-label resolves coordinates. Each ``enabled`` flag - turns its subsystem into a fallback contributor that augments the - manifest when the primary path has insufficient evidence. + Every subsystem is opt-in. With all disabled the runtime runs the XML+LLM-only flow (drawer extracts + elements from platform XML, the LLM grounds against that manifest, snap-to-label resolves + coordinates); each ``enabled`` flag makes its subsystem a fallback contributor that augments the + manifest when the primary path lacks evidence. """ model_config = ConfigDict(frozen=True, extra="forbid") diff --git a/src/fathom/schemas/resolution.py b/src/fathom/schemas/resolution.py index 2fd8f17b..0fd50ee3 100644 --- a/src/fathom/schemas/resolution.py +++ b/src/fathom/schemas/resolution.py @@ -81,9 +81,7 @@ class ResolveResult(BaseModel): """ Structured outcome of :class:`ReferenceResolutionService.resolve`. - Replaces the previous contract that returned only a (possibly - silently fuzz-matched) :class:`Action`. The status channel lets the - EXECUTE node branch deterministically: + The status channel lets the EXECUTE node branch deterministically: - ``RESOLVED`` → execute ``action``. - ``UNRESOLVED`` → emit a structured failed step that routes back @@ -92,8 +90,7 @@ class ResolveResult(BaseModel): ``candidates`` back to the agent for disambiguation on the next ANALYZE turn. - The ``action`` field always carries the resolved (or unresolved) - action so downstream consumers don't need to special-case None. + ``action`` always carries the resolved (or unresolved) action so consumers never special-case None. """ model_config = ConfigDict(frozen=True) diff --git a/src/fathom/schemas/run.py b/src/fathom/schemas/run.py index d46adfe9..ac79c13d 100644 --- a/src/fathom/schemas/run.py +++ b/src/fathom/schemas/run.py @@ -103,19 +103,10 @@ class Principal(BaseModel): """ Required identity context for a run, supplied by the host. - Every Fathom runtime entrypoint requires a fully resolved Principal. There - are no silent fallbacks: missing or empty fields fail at schema validation - time with a clear error that hosts can translate to client-friendly 4xx - responses. - - Fields: - tenant — tenant id, host-resolved from auth context. - operator — caller/user actor id, host-resolved from auth context. - agent — agent actor id, host-supplied (canonical: "agent:fathom"). - workspace — optional workspace boundary inside a tenant. - conversation — conversation thread id; the host MUST create the thread - beforehand (or generate the id locally) and pass it here. - The runner never invents one. + Every runtime entrypoint requires a fully resolved Principal with no silent fallbacks: missing or + empty fields fail at schema-validation time so hosts can return a client-friendly 4xx. The host MUST + create the ``conversation`` thread beforehand (or generate the id locally) and pass it here — the + runner never invents one. """ model_config = ConfigDict(frozen=True, extra="forbid") diff --git a/src/fathom/schemas/screens.py b/src/fathom/schemas/screens.py index 7efbfb93..94051735 100644 --- a/src/fathom/schemas/screens.py +++ b/src/fathom/schemas/screens.py @@ -57,13 +57,13 @@ def is_same_screen( """ Check if two screen states represent the same screen. - Uses Multi-Layer State Identity Algorithm (MLSIA): + Compares layered signals in order: 1. Activity check (must match) 2. Structural check (XML tree structure + content) - 3. Interaction check (Clickable elements) + 3. Interaction check (clickable elements) 4. Visual check (pHash distance) - Returns True ONLY if ALL available signals match. + Returns True only if all available signals match. """ if self.activity_hash != other.activity_hash: diff --git a/src/fathom/schemas/signing.py b/src/fathom/schemas/signing.py index fe860ca2..0375ccd0 100644 --- a/src/fathom/schemas/signing.py +++ b/src/fathom/schemas/signing.py @@ -34,7 +34,7 @@ class SigningOutcome(BaseModel): class GcsSigningConfiguration(BaseModel): """ - Configuration for the GCS artifact signer. + Credentials and URL lifetime the GCS signer uses to mint presigned artifact URLs. """ model_config = ConfigDict(frozen=True, extra="forbid") @@ -54,7 +54,7 @@ class GcsSigningConfiguration(BaseModel): class S3SigningConfiguration(BaseModel): """ - Configuration for the S3 artifact signer. + Region and URL lifetime the S3 signer uses to mint presigned artifact URLs. """ model_config = ConfigDict(frozen=True, extra="forbid") diff --git a/src/fathom/schemas/state.py b/src/fathom/schemas/state.py index fa96aa59..c0701b78 100644 --- a/src/fathom/schemas/state.py +++ b/src/fathom/schemas/state.py @@ -110,10 +110,9 @@ class LoopDetectorState(BaseModel): class InteractionTracker(BaseModel): """ - Elegantly tracks the cadence and repetition of agent interactions. + Tracks the run of consecutive same-type actions and per-type totals. - Provides deterministic data on consecutive action sequences to enforce - behavioral constraints (e.g., 'Don't swipe more than 3 times'). + Feeds behavioral limits such as "don't swipe more than 3 times" with a deterministic count. """ __consecutive_count: int = PrivateAttr(default=0) diff --git a/src/fathom/schemas/subgoal.py b/src/fathom/schemas/subgoal.py index 40d09cb5..bd082f71 100644 --- a/src/fathom/schemas/subgoal.py +++ b/src/fathom/schemas/subgoal.py @@ -63,7 +63,7 @@ class Progress(BaseModel): ) proof: Optional[PendingProof] = Field( default=None, - description="Additive checkpointed P5 evidence: a correlated command receipt ignored by live decisions until P6.", + description="Checkpointed command-receipt evidence, recorded additively and ignored by live decisions until final verification.", ) diff --git a/src/fathom/schemas/ui.py b/src/fathom/schemas/ui.py index 169862b4..b54d8175 100644 --- a/src/fathom/schemas/ui.py +++ b/src/fathom/schemas/ui.py @@ -80,7 +80,7 @@ def to_rectangle(self) -> Tuple[int, int, int, int]: class LabeledElement(BaseModel): """ - Represents a processed, drawable UI element with a label. + A UI element resolved for overlay drawing: its label, bounds, color, and attributes. """ label: str diff --git a/src/fathom/schemas/vision.py b/src/fathom/schemas/vision.py index c2705ca2..fb0f4f7b 100644 --- a/src/fathom/schemas/vision.py +++ b/src/fathom/schemas/vision.py @@ -84,11 +84,9 @@ class PastActionEntry(BaseModel): """ Typed annotation for one prior action surfaced into the vision prompt. - Built from the raw history dict already maintained by the memory/knowledge - layer rather than reconstructing the full :class:`Action` schema, because - the vision prompt sits downstream of that layer and only has the persisted - fields. ``kind`` is derived from the recorded action-type token, which is - authoritative for kind classification at serialization time. + Built from the memory/knowledge layer's raw history dict (the only fields available downstream), not + the full :class:`Action` schema. ``kind`` is derived from the recorded action-type token, which is + authoritative for kind classification. """ model_config = ConfigDict(frozen=True) diff --git a/src/fathom/settings/env.py b/src/fathom/settings/env.py index 71ada7cb..a93d1e51 100644 --- a/src/fathom/settings/env.py +++ b/src/fathom/settings/env.py @@ -26,15 +26,12 @@ PostgresSslMode, ) -# Calculate project root from this file's location PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent class FathomSettings(BaseSettings): """ - Global settings loaded from environment variables and .env file. - - This acts as the central point for accessing all environment configuration. + Global settings loaded from environment variables and the .env file. """ # Gemini settings @@ -137,7 +134,7 @@ class FathomSettings(BaseSettings): # Assets path assets_path: Path = Field(default=PROJECT_ROOT / "assets", alias="FATHOM_ASSETS_PATH") - # Interaction storage tunable's + # Interaction storage tunables interaction_backend: Optional[str] = Field( default=None, validation_alias=AliasChoices( @@ -242,9 +239,8 @@ class FathomSettings(BaseSettings): default=PROJECT_ROOT / "assets" / "logs", ) - # Perception subsystem toggles. CV stays off by default because its - # anonymous visual-control boxes are still too noisy for production - # grounding and can pollute both prompts and debug artifacts. + # Perception subsystem toggles. CV stays off by default because its anonymous visual-control boxes are still + # too noisy for production grounding and can pollute both prompts and debug artifacts. oracle_enabled: bool = Field(default=True, alias="FATHOM_ORACLE_ENABLED") observation_ocr_enabled: bool = Field(default=True, alias="FATHOM_OBSERVATION_OCR") @@ -253,10 +249,9 @@ class FathomSettings(BaseSettings): observation_overlay_enabled: bool = Field(default=True, alias="FATHOM_OBSERVATION_OVERLAY") observation_keyboard_enabled: bool = Field(default=False, alias="FATHOM_OBSERVATION_KEYBOARD") - # Ensemble vision-localizer (Gemini-vision + DocumentAI-layout) - # toggles. Enabled with both members so the supervise cascade can - # fall back to name-based localization when the XML manifest snap - # fails or returns a generic container. + # Ensemble vision-localizer (Gemini-vision + DocumentAI-layout) toggles. Enabled with both members so the + # supervise cascade can fall back to name-based localization when the XML manifest snap fails or returns a + # generic container. ensemble_localizer_enabled: bool = Field(default=True, alias="FATHOM_ENSEMBLE_LOCALIZER") ensemble_localizer_members: Optional[str] = Field( default="gemini_vision,document_ai_layout", @@ -266,8 +261,8 @@ class FathomSettings(BaseSettings): # Runtime journal adapter (local JSONL) toggle. journal_local_enabled: bool = Field(default=False, alias="FATHOM_JOURNAL_LOCAL") - # Document AI OCR provider credentials. Required only when - # observation_ocr_enabled is True and Document AI is the active provider. + # Document AI OCR provider credentials. Required only when observation_ocr_enabled is True and Document AI is + # the active provider. document_ai_project: Optional[str] = Field(default=None, alias="FATHOM_DOCUMENT_AI_PROJECT") document_ai_location: Optional[str] = Field(default=None, alias="FATHOM_DOCUMENT_AI_LOCATION") document_ai_processor: Optional[str] = Field(default=None, alias="FATHOM_DOCUMENT_AI_PROCESSOR") diff --git a/src/fathom/strategies/graph/exploration/builder.py b/src/fathom/strategies/graph/exploration/builder.py index b4410d05..c78a1198 100644 --- a/src/fathom/strategies/graph/exploration/builder.py +++ b/src/fathom/strategies/graph/exploration/builder.py @@ -34,7 +34,7 @@ def build( workflow = StateGraph(cast("Any", ExplorationGraphState)) nodes = ExplorationGraphFactory.build(self.__context) - # 1. Add Nodes + # Nodes workflow.add_node(NodeName.GROUND, nodes[NodeName.GROUND]) workflow.add_node(NodeName.SCAN, nodes[NodeName.SCAN]) @@ -44,7 +44,7 @@ def build( workflow.add_node(NodeName.NAVIGATE, nodes[NodeName.NAVIGATE]) workflow.add_node(NodeName.BFS_ROUTE, nodes[NodeName.BFS_ROUTE]) - # 2. Define Entry & Edges + # Entry point and edges workflow.set_entry_point(NodeName.GROUND) workflow.add_edge(NodeName.GROUND, NodeName.SCAN) diff --git a/src/fathom/strategies/graph/exploration/nodes.py b/src/fathom/strategies/graph/exploration/nodes.py index 0f7c2755..865bed84 100644 --- a/src/fathom/strategies/graph/exploration/nodes.py +++ b/src/fathom/strategies/graph/exploration/nodes.py @@ -32,8 +32,7 @@ class ExplorationNodeProvider: """ - Provides LangGraph nodes for application exploration. - Encapsulates dependencies and shared private logic. + Builds the exploration-graph nodes and owns the shared dependencies they read. """ def __init__(self, context: GraphContext) -> None: diff --git a/src/fathom/strategies/graph/intent/builder.py b/src/fathom/strategies/graph/intent/builder.py index cc6c310e..d8c46f67 100644 --- a/src/fathom/strategies/graph/intent/builder.py +++ b/src/fathom/strategies/graph/intent/builder.py @@ -152,12 +152,12 @@ def __route_after_analyze(self, state: IntentGraphState) -> str: f"planned_step_type={type(planned_step).__name__}" ) - # 1. Cancellation overrides everything + # Cancellation overrides everything if self.__context.is_cancelled: logger.info("[ROUTING] -> END (Cancelled)") return NodeName.END - # 2. Fatal Errors and Completion override retry logic + # Fatal errors and completion override retry logic if is_complete: reason = state.get(cast("str", CommonStateKey.COMPLETION_REASON), "") @@ -175,12 +175,12 @@ def __route_after_analyze(self, state: IntentGraphState) -> str: logger.info("[ROUTING] -> VERIFY (is_complete=True)") return NodeName.VERIFY - # 3. Soft Retries (e.g. missing elements, LLM asked to retry) + # Soft retries (e.g. missing elements, LLM asked to retry) if should_retry: logger.info("[ROUTING] -> GROUND (should_retry=True)") return NodeName.GROUND - # 4. Incomplete but missing step -> Error fallback + # Incomplete but missing step -> error fallback if not planned_step: logger.info(f"[ROUTING] -> GROUND (no planned_step, value={planned_step})") return NodeName.GROUND @@ -198,11 +198,9 @@ def __route_after_supervise(self, state: IntentGraphState) -> str: return NodeName.END if state.get(cast("str", IntentStateKey.SHOULD_RETRY)): - # SUPERVISE detected incomplete upstream state (missing - # capture or planned_step) and asked for a re-ground. - # Routing to GROUND avoids the silent EXECUTE→OBSERVE→RECORD - # cascade that would otherwise end with the misleading - # ``record.missing.step_result`` Sentry alert. + # SUPERVISE found incomplete upstream state (missing capture or planned_step) and asked for a + # re-ground; routing to GROUND avoids the silent EXECUTE->OBSERVE->RECORD cascade that would + # otherwise end with a misleading missing-step-result error. logger.info("[ROUTING] After SUPERVISE -> GROUND (should_retry=True)") return NodeName.GROUND diff --git a/src/fathom/strategies/graph/intent/nodes/analyze.py b/src/fathom/strategies/graph/intent/nodes/analyze.py index 9d1ecc7a..695d72fd 100644 --- a/src/fathom/strategies/graph/intent/nodes/analyze.py +++ b/src/fathom/strategies/graph/intent/nodes/analyze.py @@ -68,9 +68,7 @@ async def __call__(self, state: IntentGraphState) -> IntentGraphState: async def run(self, *, state: IntentGraphState) -> IntentGraphState: """ - Plan the next step using the Agent Planner. - - ERROR BOUNDARY: Wraps planning in try/except to handle LLM/network failures gracefully. + Plan the next step; LLM/network failures are contained so the graph continues. """ logger.info( @@ -146,7 +144,6 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: capture: ScreenCapture = screen_capture - # ERROR BOUNDARY: Wrap planning logic try: # Check injected context current_step = self.__provider.context.agent_state.step_count @@ -167,7 +164,7 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: elements = raw_elements # Use orientation-corrected capture dims so the planner's prompt - # advertises the actual canvas the screenshot was rendered on, ot the device-cached portrait template. + # advertises the actual canvas the screenshot was rendered on, not the device-cached portrait template. width = capture.width height = capture.height diff --git a/src/fathom/strategies/graph/intent/nodes/effect.py b/src/fathom/strategies/graph/intent/nodes/effect.py index 300812d1..6940b98b 100644 --- a/src/fathom/strategies/graph/intent/nodes/effect.py +++ b/src/fathom/strategies/graph/intent/nodes/effect.py @@ -383,13 +383,8 @@ async def __compare( image=post_capture.image, ) - # Post-action enrichment (OCR + icon + ensemble) was previously - # re-run here on every turn; the next GROUND call rebuilds the same - # observation from a fresh capture before any planner reads it, so - # the only downstream consumers of the post-action enrichment were - # history and debug artefacts. Skipping the call drops a full - # OCR/icon round-trip per step. Pre-action observation flows - # through as the fallback on the next ANALYZE turn. + # Skip post-action enrichment: the next GROUND call rebuilds the observation from a fresh capture + # before any planner reads it, so the pre-action observation serves as the fallback this turn. post_observation: Optional[ScreenObservation] = None logger.info( "Post-action enrichment skipped", diff --git a/src/fathom/strategies/graph/intent/nodes/ground.py b/src/fathom/strategies/graph/intent/nodes/ground.py index 87d528af..f15d8a1a 100644 --- a/src/fathom/strategies/graph/intent/nodes/ground.py +++ b/src/fathom/strategies/graph/intent/nodes/ground.py @@ -41,10 +41,7 @@ async def __call__(self, state: IntentGraphState) -> IntentGraphState: async def run(self, *, state: IntentGraphState) -> IntentGraphState: """ - Capture the screen and update state. - - ERROR BOUNDARY: All exceptions are caught and converted to terminal states - to ensure graph execution completes gracefully even on device failures. + Capture the screen and update state; exceptions convert to terminal states so the graph always completes. """ logger.info( @@ -72,7 +69,6 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: }, ) - # ERROR BOUNDARY: Wrap entire node in try/except try: if await self.__provider.is_cancelled(): logger.warning( @@ -119,7 +115,7 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: start_time = time.time() - # 1. Capture State (Screenshot + optional hierarchy) + # Capture state (screenshot + optional hierarchy) screen = await self.__provider.context.perception.perceive( session_id=self.__provider.context.workflow_id, step_number=self.__provider.context.agent_state.step_count + 1, @@ -150,7 +146,7 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: }, ) - # 2. Capture Dimensions (Independent hardware metadata) + # Capture dimensions (independent hardware metadata) width = screen.width height = screen.height logger.info(f"Device dimension is {height=}x{width=}") diff --git a/src/fathom/strategies/graph/intent/nodes/provider.py b/src/fathom/strategies/graph/intent/nodes/provider.py index 562b92f6..b1820546 100644 --- a/src/fathom/strategies/graph/intent/nodes/provider.py +++ b/src/fathom/strategies/graph/intent/nodes/provider.py @@ -18,8 +18,7 @@ class IntentNodeProvider: """ - Provides LangGraph nodes for intent execution. - Encapsulates dependencies and shared private logic. + Builds the intent-graph nodes and owns the shared dependencies they read. """ def __init__( diff --git a/src/fathom/strategies/graph/intent/nodes/record.py b/src/fathom/strategies/graph/intent/nodes/record.py index 83923837..dafeda76 100644 --- a/src/fathom/strategies/graph/intent/nodes/record.py +++ b/src/fathom/strategies/graph/intent/nodes/record.py @@ -74,9 +74,7 @@ async def __call__(self, state: IntentGraphState) -> IntentGraphState: async def run(self, *, state: IntentGraphState) -> IntentGraphState: """ - Record the execution result. - - ERROR BOUNDARY: Wraps recording in try/except to handle storage/telemetry failures gracefully. + Record the execution result; storage/telemetry failures are contained so the graph continues. """ logger.info( @@ -143,7 +141,6 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: step_result: StepResult = recorded_step record_watch = Stopwatch() - # ERROR BOUNDARY: Wrap recording logic try: # Record in agent state (internal bookkeeping, always done) self.__provider.context.agent_state.record_step(result=step_result) diff --git a/src/fathom/strategies/graph/intent/nodes/supervise.py b/src/fathom/strategies/graph/intent/nodes/supervise.py index 52c4f09e..1f709021 100644 --- a/src/fathom/strategies/graph/intent/nodes/supervise.py +++ b/src/fathom/strategies/graph/intent/nodes/supervise.py @@ -131,11 +131,8 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: step = planned_step.model_copy(update={"action": resolve_result.action}) if resolve_result.status == ResolveStatus.RESOLVED: - # Perception cascade — Stage 1: snap_to_label against the - # merged manifest. ``state[ELEMENTS]`` contains XML, OCR, - # icon, and CV entries thanks to ManifestMerger, so a - # successful snap may be sourced from any perception layer, - # not only XML. + # A successful snap may bind against any perception layer: ManifestMerger populates + # ``state[ELEMENTS]`` with XML, OCR, icon, and CV entries, not only XML. logger.info( "Perception cascade Stage 1 (snap) committed", extra={ @@ -148,10 +145,8 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: ) localization = self.__localization_from_snap(step=step) else: - # Stage 2: vision-localizer (Gemini) + local-localizer - # (DocumentAI / icon templates / overlay pixels) via the - # gate. Runs when the manifest snap could not bind the - # target to a concrete bounds. + # Runs when the manifest snap could not bind the target to concrete bounds: fall back to the + # vision-localizer plus local-localizer (icon templates / overlay pixels) via the gate. snap_outcome = resolve_result.unresolved_kind logger.info( "Perception cascade Stage 2 (vision-localizer) engaged", diff --git a/src/fathom/strategies/graph/intent/nodes/verify.py b/src/fathom/strategies/graph/intent/nodes/verify.py index d1edda56..977c0246 100644 --- a/src/fathom/strategies/graph/intent/nodes/verify.py +++ b/src/fathom/strategies/graph/intent/nodes/verify.py @@ -110,7 +110,7 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: start_time = time.time() - # 1. Capture the latest screen state + # Capture the latest screen state try: capture = await self.__provider.context.perception.perceive( session_id=self.__provider.context.workflow_id, @@ -169,7 +169,7 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: self.__provider.persistence.persist(result=result) return result - # 2. Construct binary validation prompt from explicit VERIFY mode. + # Construct binary validation prompt from explicit VERIFY mode. user_guidance = [ guidance.content for guidance in self.__provider.context.context_manager.get_user_guidance() @@ -180,7 +180,7 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: user_guidance=user_guidance, ) - # 3. Ask the LLM + # Ask the LLM await self.__provider.context.phase.verifying(intent=self.__provider.context.intent) try: llm_result = await self.__provider.context.llm.generate( @@ -245,7 +245,6 @@ async def run(self, *, state: IntentGraphState) -> IntentGraphState: ) # Verification artefact emission suppressed; no downstream reader today. - # await self.__emit_verification_artifact(capture=capture, complete=is_truly_complete, reason=reason) if ( is_truly_complete diff --git a/tests/__init__.py b/tests/__init__.py index bbe1a6be..0cd794cc 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -1 +1,3 @@ -"""Fathom test package.""" +""" +Fathom test package. +""" diff --git a/tests/fixtures/coordinate/README.md b/tests/fixtures/coordinate/README.md deleted file mode 100644 index 0cee32f1..00000000 --- a/tests/fixtures/coordinate/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Coordinate-dispatch fixtures - -Pinned screen captures + element hierarchies that exercise -:class:`fathom.utils.coordinates.CoordinateConverter` against real -production failure modes. The cases primarily pin the iOS retina -coordinate-space mismatch (XML logical -> drawer scaled to -device-pixel -> converter previously clamped against logical screen, -yielding a garbage dispatched tap coordinate). - -## Layout - -``` -coordinate/ -├── ios/ # platform tier -│ ├── tap/ # action-type tier -│ │ ├── 001/ # numbered case -│ │ │ ├── case.yaml # self-describing metadata -│ │ │ ├── hierarchy.xml # captured XML hierarchy -│ │ │ └── screenshot.png # captured screenshot -│ │ ├── 002/ -│ │ └── ... -│ ├── swipe/ # reserved -│ └── type/ # reserved -├── android/ -│ ├── tap/ -│ ├── swipe/ -│ └── type/ -├── output/ # renderer writes annotated + traced PNGs here (gitignored) -└── README.md -``` - -## Adding a new case - -1. Pick the platform tier (`ios/` or `android/`). -2. Pick the action-type tier (`tap/`, `swipe/`, `type/`, ...). -3. Create the next numbered directory (e.g. `005/`). -4. Drop `case.yaml`, `hierarchy.xml`, `screenshot.png` inside. - -The test loader walks every numbered directory under each action-type -tier; no Python edit is required to register a new case. diff --git a/tests/fixtures/coordinate/android/swipe/001/dimensions.txt b/tests/fixtures/coordinate/android/swipe/001/dimensions.txt deleted file mode 100644 index cd91fa0a..00000000 --- a/tests/fixtures/coordinate/android/swipe/001/dimensions.txt +++ /dev/null @@ -1 +0,0 @@ -1080x2340 diff --git a/tests/fixtures/coordinate/android/swipe/001/hierarchy.xml b/tests/fixtures/coordinate/android/swipe/001/hierarchy.xml deleted file mode 100644 index 6a72c0d7..00000000 --- a/tests/fixtures/coordinate/android/swipe/001/hierarchy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/tests/fixtures/coordinate/android/swipe/002/hierarchy.xml b/tests/fixtures/coordinate/android/swipe/002/hierarchy.xml deleted file mode 100644 index 5538251c..00000000 --- a/tests/fixtures/coordinate/android/swipe/002/hierarchy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/001/case.yaml b/tests/fixtures/coordinate/ios/tap/001/case.yaml deleted file mode 100644 index e9d57009..00000000 --- a/tests/fixtures/coordinate/ios/tap/001/case.yaml +++ /dev/null @@ -1,26 +0,0 @@ -platform: ios -label_id: "1" -target_text: "Confirm & proceed" -description: | - Outer container button at the screen footer. XML element bounds are - (32, 828, 366, 54) in logical points. After parser scale-factor x3, - the manifest carries device-pixel bounds (96, 2484, 1098, 162). - Pixel y=2484 is greater than logical screen height (932), so the - buggy clamp truncates y to 931 and height to 1 — dispatched coord - drifts to logical (263, 931), 1 px above the home-indicator edge. -screen: - logical: - width: 430 - height: 932 -expected: - resolved_pixel_bounds: - x: 96 - y: 2484 - width: 1098 - height: 162 - dispatched_logical: - x: 215 - y: 855 - observed_buggy_dispatched_logical: - x: 263 - y: 931 diff --git a/tests/fixtures/coordinate/ios/tap/001/hierarchy.xml b/tests/fixtures/coordinate/ios/tap/001/hierarchy.xml deleted file mode 100644 index f2cd0de4..00000000 --- a/tests/fixtures/coordinate/ios/tap/001/hierarchy.xml +++ /dev/null @@ -1,320 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/001/screenshot.png b/tests/fixtures/coordinate/ios/tap/001/screenshot.png deleted file mode 100644 index 820fb435..00000000 Binary files a/tests/fixtures/coordinate/ios/tap/001/screenshot.png and /dev/null differ diff --git a/tests/fixtures/coordinate/ios/tap/002/case.yaml b/tests/fixtures/coordinate/ios/tap/002/case.yaml deleted file mode 100644 index 62de4441..00000000 --- a/tests/fixtures/coordinate/ios/tap/002/case.yaml +++ /dev/null @@ -1,26 +0,0 @@ -platform: ios -label_id: "8" -target_text: "Confirm & proceed" -description: | - Inner static-text element nested inside the footer container button. - XML element bounds are (140, 846, 150, 18) in logical points. After - scale-factor x3 the manifest carries (420, 2538, 450, 54) device-pixel. - Same clamp pathology as the footer case — y truncates to 931 and the - width gets clipped against the screen right edge — yielding the - spurious (425, 931) production dispatch. -screen: - logical: - width: 430 - height: 932 -expected: - resolved_pixel_bounds: - x: 420 - y: 2538 - width: 450 - height: 54 - dispatched_logical: - x: 215 - y: 855 - observed_buggy_dispatched_logical: - x: 425 - y: 931 diff --git a/tests/fixtures/coordinate/ios/tap/002/hierarchy.xml b/tests/fixtures/coordinate/ios/tap/002/hierarchy.xml deleted file mode 100644 index b5653113..00000000 --- a/tests/fixtures/coordinate/ios/tap/002/hierarchy.xml +++ /dev/null @@ -1,320 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/002/screenshot.png b/tests/fixtures/coordinate/ios/tap/002/screenshot.png deleted file mode 100644 index 6c9d34a9..00000000 Binary files a/tests/fixtures/coordinate/ios/tap/002/screenshot.png and /dev/null differ diff --git a/tests/fixtures/coordinate/ios/tap/003/case.yaml b/tests/fixtures/coordinate/ios/tap/003/case.yaml deleted file mode 100644 index 394d51ab..00000000 --- a/tests/fixtures/coordinate/ios/tap/003/case.yaml +++ /dev/null @@ -1,24 +0,0 @@ -platform: ios -label_id: "24" -target_text: "Preparing your order banner" -description: | - Promotional banner near the bottom of the home screen, above the - navigation tabs. XML logical bounds (72, 800, 128, 15); device-pixel - (216, 2400, 384, 45). Same below-clamp pathology — production - dispatched (323, 931) on the home-indicator edge. -screen: - logical: - width: 430 - height: 932 -expected: - resolved_pixel_bounds: - x: 216 - y: 2400 - width: 384 - height: 45 - dispatched_logical: - x: 136 - y: 807 - observed_buggy_dispatched_logical: - x: 323 - y: 931 diff --git a/tests/fixtures/coordinate/ios/tap/003/hierarchy.xml b/tests/fixtures/coordinate/ios/tap/003/hierarchy.xml deleted file mode 100644 index e1d1c555..00000000 --- a/tests/fixtures/coordinate/ios/tap/003/hierarchy.xml +++ /dev/null @@ -1,818 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/003/screenshot.png b/tests/fixtures/coordinate/ios/tap/003/screenshot.png deleted file mode 100644 index 8a07b6fb..00000000 Binary files a/tests/fixtures/coordinate/ios/tap/003/screenshot.png and /dev/null differ diff --git a/tests/fixtures/coordinate/ios/tap/004/case.yaml b/tests/fixtures/coordinate/ios/tap/004/case.yaml deleted file mode 100644 index fdbf52c8..00000000 --- a/tests/fixtures/coordinate/ios/tap/004/case.yaml +++ /dev/null @@ -1,26 +0,0 @@ -platform: ios -label_id: "47" -target_text: "Food tab" -description: | - Header tab icon near the top-left of the screen. XML logical bounds - (16, 120, 88, 82); device-pixel (48, 359, 264, 247). Pixel y=359 is - inside the logical screen height (932) so the clamp does NOT fire, - but production still dispatched (180, 482) — a pixel-space coord - interpreted as logical, landing in the deals carousel mid-screen. - Demonstrates the bug fires even without clamp activation. -screen: - logical: - width: 430 - height: 932 -expected: - resolved_pixel_bounds: - x: 48 - y: 359 - width: 264 - height: 247 - dispatched_logical: - x: 60 - y: 160 - observed_buggy_dispatched_logical: - x: 180 - y: 482 diff --git a/tests/fixtures/coordinate/ios/tap/004/hierarchy.xml b/tests/fixtures/coordinate/ios/tap/004/hierarchy.xml deleted file mode 100644 index 11aef66f..00000000 --- a/tests/fixtures/coordinate/ios/tap/004/hierarchy.xml +++ /dev/null @@ -1,818 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/004/screenshot.png b/tests/fixtures/coordinate/ios/tap/004/screenshot.png deleted file mode 100644 index dd0d9f57..00000000 Binary files a/tests/fixtures/coordinate/ios/tap/004/screenshot.png and /dev/null differ diff --git a/tests/fixtures/coordinate/ios/tap/005/case.yaml b/tests/fixtures/coordinate/ios/tap/005/case.yaml deleted file mode 100644 index 1249622c..00000000 --- a/tests/fixtures/coordinate/ios/tap/005/case.yaml +++ /dev/null @@ -1,13 +0,0 @@ -platform: ios -description: | - HmrHD execution session, step 3 capture (post-back navigation). Production - Fathom emitted a non-spatial BACK action for this step (no Resolution - snap, no tap dispatched). The screen is included as a property-only - fixture: BoundsGenerator must produce a manifest and the current - CoordinateConverter must dispatch every parsed element inside its own - logical bbox. No pinned label is asserted because no production tap - coordinate exists for this step. -screen: - logical: - width: 430 - height: 932 diff --git a/tests/fixtures/coordinate/ios/tap/005/hierarchy.xml b/tests/fixtures/coordinate/ios/tap/005/hierarchy.xml deleted file mode 100644 index b5653113..00000000 --- a/tests/fixtures/coordinate/ios/tap/005/hierarchy.xml +++ /dev/null @@ -1,320 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/005/screenshot.png b/tests/fixtures/coordinate/ios/tap/005/screenshot.png deleted file mode 100644 index 496401ea..00000000 Binary files a/tests/fixtures/coordinate/ios/tap/005/screenshot.png and /dev/null differ diff --git a/tests/fixtures/coordinate/ios/tap/006/case.yaml b/tests/fixtures/coordinate/ios/tap/006/case.yaml deleted file mode 100644 index dacf6937..00000000 --- a/tests/fixtures/coordinate/ios/tap/006/case.yaml +++ /dev/null @@ -1,14 +0,0 @@ -platform: ios -description: | - HmrHD execution session, step 4 capture. Production grounding crashed - with TimeoutError before any planner action was emitted (no Resolution - snap, no tap dispatched). Carried as a property-only fixture: every - element BoundsGenerator extracts from this XML must dispatch inside - its own logical bbox under the current CoordinateConverter. Exists to - exercise the manifest pipeline on a screen the production run never - managed to act on, ensuring the converter holds across crash-adjacent - captures too. -screen: - logical: - width: 430 - height: 932 diff --git a/tests/fixtures/coordinate/ios/tap/006/hierarchy.xml b/tests/fixtures/coordinate/ios/tap/006/hierarchy.xml deleted file mode 100644 index dfc80a3e..00000000 --- a/tests/fixtures/coordinate/ios/tap/006/hierarchy.xml +++ /dev/null @@ -1,320 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/006/screenshot.png b/tests/fixtures/coordinate/ios/tap/006/screenshot.png deleted file mode 100644 index 04685c7a..00000000 Binary files a/tests/fixtures/coordinate/ios/tap/006/screenshot.png and /dev/null differ diff --git a/tests/fixtures/coordinate/ios/tap/007/case.yaml b/tests/fixtures/coordinate/ios/tap/007/case.yaml deleted file mode 100644 index 899a25ea..00000000 --- a/tests/fixtures/coordinate/ios/tap/007/case.yaml +++ /dev/null @@ -1,20 +0,0 @@ -platform: ios -description: | - gtLmU session 1, step 4 capture (pre-search-icon tap). Production - dispatched via Perception cascade Stage 2 (vision-localizer), not the - XML Stage-1 snap that the dispatch bug afflicts — observed tap was - logical (429, 204), workflow gtLmU_s1_h0e936a. The fixture is carried - to characterise the converter on a screen whose real production path - bypassed the buggy snap altogether: every element parsed from the XML - must still dispatch inside its own logical bbox under the current - CoordinateConverter, proving the fix is neutral on non-snap surfaces. -screen: - logical: - width: 430 - height: 932 -production_dispatch: - source: stage2_vision_localizer - workflow_id: gtLmU_s1_h0e936a - dispatched_logical: - x: 429 - y: 204 diff --git a/tests/fixtures/coordinate/ios/tap/007/hierarchy.xml b/tests/fixtures/coordinate/ios/tap/007/hierarchy.xml deleted file mode 100644 index 11aef66f..00000000 --- a/tests/fixtures/coordinate/ios/tap/007/hierarchy.xml +++ /dev/null @@ -1,818 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/007/screenshot.png b/tests/fixtures/coordinate/ios/tap/007/screenshot.png deleted file mode 100644 index 24193959..00000000 Binary files a/tests/fixtures/coordinate/ios/tap/007/screenshot.png and /dev/null differ diff --git a/tests/fixtures/coordinate/ios/tap/008/case.yaml b/tests/fixtures/coordinate/ios/tap/008/case.yaml deleted file mode 100644 index 489abf46..00000000 --- a/tests/fixtures/coordinate/ios/tap/008/case.yaml +++ /dev/null @@ -1,18 +0,0 @@ -platform: ios -description: | - gtLmU session 2, step 1 capture (re-entry after session 1 completion). - Production dispatched via Perception cascade Stage 2 (vision-localizer) - with the same Search-icon intent — observed tap was logical (429, 204), - workflow gtLmU_s2_ha8759a. Carried as a property-only fixture covering - the session-boundary re-entry path: parser + converter pipeline must - hold on a freshly captured screen at the start of a new session. -screen: - logical: - width: 430 - height: 932 -production_dispatch: - source: stage2_vision_localizer - workflow_id: gtLmU_s2_ha8759a - dispatched_logical: - x: 429 - y: 204 diff --git a/tests/fixtures/coordinate/ios/tap/008/hierarchy.xml b/tests/fixtures/coordinate/ios/tap/008/hierarchy.xml deleted file mode 100644 index 6c38c689..00000000 --- a/tests/fixtures/coordinate/ios/tap/008/hierarchy.xml +++ /dev/null @@ -1,902 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/fixtures/coordinate/ios/tap/008/screenshot.png b/tests/fixtures/coordinate/ios/tap/008/screenshot.png deleted file mode 100644 index 2fbb9f12..00000000 Binary files a/tests/fixtures/coordinate/ios/tap/008/screenshot.png and /dev/null differ diff --git a/tests/fixtures/coordinate/output/.gitignore b/tests/fixtures/coordinate/output/.gitignore deleted file mode 100644 index d6b7ef32..00000000 --- a/tests/fixtures/coordinate/output/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore diff --git a/tests/fixtures/execution/android/scroll/001/before.png b/tests/fixtures/execution/android/scroll/001/before.png deleted file mode 100644 index 3c93d2ed..00000000 Binary files a/tests/fixtures/execution/android/scroll/001/before.png and /dev/null differ diff --git a/tests/fixtures/perception/frames/detail.png b/tests/fixtures/perception/frames/detail.png deleted file mode 100644 index 45b2efc9..00000000 Binary files a/tests/fixtures/perception/frames/detail.png and /dev/null differ diff --git a/tests/fixtures/perception/frames/home.png b/tests/fixtures/perception/frames/home.png deleted file mode 100644 index 4514aeb9..00000000 Binary files a/tests/fixtures/perception/frames/home.png and /dev/null differ diff --git a/tests/fixtures/perception/frames/search.png b/tests/fixtures/perception/frames/search.png deleted file mode 100644 index f73e0546..00000000 Binary files a/tests/fixtures/perception/frames/search.png and /dev/null differ diff --git a/tests/fixtures/vision/corpus.py b/tests/fixtures/vision/corpus.py deleted file mode 100644 index bc23ecf0..00000000 --- a/tests/fixtures/vision/corpus.py +++ /dev/null @@ -1,507 +0,0 @@ -from __future__ import annotations - -from typing import Optional, Tuple - -from pydantic import Field, model_validator -from tests.support.vision.models import LabelSource - -from fathom.constants.assessment import VisualVerdict -from fathom.constants.success import SuccessKind -from fathom.schemas.base.common import NonBlank, SealedModel - -AMAZON_SHOPPING = "com.amazon.mShop.android.shopping" -AMAZON_MUSIC = "com.amazon.mp3" -MEESHO = "com.meesho.supply" -LAUNCHER = "com.android.launcher" -PERMISSION_UI = "com.google.android.permissioncontroller" -CHATGPT = "com.openai.chatgpt" -CONTROLLED = "controlled.capture" - -AMAZON_RUN = "assets/traces/2026-07-31/7f64d39f10e440d5ad9334acf15094ce" -AMAZON_MUSIC_RUN = "assets/traces/2026-07-31/b2282f11417c438da2c8d0d3059b02f8" -AMAZON_SIGNIN_RUN = "assets/traces/2026-07-31/aa12a78e5a054aa2baf931e4c83b1f89" -CHATGPT_AD_RUN = "assets/traces/2026-07-31/3b4fd954ab4a4841937ed7c3a718f5a9" -MEESHO_RUN = "assets/traces/2026-07-29/4ee2b518a161418fba58feaae2952844" -MEESHO_PERMISSION_RUN = "assets/traces/2026-07-29/bdcb0d1e146b4bd696d3b300d543c629" -CONTROLLED_SOURCE = "controlled/programmatic" - - -class VisionCase(SealedModel): - """ - A data-only visual-assessment case: real pixels, the threaded assertion, and its typed ground-truth. - """ - - name: NonBlank = Field(description="Stable case identifier used in reports.") - screenshot: NonBlank = Field( - description="File name under screens/ holding the captured pixels." - ) - app: NonBlank = Field(description="Application exercised by the screen.") - package: NonBlank = Field(description="Foreground package truth on the captured screen.") - assertion: NonBlank = Field( - description="Exact assertion threaded into the production VLM prompt." - ) - goal_kind: SuccessKind = Field(description="Success kind of the active goal driving this turn.") - expected_verdict: VisualVerdict = Field( - description="Oracle verdict a correct model must return." - ) - truth_satisfied: bool = Field( - description="Oracle: whether the observed goal is genuinely satisfied here." - ) - authority_package: Optional[str] = Field( - default=None, - description="Bound TargetAuthority package for the goal, or None when unbound.", - ) - scenario: NonBlank = Field(description="Screen type or adversarial trap this case represents.") - provenance: NonBlank = Field( - description="Source of the pixels: a trace run path or a controlled tag." - ) - label_source: LabelSource = Field( - description="Whether the ground-truth was assigned by human or programmatic means." - ) - critical_negative: bool = Field( - description="Whether an effective false positive here blocks the Slice-3 cutover." - ) - - @property - def expected_admission(self) -> bool: - """ - Whether the effective shadow rule should advance the goal on this case. - """ - - return self.goal_kind is SuccessKind.OBSERVED and self.truth_satisfied - - @model_validator(mode="after") - def __consistent_oracle(self) -> "VisionCase": - """ - Keep the expected verdict consistent with the satisfaction oracle for observed goals. - """ - - if self.goal_kind is SuccessKind.OBSERVED: - expected = ( - VisualVerdict.SATISFIED if self.truth_satisfied else VisualVerdict.NOT_SATISFIED - ) - if self.expected_verdict is not expected: - raise ValueError( - "Observed case expected_verdict must match its truth_satisfied oracle." - ) - return self - - -AMAZON_CASES: Tuple[VisionCase, ...] = ( - VisionCase( - name="launcher_home", - screenshot="launcher_home.png", - app="Launcher", - package=LAUNCHER, - assertion="The Amazon shopping app is open in the foreground.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=AMAZON_SHOPPING, - scenario="Clean negative: launcher home with no Amazon surface present.", - provenance=AMAZON_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="icon_visible_not_open", - screenshot="shopping_folder_amazon_icon.png", - app="Launcher", - package=LAUNCHER, - assertion="The Amazon shopping app is open in the foreground.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=AMAZON_SHOPPING, - scenario="False positive: Amazon icon prominent in an open folder, app not launched.", - provenance=AMAZON_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="amazon_versus_amazon_music", - screenshot="app_drawer_amazon_and_music.png", - app="Launcher", - package=LAUNCHER, - assertion="The Amazon shopping app, not Amazon Music, is open in the foreground.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=AMAZON_SHOPPING, - scenario="Wrong-target false positive: Amazon and Amazon Music icons adjacent in the drawer.", - provenance=AMAZON_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="amazon_home_open", - screenshot="amazon_home.png", - app="Amazon", - package=AMAZON_SHOPPING, - assertion="The Amazon shopping app home screen is open.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.SATISFIED, - truth_satisfied=True, - authority_package=AMAZON_SHOPPING, - scenario="Clean positive: the Amazon home screen is genuinely in the foreground.", - provenance=AMAZON_RUN, - label_source=LabelSource.HUMAN, - critical_negative=False, - ), - VisionCase( - name="suggestions_not_results", - screenshot="amazon_search_suggestions_ghar_soap.png", - app="Amazon", - package=AMAZON_SHOPPING, - assertion="The Amazon search results page for 'ghar soap' is displayed with a list of purchasable product cards.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=AMAZON_SHOPPING, - scenario="False positive: autocomplete suggestions with thumbnails are not the results grid.", - provenance=AMAZON_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="search_text_entered", - screenshot="amazon_search_suggestions_ghar_soap.png", - app="Amazon", - package=AMAZON_SHOPPING, - assertion="The Amazon search field contains the typed query 'ghar soap'.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.SATISFIED, - truth_satisfied=True, - authority_package=AMAZON_SHOPPING, - scenario="Clean positive: the assertion names exactly the observable typed-query state.", - provenance=AMAZON_RUN, - label_source=LabelSource.HUMAN, - critical_negative=False, - ), - VisionCase( - name="cart_not_confirmed", - screenshot="amazon_home.png", - app="Amazon", - package=AMAZON_SHOPPING, - assertion="A 'ghar soap' product has been added to the cart and an add-to-cart confirmation is visible.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=AMAZON_SHOPPING, - scenario="False positive: cart badge shows pre-existing items, no 'ghar soap' add confirmation.", - provenance=AMAZON_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="amazon_results_not_on_home", - screenshot="amazon_home.png", - app="Amazon", - package=AMAZON_SHOPPING, - assertion="The Amazon search results for 'ghar soap' are displayed with product listings.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=AMAZON_SHOPPING, - scenario="Long-but-progressing: correct app and home reached, but the results goal is not yet met.", - provenance=AMAZON_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="amazon_login_absent", - screenshot="amazon_home_signin_promo.png", - app="Amazon", - package=AMAZON_SHOPPING, - assertion="A login screen requiring the user to enter sign-in credentials is displayed.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=AMAZON_SHOPPING, - scenario="Login absent: a dismissible 'Sign in' promo banner on home is not a login screen.", - provenance=AMAZON_SIGNIN_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="amazon_music_wrong_app", - screenshot="amazon_music_interstitial.png", - app="Amazon Music", - package=AMAZON_MUSIC, - assertion="The Amazon shopping app is open in the foreground.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=AMAZON_SHOPPING, - scenario="Wrong application: Amazon Music Unlimited opened instead of Amazon shopping.", - provenance=AMAZON_MUSIC_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), -) - - -MEESHO_CASES: Tuple[VisionCase, ...] = ( - VisionCase( - name="meesho_results_present", - screenshot="meesho_search_results.png", - app="Meesho", - package=MEESHO, - assertion="The Meesho search results for 'ghar soap' are displayed with a grid of purchasable product cards.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.SATISFIED, - truth_satisfied=True, - authority_package=MEESHO, - scenario="Clean positive: a genuine Meesho results grid with product cards and prices.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=False, - ), - VisionCase( - name="meesho_results_repeated_different_goal", - screenshot="meesho_search_results.png", - app="Meesho", - package=MEESHO, - assertion="A single product detail page for one ghar soap product is open.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=MEESHO, - scenario="Repeated screen under a different goal: the results grid is not a product detail page.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="meesho_suggestions_not_results", - screenshot="meesho_search_typed_suggestions.png", - app="Meesho", - package=MEESHO, - assertion="The Meesho search results grid for 'ghar soaps' is displayed with product cards.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=MEESHO, - scenario="False positive: a typed-query autocomplete list is not the results grid.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="meesho_search_text_entered", - screenshot="meesho_search_typed_suggestions.png", - app="Meesho", - package=MEESHO, - assertion="The Meesho search field contains the typed query 'Ghar soaps'.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.SATISFIED, - truth_satisfied=True, - authority_package=MEESHO, - scenario="Clean positive: query typed into the search field but not yet submitted.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=False, - ), - VisionCase( - name="meesho_product_detail_open", - screenshot="meesho_product_detail.png", - app="Meesho", - package=MEESHO, - assertion="A product detail page for a ghar soap product is open.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.SATISFIED, - truth_satisfied=True, - authority_package=MEESHO, - scenario="Visual goal already satisfied on arrival: a single-product detail page.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=False, - ), - VisionCase( - name="meesho_detail_not_results", - screenshot="meesho_product_detail.png", - app="Meesho", - package=MEESHO, - assertion="A grid of multiple search-result product cards is displayed.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=MEESHO, - scenario="Product grid versus details: a detail page is not a multi-card results grid.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="rating_wrong_attribute", - screenshot="meesho_product_detail.png", - app="Meesho", - package=MEESHO, - assertion="The product's customer rating is at least 4.2 out of 5.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=MEESHO, - scenario="Wrong attribute above threshold: a 4.9 supplier rating must not satisfy a customer-rating predicate.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="meesho_product_not_added", - screenshot="meesho_product_detail.png", - app="Meesho", - package=MEESHO, - assertion="The product has been added to the cart and an added-to-cart confirmation is visible.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=MEESHO, - scenario="Product not selected: the detail page shows Buy Now, with no add-to-cart confirmation.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="meesho_permission_present", - screenshot="meesho_permission_contacts.png", - app="Meesho", - package=PERMISSION_UI, - assertion="A system permission dialog requesting access to contacts is visible.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.SATISFIED, - truth_satisfied=True, - authority_package=None, - scenario="Permission dialog present: an Android contacts-access prompt is on screen.", - provenance=MEESHO_PERMISSION_RUN, - label_source=LabelSource.HUMAN, - critical_negative=False, - ), - VisionCase( - name="meesho_permission_blocks_results", - screenshot="meesho_permission_contacts.png", - app="Meesho", - package=PERMISSION_UI, - assertion="The Meesho search results for 'ghar soap' are displayed.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=MEESHO, - scenario="Permission dialog blocks the goal; the foreground is the permission controller, not Meesho.", - provenance=MEESHO_PERMISSION_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="meesho_tap_command_no_assessment", - screenshot="meesho_search_results.png", - app="Meesho", - package=MEESHO, - assertion="Tap the first product card in the results.", - goal_kind=SuccessKind.COMMAND, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=MEESHO, - scenario="Command goal: completes only from a runtime receipt; no visual assessment must advance it.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=False, - ), - VisionCase( - name="meesho_capture_goal_no_assessment", - screenshot="meesho_product_detail.png", - app="Meesho", - package=MEESHO, - assertion="Store the displayed product price as the captured value 'price'.", - goal_kind=SuccessKind.CAPTURE, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=MEESHO, - scenario="Capture goal: completes only from a committed STORE receipt, never from an assessment.", - provenance=MEESHO_RUN, - label_source=LabelSource.HUMAN, - critical_negative=False, - ), -) - - -MULTI_APP_CASES: Tuple[VisionCase, ...] = ( - VisionCase( - name="chatgpt_ad_overlay_blocks", - screenshot="chatgpt_ad_overlay.png", - app="ChatGPT (ad)", - package=CHATGPT, - assertion="The Amazon search results for 'ghar soap' are displayed.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=None, - scenario="Unrelated overlay: a full-screen ChatGPT advertisement, no results present.", - provenance=CHATGPT_AD_RUN, - label_source=LabelSource.HUMAN, - critical_negative=True, - ), - VisionCase( - name="controlled_login_present", - screenshot="controlled_login.png", - app="Controlled", - package=CONTROLLED, - assertion="A login screen with email and password fields and a sign-in button is displayed.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.SATISFIED, - truth_satisfied=True, - authority_package=None, - scenario="Login present: a controlled synthetic login screen with credential fields.", - provenance=CONTROLLED_SOURCE, - label_source=LabelSource.PROGRAMMATIC, - critical_negative=False, - ), - VisionCase( - name="rating_threshold_met", - screenshot="controlled_customer_rating_high.png", - app="Controlled", - package=CONTROLLED, - assertion="The product's customer rating is at least 4.2 out of 5.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.SATISFIED, - truth_satisfied=True, - authority_package=None, - scenario="Correct attribute above threshold: a 4.5 customer rating satisfies the predicate.", - provenance=CONTROLLED_SOURCE, - label_source=LabelSource.PROGRAMMATIC, - critical_negative=False, - ), - VisionCase( - name="rating_below_threshold", - screenshot="controlled_customer_rating_low.png", - app="Controlled", - package=CONTROLLED, - assertion="The product's customer rating is at least 4.2 out of 5.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=None, - scenario="Correct attribute below threshold: a 3.8 customer rating fails the predicate.", - provenance=CONTROLLED_SOURCE, - label_source=LabelSource.PROGRAMMATIC, - critical_negative=True, - ), - VisionCase( - name="rating_unrelated_number", - screenshot="controlled_unrelated_number.png", - app="Controlled", - package=CONTROLLED, - assertion="The product's customer rating is at least 4.2 out of 5.", - goal_kind=SuccessKind.OBSERVED, - expected_verdict=VisualVerdict.NOT_SATISFIED, - truth_satisfied=False, - authority_package=None, - scenario="Number in unrelated region: a 4.5% cashback figure must not satisfy a customer-rating predicate.", - provenance=CONTROLLED_SOURCE, - label_source=LabelSource.PROGRAMMATIC, - critical_negative=True, - ), -) - - -CASES: Tuple[VisionCase, ...] = AMAZON_CASES + MEESHO_CASES + MULTI_APP_CASES diff --git a/tests/fixtures/vision/screens/amazon_home.png b/tests/fixtures/vision/screens/amazon_home.png deleted file mode 100644 index eb7989a2..00000000 Binary files a/tests/fixtures/vision/screens/amazon_home.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/amazon_home_signin_promo.png b/tests/fixtures/vision/screens/amazon_home_signin_promo.png deleted file mode 100644 index a800e27e..00000000 Binary files a/tests/fixtures/vision/screens/amazon_home_signin_promo.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/amazon_music_interstitial.png b/tests/fixtures/vision/screens/amazon_music_interstitial.png deleted file mode 100644 index 0bba0a18..00000000 Binary files a/tests/fixtures/vision/screens/amazon_music_interstitial.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/amazon_search_suggestions_ghar_soap.png b/tests/fixtures/vision/screens/amazon_search_suggestions_ghar_soap.png deleted file mode 100644 index 950c2015..00000000 Binary files a/tests/fixtures/vision/screens/amazon_search_suggestions_ghar_soap.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/app_drawer_amazon_and_music.png b/tests/fixtures/vision/screens/app_drawer_amazon_and_music.png deleted file mode 100644 index 3b8c5abb..00000000 Binary files a/tests/fixtures/vision/screens/app_drawer_amazon_and_music.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/chatgpt_ad_overlay.png b/tests/fixtures/vision/screens/chatgpt_ad_overlay.png deleted file mode 100644 index a87303c0..00000000 Binary files a/tests/fixtures/vision/screens/chatgpt_ad_overlay.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/controlled_customer_rating_high.png b/tests/fixtures/vision/screens/controlled_customer_rating_high.png deleted file mode 100644 index bb4f9c06..00000000 Binary files a/tests/fixtures/vision/screens/controlled_customer_rating_high.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/controlled_customer_rating_low.png b/tests/fixtures/vision/screens/controlled_customer_rating_low.png deleted file mode 100644 index 31c22898..00000000 Binary files a/tests/fixtures/vision/screens/controlled_customer_rating_low.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/controlled_login.png b/tests/fixtures/vision/screens/controlled_login.png deleted file mode 100644 index f439e4f6..00000000 Binary files a/tests/fixtures/vision/screens/controlled_login.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/controlled_unrelated_number.png b/tests/fixtures/vision/screens/controlled_unrelated_number.png deleted file mode 100644 index 21007497..00000000 Binary files a/tests/fixtures/vision/screens/controlled_unrelated_number.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/launcher_home.png b/tests/fixtures/vision/screens/launcher_home.png deleted file mode 100644 index 77afa684..00000000 Binary files a/tests/fixtures/vision/screens/launcher_home.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/meesho_permission_contacts.png b/tests/fixtures/vision/screens/meesho_permission_contacts.png deleted file mode 100644 index 06d17ccb..00000000 Binary files a/tests/fixtures/vision/screens/meesho_permission_contacts.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/meesho_product_detail.png b/tests/fixtures/vision/screens/meesho_product_detail.png deleted file mode 100644 index e3bbba18..00000000 Binary files a/tests/fixtures/vision/screens/meesho_product_detail.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/meesho_search_results.png b/tests/fixtures/vision/screens/meesho_search_results.png deleted file mode 100644 index 1a10334c..00000000 Binary files a/tests/fixtures/vision/screens/meesho_search_results.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/meesho_search_typed_suggestions.png b/tests/fixtures/vision/screens/meesho_search_typed_suggestions.png deleted file mode 100644 index d0441eae..00000000 Binary files a/tests/fixtures/vision/screens/meesho_search_typed_suggestions.png and /dev/null differ diff --git a/tests/fixtures/vision/screens/shopping_folder_amazon_icon.png b/tests/fixtures/vision/screens/shopping_folder_amazon_icon.png deleted file mode 100644 index b04bb1e8..00000000 Binary files a/tests/fixtures/vision/screens/shopping_folder_amazon_icon.png and /dev/null differ diff --git a/tests/integration/coordinate/test_dispatch.py b/tests/integration/coordinate/test_dispatch.py deleted file mode 100644 index e6b90ce1..00000000 --- a/tests/integration/coordinate/test_dispatch.py +++ /dev/null @@ -1,386 +0,0 @@ -from __future__ import annotations - -import io -import time -import unittest -import xml.etree.ElementTree as ET -from pathlib import Path -from typing import Any, Dict, List, Tuple - -import yaml -from PIL import Image, ImageDraw - -from fathom.constants import ActionType -from fathom.core.artifact.drawing import BoxDrawer -from fathom.core.artifact.renderer import TraceRenderer -from fathom.processing.drawer import BoundsGenerator -from fathom.schemas.actions import Action, Bounds, CoordinateSource, CoordinateSystem -from fathom.schemas.artifact import ArtifactRecord, TracePayload -from fathom.schemas.observation import ElementSource -from fathom.schemas.screens import ScreenCapture -from fathom.utils.coordinates import CoordinateConverter - -FIXTURES = Path(__file__).resolve().parents[2] / "fixtures" / "coordinate" -OUTPUT = FIXTURES / "output" - - -class CoordinateDispatchCaseLoader: - """ - Walks the fixture tree and yields one descriptor per pinned case. - """ - - def __init__(self, *, root: Path) -> None: - """ - Bind to the fixture root. - """ - - self.__root = root - - def discover(self, *, platform: str, action: str) -> List[Dict[str, Any]]: - """ - Return every case under ``///NNN/``. - """ - - action_root = self.__root / platform / action - if not action_root.is_dir(): - return [] - - cases: List[Dict[str, Any]] = [] - for case_dir in sorted(p for p in action_root.iterdir() if p.is_dir()): - descriptor = self.__load_case(case_dir=case_dir) - if descriptor: - cases.append(descriptor) - return cases - - @staticmethod - def __load_case(*, case_dir: Path) -> Dict[str, Any]: - """ - Parse one case directory into a descriptor dict. - """ - - manifest = case_dir / "case.yaml" - hierarchy = case_dir / "hierarchy.xml" - screenshot = case_dir / "screenshot.png" - if not (manifest.is_file() and hierarchy.is_file() and screenshot.is_file()): - return {} - - with manifest.open("r", encoding="utf-8") as stream: - data = yaml.safe_load(stream) - - return { - "id": case_dir.name, - "dir": case_dir, - "case": data, - "hierarchy": hierarchy, - "screenshot": screenshot, - } - - -class LegacyDispatchSimulator: - """ - Reproduces the pre-fix ``Bounds.to_pixels`` behaviour exactly. - - The legacy implementation treated ``coordinate_system="pixel"`` as - pass-through and then clamped device-pixel values against the - logical screen dimensions. This class preserves that arithmetic so - the comparison renderings show the historical dispatch coords - side-by-side with the current ones. - """ - - @staticmethod - def dispatch_center( - *, - bounds: Bounds, - logical_width: int, - logical_height: int, - ) -> Tuple[int, int]: - """ - Return the dispatched ``(x, y)`` the legacy converter would emit. - """ - - x, y, width, height = bounds.x, bounds.y, bounds.width, bounds.height - max_x = max(0, logical_width - 1) - max_y = max(0, logical_height - 1) - x = max(0, min(x, max_x)) - y = max(0, min(y, max_y)) - width = max(1, min(width, max(1, logical_width - x))) - height = max(1, min(height, max(1, logical_height - y))) - return x + width // 2, y + height // 2 - - -class CoordinateDispatchRenderer: - """ - Render the production-style annotated and trace images for one case. - - Uses :class:`BoxDrawer` for the manifest annotation (identical to - :class:`PerceptionRenderer`) and invokes :class:`TraceRenderer` once - per element on a chained canvas to draw the legacy and current - dispatch overlays. No primitive in this class duplicates production - drawing logic — the renderers are wired exactly as production wires - them; only the iteration order is test-specific. - """ - - def __init__( - self, - *, - box_drawer: BoxDrawer = None, - trace_renderer: TraceRenderer = None, - ) -> None: - """ - Bind to production drawing primitives. - """ - - self.__box_drawer = box_drawer or BoxDrawer() - self.__trace_renderer = trace_renderer or TraceRenderer() - - def render( - self, - *, - case: Dict[str, Any], - elements: List[Any], - dispatches: Dict[str, Dict[str, Tuple[int, int]]], - output_root: Path, - ) -> None: - """ - Write ``annotated.png``, ``legacy.png``, and ``current.png`` for the case. - """ - - case_id = case["id"] - platform = case["case"]["platform"] - action_type = case["dir"].parent.name - - target_dir = output_root / platform / action_type / case_id - target_dir.mkdir(parents=True, exist_ok=True) - - annotated = self.__render_annotated( - screenshot=case["screenshot"], - elements=elements, - ) - (target_dir / "annotated.png").write_bytes(annotated) - - for variant in ("legacy", "current"): - traced = self.__render_traces( - base=annotated, - case=case["case"], - elements=elements, - dispatches={ - element.label: dispatches[variant][element.label] for element in elements - }, - ) - (target_dir / f"{variant}.png").write_bytes(traced) - - def __render_annotated(self, *, screenshot: Path, elements: List[Any]) -> bytes: - """ - Compose the manifest annotation via the production :class:`BoxDrawer`. - """ - - canvas = Image.open(screenshot).convert("RGB") - draw = ImageDraw.Draw(canvas, "RGBA") - for element in elements: - bounds = element.bounds - self.__box_drawer.draw( - canvas=draw, - bounds=( - int(bounds.x1), - int(bounds.y1), - int(bounds.x2), - int(bounds.y2), - ), - source=ElementSource.XML, - label_id=element.label, - text=(element.attributes or {}).get("text") or None, - ) - buffer = io.BytesIO() - canvas.save(buffer, format="PNG") - return buffer.getvalue() - - def __render_traces( - self, - *, - base: bytes, - case: Dict[str, Any], - elements: List[Any], - dispatches: Dict[str, Tuple[int, int]], - ) -> bytes: - """ - Chain :class:`TraceRenderer` once per element on top of the annotated base. - """ - - scale_x = self.__scale(image_bytes=base) / case["screen"]["logical"]["width"] - screen = ScreenCapture( - width=case["screen"]["logical"]["width"], - height=case["screen"]["logical"]["height"], - activity="test", - image=base, - timestamp=int(time.time() * 1000), - ) - - for element in elements: - logical_xy = dispatches[element.label] - pixel_xy = ( - int(logical_xy[0] * scale_x), - int(logical_xy[1] * scale_x), - ) - record = ArtifactRecord( - session_id="test", - package_name="test", - step_number=0, - created=int(time.time() * 1000), - payload=TracePayload( - capture=screen.model_copy(update={"image": screen.image}), - coords=pixel_xy, - action=Action( - action_type=ActionType.TAP, - rationale="characterise dispatch", - target=element.label, - label_id=element.label, - ), - ), - ) - traced_bytes = self.__trace_renderer.render(record=record) - screen = screen.model_copy(update={"image": traced_bytes}) - - return screen.image - - @staticmethod - def __scale(*, image_bytes: bytes) -> int: - """ - Return the pixel width of the encoded PNG. - """ - - with Image.open(io.BytesIO(image_bytes)) as image: - return image.width - - -class IosTapDispatchTest(unittest.TestCase): - """ - Pins coordinate-dispatch correctness for every iOS tap case. - """ - - def test_every_element_dispatches_inside_its_bbox(self) -> None: - """For every manifest element on every fixture screen, the current :class:`CoordinateConverter` must dispatch to a logical coord inside that element's logical bbox.""" - - loader = CoordinateDispatchCaseLoader(root=FIXTURES) - cases = loader.discover(platform="ios", action="tap") - self.assertGreater(len(cases), 0, "no fixtures discovered under ios/tap/") - - renderer = CoordinateDispatchRenderer() - for descriptor in cases: - with self.subTest(case=descriptor["id"]): - self.__run_case(descriptor=descriptor, renderer=renderer) - - def __run_case( - self, - *, - descriptor: Dict[str, Any], - renderer: CoordinateDispatchRenderer, - ) -> None: - """ - Execute one fixture: dispatch every element, assert, render. - """ - - case = descriptor["case"] - logical_width = int(case["screen"]["logical"]["width"]) - logical_height = int(case["screen"]["logical"]["height"]) - - with Image.open(descriptor["screenshot"]) as image: - pixel_width, pixel_height = image.width, image.height - - screenshot_bytes = Path(descriptor["screenshot"]).read_bytes() - - tree = ET.parse(descriptor["hierarchy"]) - elements, _ = BoundsGenerator.create_element( - root=tree.getroot(), - image=screenshot_bytes, - action=ActionType.TAP, - cv_enabled=False, - ) - self.assertGreater( - len(elements), - 0, - msg=f"case {descriptor['id']!r}: BoundsGenerator produced no elements", - ) - - converter = CoordinateConverter( - logical_width=logical_width, - logical_height=logical_height, - pixel_width=pixel_width, - pixel_height=pixel_height, - workflow_id=f"test::{descriptor['id']}", - ) - - dispatches: Dict[str, Dict[str, Tuple[int, int]]] = { - "current": {}, - "legacy": {}, - } - - scale_x = pixel_width / logical_width - scale_y = pixel_height / logical_height - - for element in elements: - bounds = Bounds( - x=int(element.bounds.x1), - y=int(element.bounds.y1), - width=int(element.bounds.x2 - element.bounds.x1), - height=int(element.bounds.y2 - element.bounds.y1), - coordinate_system=CoordinateSystem.DEVICE_PIXEL, - source=CoordinateSource.XML, - ) - - current_xy = converter.center_to_pixels(bounds=bounds) - legacy_xy = LegacyDispatchSimulator.dispatch_center( - bounds=bounds, - logical_width=logical_width, - logical_height=logical_height, - ) - - dispatches["current"][element.label] = current_xy - dispatches["legacy"][element.label] = legacy_xy - - logical_x_range = range( - int(element.bounds.x1 / scale_x), - int(element.bounds.x2 / scale_x) + 1, - ) - logical_y_range = range( - int(element.bounds.y1 / scale_y), - int(element.bounds.y2 / scale_y) + 1, - ) - self.assertIn( - current_xy[0], - logical_x_range, - msg=( - f"case {descriptor['id']!r}: label_id={element.label!r} current " - f"converter dispatched x={current_xy[0]} outside logical bbox " - f"x range {logical_x_range.start}..{logical_x_range.stop - 1}." - ), - ) - self.assertIn( - current_xy[1], - logical_y_range, - msg=( - f"case {descriptor['id']!r}: label_id={element.label!r} current " - f"converter dispatched y={current_xy[1]} outside logical bbox " - f"y range {logical_y_range.start}..{logical_y_range.stop - 1}." - ), - ) - - pinned_label = case.get("label_id") - pinned_dispatch = (case.get("expected") or {}).get("dispatched_logical") - if pinned_label and pinned_dispatch and pinned_label in dispatches["current"]: - pinned_expected = (int(pinned_dispatch["x"]), int(pinned_dispatch["y"])) - self.assertEqual( - dispatches["current"][pinned_label], - pinned_expected, - msg=( - f"case {descriptor['id']!r}: pinned label_id={pinned_label!r} " - f"dispatch mismatch — got {dispatches['current'][pinned_label]}, " - f"case.yaml expected {pinned_expected}." - ), - ) - - renderer.render( - case=descriptor, - elements=elements, - dispatches=dispatches, - output_root=OUTPUT, - ) diff --git a/tests/integration/core/agent/test_escalation_scenario.py b/tests/integration/core/agent/test_escalation_scenario.py index efaf8cb8..619a5530 100644 --- a/tests/integration/core/agent/test_escalation_scenario.py +++ b/tests/integration/core/agent/test_escalation_scenario.py @@ -53,6 +53,7 @@ def __context() -> SimpleNamespace: consume_user_guidance=Mock(), clear_user_guidance=Mock(), clear_verifier_feedback=Mock(), + clear_completion_feedback=Mock(), ) @staticmethod diff --git a/tests/integration/core/agent/tools/test_scope.py b/tests/integration/core/agent/tools/test_scope.py deleted file mode 100644 index 820b7777..00000000 --- a/tests/integration/core/agent/tools/test_scope.py +++ /dev/null @@ -1,133 +0,0 @@ -from __future__ import annotations - -import unittest -from pathlib import Path -from typing import Final, FrozenSet, List, Tuple - -from fathom.constants.tools import ToolName, TurnMode -from fathom.core.agent.tools.registry import DEFAULT_TOOL_POLICIES -from fathom.core.agent.tools.scope import ToolScope -from fathom.schemas.capabilities import HITLCapability, RuntimeCapabilities -from fathom.schemas.tools import ToolPolicyContext - - -class IntentCorpus: - """ - Loads the production intent corpus harvested from logs and debug artifacts. - """ - - __FILE: Final[Path] = Path(__file__).resolve().parents[5] / "tests" / "fixtures" / "intents.txt" - - @classmethod - def all_intents(cls) -> Tuple[str, ...]: - """ - Return every non-empty intent string from the corpus fixture. - """ - - if not cls.__FILE.exists(): - return () - - return tuple( - line.strip() - for line in cls.__FILE.read_text(encoding="utf-8").splitlines() - if line.strip() - ) - - -class ToolScopeCorpusReplayTest(unittest.TestCase): - """ - Across the production intent corpus, the mode gate is intent-independent: an active goal keeps - base UI tactics without VERIFY-only tools; the final-verification phase exposes them. - """ - - __VERIFY_TOOLS: Final[FrozenSet[ToolName]] = frozenset( - {ToolName.VERIFY_GOAL, ToolName.VALIDATE_STATE}, - ) - - @classmethod - def __compute(cls, *, modes: FrozenSet[TurnMode], hitl: bool) -> FrozenSet[ToolName]: - """ - Compute the per-turn tool set for the given mode set and HITL capability. - """ - - return ( - ToolScope(policies=DEFAULT_TOOL_POLICIES) - .compute( - context=ToolPolicyContext( - modes=modes, - capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=hitl)), - ), - ) - .names - ) - - def test_corpus_is_non_empty(self) -> None: - """ - The corpus file must be present and contain at least one intent. - """ - - self.assertGreater(len(IntentCorpus.all_intents()), 0) - - def test_active_goal_never_exposes_verification_tools(self) -> None: - """ - An active goal (empty mode set) hides verification tools for every corpus intent and HITL value. - """ - - failures: List[str] = [] - for intent in IntentCorpus.all_intents(): - for hitl in (False, True): - tools = self.__compute(modes=frozenset(), hitl=hitl) - if tools & self.__VERIFY_TOOLS: - failures.append(f"intent={intent!r} hitl={hitl} tools={sorted(tools)}") - - self.assertFalse(failures, "active goal leaked verification tools:\n" + "\n".join(failures)) - - def test_final_verification_phase_exposes_verification_tools(self) -> None: - """ - The final-verification phase (VERIFY mode) exposes both verification tools for every intent. - """ - - failures: List[str] = [] - for intent in IntentCorpus.all_intents(): - for hitl in (False, True): - tools = self.__compute(modes=frozenset({TurnMode.VERIFY}), hitl=hitl) - missing = self.__VERIFY_TOOLS - tools - if missing: - failures.append(f"intent={intent!r} hitl={hitl} missing={sorted(missing)}") - - self.assertFalse(failures, "final phase missed verification tools:\n" + "\n".join(failures)) - - def test_execute_ui_is_always_present(self) -> None: - """ - Liveness — every (intent, mode, hitl) combination must include EXECUTE_UI. - """ - - failures: List[str] = [] - for intent in IntentCorpus.all_intents(): - for modes in (frozenset(), frozenset({TurnMode.VERIFY})): - for hitl in (False, True): - if ToolName.EXECUTE_UI not in self.__compute(modes=modes, hitl=hitl): - failures.append(f"intent={intent!r} modes={modes} hitl={hitl}") - - self.assertFalse(failures, "EXECUTE_UI invariant violated:\n" + "\n".join(failures)) - - def test_ask_user_tracks_hitl_capability(self) -> None: - """ - ASK_USER must be present iff HITL is enabled, across every corpus intent. - """ - - failures: List[str] = [] - for intent in IntentCorpus.all_intents(): - for modes in (frozenset(), frozenset({TurnMode.VERIFY})): - for hitl in (False, True): - tools = self.__compute(modes=modes, hitl=hitl) - if (ToolName.ASK_USER in tools) != hitl: - failures.append(f"intent={intent!r} modes={modes} hitl={hitl}") - - self.assertFalse( - failures, "ASK_USER did not track HITL capability:\n" + "\n".join(failures) - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/integration/core/perception/test_scroll.py b/tests/integration/core/perception/test_scroll.py deleted file mode 100644 index b4c9c8b5..00000000 --- a/tests/integration/core/perception/test_scroll.py +++ /dev/null @@ -1,119 +0,0 @@ -from __future__ import annotations - -import unittest -import xml.etree.ElementTree as ET # nosec -from pathlib import Path - -from PIL import Image - -from fathom.constants import ActionType -from fathom.core.perception.observation import ScreenObservationService -from fathom.processing.parsers.ios import IOSParser -from fathom.schemas.actions import CoordinateSource, CoordinateSystem -from fathom.schemas.budgets import PerceptionBudget -from fathom.schemas.screens import ScreenCapture, ScreenHashBundle -from fathom.utils.coordinates import CoordinateConverter - - -class ScrollRegionCoordinateRegressionTest(unittest.IsolatedAsyncioTestCase): - """ - Replays captured production-style fixtures through scroll-region perception. - """ - - __FIXTURES = Path(__file__).resolve().parents[3] / "fixtures" / "perception" / "scroll" - - @staticmethod - def __hashes() -> ScreenHashBundle: - """ - Return deterministic hashes for observation-only tests. - """ - - return ScreenHashBundle( - visual_hash="0" * 16, - xml_hash="a" * 16, - interaction_hash="b" * 16, - ) - - async def test_logical_capture_dimensions_preserve_page_region_scale(self) -> None: - """ - Logical capture dimensions with a larger PNG must not be treated as device pixels. - """ - - xml_path = self.__FIXTURES / "AEKCI" / "hierarchy.xml" - screenshot_path = self.__FIXTURES / "AEKCI" / "screenshot.png" - xml = xml_path.read_text(encoding="utf-8") - root = ET.fromstring(xml) - app = root.find(".//XCUIElementTypeApplication") - self.assertIsNotNone(app) - assert app is not None - - with Image.open(screenshot_path) as screenshot: - pixel_width, pixel_height = screenshot.size - logical_width = int(app.get("width", "0")) - logical_height = int(app.get("height", "0")) - elements = IOSParser().find_all_elements( - root=root, - screenshot_width=pixel_width, - screenshot_height=pixel_height, - ) - - observation = await ScreenObservationService().observe( - capture=ScreenCapture( - width=logical_width, - height=logical_height, - activity="bundl.swiggy", - image=screenshot_path.read_bytes(), - xml_content=xml, - timestamp=1780051837410, - ), - hashes=self.__hashes(), - budget=PerceptionBudget(ocr=0, local=0, localization=0), - manifest=tuple(elements), - session_id="logical-capture-regression", - step_number=4, - ) - - self.assertTrue(observation.scroll) - region = observation.scroll[0] - self.assertEqual(region.bounds.system, CoordinateSystem.LOGICAL) - - converter = CoordinateConverter( - logical_width=logical_width, - logical_height=logical_height, - pixel_width=pixel_width, - pixel_height=pixel_height, - ) - execution_region = converter.region_from_bounds( - bounds=region.bounds, - source=region.bounds.source or CoordinateSource.VIEWPORT, - ) - self.assertGreaterEqual(execution_region.width, int(logical_width * 0.90)) - - def test_directional_swipe_filter_retains_scrollable_collection_view(self) -> None: - """ - Directional swipe filtering should keep scrollable collection views, not static text. - """ - - xml_path = self.__FIXTURES / "FsIfE" / "hierarchy.xml" - root = ET.fromstring(xml_path.read_text(encoding="utf-8")) - parser = IOSParser() - elements = parser.find_all_elements( - root=root, - screenshot_width=1320, - screenshot_height=2868, - ) - filtered = parser.filter_by_action(elements=elements, action=ActionType.SWIPE_LEFT) - - self.assertLess(len(filtered), len(elements)) - self.assertTrue( - any( - element.attributes.get("type") == "XCUIElementTypeCollectionView" - for element in filtered - ) - ) - self.assertFalse( - any( - element.attributes.get("type") == "XCUIElementTypeStaticText" - for element in filtered - ) - ) diff --git a/tests/integration/core/services/test_workflow_generation.py b/tests/integration/core/services/test_workflow_generation.py index 33a81571..37719fae 100644 --- a/tests/integration/core/services/test_workflow_generation.py +++ b/tests/integration/core/services/test_workflow_generation.py @@ -47,7 +47,7 @@ def get_history_directory(self, *, session_id: str) -> Path: class WorkflowGenerationRegressionTest(unittest.IsolatedAsyncioTestCase): """ - Regression for run 78a8dcbf, which once generated a launcher-only partial script. + Regression for a launcher-mediated run, which once generated a launcher-only partial script. """ def setUp(self) -> None: @@ -83,10 +83,10 @@ def __fixture(self) -> Path: @staticmethod def __workflow_trace() -> Path: """ - Return the committed 78a8dcbf workflow-trace fixture. + Return the committed launcher-run workflow-trace fixture. """ - return Path("assets/history/2026-06-23/78a8dcbf/history__workflow.json") + return Path("assets/history/2026-06-23/launcher-run/history__workflow.json") def __execution_trace(self) -> Path: """ @@ -101,7 +101,7 @@ def __objective(self) -> RunObjective: """ return RunObjective( - intent="open meesho and verify", goal="cart visible", package="com.meesho.supply" + intent="open shopping and verify", goal="cart visible", package="com.example.shop" ) async def __evidence(self) -> Evidence: @@ -109,7 +109,7 @@ async def __evidence(self) -> Evidence: Read the run's workflow trace into evidence. """ - return await self.__source.read(execution_id="78a8dcbf", objective=self.__objective()) + return await self.__source.read(execution_id="launcher-run", objective=self.__objective()) def __flow(self, *, evidence: Evidence) -> Flow: """ @@ -139,7 +139,7 @@ def __flow(self, *, evidence: Evidence) -> Flow: async def test_run_launches_the_real_app_not_the_launcher(self) -> None: """ - The launcher-mediated run yields a single grounded Meesho launch and stays non-partial. + The launcher-mediated run yields a single grounded Shopping launch and stays non-partial. """ evidence = await self.__evidence() @@ -147,7 +147,7 @@ async def test_run_launches_the_real_app_not_the_launcher(self) -> None: self.assertFalse(evidence.partial) self.assertEqual(len(launches), 1) - self.assertEqual(launches[0].package, "com.meesho.supply") + self.assertEqual(launches[0].package, "com.example.shop") self.assertEqual(launches[0].provenance, LaunchProvenance.LAUNCHER_TRANSITION) async def test_system_steps_stay_in_flow_in_order(self) -> None: @@ -160,9 +160,9 @@ async def test_system_steps_stay_in_flow_in_order(self) -> None: self.assertEqual(indices, [1, 2, 3, 4, 5, 6, 7, 8, 11]) - async def test_rendered_script_opens_meesho_and_passes_policy(self) -> None: + async def test_rendered_script_opens_shopping_and_passes_policy(self) -> None: """ - The flow renders to a Meesho-first script with no launcher launch and no fidelity issues. + The flow renders to a Shopping-first script with no launcher launch and no fidelity issues. """ evidence = await self.__evidence() @@ -179,7 +179,7 @@ async def test_rendered_script_opens_meesho_and_passes_policy(self) -> None: script = self.__dialect.renderer.render(flow=flow) self.assertEqual(raised & launch_codes, set()) - self.assertEqual(script.splitlines()[0], "OPEN_APP: com.meesho.supply") + self.assertEqual(script.splitlines()[0], "OPEN_APP: com.example.shop") self.assertNotIn("nexuslauncher", script) def __warm_start_record( diff --git a/tests/integration/strategies/graph/intent/nodes/test_analyze.py b/tests/integration/strategies/graph/intent/nodes/test_analyze.py index c072044a..dd6913de 100644 --- a/tests/integration/strategies/graph/intent/nodes/test_analyze.py +++ b/tests/integration/strategies/graph/intent/nodes/test_analyze.py @@ -5,38 +5,25 @@ from typing import List from unittest.mock import AsyncMock, Mock -from tests.builders import ActionFixtures, ScreenFixtures, SubGoalFixtures, SuccessFixtures +from tests.builders import ActionFixtures, ScreenFixtures, SubGoalFixtures from tests.builders.agent import AgentFixtures from fathom.constants import ActionType from fathom.constants.assessment import VisualVerdict -from fathom.constants.observation import KeyboardVisibility as _KeyboardVisibility from fathom.constants.retries import RetryBranch, RetryKind from fathom.constants.state import CommonStateKey, CompletionReason, IntentStateKey from fathom.constants.turn.advancement import AdvanceKind from fathom.core.agent.planner import StepPlanner from fathom.core.agent.state import AgentState -from fathom.core.capability.catalog import CommandCatalogProvider as _CommandCatalogProvider -from fathom.core.services.criterion import CriterionObserver as _CriterionObserverBase +from fathom.core.services.timing import RunClock from fathom.schemas.actions import Action -from fathom.schemas.actions import Bounds as _Bounds from fathom.schemas.assessment import VisualAssessment from fathom.schemas.capabilities import HITLCapability, RuntimeCapabilities from fathom.schemas.conversation import ConversationTurn -from fathom.schemas.criterion import CriterionDecision as _CriterionDecision -from fathom.schemas.criterion import CriterionSource as _CriterionSource -from fathom.schemas.criterion import CriterionVerdict as _CriterionVerdict -from fathom.schemas.observation import ElementRole as _ElementRole -from fathom.schemas.observation import ElementSource as _ElementSource -from fathom.schemas.observation import KeyboardObservation as _KeyboardObservation -from fathom.schemas.observation import PerceivedElement as _PerceivedElement -from fathom.schemas.observation import ScreenObservation as _ScreenObservation from fathom.schemas.planner import PlannerMetrics -from fathom.schemas.results import AnalysisResult, PlanContext, PlanResult, PlanTurn +from fathom.schemas.results import AnalysisResult from fathom.schemas.retries import RetryLimits -from fathom.schemas.screens import ScreenHashBundle as _ScreenHashBundle from fathom.strategies.graph.intent.nodes.analyze import AnalyzeNode -from fathom.strategies.graph.intent.nodes.completion import SubGoalEvaluator as _SubGoalEvaluator from fathom.strategies.graph.state import IntentGraphState @@ -68,7 +55,7 @@ class _RealPlannerHarness: Drives ``AnalyzeNode`` through the production ``StepPlanner`` with only the LLM boundary (``VisionService.analyze``) stubbed. """ - BLOCKED_DESCRIPTOR: str = "Swipe left on More on Swiggy widget" + BLOCKED_DESCRIPTOR: str = "Swipe left on More on Delivery widget" def __init__(self, *, agent_state: AgentState) -> None: self.__agent_state = agent_state @@ -108,6 +95,9 @@ def provider(self) -> SimpleNamespace: max_steps=10, use_xml=True, workflow_id="run-test", + intent="test-intent", + phase=AsyncMock(), + clock=RunClock(), planner=self.__planner, reasoner=self.__reasoner, agent_state=self.__agent_state, @@ -168,8 +158,8 @@ def __build_reasoner_stub(*, action: Action) -> Mock: class AnalyzeNodePlannerRetryBudgetIntegrationTest(unittest.IsolatedAsyncioTestCase): """ - Regression: the planner rejecting the same action on an unchanged screen used to loop forever; - the retry budget must terminate the workflow at ``cap`` iterations. + The planner rejecting the same action on an unchanged screen must not loop forever; the retry + budget terminates the workflow at ``cap`` iterations. """ @staticmethod @@ -191,7 +181,7 @@ def __capture() -> object: Build a constant capture so every iteration runs against an unchanged screen. """ - return ScreenFixtures.capture(activity="bundl.swiggy", width=1080, height=2340) + return ScreenFixtures.capture(activity="com.example.delivery", width=1080, height=2340) async def test_silent_rejection_loop_terminates_at_budget(self) -> None: """ @@ -349,153 +339,6 @@ async def test_no_capture_terminates_immediately(self) -> None: self.assertEqual(agent_state.retries.planner.count, 0) -if __name__ == "__main__": - unittest.main() - - -class _SatisfiedCriterionObserver(_CriterionObserverBase): - """ - Criterion observer stub that always reports high-confidence SATISFIED on the settled screen. - """ - - def __init__(self) -> None: - self.calls = 0 - - async def check( - self, *, workflow_id: str, index: int, requirement: object, observation: _ScreenObservation - ) -> _CriterionDecision: - """ - Return a fresh high-confidence SATISFIED reading regardless of inputs. - """ - - _ = (workflow_id, index, requirement, observation) - self.calls += 1 - return _CriterionDecision( - verdict=_CriterionVerdict.SATISFIED, - source=_CriterionSource.SYMBOLIC, - confidence=0.9, - evidence=("rating >= 4.2 visible",), - ) - - -class AnalyzeNodePreDispatchSatisfiedPriorTest(unittest.IsolatedAsyncioTestCase): - """ - Graph-level: an active goal already satisfied on the settled screen advances via SATISFIED_PRIOR - inside ANALYZE after the single planner call, discarding the planned action before EXECUTE. The real - CriterionObserver-shaped stub, AdvancementPolicy and SubGoalEvaluator are exercised through the - production AnalyzeNode; only the criterion reading is fixed. - """ - - @staticmethod - def __observation() -> _ScreenObservation: - """ - Build a minimal settled-screen observation. - """ - - element = _PerceivedElement( - identifier="e0", - bounds=_Bounds(x=0, y=0, width=10, height=10), - source=_ElementSource.XML, - role=_ElementRole.TEXT, - confidence=1.0, - text="Ghar Magic Soap 4.9", - tappable=False, - ) - return _ScreenObservation( - activity="com.meesho.supply", - elements=(element,), - hashes=_ScreenHashBundle( - visual_hash="vh0", - xml_hash="0000000000000000", - interaction_hash="0000000000000000", - ), - overlays=(), - keyboard=_KeyboardObservation(visibility=_KeyboardVisibility.HIDDEN), - scroll=(), - calls_to_action=(), - focused=None, - ) - - async def test_satisfied_goal_advances_before_dispatch_without_execute(self) -> None: - """ - The already-satisfied goal advances to the next sub-goal after the single planner call, before EXECUTE. - """ - - agent_state = AgentState( - intent="buy ghar soap", - capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=False)), - ) - agent_state.set_sub_goals( - [ - SubGoalFixtures.make( - index=0, - description="Scroll until rating >= 4.2", - success=SuccessFixtures.observed( - assertion="a product with rating >= 4.2 is visible" - ), - ), - SubGoalFixtures.make( - index=1, - description="Select the product", - success=SuccessFixtures.observed(assertion="product detail open"), - ), - ] - ) - catalog = _CommandCatalogProvider().build() - checker = _SatisfiedCriterionObserver() - evaluator = _SubGoalEvaluator( - context=SimpleNamespace( - agent_state=agent_state, workflow_id="run-test", catalog=catalog - ), - criterion_observer=checker, - ) - planner = Mock() - planner.plan_step = AsyncMock( - return_value=PlanTurn( - plan=PlanResult( - reason="already satisfied", - is_complete=False, - step=None, - context=PlanContext( - analysis=AnalysisResult(reasoning="r", screen_description="s") - ), - ) - ) - ) - provider = SimpleNamespace( - is_cancelled=AsyncMock(return_value=False), - persistence=_Persistence(), - hitl=SimpleNamespace(prompt=AsyncMock()), - completion=evaluator, - context=SimpleNamespace( - workflow_id="run-test", - max_steps=10, - agent_state=agent_state, - context_manager=AgentFixtures.context_manager(), - planner=planner, - use_xml=True, - reasoner=Mock(), - memory=SimpleNamespace(set=AsyncMock()), - metrics=SimpleNamespace(record=Mock(), record_tokens=Mock()), - configuration=SimpleNamespace(intent=SimpleNamespace(prompt_user_if_stuck=False)), - telemetry=SimpleNamespace(info=AsyncMock(), error=AsyncMock()), - catalog=catalog, - ), - ) - state: IntentGraphState = { - CommonStateKey.CAPTURE: ScreenFixtures.capture(activity="com.meesho.supply"), - CommonStateKey.SCREEN_OBSERVATION: self.__observation(), - } - - result = await AnalyzeNode(provider=provider).run(state=state) - - self.assertEqual(checker.calls, 1) - planner.plan_step.assert_awaited_once() - self.assertEqual(agent_state.current_sub_goal_index, 1) - self.assertTrue(result.get(IntentStateKey.SHOULD_RETRY)) - self.assertIsNone(result.get(IntentStateKey.PLANNED_STEP)) - - class AnalyzeNodeShadowAssessmentIntegrationTest(unittest.IsolatedAsyncioTestCase): """ Graph-level proof of Slice-2 shadow recording: the real AnalyzeNode + production StepPlanner, @@ -514,6 +357,9 @@ def __provider( max_steps=10, use_xml=True, workflow_id="run-test", + intent="test-intent", + phase=AsyncMock(), + clock=RunClock(), planner=StepPlanner(vision_tool=vision), reasoner=reasoner, agent_state=agent_state, @@ -531,11 +377,11 @@ async def test_satisfied_with_action_records_retaining_candidate_action_stays_cu self, ) -> None: agent_state = AgentState( - intent="Open Amazon", + intent="Open Retail", max_steps=10, capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=False)), ) - agent_state.set_sub_goals([SubGoalFixtures.make(description="Amazon home is shown")]) + agent_state.set_sub_goals([SubGoalFixtures.make(description="Retail home is shown")]) cursor_before = agent_state.current_sub_goal_index action = ActionFixtures.make( @@ -548,7 +394,7 @@ async def test_satisfied_with_action_records_retaining_candidate_action_stays_cu action=action, metadata={"tool_args": {}}, reasoning="home visible", - screen_description="Amazon home", + screen_description="Retail home", visual_assessment=VisualAssessment( verdict=VisualVerdict.SATISFIED, confidence=0.9, evidence="home visible" ), @@ -566,7 +412,7 @@ async def test_satisfied_with_action_records_retaining_candidate_action_stays_cu with self.assertLogs("fathom.strategies.graph.intent.nodes.analyze", level="INFO") as logs: result = await node.run( - state={CommonStateKey.CAPTURE: ScreenFixtures.capture(activity="com.amazon.mp3")} + state={CommonStateKey.CAPTURE: ScreenFixtures.capture(activity="com.example.media")} ) # Exactly one model turn (the vision boundary the planner calls once). @@ -586,3 +432,7 @@ async def test_satisfied_with_action_records_retaining_candidate_action_stays_cu self.assertIs(draft.pre_dispatch.candidate.kind, AdvanceKind.RETAIN) # The goal cursor did not advance from the shadow path. self.assertEqual(agent_state.current_sub_goal_index, cursor_before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/integration/strategies/graph/intent/nodes/test_verify_final_handoff.py b/tests/integration/strategies/graph/intent/nodes/test_verify_final_handoff.py index 2219b4f7..eed43f5e 100644 --- a/tests/integration/strategies/graph/intent/nodes/test_verify_final_handoff.py +++ b/tests/integration/strategies/graph/intent/nodes/test_verify_final_handoff.py @@ -10,6 +10,7 @@ from fathom.constants import ActionType from fathom.constants.state import CommonStateKey, IntentStateKey, VerifyMode from fathom.core.agent.state import AgentState +from fathom.core.services.timing import RunClock from fathom.schemas.actions import Action from fathom.schemas.capabilities import HITLCapability, RuntimeCapabilities from fathom.schemas.results import PlanResult @@ -59,7 +60,7 @@ async def perceive(self, **_: object) -> ScreenCapture: height=200, image=b"png", timestamp=1, - activity="com.swiggy/.HomeActivity", + activity="com.delivery/.HomeActivity", ) @@ -166,6 +167,8 @@ def __init__( self.context = SimpleNamespace( llm=llm, max_steps=20, + phase=AsyncMock(), + clock=RunClock(), artifact_pipeline=None, agent_state=agent_state, perception=_Perception(), @@ -224,7 +227,7 @@ def __screen() -> ScreenState: timestamp=1, visual_hash="b" * 16, activity_hash="a" * 16, - activity="com.swiggy/.HomeActivity", + activity="com.delivery/.HomeActivity", ) def __record_state(self, *, step_number: int) -> Dict[object, object]: @@ -235,12 +238,12 @@ def __record_state(self, *, step_number: int) -> Dict[object, object]: return { CommonStateKey.IS_NEW_SCREEN: True, CommonStateKey.SCREEN_STATE: self.__screen(), - IntentStateKey.POST_ACTIVITY: "com.swiggy/.HomeActivity", + IntentStateKey.POST_ACTIVITY: "com.delivery/.HomeActivity", CommonStateKey.STEP_RESULT: self.__step_result(step_number=step_number), IntentStateKey.PLAN: PlanResult( step=None, is_complete=True, - reason="SalarySe office appears selected", + reason="Finance office appears selected", ), } @@ -301,7 +304,7 @@ def __hsr_record_state(self) -> Dict[object, object]: return { CommonStateKey.IS_NEW_SCREEN: True, CommonStateKey.SCREEN_STATE: self.__screen(), - IntentStateKey.POST_ACTIVITY: "in.swiggy.android", + IntentStateKey.POST_ACTIVITY: "com.example.delivery", CommonStateKey.STEP_RESULT: self.__hsr_corrective_step_result(), IntentStateKey.PLAN: PlanResult( step=None, @@ -322,7 +325,7 @@ async def test_final_subgoal_rejection_remains_active_until_verify_accepts(self) agent_state.set_sub_goals( [ SubGoalFixtures.make(index=0, description="Tap address selector"), - SubGoalFixtures.make(index=1, description="Confirm SalarySe office address"), + SubGoalFixtures.make(index=1, description="Confirm Finance office address"), ] ) agent_state.advance_current_sub_goal() @@ -330,8 +333,8 @@ async def test_final_subgoal_rejection_remains_active_until_verify_accepts(self) contents=[ '{"is_complete": false, "reason": "Tap Yes, continue first"}', ( - '{"is_complete": true, "reason": "SalarySe office is selected", ' - '"assertions": [{"kind": "VISIBLE", "subject": "SalarySe office address header"}]}' + '{"is_complete": true, "reason": "Finance office is selected", ' + '"assertions": [{"kind": "VISIBLE", "subject": "Finance office address header"}]}' ), ] ) @@ -379,7 +382,7 @@ async def test_final_subgoal_rejection_remains_active_until_verify_accepts(self) self.assertNotIn("Step:", llm.prompts[0]) self.assertIn("User Intent: change the address to salary-se office", llm.prompts[0]) - async def test_hsr_prod_replay_rejects_corrects_then_verifies_final_intent(self) -> None: + async def test_replay_rejects_corrects_then_verifies_final_intent(self) -> None: """ Replay 6f72ec86: final VERIFY rejects the modal, corrective tap routes back to final VERIFY, then acceptance completes. """ diff --git a/tests/integration/strategies/graph/intent/test_builder.py b/tests/integration/strategies/graph/intent/test_builder.py index 1dd55d78..d5ae2d7c 100644 --- a/tests/integration/strategies/graph/intent/test_builder.py +++ b/tests/integration/strategies/graph/intent/test_builder.py @@ -14,6 +14,7 @@ from fathom.core.agent.state import AgentState from fathom.core.capability.catalog import CommandCatalogProvider from fathom.core.exceptions import HITLNotAvailableError +from fathom.core.services.timing import RunClock from fathom.schemas.actions import Action from fathom.schemas.capabilities import HITLCapability, RuntimeCapabilities from fathom.schemas.execution import ExecutionContext @@ -48,6 +49,7 @@ async def test_compiled_graph_terminates_when_execution_context_is_missing(self) agent_state=agent_state, is_cancelled=False, max_steps=8, + clock=RunClock(), workflow_id="integration-graph-missing-context", ) provider = MagicMock(name="IntentNodeProvider") @@ -103,17 +105,23 @@ async def broken_supervise(_state: IntentGraphState) -> Dict[str, object]: class TestHitlUnavailableReplan: - """End-to-end pin for stale-ASK_USER recovery via the compiled graph.""" + """ + End-to-end pin for stale-ASK_USER recovery via the compiled graph. + """ @staticmethod def __capture() -> ScreenCapture: - """Build a minimal screen capture.""" + """ + Build a minimal screen capture. + """ return ScreenCapture(width=100, height=200, activity="app", image=b"", timestamp=1) @staticmethod def __ask_user_context() -> ExecutionContext: - """Execution context whose planned step is ASK_USER (stale replay).""" + """ + Execution context whose planned step is ASK_USER (stale replay). + """ action = Action( action_type=ActionType.ASK_USER, @@ -138,7 +146,9 @@ def __ask_user_context() -> ExecutionContext: @pytest.mark.asyncio async def test_stale_ask_user_routes_execute_back_to_ground(self) -> None: - """A replayed ASK_USER step under autonomous capabilities must reach GROUND, not OBSERVE.""" + """ + A replayed ASK_USER step under autonomous capabilities must reach GROUND, not OBSERVE. + """ agent_state = AgentState( intent="login", @@ -150,6 +160,7 @@ async def test_stale_ask_user_routes_execute_back_to_ground(self) -> None: is_cancelled=False, max_steps=5, catalog=CommandCatalogProvider().build(), + clock=RunClock(), workflow_id="integration-hitl-unavailable", ) provider = MagicMock(name="IntentNodeProvider") diff --git a/tests/live/core/agent/tools/test_scope.py b/tests/live/core/agent/tools/test_scope.py deleted file mode 100644 index 881e6e7b..00000000 --- a/tests/live/core/agent/tools/test_scope.py +++ /dev/null @@ -1,112 +0,0 @@ -from __future__ import annotations - -from typing import Final, FrozenSet - -import pytest - -from fathom.constants.tools import ToolName -from fathom.core.agent.tools.registry import DEFAULT_TOOL_POLICIES -from fathom.core.agent.tools.scope import ToolScope -from fathom.core.capability.catalog import CommandCatalogProvider -from fathom.core.services.decomposer import IntentDecomposer -from fathom.core.services.translation import ProposalTranslator -from fathom.interfaces.llm import LLMPort -from fathom.schemas.capabilities import HITLCapability, RuntimeCapabilities -from fathom.schemas.subgoal import GoalState -from fathom.schemas.tools import ToolPolicyContext -from tests.fixtures.intents import VERIFY_TOOLS, IntentCorpus - - -def _tool_set_for(*, sub_goal: GoalState, hitl: bool) -> FrozenSet[ToolName]: - """ - Compute the per-turn tool set for an active goal (mode gate is intent- and variant-independent). - """ - - _ = sub_goal - return ( - ToolScope(policies=DEFAULT_TOOL_POLICIES) - .compute( - context=ToolPolicyContext( - modes=frozenset(), - capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=hitl)), - ), - ) - .names - ) - - -def _assert_contract(*, sub_goal: GoalState, intent: str, hitl: bool) -> None: - """ - Assert an active goal keeps base UI tactics without VERIFY-only tools, for any success variant. - """ - - tools = _tool_set_for(sub_goal=sub_goal, hitl=hitl) - assert ToolName.EXECUTE_UI in tools - assert ToolName.STORE_MEMORY in tools - assert ToolName.RECALL_MEMORY in tools - assert (ToolName.ASK_USER in tools) == hitl - assert not (tools & VERIFY_TOOLS), ( - f"active goal leaked verification tools for intent={intent!r} " - f"sub_goal={sub_goal.objective!r}" - ) - - -class TestLiveToolScope: - """ - Live decomposer x :class:`ToolScope` replay — guards production correctness end-to-end. - """ - - __VERIFY_TOOLS: Final[FrozenSet[ToolName]] = VERIFY_TOOLS - - @pytest.mark.asyncio - @pytest.mark.parametrize("intent", IntentCorpus.representative()) - async def test_representative_intent_obeys_tool_scope_contract( - self, - *, - intent: str, - llm: LLMPort, - ) -> None: - """ - Quick-sample subset of the corpus runs end-to-end against the live decomposer. - """ - - sub_goals = await IntentDecomposer( - llm=llm, translator=ProposalTranslator(catalog=CommandCatalogProvider().build()) - ).decompose(intent=intent) - assert sub_goals, f"decomposer returned no sub-goals for intent: {intent!r}" - - for sub_goal in sub_goals: - for hitl in (False, True): - _assert_contract(sub_goal=sub_goal, intent=intent, hitl=hitl) - - -@pytest.mark.slow -class TestLiveToolScopeFullCorpus: - """ - Exhaustive corpus replay through the live decomposer. - - Every intent from ``tests/fixtures/intents.txt`` runs against real Gemini. - Costly — gated by both FATHOM_RUN_LIVE_TESTS=1 and the ``slow`` pytest marker. - Invoke explicitly with ``pytest -m slow tests/live/core/agent/tools/``. - """ - - @pytest.mark.asyncio - @pytest.mark.parametrize("intent", IntentCorpus.all_intents()) - async def test_every_corpus_intent_obeys_tool_scope_contract( - self, - *, - intent: str, - llm: LLMPort, - ) -> None: - """ - Every corpus intent's decomposition must obey the framework contract end-to-end. - """ - - sub_goals = await IntentDecomposer( - llm=llm, translator=ProposalTranslator(catalog=CommandCatalogProvider().build()) - ).decompose(intent=intent) - assert sub_goals, f"decomposer returned no sub-goals for intent: {intent!r}" - - for sub_goal in sub_goals: - for hitl in (False, True): - _assert_contract(sub_goal=sub_goal, intent=intent, hitl=hitl) diff --git a/tests/live/core/perception/test_scroll.py b/tests/live/core/perception/test_scroll.py deleted file mode 100644 index e3c0200f..00000000 --- a/tests/live/core/perception/test_scroll.py +++ /dev/null @@ -1,45 +0,0 @@ -from __future__ import annotations - -import unittest -import xml.etree.ElementTree as ET # nosec -from pathlib import Path - -import pytest - -from fathom.constants import ActionType -from fathom.processing.parsers.ios import IOSParser - -pytestmark = pytest.mark.release - - -class LiveScrollRegionFixtureTest(unittest.TestCase): - """ - Release-gated smoke tests over captured scroll-region fixtures. - """ - - __ROOT = Path(__file__).resolve().parents[4] - __DEBUG = __ROOT / "debug" / "scroll" - - def test_directional_swipe_filter_excludes_static_text(self) -> None: - """ - Directional swipe filtering must not treat static labels as gesture targets. - """ - - xml_path = self.__DEBUG / "FsIfE" / "assets" / "xmls" / "1780051090775__bundl.swiggy.png" - root = ET.fromstring(xml_path.read_text(encoding="utf-8")) - parser = IOSParser() - elements = parser.find_all_elements( - root=root, - screenshot_width=1320, - screenshot_height=2868, - ) - - filtered = parser.filter_by_action(elements=elements, action=ActionType.SWIPE_LEFT) - - self.assertTrue(filtered) - self.assertFalse( - any( - element.attributes.get("type") == "XCUIElementTypeStaticText" - for element in filtered - ) - ) diff --git a/tests/live/core/services/qualifier/test_llm.py b/tests/live/core/services/qualifier/test_llm.py index d597c698..d1da546b 100644 --- a/tests/live/core/services/qualifier/test_llm.py +++ b/tests/live/core/services/qualifier/test_llm.py @@ -51,46 +51,46 @@ class IntentCorpus: """ OBSERVED_EXECUTABLE: List[str] = [ - "Open Meesho and then scroll down until you find Jars & containers on the screen", + "Open Shopping and then scroll down until you find Jars & containers on the screen", ( - "Open Swiggy app. Tap on Location dropdown. Select 'HSR Layout'. " + "Open Delivery app. Tap on Location dropdown. Select 'HSR Layout'. " "Tap on search bar. Enter 'Biryani' in search bar. Scroll up 40% auto suggest " "page. Tap on Show results. Validate srp page is loaded. " "Tap on heart icon in restaurant list. Validate login half card is displayed" ), "Scroll down until you find Jars & containers on the screen", "Scroll vertically until you find Asha Tiffin on the screen", - "Search for McPuff", + "Search for Veg Roll", "Search for a product, add it to cart, and complete checkout.", "open the contact app add new contact to it", ] REAL_USER_INTENTS: List[str] = [ ( - "Hi. I would like you to open the Fairway Solitaire app. go through the Big Fish " + "Hi. I would like you to open the game app. go through the game " "Splash Screen, and await until you are on the main menu. If it asks to send " "notifications, allow. If it asks for Terms of Use, accept. If it asks to get a " "more personalized Experience, select Next. If it asks to track your activities " "across partner companies, allow.\nYou should be on the main screen, select Play " "to begin FTUE." ), - "Ok lets simplify this, open the Fairway app, that is all", + "Ok lets simplify this, open the game app, that is all", "Hello there, can you open the fair way app and get the the main menu?", - "ok hello, can you open the Cooking Craze app, and then proceed to claim the daily reward.", - "Open the Cooking Craze app and claim the daily reward", + "ok hello, can you open the game app, and then proceed to claim the daily reward.", + "Open the game app and claim the daily reward", ( - "ok we are gonna take it up a notch\nOpen the Cooking Craze app. navigate to the " + "ok we are gonna take it up a notch\nOpen the game app. navigate to the " "main menu and open the settings. The settings will have a gear icon. When in " "settings select the support tab and open the terms of use. Take a screenshot of " "the terms of use. return back to the main menu and stop testing." ), ( - "Open the Cooking Craze app.\nSelect the play button.\nSelect the Settings button, " + "Open the game app.\nSelect the play button.\nSelect the Settings button, " "it looks like a gear icon.\nOpen the support tab.\nOpen the terms of use page.\n" "Take a screenshot of the terms of use.\nReturn back to game.\nClose the settings " "menu.\nEnd Testing." ), ( - "Open the Cooking Craze App\nPress the Play button\nSelect the spoons Icon in the " + "Open the game App\nPress the Play button\nSelect the spoons Icon in the " "bottom right tiles\nOpen the offers to get spoons\nVerify that the player is " "re-directed to the offerwall.\nReturn to game\nClose the Survey/Offer wall menu.\n" "End test" @@ -98,19 +98,19 @@ class IntentCorpus: ( "If any of the attempts below are made more than 5 times and it still does not " "yield the desired results, mark the test as a fail and stop testing.\n\nOpen the " - "Cooking Craze App\nPress the Play button\nSelect the spoons Icon in the bottom " + "game App\nPress the Play button\nSelect the spoons Icon in the bottom " "right tiles\nOpen the offers to get spoons\nVerify that the player is re-directed " "to the offerwall.\nReturn to game\nClose the Survey/Offer wall menu.\nEnd test" ), ( - "Open Cooking Craze, select play and open the settings menu. From there open the " + "Open game, select play and open the settings menu. From there open the " "Support tab and open the terms of use. Validate that they are displayed. Return " "to game and close the settings menu." ), ( "If any step takes more than 5 attempts immediately stop testing and fail the test.\n" "Main Test: Can the player select the offerwall and be directed to the offer wall\n" - "- Open the Cooking Craze app.\n- Select the play button.\n- Select the Spoons icon " + "- Open the game app.\n- Select the play button.\n- Select the Spoons icon " "in the bottom right tiles.\n- Select Offer.\n- Observe the player is directed to " "the offerwall.\n- Close Offerwall and return to game.\n- Close the Spoons menu.\n" "- End Test." @@ -118,7 +118,7 @@ class IntentCorpus: ( "If any step takes more than 5 attempts immediately stop testing. No system " "override allowed, STOP TESTING.\n\nMain Test: Can the player select the offerwall " - "and be directed to the offer wall\n- Open the Cooking Craze app.\n- Select the " + "and be directed to the offer wall\n- Open the game app.\n- Select the " "play button.\n- Select the Spoons icon in the bottom right tiles.\n- Select Offer.\n" "- Observe the player is directed to the offerwall.\n- Close Offerwall and return " "to game.\n- Close the Spoons menu.\n- End Test." @@ -155,7 +155,7 @@ class IntentCorpus: "Skip device setup during onboarding", ] QUESTION_FORM_EXECUTABLE: List[str] = [ - "Can you open Swiggy and search for Biryani?", + "Can you open Delivery and search for Biryani?", "Can you tap the checkout button?", "Could you scroll down and find the price?", "Can you go back to the previous screen?", @@ -383,7 +383,9 @@ async def __classify( ) async def test_every_intent_classifies_correctly(self) -> None: - """Run the corpus through the real qualifier wiring and report per-intent and aggregate outcomes.""" + """ + Run the corpus through the real qualifier wiring and report per-intent and aggregate outcomes. + """ cases = IntentCorpus.cases() configuration = QualifierConfiguration() diff --git a/tests/live/core/services/test_decomposer.py b/tests/live/core/services/test_decomposer.py index 5c45de2c..754807a6 100644 --- a/tests/live/core/services/test_decomposer.py +++ b/tests/live/core/services/test_decomposer.py @@ -14,14 +14,14 @@ pytestmark = pytest.mark.release -VARO_ONBOARDING_INTENT = ( - "I want to launch the Varo app and login with " - "dev+test+Ilu+z2O5@varomoney.com and password Password1! " +BANKING_ONBOARDING_INTENT = ( + "I want to launch the banking app and login with " + "dev+test+Ilu+z2O5@example.com and password Password1! " 'I then want you to step through the onboarding wizard and get to the main "Home" screen.' ) CONDITIONAL_STORE_INTENT = ( - "Open Meesho and then, Search for Ghar soaps, check whether customer rating is >= 4.2 " + "Open Shopping and then, Search for Ghar soaps, check whether customer rating is >= 4.2 " "or not if it is, store the price of selected item as item_price and then proceed to buy " "until login screen" ) @@ -75,22 +75,22 @@ class TestIntentDecomposer: Live LLM checks for IntentDecomposer. """ - async def test_varo_onboarding_intent_preserves_required_steps(self, llm: LLMPort) -> None: + async def test_banking_onboarding_intent_preserves_required_steps(self, llm: LLMPort) -> None: """ - Varo onboarding must decompose into ordered, executable sub-goals. + Banking onboarding must decompose into ordered, executable sub-goals. """ decomposer = IntentDecomposer( llm=llm, translator=ProposalTranslator(catalog=CommandCatalogProvider().build()) ) - sub_goals = await decomposer.decompose(intent=VARO_ONBOARDING_INTENT) + sub_goals = await decomposer.decompose(intent=BANKING_ONBOARDING_INTENT) descriptions = DecompositionAssertions.joined_descriptions(sub_goals=sub_goals) assert len(sub_goals) >= 3 - assert "dev+test+ilu+z2o5@varomoney.com" in descriptions + assert "dev+test+ilu+z2o5@example.com" in descriptions assert "password1!" in descriptions - assert "varo" in descriptions + assert "banking" in descriptions assert "home" in descriptions assert "onboarding" in descriptions or "wizard" in descriptions DecompositionAssertions.assert_contains_in_order( diff --git a/tests/live/core/services/test_recorder.py b/tests/live/core/services/test_recorder.py index 8c9d9f57..12d12de9 100644 --- a/tests/live/core/services/test_recorder.py +++ b/tests/live/core/services/test_recorder.py @@ -311,8 +311,8 @@ class TestRecorderMultiTenantResilience: """ __TENANTS: Tuple[Tuple[str, str], ...] = ( - ("1", "alice@drizz.dev"), - ("343", "aman@drizz.com"), + ("1", "alice@example.com"), + ("343", "sam@example.com"), ("500", "bob@othercorp.com"), ("900", "carol@newco.com"), ("1201", "dan@scaleup.io"), @@ -401,7 +401,7 @@ def attempt() -> Run: thread=thread, created=started, workflow=workflow, - operator="aman@drizz.com", + operator="sam@example.com", ) # Two independent runs with identical content, as a deterministic retry @@ -432,7 +432,7 @@ async def test_recording_failure_is_swallowed(self) -> None: recorder = harness.recorder() handle = await recorder.record_run_started( - run=RunFactory.build(tenant="343", operator="aman@drizz.com") + run=RunFactory.build(tenant="343", operator="sam@example.com") ) assert handle is None @@ -476,7 +476,7 @@ def __handle(cls) -> Handle: responder=cls.__ACTOR, workflow=cls.__WORKFLOW, execution=cls.__EXECUTION, - requester="aman@drizz.com", + requester="sam@example.com", ) @classmethod @@ -541,7 +541,7 @@ def __run(cls) -> Run: tenant=cls.__TENANT, thread=cls.__THREAD, workflow=cls.__WORKFLOW, - operator="aman@drizz.com", + operator="sam@example.com", ) @classmethod @@ -585,7 +585,7 @@ def __answer(cls) -> Answer: **cls.__scope(), created=cls.__NOW, id="message-answer-343", - actor="aman@drizz.com", + actor="sam@example.com", execution=cls.__EXECUTION, body={"text": "the primary one"}, question="message-question-343", diff --git a/tests/live/core/services/test_vision.py b/tests/live/core/services/test_vision.py index 90345be5..3fd5e5a0 100644 --- a/tests/live/core/services/test_vision.py +++ b/tests/live/core/services/test_vision.py @@ -17,7 +17,7 @@ pytestmark = pytest.mark.release -EMAIL = "dev+test+Ilu+z2O5@varomoney.com" +EMAIL = "dev+test+Ilu+z2O5@example.com" class NoopTelemetry(TelemetryPort): @@ -80,7 +80,7 @@ def capture() -> ScreenCapture: image = Image.new("RGB", (402, 874), "white") draw = ImageDraw.Draw(image) - draw.text((38, 80), "Varo", fill="black") + draw.text((38, 80), "Banking", fill="black") draw.text((38, 140), "Email", fill="black") draw.rectangle((38, 170, 364, 225), outline="black", width=2) draw.text((50, 188), EMAIL, fill="black") @@ -93,7 +93,7 @@ def capture() -> ScreenCapture: return ScreenCapture( width=402, height=874, - activity="com.varomoney.varo", + activity="com.example.bank", image=buffer.getvalue(), timestamp=int(time.time() * 1000), ) diff --git a/tests/live/core/services/test_vision_assessment.py b/tests/live/core/services/test_vision_assessment.py deleted file mode 100644 index 1c606680..00000000 --- a/tests/live/core/services/test_vision_assessment.py +++ /dev/null @@ -1,135 +0,0 @@ -from __future__ import annotations - -import os -from pathlib import Path - -import pytest - -from fathom.core.agent.candidate import ShadowCandidate -from fathom.core.agent.tools import DEFAULT_TOOL_POLICIES, ToolScope -from fathom.core.services.vision import VisionService -from fathom.interfaces.llm import LLMPort -from fathom.interfaces.memory import MemoryPort -from fathom.schemas.capabilities import HITLCapability, RuntimeCapabilities -from fathom.schemas.tools import ToolPolicyContext -from tests.fixtures.vision.corpus import CASES -from tests.live.core.services.test_vision import NoopTelemetry -from tests.support.vision.evaluator import AssessmentEvaluator -from tests.support.vision.models import EvaluationReport -from tests.support.vision.repository import ReportWriter, VisionCaseRepository - -pytestmark = pytest.mark.release - -REPORT_PATH = Path("debug/vision_assessment/report.json") -LATENCY_BUDGET_MS = 8000.0 - - -class TestVisionAssessmentGate: - """ - Drives the real model over the multi-app real-pixel corpus and evaluates the effective shadow admission rule. - """ - - async def test_effective_shadow_admission_has_no_false_positive_advancement( - self, - llm: LLMPort, - memory_port_stub: MemoryPort, - ) -> None: - """ - The effective rule must not advance any negative case, still advance positives, and stay in latency budget. - """ - - capabilities = RuntimeCapabilities(hitl=HITLCapability(enabled=False)) - tools = ToolScope(policies=DEFAULT_TOOL_POLICIES).compute( - context=ToolPolicyContext(capabilities=capabilities) - ) - service = VisionService( - llm=llm, - memory=memory_port_stub, - telemetry=NoopTelemetry(), - use_cache=False, - capabilities=capabilities, - session_id="live-assessment", - ) - evaluator = AssessmentEvaluator( - service=service, - repository=VisionCaseRepository(), - candidate=ShadowCandidate(), - tools=tools, - memory=memory_port_stub, - reps=int(os.getenv("FATHOM_ASSESS_REPS", "3")), - ) - - cases = await evaluator.evaluate(cases=CASES) - report = EvaluationReport.assemble( - model=llm.model_name, - reps_per_case=int(os.getenv("FATHOM_ASSESS_REPS", "3")), - latency_budget_ms=LATENCY_BUDGET_MS, - cases=cases, - ) - ReportWriter().write(report=report, path=REPORT_PATH) - await llm.cleanup() - - self.__print(report=report) - - self.__assertions(report=report) - - @staticmethod - def __print(*, report: EvaluationReport) -> None: - """ - Emit a compact human-readable table alongside the persisted typed report. - """ - - print("\n=== EFFECTIVE SHADOW ADMISSION — real model, real-pixel corpus ===") - print( - f"model={report.model} reps/case={report.reps_per_case} apps={list(report.apps)} " - f"cases={len(report.cases)} attempts={report.totals.attempts}" - ) - print( - f"raw FP/FN={report.totals.raw_false_positive}/{report.totals.raw_false_negative} " - f"effective FP/FN={report.totals.effective_false_positive}/{report.totals.effective_false_negative} " - f"missing={report.totals.missing} schema_fail={report.totals.schema_failures} " - f"latency p50/p95/max={report.latency.p50_ms}/{report.latency.p95_ms}/{report.latency.max_ms}ms" - ) - for case in report.cases: - print( - f"{case.name:30} {case.app:12} exp_adv={str(case.expected_admission):5} " - f"rawFP={case.raw_false_positive} effFP={case.effective_false_positive} " - f"effFN={case.effective_false_negative} miss={case.missing} " - f"verdicts={[attempt.verdict.value if attempt.verdict else 'MISSING' for attempt in case.attempts]}" - ) - print( - f"acceptance_passed={report.acceptance_passed} " - f"critical_effFP={report.critical_effective_false_positive} " - f"unresolved_rawFP={list(report.unresolved_raw_false_positive)}" - ) - - def __assertions(self, *, report: EvaluationReport) -> None: - """ - Enforce every cutover acceptance condition as hard assertions. - """ - - assert report.totals.missing == 0, ( - "An observed goal produced no assessment; the boundary failed to decode." - ) - assert report.totals.schema_failures == 0, ( - "An assessment failed its schema at the production boundary." - ) - assert report.totals.effective_false_positive == 0, ( - f"Effective false-positive advancement remains: {list(report.unresolved_raw_false_positive)}." - ) - assert report.critical_effective_false_positive == 0, ( - "A critical-negative case advanced under the shadow rule." - ) - assert not report.unresolved_raw_false_positive, ( - f"Raw false positives not neutralized by a deterministic veto: {list(report.unresolved_raw_false_positive)}." - ) - positives_retained = [ - case.name - for case in report.cases - if case.expected_admission and case.effective_false_negative > 0 - ] - assert not positives_retained, f"Positive cases failed to advance: {positives_retained}." - assert report.latency.p95_ms <= report.latency_budget_ms, ( - f"p95 latency {report.latency.p95_ms}ms exceeds budget {report.latency_budget_ms}ms." - ) - assert report.acceptance_passed, "Cutover acceptance did not hold." diff --git a/tests/live/infrastructure/interaction/orm/test_conversation.py b/tests/live/infrastructure/interaction/orm/test_conversation.py index 4f0c793e..3873148f 100644 --- a/tests/live/infrastructure/interaction/orm/test_conversation.py +++ b/tests/live/infrastructure/interaction/orm/test_conversation.py @@ -389,7 +389,7 @@ async def __write_conversation( audience=Audience.THREAD, created=now + timedelta(seconds=6), body={ - "package": "com.drizz.live", + "package": "com.example.live", "intent": "Run the live Postgres path.", }, ) @@ -716,7 +716,7 @@ async def __verify_service_reads( assert summary.runs[0].execution.id == ids.execution assert summary.runs[0].intent.packages is not None - assert summary.runs[0].intent.packages.target == "com.drizz.live" + assert summary.runs[0].intent.packages.target == "com.example.live" assert summary.runs[0].intent.text == "Run the live Postgres path." assert summary.runs[0].outcome.status == "success" diff --git a/tests/live/strategies/graph/intent/nodes/test_verify_final_handoff.py b/tests/live/strategies/graph/intent/nodes/test_verify_final_handoff.py index 5f194e93..e5e056e2 100644 --- a/tests/live/strategies/graph/intent/nodes/test_verify_final_handoff.py +++ b/tests/live/strategies/graph/intent/nodes/test_verify_final_handoff.py @@ -2,7 +2,6 @@ import io import time -from pathlib import Path from types import SimpleNamespace from typing import Any, Dict, List, Optional, Sequence from unittest.mock import AsyncMock, MagicMock @@ -91,9 +90,9 @@ def _print_llm_responses(*, responses: List[str]) -> None: print(f"\n[VERIFY_LLM_RESPONSE_{index}]\n{response}\n") -class SalarySeModalFixture: +class FinanceModalFixture: """ - Builds a visual replay of the SalarySe address-confirmation blocker. + Builds a visual replay of the Finance address-confirmation blocker. """ @staticmethod @@ -107,7 +106,7 @@ def capture() -> ScreenCapture: draw.rectangle((0, 0, 402, 874), fill="#f3f3f3") draw.text((30, 60), "Selected Address", fill="#666666") - draw.text((30, 90), "SalarySe office", fill="#111111") + draw.text((30, 90), "Finance office", fill="#111111") draw.rectangle((0, 0, 402, 874), fill="#000000") draw.rectangle((36, 280, 366, 560), fill="#ffffff", outline="#222222", width=2) @@ -125,13 +124,13 @@ def capture() -> ScreenCapture: height=874, image=buffer.getvalue(), timestamp=int(time.time() * 1000), - activity="in.swiggy.android/.HomeActivity", + activity="com.example.delivery/.HomeActivity", ) @staticmethod def completed_capture() -> ScreenCapture: """ - Render the post-correction screen where the SalarySe address is selected and no modal remains. + Render the post-correction screen where the Finance address is selected and no modal remains. """ image = Image.new("RGB", (402, 874), "#ffffff") @@ -140,9 +139,9 @@ def completed_capture() -> ScreenCapture: draw.rectangle((0, 0, 402, 96), fill="#fc8019") draw.text((24, 36), "Selected Address", fill="#ffffff") draw.rectangle((24, 140, 378, 260), fill="#f7fff7", outline="#178a3b", width=3) - draw.text((48, 170), "SalarySe office", fill="#111111") + draw.text((48, 170), "Finance office", fill="#111111") draw.text((48, 205), "Delivery address selected", fill="#178a3b") - draw.text((48, 330), "Restaurants near SalarySe office", fill="#111111") + draw.text((48, 330), "Restaurants near Finance office", fill="#111111") draw.rectangle((48, 385, 354, 455), fill="#f1f1f1", outline="#dddddd") draw.text((72, 410), "Food delivery home screen", fill="#333333") @@ -154,60 +153,7 @@ def completed_capture() -> ScreenCapture: height=874, image=buffer.getvalue(), timestamp=int(time.time() * 1000), - activity="in.swiggy.android/.HomeActivity", - ) - - -class HsrProdAssetFixture: - """ - Loads the downloaded 6f72ec86 Swiggy screenshots for live verifier replay. - """ - - ASSET_ROOT = Path( - "/Users/aman/Desktop/Drizz/fathom/debug/" - "6f72ec86-5952-4850-add9-631b4858c6aa/assets/screenshot/" - "6f72ec86-5952-4850-add9-631b4858c6aa" - ) - MODAL_SCREENSHOT = ASSET_ROOT / "step-005__screenshot__2026-06-11T06-28-10Z-692.png" - COMPLETED_SCREENSHOT = ASSET_ROOT / "step-006__screenshot__2026-06-11T06-28-25Z-609.png" - - @classmethod - def is_available(cls) -> bool: - """ - Return whether the downloaded prod replay screenshots are present locally. - """ - - return cls.MODAL_SCREENSHOT.exists() and cls.COMPLETED_SCREENSHOT.exists() - - @classmethod - def captures(cls) -> List[ScreenCapture]: - """ - Return modal and completed captures from the downloaded prod artifacts. - """ - - return [ - cls.__capture(path=cls.MODAL_SCREENSHOT, timestamp=1781159290692), - cls.__capture(path=cls.COMPLETED_SCREENSHOT, timestamp=1781159305609), - ] - - @staticmethod - def __capture(*, path: Path, timestamp: int) -> ScreenCapture: - """ - Build a ScreenCapture from a downloaded screenshot path. - """ - - image = Image.open(path) - try: - width, height = image.size - finally: - image.close() - - return ScreenCapture( - width=width, - height=height, - image=path.read_bytes(), - timestamp=timestamp, - activity="in.swiggy.android", + activity="com.example.delivery/.HomeActivity", ) @@ -335,7 +281,7 @@ def __init__( agent_state=agent_state, perception=_Perception( captures=captures - or [SalarySeModalFixture.capture(), SalarySeModalFixture.completed_capture()] + or [FinanceModalFixture.capture(), FinanceModalFixture.completed_capture()] ), context_manager=self.context_manager, auditor=SimpleNamespace(log_step=MagicMock()), @@ -355,7 +301,7 @@ async def is_cancelled(self) -> bool: return False -class TestSalarySeFinalVerifyLive: +class TestFinanceFinalVerifyLive: """ Live Gemini replay for the final-subgoal VERIFY rejection case. """ @@ -363,7 +309,7 @@ class TestSalarySeFinalVerifyLive: @staticmethod def __agent_state() -> AgentState: """ - Build AgentState with the final SalarySe sub-goal active. + Build AgentState with the final Finance sub-goal active. """ agent_state = AgentState( @@ -375,54 +321,18 @@ def __agent_state() -> AgentState: timestamp=1, visual_hash="1" * 16, activity_hash="a" * 16, - activity="in.swiggy.android/.HomeActivity", + activity="com.example.delivery/.HomeActivity", ) ) agent_state.set_sub_goals( [ SubGoalFixtures.make(index=0, description="Tap address selector"), - SubGoalFixtures.make(index=1, description="Confirm SalarySe office address"), + SubGoalFixtures.make(index=1, description="Confirm Finance office address"), ] ) agent_state.advance_current_sub_goal() return agent_state - @staticmethod - def __hsr_agent_state() -> AgentState: - """ - Build AgentState at the 6f72ec86 final-confirmation handoff. - """ - - agent_state = AgentState( - intent="Change the address to HSR Layout", - capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=False)), - ) - agent_state.update_screen( - screen=ScreenState( - timestamp=1, - visual_hash="1" * 16, - activity_hash="a" * 16, - activity="in.swiggy.android", - ) - ) - agent_state.set_sub_goals( - [ - SubGoalFixtures.make( - index=0, description="Tap on the current address or change address option" - ), - SubGoalFixtures.make( - index=1, description="Type HSR Layout into the address search field" - ), - SubGoalFixtures.make(index=2, description="Tap HSR Layout from the search results"), - SubGoalFixtures.make( - index=3, description="Tap the button to confirm or save the address change" - ), - ] - ) - for _ in range(3): - agent_state.advance_current_sub_goal() - return agent_state - @staticmethod def __corrective_step_result() -> StepResult: """ @@ -454,28 +364,7 @@ def __completed_screen_state() -> ScreenState: timestamp=2, visual_hash="2" * 16, activity_hash="a" * 16, - activity="in.swiggy.android/.HomeActivity", - ) - - @staticmethod - def __hsr_corrective_step_result() -> StepResult: - """ - Build the corrective HSR modal action from the prod run. - """ - - action = Action( - confidence=1.0, - action_type=ActionType.TAP, - target="Yes, continue with this location", - rationale="Tap the confirmation modal action before validating HSR Layout", - ) - return StepResult( - success=True, - duration=6749, - pre_hash="f75dfff77f7ff7df", - post_hash="ae41df2b4e7fb7df", - screen_changed=True, - step=Step(action=action, step_number=6, screen_hash="f75dfff77f7ff7df"), + activity="com.example.delivery/.HomeActivity", ) def __record_state(self) -> Dict[object, object]: @@ -486,34 +375,12 @@ def __record_state(self) -> Dict[object, object]: return { CommonStateKey.IS_NEW_SCREEN: True, CommonStateKey.SCREEN_STATE: self.__completed_screen_state(), - IntentStateKey.POST_ACTIVITY: "in.swiggy.android/.HomeActivity", + IntentStateKey.POST_ACTIVITY: "com.example.delivery/.HomeActivity", CommonStateKey.STEP_RESULT: self.__corrective_step_result(), IntentStateKey.PLAN: PlanResult( step=None, is_complete=True, - reason="SalarySe office address is selected", - ), - } - - def __hsr_record_state(self) -> Dict[object, object]: - """ - Build the graph patch that RECORD sees after tapping the HSR confirmation action. - """ - - return { - CommonStateKey.IS_NEW_SCREEN: True, - CommonStateKey.SCREEN_STATE: ScreenState( - timestamp=2, - visual_hash="ae41df2b4e7fb7df", - activity_hash="a" * 16, - activity="in.swiggy.android", - ), - IntentStateKey.POST_ACTIVITY: "in.swiggy.android", - CommonStateKey.STEP_RESULT: self.__hsr_corrective_step_result(), - IntentStateKey.PLAN: PlanResult( - step=None, - is_complete=True, - reason="HSR Layout is selected in the delivery address header", + reason="Finance office address is selected", ), } @@ -579,50 +446,3 @@ async def test_modal_rejection_then_corrective_record_completes_intent( assert agent_state.all_sub_goals_complete() is True assert provider.context_manager.cleared is True _print_llm_responses(responses=recording_llm.responses) - - async def test_hsr_prod_artifact_replay_rejects_then_completes(self, llm: LLMPort) -> None: - """ - Live Gemini replay of 6f72ec86 using the downloaded modal and post-correction screenshots. - """ - - if not HsrProdAssetFixture.is_available(): - pytest.skip("6f72ec86 downloaded screenshots are not available in debug assets") - - agent_state = self.__hsr_agent_state() - recording_llm = _RecordingLlm(llm=llm) - provider = _Provider( - llm=recording_llm, - agent_state=agent_state, - captures=HsrProdAssetFixture.captures(), - intent="Change the address to HSR Layout", - workflow_id="live-6f72ec86-hsr-final-verify", - ) - verify = VerifyNode(provider=provider) # type: ignore[arg-type] - record = RecordNode(provider=provider) # type: ignore[arg-type] - - rejected = await verify.run( - state={IntentStateKey.VERIFY_MODE: VerifyMode.PENDING_FINAL_COMMIT.value} - ) # type: ignore[arg-type] - - assert rejected[CommonStateKey.IS_COMPLETE] is False - assert rejected[IntentStateKey.SHOULD_RETRY] is True - assert agent_state.current_sub_goal_index == 3 - assert provider.context_manager.feedback - - pending_again = await record.run(state=self.__hsr_record_state()) # type: ignore[arg-type] - - assert pending_again[CommonStateKey.IS_COMPLETE] is True - assert pending_again[IntentStateKey.SHOULD_RETRY] is False - assert pending_again[IntentStateKey.VERIFY_MODE] == VerifyMode.PENDING_FINAL_COMMIT.value - assert agent_state.current_sub_goal_index == 3 - assert agent_state.is_complete is False - - accepted = await verify.run(state=pending_again) # type: ignore[arg-type] - - assert accepted[CommonStateKey.IS_COMPLETE] is True - assert accepted[IntentStateKey.SHOULD_RETRY] is False - assert accepted[IntentStateKey.VERIFY_MODE] is None - assert agent_state.is_complete is True - assert agent_state.all_sub_goals_complete() is True - assert provider.context_manager.cleared is True - _print_llm_responses(responses=recording_llm.responses) diff --git a/tests/support/vision/__init__.py b/tests/support/vision/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/support/vision/evaluator.py b/tests/support/vision/evaluator.py deleted file mode 100644 index 0ff4a8fa..00000000 --- a/tests/support/vision/evaluator.py +++ /dev/null @@ -1,230 +0,0 @@ -from __future__ import annotations - -import hashlib -from time import perf_counter -from typing import List, Tuple - -from fathom.constants.assessment import VisualVerdict -from fathom.constants.success import SuccessKind -from fathom.constants.turn.advancement import AdvanceKind, ObservationPhase -from fathom.core.agent.candidate import ShadowCandidate -from fathom.core.agent.shadow import ShadowAssessor -from fathom.core.context.manager import ContextManager -from fathom.core.services.vision import SubGoalContext, VisionService -from fathom.interfaces.memory import MemoryPort -from fathom.schemas.results import AnalysisResult -from fathom.schemas.screens import ScreenCapture -from fathom.schemas.success import ObservedSuccess, Success -from fathom.schemas.target import TargetAuthority -from fathom.schemas.tools import AllowedTools -from tests.builders.success import SuccessFixtures -from tests.fixtures.vision.corpus import VisionCase -from tests.support.vision.models import CaseAttempt, CaseReport -from tests.support.vision.repository import VisionCaseRepository - -STATIC_SCREEN = "static-corpus-screen" - - -class AssessmentEvaluator: - """ - Runs each corpus case through the production single-call boundary and records complete per-attempt evidence. - """ - - def __init__( - self, - *, - service: VisionService, - repository: VisionCaseRepository, - candidate: ShadowCandidate, - tools: AllowedTools, - memory: MemoryPort, - reps: int, - ) -> None: - """ - Bind the production service, the fixture repository, the shared advancement candidate, and the run shape. - """ - - self.__service = service - self.__repository = repository - self.__candidate = candidate - self.__assessor = ShadowAssessor() - self.__tools = tools - self.__memory = memory - self.__reps = reps - - async def evaluate(self, *, cases: Tuple[VisionCase, ...]) -> Tuple[CaseReport, ...]: - """ - Evaluate every case across all repetitions and fold the attempts into case reports. - """ - - return tuple([await self.__case(case=case) for case in cases]) - - async def __case(self, *, case: VisionCase) -> CaseReport: - """ - Run one case for every repetition and assemble its report. - """ - - success = self.__success(case=case) - sub_goal = self.__sub_goal(case=case) - capture = self.__capture(case=case) - authority = ( - TargetAuthority.requested(package=case.authority_package) - if case.authority_package is not None - else TargetAuthority.unbound() - ) - - attempts: List[CaseAttempt] = [] - for rep in range(self.__reps): - context = ContextManager(memory=self.__memory, workflow_id=f"assess-{case.name}-{rep}") - started = perf_counter() - analysis = await self.__service.analyze( - intent=case.assertion, - tools=self.__tools, - capture=capture, - context_manager=context, - visual_hash=hashlib.sha256(f"{case.name}:{rep}".encode()).hexdigest()[:16], - screen_width=capture.width, - screen_height=capture.height, - sub_goal_info=sub_goal, - ) - latency_ms = (perf_counter() - started) * 1000.0 - attempts.append( - self.__attempt( - case=case, - rep=rep, - analysis=analysis, - latency_ms=latency_ms, - success=success, - authority=authority, - foreground_package=capture.activity, - ) - ) - - return CaseReport.assemble( - name=case.name, - app=case.app, - scenario=case.scenario, - goal_kind=case.goal_kind, - provenance=case.provenance, - label_source=case.label_source, - critical_negative=case.critical_negative, - expected_verdict=case.expected_verdict, - expected_admission=case.expected_admission, - attempts=attempts, - ) - - def __attempt( - self, - *, - case: VisionCase, - rep: int, - analysis: AnalysisResult, - latency_ms: float, - success: Success, - authority: TargetAuthority, - foreground_package: str, - ) -> CaseAttempt: - """ - Build the full record for one repetition, including the deterministic admission decision and labels. - """ - - assessment = analysis.visual_assessment - malformed = analysis.assessment_malformed - verdict = assessment.verdict if assessment is not None else None - action = analysis.action - action_present = action is not None - - candidate = self.__candidate.decide( - success=success, - phase=ObservationPhase.POST_DISPATCH, - assessment=assessment, - malformed=malformed, - action_present=action_present, - screen=STATIC_SCREEN, - authority=authority, - foreground=foreground_package, - execution=None, - ) - admitted = candidate.kind in (AdvanceKind.ADVANCE, AdvanceKind.SATISFIED_PRIOR) - divergences = tuple( - divergence.kind - for divergence in self.__assessor.assess( - success=success, - assessment=assessment, - action_present=action_present, - assessment_malformed=malformed, - authority=authority, - foreground_package=foreground_package, - ) - ) - satisfied = verdict is VisualVerdict.SATISFIED - missing = isinstance(success, ObservedSuccess) and assessment is None and not malformed - raw_false_positive = satisfied and not case.truth_satisfied - raw_false_negative = case.truth_satisfied and not satisfied - - return CaseAttempt( - rep=rep, - assertion=case.assertion, - expected_verdict=case.expected_verdict, - expected_admission=case.expected_admission, - verdict=verdict, - confidence=assessment.confidence if assessment is not None else None, - evidence=assessment.evidence if assessment is not None else None, - action_type=action.action_type.value if action is not None else None, - action_target=action.target if action is not None else None, - action_present=action_present, - foreground_package=foreground_package, - authority_package=authority.package, - divergences=divergences, - schema_malformed=malformed, - missing=missing, - raw_false_positive=raw_false_positive, - raw_false_negative=raw_false_negative, - admitted=admitted, - effective_false_positive=admitted and not case.expected_admission, - effective_false_negative=not admitted and case.expected_admission, - latency_ms=latency_ms, - ) - - @staticmethod - def __success(*, case: VisionCase) -> Success: - """ - Build the active goal's typed success from the case's declared goal kind. - """ - - if case.goal_kind is SuccessKind.OBSERVED: - return SuccessFixtures.observed(assertion=case.assertion) - if case.goal_kind is SuccessKind.COMMAND: - return SuccessFixtures.command() - return SuccessFixtures.capture() - - @staticmethod - def __sub_goal(*, case: VisionCase) -> SubGoalContext: - """ - Thread the assertion only for observed goals; command and capture goals request no assessment. - """ - - context = SubGoalContext( - index=0, - total=2, - description=f"Reach the state: {case.assertion}", - durable=case.goal_kind is not SuccessKind.OBSERVED, - ) - if case.goal_kind is SuccessKind.OBSERVED: - context["assertion"] = case.assertion - return context - - def __capture(self, *, case: VisionCase) -> ScreenCapture: - """ - Wrap the committed pixels with a truthful foreground package and real dimensions. - """ - - data = self.__repository.image_bytes(case=case) - width, height = self.__repository.dimensions(case=case) - return ScreenCapture( - width=width, - height=height, - activity=case.package, - image=data, - timestamp=0, - ) diff --git a/tests/support/vision/models.py b/tests/support/vision/models.py deleted file mode 100644 index 5e5634c6..00000000 --- a/tests/support/vision/models.py +++ /dev/null @@ -1,319 +0,0 @@ -from __future__ import annotations - -from enum import StrEnum -from math import ceil -from typing import Optional, Sequence, Tuple - -from pydantic import Field - -from fathom.constants.assessment import ShadowDivergenceKind, VisualVerdict -from fathom.constants.success import SuccessKind -from fathom.schemas.base.common import NonBlank, SealedModel - - -class LabelSource(StrEnum): - """ - Whether a case's ground-truth label was assigned by human inspection or produced programmatically. - """ - - HUMAN = "HUMAN" - PROGRAMMATIC = "PROGRAMMATIC" - - -class CaseAttempt(SealedModel): - """ - One live repetition of one case: the model output, the deterministic shadow admission, and its labels. - """ - - rep: int = Field(ge=0, description="Zero-based repetition index for this case.") - assertion: NonBlank = Field( - description="Exact assertion threaded into the prompt this attempt." - ) - expected_verdict: VisualVerdict = Field(description="Oracle verdict for an observed goal.") - expected_admission: bool = Field( - description="Whether the effective rule should advance this attempt." - ) - verdict: Optional[VisualVerdict] = Field( - default=None, description="Model verdict, or None when absent." - ) - confidence: Optional[float] = Field( - default=None, description="Model confidence; recorded for calibration only." - ) - evidence: Optional[str] = Field( - default=None, description="Concise visible evidence the model cited." - ) - action_type: Optional[str] = Field( - default=None, description="Proposed action type, or None when absent." - ) - action_target: Optional[str] = Field( - default=None, description="Proposed action target, or None when absent." - ) - action_present: bool = Field( - description="Whether the model proposed an action on the same response." - ) - foreground_package: Optional[str] = Field( - default=None, description="Foreground package on the captured screen." - ) - authority_package: Optional[str] = Field( - default=None, description="Bound TargetAuthority package, or None." - ) - divergences: Tuple[ShadowDivergenceKind, ...] = Field( - default=(), description="Every deterministic shadow divergence recorded for this attempt." - ) - schema_malformed: bool = Field( - default=False, description="Whether the assessment payload failed its schema." - ) - missing: bool = Field( - default=False, description="Whether an observed goal produced no assessment at all." - ) - raw_false_positive: bool = Field( - description="Verdict SATISFIED while the oracle says not satisfied." - ) - raw_false_negative: bool = Field( - description="Verdict withheld while the oracle says satisfied." - ) - admitted: bool = Field( - description="Whether the effective shadow rule would advance the goal this attempt." - ) - effective_false_positive: bool = Field( - description="Admitted advance while the oracle says not satisfied." - ) - effective_false_negative: bool = Field( - description="Not admitted while the oracle says satisfied." - ) - latency_ms: float = Field( - ge=0.0, description="Wall-clock latency of the single production call." - ) - - -class LatencySummary(SealedModel): - """ - Distribution of single-call latencies in milliseconds. - """ - - samples: int = Field(ge=0, description="Number of latency samples.") - min_ms: float = Field(ge=0.0, description="Fastest observed call.") - p50_ms: float = Field(ge=0.0, description="Median call latency.") - p95_ms: float = Field(ge=0.0, description="95th-percentile call latency.") - max_ms: float = Field(ge=0.0, description="Slowest observed call.") - - @classmethod - def from_samples(cls, *, samples: Sequence[float]) -> "LatencySummary": - """ - Build a summary using nearest-rank percentiles; an empty input yields all zeros. - """ - - if not samples: - return cls(samples=0, min_ms=0.0, p50_ms=0.0, p95_ms=0.0, max_ms=0.0) - - ordered = sorted(samples) - count = len(ordered) - return cls( - samples=count, - min_ms=round(ordered[0], 1), - p50_ms=round(ordered[cls.__rank(count=count, quantile=0.50)], 1), - p95_ms=round(ordered[cls.__rank(count=count, quantile=0.95)], 1), - max_ms=round(ordered[-1], 1), - ) - - @staticmethod - def __rank(*, count: int, quantile: float) -> int: - """ - Return the nearest-rank index into an ascending sequence for a quantile. - """ - - return min(count - 1, max(0, ceil(quantile * count) - 1)) - - -class CaseReport(SealedModel): - """ - Aggregated outcome for one case across all repetitions. - """ - - name: NonBlank = Field(description="Case identifier.") - app: NonBlank = Field(description="Application exercised by the screen.") - scenario: NonBlank = Field(description="Screen type / adversarial trap this case represents.") - goal_kind: SuccessKind = Field(description="Success kind of the active goal.") - provenance: NonBlank = Field( - description="Source of the pixels (trace run path or a controlled tag)." - ) - label_source: LabelSource = Field(description="How this case's ground-truth was labeled.") - critical_negative: bool = Field( - description="Whether an effective false positive here blocks cutover." - ) - expected_verdict: VisualVerdict = Field(description="Oracle verdict.") - expected_admission: bool = Field( - description="Whether the effective rule should advance this case." - ) - attempts: Tuple[CaseAttempt, ...] = Field(description="Every repetition's full record.") - latency: LatencySummary = Field(description="Latency distribution across repetitions.") - raw_false_positive: int = Field( - ge=0, description="Repetitions with a raw verdict false positive." - ) - raw_false_negative: int = Field( - ge=0, description="Repetitions with a raw verdict false negative." - ) - effective_false_positive: int = Field( - ge=0, description="Repetitions admitted to advance against the oracle." - ) - effective_false_negative: int = Field( - ge=0, description="Repetitions wrongly not admitted for a satisfied goal." - ) - missing: int = Field(ge=0, description="Repetitions with no assessment for an observed goal.") - schema_failures: int = Field( - ge=0, description="Repetitions whose assessment failed its schema." - ) - - @classmethod - def assemble( - cls, - *, - name: str, - app: str, - scenario: str, - goal_kind: SuccessKind, - provenance: str, - label_source: LabelSource, - critical_negative: bool, - expected_verdict: VisualVerdict, - expected_admission: bool, - attempts: Sequence[CaseAttempt], - ) -> "CaseReport": - """ - Fold the per-attempt records into a single case report. - """ - - return cls( - name=name, - app=app, - scenario=scenario, - goal_kind=goal_kind, - provenance=provenance, - label_source=label_source, - critical_negative=critical_negative, - expected_verdict=expected_verdict, - expected_admission=expected_admission, - attempts=tuple(attempts), - latency=LatencySummary.from_samples( - samples=[attempt.latency_ms for attempt in attempts] - ), - raw_false_positive=sum(1 for attempt in attempts if attempt.raw_false_positive), - raw_false_negative=sum(1 for attempt in attempts if attempt.raw_false_negative), - effective_false_positive=sum( - 1 for attempt in attempts if attempt.effective_false_positive - ), - effective_false_negative=sum( - 1 for attempt in attempts if attempt.effective_false_negative - ), - missing=sum(1 for attempt in attempts if attempt.missing), - schema_failures=sum(1 for attempt in attempts if attempt.schema_malformed), - ) - - -class Totals(SealedModel): - """ - Corpus-wide counts across every case and repetition. - """ - - attempts: int = Field(ge=0, description="Total repetitions executed.") - raw_false_positive: int = Field(ge=0, description="Total raw verdict false positives.") - raw_false_negative: int = Field(ge=0, description="Total raw verdict false negatives.") - effective_false_positive: int = Field( - ge=0, description="Total effective false-positive advancements." - ) - effective_false_negative: int = Field( - ge=0, description="Total effective false-negative retentions." - ) - missing: int = Field(ge=0, description="Total observed-goal calls with no assessment.") - schema_failures: int = Field(ge=0, description="Total assessments that failed their schema.") - - @classmethod - def from_cases(cls, *, cases: Sequence[CaseReport]) -> "Totals": - """ - Sum the case reports into corpus-wide totals. - """ - - return cls( - attempts=sum(len(case.attempts) for case in cases), - raw_false_positive=sum(case.raw_false_positive for case in cases), - raw_false_negative=sum(case.raw_false_negative for case in cases), - effective_false_positive=sum(case.effective_false_positive for case in cases), - effective_false_negative=sum(case.effective_false_negative for case in cases), - missing=sum(case.missing for case in cases), - schema_failures=sum(case.schema_failures for case in cases), - ) - - -class EvaluationReport(SealedModel): - """ - The complete shadow-gate evidence: totals, latency, per-case reports, and the acceptance decision. - """ - - model: NonBlank = Field(description="Model identifier used for the run.") - reps_per_case: int = Field(gt=0, description="Repetitions executed per case.") - apps: Tuple[str, ...] = Field(description="Distinct applications covered by the corpus.") - provenances: Tuple[str, ...] = Field( - description="Distinct pixel sources covered by the corpus." - ) - totals: Totals = Field(description="Corpus-wide counts.") - latency: LatencySummary = Field(description="Latency distribution across all calls.") - latency_budget_ms: float = Field( - gt=0.0, description="The p95 latency budget the gate is held to." - ) - critical_effective_false_positive: int = Field( - ge=0, description="Effective false-positive advancements on critical-negative cases." - ) - unresolved_raw_false_positive: Tuple[str, ...] = Field( - description="Case names whose raw false positive was not neutralized by a deterministic veto." - ) - acceptance_passed: bool = Field(description="Whether every cutover acceptance condition held.") - cases: Tuple[CaseReport, ...] = Field(description="Every case's aggregated report.") - - @classmethod - def assemble( - cls, - *, - model: str, - reps_per_case: int, - latency_budget_ms: float, - cases: Sequence[CaseReport], - ) -> "EvaluationReport": - """ - Assemble the corpus report and evaluate cutover acceptance from the case records. - """ - - totals = Totals.from_cases(cases=cases) - latency = LatencySummary.from_samples( - samples=[attempt.latency_ms for case in cases for attempt in case.attempts] - ) - critical_fp = sum(case.effective_false_positive for case in cases if case.critical_negative) - unresolved = tuple( - case.name - for case in cases - if case.raw_false_positive > 0 and case.effective_false_positive > 0 - ) - positives_advance = all( - case.effective_false_negative == 0 for case in cases if case.expected_admission - ) - acceptance = ( - critical_fp == 0 - and totals.effective_false_positive == 0 - and not unresolved - and positives_advance - and totals.missing == 0 - and totals.schema_failures == 0 - and latency.p95_ms <= latency_budget_ms - ) - return cls( - model=model, - reps_per_case=reps_per_case, - apps=tuple(sorted({case.app for case in cases})), - provenances=tuple(sorted({case.provenance for case in cases})), - totals=totals, - latency=latency, - latency_budget_ms=latency_budget_ms, - critical_effective_false_positive=critical_fp, - unresolved_raw_false_positive=unresolved, - acceptance_passed=acceptance, - cases=tuple(cases), - ) diff --git a/tests/support/vision/repository.py b/tests/support/vision/repository.py deleted file mode 100644 index 5652fd5b..00000000 --- a/tests/support/vision/repository.py +++ /dev/null @@ -1,64 +0,0 @@ -from __future__ import annotations - -import io -from pathlib import Path -from typing import Tuple - -from PIL import Image - -from tests.fixtures.vision.corpus import VisionCase -from tests.support.vision.models import EvaluationReport - - -class VisionCaseRepository: - """ - Loads real-pixel case bytes and dimensions; the case entities stay data-only. - """ - - def __init__(self, *, root: Path | None = None) -> None: - """ - Bind the fixtures root; defaults to the committed tests/fixtures/vision directory. - """ - - self.__root = ( - root - if root is not None - else Path(__file__).resolve().parents[2] / "fixtures" / "vision" - ) - - @property - def screens(self) -> Path: - """ - Directory holding the committed screenshots. - """ - - return self.__root / "screens" - - def image_bytes(self, *, case: VisionCase) -> bytes: - """ - Return the committed pixels for a case. - """ - - return (self.screens / case.screenshot).read_bytes() - - def dimensions(self, *, case: VisionCase) -> Tuple[int, int]: - """ - Return the pixel width and height of a case screenshot. - """ - - with Image.open(io.BytesIO(self.image_bytes(case=case))) as image: - return image.size - - -class ReportWriter: - """ - Persists an evaluation report as canonical JSON. - """ - - def write(self, *, report: EvaluationReport, path: Path) -> None: - """ - Serialize the typed report to the given path, creating parent directories. - """ - - path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(report.model_dump_json(indent=2)) diff --git a/tests/unit/adapters/device/local/test_adb.py b/tests/unit/adapters/device/local/test_adb.py index 2af8cc21..9f576eec 100644 --- a/tests/unit/adapters/device/local/test_adb.py +++ b/tests/unit/adapters/device/local/test_adb.py @@ -321,12 +321,12 @@ class ADBDeviceFrameParseTest(unittest.TestCase): WINDOW MANAGER WINDOWS (dumpsys window windows) Window #0 Window{1a2b3c4 u0 NavigationBar0}: mFrame=[0,2148][1080,2208] - Window #1 Window{5d6e7f8 u0 com.swiggy.android/com.swiggy.android.MainActivity}: + Window #1 Window{5d6e7f8 u0 com.delivery.android/com.delivery.android.MainActivity}: mDisplayId=0 rootTaskId=1 mFrame=[0,80][1080,2080] Window #2 Window{9a8b7c6 u0 StatusBar}: mFrame=[0,0][1080,80] - mCurrentFocus=Window{5d6e7f8 u0 com.swiggy.android/com.swiggy.android.MainActivity} + mCurrentFocus=Window{5d6e7f8 u0 com.delivery.android/com.delivery.android.MainActivity} """ def test_parses_focused_window_frame(self) -> None: diff --git a/tests/unit/adapters/interaction/orm/__init__.py b/tests/unit/adapters/interaction/orm/__init__.py index f18e9e24..41375bed 100644 --- a/tests/unit/adapters/interaction/orm/__init__.py +++ b/tests/unit/adapters/interaction/orm/__init__.py @@ -1 +1,3 @@ -"""Tests for ORM-backed interaction adapters.""" +""" +Tests for ORM-backed interaction adapters. +""" diff --git a/tests/unit/adapters/llm/test_gemini.py b/tests/unit/adapters/llm/test_gemini.py index 00de472c..b10f9b8a 100644 --- a/tests/unit/adapters/llm/test_gemini.py +++ b/tests/unit/adapters/llm/test_gemini.py @@ -234,7 +234,9 @@ def test_cancelled_detection_uses_status_code(self) -> None: self.assertTrue(result) def test_generation_config_maps_unavailable_thinking_levels(self) -> None: - """Falls back to LOW when the SDK does not expose the requested thinking level.""" + """ + Falls back to LOW when the SDK does not expose the requested thinking level. + """ gemini = object.__new__(GeminiLLM) gemini._GeminiLLM__configuration = LLMConfiguration( @@ -250,7 +252,9 @@ def test_generation_config_maps_unavailable_thinking_levels(self) -> None: self.assertEqual(config.thinking_config.thinking_level, types.ThinkingLevel.LOW) def test_async_timeout_does_not_match_cancelled_classifier(self) -> None: - """Regression: asyncio.wait_for raises asyncio.TimeoutError when the per-attempt budget expires.""" + """ + Regression: asyncio.wait_for raises asyncio.TimeoutError when the per-attempt budget expires. + """ timeout_message = str(asyncio.TimeoutError()).casefold() result = GeminiLLM._GeminiLLM__is_cancelled_error(status_code=None, text=timeout_message) diff --git a/tests/unit/adapters/localization/gemini/test_vision.py b/tests/unit/adapters/localization/gemini/test_vision.py index b088369d..6f0a731c 100644 --- a/tests/unit/adapters/localization/gemini/test_vision.py +++ b/tests/unit/adapters/localization/gemini/test_vision.py @@ -229,7 +229,9 @@ async def test_grid_payload_survives_dispatch_translation_on_retina(self) -> Non self.assertEqual(dispatch_height, 43) async def test_all_zero_payload_is_refusal_not_zero_bound_proposal(self) -> None: - """The all-zero coordinate/confidence payload is the refusal protocol marker.""" + """ + The all-zero coordinate/confidence payload is the refusal protocol marker. + """ llm = _StaticLlm( payload={ @@ -300,7 +302,9 @@ async def test_blank_target_short_circuits_before_llm_call(self) -> None: self.assertEqual(llm.calls, 0) async def test_zero_pixel_box_rejected_as_invalid(self) -> None: - """Payloads whose projected width or height rounds to zero pixels are rejected even when the grid coordinates are non-zero.""" + """ + Payloads whose projected width or height rounds to zero pixels are rejected even when the grid coordinates are non-zero. + """ llm = _StaticLlm( payload={ @@ -324,7 +328,9 @@ async def test_zero_pixel_box_rejected_as_invalid(self) -> None: self.assertIsNone(result) async def test_confidence_out_of_range_returns_none(self) -> None: - """Provider-reported confidence outside the closed unit interval is rejected at the schema boundary.""" + """ + Provider-reported confidence outside the closed unit interval is rejected at the schema boundary. + """ llm = _StaticLlm( payload={ diff --git a/tests/unit/adapters/ocr/document/test_adapter.py b/tests/unit/adapters/ocr/document/test_adapter.py index c19e58e2..7844d6ea 100644 --- a/tests/unit/adapters/ocr/document/test_adapter.py +++ b/tests/unit/adapters/ocr/document/test_adapter.py @@ -148,18 +148,6 @@ async def test_extract_returns_empty_result_for_empty_document(self) -> None: self.assertIsNotNone(result.raw_response) self.assertIn('"text": ""', result.raw_response or "") - async def test_extract_invokes_client_with_processor_path(self) -> None: - """ - The adapter delegates the call to the Document AI client exactly once. - """ - - client = _StubClient(document=self.__empty_document()) - adapter = DocumentAiOcr(configuration=self.__configuration(), client=client) - - await adapter.extract(capture=self.__capture(), budget=self.__budget()) - - self.assertEqual(client.calls, 1) - async def test_extract_returns_empty_result_on_provider_exception(self) -> None: """ A client exception must be suppressed at the adapter boundary @@ -227,7 +215,9 @@ def test_build_default_client_when_omitted(self) -> None: self.assertIsNone(kwargs["credentials"]) def test_build_client_materializes_inline_dict_credentials(self) -> None: - """Inline dict credentials are materialized into a :class:`service_account.Credentials` instance via ``from_service_account_info`` and passed to the gRPC client.""" + """ + Inline dict credentials are materialized into a :class:`service_account.Credentials` instance via ``from_service_account_info`` and passed to the gRPC client. + """ configuration = DocumentAiConfiguration( project="vision-478905", @@ -254,7 +244,9 @@ def test_build_client_materializes_inline_dict_credentials(self) -> None: self.assertIs(fake_client_class.call_args.kwargs["credentials"], fake_credentials) def test_build_client_materializes_file_path_credentials(self) -> None: - """A file-path credentials value resolves through ``from_service_account_file`` and is forwarded to the gRPC client.""" + """ + A file-path credentials value resolves through ``from_service_account_file`` and is forwarded to the gRPC client. + """ configuration = DocumentAiConfiguration( project="vision-478905", diff --git a/tests/unit/adapters/ocr/document/test_adapter_pixel_dimensions.py b/tests/unit/adapters/ocr/document/test_adapter_pixel_dimensions.py index 4f12d239..e5760d76 100644 --- a/tests/unit/adapters/ocr/document/test_adapter_pixel_dimensions.py +++ b/tests/unit/adapters/ocr/document/test_adapter_pixel_dimensions.py @@ -38,11 +38,15 @@ def map_document(self, *, document: Any, width: int, height: int) -> Tuple[Any, class _StubDocument: - """Opaque stand-in for a Document AI ``Document``.""" + """ + Opaque stand-in for a Document AI ``Document``. + """ class _StubResponse: - """Carries ``.document``, which is all the adapter reads off the RPC.""" + """ + Carries ``.document``, which is all the adapter reads off the RPC. + """ document = _StubDocument() @@ -72,9 +76,9 @@ class DocumentAiPixelDimensionsTest(unittest.IsolatedAsyncioTestCase): which ``to_logical_dispatch`` then divided by the scale a second time — every OCR-resolved tap landed at 1/scale of its correct distance from the origin. - Live incident 2026-08-06 (iPad Air 4, logical 1180x820 / pixel 2360x1640): - OCR located "Add Visit" at (936, 631), the tap went to (485, 318) — ~590px - away. Identical in runs HXPBk, HawUV and QgzIM. + Concrete case (iPad Air 4, logical 1180x820 / pixel 2360x1640): OCR located "Add Visit" at + (936, 631); passing the logical size sent the tap to (485, 318) — ~590px away, identically + across repeated runs. """ @staticmethod @@ -140,8 +144,7 @@ async def test_logical_and_pixel_agree_on_non_retina(self) -> None: self.assertEqual([(800, 600)], mapper.calls) async def test_falls_back_to_logical_when_image_is_undecodable(self) -> None: - # Garbage bytes must not take the OCR pass down — degrade to the logical - # pair, which is what the adapter used before this fix. + # Garbage bytes must not take the OCR pass down — degrade to the logical pair. mapper = _RecordingMapper() capture = ScreenCapture( width=1180, diff --git a/tests/unit/adapters/perception/test_android.py b/tests/unit/adapters/perception/test_android.py index 30c14a94..77e0ebee 100644 --- a/tests/unit/adapters/perception/test_android.py +++ b/tests/unit/adapters/perception/test_android.py @@ -39,7 +39,7 @@ def __device(cls, *, reported: tuple[int, int]) -> Mock: async def test_landscape_screenshot_swaps_portrait_report(self) -> None: """ - Cooking-Craze-style mismatch: device cache says portrait, screenshot is landscape. + game-app-style mismatch: device cache says portrait, screenshot is landscape. """ screenshot = self.__screenshot(width=2340, height=1080) diff --git a/tests/unit/adapters/perception/test_remote.py b/tests/unit/adapters/perception/test_remote.py index 560e1a6d..74cd32fe 100644 --- a/tests/unit/adapters/perception/test_remote.py +++ b/tests/unit/adapters/perception/test_remote.py @@ -35,7 +35,7 @@ def __build_device(self) -> Mock: device.configuration = DeviceRuntimeConfiguration() device.get_dimensions = AsyncMock(return_value=(1080, 2400)) - device.get_current_package = AsyncMock(return_value="in.swiggy.android") + device.get_current_package = AsyncMock(return_value="com.example.delivery") return device diff --git a/tests/unit/adapters/script/test_refresher.py b/tests/unit/adapters/script/test_refresher.py index 83347d27..016e59c3 100644 --- a/tests/unit/adapters/script/test_refresher.py +++ b/tests/unit/adapters/script/test_refresher.py @@ -31,7 +31,7 @@ StepTarget, ) -PACKAGE: str = "in.swiggy.android" +PACKAGE: str = "com.example.delivery" class _RecordingSource(EvidenceSource): diff --git a/tests/unit/authoring/test_composer.py b/tests/unit/authoring/test_composer.py index 16bccbf0..7065bf60 100644 --- a/tests/unit/authoring/test_composer.py +++ b/tests/unit/authoring/test_composer.py @@ -155,7 +155,7 @@ def test_grounded_launch_baseline_is_not_duplicated_by_step_draft(self) -> None: evidence = Evidence( intent="login", goal="login", - package="com.healthtap.userhtexpress", + package="com.example.health", partial=False, steps=( EvidenceStep( @@ -163,7 +163,7 @@ def test_grounded_launch_baseline_is_not_duplicated_by_step_draft(self) -> None: event="launch", action="launch", launch=StepLaunch( - package="com.healthtap.userhtexpress", + package="com.example.health", provenance=LaunchProvenance.LAUNCHER_TRANSITION, source_steps=(0,), ), @@ -174,14 +174,14 @@ def test_grounded_launch_baseline_is_not_duplicated_by_step_draft(self) -> None: baseline = AuthoringBaseline( content="\n".join( ( - "OPEN_APP: com.healthtap.userhtexpress", + "OPEN_APP: com.example.health", 'Type "user@example.com" into Email field', ) ), partial=False, commands=( AuthoringBaselineCommand( - text="OPEN_APP: com.healthtap.userhtexpress", + text="OPEN_APP: com.example.health", role=ScriptCommandRole.LAUNCH, source_steps=(0,), ), @@ -192,7 +192,7 @@ def test_grounded_launch_baseline_is_not_duplicated_by_step_draft(self) -> None: ), ) drafts = ( - self.__draft(step=0, text="OPEN_APP: com.healthtap.userhtexpress"), + self.__draft(step=0, text="OPEN_APP: com.example.health"), self.__draft(step=1, text='Type "user@example.com" into Email field'), ) @@ -200,7 +200,7 @@ def test_grounded_launch_baseline_is_not_duplicated_by_step_draft(self) -> None: self.assertIsNotNone(result) assert result is not None - self.assertEqual(result.text.splitlines().count("OPEN_APP: com.healthtap.userhtexpress"), 1) + self.assertEqual(result.text.splitlines().count("OPEN_APP: com.example.health"), 1) def test_warm_start_launch_baseline_is_kept_without_source_steps(self) -> None: """ @@ -211,7 +211,7 @@ def test_warm_start_launch_baseline_is_kept_without_source_steps(self) -> None: evidence = Evidence( intent="login", goal="login", - package="com.healthtap.userhtexpress", + package="com.example.health", partial=False, steps=( EvidenceStep( @@ -219,7 +219,7 @@ def test_warm_start_launch_baseline_is_kept_without_source_steps(self) -> None: event="launch", action="launch", launch=StepLaunch( - package="com.healthtap.userhtexpress", + package="com.example.health", provenance=LaunchProvenance.SYNTHETIC_WARM_START, ), ), @@ -229,14 +229,14 @@ def test_warm_start_launch_baseline_is_kept_without_source_steps(self) -> None: baseline = AuthoringBaseline( content="\n".join( ( - "OPEN_APP: com.healthtap.userhtexpress", + "OPEN_APP: com.example.health", 'Type "user@example.com" into Email field', ) ), partial=False, commands=( AuthoringBaselineCommand( - text="OPEN_APP: com.healthtap.userhtexpress", + text="OPEN_APP: com.example.health", role=ScriptCommandRole.LAUNCH, ), AuthoringBaselineCommand( @@ -246,7 +246,7 @@ def test_warm_start_launch_baseline_is_kept_without_source_steps(self) -> None: ), ) drafts = ( - self.__draft(step=0, text="OPEN_APP: com.healthtap.userhtexpress"), + self.__draft(step=0, text="OPEN_APP: com.example.health"), self.__draft(step=1, text='Type "user@example.com" into Email field'), ) @@ -258,7 +258,7 @@ def test_warm_start_launch_baseline_is_kept_without_source_steps(self) -> None: result.text, "\n".join( ( - "OPEN_APP: com.healthtap.userhtexpress", + "OPEN_APP: com.example.health", 'Type "user@example.com" into Email field', ) ), diff --git a/tests/unit/core/agent/planner/test_planner.py b/tests/unit/core/agent/planner/test_planner.py index cfc96d8d..f7a28fc8 100644 --- a/tests/unit/core/agent/planner/test_planner.py +++ b/tests/unit/core/agent/planner/test_planner.py @@ -172,9 +172,9 @@ def choose(primary: Action, alternatives: object, failed_actions: object) -> Act async def test_validate_command_admitted_as_preparatory_under_capture_goal(self) -> None: """ - Regression: a VALIDATE emitted under a capture (STORE) goal is admitted as a preparatory - action, not gate-rejected by directive. It carries no admitted requirement, so it cannot - complete the capture goal — the old directive-based "not authorized" rejection must not recur. + A VALIDATE emitted under a capture (STORE) goal is admitted as a preparatory action, not + gate-rejected by directive. It carries no admitted requirement, so it cannot complete the + capture goal. """ analysis = AnalysisResult( @@ -356,11 +356,15 @@ async def test_action_sub_goal_turn_hides_verification_tools(self) -> None: class StepPlannerAutonomousAskUserSubstitutionTest(unittest.IsolatedAsyncioTestCase): - """Pins the autonomous-runtime substitution: ASK_USER -> recovery ladder.""" + """ + Pins the autonomous-runtime substitution: ASK_USER -> recovery ladder. + """ @staticmethod def __ask_user_analysis() -> AnalysisResult: - """Return an analysis whose primary action is ASK_USER.""" + """ + Return an analysis whose primary action is ASK_USER. + """ action = ActionFixtures.make( target="User", @@ -376,7 +380,9 @@ def __ask_user_analysis() -> AnalysisResult: ) async def test_substitutes_ask_user_with_recovery_action(self) -> None: - """ASK_USER on autonomous runtime substitutes with the next ladder rung.""" + """ + ASK_USER on autonomous runtime substitutes with the next ladder rung. + """ analysis = self.__ask_user_analysis() vision = Mock() @@ -411,7 +417,9 @@ async def test_substitutes_ask_user_with_recovery_action(self) -> None: self.assertFalse(result.is_complete) async def test_terminates_when_ladder_exhausted(self) -> None: - """When the recovery ladder is spent, ASK_USER becomes terminal INTERVENTION_REQUIRED.""" + """ + When the recovery ladder is spent, ASK_USER becomes terminal INTERVENTION_REQUIRED. + """ analysis = self.__ask_user_analysis() vision = Mock() @@ -446,7 +454,8 @@ async def test_terminates_when_ladder_exhausted(self) -> None: class StepPlannerControlAdmissionTest(unittest.IsolatedAsyncioTestCase): """ - P0-2: an LLM-emitted ASK_USER *command* must pass CommandGate under proof-bearing goals and reach the escalation/HITL policy, never be blocked at admission. + An LLM-emitted ASK_USER *command* must pass CommandGate under proof-bearing goals and reach the + escalation/HITL policy, never be blocked at admission. """ @staticmethod @@ -613,7 +622,7 @@ async def test_should_avoid_action_returns_should_retry_with_no_step(self) -> No rejection_payload = ["seeded-turn"] result, _, _ = await self.__plan( - descriptor_target="More on Swiggy widget", + descriptor_target="More on Delivery widget", rejection_history_return=rejection_payload, ) @@ -628,7 +637,7 @@ async def test_should_avoid_action_writes_rejection_history(self) -> None: rejection_payload = ["seeded-turn"] _, state, vision = await self.__plan( - descriptor_target="More on Swiggy widget", + descriptor_target="More on Delivery widget", rejection_history_return=rejection_payload, ) @@ -645,14 +654,14 @@ async def test_should_avoid_action_stamps_retry_metadata(self) -> None: """ result, _, _ = await self.__plan( - descriptor_target="More on Swiggy widget", + descriptor_target="More on Delivery widget", rejection_history_return=["x"], ) assert result.context.retry is not None self.assertIs(result.context.retry.kind, RetryKind.SILENT_REJECTION) self.assertIs(result.context.retry.branch, RetryBranch.SHOULD_AVOID_ACTION) - self.assertIn("More on Swiggy widget", result.context.retry.action or "") + self.assertIn("More on Delivery widget", result.context.retry.action or "") async def test_should_avoid_action_does_not_advance_step_count(self) -> None: """ @@ -661,7 +670,7 @@ async def test_should_avoid_action_does_not_advance_step_count(self) -> None: before = AgentFixtures.state(intent="x").step_count _, state, _ = await self.__plan( - descriptor_target="More on Swiggy widget", + descriptor_target="More on Delivery widget", rejection_history_return=["x"], ) self.assertEqual(state.step_count, before) diff --git a/tests/unit/core/agent/planner/test_vision_turn.py b/tests/unit/core/agent/planner/test_vision_turn.py index e6d4ba8c..bfe7afe2 100644 --- a/tests/unit/core/agent/planner/test_vision_turn.py +++ b/tests/unit/core/agent/planner/test_vision_turn.py @@ -40,9 +40,9 @@ def test_observed_sub_goal_threads_its_assertion(self) -> None: [ SubGoalFixtures.make( index=0, - description="Open Amazon and search", + description="Open Retail and search", success=SuccessFixtures.observed( - assertion="The Amazon search results for 'ghar soap' are displayed." + assertion="The Retail search results for 'ghar soap' are displayed." ), ), SubGoalFixtures.make(index=1, description="Confirm"), @@ -53,7 +53,7 @@ def test_observed_sub_goal_threads_its_assertion(self) -> None: assert context is not None self.assertEqual( - context["assertion"], "The Amazon search results for 'ghar soap' are displayed." + context["assertion"], "The Retail search results for 'ghar soap' are displayed." ) self.assertFalse(context["durable"]) diff --git a/tests/unit/core/agent/state/test_state.py b/tests/unit/core/agent/state/test_state.py index c188eceb..efb7b728 100644 --- a/tests/unit/core/agent/state/test_state.py +++ b/tests/unit/core/agent/state/test_state.py @@ -265,7 +265,9 @@ def __tap_action(*, target: str) -> Action: ) def test_last_action_round_trips_through_checkpoint(self) -> None: - """``to_checkpoint`` / ``from_checkpoint`` must preserve ``__last_action_type`` and ``__last_action_description`` so a graph-state restore between nodes does not wipe the descriptor the LoopDetector will consume on the next ``update_screen``.""" + """ + ``to_checkpoint`` / ``from_checkpoint`` must preserve ``__last_action_type`` and ``__last_action_description`` so a graph-state restore between nodes does not wipe the descriptor the LoopDetector will consume on the next ``update_screen``. + """ state = AgentState(intent="test", capabilities=self.__caps()) @@ -423,7 +425,7 @@ def __state(*, cap: int = 5) -> AgentState: ) @staticmethod - def __tap_action(*, target: str = "More on Swiggy") -> Action: + def __tap_action(*, target: str = "More on Delivery") -> Action: """ Tap action used to exercise the budget reset on EXECUTE dispatch. """ @@ -729,7 +731,7 @@ def test_last_attempt_snapshot_captures_branch_and_action(self) -> None: state.tick_planner_retry( kind=RetryKind.SILENT_REJECTION, branch=RetryBranch.SHOULD_AVOID_ACTION, - action="Swipe left on More on Swiggy", + action="Swipe left on More on Delivery", ) attempt = state.last_retry_attempt @@ -737,7 +739,7 @@ def test_last_attempt_snapshot_captures_branch_and_action(self) -> None: assert attempt is not None self.assertIs(attempt.kind, RetryKind.SILENT_REJECTION) self.assertIs(attempt.branch, RetryBranch.SHOULD_AVOID_ACTION) - self.assertEqual(attempt.action, "Swipe left on More on Swiggy") + self.assertEqual(attempt.action, "Swipe left on More on Delivery") class AgentStatePlannerRetryCheckpointTest(unittest.TestCase): @@ -873,13 +875,13 @@ def test_requested_authority_round_trips(self) -> None: state = AgentState( intent="x", capabilities=self.__caps(), - target_authority=TargetAuthority.requested(package="com.meesho.supply"), + target_authority=TargetAuthority.requested(package="com.example.shop"), ) restored = AgentState.from_checkpoint(state.to_checkpoint(), capabilities=self.__caps()) self.assertTrue(restored.target_authority.bound) - self.assertEqual(restored.target_authority.package, "com.meesho.supply") + self.assertEqual(restored.target_authority.package, "com.example.shop") def test_default_authority_is_unbound(self) -> None: """ @@ -899,7 +901,7 @@ def test_legacy_checkpoint_without_authority_restores_unbound(self) -> None: state = AgentState( intent="x", capabilities=self.__caps(), - target_authority=TargetAuthority.requested(package="com.meesho.supply"), + target_authority=TargetAuthority.requested(package="com.example.shop"), ) payload = state.to_checkpoint() payload.pop("target_authority") @@ -935,7 +937,7 @@ def __screen() -> ScreenState: return ScreenState( timestamp=0, - activity="com.meesho.supply", + activity="com.example.shop", visual_hash="c" * 16, activity_hash="d" * 16, ) diff --git a/tests/unit/core/agent/test_advancement.py b/tests/unit/core/agent/test_advancement.py index 0e705275..41590c78 100644 --- a/tests/unit/core/agent/test_advancement.py +++ b/tests/unit/core/agent/test_advancement.py @@ -301,7 +301,7 @@ def test_matching_committed_capture_advances(self) -> None: assert _decide(self._capture_success(), evidence) is AdvanceKind.ADVANCE def test_capture_advances_despite_free_text_subject_difference(self) -> None: - # Regression (live Amazon run): the planner phrases the STORE subject independently of the + # Regression (live Retail run): the planner phrases the STORE subject independently of the # decomposer's; identity is the NAME, so a differing free-text subject must still advance. action = _action( ActionType.STORE, @@ -342,11 +342,8 @@ def test_satisfied_below_floor_retains(self) -> None: class TestEscalation: """ - Ported loop-bounding incidents: a stalled retain escalates, and a refuted own-observation is terminal. - - These preserve the documented production loops (runs 59cd9b0b/6033fea1/44abb3b9/9c8704be/154ec8a1) - as a hermetic invariant on the new stall-driven policy, without the gitignored replay tapes: a - sub-goal that cannot prove itself may not retain unboundedly once momentum reports a stall. + A stalled retain escalates, and a refuted own-observation is terminal: a sub-goal that cannot + prove itself may not retain unboundedly once momentum reports a stall. """ @staticmethod @@ -465,11 +462,11 @@ def _store_step() -> Step: ) def test_satisfied_verdict_for_other_goal_cannot_advance(self) -> None: - # "Open Amazon" satisfied must not advance the "search ghar soap" goal. + # "Open Retail" satisfied must not advance the "search ghar soap" goal. success = ObservedSuccess(observation=_obs("search results for ghar soap shown")) evidence = _turn( execution=_result(_step(_action(ActionType.TAP))), - observation=_obs("Amazon home screen shown"), + observation=_obs("Retail home screen shown"), verdict=_satisfied(), ) assert _decide(success, evidence) is AdvanceKind.RETAIN @@ -596,14 +593,14 @@ def test_observed_bound_matching_foreground_advances(self) -> None: A satisfied verdict on the exact bound foreground package advances. """ - obs = _obs("Amazon home screen shown") + obs = _obs("Retail home screen shown") evidence = self.__turn( observation=obs, visual=self.__visual( observation=obs, verdict=VisualVerdict.SATISFIED, - authority=TargetAuthority.requested(package="com.amazon.mShop.android.shopping"), - foreground="com.amazon.mShop.android.shopping", + authority=TargetAuthority.requested(package="com.example.shop2"), + foreground="com.example.shop2", ), ) assert _decide(ObservedSuccess(observation=obs), evidence) is AdvanceKind.ADVANCE @@ -613,13 +610,13 @@ def test_observed_bound_mismatched_foreground_retains(self) -> None: A satisfied verdict on a foreground other than the bound target retains. """ - obs = _obs("Amazon home screen shown") + obs = _obs("Retail home screen shown") evidence = self.__turn( observation=obs, visual=self.__visual( observation=obs, verdict=VisualVerdict.SATISFIED, - authority=TargetAuthority.requested(package="com.amazon.mShop.android.shopping"), + authority=TargetAuthority.requested(package="com.example.shop2"), foreground="com.android.launcher", ), ) @@ -630,13 +627,13 @@ def test_observed_bound_missing_foreground_fails_closed(self) -> None: A satisfied verdict under a bound target with an unknown foreground fails closed and retains. """ - obs = _obs("Amazon home screen shown") + obs = _obs("Retail home screen shown") evidence = self.__turn( observation=obs, visual=self.__visual( observation=obs, verdict=VisualVerdict.SATISFIED, - authority=TargetAuthority.requested(package="com.amazon.mShop.android.shopping"), + authority=TargetAuthority.requested(package="com.example.shop2"), foreground=None, ), ) diff --git a/tests/unit/core/agent/test_command.py b/tests/unit/core/agent/test_command.py index 784f8610..9d29d4ed 100644 --- a/tests/unit/core/agent/test_command.py +++ b/tests/unit/core/agent/test_command.py @@ -139,9 +139,8 @@ def test_rejects_command_missing_from_catalog(self) -> None: def test_well_formed_commands_admitted_regardless_of_goal(self) -> None: """ - Regression: the gate performs no directive/completion-mode admission. A well-formed - proof-bearing or preparatory command is admitted structurally — the old symmetric gate that - rejected preparatory tactics under a mismatched goal must not recur. + The gate performs no directive/completion-mode admission. A well-formed proof-bearing or + preparatory command is admitted structurally, regardless of the active goal. """ gate = self.__gate() diff --git a/tests/unit/core/agent/test_ladder.py b/tests/unit/core/agent/test_ladder.py index 8e3e13c9..653ce739 100644 --- a/tests/unit/core/agent/test_ladder.py +++ b/tests/unit/core/agent/test_ladder.py @@ -215,7 +215,7 @@ def test_validate_passive_still_increments_recovery_budget(self) -> None: def test_validate_passive_on_no_back_device_does_not_emit_home(self) -> None: """ - Specifically the regression P1 caught: no-BACK device must not jump to HOME after a passive VALIDATE. + A no-BACK device must not jump to HOME after a passive VALIDATE. """ detector = LoopDetector(max_recovery=3) diff --git a/tests/unit/core/agent/test_reasoner.py b/tests/unit/core/agent/test_reasoner.py index 294d2814..89d15e3e 100644 --- a/tests/unit/core/agent/test_reasoner.py +++ b/tests/unit/core/agent/test_reasoner.py @@ -16,7 +16,7 @@ class ReasonerAnalyzeCompletionTest(unittest.TestCase): """ @staticmethod - def __reasoner(intent: str = "open meesho and find Jars & containers") -> Reasoner: + def __reasoner(intent: str = "open shopping and find Jars & containers") -> Reasoner: """ Build a Reasoner with a representative intent string. """ diff --git a/tests/unit/core/agent/test_shadow.py b/tests/unit/core/agent/test_shadow.py index cdf94273..7e0ec8fe 100644 --- a/tests/unit/core/agent/test_shadow.py +++ b/tests/unit/core/agent/test_shadow.py @@ -18,7 +18,7 @@ from fathom.schemas.target import TargetAuthority -def _observed(*, assertion: str = "Amazon home screen shown") -> ObservedSuccess: +def _observed(*, assertion: str = "Retail home screen shown") -> ObservedSuccess: return ObservedSuccess(observation=ObservationRequirement(assertion=assertion)) @@ -70,7 +70,7 @@ def test_command_goal_without_assessment_is_clean(self) -> None: class TestSatisfiedWithActionIsRecordedNotEnforced: def test_satisfied_with_action_is_a_divergence(self) -> None: - # Slice 2 records the conflict; the action still executes live and no goal advances. + # The assessor records the conflict; the action still executes live and no goal advances. out = ShadowAssessor().assess( success=_observed(), assessment=_assessment(VisualVerdict.SATISFIED), @@ -88,21 +88,21 @@ def test_satisfied_without_action_is_clean(self) -> None: class TestPackageAuthorityContradiction: - __SHOPPING = "com.amazon.mShop.android.shopping" + __SHOPPING = "com.example.shop2" - def test_amazon_music_does_not_satisfy_amazon_shopping(self) -> None: + def test_retail_music_does_not_satisfy_retail_shopping(self) -> None: out = ShadowAssessor().assess( - success=_observed(assertion="Open Amazon"), + success=_observed(assertion="Open Retail"), assessment=_assessment(VisualVerdict.SATISFIED), action_present=False, authority=TargetAuthority.requested(package=self.__SHOPPING), - foreground_package="com.amazon.mp3", + foreground_package="com.example.media", ) assert _kinds(out) == {ShadowDivergenceKind.PACKAGE_CONTRADICTION} def test_exact_authoritative_package_matches(self) -> None: out = ShadowAssessor().assess( - success=_observed(assertion="Open Amazon"), + success=_observed(assertion="Open Retail"), assessment=_assessment(VisualVerdict.SATISFIED), action_present=False, authority=TargetAuthority.requested(package=self.__SHOPPING), @@ -111,24 +111,24 @@ def test_exact_authoritative_package_matches(self) -> None: assert out == () def test_prefix_is_not_package_identity(self) -> None: - # P0 regression: package identity is exact, never a prefix. ``com.amazon.app.evil`` - # must not satisfy an authority bound to ``com.amazon.app``. + # Package identity is exact, never a prefix. ``com.retail.app.evil`` + # must not satisfy an authority bound to ``com.retail.app``. out = ShadowAssessor().assess( success=_observed(), assessment=_assessment(VisualVerdict.SATISFIED), action_present=False, - authority=TargetAuthority.requested(package="com.amazon.app"), - foreground_package="com.amazon.app.evil", + authority=TargetAuthority.requested(package="com.retail.app"), + foreground_package="com.retail.app.evil", ) assert _kinds(out) == {ShadowDivergenceKind.PACKAGE_CONTRADICTION} def test_unbound_authority_never_contradicts(self) -> None: out = ShadowAssessor().assess( - success=_observed(assertion="Open Amazon"), + success=_observed(assertion="Open Retail"), assessment=_assessment(VisualVerdict.SATISFIED), action_present=False, authority=TargetAuthority.unbound(), - foreground_package="com.amazon.mp3", + foreground_package="com.example.media", ) assert out == () diff --git a/tests/unit/core/agent/tools/test_scope.py b/tests/unit/core/agent/tools/test_scope.py index 97fd38e9..86d04fa0 100644 --- a/tests/unit/core/agent/tools/test_scope.py +++ b/tests/unit/core/agent/tools/test_scope.py @@ -4,7 +4,6 @@ from unittest.mock import patch from pydantic import ValidationError -from tests.fixtures.intents import VERIFY_TOOLS from fathom.constants.tools import BASE_TOOLS, ToolName, TurnMode from fathom.core.agent.tools.policy import ToolPolicy @@ -14,6 +13,8 @@ from fathom.schemas.capabilities import HITLCapability, RuntimeCapabilities from fathom.schemas.tools import ToolPolicyContext +VERIFY_TOOLS = frozenset({ToolName.VERIFY_GOAL, ToolName.VALIDATE_STATE}) + class _AlwaysAllowsToolPolicy(ToolPolicy): """ diff --git a/tests/unit/core/artifact/test_pipeline.py b/tests/unit/core/artifact/test_pipeline.py index c9ddc949..1a9ca666 100644 --- a/tests/unit/core/artifact/test_pipeline.py +++ b/tests/unit/core/artifact/test_pipeline.py @@ -258,7 +258,7 @@ async def test_emit_writes_ocr_raw_json_to_xmls_directory(self) -> None: package_name="app", session_id="run-test", created=1_700_000_000_000, - payload=OcrRawPayload(content='{"text": "Swiggy"}'), + payload=OcrRawPayload(content='{"text": "Delivery"}'), ) ) await pipeline.drain() @@ -266,7 +266,7 @@ async def test_emit_writes_ocr_raw_json_to_xmls_directory(self) -> None: payloads = list(tmp_path.rglob("xmls/**/step-000__ocr_raw__*.json")) self.assertEqual(len(payloads), 1) - self.assertEqual(payloads[0].read_text(), '{"text": "Swiggy"}') + self.assertEqual(payloads[0].read_text(), '{"text": "Delivery"}') async def test_emit_drops_record_when_kind_has_no_renderer(self) -> None: """ diff --git a/tests/unit/core/artifact/test_renderer.py b/tests/unit/core/artifact/test_renderer.py index c3d22391..277aa059 100644 --- a/tests/unit/core/artifact/test_renderer.py +++ b/tests/unit/core/artifact/test_renderer.py @@ -165,10 +165,10 @@ def test_ocr_raw_encodes_content_as_utf8(self) -> None: renderer = PassthroughRenderer(kind=ArtifactKind.OCR_RAW) rendered = renderer.render( - record=_Fixtures.record(payload=OcrRawPayload(content='{"text": "Swiggy"}')), + record=_Fixtures.record(payload=OcrRawPayload(content='{"text": "Delivery"}')), ) - self.assertEqual(rendered, b'{"text": "Swiggy"}') + self.assertEqual(rendered, b'{"text": "Delivery"}') def test_script_encodes_content_as_utf8(self) -> None: """ diff --git a/tests/unit/core/config/test_loader.py b/tests/unit/core/config/test_loader.py index c5ab602d..248f2b2c 100644 --- a/tests/unit/core/config/test_loader.py +++ b/tests/unit/core/config/test_loader.py @@ -38,7 +38,9 @@ class RuntimeConfigLoaderTest(unittest.TestCase): """ def test_perception_defaults_keep_cv_disabled(self) -> None: - """Production defaults keep CV disabled while OCR, icon, and overlay remain enabled.""" + """ + Production defaults keep CV disabled while OCR, icon, and overlay remain enabled. + """ config = RuntimeConfigLoader(settings=_settings()).perception() @@ -111,7 +113,9 @@ def test_perception_drops_partial_document_ai_credentials(self) -> None: self.assertIsNone(config.ocr.document_ai) def test_perception_threads_inline_google_credentials_dict(self) -> None: - """Inline ``GOOGLE_APPLICATION_CREDENTIALS_JSON`` material rides into :class:`DocumentAiCredentials` so the Document AI adapter authenticates against the same identity Gemini already uses — no reliance on ambient ADC.""" + """ + Inline ``GOOGLE_APPLICATION_CREDENTIALS_JSON`` material rides into :class:`DocumentAiCredentials` so the Document AI adapter authenticates against the same identity Gemini already uses — no reliance on ambient ADC. + """ payload = {"type": "service_account", "project_id": "vision-478905"} config = RuntimeConfigLoader( @@ -259,7 +263,9 @@ def test_localization_rejects_unknown_member(self) -> None: self.assertIn("bogus_member", str(caught.exception)) def test_localization_enabled_flag_with_empty_member_list_returns_empty_tuple(self) -> None: - """Enabling the flag with an explicit empty member list yields an enabled config with an empty tuple — the default member set is only chosen when the operator leaves the env value at its bring-up default.""" + """ + Enabling the flag with an explicit empty member list yields an enabled config with an empty tuple — the default member set is only chosen when the operator leaves the env value at its bring-up default. + """ config = RuntimeConfigLoader( settings=_settings( diff --git a/tests/unit/core/context/test_manager.py b/tests/unit/core/context/test_manager.py index 1fdc2434..b805d684 100644 --- a/tests/unit/core/context/test_manager.py +++ b/tests/unit/core/context/test_manager.py @@ -218,7 +218,9 @@ async def test_shutdown_returns_promptly_when_no_background_work(self) -> None: ) async def test_commit_does_not_grow_persist_queue(self) -> None: - """Regression for the unbounded-queue leak in __enqueue_persist.""" + """ + Regression for the unbounded-queue leak in __enqueue_persist. + """ manager = ContextManager(memory=MagicMock()) diff --git a/tests/unit/core/embedding/test_cache.py b/tests/unit/core/embedding/test_cache.py index 486fcf58..b03dafa4 100644 --- a/tests/unit/core/embedding/test_cache.py +++ b/tests/unit/core/embedding/test_cache.py @@ -76,8 +76,8 @@ async def test_warm_then_get_returns_cached_vector(self) -> None: embedder = _StubEmbedder(responses=[(vector,)]) cache = EmbeddingCache(embedder=embedder) - cache.warm(texts=("Open the Posh app",)) - result = await cache.get(text="Open the Posh app") + cache.warm(texts=("Open the Events app",)) + result = await cache.get(text="Open the Events app") self.assertEqual(result, vector) self.assertEqual(len(embedder.calls), 1) diff --git a/tests/unit/core/perception/test_observation.py b/tests/unit/core/perception/test_observation.py deleted file mode 100644 index 723f4489..00000000 --- a/tests/unit/core/perception/test_observation.py +++ /dev/null @@ -1,832 +0,0 @@ -from __future__ import annotations - -import unittest -from pathlib import Path -from typing import Tuple -from unittest.mock import AsyncMock, Mock - -from fathom.constants.observation import KeyboardVisibility -from fathom.constants.ocr import OcrConfidence -from fathom.core.perception.observation import ScreenObservationService -from fathom.schemas.actions import Bounds, CoordinateSource, CoordinateSystem -from fathom.schemas.artifact import OcrPerceptionPayload, OcrRawPayload, OverlayPerceptionPayload -from fathom.schemas.budgets import PerceptionBudget -from fathom.schemas.observation import ( - ElementRole, - ElementSource, - OverlayObservation, - PerceivedElement, -) -from fathom.schemas.ocr import OcrResult, OcrToken -from fathom.schemas.perception import KeyboardConfiguration, PerceptionConfiguration -from fathom.schemas.screens import ScreenCapture, ScreenHashBundle -from fathom.schemas.ui import LabeledElement, UIBounds - - -class _StaticOcr: - """ - Test OCR port returning one stable token and raw provider JSON. - """ - - async def extract(self, *, capture: ScreenCapture, budget: PerceptionBudget) -> OcrResult: - """ - Return a Swiggy OCR token regardless of capture contents. - """ - - _ = capture, budget - return OcrResult( - duration=12, - raw_response='{"text": "Swiggy"}', - tokens=( - OcrToken( - text="Swiggy", - bounds=Bounds( - x=284, - y=383, - width=108, - height=31, - source=CoordinateSource.OCR, - coordinate_system=CoordinateSystem.DEVICE_PIXEL, - ), - raw_score=0.96, - confidence=OcrConfidence.HIGH, - ), - ), - ) - - -class ScreenObservationServiceOverlayDedupTest(unittest.IsolatedAsyncioTestCase): - """ - Pins the overlay-dedup invariant on :class:`ScreenObservationService`. - - The supervisor only needs a single BLOCKING vote per screen. Two - qualifying overlay elements in the same manifest (stacked dialogs) - must therefore collapse into one :class:`OverlayObservation`, not be - surfaced as two independent signals. The fixture PNG is a real - 1206x2622 Swiggy capture from ``assets/screenshot/`` — only the byte - payload is consumed. - """ - - __FRAMES = Path(__file__).resolve().parents[3] / "fixtures" / "perception" / "frames" - __IMAGE = __FRAMES / "home.png" - - @classmethod - def __capture(cls) -> ScreenCapture: - """ - :class:`ScreenCapture` fixture wrapping the on-disk PNG. The width - and height match the source asset so any subsequent visual - processing reads consistent pixel coordinates. - """ - - return ScreenCapture( - width=1206, - height=2622, - activity="app", - image=cls.__IMAGE.read_bytes(), - timestamp=0, - ) - - @staticmethod - def __hashes() -> ScreenHashBundle: - """ - Deterministic :class:`ScreenHashBundle` fixture. The observation - service does not read these values; they exist only to satisfy - the schema. - """ - - return ScreenHashBundle( - visual_hash="0" * 16, - xml_hash="a" * 16, - interaction_hash="b" * 16, - ) - - @staticmethod - def __budget() -> PerceptionBudget: - """ - Zero-budget :class:`PerceptionBudget`. The test exercises only the - manifest-driven overlay path, so OCR / icon / overlay providers - must stay inert; a zero budget keeps the noop fall-back active. - """ - - return PerceptionBudget(ocr=0, local=0, localization=0) - - @staticmethod - def __overlay_manifest() -> Tuple[LabeledElement, ...]: - """ - Two large model-sourced dialog elements. Both individually meet - the overlay-area threshold; the test pins that the service still - produces exactly one :class:`OverlayObservation`. - """ - - return ( - LabeledElement( - label="L1", - bounds=UIBounds(x1=0, y1=0, x2=1206, y2=2400), - attributes={ - "class": "DialogContainer", - "source": "model", - "text": "First overlay", - }, - ), - LabeledElement( - label="L2", - bounds=UIBounds(x1=50, y1=50, x2=1156, y2=2350), - attributes={ - "class": "DialogContainer", - "source": "model", - "text": "Second overlay", - }, - ), - ) - - async def test_stacked_qualifying_elements_collapse_to_single_overlay(self) -> None: - """ - Two stacked qualifying elements must yield exactly one overlay - observation. The supervisor consumes overlays as boolean BLOCKING - votes, so reporting both would double-count the same screen state. - """ - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=self.__overlay_manifest(), - session_id="run-test", - step_number=0, - ) - - self.assertEqual(len(observation.overlays), 1) - self.assertIsInstance(observation.overlays[0], OverlayObservation) - - async def test_cv_attribute_maps_to_cv_element_source(self) -> None: - """A :class:`LabeledElement` carrying ``attributes["source"] == "cv"`` — produced by :class:`VisualControlLabeler` — must surface in the resulting :class:`ScreenObservation` with ``ElementSource.CV``, not ``ElementSource.VISION``.""" - - manifest = ( - LabeledElement( - label="L1", - bounds=UIBounds(x1=200, y1=400, x2=900, y2=520), - attributes={ - "class": "VisualControl", - "source": "cv", - "confidence": "0.85", - }, - ), - ) - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - cv_elements = tuple( - element for element in observation.elements if element.source == ElementSource.CV - ) - self.assertGreaterEqual(len(cv_elements), 1) - self.assertFalse( - any( - element.source == ElementSource.VISION - for element in observation.elements - if "VisualControl" in str(element.identifier) or element.label_id == "L1" - ), - "CV-tagged labeled elements must not be rewritten to ElementSource.VISION.", - ) - - async def test_oversized_manifest_bounds_are_clamped_before_schema_conversion(self) -> None: - """ - Malformed provider bounds must be clipped to the visible viewport. - """ - - manifest = ( - LabeledElement( - label="L1", - bounds=UIBounds(x1=114, y1=888, x2=1092, y2=26643), - attributes={ - "type": "XCUIElementTypeTextView", - "value": "Privacy text", - "visible": "true", - "enabled": "true", - "scrollable": "true", - "axis": "vertical", - "kind": "viewport", - }, - ), - ) - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - self.assertEqual(len(observation.elements), 1) - self.assertLessEqual( - observation.elements[0].bounds.x + observation.elements[0].bounds.width, - self.__capture().width, - ) - self.assertLessEqual( - observation.elements[0].bounds.y + observation.elements[0].bounds.height, - self.__capture().height, - ) - - async def test_manifest_bounds_outside_viewport_are_dropped(self) -> None: - """ - Elements fully outside the viewport must not enter observations. - """ - - manifest = ( - LabeledElement( - label="L1", - bounds=UIBounds(x1=1300, y1=3000, x2=1500, y2=3300), - attributes={ - "type": "XCUIElementTypeButton", - "value": "Invisible", - "visible": "true", - "enabled": "true", - }, - ), - ) - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - self.assertEqual(observation.elements, ()) - - async def test_visual_controls_are_not_injected_when_cv_is_disabled(self) -> None: - """ - CV-derived visual controls must stay out of observations when the - runtime CV toggle is disabled. - """ - - observation = await ScreenObservationService( - configuration=PerceptionConfiguration(), - ).observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=(), - session_id="run-test", - step_number=0, - ) - - self.assertEqual( - tuple( - element for element in observation.elements if element.source == ElementSource.CV - ), - (), - ) - - async def test_small_xml_buttons_do_not_qualify_as_overlay(self) -> None: - """ - XML-sourced elements only qualify as overlays when their role is - ``OVERLAY`` explicitly. A small XML button — even one named - ``Close`` — must not surface as a blocking layer. - """ - - manifest = ( - LabeledElement( - label="L1", - bounds=UIBounds(x1=20, y1=20, x2=200, y2=80), - attributes={"class": "Button", "source": "xml", "text": "Close"}, - ), - ) - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - self.assertEqual(observation.overlays, ()) - - async def test_bottom_controls_do_not_imply_keyboard_visibility(self) -> None: - """ - Large bottom controls are not enough to claim a visible keyboard. - """ - - manifest = ( - LabeledElement( - label="L1", - bounds=UIBounds(x1=0, y1=2200, x2=1206, y2=2480), - attributes={ - "class": "BottomActionBar", - "source": "model", - "text": "Apply coupon", - }, - ), - ) - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - self.assertFalse(observation.keyboard.visibility is KeyboardVisibility.VISIBLE) - - async def test_keyboard_detection_stays_off_when_disabled(self) -> None: - """ - Explicit keyboard-like manifest elements must be ignored when keyboard detection is disabled. - """ - - manifest = ( - LabeledElement( - label="K1", - bounds=UIBounds(x1=0, y1=1800, x2=1206, y2=2622), - attributes={"class": "KeyboardView", "source": "xml"}, - ), - ) - - observation = await ScreenObservationService( - configuration=PerceptionConfiguration( - keyboard=KeyboardConfiguration(enabled=False), - ) - ).observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - self.assertFalse(observation.keyboard.visibility is KeyboardVisibility.VISIBLE) - - async def test_page_scroll_region_is_inferred_when_only_nested_strip_scrollview_exists( - self, - ) -> None: - """ - A feed-like screen with only small nested scrollviews should still expose a page scroll lane. - """ - - manifest = ( - LabeledElement( - label="search", - bounds=UIBounds(x1=16, y1=221, x2=386, y2=278), - attributes={ - "type": "XCUIElementTypeSearchField", - "source": "xml", - "label": "Search, Order, Enjoy, Repeat!", - }, - ), - LabeledElement( - label="chip_row", - bounds=UIBounds(x1=16, y1=741, x2=386, y2=782), - attributes={ - "type": "XCUIElementTypeScrollView", - "source": "xml", - }, - ), - LabeledElement( - label="nav_1", - bounds=UIBounds(x1=40, y1=2487, x2=220, y2=2622), - attributes={"type": "XCUIElementTypeButton", "source": "xml", "label": "Food"}, - ), - LabeledElement( - label="nav_2", - bounds=UIBounds(x1=240, y1=2487, x2=420, y2=2622), - attributes={"type": "XCUIElementTypeButton", "source": "xml", "label": "Bolt"}, - ), - LabeledElement( - label="nav_3", - bounds=UIBounds(x1=440, y1=2487, x2=620, y2=2622), - attributes={"type": "XCUIElementTypeButton", "source": "xml", "label": "99 store"}, - ), - LabeledElement( - label="nav_4", - bounds=UIBounds(x1=640, y1=2487, x2=820, y2=2622), - attributes={"type": "XCUIElementTypeButton", "source": "xml", "label": "EatRight"}, - ), - LabeledElement( - label="nav_5", - bounds=UIBounds(x1=840, y1=2487, x2=1020, y2=2622), - attributes={"type": "XCUIElementTypeButton", "source": "xml", "label": "Reorder"}, - ), - ) - - observation = await ScreenObservationService().observe( - capture=self.__capture().model_copy( - update={"xml_content": ""} - ), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - page_regions = tuple( - region for region in observation.scroll if region.bounds.height >= int(2622 * 0.30) - ) - self.assertGreaterEqual(len(page_regions), 1) - - async def test_page_scroll_region_uses_logical_system_when_capture_dimensions_are_logical( - self, - ) -> None: - """ - A synthetic page lane built from logical capture dimensions must - stay logical so execution does not divide it by the retina scale. - """ - - observation = await ScreenObservationService().observe( - capture=self.__capture().model_copy(update={"width": 402, "height": 874}), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=(), - session_id="run-aekci", - step_number=4, - ) - - self.assertEqual(len(observation.scroll), 1) - self.assertEqual(observation.scroll[0].bounds.system, CoordinateSystem.LOGICAL) - self.assertEqual(observation.scroll[0].bounds.width, 402) - - async def test_large_manifest_container_becomes_explicit_scroll_region(self) -> None: - """ - A large manifest-backed container should surface as an explicit scroll region. - """ - - manifest = ( - LabeledElement( - label="feed", - bounds=UIBounds(x1=0, y1=330, x2=1206, y2=2200), - attributes={"class": "Cell", "source": "xml"}, - ), - LabeledElement( - label="card_1", - bounds=UIBounds(x1=48, y1=420, x2=1158, y2=1300), - attributes={"class": "Other", "source": "xml", "label": "Restaurant A"}, - ), - ) - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - explicit = tuple( - region - for region in observation.scroll - if region.manifest_label_id is not None and region.bounds.width == 1206 - ) - self.assertTrue(explicit) - self.assertEqual(explicit[0].manifest_label_id, "feed") - - async def test_horizontal_scroll_regions_do_not_also_infer_vertical_page_region(self) -> None: - """ - Explicit horizontal scroll containers must not be mixed with a synthetic vertical page region. - """ - - manifest = ( - LabeledElement( - label="carousel", - bounds=UIBounds(x1=0, y1=420, x2=1206, y2=620), - attributes={ - "type": "XCUIElementTypeScrollView", - "source": "xml", - "axis": "horizontal", - "kind": "carousel", - "scrollable": "true", - }, - ), - ) - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - self.assertEqual(len(observation.scroll), 1) - self.assertEqual(observation.scroll[0].axis, "horizontal") - self.assertEqual(observation.scroll[0].manifest_label_id, "carousel") - self.assertIsNone(observation.scroll[0].observation_region_id) - - async def test_manifest_only_observation_does_not_emit_merged_perception_artifact(self) -> None: - """ - Manifest/accessibility-only observation should not create a duplicate merged perception image. - """ - - pipeline = Mock() - pipeline.emit = AsyncMock() - manifest = ( - LabeledElement( - label="L1", - bounds=UIBounds(x1=20, y1=20, x2=200, y2=80), - attributes={"class": "Button", "source": "xml", "text": "Close"}, - ), - ) - - await ScreenObservationService(pipeline=pipeline).observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=manifest, - session_id="run-test", - step_number=0, - ) - - self.assertEqual( - [type(call.kwargs["record"].payload) for call in pipeline.emit.await_args_list], - [], - ) - - async def test_overlay_artifact_still_emits_without_merged_perception_image(self) -> None: - """ - Overlay-specific artifacts should still be emitted when overlay evidence exists. - """ - - pipeline = Mock() - pipeline.emit = AsyncMock() - - await ScreenObservationService(pipeline=pipeline).observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=self.__overlay_manifest(), - session_id="run-test", - step_number=0, - ) - - payload_types = [ - type(call.kwargs["record"].payload) for call in pipeline.emit.await_args_list - ] - self.assertEqual(payload_types, [OverlayPerceptionPayload]) - - async def test_ocr_raw_and_annotated_artifacts_emit_when_ocr_contributes(self) -> None: - """ - OCR enrichment must persist both raw provider JSON and OCR-only annotation. - """ - - pipeline = Mock() - pipeline.emit = AsyncMock() - - observation = await ScreenObservationService( - ocr=_StaticOcr(), - pipeline=pipeline, - ).observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=(), - session_id="run-test", - step_number=0, - ) - - self.assertEqual(observation.elements[0].text, "Swiggy") - payloads = [call.kwargs["record"].payload for call in pipeline.emit.await_args_list] - self.assertTrue(any(isinstance(payload, OcrRawPayload) for payload in payloads)) - self.assertTrue(any(isinstance(payload, OcrPerceptionPayload) for payload in payloads)) - raw_payloads = [payload for payload in payloads if isinstance(payload, OcrRawPayload)] - self.assertEqual(raw_payloads[0].content, '{"text": "Swiggy"}') - - -class ScreenObservationServiceKeyboardProbeTest(unittest.IsolatedAsyncioTestCase): - """ - Pin the device-backed fallback for keyboard detection in vision-only mode. - """ - - __FRAMES = Path(__file__).resolve().parents[3] / "fixtures" / "perception" / "frames" - __IMAGE = __FRAMES / "home.png" - - @classmethod - def __capture(cls) -> ScreenCapture: - """ - Build one capture fixture from the on-disk Swiggy frame. - """ - - return ScreenCapture( - width=1206, - height=2622, - activity="app", - image=cls.__IMAGE.read_bytes(), - timestamp=0, - ) - - @staticmethod - def __hashes() -> ScreenHashBundle: - """ - Stable triple-hash fixture for the keyboard-probe tests. - """ - - return ScreenHashBundle( - visual_hash="v" * 16, - xml_hash="x" * 16, - interaction_hash="i" * 16, - ) - - @staticmethod - def __budget() -> PerceptionBudget: - """ - Zero-budget so OCR/icon/overlay providers stay inert. - """ - - return PerceptionBudget(ocr=0, local=0, localization=0) - - async def test_device_probe_invoked_when_no_keyboard_element_present(self) -> None: - """ - With no KEYBOARD-class manifest element, the service must consult the device adapter. - """ - - from fathom.schemas.observation import KeyboardObservation - - device = Mock() - device.detect_keyboard = AsyncMock( - return_value=KeyboardObservation( - visibility=KeyboardVisibility.VISIBLE, - bounds=Bounds( - x=0, - y=1507, - width=1080, - height=701, - coordinate_system=CoordinateSystem.DEVICE_PIXEL, - ), - ) - ) - - observation = await ScreenObservationService(device=device).observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=(), - session_id="run-test", - step_number=0, - ) - - device.detect_keyboard.assert_awaited_once() - self.assertIs(observation.keyboard.visibility, KeyboardVisibility.VISIBLE) - self.assertIsNotNone(observation.keyboard.bounds) - - async def test_unknown_when_no_device_and_no_manifest_keyboard(self) -> None: - """ - Without a device adapter, the service preserves the UNKNOWN sentinel. - """ - - observation = await ScreenObservationService().observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=(), - session_id="run-test", - step_number=0, - ) - - self.assertIs(observation.keyboard.visibility, KeyboardVisibility.UNKNOWN) - - async def test_device_probe_exception_degrades_to_unknown(self) -> None: - """ - A throwing keyboard probe must not crash the observation pipeline; UNKNOWN is the fallback. - """ - - device = Mock() - device.detect_keyboard = AsyncMock(side_effect=RuntimeError("transport closed")) - - observation = await ScreenObservationService(device=device).observe( - capture=self.__capture(), - hashes=self.__hashes(), - budget=self.__budget(), - manifest=(), - session_id="run-test", - step_number=0, - ) - - device.detect_keyboard.assert_awaited_once() - self.assertIs(observation.keyboard.visibility, KeyboardVisibility.UNKNOWN) - - -class ScreenObservationServiceOcrTriggerTest(unittest.TestCase): - """ - Pins the sparse-manifest gate that decides whether OCR enrichment runs. - """ - - @staticmethod - def __element(*, text: str, identifier: str) -> PerceivedElement: - """ - Build one perceived element carrying the supplied text label. - """ - - return PerceivedElement( - parent=None, - tappable=True, - text=text, - label_id=identifier, - bounds=Bounds( - x=0, - y=0, - width=100, - height=40, - source=CoordinateSource.XML, - coordinate_system=CoordinateSystem.DEVICE_PIXEL, - ), - role=ElementRole.BUTTON, - source=ElementSource.XML, - identifier=identifier, - confidence=1.0, - ) - - def test_unity_collapse_single_textful_element_triggers_ocr(self) -> None: - """ - A manifest with one generic textful container fires OCR despite a 1.0 ratio. - """ - - elements = (self.__element(text="Game view", identifier="xml_1"),) - - decision = ScreenObservationService._ScreenObservationService__should_run_ocr( - elements=elements, - ) - - self.assertTrue(decision) - - def test_two_textful_elements_still_below_count_floor(self) -> None: - """ - Two text-bearing elements is still below the floor and must run OCR. - """ - - elements = ( - self.__element(text="Home", identifier="xml_1"), - self.__element(text="Settings", identifier="xml_2"), - ) - - decision = ScreenObservationService._ScreenObservationService__should_run_ocr( - elements=elements, - ) - - self.assertTrue(decision) - - def test_three_textful_elements_still_below_manifest_size_floor(self) -> None: - """ - A three-element manifest is still too thin to trust the hierarchy; even - with a perfect text ratio, OCR must run to cover the missing nodes. - """ - - elements = ( - self.__element(text="Home", identifier="xml_1"), - self.__element(text="Settings", identifier="xml_2"), - self.__element(text="Profile", identifier="xml_3"), - ) - - decision = ScreenObservationService._ScreenObservationService__should_run_ocr( - elements=elements, - ) - - self.assertTrue(decision) - - def test_dense_textful_manifest_skips_ocr(self) -> None: - """ - Once the manifest is dense and well-labelled (size, text-bearing count, - and coverage all above their floors), OCR is redundant and may skip. - """ - - elements = tuple( - self.__element(text=f"Item {index}", identifier=f"xml_{index}") for index in range(8) - ) - - decision = ScreenObservationService._ScreenObservationService__should_run_ocr( - elements=elements, - ) - - self.assertFalse(decision) - - def test_low_ratio_manifest_still_triggers_ocr(self) -> None: - """ - Even with enough text-bearing elements, a low ratio still triggers OCR. - """ - - textful = tuple( - self.__element(text=f"Item {index}", identifier=f"xml_{index}") for index in range(3) - ) - empty = tuple( - self.__element(text="", identifier=f"xml_empty_{index}") for index in range(20) - ) - elements = textful + empty - - decision = ScreenObservationService._ScreenObservationService__should_run_ocr( - elements=elements, - ) - - self.assertTrue(decision) diff --git a/tests/unit/core/perception/test_observation_screen_kind.py b/tests/unit/core/perception/test_observation_screen_kind.py deleted file mode 100644 index 0a81495d..00000000 --- a/tests/unit/core/perception/test_observation_screen_kind.py +++ /dev/null @@ -1,198 +0,0 @@ -from __future__ import annotations - -import unittest -from pathlib import Path -from typing import Tuple -from unittest.mock import AsyncMock, Mock - -from fathom.constants.observation import KeyboardVisibility -from fathom.core.perception.observation import ScreenObservationService -from fathom.schemas.budgets import PerceptionBudget -from fathom.schemas.ocr import OcrResult -from fathom.schemas.screens import ScreenCapture, ScreenHashBundle -from fathom.schemas.ui import LabeledElement - -_FRAMES = Path(__file__).resolve().parents[3] / "fixtures" / "perception" / "frames" -_IMAGE = _FRAMES / "home.png" - - -class ScreenObservationServiceScreenKindTest(unittest.IsolatedAsyncioTestCase): - """ - Pin the OCR-skip and OCR-run paths in :class:`ScreenObservationService` - against synthetic capture fixtures whose ``xml_content`` deterministically - resolves to the three :class:`ScreenKind` values. - """ - - @staticmethod - def __capture(*, xml_content: str | None) -> ScreenCapture: - """ - Build a capture fixture with the supplied hierarchy XML. - """ - - return ScreenCapture( - width=2340, - height=1080, - timestamp=0, - activity="app", - xml_content=xml_content, - image=_IMAGE.read_bytes(), - ) - - @staticmethod - def __hashes() -> ScreenHashBundle: - """ - Deterministic hash bundle for the screen-kind tests. - """ - - return ScreenHashBundle( - xml_hash="a" * 16, - visual_hash="0" * 16, - interaction_hash="b" * 16, - ) - - @staticmethod - def __budget() -> PerceptionBudget: - """ - Generous budget so OCR would otherwise run. - """ - - return PerceptionBudget(ocr=30_000, local=5_000, localization=60_000) - - @staticmethod - def __manifest() -> Tuple[LabeledElement, ...]: - """ - Empty manifest forces the OCR-trigger heuristic to vote yes. - """ - - return () - - @staticmethod - def __ocr_mock() -> Mock: - """ - Spy OCR port returning an empty result. - """ - - ocr = Mock() - ocr.extract = AsyncMock(return_value=OcrResult(duration=0, raw_response=None, tokens=())) - - return ocr - - async def test_native_frame_runs_ocr(self) -> None: - """ - A frame whose XML has no WebView / SurfaceView must run OCR normally. - """ - - ocr = self.__ocr_mock() - await ScreenObservationService(ocr=ocr).observe( - step_number=0, - session_id="run-test", - hashes=self.__hashes(), - budget=self.__budget(), - manifest=self.__manifest(), - capture=self.__capture( - xml_content='' - ), - ) - - ocr.extract.assert_awaited_once() - - async def test_webview_frame_forces_ocr(self) -> None: - """ - WebView hierarchies are opaque (one node, no clickable children); OCR - is the only signal that can populate the manifest, so it must run - regardless of the text-coverage heuristic. - """ - - ocr = self.__ocr_mock() - await ScreenObservationService(ocr=ocr).observe( - step_number=0, - session_id="run-test", - hashes=self.__hashes(), - budget=self.__budget(), - manifest=self.__manifest(), - capture=self.__capture( - xml_content=('') - ), - ) - - ocr.extract.assert_awaited_once() - - async def test_game_surface_frame_forces_ocr(self) -> None: - """ - OpenGL / SurfaceView roots expose no element tree; OCR must run to - produce any actionable manifest at all. - """ - - ocr = self.__ocr_mock() - await ScreenObservationService(ocr=ocr).observe( - step_number=0, - session_id="run-test", - hashes=self.__hashes(), - budget=self.__budget(), - manifest=self.__manifest(), - capture=self.__capture( - xml_content=('') - ), - ) - - ocr.extract.assert_awaited_once() - - async def test_sparse_native_hierarchy_forces_ocr(self) -> None: - """ - A NATIVE frame whose hierarchy parsed but yielded only a handful of - container nodes is treated as incomplete; OCR must run to recover the - text-bearing elements the dump missed. - """ - - ocr = self.__ocr_mock() - await ScreenObservationService(ocr=ocr).observe( - step_number=0, - session_id="run-test", - hashes=self.__hashes(), - budget=self.__budget(), - manifest=self.__manifest(), - capture=self.__capture( - xml_content='' - ), - ) - - ocr.extract.assert_awaited_once() - - async def test_missing_xml_keeps_ocr_running(self) -> None: - """ - Absent XML defaults to NATIVE; the existing OCR call path remains intact. - """ - - ocr = self.__ocr_mock() - await ScreenObservationService(ocr=ocr).observe( - step_number=0, - session_id="run-test", - hashes=self.__hashes(), - budget=self.__budget(), - manifest=self.__manifest(), - capture=self.__capture(xml_content=None), - ) - - ocr.extract.assert_awaited_once() - - async def test_keyboard_visibility_default_when_no_device(self) -> None: - """ - Sanity check the observation still returns a HIDDEN keyboard when no - device adapter is wired. Belt-and-braces guard so the OCR-skip path - doesn't inadvertently short-circuit unrelated branches. - """ - - ocr = self.__ocr_mock() - - observation = await ScreenObservationService(ocr=ocr).observe( - step_number=0, - session_id="run-test", - hashes=self.__hashes(), - budget=self.__budget(), - manifest=self.__manifest(), - capture=self.__capture( - xml_content=('') - ), - ) - - self.assertIs(observation.keyboard.visibility, KeyboardVisibility.UNKNOWN) diff --git a/tests/unit/core/perception/test_ocr.py b/tests/unit/core/perception/test_ocr.py index c01d03f0..fee157ff 100644 --- a/tests/unit/core/perception/test_ocr.py +++ b/tests/unit/core/perception/test_ocr.py @@ -179,7 +179,9 @@ async def test_disjoint_tokens_both_survive(self) -> None: self.assertEqual(len(result.tokens), 2) async def test_failing_member_is_isolated_from_ensemble(self) -> None: - """A member that raises :class:`OcrError` must be silently dropped; the remaining members still produce their tokens.""" + """ + A member that raises :class:`OcrError` must be silently dropped; the remaining members still produce their tokens. + """ token = self.__token(text="Hello", score=0.9, bounds=self.__bounds(x=10)) service = OcrEnsembleService( diff --git a/tests/unit/core/perception/test_orientation.py b/tests/unit/core/perception/test_orientation.py index cc28e0ed..f921767d 100644 --- a/tests/unit/core/perception/test_orientation.py +++ b/tests/unit/core/perception/test_orientation.py @@ -26,7 +26,7 @@ def __png_bytes(*, width: int, height: int) -> bytes: def test_landscape_image_with_portrait_report_swaps_dims(self) -> None: """ - Cooking-Craze-style mismatch: image is wider than tall, device reports portrait. + game-app-style mismatch: image is wider than tall, device reports portrait. """ image = self.__png_bytes(width=2340, height=1080) diff --git a/tests/unit/core/prompts/test_gemini.py b/tests/unit/core/prompts/test_gemini.py index 02a32b98..809ae143 100644 --- a/tests/unit/core/prompts/test_gemini.py +++ b/tests/unit/core/prompts/test_gemini.py @@ -55,7 +55,7 @@ def test_verifier_feedback_requires_corrective_action_before_completion(self) -> {"reason": "modal still visible"}, ] }, - sub_goal_info={"description": "Confirm SalarySe office address"}, + sub_goal_info={"description": "Confirm Finance office address"}, ) self.assertIn("Take the next concrete UI action", user_context) @@ -104,8 +104,8 @@ def test_observed_assertion_is_rendered_in_current_step(self) -> None: sub_goal_info={ "index": 1, "total": 3, - "description": "Search for ghar soap on Amazon", - "assertion": "The Amazon search results page for 'ghar soap' is displayed with product cards.", + "description": "Search for ghar soap on Retail", + "assertion": "The Retail search results page for 'ghar soap' is displayed with product cards.", }, ) @@ -121,8 +121,8 @@ def test_observed_goal_makes_visual_assessment_the_sole_completion_signal(self) sub_goal_info={ "index": 1, "total": 3, - "description": "Search for ghar soap on Amazon", - "assertion": "The Amazon search results for 'ghar soap' are displayed.", + "description": "Search for ghar soap on Retail", + "assertion": "The Retail search results for 'ghar soap' are displayed.", }, ) diff --git a/tests/unit/core/prompts/test_rejection.py b/tests/unit/core/prompts/test_rejection.py index ed85c824..fdfb9fa0 100644 --- a/tests/unit/core/prompts/test_rejection.py +++ b/tests/unit/core/prompts/test_rejection.py @@ -16,12 +16,12 @@ def test_interactive_prompt_offers_ask_user(self) -> None: """ text = RepeatedFailureRejectionPromptBuilder.build( - action_descriptor="Swipe left on More on Swiggy", + action_descriptor="Swipe left on More on Delivery", interactive=True, ) self.assertIn("REJECTED", text) - self.assertIn("Swipe left on More on Swiggy", text) + self.assertIn("Swipe left on More on Delivery", text) self.assertIn("ask_user", text) def test_interactive_prompt_does_not_request_validate_completion(self) -> None: @@ -48,12 +48,12 @@ def test_non_interactive_prompt_does_not_offer_ask_user(self) -> None: """ text = RepeatedFailureRejectionPromptBuilder.build( - action_descriptor="Swipe left on More on Swiggy", + action_descriptor="Swipe left on More on Delivery", interactive=False, ) self.assertIn("REJECTED", text) - self.assertIn("Swipe left on More on Swiggy", text) + self.assertIn("Swipe left on More on Delivery", text) self.assertNotIn("ask_user", text) def test_non_interactive_prompt_offers_navigate_back_escape(self) -> None: diff --git a/tests/unit/core/prompts/test_tools_schema.py b/tests/unit/core/prompts/test_tools_schema.py index ce8613ab..97fafe85 100644 --- a/tests/unit/core/prompts/test_tools_schema.py +++ b/tests/unit/core/prompts/test_tools_schema.py @@ -99,7 +99,9 @@ def test_get_all_definitions_returns_full_catalog(self) -> None: ) def test_action_type_enum_omits_legacy_enter(self) -> None: - """The execute_ui action_type enum must not advertise the deprecated 'enter' action.""" + """ + The execute_ui action_type enum must not advertise the deprecated 'enter' action. + """ definitions = ToolRegistry.get_all_definitions()["function_declarations"] execute_ui = next( diff --git a/tests/unit/core/safety/test_classifier.py b/tests/unit/core/safety/test_classifier.py index 8618e6ee..090b43be 100644 --- a/tests/unit/core/safety/test_classifier.py +++ b/tests/unit/core/safety/test_classifier.py @@ -7,14 +7,8 @@ class IntentSafetyClassifierTest(unittest.TestCase): """ - Pins the pre-execution intent-safety classifier behaviour. - - The classifier replaces the previous per-step safety scan. - Per-step scanning - matched ``"wipe"`` inside ``"swipe"`` and blocked every scroll - gesture; intent-level screening only runs once on the user's stated - goal so legitimate swipe / type / tap actions cannot be blocked by - a substring false positive. + Pins the pre-execution intent-safety classifier: it screens the stated goal once, so + legitimate swipe / type / tap actions are never blocked by a substring false positive. """ def test_safe_intent_is_cleared(self) -> None: @@ -22,7 +16,7 @@ def test_safe_intent_is_cleared(self) -> None: A benign intent passes the classifier with no matched keyword. """ - verdict = IntentSafetyClassifier().classify(intent="Open Swiggy app and search for dosa") + verdict = IntentSafetyClassifier().classify(intent="Open Delivery app and search for dosa") self.assertTrue(verdict.safe) self.assertIsNone(verdict.matched_keyword) diff --git a/tests/unit/core/services/conversation/test_title.py b/tests/unit/core/services/conversation/test_title.py index 4d0b70d1..29377340 100644 --- a/tests/unit/core/services/conversation/test_title.py +++ b/tests/unit/core/services/conversation/test_title.py @@ -17,7 +17,7 @@ class FakeTitleLlm(LLMPort): LLM test double for conversation title composition. """ - def __init__(self, *, content: str = '"HealthTap Login"') -> None: + def __init__(self, *, content: str = '"Healthcare Login"') -> None: """ Store the generated content returned by the fake model. """ @@ -70,15 +70,15 @@ async def test_compose_uses_llm_title_when_available(self) -> None: title = await TitleComposer(llm=FakeTitleLlm(content='"Test login flow"')).compose( context=TitleContext( intent=( - "Open HealthTap and login with email siddhant.sisodiya@drizz.dev " + "Open Healthcare and login with email test.user@example.com " "and password Testin@23" ), - package="com.healthtap.userhtexpress", + package="com.example.health", ) ) self.assertEqual(title, "Test login flow") - self.assertNotIn("siddhant.sisodiya", title) + self.assertNotIn("test.user", title) self.assertNotIn("Testin@23", title) async def test_compose_rejects_rogue_intent_echo(self) -> None: @@ -89,13 +89,13 @@ async def test_compose_rejects_rogue_intent_echo(self) -> None: title = await TitleComposer( llm=FakeTitleLlm( content=( - "Open HealthTap and login with email siddhant.sisodiya@drizz.dev " + "Open Healthcare and login with email test.user@example.com " "and password Testin@23" ) ) - ).compose(context=TitleContext(intent=self.__long_intent(), package="com.healthtap")) + ).compose(context=TitleContext(intent=self.__long_intent(), package="com.example.health")) - self.assertEqual(title, "Authoring com.healthtap") + self.assertEqual(title, "Authoring com.example.health") async def test_compose_without_llm_uses_package_fallback(self) -> None: """ @@ -105,16 +105,16 @@ async def test_compose_without_llm_uses_package_fallback(self) -> None: title = await TitleComposer().compose( context=TitleContext( intent=( - "Open HealthTap and login with email siddhant.sisodiya@drizz.dev " + "Open Healthcare and login with email test.user@example.com " "and password Testin@23" ), - package="com.healthtap.userhtexpress", + package="com.example.health", ) ) - self.assertEqual(title, "Authoring com.healthtap.userhtexpress") - self.assertNotIn("HealthTap", title) - self.assertNotIn("siddhant.sisodiya", title) + self.assertEqual(title, "Authoring com.example.health") + self.assertNotIn("Healthcare", title) + self.assertNotIn("test.user", title) async def test_initial_uses_generic_authoring_fallback_without_package(self) -> None: """ @@ -122,7 +122,7 @@ async def test_initial_uses_generic_authoring_fallback_without_package(self) -> """ title = TitleComposer().initial( - context=TitleContext(intent="Open HealthTap and login", package=None) + context=TitleContext(intent="Open Healthcare and login", package=None) ) self.assertEqual(title, "Authoring session") @@ -177,7 +177,7 @@ async def test_prompt_requests_semantic_title_not_intent_copy(self) -> None: prompt = TitlePromptBuilder() system = prompt.build_system_instruction() - user = prompt.build_prompt(intent="Open HealthTap and login with email and password") + user = prompt.build_prompt(intent="Open Healthcare and login with email and password") self.assertIn("short title for an authoring run", system) self.assertIn("Create a fresh 2-6 word action phrase", system) @@ -191,9 +191,9 @@ async def test_prompt_requests_semantic_title_not_intent_copy(self) -> None: @staticmethod def __long_intent() -> str: """ - Return a repeated intent like staging supplied for the HealthTap run. + Return a repeated intent like staging supplied for the Healthcare run. """ return "\n".join( - "HealthTap app is opened, now login with email and password" for _ in range(10) + "Healthcare app is opened, now login with email and password" for _ in range(10) ) diff --git a/tests/unit/core/services/generation/test_assembler.py b/tests/unit/core/services/generation/test_assembler.py index e5bb879d..b697a6e7 100644 --- a/tests/unit/core/services/generation/test_assembler.py +++ b/tests/unit/core/services/generation/test_assembler.py @@ -325,11 +325,11 @@ def test_launch_marker_becomes_a_launch_step(self) -> None: evidence = self.__assembler.assemble( intent="i", goal="g", - package="com.meesho.supply", + package="com.example.shop", trace=self.__trace( NormalizedEntry( launch=LaunchMarker( - package="com.meesho.supply", + package="com.example.shop", provenance=LaunchProvenance.LAUNCHER_TRANSITION, source_steps=(0,), ) @@ -342,7 +342,7 @@ def test_launch_marker_becomes_a_launch_step(self) -> None: self.assertEqual(launch.event, "launch") self.assertIsNotNone(launch.launch) assert launch.launch is not None - self.assertEqual(launch.launch.package, "com.meesho.supply") + self.assertEqual(launch.launch.package, "com.example.shop") self.assertEqual(launch.launch.provenance, LaunchProvenance.LAUNCHER_TRANSITION) self.assertEqual(launch.launch.source_steps, (0,)) @@ -383,7 +383,7 @@ def test_evidence_package_is_taken_from_the_first_launch_marker(self) -> None: trace=self.__trace( NormalizedEntry( launch=LaunchMarker( - package="com.meesho.supply", + package="com.example.shop", provenance=LaunchProvenance.LAUNCHER_TRANSITION, source_steps=(0,), ) @@ -392,7 +392,7 @@ def test_evidence_package_is_taken_from_the_first_launch_marker(self) -> None: ), ) - self.assertEqual(evidence.package, "com.meesho.supply") + self.assertEqual(evidence.package, "com.example.shop") def test_store_record_maps_to_capture_evidence(self) -> None: """ diff --git a/tests/unit/core/services/generation/test_baseline.py b/tests/unit/core/services/generation/test_baseline.py index 3976e1dc..d1742950 100644 --- a/tests/unit/core/services/generation/test_baseline.py +++ b/tests/unit/core/services/generation/test_baseline.py @@ -46,7 +46,7 @@ def __evidence(*, steps: Tuple[EvidenceStep, ...], partial: bool = False) -> Evi partial=partial, intent="order a burger", goal="burger added to cart", - package="in.swiggy.android", + package="com.example.delivery", ) @staticmethod @@ -61,7 +61,7 @@ def __launch() -> EvidenceStep: action="launch", launch=StepLaunch( source_steps=(0,), - package="in.swiggy.android", + package="com.example.delivery", provenance=LaunchProvenance.LAUNCHER_TRANSITION, ), ) diff --git a/tests/unit/core/services/generation/test_classifier.py b/tests/unit/core/services/generation/test_classifier.py index 3a4b61e7..904de9fe 100644 --- a/tests/unit/core/services/generation/test_classifier.py +++ b/tests/unit/core/services/generation/test_classifier.py @@ -31,7 +31,7 @@ def test_rejects_a_real_app_package(self) -> None: A real app package is not classified as a launcher. """ - self.assertFalse(self.__classifier.is_launcher(package="com.meesho.supply")) + self.assertFalse(self.__classifier.is_launcher(package="com.example.shop")) def test_honours_an_injected_launcher_set(self) -> None: """ diff --git a/tests/unit/core/services/generation/test_distiller.py b/tests/unit/core/services/generation/test_distiller.py index 98fef6eb..17efa27e 100644 --- a/tests/unit/core/services/generation/test_distiller.py +++ b/tests/unit/core/services/generation/test_distiller.py @@ -24,14 +24,14 @@ def setUp(self) -> None: def __fixture(self) -> Path: """ - Return the committed Meesho loop run fixture path. + Return the committed Shopping loop run fixture path. """ - return Path("assets/history/2026-06-09/15a28bb0/history__com.meesho.supply.json") + return Path("assets/history/2026-06-09/loop-run/history__com.example.shop.json") def __recovery_steps(self) -> Tuple[int, ...]: """ - Return the recorded recovery step numbers in the Meesho loop fixture. + Return the recorded recovery step numbers in the Shopping loop fixture. """ return (10, 14, 15, 27, 28) @@ -340,13 +340,13 @@ def test_not_partial_when_validation_succeeded(self) -> None: self.assertFalse(result.partial) self.assertIsNone(result.reason) - def test_meesho_loop_fixture_is_distilled(self) -> None: + def test_shopping_loop_fixture_is_distilled(self) -> None: """ - The recorded Meesho loop drops recovery, collapses inside the region, and flags partial. + The recorded Shopping loop drops recovery, collapses inside the region, and flags partial. """ if not self.__fixture().exists(): - self.skipTest("Meesho loop history fixture absent (fixtures are gitignored).") + self.skipTest("Shopping loop history fixture absent (fixtures are gitignored).") payload = json.loads(self.__fixture().read_text()) records = tuple(StepRecord.model_validate(item) for item in payload["history"]) diff --git a/tests/unit/core/services/generation/test_normalizer.py b/tests/unit/core/services/generation/test_normalizer.py index 569b3e76..3669635b 100644 --- a/tests/unit/core/services/generation/test_normalizer.py +++ b/tests/unit/core/services/generation/test_normalizer.py @@ -34,10 +34,10 @@ def __launcher(self) -> str: def __fixture_dir(self) -> Path: """ - Return the committed 78a8dcbf run fixture directory. + Return the committed launcher run fixture directory. """ - return Path("assets/history/2026-06-23/78a8dcbf") + return Path("assets/history/2026-06-23/launcher-run") def __record( self, @@ -88,14 +88,14 @@ def test_warm_start_synthesises_leading_launch(self) -> None: """ records = ( - self.__record(number=0, execution="com.meesho.supply"), - self.__record(number=1, execution="com.meesho.supply"), + self.__record(number=0, execution="com.example.shop"), + self.__record(number=1, execution="com.example.shop"), ) launches = self.__launches(entries=self.__normalizer.normalize(records=records).entries) self.assertEqual(len(launches), 1) - self.assertEqual(launches[0].package, "com.meesho.supply") + self.assertEqual(launches[0].package, "com.example.shop") self.assertEqual(launches[0].provenance, LaunchProvenance.SYNTHETIC_WARM_START) self.assertEqual(launches[0].source_steps, ()) @@ -105,15 +105,15 @@ def test_launcher_transition_collapses_and_grounds_launch(self) -> None: """ records = ( - self.__record(number=0, execution=self.__launcher(), activity="com.meesho.supply"), - self.__record(number=1, execution="com.meesho.supply"), + self.__record(number=0, execution=self.__launcher(), activity="com.example.shop"), + self.__record(number=1, execution="com.example.shop"), ) entries = self.__normalizer.normalize(records=records).entries launches = self.__launches(entries=entries) self.assertEqual(len(launches), 1) - self.assertEqual(launches[0].package, "com.meesho.supply") + self.assertEqual(launches[0].package, "com.example.shop") self.assertEqual(launches[0].provenance, LaunchProvenance.LAUNCHER_TRANSITION) self.assertEqual(launches[0].source_steps, (0,)) self.assertEqual(self.__kept(entries=entries), (1,)) @@ -124,9 +124,9 @@ def test_system_package_stays_in_flow(self) -> None: """ records = ( - self.__record(number=0, execution="com.meesho.supply"), + self.__record(number=0, execution="com.example.shop"), self.__record(number=1, execution="com.google.android.gms"), - self.__record(number=2, execution="com.meesho.supply"), + self.__record(number=2, execution="com.example.shop"), ) entries = self.__normalizer.normalize(records=records).entries @@ -140,10 +140,10 @@ def test_app_triggered_external_surface_stays_in_flow(self) -> None: """ records = ( - self.__record(number=0, execution="com.healthtap.userhtexpress"), + self.__record(number=0, execution="com.example.health"), self.__record( number=1, - execution="com.healthtap.userhtexpress", + execution="com.example.health", activity="com.android.chrome", ), self.__record(number=2, execution="com.android.chrome"), @@ -152,7 +152,7 @@ def test_app_triggered_external_surface_stays_in_flow(self) -> None: entries = self.__normalizer.normalize(records=records).entries launches = self.__launches(entries=entries) - self.assertEqual([marker.package for marker in launches], ["com.healthtap.userhtexpress"]) + self.assertEqual([marker.package for marker in launches], ["com.example.health"]) self.assertEqual(self.__kept(entries=entries), (0, 1, 2)) def test_launcher_opened_browser_remains_a_real_launch(self) -> None: @@ -161,7 +161,7 @@ def test_launcher_opened_browser_remains_a_real_launch(self) -> None: """ records = ( - self.__record(number=0, execution="com.healthtap.userhtexpress"), + self.__record(number=0, execution="com.example.health"), self.__record( number=1, execution=self.__launcher(), @@ -174,7 +174,7 @@ def test_launcher_opened_browser_remains_a_real_launch(self) -> None: self.assertEqual( [marker.package for marker in launches], - ["com.healthtap.userhtexpress", "com.android.chrome"], + ["com.example.health", "com.android.chrome"], ) def test_trailing_launcher_step_is_dropped_without_launch(self) -> None: @@ -183,7 +183,7 @@ def test_trailing_launcher_step_is_dropped_without_launch(self) -> None: """ records = ( - self.__record(number=0, execution="com.meesho.supply"), + self.__record(number=0, execution="com.example.shop"), self.__record( number=1, execution=self.__launcher(), activity=self.__launcher(), action="home" ), @@ -245,21 +245,21 @@ def test_never_targets_a_launcher_package(self) -> None: """ records = ( - self.__record(number=0, execution=self.__launcher(), activity="com.meesho.supply"), - self.__record(number=1, execution="com.meesho.supply"), + self.__record(number=0, execution=self.__launcher(), activity="com.example.shop"), + self.__record(number=1, execution="com.example.shop"), ) launches = self.__launches(entries=self.__normalizer.normalize(records=records).entries) self.assertTrue(all(marker.package not in LAUNCHER_PACKAGES for marker in launches)) - def test_78a8dcbf_run_normalizes_to_meesho_launch(self) -> None: + def test_launcher_run_normalizes_to_shopping_launch(self) -> None: """ - The recorded launcher-launched Meesho run yields one Meesho launch and keeps system steps. + The recorded launcher-launched Shopping run yields one Shopping launch and keeps system steps. """ if not self.__fixture_dir().exists(): - self.skipTest("78a8dcbf run history fixture absent (fixtures are gitignored).") + self.skipTest("launcher run history fixture absent (fixtures are gitignored).") records: List[StepRecord] = [] for path in sorted(self.__fixture_dir().glob("history__com.*.json")): @@ -270,7 +270,7 @@ def test_78a8dcbf_run_normalizes_to_meesho_launch(self) -> None: launches = self.__launches(entries=entries) self.assertEqual(len(launches), 1) - self.assertEqual(launches[0].package, "com.meesho.supply") + self.assertEqual(launches[0].package, "com.example.shop") self.assertEqual(launches[0].provenance, LaunchProvenance.LAUNCHER_TRANSITION) self.assertIn(0, launches[0].source_steps) self.assertTrue(all(marker.package not in LAUNCHER_PACKAGES for marker in launches)) diff --git a/tests/unit/core/services/generation/test_projector.py b/tests/unit/core/services/generation/test_projector.py index b5753f38..74441fc5 100644 --- a/tests/unit/core/services/generation/test_projector.py +++ b/tests/unit/core/services/generation/test_projector.py @@ -52,7 +52,7 @@ def __generator(self) -> DeterministicFlowGenerator: return DeterministicFlowGenerator() @staticmethod - def __launch(*, index: int = 0, package: str = "in.swiggy.android") -> EvidenceStep: + def __launch(*, index: int = 0, package: str = "com.example.delivery") -> EvidenceStep: """ Build a launcher-transition launch evidence step. """ @@ -99,20 +99,20 @@ def __validation(*, index: int, success: bool = True) -> EvidenceStep: @staticmethod def __evidence(*, steps: Tuple[EvidenceStep, ...], partial: bool = False) -> Evidence: """ - Wrap evidence steps for the Swiggy-style run. + Wrap evidence steps for the Delivery-style run. """ return Evidence( - intent="order a burger on swiggy", + intent="order a burger on delivery", goal="McDonald's burger added to cart", - package="in.swiggy.android", + package="com.example.delivery", steps=steps, partial=partial, ) - async def test_swiggy_run_projects_to_policy_clean_flow(self) -> None: + async def test_delivery_run_projects_to_policy_clean_flow(self) -> None: """ - The Swiggy run (launch + taps + validation) projects to a launch-led, validation-terminated, policy-clean flow. + The Delivery run (launch + taps + validation) projects to a launch-led, validation-terminated, policy-clean flow. """ evidence = self.__evidence( diff --git a/tests/unit/core/services/generation/test_projector_fixtures.py b/tests/unit/core/services/generation/test_projector_fixtures.py deleted file mode 100644 index b825009b..00000000 --- a/tests/unit/core/services/generation/test_projector_fixtures.py +++ /dev/null @@ -1,112 +0,0 @@ -from __future__ import annotations - -import json -import unittest -from pathlib import Path -from typing import Tuple - -from fathom.adapters.dialect.drizz.factory import DrizzDialectFactory -from fathom.constants.flow import LaunchProvenance, NodeKind -from fathom.core.dialect.policy import Policy -from fathom.core.services.generation.assembler import EvidenceAssembler -from fathom.core.services.generation.classifier import LauncherClassifier -from fathom.core.services.generation.distiller import Distiller -from fathom.core.services.generation.normalizer import RunTraceNormalizer -from fathom.core.services.generation.projector import DeterministicFlowGenerator -from fathom.schemas.flow import Evidence, Issue, LaunchNode -from fathom.schemas.generation import ProjectionReport -from fathom.schemas.steps import StepHistory - -FIXTURE_DIR = Path(__file__).resolve().parents[4] / "fixtures" / "generation" - - -class ProjectorRcaFixtureTest(unittest.IsolatedAsyncioTestCase): - """ - Drives real recorded RCA histories through distill -> normalize -> assemble -> project -> policy -> render -> check. - """ - - def __evidence(self, *, fixture: str, intent: str, goal: str, package: str) -> Evidence: - """ - Build evidence from a recorded history fixture via the production generation pipeline. - """ - - raw = json.loads((FIXTURE_DIR / fixture).read_text()) - records = StepHistory.model_validate(raw).history - distillation = Distiller().distill(records=records) - trace = RunTraceNormalizer(classifier=LauncherClassifier()).normalize( - records=distillation.records - ) - - return EvidenceAssembler().assemble( - trace=trace, - intent=intent, - goal=goal, - package=package, - partial=distillation.partial, - discarded=distillation.discarded, - reason=distillation.reason, - ) - - def __render( - self, *, evidence: Evidence - ) -> Tuple[ProjectionReport, Tuple[Issue, ...], str, Tuple[Issue, ...]]: - """ - Project the evidence and return the report, policy issues, rendered text, and checker issues. - """ - - report = DeterministicFlowGenerator().project(evidence=evidence) - policy_evidence = evidence.model_copy(update={"partial": report.flow.partial}) - policy = Policy().evaluate(flow=report.flow, evidence=policy_evidence) - dialect = DrizzDialectFactory().create() - text = dialect.renderer.render(flow=report.flow) - check = dialect.checker.check(text=text) - - return report, policy.issues, text, check.issues - - async def test_swiggy_history_projects_to_clean_grounded_script(self) -> None: - """ - The Swiggy RCA run projects to a launch-led, partial, policy- and syntax-clean script. - """ - - evidence = self.__evidence( - fixture="swiggy_history.json", - intent="order a burger on swiggy", - goal="burger added to cart", - package="in.swiggy.android", - ) - report, policy_issues, text, check_issues = self.__render(evidence=evidence) - launch = report.flow.nodes[0] - self.assertIsInstance(launch, LaunchNode) - assert isinstance(launch, LaunchNode) - - self.assertEqual(policy_issues, ()) - self.assertEqual(check_issues, ()) - self.assertIs(launch.kind, NodeKind.LAUNCH) - self.assertEqual(launch.package, "in.swiggy.android") - self.assertIs(launch.provenance, LaunchProvenance.LAUNCHER_TRANSITION) - self.assertEqual(launch.source_steps, (0,)) - self.assertTrue(report.flow.partial) - self.assertIsNot(report.flow.nodes[-1].kind, NodeKind.CHECK) - self.assertTrue(text.startswith("OPEN_APP")) - self.assertIn("in.swiggy.android", text.splitlines()[0]) - self.assertNotIn("Validate", text) - - async def test_radioplayer_history_projects_to_partial_grounded_script(self) -> None: - """ - The Radioplayer RCA run projects without fabricating an unstructured validation. - """ - - evidence = self.__evidence( - fixture="radioplayer_history.json", - intent="open radioplayer and reach the homepage", - goal="homepage visible", - package="com.radioplayer.mobile", - ) - report, policy_issues, text, check_issues = self.__render(evidence=evidence) - - self.assertEqual(policy_issues, ()) - self.assertEqual(check_issues, ()) - self.assertTrue(text.startswith("OPEN_APP")) - self.assertIn("com.radioplayer.mobile", text.splitlines()[0]) - self.assertTrue(report.flow.partial) - self.assertIsNot(report.flow.nodes[-1].kind, NodeKind.CHECK) diff --git a/tests/unit/core/services/qualifier/test_llm.py b/tests/unit/core/services/qualifier/test_llm.py index 4f195f35..7fe625b2 100644 --- a/tests/unit/core/services/qualifier/test_llm.py +++ b/tests/unit/core/services/qualifier/test_llm.py @@ -127,16 +127,16 @@ def json( REAL_EXECUTABLE_INTENTS = ( - "Search for McPuff", + "Search for Veg Roll", "open the contact app add new contact to it", "Search for a product, add it to cart, and complete checkout.", "Scroll vertically until you find Dominoes on the screen", "Scroll until you find McDonal's on the screen", "Scroll the food catalog section until you find Salad on the screen", "Scroll down until you find Jars & containers on the screen", - "Open Meesho and then scroll down until you find Jars & containers on the screen", + "Open Shopping and then scroll down until you find Jars & containers on the screen", ( - "Open Swiggy app. Tap on Location dropdown. Select 'HSR Layout'. Tap on search bar. " + "Open Delivery app. Tap on Location dropdown. Select 'HSR Layout'. Tap on search bar. " "Enter 'Biryani' in search bar. Scroll up 40% auto suggest page. Tap on Show results." ), ) @@ -156,7 +156,7 @@ def json( POLITE_QUESTION_EXECUTABLE_INTENTS = ( - "Can you open Swiggy and search for Biryani?", + "Can you open Delivery and search for Biryani?", "Can you tap the checkout button?", "Could you scroll down and find the price?", "Can you go back to the previous screen?", @@ -219,7 +219,7 @@ async def test_qualify_call_passes_structured_output_contract(self) -> None: llm = ScriptedLLM(contents=[VerdictPayload.json(label="EXECUTABLE", confidence=0.9)]) qualifier = LLMIntentQualifier(llm=llm) - await qualifier.qualify(intent="Open Swiggy") + await qualifier.qualify(intent="Open Delivery") self.assertEqual(len(llm.structured_outputs), 1) structured = llm.structured_outputs[0] @@ -234,7 +234,7 @@ async def test_executable_intent_passes_through(self) -> None: llm = ScriptedLLM(contents=[VerdictPayload.json(label="EXECUTABLE", confidence=0.95)]) qualifier = LLMIntentQualifier(llm=llm) - verdict = await qualifier.qualify(intent="Search for McPuff") + verdict = await qualifier.qualify(intent="Search for Veg Roll") self.assertEqual(verdict.label, QualificationLabel.EXECUTABLE) self.assertEqual(verdict.rationale.category, RationaleCategory.UI_TASK) self.assertFalse(GATE_POLICY.should_block(verdict=verdict)) @@ -268,7 +268,7 @@ async def test_non_json_response_fails_open(self) -> None: """ qualifier = LLMIntentQualifier(llm=ScriptedLLM(contents=["definitely not json"])) - verdict = await qualifier.qualify(intent="Search for McPuff") + verdict = await qualifier.qualify(intent="Search for Veg Roll") self.assertEqual(verdict.label, QualificationLabel.EXECUTABLE) self.assertEqual(verdict.rationale.category, RationaleCategory.QUALIFIER_ERROR) self.assertFalse(GATE_POLICY.should_block(verdict=verdict)) @@ -282,7 +282,7 @@ async def test_valid_json_but_not_object_fails_open(self) -> None: for body in ("[]", '"foo"', "123", "null", "true"): with self.subTest(body=body): qualifier = LLMIntentQualifier(llm=ScriptedLLM(contents=[body])) - verdict = await qualifier.qualify(intent="Search for McPuff") + verdict = await qualifier.qualify(intent="Search for Veg Roll") self.assertEqual(verdict.label, QualificationLabel.EXECUTABLE) self.assertEqual(verdict.rationale.category, RationaleCategory.QUALIFIER_ERROR) self.assertFalse(GATE_POLICY.should_block(verdict=verdict)) @@ -294,7 +294,7 @@ async def test_rationale_is_not_object_fails_open(self) -> None: body = json.dumps({"label": "EXECUTABLE", "confidence": 0.9, "rationale": "oops"}) qualifier = LLMIntentQualifier(llm=ScriptedLLM(contents=[body])) - verdict = await qualifier.qualify(intent="Search for McPuff") + verdict = await qualifier.qualify(intent="Search for Veg Roll") self.assertEqual(verdict.label, QualificationLabel.EXECUTABLE) self.assertEqual(verdict.rationale.category, RationaleCategory.QUALIFIER_ERROR) @@ -315,13 +315,15 @@ async def test_invalid_label_fails_open(self) -> None: ] ) qualifier = LLMIntentQualifier(llm=llm) - verdict = await qualifier.qualify(intent="Search for McPuff") + verdict = await qualifier.qualify(intent="Search for Veg Roll") self.assertEqual(verdict.label, QualificationLabel.EXECUTABLE) self.assertEqual(verdict.rationale.category, RationaleCategory.QUALIFIER_ERROR) self.assertFalse(GATE_POLICY.should_block(verdict=verdict)) async def test_unknown_probably_executable_string_fails_open(self) -> None: - """QualificationLabel is binary.""" + """ + QualificationLabel is binary. + """ llm = ScriptedLLM( contents=[ @@ -382,7 +384,7 @@ async def test_invalid_category_fails_open(self) -> None: ] ) qualifier = LLMIntentQualifier(llm=llm) - verdict = await qualifier.qualify(intent="Search for McPuff") + verdict = await qualifier.qualify(intent="Search for Veg Roll") self.assertEqual(verdict.rationale.category, RationaleCategory.QUALIFIER_ERROR) async def test_markdown_fence_is_stripped(self) -> None: @@ -393,7 +395,7 @@ async def test_markdown_fence_is_stripped(self) -> None: wrapped = "```json\n" + VerdictPayload.json(label="EXECUTABLE", confidence=0.9) + "\n```" qualifier = LLMIntentQualifier(llm=ScriptedLLM(contents=[wrapped])) - verdict = await qualifier.qualify(intent="Search for McPuff") + verdict = await qualifier.qualify(intent="Search for Veg Roll") self.assertEqual(verdict.label, QualificationLabel.EXECUTABLE) @@ -403,7 +405,7 @@ async def test_llm_exception_fails_open(self) -> None: """ qualifier = LLMIntentQualifier(llm=ExplodingLLM()) - verdict = await qualifier.qualify(intent="Search for McPuff") + verdict = await qualifier.qualify(intent="Search for Veg Roll") self.assertFalse(GATE_POLICY.should_block(verdict=verdict)) self.assertEqual(verdict.label, QualificationLabel.EXECUTABLE) @@ -450,7 +452,7 @@ async def test_under_specified_ui_intents_pass(self) -> None: async def test_polite_question_executable_intents_pass(self) -> None: """ - Polite-question-form UI commands ('Can you open Swiggy?') must pass the + Polite-question-form UI commands ('Can you open Delivery?') must pass the gate. Question mark is not a block signal. """ diff --git a/tests/unit/core/services/qualifier/test_permissive.py b/tests/unit/core/services/qualifier/test_permissive.py index b871c077..fa0d5a9e 100644 --- a/tests/unit/core/services/qualifier/test_permissive.py +++ b/tests/unit/core/services/qualifier/test_permissive.py @@ -26,7 +26,7 @@ async def test_returns_executable_for_normal_intent(self) -> None: A well-formed intent must be accepted with PERMISSIVE rationale. """ - verdict = await self.__qualifier.qualify(intent="Search for McPuff") + verdict = await self.__qualifier.qualify(intent="Search for Veg Roll") self.assertEqual(verdict.label, QualificationLabel.EXECUTABLE) self.assertEqual(verdict.rationale.category, RationaleCategory.PERMISSIVE) self.assertFalse(self.__policy.should_block(verdict=verdict)) diff --git a/tests/unit/core/services/resolution/test_resolution.py b/tests/unit/core/services/resolution/test_resolution.py index e290ffd7..bb995123 100644 --- a/tests/unit/core/services/resolution/test_resolution.py +++ b/tests/unit/core/services/resolution/test_resolution.py @@ -270,13 +270,13 @@ async def test_ocr_manifest_label_snaps_with_ocr_coordinate_source(self) -> None action = Action( label_id="1", rationale="open app", - target="Swiggy app icon", + target="Delivery app icon", action_type=ActionType.TAP, confidence=1.0, ) elements = { "1": { - "text": "Swiggy", + "text": "Delivery", "source": "ocr", "bounds": "[284,383][392,414]", }, @@ -496,7 +496,7 @@ async def test_horizontal_swipe_rejects_explicit_vertical_scroll_region(self) -> service = self.__build_service() action = Action( action_type=ActionType.SWIPE_LEFT, - target="More on Swiggy carousel", + target="More on Delivery carousel", rationale="find hidden card", label_id="2", confidence=1.0, @@ -522,7 +522,7 @@ async def test_horizontal_swipe_accepts_carousel_region(self) -> None: service = self.__build_service() action = Action( action_type=ActionType.SWIPE_LEFT, - target="More on Swiggy carousel", + target="More on Delivery carousel", rationale="find hidden card", label_id="7", confidence=1.0, diff --git a/tests/unit/core/services/resolution/test_unresolved_kind.py b/tests/unit/core/services/resolution/test_unresolved_kind.py index 398d2647..85068a3b 100644 --- a/tests/unit/core/services/resolution/test_unresolved_kind.py +++ b/tests/unit/core/services/resolution/test_unresolved_kind.py @@ -206,7 +206,9 @@ async def test_low_iou_text_less_view_stamps_generic_container(self) -> None: self.assertEqual(resolved.unresolved_kind, UnresolvedKind.GENERIC_CONTAINER) async def test_high_iou_textless_view_snaps_label(self) -> None: - """Text less View whose bounds the LLM bbox overlaps (IoU above the agreement floor) must trust the label_id and resolve via snap — avoiding an unnecessary perception round-trip when the LLM and manifest already agree on the region.""" + """ + Text less View whose bounds the LLM bbox overlaps (IoU above the agreement floor) must trust the label_id and resolve via snap — avoiding an unnecessary perception round-trip when the LLM and manifest already agree on the region. + """ service = self.__build_service() elements: Dict[str, Any] = { diff --git a/tests/unit/core/services/telemetry/test_announcer.py b/tests/unit/core/services/telemetry/test_announcer.py index df309ae1..4271207d 100644 --- a/tests/unit/core/services/telemetry/test_announcer.py +++ b/tests/unit/core/services/telemetry/test_announcer.py @@ -264,8 +264,9 @@ async def test_limit_bounds_the_loop(self) -> None: async def test_shutdown_after_unpaired_phase_open_kills_pulse(self) -> None: """ - Regression: a phase method that opens a pulse without a paired terminal call (e.g. INTENT_QUALIFYING with no INTENT_QUALIFIED closer) - must be cancellable by shutdown. In prod, a leaked QUALIFYING pulse kept firing PHASE_HEARTBEAT events for minutes after the workflow ended — pin shutdown is the safety net. + A phase method that opens a pulse without a paired terminal call (e.g. INTENT_QUALIFYING with + no INTENT_QUALIFIED closer) must still be cancellable by shutdown, so no PHASE_HEARTBEAT + events outlive the workflow. """ announcer, telemetry = self.__build(threshold=0.05, limit=120) diff --git a/tests/unit/core/services/test_conversation.py b/tests/unit/core/services/test_conversation.py index a49ef384..4911ff34 100644 --- a/tests/unit/core/services/test_conversation.py +++ b/tests/unit/core/services/test_conversation.py @@ -253,7 +253,7 @@ async def test_create_normalizes_long_initial_title_before_persistence(self) -> Thread creation accepts bounded long input and stores a ledger-safe title. """ - title = "Open swiggy app. " * 60 + title = "Open delivery app. " * 44 view = await self.__service.create( request=ThreadCreate( diff --git a/tests/unit/core/services/test_effect.py b/tests/unit/core/services/test_effect.py index 5088346e..64ff04a9 100644 --- a/tests/unit/core/services/test_effect.py +++ b/tests/unit/core/services/test_effect.py @@ -70,7 +70,7 @@ def test_departed_foreground_overrides_visual_progress(self) -> None: effect=self.__effect(status=ActionEffectStatus.PROGRESS), diff=self.__diff(regions=[]), bounds=self.bounds, - package="com.miniclip.game", + package="com.example.game", foreground="com.android.launcher", ) @@ -121,7 +121,7 @@ def test_unbound_target_launch_is_not_regression(self) -> None: diff=self.__diff(regions=[ScreenChangeRegion(x=410, y=1210, width=180, height=100)]), bounds=self.bounds, package=None, - foreground="com.meesho.supply", + foreground="com.example.shop", ) self.assertIsNone(reading.departed) @@ -137,7 +137,7 @@ def test_explicit_target_departure_remains_regression(self) -> None: effect=self.__effect(status=ActionEffectStatus.PROGRESS), diff=self.__diff(regions=[]), bounds=self.bounds, - package="com.meesho.supply", + package="com.example.shop", foreground="com.google.android.gms", ) diff --git a/tests/unit/core/services/test_hierarchy.py b/tests/unit/core/services/test_hierarchy.py index 2d9424a4..710cb5d8 100644 --- a/tests/unit/core/services/test_hierarchy.py +++ b/tests/unit/core/services/test_hierarchy.py @@ -194,7 +194,9 @@ async def test_process_xml_and_screen_returns_annotated_capture_with_bytes(self) self.assertGreater(len(result.annotated_capture.annotated_image or b""), 0) async def test_process_xml_and_screen_survives_pipeline_local_cleanup(self) -> None: - """Race regression: even when the pipeline's sink completes upload and the staging file becomes eligible for cleanup before any downstream stage runs, the hierarchy result must still carry the labeled manifest.""" + """ + Race regression: even when the pipeline's sink completes upload and the staging file becomes eligible for cleanup before any downstream stage runs, the hierarchy result must still carry the labeled manifest. + """ sink = _UnlinkingSink() pipeline = self.__build_pipeline(sink=sink) diff --git a/tests/unit/core/services/test_history.py b/tests/unit/core/services/test_history.py index 9aea3283..12985c03 100644 --- a/tests/unit/core/services/test_history.py +++ b/tests/unit/core/services/test_history.py @@ -143,13 +143,13 @@ async def test_appends_every_step_in_order_across_packages(self) -> None: await service.save_step( self.__result(number=0), - package_name="com.meesho.supply", + package_name="com.example.shop", execution_activity=self.__launcher(), ) await service.save_step( self.__result(number=1), - package_name="com.meesho.supply", - execution_activity="com.meesho.supply", + package_name="com.example.shop", + execution_activity="com.example.shop", ) await service.save_step( self.__result(number=2), @@ -172,7 +172,7 @@ async def test_preserves_execution_activity(self) -> None: await service.save_step( self.__result(number=0), - package_name="com.meesho.supply", + package_name="com.example.shop", execution_activity=self.__launcher(), ) @@ -191,8 +191,8 @@ async def test_persists_goal_context_on_workflow_record(self) -> None: await service.save_step( self.__result(number=0), - package_name="com.meesho.supply", - execution_activity="com.meesho.supply", + package_name="com.example.shop", + execution_activity="com.example.shop", goal=StepGoal( index=2, description="Check whether customer rating is >= 4.2", @@ -217,8 +217,8 @@ async def test_corrupt_trace_is_backed_up_not_silently_restarted(self) -> None: await service.save_step( self.__result(number=0), - package_name="com.meesho.supply", - execution_activity="com.meesho.supply", + package_name="com.example.shop", + execution_activity="com.example.shop", ) backups = list(directory.glob("history__execution.corrupt.*.json")) @@ -240,15 +240,15 @@ async def test_save_step_schedules_baseline_refresh_for_workflow_trace(self) -> await service.save_step( self.__result(number=0), intent="open and verify", - package_name="com.meesho.supply", - execution_activity="com.meesho.supply", + package_name="com.example.shop", + execution_activity="com.example.shop", ) self.assertEqual(len(refresher.scheduled), 1) execution_id, objective = refresher.scheduled[0] self.assertEqual(execution_id, "wf-1") self.assertEqual(objective.intent, "open and verify") - self.assertEqual(objective.package, "com.meesho.supply") + self.assertEqual(objective.package, "com.example.shop") async def test_flush_drains_baseline_refresher(self) -> None: """ @@ -283,15 +283,15 @@ async def test_completion_assertions_schedule_fresh_baseline_refresh(self) -> No await service.save_step( self.__result(number=0), intent="open and verify login screen", - package_name="com.meesho.supply", - execution_activity="com.meesho.supply", + package_name="com.example.shop", + execution_activity="com.example.shop", ) service.save_completion_assertions(assertions=(assertion,)) self.assertEqual(len(refresher.scheduled), 2) self.assertEqual(refresher.scheduled[1][0], "wf-1") self.assertEqual(refresher.scheduled[1][1].intent, "open and verify login screen") - self.assertEqual(refresher.scheduled[1][1].package, "com.meesho.supply") + self.assertEqual(refresher.scheduled[1][1].package, "com.example.shop") async def test_normal_mode_writes_only_workflow_trace_for_step_history(self) -> None: """ @@ -304,13 +304,13 @@ async def test_normal_mode_writes_only_workflow_trace_for_step_history(self) -> await service.save_step( self.__result(number=0), - package_name="com.meesho.supply", - execution_activity="com.meesho.supply", + package_name="com.example.shop", + execution_activity="com.example.shop", ) self.assertTrue((directory / "history__execution.json").exists()) - self.assertFalse((directory / "history__com.meesho.supply.json").exists()) - self.assertFalse((directory / "history__com.meesho.supply.yaml").exists()) + self.assertFalse((directory / "history__com.example.shop.json").exists()) + self.assertFalse((directory / "history__com.example.shop.yaml").exists()) async def test_debug_mode_writes_per_package_step_history(self) -> None: """ @@ -326,13 +326,13 @@ async def test_debug_mode_writes_per_package_step_history(self) -> None: await service.save_step( self.__result(number=0), - package_name="com.meesho.supply", - execution_activity="com.meesho.supply", + package_name="com.example.shop", + execution_activity="com.example.shop", ) self.assertTrue((directory / "history__execution.json").exists()) - self.assertTrue((directory / "history__com.meesho.supply.json").exists()) - self.assertTrue((directory / "history__com.meesho.supply.yaml").exists()) + self.assertTrue((directory / "history__com.example.shop.json").exists()) + self.assertTrue((directory / "history__com.example.shop.yaml").exists()) class HistoryFinalizationTest(unittest.IsolatedAsyncioTestCase): diff --git a/tests/unit/core/services/test_parsing.py b/tests/unit/core/services/test_parsing.py index 6d6c172f..262b81df 100644 --- a/tests/unit/core/services/test_parsing.py +++ b/tests/unit/core/services/test_parsing.py @@ -412,7 +412,9 @@ def test_leaves_reason_null_when_rationale_is_whitespace_only(self) -> None: def test_complete_action_with_false_sub_goal_flag_autofills_after_normalization( self, ) -> None: - """When ``action_type=COMPLETE`` arrives with ``sub_goal_completed=False``, the normalizer must force the flag to True FIRST, then the autofill must see the True flag and populate ``subgoal_completion_reason`` from the rationale — pinning the COMPLETE-flag → autofill ordering.""" + """ + When ``action_type=COMPLETE`` arrives with ``sub_goal_completed=False``, the normalizer must force the flag to True FIRST, then the autofill must see the True flag and populate ``subgoal_completion_reason`` from the rationale — pinning the COMPLETE-flag → autofill ordering. + """ parser = ToolResponseParser() response = self.__response( @@ -573,6 +575,34 @@ def test_verify_goal_complete_preserves_validation_subject(self) -> None: self.assertEqual(result.action.action_type, ActionType.COMPLETE) self.assertEqual(result.action.validation_subject, "The final step is complete.") + def test_verify_goal_prefers_explicit_assertion_for_validation_subject(self) -> None: + """ + A crisp assertion beats completion reasons and the screen description. + """ + + parser = ToolResponseParser() + result = parser.parse( + response=self.__response( + call=_Call( + name="verify_goal", + args={ + "assistant_message": "The cart shows the item.", + "goal_completed": False, + "sub_goal_completed": True, + "subgoal_completion_reason": "Item added.", + "current_screen": "Cart screen", + "assertion": "Cart contains Diet Coke x1", + "evidence": "Cart badge shows 1.", + }, + ) + ) + ) + + assert result.validation is not None + assert result.action is not None + self.assertEqual(result.validation.subject, "Cart contains Diet Coke x1") + self.assertEqual(result.action.validation_subject, "Cart contains Diet Coke x1") + class ToolResponseParserBoundaryTest(unittest.TestCase): """ @@ -907,37 +937,6 @@ def test_recall_memory_does_not_invent_tool_data(self) -> None: ) -if __name__ == "__main__": - unittest.main() - - def test_verify_goal_prefers_explicit_assertion_for_validation_subject(self) -> None: - """ - A crisp assertion beats completion reasons and the screen description. - """ - - parser = ToolResponseParser() - result = parser.parse( - response=self.__response( - call=_Call( - name="verify_goal", - args={ - "assistant_message": "The cart shows the item.", - "goal_completed": False, - "sub_goal_completed": True, - "subgoal_completion_reason": "Item added.", - "current_screen": "Cart screen", - "assertion": "Cart contains Diet Coke x1", - "evidence": "Cart badge shows 1.", - }, - ) - ) - ) - - assert result.validation is not None - self.assertEqual(result.validation.subject, "Cart contains Diet Coke x1") - self.assertEqual(result.action.validation_subject, "Cart contains Diet Coke x1") - - class ToolResponseParserVisualAssessmentTest(unittest.TestCase): """ Covers the shadow visual assessment riding the same primary response as the live action. @@ -1019,3 +1018,7 @@ def test_absent_assessment_is_clean(self) -> None: self.assertIsNone(result.visual_assessment) self.assertFalse(result.assessment_malformed) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/core/services/test_projector.py b/tests/unit/core/services/test_projector.py index 418eed0b..b27e2a74 100644 --- a/tests/unit/core/services/test_projector.py +++ b/tests/unit/core/services/test_projector.py @@ -122,8 +122,7 @@ def __job(self) -> Job: async def test_projector_walks_every_page(self) -> None: """ - Three pages of messages must all be projected; previously only the - first page was read and the rest were silently dropped. + Every page of messages must be projected — all three pages here, not just the first. """ pages = [ diff --git a/tests/unit/core/services/test_recorder.py b/tests/unit/core/services/test_recorder.py index cdea3eb8..cf0932d4 100644 --- a/tests/unit/core/services/test_recorder.py +++ b/tests/unit/core/services/test_recorder.py @@ -521,7 +521,7 @@ async def test_reason_with_parenthetical_clause_is_not_split(self) -> None: result="message-result-no-split", reason=( "All sub-goals completed (LLM disagreed: the screenshot showed a " - "Swiggy McDonald's menu, not the running-shoes result page.)" + "Delivery McDonald's menu, not the running-shoes result page.)" ), code=TaskCode.COMPLETED, finished=self.__now.replace(second=12), @@ -533,7 +533,7 @@ async def test_reason_with_parenthetical_clause_is_not_split(self) -> None: self.assertEqual( "All sub-goals completed (LLM disagreed: the screenshot showed a " - "Swiggy McDonald's menu, not the running-shoes result page.)", + "Delivery McDonald's menu, not the running-shoes result page.)", body["summary"], ) self.assertIsNone(body["detail"]) diff --git a/tests/unit/core/swipe/test_planner.py b/tests/unit/core/swipe/test_planner.py index bda0b587..c5aa291c 100644 --- a/tests/unit/core/swipe/test_planner.py +++ b/tests/unit/core/swipe/test_planner.py @@ -142,8 +142,10 @@ def test_retries_through_keyboard_region_are_accepted(self) -> None: self.assertNotIn(AbortReason.KEYBOARD_BLOCKED, rejection_reasons) self.assertGreaterEqual(len(sequence.accepted), 1) - def test_short_travel_original_is_dispatched_cGJoU_replay(self) -> None: - """cGJoU replay: a gesture whose travel would have triggered the legacy MINIMUM_TRAVEL_VIOLATED pre-dispatch reject is now dispatched.""" + def test_short_travel_original_is_dispatched(self) -> None: + """ + A gesture whose travel would have triggered the legacy MINIMUM_TRAVEL_VIOLATED pre-dispatch reject is now dispatched. + """ policy = SwipeRetryPolicy(enabled=False, minimum_travel=300) sequence = SwipeRetryPlanner().candidates( @@ -230,7 +232,7 @@ def __frame() -> Bounds: def test_anchor_in_gesture_zone_is_confined_into_the_frame(self) -> None: """ - The Swiggy full-viewport case: a touch-down at the screen bottom edge is pulled inside the frame instead of dispatching there. + The Delivery full-viewport case: a touch-down at the screen bottom edge is pulled inside the frame instead of dispatching there. """ path = GesturePath(start_x=540, start_y=2190, end_x=540, end_y=800, duration=300) diff --git a/tests/unit/infrastructure/memory/test_sqlite.py b/tests/unit/infrastructure/memory/test_sqlite.py index 50eae743..0f274d78 100644 --- a/tests/unit/infrastructure/memory/test_sqlite.py +++ b/tests/unit/infrastructure/memory/test_sqlite.py @@ -28,7 +28,7 @@ def __action() -> Action: return Action( action_type=ActionType.TAP, - target="Swiggy app icon", + target="Delivery app icon", rationale="Open app.", confidence=1.0, ) @@ -55,7 +55,7 @@ async def test_launcher_screen_experiences_are_not_retrieved(self) -> None: provider = SQLiteMemoryProvider(database_path=Path(directory) / "memory.db") screen = self.__screen(activity="com.google.android.apps.nexuslauncher") - await provider.store_observation(screen=screen, description="Opening Swiggy.") + await provider.store_observation(screen=screen, description="Opening Delivery.") await provider.store_experience( visual_hash=screen.visual_hash, action=self.__action(), @@ -74,9 +74,9 @@ async def test_app_screen_experiences_are_retrieved(self) -> None: with tempfile.TemporaryDirectory() as directory: provider = SQLiteMemoryProvider(database_path=Path(directory) / "memory.db") - screen = self.__screen(activity="in.swiggy.android") + screen = self.__screen(activity="com.example.delivery") - await provider.store_observation(screen=screen, description="Swiggy home.") + await provider.store_observation(screen=screen, description="Delivery home.") await provider.store_experience( visual_hash=screen.visual_hash, action=self.__action(), @@ -85,7 +85,7 @@ async def test_app_screen_experiences_are_retrieved(self) -> None: knowledge = await provider.retrieve_knowledge(visual_hash=screen.visual_hash) - self.assertEqual(knowledge["description"], "Swiggy home.") + self.assertEqual(knowledge["description"], "Delivery home.") self.assertEqual(len(knowledge["previous_actions"]), 1) async def test_typed_outcome_round_trips_through_the_store(self) -> None: @@ -99,7 +99,7 @@ async def test_typed_outcome_round_trips_through_the_store(self) -> None: await provider.store_outcome( experience=Experience( - workflow="6cfc5fd2", + workflow="wf-sample", session="exec-1", screen="b" * 16, action=ActionType.TAP, @@ -118,7 +118,7 @@ async def test_typed_outcome_round_trips_through_the_store(self) -> None: rows = await cursor.fetchall() self.assertEqual(len(rows), 1) - self.assertEqual(rows[0][0], "6cfc5fd2") + self.assertEqual(rows[0][0], "wf-sample") self.assertEqual(rows[0][1], "tap") self.assertEqual(rows[0][2], 1) self.assertEqual(rows[0][3], "progress") diff --git a/tests/unit/infrastructure/storage/test_cloud.py b/tests/unit/infrastructure/storage/test_cloud.py index 264aa962..dba1f3b0 100644 --- a/tests/unit/infrastructure/storage/test_cloud.py +++ b/tests/unit/infrastructure/storage/test_cloud.py @@ -6,10 +6,14 @@ class GCSFilenameFallbackTest(unittest.TestCase): - """Pins generated filenames for direct storage callers.""" + """ + Pins generated filenames for direct storage callers. + """ def test_xmls_category_uses_xml_extension(self) -> None: - """Hierarchy XML uploads without a caller filename still land as XML.""" + """ + Hierarchy XML uploads without a caller filename still land as XML. + """ filename = GCSImageStorage._GCSImageStorage__fallback_filename( # type: ignore[attr-defined] category="xmls", @@ -20,7 +24,9 @@ def test_xmls_category_uses_xml_extension(self) -> None: self.assertTrue(filename.endswith("__com.example__MainActivity.xml")) def test_history_category_uses_text_extension(self) -> None: - """History uploads without a caller filename still land as text.""" + """ + History uploads without a caller filename still land as text. + """ filename = GCSImageStorage._GCSImageStorage__fallback_filename( # type: ignore[attr-defined] category="history", @@ -31,7 +37,9 @@ def test_history_category_uses_text_extension(self) -> None: self.assertTrue(filename.endswith("__com.example__MainActivity.txt")) def test_image_categories_default_to_png_extension(self) -> None: - """Image-bearing categories without a caller filename still land as PNG.""" + """ + Image-bearing categories without a caller filename still land as PNG. + """ for category in ("screenshot", "annotated", "traces"): with self.subTest(category=category): @@ -45,10 +53,14 @@ def test_image_categories_default_to_png_extension(self) -> None: class GCSContentTypeTest(unittest.TestCase): - """Pins the content-type resolution against the resolved filename extension.""" + """ + Pins the content-type resolution against the resolved filename extension. + """ def test_xml_filename_returns_application_xml(self) -> None: - """XML uploads carry the ``application/xml`` content-type in GCS metadata.""" + """ + XML uploads carry the ``application/xml`` content-type in GCS metadata. + """ content_type = GCSImageStorage._GCSImageStorage__content_type_for( # type: ignore[attr-defined] filename="xmls/2026-06-04/session__1/dump.xml" @@ -57,7 +69,9 @@ def test_xml_filename_returns_application_xml(self) -> None: self.assertEqual(content_type, "application/xml") def test_png_filename_returns_image_png(self) -> None: - """PNG uploads carry the ``image/png`` content-type in GCS metadata.""" + """ + PNG uploads carry the ``image/png`` content-type in GCS metadata. + """ content_type = GCSImageStorage._GCSImageStorage__content_type_for( # type: ignore[attr-defined] filename="screenshot/2026-06-04/session__1/shot.png" @@ -66,7 +80,9 @@ def test_png_filename_returns_image_png(self) -> None: self.assertEqual(content_type, "image/png") def test_unknown_extension_returns_octet_stream(self) -> None: - """Unknown extensions fall back to ``application/octet-stream`` per HTTP convention.""" + """ + Unknown extensions fall back to ``application/octet-stream`` per HTTP convention. + """ content_type = GCSImageStorage._GCSImageStorage__content_type_for( # type: ignore[attr-defined] filename="xmls/2026-06-04/session__1/dump.bin" diff --git a/tests/unit/processing/test_ios.py b/tests/unit/processing/test_ios.py index 3c76ceec..5f004d2a 100644 --- a/tests/unit/processing/test_ios.py +++ b/tests/unit/processing/test_ios.py @@ -67,7 +67,7 @@ def test_directional_swipe_filters_to_swipeable_candidates(self) -> None: xml = """ - + diff --git a/tests/unit/processing/test_kind.py b/tests/unit/processing/test_kind.py deleted file mode 100644 index 2a54ac2d..00000000 --- a/tests/unit/processing/test_kind.py +++ /dev/null @@ -1,182 +0,0 @@ -from __future__ import annotations - -import unittest -from pathlib import Path - -from fathom.constants.screen import ( - GAME_SURFACE_AREA_FLOOR, - WEBVIEW_AREA_FLOOR, - ScreenKind, -) -from fathom.processing.parsers.kind import ScreenKindClassifier - -_FULL_SCREEN_WEBVIEW_FIXTURE = ( - Path(__file__).resolve().parents[2] - / "fixtures" - / "processing" - / "kind" - / "webview_full_screen.xml" -) - - -class ScreenKindClassifierTest(unittest.TestCase): - """ - Pins :meth:`ScreenKindClassifier.classify` across native, webview, and game-surface frames. - """ - - def test_empty_xml_returns_native(self) -> None: - """ - Missing hierarchy degrades safely to NATIVE rather than mis-routing OCR. - """ - - result = ScreenKindClassifier.classify( - xml_content=None, - screen_width=2340, - screen_height=1080, - ) - - self.assertIs(result, ScreenKind.NATIVE) - - def test_zero_dimensions_returns_native(self) -> None: - """ - Zero / negative dimensions short-circuit to NATIVE; no divide-by-zero risk. - """ - - result = ScreenKindClassifier.classify( - screen_width=0, - screen_height=1080, - xml_content="", - ) - - self.assertIs(result, ScreenKind.NATIVE) - - def test_malformed_xml_returns_native(self) -> None: - """ - Parse failures degrade to NATIVE — classifier never raises into the perception layer. - """ - - result = ScreenKindClassifier.classify( - screen_width=2340, - screen_height=1080, - xml_content="<< None: - """ - A tappable button alone classifies as NATIVE. - """ - - xml = '' - - result = ScreenKindClassifier.classify( - xml_content=xml, - screen_width=2340, - screen_height=1080, - ) - - self.assertIs(result, ScreenKind.NATIVE) - - def test_appium_tag_webview_above_floor_returns_webview(self) -> None: - """ - An Appium-style WebView tag covering >= the floor area classifies as WEBVIEW. - """ - - xml = '' - - result = ScreenKindClassifier.classify( - xml_content=xml, - screen_width=2340, - screen_height=1080, - ) - - self.assertIs(result, ScreenKind.WEBVIEW) - - def test_uiautomator_class_attribute_webview_returns_webview(self) -> None: - """ - uiautomator emits class as an attribute, not a tag; classifier must match both shapes. - """ - - xml = '' - - result = ScreenKindClassifier.classify( - xml_content=xml, - screen_width=2340, - screen_height=1080, - ) - - self.assertIs(result, ScreenKind.WEBVIEW) - - def test_webview_below_floor_returns_native(self) -> None: - """ - A WebView whose area is below WEBVIEW_AREA_FLOOR must not flip the classification. - """ - - small_height = int(2340 * 1080 * (WEBVIEW_AREA_FLOOR / 2.0) / 2340) - xml = f'' - - result = ScreenKindClassifier.classify( - xml_content=xml, - screen_width=2340, - screen_height=1080, - ) - - self.assertIs(result, ScreenKind.NATIVE) - - def test_full_screen_surfaceview_returns_game_surface(self) -> None: - """ - A SurfaceView covering >= the game-surface floor area classifies as GAME_SURFACE. - """ - - xml = '' - - result = ScreenKindClassifier.classify( - xml_content=xml, - screen_width=2340, - screen_height=1080, - ) - - self.assertIs(result, ScreenKind.GAME_SURFACE) - - def test_ios_webview_tag_returns_webview(self) -> None: - """ - iOS Appium uses ``XCUIElementTypeWebView`` with x/y/width/height attributes. - """ - - xml = '' - - result = ScreenKindClassifier.classify( - xml_content=xml, - screen_width=1170, - screen_height=2532, - ) - - self.assertIs(result, ScreenKind.WEBVIEW) - - def test_game_surface_floor_above_webview_floor_short_circuits(self) -> None: - """ - Floor invariant: GAME_SURFACE_AREA_FLOOR must be no smaller than WEBVIEW_AREA_FLOOR - so a full-screen surface can never resolve as a webview. - """ - - self.assertGreaterEqual(GAME_SURFACE_AREA_FLOOR, WEBVIEW_AREA_FLOOR) - - @unittest.skipUnless( - _FULL_SCREEN_WEBVIEW_FIXTURE.exists(), - "full-screen webview hierarchy fixture not present on disk", - ) - def test_full_screen_webview_hierarchy_fixture_classifies_as_webview(self) -> None: - """ - End-to-end pin: a real captured WebView hierarchy still classifies as WEBVIEW. - """ - - xml = _FULL_SCREEN_WEBVIEW_FIXTURE.read_text() - - result = ScreenKindClassifier.classify( - xml_content=xml, - screen_width=2340, - screen_height=1080, - ) - - self.assertIs(result, ScreenKind.WEBVIEW) diff --git a/tests/unit/runtime/qualifier/test_composer.py b/tests/unit/runtime/qualifier/test_composer.py index 588818d6..000c8112 100644 --- a/tests/unit/runtime/qualifier/test_composer.py +++ b/tests/unit/runtime/qualifier/test_composer.py @@ -225,7 +225,9 @@ async def test_post_construction_compose_failure_cleans_dedicated_llm(self) -> N dedicated_llm.cleanup.assert_awaited_once_with() async def test_post_construction_compose_cancellation_cleans_dedicated_llm(self) -> None: - """Regression: CancelledError is BaseException-derived in Python 3.8+, so catching only Exception would leak the dedicated qualifier LLM if a future refactor introduces an await inside compose()'s try block and the activity is cancelled at that point.""" + """ + Regression: CancelledError is BaseException-derived in Python 3.8+, so catching only Exception would leak the dedicated qualifier LLM if a future refactor introduces an await inside compose()'s try block and the activity is cancelled at that point. + """ dedicated_llm = MagicMock(spec=LLMPort) dedicated_llm.cleanup = AsyncMock() diff --git a/tests/unit/runtime/temporal/test_activities.py b/tests/unit/runtime/temporal/test_activities.py index d8f1d802..8983c607 100644 --- a/tests/unit/runtime/temporal/test_activities.py +++ b/tests/unit/runtime/temporal/test_activities.py @@ -25,7 +25,7 @@ async def test_execute_intent_cancels_runner_before_cleanup(self) -> None: runner = Mock() runner.device = Mock() - runner.device.get_current_package = AsyncMock(return_value="in.swiggy.android") + runner.device.get_current_package = AsyncMock(return_value="com.example.delivery") runner.run_intent = AsyncMock(side_effect=RuntimeError("boom")) runner.cancel = Mock(side_effect=lambda: cleanup_order.append("cancel")) runner.cleanup = AsyncMock(side_effect=lambda: cleanup_order.append("cleanup")) diff --git a/tests/unit/runtime/temporal/test_activities_partial_build.py b/tests/unit/runtime/temporal/test_activities_partial_build.py index 3b306d88..2198e729 100644 --- a/tests/unit/runtime/temporal/test_activities_partial_build.py +++ b/tests/unit/runtime/temporal/test_activities_partial_build.py @@ -161,10 +161,8 @@ def __build(self) -> object: class FathomActivitiesPartialBuildTest(unittest.IsolatedAsyncioTestCase): """ - Regression: if any step after partial adapters are created fails during - __build_runner, every registered adapter must be drained — not just the - LLMs. Earlier versions only tracked LLMs and leaked telemetry / storage - / device / perception when the build failed downstream. + If any step after partial adapters are created fails during __build_runner, every registered + adapter must be drained — telemetry, storage, device, and perception, not just the LLMs. """ async def test_partial_build_drains_every_registered_adapter(self) -> None: @@ -285,7 +283,9 @@ async def test_partial_build_skips_adapters_without_cleanup_or_close(self) -> No activities = FathomActivities(settings=FathomSettings()) class _Inert: - """Adapter with no teardown methods at all.""" + """ + Adapter with no teardown methods at all. + """ # Should not raise even with no teardown methods present. await activities._FathomActivities__drain_partial_resources( # type: ignore[attr-defined] diff --git a/tests/unit/runtime/test_adapters.py b/tests/unit/runtime/test_adapters.py index 1afc7e01..87063ed3 100644 --- a/tests/unit/runtime/test_adapters.py +++ b/tests/unit/runtime/test_adapters.py @@ -189,7 +189,9 @@ def test_ensemble_empty_when_disabled(self) -> None: self.assertEqual(assembly.ensemble().members, ()) def test_ensemble_builds_configured_members(self) -> None: - """Enabled ensemble with a member list yields the matching localizer instances.""" + """ + Enabled ensemble with a member list yields the matching localizer instances. + """ assembly = self.__assemble( ensemble_localizer_enabled=True, diff --git a/tests/unit/runtime/test_builder.py b/tests/unit/runtime/test_builder.py index bc3fa1be..e33b285c 100644 --- a/tests/unit/runtime/test_builder.py +++ b/tests/unit/runtime/test_builder.py @@ -145,7 +145,7 @@ class FathomBuilderWithAssemblyTest(unittest.TestCase): QualifierConfiguration.inference.{model, timeout, max_retries, ...} actually take effect. Without it, the builder falls back to running the qualifier on the planner LLM and ignores the inference block — the documented prior - behavior that Enricher silently inherited. + behavior that host callers silently inherited. """ @staticmethod diff --git a/tests/unit/schemas/conversation/test_wire.py b/tests/unit/schemas/conversation/test_wire.py index 9c67af5a..d3f70cde 100644 --- a/tests/unit/schemas/conversation/test_wire.py +++ b/tests/unit/schemas/conversation/test_wire.py @@ -306,7 +306,7 @@ def test_intent_only(self) -> None: """ projected = WireRequestBody.project( - body={"intent": "search for burgers", "starting_package": "com.swiggy"} + body={"intent": "search for burgers", "starting_package": "com.delivery"} ) assert projected is not None diff --git a/tests/unit/schemas/test_artifact.py b/tests/unit/schemas/test_artifact.py index 4d9f60fe..de544fb7 100644 --- a/tests/unit/schemas/test_artifact.py +++ b/tests/unit/schemas/test_artifact.py @@ -97,7 +97,7 @@ def test_ocr_raw_payload_kind_locked_to_ocr_raw(self) -> None: Raw OCR JSON payloads route through the OCR raw artifact kind. """ - payload = OcrRawPayload(content='{"text": "Swiggy"}') + payload = OcrRawPayload(content='{"text": "Delivery"}') self.assertEqual(payload.kind, ArtifactKind.OCR_RAW) diff --git a/tests/unit/schemas/test_artifacts.py b/tests/unit/schemas/test_artifacts.py index 888d0c91..fe48091a 100644 --- a/tests/unit/schemas/test_artifacts.py +++ b/tests/unit/schemas/test_artifacts.py @@ -93,7 +93,7 @@ def test_storage_backend_rejects_unknown_value(self) -> None: """ with self.assertRaises(ValidationError): - ScreenArtifact(uri="/tmp/before.png", storage_backend="cloudinary") # type: ignore[arg-type] + ScreenArtifact(uri="/tmp/before.png", storage_backend="unknown_backend") # type: ignore[arg-type] def test_artifact_is_frozen(self) -> None: """ diff --git a/tests/unit/schemas/test_capabilities.py b/tests/unit/schemas/test_capabilities.py index a76276bb..80251191 100644 --- a/tests/unit/schemas/test_capabilities.py +++ b/tests/unit/schemas/test_capabilities.py @@ -9,24 +9,32 @@ class HITLCapabilityTest(unittest.TestCase): - """Pins the HITLCapability schema contract.""" + """ + Pins the HITLCapability schema contract. + """ def test_enabled_true_is_readable(self) -> None: - """enabled is set and readable.""" + """ + enabled is set and readable. + """ capability = HITLCapability(enabled=True) self.assertTrue(capability.enabled) def test_enabled_false_is_readable(self) -> None: - """Autonomous runtime maps to enabled=False.""" + """ + Autonomous runtime maps to enabled=False. + """ capability = HITLCapability(enabled=False) self.assertFalse(capability.enabled) def test_is_immutable(self) -> None: - """Frozen model prevents post-construction mutation.""" + """ + Frozen model prevents post-construction mutation. + """ capability = HITLCapability(enabled=False) @@ -34,24 +42,32 @@ def test_is_immutable(self) -> None: capability.enabled = True # type: ignore[misc] def test_requires_enabled(self) -> None: - """enabled has no default and must be supplied explicitly.""" + """ + enabled has no default and must be supplied explicitly. + """ with pytest.raises(ValidationError): HITLCapability() # type: ignore[call-arg] class RuntimeCapabilitiesTest(unittest.TestCase): - """Pins the RuntimeCapabilities schema contract.""" + """ + Pins the RuntimeCapabilities schema contract. + """ def test_exposes_nested_hitl_flag(self) -> None: - """Hitl capability is reachable via the nested field.""" + """ + Hitl capability is reachable via the nested field. + """ capabilities = RuntimeCapabilities(hitl=HITLCapability(enabled=True)) self.assertTrue(capabilities.hitl.enabled) def test_is_immutable(self) -> None: - """Frozen model prevents field reassignment.""" + """ + Frozen model prevents field reassignment. + """ capabilities = RuntimeCapabilities(hitl=HITLCapability(enabled=False)) @@ -59,13 +75,17 @@ def test_is_immutable(self) -> None: capabilities.hitl = HITLCapability(enabled=True) # type: ignore[misc] def test_requires_hitl(self) -> None: - """hitl has no default and must be supplied explicitly.""" + """ + hitl has no default and must be supplied explicitly. + """ with pytest.raises(ValidationError): RuntimeCapabilities() # type: ignore[call-arg] def test_equality_by_value(self) -> None: - """Two capability records with the same nested flag compare equal.""" + """ + Two capability records with the same nested flag compare equal. + """ self.assertEqual( RuntimeCapabilities(hitl=HITLCapability(enabled=True)), diff --git a/tests/unit/schemas/test_run.py b/tests/unit/schemas/test_run.py index a8b7b74a..98f90606 100644 --- a/tests/unit/schemas/test_run.py +++ b/tests/unit/schemas/test_run.py @@ -47,7 +47,7 @@ def test_intent_run_request_uses_canonical_nested_sections(self) -> None: max_steps=25, use_xml=True, intent="Open Airbnb", - package_name="com.airbnb.android", + package_name="com.example.airbnb", ), runtime=RuntimeConfiguration( interactive=True, @@ -69,7 +69,7 @@ def test_intent_run_request_uses_canonical_nested_sections(self) -> None: "remote": { "session_id": "session-123", "execution_id": "execution-123", - "provider_url": "https://core.drizz.io/v1", + "provider_url": "https://api.example.com/v1", }, }, ) @@ -171,7 +171,7 @@ def test_exploration_run_request_defaults_to_exploration_mode(self) -> None: "remote": { "session_id": "session-123", "execution_id": "execution-123", - "provider_url": "https://core.drizz.io/v1", + "provider_url": "https://api.example.com/v1", }, } ) diff --git a/tests/unit/schemas/test_scroll_adaptive_back_compat.py b/tests/unit/schemas/test_scroll_adaptive_back_compat.py index 26e1940d..23095dc2 100644 --- a/tests/unit/schemas/test_scroll_adaptive_back_compat.py +++ b/tests/unit/schemas/test_scroll_adaptive_back_compat.py @@ -11,9 +11,9 @@ class TestAdaptivePolicyBackwardCompatibility(unittest.TestCase): Pins that the deprecated AdaptivePolicy shim remains importable and inert. """ - def test_enricher_legacy_construction_succeeds(self) -> None: + def test_legacy_host_construction_succeeds(self) -> None: """ - Exact legacy invocation from the enricher healing bridge must not raise. + Exact legacy invocation from an older host caller must not raise. """ policy = ScrollInteractionPolicy( diff --git a/tests/unit/schemas/test_steps.py b/tests/unit/schemas/test_steps.py index e824b803..2d00530f 100644 --- a/tests/unit/schemas/test_steps.py +++ b/tests/unit/schemas/test_steps.py @@ -13,11 +13,15 @@ class TestStepResultArtifacts(unittest.TestCase): - """Unit tests covering the optional `artifacts` field on `StepResult`.""" + """ + Unit tests covering the optional `artifacts` field on `StepResult`. + """ @staticmethod def __build_step(*, step_number: int = 0) -> Step: - """Build a minimal `Step` instance suitable for `StepResult` construction.""" + """ + Build a minimal `Step` instance suitable for `StepResult` construction. + """ return Step( action=Action( @@ -30,7 +34,9 @@ def __build_step(*, step_number: int = 0) -> Step: ) def test_step_result_defaults_artifacts_to_none(self) -> None: - """Existing call sites that omit `artifacts` continue to work.""" + """ + Existing call sites that omit `artifacts` continue to work. + """ step_result = StepResult( success=True, @@ -44,7 +50,9 @@ def test_step_result_defaults_artifacts_to_none(self) -> None: self.assertIsNone(step_result.artifacts) def test_step_result_accepts_screen_before_and_after(self) -> None: - """Artifacts surface as a nested `screen.before` / `screen.after` payload.""" + """ + Artifacts surface as a nested `screen.before` / `screen.after` payload. + """ artifacts = StepArtifacts( screen=ScreenArtifactBundle( @@ -84,7 +92,9 @@ def test_step_result_accepts_screen_before_and_after(self) -> None: self.assertEqual(screen.after.uri, "/tmp/after.png") def test_step_result_serializes_artifacts_namespaced(self) -> None: - """JSON serialization preserves the nested artifact namespace consumed by telemetry adapters.""" + """ + JSON serialization preserves the nested artifact namespace consumed by telemetry adapters. + """ step_result = StepResult( duration=80, @@ -108,7 +118,9 @@ def test_step_result_serializes_artifacts_namespaced(self) -> None: self.assertIsNone(payload["artifacts"]["screen"]["after"]) def test_step_result_to_record_carries_artifacts_when_present(self) -> None: - """`to_record()` persists artifacts when they are present.""" + """ + `to_record()` persists artifacts when they are present. + """ without_artifacts = StepResult( duration=50, @@ -136,7 +148,9 @@ def test_step_result_to_record_carries_artifacts_when_present(self) -> None: self.assertEqual(with_artifacts.to_record().artifacts, with_artifacts.artifacts) def test_step_result_to_record_carries_goal_context(self) -> None: - """`to_record()` persists compact sub-goal context when supplied.""" + """ + `to_record()` persists compact sub-goal context when supplied. + """ goal = StepGoal(index=2, description="Check rating", directive="validate") record = StepResult( @@ -156,11 +170,15 @@ def test_step_result_to_record_carries_goal_context(self) -> None: class TestStepResultCapture(unittest.TestCase): - """Covers persistence of STORE capture metadata onto the step record and history.""" + """ + Covers persistence of STORE capture metadata onto the step record and history. + """ @staticmethod def __step(*, action_type: ActionType) -> Step: - """Build a minimal Step for the given action type.""" + """ + Build a minimal Step for the given action type. + """ return Step( action=Action(action_type=action_type, target="element", rationale="r"), @@ -169,7 +187,9 @@ def __step(*, action_type: ActionType) -> Step: ) def __result(self, *, action_type: ActionType, capture: object) -> StepResult: - """Build a step result carrying the given capture.""" + """ + Build a step result carrying the given capture. + """ return StepResult( step=self.__step(action_type=action_type), @@ -182,7 +202,9 @@ def __result(self, *, action_type: ActionType, capture: object) -> StepResult: ) def test_store_success_record_has_capture(self) -> None: - """A successful STORE persists its capture (value, success) onto the record.""" + """ + A successful STORE persists its capture (value, success) onto the record. + """ record = self.__result( action_type=ActionType.STORE, @@ -195,7 +217,9 @@ def test_store_success_record_has_capture(self) -> None: self.assertEqual(record.capture.value, "₹499") def test_store_failed_record_has_capture(self) -> None: - """A failed STORE persists its failed capture (success=False, reason) onto the record.""" + """ + A failed STORE persists its failed capture (success=False, reason) onto the record. + """ record = self.__result( action_type=ActionType.STORE, @@ -208,14 +232,18 @@ def test_store_failed_record_has_capture(self) -> None: self.assertEqual(record.capture.reason, "no element") def test_non_store_record_has_no_capture(self) -> None: - """A non-STORE step persists no capture.""" + """ + A non-STORE step persists no capture. + """ record = self.__result(action_type=ActionType.TAP, capture=None).to_record() self.assertIsNone(record.capture) def test_old_history_without_capture_still_loads(self) -> None: - """A history record predating the capture field loads with capture defaulting to None.""" + """ + A history record predating the capture field loads with capture defaulting to None. + """ history = StepHistory.model_validate( { @@ -236,7 +264,9 @@ def test_old_history_without_capture_still_loads(self) -> None: self.assertIsNone(history.history[0].capture) def test_history_export_includes_capture(self) -> None: - """The serialized record exposes the capture payload for downstream script generation.""" + """ + The serialized record exposes the capture payload for downstream script generation. + """ payload = ( self.__result( @@ -252,7 +282,9 @@ def test_history_export_includes_capture(self) -> None: self.assertEqual(payload["capture"]["value"], "₹499") def test_store_record_carries_capture_request(self) -> None: - """A STORE step persists the request (name/subject/value) that drives script generation.""" + """ + A STORE step persists the request (name/subject/value) that drives script generation. + """ action = Action( action_type=ActionType.STORE, @@ -278,7 +310,9 @@ def test_store_record_carries_capture_request(self) -> None: self.assertEqual(record.capture_request.value, "₹499") def test_non_store_record_has_no_capture_request(self) -> None: - """A non-STORE step persists no capture request.""" + """ + A non-STORE step persists no capture request. + """ record = self.__result(action_type=ActionType.TAP, capture=None).to_record() diff --git a/tests/unit/schemas/test_subgoal.py b/tests/unit/schemas/test_subgoal.py index 5aa5a3bb..f0d13477 100644 --- a/tests/unit/schemas/test_subgoal.py +++ b/tests/unit/schemas/test_subgoal.py @@ -59,7 +59,7 @@ class TestSubGoalDefinition: @staticmethod def __goal() -> SubGoal: - return SubGoal(index=0, objective="Open Swiggy app", success=SuccessFixtures.observed()) + return SubGoal(index=0, objective="Open Delivery app", success=SuccessFixtures.observed()) def test_goal_is_immutable(self) -> None: """ @@ -76,7 +76,7 @@ def test_goal_state_exposes_definition(self) -> None: state = GoalState(goal=self.__goal()) assert state.index == 0 - assert state.objective == "Open Swiggy app" + assert state.objective == "Open Delivery app" assert state.progress.status == SubGoalStatus.PENDING def test_lifecycle_transitions_apply_to_progress(self) -> None: diff --git a/tests/unit/schemas/test_target.py b/tests/unit/schemas/test_target.py index dd55391e..503d215e 100644 --- a/tests/unit/schemas/test_target.py +++ b/tests/unit/schemas/test_target.py @@ -17,10 +17,10 @@ def test_requested_binds_to_package(self) -> None: An explicitly requested package produces bound authority. """ - authority = TargetAuthority.requested(package="com.meesho.supply") + authority = TargetAuthority.requested(package="com.example.shop") self.assertTrue(authority.bound) - self.assertEqual(authority.package, "com.meesho.supply") + self.assertEqual(authority.package, "com.example.shop") def test_unbound_has_no_package(self) -> None: """ @@ -40,7 +40,7 @@ def test_is_immutable(self) -> None: authority = TargetAuthority.unbound() with self.assertRaises(ValidationError): - authority.package = "com.meesho.supply" + authority.package = "com.example.shop" def test_rejects_unknown_field(self) -> None: """ diff --git a/tests/unit/schemas/test_tools.py b/tests/unit/schemas/test_tools.py index beab6ffe..879d0129 100644 --- a/tests/unit/schemas/test_tools.py +++ b/tests/unit/schemas/test_tools.py @@ -10,10 +10,14 @@ class AllowedToolsTest(unittest.TestCase): - """Pins the AllowedTools schema contract.""" + """ + Pins the AllowedTools schema contract. + """ def test_contains_returns_true_for_member(self) -> None: - """contains() reports membership of declared tool names.""" + """ + contains() reports membership of declared tool names. + """ tools = AllowedTools(names=frozenset({ToolName.EXECUTE_UI, ToolName.ASK_USER})) @@ -21,21 +25,27 @@ def test_contains_returns_true_for_member(self) -> None: self.assertTrue(tools.contains(name=ToolName.EXECUTE_UI)) def test_contains_returns_false_for_non_member(self) -> None: - """contains() reports absence of undeclared tool names.""" + """ + contains() reports absence of undeclared tool names. + """ tools = AllowedTools(names=frozenset({ToolName.EXECUTE_UI})) self.assertFalse(tools.contains(name=ToolName.ASK_USER)) def test_supports_empty_set(self) -> None: - """An empty allowed set is a valid (degenerate) configuration.""" + """ + An empty allowed set is a valid (degenerate) configuration. + """ tools = AllowedTools(names=frozenset()) self.assertFalse(tools.contains(name=ToolName.ASK_USER)) def test_is_immutable(self) -> None: - """Frozen model prevents reassignment of the names field.""" + """ + Frozen model prevents reassignment of the names field. + """ tools = AllowedTools(names=frozenset({ToolName.EXECUTE_UI})) diff --git a/tests/unit/strategies/graph/intent/nodes/test_analyze.py b/tests/unit/strategies/graph/intent/nodes/test_analyze.py index 89a27f85..0323da35 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_analyze.py +++ b/tests/unit/strategies/graph/intent/nodes/test_analyze.py @@ -365,11 +365,11 @@ async def test_final_active_subgoal_completion_routes_pending_final_commit(self) """ agent_state = AgentState( - intent="change the address to salaryse office", + intent="change the address to finance office", capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=False)), ) agent_state.set_sub_goals( - [SubGoalFixtures.make(index=0, description="Confirm SalarySe address")] + [SubGoalFixtures.make(index=0, description="Confirm Finance address")] ) planner = Mock() planner.plan_step = AsyncMock( @@ -434,13 +434,13 @@ async def test_deferred_completion_clears_planned_step_and_forces_retry(self) -> """ agent_state = AgentState( - intent="change the address to salaryse office", + intent="change the address to finance office", capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=False)), ) agent_state.set_sub_goals( [ SubGoalFixtures.make(index=0, description="Tap address selector"), - SubGoalFixtures.make(index=1, description="Confirm SalarySe address"), + SubGoalFixtures.make(index=1, description="Confirm Finance address"), ] ) planner = Mock() @@ -513,7 +513,7 @@ async def test_terminal_completion_does_not_stamp_verify_mode(self) -> None: """ agent_state = AgentState( - intent="change the address to salaryse office", + intent="change the address to finance office", capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=False)), ) for reason in TERMINAL_COMPLETION_REASONS: diff --git a/tests/unit/strategies/graph/intent/nodes/test_execute.py b/tests/unit/strategies/graph/intent/nodes/test_execute.py index 6782857a..1d34d414 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_execute.py +++ b/tests/unit/strategies/graph/intent/nodes/test_execute.py @@ -64,13 +64,17 @@ async def test_cancellation_marks_complete(self) -> None: @staticmethod def __capture() -> ScreenCapture: - """Build a minimal screen capture for ExecutionContext.""" + """ + Build a minimal screen capture for ExecutionContext. + """ return ScreenCapture(width=100, height=200, activity="app", image=b"", timestamp=1) @staticmethod def __ask_user_execution_context() -> ExecutionContext: - """Build an ExecutionContext carrying an ASK_USER step.""" + """ + Build an ExecutionContext carrying an ASK_USER step. + """ action = Action( action_type=ActionType.ASK_USER, diff --git a/tests/unit/strategies/graph/intent/nodes/test_ground.py b/tests/unit/strategies/graph/intent/nodes/test_ground.py index ba77eb0d..a5cc3880 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_ground.py +++ b/tests/unit/strategies/graph/intent/nodes/test_ground.py @@ -158,7 +158,7 @@ def __capture(cls) -> ScreenCapture: @staticmethod def __observation() -> ScreenObservation: """ - OCR-only observation matching the launcher Swiggy label. + OCR-only observation matching the launcher Delivery label. """ return ScreenObservation( @@ -172,7 +172,7 @@ def __observation() -> ScreenObservation: elements=( PerceivedElement( label_id="13", - text="Swiggy", + text="Delivery", parent=None, tappable=False, confidence=0.96, @@ -248,7 +248,7 @@ async def test_ocr_elements_become_manifest_when_xml_is_absent(self) -> None: result: Any = await node(state={}) # type: ignore[arg-type] elements = result[IntentStateKey.ELEMENTS] - self.assertEqual(elements["1"]["text"], "Swiggy") + self.assertEqual(elements["1"]["text"], "Delivery") self.assertEqual(elements["1"]["source"], "ocr") self.assertEqual(elements["1"]["bounds"], "[284,383][392,414]") self.assertIsNotNone(result[CommonStateKey.CAPTURE].annotated_image) diff --git a/tests/unit/strategies/graph/intent/nodes/test_observe.py b/tests/unit/strategies/graph/intent/nodes/test_observe.py index faf6bd71..0241b833 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_observe.py +++ b/tests/unit/strategies/graph/intent/nodes/test_observe.py @@ -123,8 +123,8 @@ def test_non_gesture_success_keeps_execution_result(self) -> None: def test_control_command_success_ignores_screen_change(self) -> None: """ - Run-83752b18 fix: a successful ASK_USER (delivered + answered) succeeds even though the - control operation leaves the screen unchanged — screen change is not its postcondition. + A successful ASK_USER (delivered + answered) succeeds even though the control operation + leaves the screen unchanged — screen change is not its postcondition. """ effect = ActionEffect( diff --git a/tests/unit/strategies/graph/intent/nodes/test_persistence.py b/tests/unit/strategies/graph/intent/nodes/test_persistence.py index 5a4a2e73..f504ecd1 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_persistence.py +++ b/tests/unit/strategies/graph/intent/nodes/test_persistence.py @@ -49,7 +49,7 @@ def test_persists_when_launcher_transitions_to_app(self) -> None: self.assertFalse( GraphStatePersistence.should_skip_launcher( execution_activity="com.android.launcher3/Activity", - observed_activity="bundl.swiggy.production/Home", + observed_activity="com.example.delivery/Home", ), ) @@ -60,7 +60,7 @@ def test_persists_when_execution_was_not_on_launcher(self) -> None: self.assertFalse( GraphStatePersistence.should_skip_launcher( - execution_activity="bundl.swiggy.production/Home", - observed_activity="bundl.swiggy.production/Search", + execution_activity="com.example.delivery/Home", + observed_activity="com.example.delivery/Search", ), ) diff --git a/tests/unit/strategies/graph/intent/nodes/test_persistence_roundtrip.py b/tests/unit/strategies/graph/intent/nodes/test_persistence_roundtrip.py index c1988e8b..0fe59683 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_persistence_roundtrip.py +++ b/tests/unit/strategies/graph/intent/nodes/test_persistence_roundtrip.py @@ -219,8 +219,8 @@ def test_enqueue_history_passes_active_goal_context(self) -> None: pre_hash="pre", post_hash="post", ), - current_activity="com.meesho.supply", - execution_activity="com.meesho.supply", + current_activity="com.example.shop", + execution_activity="com.example.shop", ) goal = context.history.enqueue_save_step.call_args.kwargs["goal"] # type: ignore[attr-defined] diff --git a/tests/unit/strategies/graph/intent/nodes/test_record.py b/tests/unit/strategies/graph/intent/nodes/test_record.py index 99248bd0..ccde1a93 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_record.py +++ b/tests/unit/strategies/graph/intent/nodes/test_record.py @@ -158,7 +158,7 @@ async def test_plan_complete_with_active_final_subgoal_routes_pending_verify(sel agent_state = AgentState(intent="change address", capabilities=self.__caps()) agent_state.set_sub_goals( - [SubGoalFixtures.make(index=0, description="Confirm SalarySe address")] + [SubGoalFixtures.make(index=0, description="Confirm Finance address")] ) agent_state.record_complete_deferral() agent_state.record_verify_rejection( @@ -192,9 +192,9 @@ async def test_plan_complete_with_active_final_subgoal_routes_pending_verify(sel self.assertEqual(agent_state.consecutive_complete_deferrals, 0) provider.completion.evaluate.assert_not_called() - async def test_hsr_final_confirmation_replay_routes_pending_verify(self) -> None: + async def test_final_confirmation_replay_routes_pending_verify(self) -> None: """ - HSR prod replay: after tapping the final confirmation, RECORD must route to pending final VERIFY without committing the final sub-goal. + After tapping the final confirmation, RECORD must route to pending final VERIFY without committing the final sub-goal. """ agent_state = AgentState( @@ -226,7 +226,7 @@ async def test_hsr_final_confirmation_replay_routes_pending_verify(self) -> None CommonStateKey.STEP_RESULT: self.__step_result(), CommonStateKey.SCREEN_STATE: self.__screen(), CommonStateKey.IS_NEW_SCREEN: True, - IntentStateKey.POST_ACTIVITY: "in.swiggy.android", + IntentStateKey.POST_ACTIVITY: "com.example.delivery", IntentStateKey.PLAN: PlanResult( is_complete=True, reason="HSR Layout is selected after tapping Yes, continue with this location", @@ -285,7 +285,7 @@ async def test_plan_complete_without_active_subgoal_preserves_legacy_completion( agent_state = AgentState(intent="change address", capabilities=self.__caps()) agent_state.set_sub_goals( - [SubGoalFixtures.make(index=0, description="Confirm SalarySe address")] + [SubGoalFixtures.make(index=0, description="Confirm Finance address")] ) agent_state.advance_current_sub_goal() agent_state.record_complete_deferral() diff --git a/tests/unit/strategies/graph/intent/nodes/test_verify.py b/tests/unit/strategies/graph/intent/nodes/test_verify.py index 8ea380fb..7bf477b3 100644 --- a/tests/unit/strategies/graph/intent/nodes/test_verify.py +++ b/tests/unit/strategies/graph/intent/nodes/test_verify.py @@ -167,14 +167,14 @@ def _agent_state(self) -> AgentState: def _final_agent_state(self) -> AgentState: state = AgentState( - intent="change the address to salaryse office", + intent="change the address to finance office", capabilities=RuntimeCapabilities(hitl=HITLCapability(enabled=False)), ) state.update_screen(screen=self._screen()) state.set_sub_goals( [ SubGoalFixtures.make(index=0, description="Tap address selector"), - SubGoalFixtures.make(index=1, description="Confirm SalarySe office address"), + SubGoalFixtures.make(index=1, description="Confirm Finance office address"), ] ) state.advance_current_sub_goal() @@ -282,7 +282,7 @@ async def test_pending_final_commit_uses_full_intent_prompt_and_commits_on_accep ) -> None: provider = _Provider( agent_state=self._final_agent_state(), - llm_content=self._complete_with_assertion(reason="SalarySe office is selected"), + llm_content=self._complete_with_assertion(reason="Finance office is selected"), ) node = VerifyNode(provider=provider) # type: ignore[arg-type] diff --git a/tests/unit/strategies/graph/intent/test_builder.py b/tests/unit/strategies/graph/intent/test_builder.py index 0b833c3c..a92eb65b 100644 --- a/tests/unit/strategies/graph/intent/test_builder.py +++ b/tests/unit/strategies/graph/intent/test_builder.py @@ -245,18 +245,24 @@ def test_terminal_completion_after_analyze_routes_to_end(self) -> None: class TestRouteAfterExecute(unittest.TestCase): - """Pins routing decisions for the new conditional edge after EXECUTE.""" + """ + Pins routing decisions for the new conditional edge after EXECUTE. + """ @staticmethod def __builder(*, is_cancelled: bool = False) -> IntentGraphBuilder: - """Build a routing-only IntentGraphBuilder bound to a minimal context.""" + """ + Build a routing-only IntentGraphBuilder bound to a minimal context. + """ return IntentGraphBuilder( context=SimpleNamespace(is_cancelled=is_cancelled), # type: ignore[arg-type] ) def test_cancellation_routes_to_end(self) -> None: - """A cancelled context overrides any other state and routes to END.""" + """ + A cancelled context overrides any other state and routes to END. + """ route = self.__builder(is_cancelled=True)._IntentGraphBuilder__route_after_execute( # type: ignore[attr-defined] {IntentStateKey.SHOULD_RETRY: True}, @@ -265,7 +271,9 @@ def test_cancellation_routes_to_end(self) -> None: self.assertEqual(route, NodeName.END) def test_terminal_completion_routes_to_end(self) -> None: - """A terminal completion reason routes to END.""" + """ + A terminal completion reason routes to END. + """ for reason in TERMINAL_COMPLETION_REASONS: with self.subTest(reason=reason): @@ -278,7 +286,9 @@ def test_terminal_completion_routes_to_end(self) -> None: self.assertEqual(route, NodeName.END) def test_non_terminal_completion_routes_to_verify(self) -> None: - """A non-terminal completion (e.g. success) routes to VERIFY.""" + """ + A non-terminal completion (e.g. success) routes to VERIFY. + """ route = self.__builder()._IntentGraphBuilder__route_after_execute( # type: ignore[attr-defined] { @@ -290,7 +300,9 @@ def test_non_terminal_completion_routes_to_verify(self) -> None: self.assertEqual(route, NodeName.VERIFY) def test_should_retry_routes_to_ground(self) -> None: - """SHOULD_RETRY from EXECUTE (HITL unavailable) routes back to GROUND.""" + """ + SHOULD_RETRY from EXECUTE (HITL unavailable) routes back to GROUND. + """ route = self.__builder()._IntentGraphBuilder__route_after_execute( # type: ignore[attr-defined] {IntentStateKey.SHOULD_RETRY: True}, @@ -299,7 +311,9 @@ def test_should_retry_routes_to_ground(self) -> None: self.assertEqual(route, NodeName.GROUND) def test_default_path_routes_to_observe(self) -> None: - """Successful execution with no termination/retry signal routes to OBSERVE.""" + """ + Successful execution with no termination/retry signal routes to OBSERVE. + """ route = self.__builder()._IntentGraphBuilder__route_after_execute( # type: ignore[attr-defined] {}, diff --git a/tests/unit/strategies/graph/intent/test_verification.py b/tests/unit/strategies/graph/intent/test_verification.py index 8ecd544d..5a76f24b 100644 --- a/tests/unit/strategies/graph/intent/test_verification.py +++ b/tests/unit/strategies/graph/intent/test_verification.py @@ -39,7 +39,7 @@ def test_producer_uses_sub_goal_mode_for_non_final_active_sub_goal(self) -> None agent_state.set_sub_goals( [ SubGoalFixtures.make(index=0, description="Open address selector"), - SubGoalFixtures.make(index=1, description="Confirm SalarySe address"), + SubGoalFixtures.make(index=1, description="Confirm Finance address"), ] ) @@ -54,7 +54,7 @@ def test_producer_uses_pending_final_commit_for_active_final_sub_goal(self) -> N agent_state = AgentState(intent="change address", capabilities=self.__caps()) agent_state.set_sub_goals( - [SubGoalFixtures.make(index=0, description="Confirm SalarySe address")] + [SubGoalFixtures.make(index=0, description="Confirm Finance address")] ) mode = self.__policy.mode_for_producer(agent_state=agent_state) @@ -68,7 +68,7 @@ def test_producer_uses_full_intent_after_all_sub_goals_complete(self) -> None: agent_state = AgentState(intent="change address", capabilities=self.__caps()) agent_state.set_sub_goals( - [SubGoalFixtures.make(index=0, description="Confirm SalarySe address")] + [SubGoalFixtures.make(index=0, description="Confirm Finance address")] ) agent_state.advance_current_sub_goal() @@ -99,7 +99,7 @@ def test_graph_state_without_mode_uses_cursor_inference(self) -> None: agent_state.set_sub_goals( [ SubGoalFixtures.make(index=0, description="Open address selector"), - SubGoalFixtures.make(index=1, description="Confirm SalarySe address"), + SubGoalFixtures.make(index=1, description="Confirm Finance address"), ] ) @@ -114,7 +114,7 @@ def test_graph_state_without_mode_uses_full_intent_for_active_final_subgoal(self agent_state = AgentState(intent="change address", capabilities=self.__caps()) agent_state.set_sub_goals( - [SubGoalFixtures.make(index=0, description="Confirm SalarySe address")] + [SubGoalFixtures.make(index=0, description="Confirm Finance address")] ) mode = self.__policy.mode_for_verify(state={}, agent_state=agent_state) diff --git a/tests/unit/strategies/intent/test_cancellation.py b/tests/unit/strategies/intent/test_cancellation.py index 2f6679ef..d7c33e91 100644 --- a/tests/unit/strategies/intent/test_cancellation.py +++ b/tests/unit/strategies/intent/test_cancellation.py @@ -156,7 +156,7 @@ async def test_completed_outcome_tags_telemetry_event(self) -> None: await self.__invoke_emit( strategy=strategy, run_outcome=RunOutcome.COMPLETED, - script_data="open swiggy\nsearch biryani", + script_data="open delivery\nsearch biryani", ) call = telemetry.info.call_args diff --git a/tests/unit/strategies/intent/test_checkpoint_allowlist.py b/tests/unit/strategies/intent/test_checkpoint_allowlist.py index 5fdecdf6..80b2e4ee 100644 --- a/tests/unit/strategies/intent/test_checkpoint_allowlist.py +++ b/tests/unit/strategies/intent/test_checkpoint_allowlist.py @@ -85,7 +85,9 @@ def test_allowlist_covers_intent_graph_state_closure(self) -> None: ) def test_msgpack_allowlist_matches_json_allowlist(self) -> None: - """The msgpack and json allow-lists must stay in sync.""" + """ + The msgpack and json allow-lists must stay in sync. + """ self.assertEqual( CHECKPOINT_ALLOWED_MSGPACK_MODULES, diff --git a/tests/unit/strategies/intent/test_intent.py b/tests/unit/strategies/intent/test_intent.py index b379555c..01e98a3f 100644 --- a/tests/unit/strategies/intent/test_intent.py +++ b/tests/unit/strategies/intent/test_intent.py @@ -175,12 +175,12 @@ async def test_script_generated_emits_with_non_empty_content(self) -> None: """ strategy, telemetry = self.__strategy_with_stubbed_context(step_count=5) - await self.__invoke_emit(strategy=strategy, script_data="open swiggy\nsearch biryani") + await self.__invoke_emit(strategy=strategy, script_data="open delivery\nsearch biryani") telemetry.info.assert_awaited_once() call = telemetry.info.call_args - self.assertEqual(call.args[0], "open swiggy\nsearch biryani") + self.assertEqual(call.args[0], "open delivery\nsearch biryani") self.assertEqual(call.kwargs["type"], FathomEvent.SCRIPT_GENERATED) self.assertEqual(call.kwargs["step"], 5) self.assertFalse(call.kwargs["is_empty"]) diff --git a/tests/unit/strategies/intent/test_nodes.py b/tests/unit/strategies/intent/test_nodes.py index 758d9732..348fc944 100644 --- a/tests/unit/strategies/intent/test_nodes.py +++ b/tests/unit/strategies/intent/test_nodes.py @@ -2,7 +2,9 @@ def test_should_skip_launcher_persistence_on_launcher_only_steps() -> None: - """Skip persistence when execution both starts and ends on launcher packages.""" + """ + Skip persistence when execution both starts and ends on launcher packages. + """ should_skip = GraphStatePersistence.should_skip_launcher( execution_activity="com.google.android.apps.nexuslauncher", @@ -13,18 +15,22 @@ def test_should_skip_launcher_persistence_on_launcher_only_steps() -> None: def test_should_persist_launcher_to_app_transition() -> None: - """Persist steps that leave the launcher and open the requested app.""" + """ + Persist steps that leave the launcher and open the requested app. + """ should_skip = GraphStatePersistence.should_skip_launcher( execution_activity="com.google.android.apps.nexuslauncher", - observed_activity="com.snabbit.customer", + observed_activity="com.example.customer", ) assert should_skip is False def test_should_skip_when_observed_package_is_unknown() -> None: - """Keep launcher suppression when post-action package resolution is unavailable.""" + """ + Keep launcher suppression when post-action package resolution is unavailable. + """ should_skip = GraphStatePersistence.should_skip_launcher( execution_activity="com.google.android.apps.nexuslauncher", diff --git a/tests/unit/utils/test_coordinates.py b/tests/unit/utils/test_coordinates.py index 435b7c53..3e65e031 100644 --- a/tests/unit/utils/test_coordinates.py +++ b/tests/unit/utils/test_coordinates.py @@ -1,85 +1,24 @@ from __future__ import annotations -import re import unittest -import xml.etree.ElementTree as ElementTree -from pathlib import Path from fathom.schemas.actions import Bounds, CoordinateSource, CoordinateSystem from fathom.utils.coordinates import CoordinateConverter -PROJECT_ROOT = Path(__file__).resolve().parents[3] - class CoordinateConverterTest(unittest.TestCase): """ Unit tests for region-based gesture path derivation. """ - def test_rolodex_knob_xml_region_uses_edge_based_swipe_path(self) -> None: - """ - Derive the swipe path from the real Rolodex knob XML bounds. - """ - - bounds = self.__rolodex_knob_bounds() - converter = CoordinateConverter(logical_width=1080, logical_height=2340) - - region = converter.region_from_bounds(bounds=bounds, source=CoordinateSource.XML) - path = converter.resolve_swipe_path(region=region, direction="right") - - self.assertEqual(region.source, "xml") - self.assertEqual((region.x, region.y, region.width, region.height), (66, 2010, 132, 62)) - - self.assertEqual(path.distance, 100) - self.assertEqual(path.to_coordinates(), (82, 2041, 182, 2041)) - - def test_save_to_draft_xml_region_uses_full_region_width(self) -> None: - """ - Derive a wide path from the real Save to draft XML bounds. - """ - - bounds = self.__save_to_draft_bounds() - converter = CoordinateConverter(logical_width=1080, logical_height=2340) - - region = converter.region_from_bounds(bounds=bounds, source=CoordinateSource.XML) - path = converter.resolve_swipe_path(region=region, direction="right") - - self.assertEqual(region.source, "xml") - self.assertEqual((region.x, region.y, region.width, region.height), (44, 1817, 992, 143)) - - self.assertEqual(path.distance, 864) - self.assertEqual(path.to_coordinates(), (108, 1888, 972, 1888)) - - def test_viewport_scroll_uses_real_screenshot_dimensions(self) -> None: - """ - Derive scroll distance from the real screenshot viewport. - """ - - width, height = self.__screen_dimensions( - PROJECT_ROOT / "tests/fixtures/coordinate/android/swipe/001/dimensions.txt" - ) - converter = CoordinateConverter(logical_width=width, logical_height=height) - - region = converter.viewport_region() - path = converter.resolve_scroll_path(region=region, direction="down") - - self.assertEqual(region.source, "viewport") - self.assertEqual((region.x, region.y, region.width, region.height), (0, 0, 1080, 2340)) - - self.assertEqual(path.distance, 2020) - self.assertEqual(path.to_coordinates(), (540, 2180, 540, 160)) - def test_model_region_works_without_xml(self) -> None: """ - Derive a swipe path from a real Gemini bbox when XML is unavailable. + Derive a swipe path from a model bbox when XML is unavailable. """ converter = CoordinateConverter(logical_width=1080, logical_height=2340) - # The original fixture stamped these device-pixel values as - # "normalized" because the old is_normalized heuristic silently - # re-classified them. With explicit coordinate systems the - # producer must declare DEVICE_PIXEL when the magnitudes are - # already in screen-pixel space. + # Magnitudes already in screen-pixel space, so the producer must declare + # DEVICE_PIXEL rather than rely on any normalized-vs-pixel inference. bounds = Bounds( x=44, y=1983, @@ -115,90 +54,6 @@ def test_capture_bounds_scale_logical_region_to_retina_pixels(self) -> None: self.assertEqual(bounds.system, CoordinateSystem.DEVICE_PIXEL) self.assertEqual((bounds.x, bounds.y, bounds.width, bounds.height), (0, 0, 1290, 2796)) - @staticmethod - def __screen_dimensions(path: Path) -> tuple[int, int]: - """ - Read captured screenshot dimensions from a stable fixture. - """ - - value = path.read_text(encoding="utf-8").strip() - match = re.fullmatch(r"(\d+)x(\d+)", value) - - if not match: - raise AssertionError(f"Invalid dimensions fixture: {path}") - - width, height = (int(group) for group in match.groups()) - return width, height - - @staticmethod - def __rolodex_knob_bounds() -> Bounds: - """ - Return the real Rolodex knob bounds from coordinate fixture 001. - """ - - path = PROJECT_ROOT / "tests/fixtures/coordinate/android/swipe/001/hierarchy.xml" - root = ElementTree.parse(path).getroot() - - for node in root.iter("node"): - children = list(node) - has_rolodex_text = any( - child.attrib.get("text") == "Add to rolodex" for child in children - ) - if not has_rolodex_text: - continue - for child in children: - if ( - child.attrib.get("text") == "" - and child.attrib.get("class") == "android.view.View" - and child.attrib.get("bounds") == "[66,2010][198,2072]" - ): - return CoordinateConverterTest.__bounds_from_xml(child.attrib["bounds"]) - - raise AssertionError(f"Could not find Rolodex knob bounds in {path}") - - @staticmethod - def __save_to_draft_bounds() -> Bounds: - """ - Return the real Save to draft button bounds from coordinate fixture 002. - """ - - path = PROJECT_ROOT / "tests/fixtures/coordinate/android/swipe/002/hierarchy.xml" - root = ElementTree.parse(path).getroot() - - for node in root.iter("node"): - children = list(node) - has_save_text = any( - child.attrib.get("text") == "Save to draft (to complete later)" - for child in children - ) - has_button_shape = any( - child.attrib.get("class") == "android.widget.Button" - and child.attrib.get("bounds") == "[44,1817][1036,1960]" - for child in children - ) - - if has_save_text and has_button_shape: - return CoordinateConverterTest.__bounds_from_xml(node.attrib["bounds"]) - - raise AssertionError(f"Could not find Save to draft text in {path}") - - @staticmethod - def __bounds_from_xml(value: str) -> Bounds: - """ - Convert an Android XML bounds string into pixel bounds. - """ - - match = re.fullmatch(r"\[(\d+),(\d+)\]\[(\d+),(\d+)\]", value) - if not match: - raise AssertionError(f"Invalid Android bounds string: {value}") - - left, top, right, bottom = (int(group) for group in match.groups()) - - return Bounds( - x=left, - y=top, - width=right - left, - height=bottom - top, - coordinate_system=CoordinateSystem.DEVICE_PIXEL, - ) +if __name__ == "__main__": + unittest.main()