Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Remove the Task V3 required-field-answers prompt arm and pin both system prompts by sha256 (#8727)
pedrohsdb4c469c963fd6
diff --git a/skyvern/config.py b/skyvern/config.pyindex 2ec0fa298..bcaba82f0 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -556,10 +556,6 @@ class Settings(BaseSettings):# measured via taskv3_block_context_tokens before it earns default-on. The outcome itself is# persisted on workflow_run_blocks regardless of this flag (one row read + one update per block).TASK_V3_BLOCK_HANDOFF: bool = False- # Swap in the fill-rule text an AgentFunction supplies (task_v3_required_field_answers_text); with no- # text supplied the run gets the control prompt. Force-on term only: runs are randomized per run by the- # flag of the same name, read through run_arm_enabled().- TASK_V3_REQUIRED_FIELD_ANSWERS: bool = False# State in the system prompt that the task's own instructions win over its general rules. Force-on term only:# runs are randomized per run by the flag of the same name, read through run_arm_enabled().TASK_V3_CUSTOMER_PRECEDENCE: bool = Falsediff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex b2a851cc4..f464a8277 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -201,7 +201,6 @@ from skyvern.forge.taskv3.run_arms import (GOAL_CHECK_ENFORCE_FLAG,GOAL_CHECK_FLAG,HUMANIZED_INPUT_FLAG,- REQUIRED_FIELD_ANSWERS_FLAG,TYPE_COORDINATE_CLICK_FLAG,resolve_run_arm,run_arm_enabled,@@ -2343,18 +2342,6 @@ class ForgeAgent:organization_id=task.organization_id,forced=settings.TASK_V3_DATE_SEGMENT_AIM,)- await resolve_run_arm(- context,- REQUIRED_FIELD_ANSWERS_FLAG,- distinct_id=task.workflow_run_id or task.task_id,- organization_id=task.organization_id,- forced=settings.TASK_V3_REQUIRED_FIELD_ANSWERS,- properties={- "workflow_permanent_id": task.workflow_permanent_id- or context.workflow_permanent_id- or "not_workflow"- },- )await resolve_run_arm(context,CUSTOMER_PRECEDENCE_FLAG,diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex fa5d9838e..32f462e9e 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -990,11 +990,6 @@ class AgentFunction:async def resolve_billing_tier(self, organization_id: str | None) -> BillingTier:return BillingTier.UNKNOWN- # (fill text, self-screen bullet) for the v3 required-field-answers arm's treatment prompt. OSS- # supplies none, so a run in that arm's treatment renders the control prompt.- def task_v3_required_field_answers_text(self) -> tuple[str, str] | None:- return None-# (text appended to a page-aware v3 run's task message or None, reason logged on the loop-finished line), given# the run's payload. OSS supplies no default.def task_v3_age_default(self, parameters: dict[str, Any] | None) -> tuple[str | None, str] | None:diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.pyindex 7419869d8..5c7fde1ef 100644--- a/skyvern/forge/taskv3/engine.py+++ b/skyvern/forge/taskv3/engine.py@@ -21,7 +21,6 @@ in-process adapter over ``do_observe``/``do_execute`` for shared hardening + actfrom __future__ import annotations-import functoolsimport jsonimport timefrom datetime import UTC, datetime@@ -71,7 +70,6 @@ from skyvern.forge.taskv3.loop import (from skyvern.forge.taskv3.opaque_refs import OpaqueUrlRefs, is_signed_url, mask_opaque_urlsfrom skyvern.forge.taskv3.run_arms import (CUSTOMER_PRECEDENCE_FLAG,- REQUIRED_FIELD_ANSWERS_FLAG,run_arm_enabled,)from skyvern.forge.taskv3.tools import (@@ -119,18 +117,7 @@ MAX_TOKENS_CEILING = 4 * DEFAULT_MAX_TOKENS# Left between the judge's timeout and the run's deadline, so a judge call cannot be what ends the run.GOAL_CHECK_DEADLINE_MARGIN_SECONDS = 2.0-# The rule for a required sensitive field the task's data cannot fill; the required-field-answers prompt must keep it.-SENSITIVE_FIELD_STOP_CLAUSE = "stop and report it rather than guessing"--# The anchor ends before SENSITIVE_FIELD_STOP_CLAUSE so the required-field-answers prompt keeps that stop.-REQUIRED_FIELD_ANSWERS_ANCHOR = (- "prefer the provided values, and for an ordinary required field with no exact value, enter the most reasonable "- "value you can. Do not invent sensitive or identifying values (government IDs, financial details, or "- "legal/eligibility attestations); if one of those is required and not provided, "-)-SELF_SCREEN_ANCHOR = "- A page message rejecting your submission"--# Inserted above "How to work:" so it covers every section below it and sits outside every span another arm rewrites.+# Inserted above "How to work:" so it covers every section below it.CUSTOMER_PRECEDENCE_ANCHOR = "\n\nHow to work:\n"CUSTOMER_PRECEDENCE_TEXT = ("\n\nThe task's goal, its completion and termination criteria, and the user's instructions for this task come "@@ -165,43 +152,14 @@ Rules:- Do not submit forms or take irreversible actions unless the goal explicitly instructs it."""[email protected]_cache(maxsize=4)-def _build_required_field_answers_prompt(fill_text: str, self_screen_bullet: str) -> str:- """Falls back to `SYSTEM_PROMPT` itself unless every anchor is uniquely present and the stop clause survives."""- if SYSTEM_PROMPT.count(REQUIRED_FIELD_ANSWERS_ANCHOR) != 1 or SYSTEM_PROMPT.count(SELF_SCREEN_ANCHOR) != 1:- return SYSTEM_PROMPT- prompt = SYSTEM_PROMPT.replace(REQUIRED_FIELD_ANSWERS_ANCHOR, fill_text).replace(- SELF_SCREEN_ANCHOR, self_screen_bullet + SELF_SCREEN_ANCHOR- )- if prompt.count(SENSITIVE_FIELD_STOP_CLAUSE) != 1:- return SYSTEM_PROMPT- return prompt---def system_prompt_for_run_arms(- *, required_field_answers_text: tuple[str, str] | None, customer_precedence: bool-) -> str:- """The v3 system prompt for this run's required-field-answers and customer-precedence arms.-- `required_field_answers_text` is (fill text, self-screen bullet) for a run in that arm's treatment, else None.- With every arm off this is `SYSTEM_PROMPT` itself, not a copy, so the off arms cannot drift from today's prompt.- """- prompt = _system_prompt_for_fill_arms(required_field_answers_text=required_field_answers_text)+def system_prompt_for_run_arms(*, customer_precedence: bool) -> str:+ """With every arm off this is `SYSTEM_PROMPT` itself, not a copy, so the off arms cannot drift from it."""if not customer_precedence:- return prompt- if prompt.count(CUSTOMER_PRECEDENCE_ANCHOR) != 1:+ return SYSTEM_PROMPT+ if SYSTEM_PROMPT.count(CUSTOMER_PRECEDENCE_ANCHOR) != 1:LOG.error("Task V3 customer-precedence anchor is not uniquely present; sent the prompt without it")- return prompt- return prompt.replace(CUSTOMER_PRECEDENCE_ANCHOR, CUSTOMER_PRECEDENCE_TEXT + CUSTOMER_PRECEDENCE_ANCHOR)---def _system_prompt_for_fill_arms(*, required_field_answers_text: tuple[str, str] | None) -> str:- if required_field_answers_text is None:return SYSTEM_PROMPT- prompt = _build_required_field_answers_prompt(*required_field_answers_text)- if prompt is SYSTEM_PROMPT:- LOG.error("Task V3 required-field-answers clause is not uniquely present; sent control")- return prompt+ return SYSTEM_PROMPT.replace(CUSTOMER_PRECEDENCE_ANCHOR, CUSTOMER_PRECEDENCE_TEXT + CUSTOMER_PRECEDENCE_ANCHOR)OPAQUE_URL_GUIDANCE = """@@ -569,18 +527,7 @@ async def run_task_v3_agent_loop(if page_free:base_system_prompt = PAGE_FREE_SYSTEM_PROMPTelse:- required_field_answers = run_arm_enabled(REQUIRED_FIELD_ANSWERS_FLAG, settings.TASK_V3_REQUIRED_FIELD_ANSWERS)- required_field_answers_text = (- app.AGENT_FUNCTION.task_v3_required_field_answers_text() if required_field_answers else None- )- if required_field_answers and required_field_answers_text is None:- LOG.info(- "Task V3 required-field-answers arm resolved treatment but no text is supplied; sent control",- workflow_run_id=ctx.workflow_run_id if ctx else None,- task_id=ctx.task_id if ctx else None,- )base_system_prompt = system_prompt_for_run_arms(- required_field_answers_text=required_field_answers_text,customer_precedence=run_arm_enabled(CUSTOMER_PRECEDENCE_FLAG, settings.TASK_V3_CUSTOMER_PRECEDENCE),)# Keyed on which hooks are present, not completion_probe alone: an extraction blocker-onlydiff --git a/skyvern/forge/taskv3/run_arms.py b/skyvern/forge/taskv3/run_arms.pyindex cbefa1196..de4966d86 100644--- a/skyvern/forge/taskv3/run_arms.py+++ b/skyvern/forge/taskv3/run_arms.py@@ -18,7 +18,6 @@ LOG = structlog.get_logger()TYPE_COORDINATE_CLICK_FLAG = "TASK_V3_TYPE_COORDINATE_CLICK"DATE_SEGMENT_AIM_FLAG = "TASK_V3_DATE_SEGMENT_AIM"-REQUIRED_FIELD_ANSWERS_FLAG = "TASK_V3_REQUIRED_FIELD_ANSWERS"CUSTOMER_PRECEDENCE_FLAG = "TASK_V3_CUSTOMER_PRECEDENCE"EXTRACTION_REPORTS_FLAG = "TASK_V3_EXTRACTION_REPORTS"GOAL_CHECK_FLAG = "TASK_V3_GOAL_CHECK"@@ -28,7 +27,6 @@ HUMANIZED_INPUT_FLAG = "TASK_V3_HUMANIZED_INPUT"# Person properties a flag is evaluated with beyond organization_id; resolve_run_arm drops any other key. The# PostHog preflight (scripts/check_run_arm_flags.py) reads this mapping to accept release conditions on them.RUN_ARM_EXTRA_PROPERTIES: dict[str, tuple[str, ...]] = {- REQUIRED_FIELD_ANSWERS_FLAG: ("workflow_permanent_id",),CUSTOMER_PRECEDENCE_FLAG: ("workflow_permanent_id",),}diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.pyindex 7acdb8cab..9bcc97d5c 100644--- a/skyvern/forge/taskv3/tools.py+++ b/skyvern/forge/taskv3/tools.py@@ -1289,8 +1289,9 @@ _OFF_CANVAS_JS = r"""(el, r) => {# Emits `root`'s semantic matches merged in document order with its "pointer roots" (named, role-less# elements styled cursor:pointer, the only trace a delegated click listener leaves; v1 lists them via# isHoverPointerElement, domUtils.js), recording each root and its name in `state.roots`. An element is-# not a root when the reading already covers it: it is, is inside, or holds a control `listable` keeps,-# or its pointer parent is itself a root or covered.+# not a root when the reading already covers it: it is or is inside a control `listable` keeps, or its+# pointer parent is itself a root or covered. One that holds such a control is a holder: at most one+# named, control-free pointer descendant is listed for it, recorded in `state.held`._WITH_POINTER_ROOTS_JS = (r"""(root, q, semantic, state, emit, listable) => {// A linked list, not an array: a page that poisons Array.prototype.push or its index setters@@ -1424,10 +1425,22 @@ _WITH_POINTER_ROOTS_JS = (// A control the reading drops is not a root, but its pointer children may be.if (matches.call(el, q)) { if (listable(el)) state.covered.add(el); continue; }const sr = shadowRootOf.call(el);- if (inListable(parentOf.call(el)) || anyListable(qsa.call(el, q))- || (sr && sr.nodeType === 11 && anyListable(fragQsa.call(sr, q))) || heldBySlot(el)+ const holds = anyListable(qsa.call(el, q));+ if (inListable(parentOf.call(el)) || (sr && sr.nodeType === 11 && (holds || anyListable(fragQsa.call(sr, q))))+ || heldBySlot(el)// A label bound to a control names that control, which is listed (or skinned) on its own.|| (tag === 'label' && el.control)) { state.covered.add(el); continue; }+ // A row or card that also carries a button is not listed (its centre may land on the button);+ // its first named control-free pointer child stands for it instead, for as many holders as the+ // cap could ever list. Past that a holder is covered, so a long list costs no more work than before.+ if (holds) { (state.heldCount < state.heldCap ? state.holders : state.covered).add(el); continue; }+ let holder = null;+ for (let a = parent, i = 0; a && i < 64 && isPointer(a); a = parentOf.call(a), i++) {+ if (state.holders.has(a)) { holder = a; break; }+ }+ if (holder && (state.represented.has(holder) || state.heldCount >= state.heldCap)) { state.covered.add(el); continue; }+ // A decorative child (an icon font's ligature) does not name the row.+ if (holder && closest.call(el, '[aria-hidden="true"]')) continue;const r = bcr.call(el);if (!(r.width > 0 && r.height > 0)) continue;if (getComputedStyle(el).visibility !== 'visible' || offCanvas(el, r)) continue;@@ -1457,7 +1470,13 @@ _WITH_POINTER_ROOTS_JS = (if (!painted(el, r) || offRight(el, r)) continue;state.roots.set(el, name.replace(/\s+/g, ' ').slice(0, retain));state.covered.add(el);- state.count++;+ // A holder's child ranks below every other pointer root for the listing cap, so it neither+ // spends the scan ceiling nor displaces a root the reading lists without holders.+ if (holder) {+ state.held.add(el);+ state.heldCount++;+ for (let a = holder, i = 0; a && i < 64 && state.holders.has(a); a = parentOf.call(a), i++) state.represented.add(a);+ } else state.count++;const node = { el, next: null };if (tail) tail.next = node; else head = node;tail = node;@@ -7726,7 +7745,9 @@ async (__tv3TextArgs) => {const _screenListable = (el) => {try { return _screen(el, false).why === null; } catch (e) { return false; }};- const _pointerState = { pointer: new Map(), covered: new Set(), roots: new Map(), count: 0, retain: _RETAIN_WIDTH, ceiling: """+ const _pointerState = { pointer: new Map(), covered: new Set(), roots: new Map(), holders: new Set(), represented: new Set(), held: new Set(), heldCount: 0, heldCap: """+ + str(OBSERVE_POINTER_ROOT_CAP)+ + r""", count: 0, retain: _RETAIN_WIDTH, ceiling: """+ str(_POINTER_ROOT_SCAN_CEILING)+ r""" };let pointerListed = 0;@@ -8588,6 +8609,9 @@ async (__tv3TextArgs) => {return b.bottom + window.scrollY > 0 && b.top + window.scrollY < _scrollHeightOf.call(se)&& b.right + window.scrollX > 0 && b.left + window.scrollX < _scrollWidthOf.call(se);};+ // Places the cap keeps for the pointer roots not yet reached that no holder expansion produced+ // (`count` tallies exactly those).+ let pointerReserved = _pointerState.count;for (let idx = 0; idx < els.length; idx++) {const el = els[idx].el;const host = els[idx].host;@@ -8603,6 +8627,7 @@ async (__tv3TextArgs) => {// The collector screened a pointer root with these same visibility gates, so none of the hidden// counters below ever describes one: a pointer root is listed or counted as one.pointerRoot = _pointerState.roots.has(el);+ if (pointerRoot && !_pointerState.held.has(el)) pointerReserved--;const screened = _screen(el, pointerRoot);const { r, gr, gateEl, ownGated } = screened;if (screened.why === 'offCanvas') { hiddenDropped++; hiddenDroppedOffCanvas++; continue; }@@ -8672,7 +8697,7 @@ async (__tv3TextArgs) => {continue;}}- if (pointerRoot && pointerListed >= _POINTER_ROOT_CAP) { pointerCapped++; continue; }+ if (pointerRoot && pointerListed + (_pointerState.held.has(el) ? pointerReserved : 0) >= _POINTER_ROOT_CAP) { pointerCapped++; continue; }let selector = naturalSelector(el);if (!selector) {// We do not write inside a shadow root. Setting a marker there is a mutation of the@@ -8732,6 +8757,7 @@ async (__tv3TextArgs) => {// recognition and leak its signing tail.const rec = { i, tag: el.tagName.toLowerCase(), type: (_typed && el.type) || null, selector, label: label.slice(0, _RETAIN_WIDTH) };if (pointerRoot) rec.pointerRoot = true;+ if (pointerRoot && _pointerState.held.has(el)) rec.pointerHeld = true;if (placeholder && placeholder !== label) rec.placeholder = placeholder.slice(0, _RETAIN_WIDTH);if (hidden) rec.hidden = true;if (removedBy) rec.a11yRemoved = removedBy;@@ -10652,12 +10678,16 @@ def _merge_realm(into: dict[str, Any], other: dict[str, Any]) -> list[int]:# Pointer roots ride outside the element budget here as in each realm, under their own cap applied# page-wide, so neither limit ever costs the other kind a place.room = max(0, OBSERVE_MERGED_ELEMENT_MAX - sum(1 for e in elements if not e.get("pointerRoot")))- pointer_room = max(0, OBSERVE_POINTER_ROOT_CAP - sum(1 for e in elements if e.get("pointerRoot")))+ pointer_room = max(+ 0, OBSERVE_POINTER_ROOT_CAP - sum(1 for e in elements if e.get("pointerRoot") and not e.get("pointerHeld"))+ )kept: list[int] = []pointer_over_cap = 0over_page_cap = 0for i, e in enumerate(incoming):- if e.get("pointerRoot"):+ if e.get("pointerHeld"):+ pass # Ranked page-wide by _rank_held_pointer_roots_last once every realm is merged.+ elif e.get("pointerRoot"):if pointer_room == 0:pointer_over_cap += 1continue@@ -10695,6 +10725,25 @@ def _merge_realm(into: dict[str, Any], other: dict[str, Any]) -> list[int]:return kept+def _rank_held_pointer_roots_last(data: dict[str, Any]) -> list[int]:+ """Keep a holder's stand-in child only in the page-wide pointer cap left after every other pointer root.+ Returns the kept indices, which the caller applies to its handle and owner lists."""+ elements = data.get("elements") or []+ room = OBSERVE_POINTER_ROOT_CAP - sum(1 for e in elements if e.get("pointerRoot") and not e.get("pointerHeld"))+ kept: list[int] = []+ for i, e in enumerate(elements):+ if e.get("pointerHeld"):+ if room <= 0:+ continue+ room -= 1+ kept.append(i)+ over = len(elements) - len(kept)+ data["elements"] = [elements[i] for i in kept]+ data["pointerCapped"] = int(data.get("pointerCapped") or 0) + over+ data["pointerListed"] = int(data.get("pointerListed") or 0) - over+ return kept++_HIT_CLASSES = frozenset({"self", "non_target", "no_hit", "unknown", "disabled"})@@ -11166,6 +11215,17 @@ def build_browser_tools(main_handles.extend(frame_handles[i] for i in kept)owners.extend([frame] * len(kept))fresh[frame] = bool(frame_data.get("refsFresh"))+ # A split reading already fails closed at pairing, so it is left for that check to refuse.+ if len(main_handles) == len(owners) == len(main_data.get("elements") or []):+ kept = _rank_held_pointer_roots_last(main_data)+ kept_set = set(kept)+ for spare in [h for i, h in enumerate(main_handles) if h is not None and i not in kept_set]:+ try:+ await spare.dispose()+ except Exception:+ pass+ main_handles = [main_handles[i] for i in kept]+ owners = [owners[i] for i in kept]# The page's identity re-checked AFTER the frames were read. The main frame navigating in between# would otherwise assemble one reading out of two documents -- the old page's url, text and# controls beside child frames belonging to its replacement -- and while the old main handles godiff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.pyindex f9b1f36be..6200bac82 100644--- a/tests/unit/force_stub_app.py+++ b/tests/unit/force_stub_app.py@@ -66,9 +66,6 @@ def create_forge_stub_app() -> ForgeApp:# Class constant, not a method — _LazyNamespace would auto-mock it into a non-iterable AsyncMock# and break every caller that scans it for close-page phrases.fake_app_module.AGENT_FUNCTION.MAGIC_LINK_CLOSE_SIGNALS = base_agent_function.MAGIC_LINK_CLOSE_SIGNALS- fake_app_module.AGENT_FUNCTION.task_v3_required_field_answers_text = (- base_agent_function.task_v3_required_field_answers_text- )fake_app_module.AGENT_FUNCTION.task_v3_age_default = base_agent_function.task_v3_age_defaultfake_app_module.AGENT_FUNCTION.serialize_codeblock_parameters = base_agent_function.serialize_codeblock_parametersfake_app_module.AGENT_FUNCTION.redact_codeblock_parameter_values = (diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.pyindex cd2c6d1f9..121385eaa 100644--- a/tests/unit/test_agent_task_v3.py+++ b/tests/unit/test_agent_task_v3.py@@ -81,7 +81,6 @@ from skyvern.forge.taskv3.run_arms import (CUSTOMER_PRECEDENCE_FLAG,DATE_SEGMENT_AIM_FLAG,EXTRACTION_REPORTS_FLAG,- REQUIRED_FIELD_ANSWERS_FLAG,TYPE_COORDINATE_CLICK_FLAG,run_arm_enabled,)@@ -180,7 +179,6 @@ async def _run_execute_task_v3(loop_mock.active_credential_parameter_key_during_loop = context.active_credential_parameter_keyloop_mock.type_coordinate_click_enabled_during_loop = run_arm_enabled(TYPE_COORDINATE_CLICK_FLAG, forced=False)loop_mock.date_segment_aim_enabled_during_loop = run_arm_enabled(DATE_SEGMENT_AIM_FLAG, forced=False)- loop_mock.required_field_answers_during_loop = run_arm_enabled(REQUIRED_FIELD_ANSWERS_FLAG, forced=False)loop_mock.customer_precedence_during_loop = run_arm_enabled(CUSTOMER_PRECEDENCE_FLAG, forced=False)cb = kwargs.get("on_action_round")if cb is not None and action_rounds:@@ -351,40 +349,12 @@ async def test_execute_task_v3_buckets_the_date_segment_aim_arm_per_run(monkeypa@pytest.mark.asyncio@pytest.mark.parametrize(("workflow_permanent_id", "targeted_wpid"),- [("wpid_required_field_answers", "wpid_required_field_answers"), (None, "not_workflow")],+ [("wpid_customer_precedence", "wpid_customer_precedence"), (None, "not_workflow")],)-async def test_execute_task_v3_resolves_the_required_field_answers_arm_before_the_loop_reads_it(+async def test_execute_task_v3_resolves_the_customer_precedence_arm_before_the_loop_reads_it(monkeypatch: pytest.MonkeyPatch, workflow_permanent_id: str | None, targeted_wpid: str) -> None:# The rollout is targeted by workflow, so the flag must be evaluated with the wpid property.- monkeypatch.setattr(settings, "TASK_V3_REQUIRED_FIELD_ANSWERS", False)- provider = AsyncMock(return_value="treatment")- monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "get_value_cached", provider)-- outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])- _step, task, loop_mock, _post = await _run_execute_task_v3(- monkeypatch,- outcome,- workflow_run_id="wr_required_field_answers_reach",- workflow_permanent_id=workflow_permanent_id,- data_extraction_goal=None,- extracted_information_schema=None,- )-- assert task.workflow_run_id != task.task_id- assert loop_mock.required_field_answers_during_loop is True- assert loop_mock.context.run_arms[REQUIRED_FIELD_ANSWERS_FLAG] == (task.workflow_run_id, "treatment")- provider.assert_any_await(- REQUIRED_FIELD_ANSWERS_FLAG,- task.workflow_run_id,- properties={"organization_id": task.organization_id, "workflow_permanent_id": targeted_wpid},- )---async def test_execute_task_v3_resolves_the_customer_precedence_arm_before_the_loop_reads_it(- monkeypatch: pytest.MonkeyPatch,-) -> None:monkeypatch.setattr(settings, "TASK_V3_CUSTOMER_PRECEDENCE", False)provider = AsyncMock(return_value="treatment")monkeypatch.setattr(app.EXPERIMENTATION_PROVIDER, "get_value_cached", provider)@@ -394,7 +364,7 @@ async def test_execute_task_v3_resolves_the_customer_precedence_arm_before_the_lmonkeypatch,outcome,workflow_run_id="wr_customer_precedence_reach",- workflow_permanent_id="wpid_customer_precedence",+ workflow_permanent_id=workflow_permanent_id,data_extraction_goal=None,extracted_information_schema=None,)@@ -405,7 +375,7 @@ async def test_execute_task_v3_resolves_the_customer_precedence_arm_before_the_lprovider.assert_any_await(CUSTOMER_PRECEDENCE_FLAG,task.workflow_run_id,- properties={"organization_id": task.organization_id, "workflow_permanent_id": "wpid_customer_precedence"},+ properties={"organization_id": task.organization_id, "workflow_permanent_id": targeted_wpid},)diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.pyindex 983d6f084..2c207fc49 100644--- a/tests/unit/test_taskv3_engine.py+++ b/tests/unit/test_taskv3_engine.py@@ -7,6 +7,7 @@ from the tools test, so the engine's wiring is exercised without a real LLM or bfrom __future__ import annotationsimport asyncio+import hashlibimport jsonfrom collections.abc import Callablefrom pathlib import Path@@ -41,9 +42,7 @@ from skyvern.forge.taskv3.engine import (MAX_TOOL_CALLS_PER_ACTION_STEP,MAX_TURNS_PER_ACTION_STEP,OPAQUE_URL_GUIDANCE,- REQUIRED_FIELD_ANSWERS_ANCHOR,- SELF_SCREEN_ANCHOR,- SENSITIVE_FIELD_STOP_CLAUSE,+ PAGE_FREE_SYSTEM_PROMPT,SYSTEM_PROMPT,coerce_v3_parameters,run_task_v3_agent_loop,@@ -63,10 +62,7 @@ from skyvern.forge.taskv3.loop import (_ProgressEvidence,)from skyvern.forge.taskv3.opaque_refs import OpaqueUrlRefs, mask_opaque_urls-from skyvern.forge.taskv3.run_arms import (- CUSTOMER_PRECEDENCE_FLAG,- REQUIRED_FIELD_ANSWERS_FLAG,-)+from skyvern.forge.taskv3.run_arms import CUSTOMER_PRECEDENCE_FLAGfrom skyvern.forge.taskv3.tools import PAGE_UNAVAILABLE_ERRORfrom skyvern.schemas.llm import LLMConfig, LLMRouterConfig, LLMRouterModelConfigfrom tests.unit.helpers import fallback_receipts@@ -1945,25 +1941,9 @@ def test_dispatchable_deployments_covers_every_fallback_group_shape() -> None:assert "main" in _names(["fb1"], ["main", "fb1"])-STUB_REQUIRED_FIELD_ANSWERS_FILL = "prefer the provided values. Stub fill rule. If one of those is required, "-STUB_SELF_SCREEN_BULLET = "- Stub self-screen bullet.\n"---def stub_required_field_answers_text(monkeypatch: pytest.MonkeyPatch) -> tuple[str, str]:- """Stands in for a deployment that supplies the required-field-answers text; OSS supplies none."""- texts = (STUB_REQUIRED_FIELD_ANSWERS_FILL, STUB_SELF_SCREEN_BULLET)- monkeypatch.setattr(app.AGENT_FUNCTION, "task_v3_required_field_answers_text", lambda: texts)- return texts---async def _system_prompt_for_run(- *, required_field_answers_arm: str | None = None, precedence_arm: str | None = None-) -> str:- """The system message an actual engine run sends, with the fill-rule and precedence arms pinned."""+async def _system_prompt_for_run(*, precedence_arm: str | None = None) -> str:+ """The system message an actual engine run sends, with the precedence arm pinned."""context = SkyvernContext()- if required_field_answers_arm is not None:- context.run_arms = {**context.run_arms, REQUIRED_FIELD_ANSWERS_FLAG: ("wr_1", required_field_answers_arm)}if precedence_arm is not None:context.run_arms = {**context.run_arms, CUSTOMER_PRECEDENCE_FLAG: ("wr_1", precedence_arm)}skyvern_context.set(context)@@ -1981,93 +1961,28 @@ async def _system_prompt_for_run(_DATE_MARKER = "\n\nToday's date is "[email protected]("required_field_answers_arm", [None, "control", "unrandomized"])-async def test_required_field_answers_off_arms_send_todays_prompt_unchanged(- required_field_answers_arm: str | None, stub_required_field_answers_text: tuple[str, str]-) -> None:- # The off arms are the deployed prompt, byte for byte: a run outside the experiment must not be- # able to drift because the experiment exists.- system_prompt = await _system_prompt_for_run(required_field_answers_arm=required_field_answers_arm)- assert system_prompt.startswith(SYSTEM_PROMPT)- assert system_prompt_for_run_arms(required_field_answers_text=None, customer_precedence=False) is SYSTEM_PROMPT+_SYSTEM_PROMPT_SHA256 = "4b1e2c70182196a4a40f8dec1a134496cc6074a02b383ba42d4ef8df39d8937c"+_PAGE_FREE_SYSTEM_PROMPT_SHA256 = "f2467a7f82ea2db5e08b6da7576a3e58371295af0569cfe143d59903d2580f37"-async def test_required_field_answers_treatment_is_not_the_silent_fallback(- stub_required_field_answers_text: tuple[str, str],-) -> None:- # The builder falls back to today's prompt when an anchor stops matching; a green suite must not- # hide a treatment arm that is byte-identical to control.- treatment = await _system_prompt_for_run(required_field_answers_arm="treatment")- control = await _system_prompt_for_run(required_field_answers_arm="control")- treatment_body = treatment.split(_DATE_MARKER)[0]-- assert not treatment.startswith(SYSTEM_PROMPT)- assert STUB_REQUIRED_FIELD_ANSWERS_FILL in treatment_body and STUB_SELF_SCREEN_BULLET in treatment_body- assert treatment_body.count(SENSITIVE_FIELD_STOP_CLAUSE) == 1- assert (- treatment_body.replace(STUB_REQUIRED_FIELD_ANSWERS_FILL, REQUIRED_FIELD_ANSWERS_ANCHOR).replace(- STUB_SELF_SCREEN_BULLET, ""- )- == control.split(_DATE_MARKER)[0]+def test_system_prompts_are_pinned() -> None:+ message = (+ "{} changed. Any change to the Task V3 system prompt needs a dated operator ruling cited in the PR "+ "(cloud_docs/task-v3/CHARTER.md, Governance) and a deliberate update of this pin.")---async def test_required_field_answers_treatment_without_supplied_text_renders_control() -> None:- # OSS supplies no required-field-answers text, so that arm's treatment must be indistinguishable from- # its control, and say so once for the read to drop.- with capture_logs() as logs:- system_prompt = await _system_prompt_for_run(required_field_answers_arm="treatment")-- assert system_prompt.split(_DATE_MARKER)[0] == SYSTEM_PROMPT- events = [e["event"] for e in logs]- assert (- events.count("Task V3 required-field-answers arm resolved treatment but no text is supplied; sent control") == 1+ assert hashlib.sha256(SYSTEM_PROMPT.encode()).hexdigest() == _SYSTEM_PROMPT_SHA256, message.format("SYSTEM_PROMPT")+ assert hashlib.sha256(PAGE_FREE_SYSTEM_PROMPT.encode()).hexdigest() == _PAGE_FREE_SYSTEM_PROMPT_SHA256, (+ message.format("PAGE_FREE_SYSTEM_PROMPT"))- "drifted_prompt",- [- SYSTEM_PROMPT.replace(REQUIRED_FIELD_ANSWERS_ANCHOR, ""),- SYSTEM_PROMPT.replace(SELF_SCREEN_ANCHOR, ""),- SYSTEM_PROMPT + REQUIRED_FIELD_ANSWERS_ANCHOR,- ],-)-def test_required_field_answers_falls_back_to_control_when_an_anchor_drifts(- monkeypatch: pytest.MonkeyPatch, drifted_prompt: str-) -> None:- engine_mod._build_required_field_answers_prompt.cache_clear()- monkeypatch.setattr(engine_mod, "SYSTEM_PROMPT", drifted_prompt)- try:- with capture_logs() as logs:- prompt = system_prompt_for_run_arms(- required_field_answers_text=(STUB_REQUIRED_FIELD_ANSWERS_FILL, STUB_SELF_SCREEN_BULLET),- customer_precedence=False,- )- finally:- engine_mod._build_required_field_answers_prompt.cache_clear()- assert prompt is drifted_prompt- assert [e["event"] for e in logs] == ["Task V3 required-field-answers clause is not uniquely present; sent control"]--@pytest.mark.asyncio@pytest.mark.parametrize("precedence_arm", [None, "treatment"])[email protected]("required_field_answers_arm", [None, "treatment"])-async def test_prompt_arms_add_no_submit_pressure(- required_field_answers_arm: str | None,- precedence_arm: str | None,- stub_required_field_answers_text: tuple[str, str],-) -> None:+async def test_prompt_arms_add_no_submit_pressure(precedence_arm: str | None) -> None:# The charter's non-negotiable: while the only thing standing between a model error and an# unauthorized submit is a line of system prompt, no arm may add prose that competes with it.- # Asserted on the prompt the engine actually sends, not the constant. The supplied- # required-field-answers wording itself is pinned against this where it lives.- treatment = await _system_prompt_for_run(- required_field_answers_arm=required_field_answers_arm, precedence_arm=precedence_arm- )+ # Asserted on the prompt the engine actually sends, not the constant.+ treatment = await _system_prompt_for_run(precedence_arm=precedence_arm)base_control = await _system_prompt_for_run()bullet = next(line for line in treatment.splitlines() if line.startswith("- Fill fields from the task's data"))@@ -2079,16 +1994,14 @@ async def test_prompt_arms_add_no_submit_pressure(assert contract in base_controlno_submit = "Do not submit forms or take irreversible actions unless the goal explicitly instructs it."assert no_submit in treatment and no_submit in base_control- # Pinned as a literal so an edit weakening SYSTEM_PROMPT cannot pass by weakening the constant too. Only the- # required-field-answers arm rewrites this rule; every other arm sends it verbatim.+ # Pinned as a literal so an edit weakening SYSTEM_PROMPT cannot pass by weakening the constant too.do_not_invent = ("Do not invent sensitive or identifying values (government IDs, financial details, or ""legal/eligibility attestations); if one of those is required and not provided, stop and report it ""rather than guessing.")assert do_not_invent in base_control- if required_field_answers_arm is None:- assert do_not_invent in treatment+ assert do_not_invent in treatment# The precedence paragraph sits beside that guard, so it may name submitting only to exempt that guard.if precedence_arm == "treatment":paragraph = treatment.split(CUSTOMER_PRECEDENCE_ANCHOR)[0].split("\n\n")[-1]@@ -2109,7 +2022,7 @@ async def test_customer_precedence_off_arms_send_todays_prompt(precedence_arm: sassert system_prompt.startswith(SYSTEM_PROMPT)assert CUSTOMER_PRECEDENCE_TEXT not in system_prompt- assert system_prompt_for_run_arms(required_field_answers_text=None, customer_precedence=False) is SYSTEM_PROMPT+ assert system_prompt_for_run_arms(customer_precedence=False) is SYSTEM_PROMPT@pytest.mark.asyncio@@ -2134,40 +2047,13 @@ def test_customer_precedence_sends_the_prompt_unchanged_when_its_anchor_drifts() -> None:monkeypatch.setattr(engine_mod, "SYSTEM_PROMPT", drifted_prompt)with capture_logs() as logs:- prompt = system_prompt_for_run_arms(required_field_answers_text=None, customer_precedence=True)+ prompt = system_prompt_for_run_arms(customer_precedence=True)assert prompt is drifted_promptassert [e["event"] for e in logs] == ["Task V3 customer-precedence anchor is not uniquely present; sent the prompt without it"][email protected]("required_field_answers_arm", [None, "treatment"])-async def test_customer_precedence_composes_with_the_fill_rule_arms(- required_field_answers_arm: str | None,- stub_required_field_answers_text: tuple[str, str],-) -> None:- without = _body(- await _system_prompt_for_run(required_field_answers_arm=required_field_answers_arm, precedence_arm="control")- )- with_precedence = _body(- await _system_prompt_for_run(required_field_answers_arm=required_field_answers_arm, precedence_arm="treatment")- )-- # Above "How to work:" (named literally, not through the anchor constant), outside every span another arm rewrites.- assert with_precedence.count(CUSTOMER_PRECEDENCE_TEXT) == 1- assert with_precedence.split("\n\nHow to work:\n")[0].endswith(CUSTOMER_PRECEDENCE_TEXT)- assert with_precedence.replace(CUSTOMER_PRECEDENCE_TEXT, "", 1) == without- assert with_precedence.count(SENSITIVE_FIELD_STOP_CLAUSE) == 1- for other_arms_anchor in (- SENSITIVE_FIELD_STOP_CLAUSE,- REQUIRED_FIELD_ANSWERS_ANCHOR,- SELF_SCREEN_ANCHOR,- CUSTOMER_PRECEDENCE_ANCHOR,- ):- assert other_arms_anchor not in CUSTOMER_PRECEDENCE_TEXT--@pytest.mark.asyncioasync def test_customer_precedence_keeps_page_text_out_of_the_users_reach() -> None:# Security-critical wording, so pinned exactly: page text never becomes the user's instruction, and the twodiff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.pyindex 253569be1..98b9a8552 100644--- a/tests/unit/test_taskv3_tools.py+++ b/tests/unit/test_taskv3_tools.py@@ -75,6 +75,7 @@ from skyvern.forge.taskv3.tools import (_TYPE_TARGET_PROBE_JS,NAVIGATION_DEAD_END_STATUSES,OBSERVE_DISPLAY_WIDTHS,+ OBSERVE_POINTER_ROOT_CAP,OBSERVE_RETAIN_WIDTH_MIN,OBSERVE_SELECTED_OPTIONS_TOTAL_CAP,PAGE_UNAVAILABLE_ERROR,@@ -10823,13 +10824,15 @@ async def test_observe_lists_delegated_pointer_div_trigger_and_its_menu_is_reach@_skip_no_browser@pytest.mark.asyncio-async def test_observe_pointer_roots_skip_inherited_children_wrappers_of_controls_and_unnamed_boxes() -> None:+async def test_observe_pointer_roots_skip_inherited_and_unnamed_boxes_and_list_a_holders_free_child() -> None:html = ("<!doctype html><html><body>"'<div style="cursor:pointer;width:300px"><span style="display:inline-block">Inherited child</span>'" Pointer root</div>"'<div style="cursor:pointer;width:300px"><button type="button">Real button</button>'"<span>Wrapper text</span></div>"+ '<div style="cursor:pointer;width:300px"><span aria-hidden="true">receipt_long</span><span>Record 7</span>'+ "<button>Pay</button></div>"'<div style="cursor:pointer;width:40px;height:40px"></div>''<label style="cursor:pointer"><input type="checkbox"><span>Accept</span></label>''<p style="width:220px;font:16px/20px sans-serif">Please read our full <span style="cursor:pointer">'@@ -10858,7 +10861,10 @@ async def test_observe_pointer_roots_skip_inherited_children_wrappers_of_controlinherited = [line for line in ref_lines if "Inherited child" in line]assert len(inherited) == 1 and "div 'Inherited child Pointer root'" in inherited[0], ref_linesassert any("button 'Real button'" in line for line in ref_lines)- assert not any("Wrapper text" in line for line in ref_lines)+ # A pointer box holding a control is not listed, but its control-free pointer child is.+ assert any("span 'Wrapper text'" in line for line in ref_lines), ref_lines+ assert any("span 'Record 7'" in line for line in ref_lines), ref_lines+ assert not any("receipt_long" in line for line in ref_lines), ref_linesassert any("input/checkbox 'Accept'" in line for line in ref_lines), ref_linesassert not any("span 'Accept'" in line for line in ref_lines), ref_linesassert any("span 'terms of use'" in line for line in ref_lines), ref_lines@@ -10868,7 +10874,7 @@ async def test_observe_pointer_roots_skip_inherited_children_wrappers_of_controlassert not any("Collapsed" in line for line in ref_lines), ref_linesyes = [line for line in ref_lines if "'Yes'" in line]assert len(yes) == 1 and "input/radio 'Yes'" in yes[0], ref_lines- assert len(ref_lines) == 11, ref_lines+ assert len(ref_lines) == 14, ref_lines# A pointer control the reading drops does not stand in for its visible child.html = (@@ -10981,6 +10987,29 @@ async def test_observe_pointer_root_cap_is_page_wide_and_never_costs_a_frames_fiassert await page.evaluate("() => window.__saved") == 1+@_skip_no_browser+async def test_observe_holder_stand_ins_never_displace_a_frames_pointer_roots_or_exceed_the_cap() -> None:+ # The page's 30 holder rows and 5 plain roots fit its own cap; with the frame's 15 tiles the page-wide+ # cap still holds, and the rows' stand-ins are what give way.+ rows = "".join(+ f'<div style="cursor:pointer;width:300px"><span>Row {i}</span><button type="button">Pay {i}</button></div>'+ for i in range(30)+ )+ plain = "".join(f'<div style="cursor:pointer;width:200px">Plain {i}</div>' for i in range(5))+ tiles = "".join(f"<div style='cursor:pointer;width:100px'>Tile {i}</div>" for i in range(15))+ html = f'<!doctype html><html><body>{rows}{plain}<iframe srcdoc="{tiles}" width="300" height="400"></iframe></body></html>'+ async with _live_page(html) as page:+ r = await _tool(build_browser_tools(_fixed_page_provider(page)), "observe").handler({})+ assert r.status == "ok"+ ref_lines = [line for line in r.content.splitlines() if line.startswith("ref=")]+ for name in [f"Plain {i}" for i in range(5)] + [f"Tile {i}" for i in range(15)]:+ assert any(f"div '{name}'" in line for line in ref_lines), (name, ref_lines)+ pointer_lines = [line for line in ref_lines if re.match(r"^ref=\d+ (?:div|span) ", line)]+ assert len(pointer_lines) == OBSERVE_POINTER_ROOT_CAP, pointer_lines+ assert sum("'Pay " in line for line in ref_lines) == 30, ref_lines++@_skip_no_browser@pytest.mark.asyncioasync def test_dom_self_mutating_row_text_is_not_commit_evidence() -> None:@@ -34287,6 +34316,24 @@ def test_merging_caps_elements_page_wide_and_counts_what_it_dropped() -> None:assert page["mergeCapDropped"] == 2+def test_a_holders_stand_in_children_never_displace_another_frames_pointer_roots() -> None:+ # The page lists 5 plain pointer roots and 30 holder rows' stand-in children (35 fit its own cap); a+ # frame lists 15 pointer tiles. Every plain root and tile keeps its place, and the rows share what is left.+ from skyvern.forge.taskv3.tools import OBSERVE_POINTER_ROOT_CAP, _merge_realm, _rank_held_pointer_roots_last++ plain = [{"pointerRoot": True, "plain": n} for n in range(5)]+ held = [{"pointerRoot": True, "pointerHeld": True, "row": n} for n in range(30)]+ page = {"elements": plain + held, "text": [], "textFull": [], "pointerListed": 35}+ tiles = [{"pointerRoot": True, "tile": n} for n in range(15)]+ _merge_realm(page, {"elements": tiles, "text": [], "textFull": [], "pointerListed": 15})+ kept = _rank_held_pointer_roots_last(page)++ assert [e for e in page["elements"] if not e.get("pointerHeld")] == plain + tiles+ assert len(page["elements"]) == OBSERVE_POINTER_ROOT_CAP == len(kept)+ assert kept == list(range(25)) + list(range(35, 50))+ assert page["pointerCapped"] == 10 and page["pointerListed"] == OBSERVE_POINTER_ROOT_CAP++@pytest.mark.asyncioasync def test_the_download_notice_rebuild_keeps_every_field_the_inner_wrappers_set() -> None:# _apply_download_signal is the OUTERMOST wrapper on every tool, and when it has a notice to