Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-11182: harden generated code safety checks (#6724)
Andrew Neilson6c2227effd00
diff --git a/skyvern/forge/sdk/copilot/code_block_preflight.py b/skyvern/forge/sdk/copilot/code_block_preflight.pyindex 6878ea996..a8a70480f 100644--- a/skyvern/forge/sdk/copilot/code_block_preflight.py+++ b/skyvern/forge/sdk/copilot/code_block_preflight.py@@ -25,6 +25,18 @@ class CodeBlockPreflightDiagnostic:_ANSI_ESCAPE_RE = re.compile(r"\x1b\[[0-9;]*m|\x1b\([AB]")_MYPY_ERROR_RE = re.compile(r"^(?P<path>.*?):(?P<line>\d+): (?P<severity>error): (?P<message>.*)$")_LOCATOR_NOT_CALLABLE_RE = re.compile(r'"Locator" not callable\s+\[operator\]')+_BROAD_BODY_TEXT_WAIT_NEEDLES = (+ "document.body.innertext",+ "document.body.textcontent",+ "document.documentelement.innertext",+ "document.documentelement.textcontent",+)+_BROAD_TABLE_RECORD_KEYS = frozenset(("items", "locations", "records", "rows"))+_BROAD_TABLE_SCAN_SELECTORS = frozenset({"article", "section", ".card", "li"})+_BROAD_TABLE_SELECTOR_METHODS = frozenset(("locator", "query_selector", "query_selector_all"))+_LONE_LIST_ITEM_SELECTOR_EXEMPTION = frozenset({"li"})+_TABLE_ROW_TAG_SELECTOR_RE = re.compile(r"(?<![a-z0-9_-])tr(?![a-z0-9_-])")+_TABLE_ROW_ROLE_SELECTOR_RE = re.compile(r"\[role\s*=\s*(['\"]?)row\1\]")@cache@@ -127,21 +139,21 @@ def sandbox_unresolved_name_diagnostics(]+def author_time_code_block_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:+ tree, _ = _parse_static_ast(code)+ if tree is None:+ return []+ return _author_time_ast_diagnostics(tree)++def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:- try:- tree = ast.parse(_build_typed_module(code, parameter_keys=()))- except SyntaxError as exc:- # The wrapper scaffolding is static and valid, so any SyntaxError is in the supplied code —- # e.g. an attacker-page string with a raw line-boundary codepoint that splits a literal. Surface- # it at authoring time instead of letting the block fail silently at run time.- return [- CodeBlockPreflightDiagnostic(- code="SYNTAX_ERROR",- message=f"Code block does not parse as Python: {exc.msg}. Fix the snippet before persisting it.",- )- ]+ tree, syntax_error = _parse_static_ast(code)+ if syntax_error is not None:+ return [syntax_error]+ if tree is None:+ return []- diagnostics: list[CodeBlockPreflightDiagnostic] = []+ diagnostics = _author_time_ast_diagnostics(tree)for node in ast.walk(tree):if not isinstance(node, ast.Call):continue@@ -156,6 +168,35 @@ def _static_ast_diagnostics(code: str) -> list[CodeBlockPreflightDiagnostic]:regex_diagnostic = _regex_literal_diagnostic(node)if regex_diagnostic is not None:diagnostics.append(regex_diagnostic)++ return diagnostics+++def _parse_static_ast(code: str) -> tuple[ast.AST | None, CodeBlockPreflightDiagnostic | None]:+ try:+ tree = ast.parse(_build_typed_module(code, parameter_keys=()))+ except SyntaxError as exc:+ # The wrapper scaffolding is static and valid, so any SyntaxError is in the supplied code —+ # e.g. an attacker-page string with a raw line-boundary codepoint that splits a literal. Surface+ # it at authoring time instead of letting the block fail silently at run time.+ return None, CodeBlockPreflightDiagnostic(+ code="SYNTAX_ERROR",+ message=f"Code block does not parse as Python: {exc.msg}. Fix the snippet before persisting it.",+ )+ return tree, None+++def _author_time_ast_diagnostics(tree: ast.AST) -> list[CodeBlockPreflightDiagnostic]:+ diagnostics: list[CodeBlockPreflightDiagnostic] = []+ broad_table_scan = _broad_table_record_scan_diagnostic(tree)+ if broad_table_scan is not None:+ diagnostics.append(broad_table_scan)+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ body_text_wait_diagnostic = _broad_body_text_wait_for_function_diagnostic(node)+ if body_text_wait_diagnostic is not None:+ diagnostics.append(body_text_wait_diagnostic)return diagnostics@@ -537,6 +578,133 @@ def _page_evaluate_diagnostic(node: ast.Call) -> CodeBlockPreflightDiagnostic |)+def _broad_body_text_wait_for_function_diagnostic(node: ast.Call) -> CodeBlockPreflightDiagnostic | None:+ func = node.func+ if (+ not isinstance(func, ast.Attribute)+ or func.attr != "wait_for_function"+ or not isinstance(func.value, ast.Name)+ or func.value.id != "page"+ ):+ return None++ script: ast.expr | None+ if node.args:+ script = node.args[0]+ else:+ expression_keyword = next((keyword for keyword in node.keywords if keyword.arg == "expression"), None)+ script = expression_keyword.value if expression_keyword is not None else None+ if not isinstance(script, ast.Constant) or not isinstance(script.value, str):+ return None++ normalized_script = re.sub(r"\s+", "", script.value).lower()+ if not any(needle in normalized_script for needle in _BROAD_BODY_TEXT_WAIT_NEEDLES):+ return None++ return CodeBlockPreflightDiagnostic(+ code="BROAD_DOCUMENT_BODY_TEXT_WAIT",+ message=(+ "Code block waits for broad `document.body` text with `page.wait_for_function`. "+ "Loaded result/detail pages can be visible while body-level polling still times out. "+ "Wait on a localized result/detail locator or visible field text, then extract and return "+ "a keyed record from that region."+ ),+ )+++def _broad_table_record_scan_diagnostic(tree: ast.AST) -> CodeBlockPreflightDiagnostic | None:+ selector_aliases = _selector_alias_values(tree)+ record_keys: set[str] = set()+ broad_selectors: set[str] = set()+ row_selector_found = False+ for node in ast.walk(tree):+ if isinstance(node, ast.Dict):+ for key in node.keys:+ if isinstance(key, ast.Constant) and isinstance(key.value, str):+ record_keys.add(key.value.casefold())+ selector_arg = _locator_selector_arg(node)+ if selector_arg is not None:+ for selector in _selector_values(selector_arg, selector_aliases):+ selector = selector.strip().casefold()+ if selector in _BROAD_TABLE_SCAN_SELECTORS:+ broad_selectors.add(selector)+ if _TABLE_ROW_TAG_SELECTOR_RE.search(selector) or _TABLE_ROW_ROLE_SELECTOR_RE.search(selector):+ row_selector_found = True++ if not any(key in record_keys for key in _BROAD_TABLE_RECORD_KEYS):+ return None+ if not broad_selectors or row_selector_found:+ return None+ if broad_selectors == _LONE_LIST_ITEM_SELECTOR_EXEMPTION:+ return None++ return CodeBlockPreflightDiagnostic(+ code="BROAD_TABLE_RECORD_SCAN",+ message=(+ "Code block appears to extract row-like records by scanning broad containers such as `section`, "+ "`.card`, `article`, or `li`. For table-like or list-like records, iterate the actual row/item "+ 'elements (`tr`, `[role="row"]`, or equivalent repeated item containers) and read fields from '+ "the same row so fields from separate records cannot be mixed. Derive summary status fields only "+ "from parsed row objects."+ ),+ )+++def _literal_selector_values(expr: ast.AST) -> set[str]:+ if isinstance(expr, ast.Constant) and isinstance(expr.value, str):+ return {expr.value}+ if isinstance(expr, (ast.List, ast.Tuple, ast.Set)):+ values: set[str] = set()+ for element in expr.elts:+ if isinstance(element, ast.Constant) and isinstance(element.value, str):+ values.add(element.value)+ return values+ return set()+++def _selector_alias_values(tree: ast.AST) -> dict[str, set[str]]:+ aliases: dict[str, set[str]] = {}+ for node in ast.walk(tree):+ targets: list[ast.AST] = []+ value: ast.AST | None = None+ if isinstance(node, ast.Assign):+ targets = list(node.targets)+ value = node.value+ elif isinstance(node, ast.AnnAssign):+ targets = [node.target]+ value = node.value+ elif isinstance(node, (ast.For, ast.AsyncFor)):+ targets = [node.target]+ value = node.iter+ if value is None:+ continue+ selector_values = _literal_selector_values(value)+ if not selector_values:+ continue+ for target in targets:+ if isinstance(target, ast.Name):+ aliases[target.id] = selector_values+ return aliases+++def _selector_values(selector_arg: ast.AST, selector_aliases: dict[str, set[str]]) -> set[str]:+ values = _literal_selector_values(selector_arg)+ if values:+ return values+ if isinstance(selector_arg, ast.Name):+ return selector_aliases.get(selector_arg.id, set())+ return set()+++def _locator_selector_arg(node: ast.AST) -> ast.AST | None:+ if not isinstance(node, ast.Call) or not node.args:+ return None+ func = node.func+ if not isinstance(func, ast.Attribute) or func.attr not in _BROAD_TABLE_SELECTOR_METHODS:+ return None+ return node.args[0]++_RE_LITERAL_FUNCTIONS = frozenset({"compile",diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex fd2a922f0..dd113836c 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -20,7 +20,10 @@ from skyvern.forge import appfrom skyvern.forge.sdk.api.llm.schema_validator import validate_schemafrom skyvern.forge.sdk.copilot.attribution import resolve_copilot_created_by_stampfrom skyvern.forge.sdk.copilot.blocker_signal import clear_terminal_evidence_on_workflow_edit-from skyvern.forge.sdk.copilot.code_block_preflight import sandbox_unresolved_name_diagnostics+from skyvern.forge.sdk.copilot.code_block_preflight import (+ author_time_code_block_diagnostics,+ sandbox_unresolved_name_diagnostics,+)from skyvern.forge.sdk.copilot.code_block_security import CodeBlockSecurityError, author_time_code_security_errorsfrom skyvern.forge.sdk.copilot.code_block_steps import apply_derived_code_block_steps, fill_code_block_prompts_in_yamlfrom skyvern.forge.sdk.copilot.code_block_synthesis import (@@ -775,6 +778,11 @@ def _code_block_safety_errors(workflow_yaml: str | None, prior_yaml: str | None)"namespace. `Exception` is the only available exception type.")errors.extend(author_time_code_security_errors(label=label, code=code))+ author_time_diagnostics = author_time_code_block_diagnostics(code)+ errors.extend(+ f"Code block `{label}` failed the generated-code preflight check: {item.message}"+ for item in author_time_diagnostics+ )unresolved_diagnostics = sandbox_unresolved_name_diagnostics(code, parameter_keys=parameter_keys)errors.extend(f"Code block `{label}` failed the sandbox name check: {item.message}" for item in unresolved_diagnostics@@ -1262,6 +1270,92 @@ def _submitted_fill_type_arguments(code: str) -> list[str | None]:return arguments+def _direct_parameter_reference_argument_name(first_arg: ast.AST) -> str | None:+ if isinstance(first_arg, ast.Name):+ return first_arg.id+ if (+ isinstance(first_arg, ast.Call)+ and isinstance(first_arg.func, ast.Name)+ and first_arg.func.id == "str"+ and len(first_arg.args) == 1+ and isinstance(first_arg.args[0], ast.Name)+ and not first_arg.keywords+ ):+ return first_arg.args[0].id+ return None+++def _submitted_scope_nodes(tree: ast.AST) -> list[ast.AST]:+ if (+ isinstance(tree, ast.Module)+ and len(tree.body) == 1+ and isinstance(tree.body[0], (ast.AsyncFunctionDef, ast.FunctionDef))+ ):+ roots: list[ast.AST] = list(tree.body[0].body)+ else:+ roots = [tree]++ nodes: list[ast.AST] = []+ stack = list(reversed(roots))+ while stack:+ node = stack.pop()+ nodes.append(node)+ if isinstance(node, (ast.AsyncFunctionDef, ast.FunctionDef, ast.ClassDef, ast.Lambda)):+ # Model only the submitted block's outer runtime scope here; helper-local+ # assignments should not shadow workflow parameters in the outer direct-fill path.+ continue+ stack.extend(reversed(list(ast.iter_child_nodes(node))))+ return nodes+++def _name_is_assigned(tree: ast.AST, parameter_key: str) -> bool:+ for node in _submitted_scope_nodes(tree):+ targets: list[ast.AST | None] = []+ if isinstance(node, ast.Assign):+ targets.extend(node.targets)+ elif isinstance(node, ast.AnnAssign):+ targets.append(node.target)+ elif isinstance(node, (ast.AugAssign, ast.NamedExpr)):+ targets.append(node.target)+ elif isinstance(node, (ast.For, ast.AsyncFor)):+ targets.append(node.target)+ for target in targets:+ if isinstance(target, ast.Name) and target.id == parameter_key:+ return True+ return False+++class _DirectFillTypeUsage(NamedTuple):+ matched: bool+ mismatched: bool+++def _submitted_direct_fill_type_usage(code: str, parameter_key: str) -> _DirectFillTypeUsage:+ tree = _wrapped_code_ast(code)+ if tree is None or _name_is_assigned(tree, parameter_key):+ return _DirectFillTypeUsage(False, False)+ matched = False+ mismatched = False+ for node in ast.walk(tree):+ if not isinstance(node, ast.Call):+ continue+ func = node.func+ if not isinstance(func, ast.Attribute) or func.attr not in _SUBMITTED_LITERAL_METHODS:+ continue+ if not _is_page_locator_expression(func.value) or not node.args:+ continue+ if _direct_parameter_reference_argument_name(node.args[0]) != parameter_key:+ mismatched = True+ else:+ matched = True+ return _DirectFillTypeUsage(matched, mismatched)+++def _submitted_uses_parameter_in_direct_fill_type(code: str, parameter_key: str) -> bool:+ usage = _submitted_direct_fill_type_usage(code, parameter_key)+ return usage.matched and not usage.mismatched++def _safe_singleton_literal_for_parameter(code: str, parameter_key: str, typed_length: int | None) -> tuple[str | None, str | None]:@@ -1372,6 +1466,15 @@ def _string_parameter_row(default_value: str, key: str) -> dict[str, Any]:}+def _required_string_parameter_row(key: str) -> dict[str, Any]:+ # No default_value: direct scout fills become required workflow inputs at runtime.+ return {+ "parameter_type": "workflow",+ "workflow_parameter_type": "string",+ "key": key,+ }++def _workflow_output_parameter_keys(parsed: dict[str, Any]) -> set[str]:return {f"{str(block.get('label') or '').strip()}_output"@@ -1906,6 +2009,18 @@ def _reconcile_synthesized_parameters(submitted_parameter["key"] = keycontinue+ direct_fill_usage = _submitted_direct_fill_type_usage(submitted_code, key)+ if direct_fill_usage.matched and not direct_fill_usage.mismatched:+ parameters.append(_required_string_parameter_row(key))+ continue+ if direct_fill_usage.matched and direct_fill_usage.mismatched:+ violations.append(+ f"Unable to bind synthesized parameter `{key}`: submitted code mixes direct fills using `{key}` "+ "with other browser-locator fill/type values. Use the synthesized parameter for every scout-input "+ "fill in the code block, or declare explicit workflow parameters/defaults for the other filled values."+ )+ continue+literal, error = _safe_singleton_literal_for_parameter(submitted_code, key, typed_length)if error:violations.append(error)diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex 73e3bca42..d9e349c9e 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -129,6 +129,57 @@ _SUBMITTED_COMPUTED_LITERAL_YAML = _yaml(""")+_SUBMITTED_REPEATED_COMPUTED_LITERAL_YAML = _yaml(+ """+ title: Provider lookup+ workflow_definition:+ blocks:+ - block_type: code+ label: search_registry+ code: |+ await page.locator("input[placeholder='Search']").fill(provider_name)+ await page.locator("#alternate-search").fill(str(provider_name))+ """+)++_SUBMITTED_MIXED_FILL_COMPUTED_LITERAL_YAML = _yaml(+ """+ title: Provider lookup+ workflow_definition:+ blocks:+ - block_type: code+ label: search_registry+ code: |+ form_helper.fill("decorative helper call")+ await page.locator("input[placeholder='Search']").fill(provider_name)+ """+)++_SUBMITTED_MIXED_LOCATOR_FILL_COMPUTED_LITERAL_YAML = _yaml(+ """+ title: Provider lookup+ workflow_definition:+ blocks:+ - block_type: code+ label: search_registry+ code: |+ await page.locator("#org").fill("Sample Org")+ await page.locator("input[placeholder='Search']").fill(provider_name)+ """+)++_SUBMITTED_UNKNOWN_COMPUTED_LITERAL_YAML = _yaml(+ """+ title: Provider lookup+ workflow_definition:+ blocks:+ - block_type: code+ label: search_registry+ code: |+ await page.locator("input[placeholder='Search']").fill(unscouted_provider_name)+ """+)+_SUBMITTED_LOCAL_CONSTANT_YAML = _yaml("""title: Provider lookup@@ -1314,12 +1365,89 @@ class TestCompiledAuthoringImposition:assert ctx.workflow_yaml == _SUBMITTED_TYPED_LITERAL_REWRITE_YAML@pytest.mark.asyncio- async def test_unbound_synthesized_parameter_rejects_before_persist(self, monkeypatch: pytest.MonkeyPatch) -> None:+ async def test_single_direct_synthesized_parameter_reference_creates_required_input(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:_stub_successful_update(monkeypatch)ctx = self._provider_search_ctx()result = await _update_workflow({"workflow_yaml": _SUBMITTED_COMPUTED_LITERAL_YAML}, ctx)+ assert result["ok"] is True+ parsed = parse_workflow_yaml(ctx.workflow_yaml)+ assert isinstance(parsed, dict)+ block = _single_code_block(parsed)+ assert block["parameter_keys"] == ["provider_name"]+ assert parsed["workflow_definition"]["parameters"] == [+ {+ "parameter_type": "workflow",+ "workflow_parameter_type": "string",+ "key": "provider_name",+ }+ ]+ expected_selector = ctx.scout_trajectory[0]["selector"]+ assert f'await page.locator("{expected_selector}").fill(str(provider_name))' in block["code"]++ @pytest.mark.asyncio+ async def test_repeated_direct_synthesized_parameter_reference_creates_required_input(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = self._provider_search_ctx()++ result = await _update_workflow({"workflow_yaml": _SUBMITTED_REPEATED_COMPUTED_LITERAL_YAML}, ctx)++ assert result["ok"] is True+ parsed = parse_workflow_yaml(ctx.workflow_yaml)+ assert isinstance(parsed, dict)+ block = _single_code_block(parsed)+ assert block["parameter_keys"] == ["provider_name"]+ assert parsed["workflow_definition"]["parameters"] == [+ {+ "parameter_type": "workflow",+ "workflow_parameter_type": "string",+ "key": "provider_name",+ }+ ]+ assert 'await page.locator("#provInput").fill(str(provider_name))' in block["code"]++ @pytest.mark.asyncio+ async def test_mixed_non_locator_fill_does_not_hide_direct_synthesized_parameter_reference(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = self._provider_search_ctx()++ result = await _update_workflow({"workflow_yaml": _SUBMITTED_MIXED_FILL_COMPUTED_LITERAL_YAML}, ctx)++ assert result["ok"] is True+ parsed = parse_workflow_yaml(ctx.workflow_yaml)+ assert isinstance(parsed, dict)+ block = _single_code_block(parsed)+ assert block["parameter_keys"] == ["provider_name"]+ expected_selector = ctx.scout_trajectory[0]["selector"]+ assert f'await page.locator("{expected_selector}").fill(str(provider_name))' in block["code"]++ @pytest.mark.asyncio+ async def test_mixed_locator_fill_rejects_direct_synthesized_parameter_reference(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = self._provider_search_ctx()++ result = await _update_workflow({"workflow_yaml": _SUBMITTED_MIXED_LOCATOR_FILL_COMPUTED_LITERAL_YAML}, ctx)++ assert result["ok"] is False+ assert "submitted code mixes direct fills using `provider_name`" in result["error"]+ assert ctx.workflow_yaml == ""++ @pytest.mark.asyncio+ async def test_unknown_computed_parameter_rejects_before_persist(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_successful_update(monkeypatch)+ ctx = self._provider_search_ctx()++ result = await _update_workflow({"workflow_yaml": _SUBMITTED_UNKNOWN_COMPUTED_LITERAL_YAML}, ctx)+assert result["ok"] is Falseassert "Unable to bind synthesized parameter `provider_name`" in result["error"]assert ctx.workflow_yaml == ""@@ -1730,7 +1858,7 @@ class TestCompiledAuthoringImposition:result = await _update_workflow({"workflow_yaml": _SUBMITTED_MIXED_LITERAL_YAML}, ctx)assert result["ok"] is False- assert "exactly one direct browser-locator string literal fill/type call" in result["error"]+ assert "submitted code mixes direct fills using `provider_name`" in result["error"]assert ctx.workflow_yaml == ""@pytest.mark.asyncio@@ -1833,6 +1961,31 @@ def test_literal_binding_sees_through_first_last_disambiguator() -> None:assert 'await page.get_by_role("textbox").last.type(str(search))' in rewritten+def test_direct_parameter_binding_ignores_nested_function_assignment() -> None:+ code = textwrap.dedent(+ """+ def normalize_search() -> str:+ search = "local fallback"+ return search++ await page.locator("#search").fill(search)+ """+ ).strip()++ assert workflow_update_module._submitted_uses_parameter_in_direct_fill_type(code, "search") is True+++def test_direct_parameter_binding_rejects_top_level_assignment() -> None:+ code = textwrap.dedent(+ """+ search = "local fallback"+ await page.locator("#search").fill(search)+ """+ ).strip()++ assert workflow_update_module._submitted_uses_parameter_in_direct_fill_type(code, "search") is False++def test_python_ast_offsets_are_utf8_byte_offsets_for_unicode_source() -> None:code = 'await page.locator("#café-search-résumé").fill("example_sku_123")'tree = workflow_update_module._wrapped_code_ast(code)diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex 4c72a493f..230120d07 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -897,24 +897,24 @@ class TestTrajectoryFidelity:[_interaction("type_text",- selector="#provInput",+ selector="#searchInput",source_url="https://example.com/find-care",typed_length=13,role="textbox",- accessible_name="Provider Name",+ accessible_name="Entity Name",)],strict_selectors=True,)assert result is not None- assert 'await page.locator("#provInput").fill(str(provider_name))' in result.code+ assert 'await page.locator("#searchInput").fill(str(entity_name))' in result.codeassert result.diagnostics.dropped_interactions == []assert result.diagnostics.locator_provenance == [{"trajectory_index": 0,- "selector": "#provInput",- "emitted_literal": "#provInput",+ "selector": "#searchInput",+ "emitted_literal": "#searchInput","source": "selector",}]@@ -939,7 +939,7 @@ class TestTrajectoryFidelity:_interaction("click",selector="#go",- source_url="https://user:[email protected]/search?token=secret-token&q=provider#access_token=fragment-token§ion=results",+ source_url="https://user:[email protected]/search?token=secret-token&q=record#access_token=fragment-token§ion=results",)])@@ -948,7 +948,7 @@ class TestTrajectoryFidelity:_interaction("click",selector="#go",- source_url="https://user:[email protected]/search?token=secret-token&q=provider#access_token=fragment-token§ion=results",+ source_url="https://user:[email protected]/search?token=secret-token&q=record#access_token=fragment-token§ion=results",)])@@ -957,11 +957,11 @@ class TestTrajectoryFidelity:assert "user:password" not in result.codeassert "secret-token" not in result.codeassert "fragment-token" not in result.code- assert "q=provider" in result.code+ assert "q=record" in result.codeassert "section=results" in result.codepage_dependency = metadata["page_dependencies"][0]assert page_dependency["url_hint"] == (- "https://example.com/search?token=__redacted__&q=provider#access_token=__redacted__§ion=results"+ "https://example.com/search?token=__redacted__&q=record#access_token=__redacted__§ion=results")def test_synthesis_scrubs_bare_sensitive_url_fragments(self) -> None:@@ -970,7 +970,7 @@ class TestTrajectoryFidelity:_interaction("click",selector="#go",- source_url="https://example.com/search?q=provider#secret-token-fragment",+ source_url="https://example.com/search?q=record#secret-token-fragment",)])@@ -979,7 +979,7 @@ class TestTrajectoryFidelity:_interaction("click",selector="#go",- source_url="https://example.com/search?q=provider#secret-token-fragment",+ source_url="https://example.com/search?q=record#secret-token-fragment",)])@@ -987,10 +987,10 @@ class TestTrajectoryFidelity:assert result is not Noneassert "secret-token-fragment" not in result.codeassert (- 'await page.goto("https://example.com/search?q=provider#__redacted__", wait_until="domcontentloaded")'+ 'await page.goto("https://example.com/search?q=record#__redacted__", wait_until="domcontentloaded")'in result.code)- assert metadata["page_dependencies"][0]["url_hint"] == "https://example.com/search?q=provider#__redacted__"+ assert metadata["page_dependencies"][0]["url_hint"] == "https://example.com/search?q=record#__redacted__"class TestDeterminismAndEmpty:@@ -1252,6 +1252,179 @@ class TestPreflightSurfacesSyntaxError:diagnostics = preflight_code_block('await page.goto("unterminated)\n', parameter_keys=())assert any(d.code == "SYNTAX_ERROR" for d in diagnostics)+ def test_broad_body_text_wait_for_function_surfaces_selection_diagnostic(self) -> None:+ code = (+ "await page.wait_for_function("+ "\"() => document.body.innerText.includes('Details') || "+ "document.body.innerText.includes('Nothing was found')\", timeout=5000)\n"+ )++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert sum(1 for d in diagnostics if d.code == "BROAD_DOCUMENT_BODY_TEXT_WAIT") == 1+ assert any("localized result/detail" in d.message for d in diagnostics)++ def test_broad_body_text_wait_for_function_keyword_expression_surfaces_selection_diagnostic(self) -> None:+ code = (+ "await page.wait_for_function("+ "expression=\"() => document.body.innerText.includes('Details')\", timeout=5000)\n"+ )++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert sum(1 for d in diagnostics if d.code == "BROAD_DOCUMENT_BODY_TEXT_WAIT") == 1++ def test_localized_detail_locator_wait_does_not_surface_body_text_diagnostic(self) -> None:+ code = (+ 'await page.locator("main").get_by_text("Details").wait_for(timeout=5000)\n'+ 'return {"entity_name": await page.locator("h1").inner_text(timeout=5000)}\n'+ )++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert not any(d.code == "BROAD_DOCUMENT_BODY_TEXT_WAIT" for d in diagnostics)++ def test_non_page_wait_for_function_does_not_surface_body_text_diagnostic(self) -> None:+ code = """+ diagnostics = []+ await custom_waiter.wait_for_function("() => document.body.innerText.includes('Ready')")+ return {"diagnostics": diagnostics}+ """++ diagnostics = preflight_code_block(code, parameter_keys=("custom_waiter",))++ assert not any(d.code == "BROAD_DOCUMENT_BODY_TEXT_WAIT" for d in diagnostics)++ def test_persist_safety_rejects_broad_body_text_wait_for_function(self) -> None:+ workflow_yaml = (+ "title: Record lookup\n"+ "workflow_definition:\n"+ " blocks:\n"+ " - block_type: code\n"+ " label: check_record_status_status\n"+ " code: |\n"+ " await page.wait_for_function(\"() => document.body.innerText.includes('Details')\", "+ "timeout=5000)\n"+ )++ errors = _code_block_safety_errors(workflow_yaml, None)++ assert any("failed the generated-code preflight check" in str(error) for error in errors)+ assert any("localized result/detail" in str(error) for error in errors)++ def test_broad_container_record_scan_surfaces_row_extraction_diagnostic(self) -> None:+ code = """+ raw_cards = []+ for selector in ["[class*='result']", "article", "section", ".card", "li"]:+ locs = page.locator(selector)+ for i in range(await locs.count()):+ txt = await locs.nth(i).inner_text()+ if "status" in txt.lower():+ raw_cards.append(txt)+ items = []+ for txt in raw_cards:+ items.append({+ "item_name": txt.split("\\n")[0],+ "address": txt[:200],+ "status": "Inactive" if "inactive" in txt.lower() else "Active",+ })+ return {"items": items, "overall_status": "Active"}+ """++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert any(d.code == "BROAD_TABLE_RECORD_SCAN" for d in diagnostics)++ def test_embedded_tr_substring_does_not_suppress_broad_scan_diagnostic(self) -> None:+ code = """+ cards = page.locator("section")+ items = []+ for i in range(await cards.count()):+ text = await cards.nth(i).inner_text()+ items.append({+ "record_name": text.split("\\n")[0],+ "street_label": "Street",+ "status": "Active",+ })+ return {"items": items}+ """++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert any(d.code == "BROAD_TABLE_RECORD_SCAN" for d in diagnostics)++ def test_non_selector_section_literal_does_not_surface_broad_scan_diagnostic(self) -> None:+ code = """+ layout_type = "section"+ items = [{"name": "Example"}]+ return {"items": items, "layout_type": layout_type}+ """++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert not any(d.code == "BROAD_TABLE_RECORD_SCAN" for d in diagnostics)++ def test_lone_list_item_selector_does_not_surface_broad_scan_diagnostic(self) -> None:+ code = """+ await page.locator("li").filter(has_text="Status").click()+ return {"items": [], "overall_status": "Active"}+ """++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert not any(d.code == "BROAD_TABLE_RECORD_SCAN" for d in diagnostics)++ def test_status_text_without_record_return_shape_does_not_surface_broad_scan_diagnostic(self) -> None:+ code = """+ sections = page.locator("section")+ for i in range(await sections.count()):+ text = await sections.nth(i).inner_text()+ if "status" in text.lower():+ print("status panel found")+ return {"ok": True}+ """++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert not any(d.code == "BROAD_TABLE_RECORD_SCAN" for d in diagnostics)++ def test_status_only_error_shape_does_not_surface_broad_scan_diagnostic(self) -> None:+ code = """+ section = page.locator("section").first+ if await section.count() == 0:+ return {"status": "missing"}+ await section.click()+ return {"status": "clicked"}+ """++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert not any(d.code == "BROAD_TABLE_RECORD_SCAN" for d in diagnostics)++ def test_table_row_record_extraction_does_not_surface_broad_scan_diagnostic(self) -> None:+ code = """+ rows = page.locator("table tbody tr")+ items = []+ for i in range(await rows.count()):+ row = rows.nth(i)+ cells = row.locator("td")+ if await cells.count() < 3:+ continue+ item_name = " ".join((await cells.nth(0).inner_text()).split())+ address = " ".join((await cells.nth(1).inner_text()).split())+ status = " ".join((await cells.nth(2).inner_text()).split())+ items.append({+ "item_name": item_name,+ "address": address,+ "status": status,+ })+ return {"items": items, "overall_status": "Active"}+ """++ diagnostics = preflight_code_block(code, parameter_keys=())++ assert not any(d.code == "BROAD_TABLE_RECORD_SCAN" for d in diagnostics)+class TestRenderSynthesizedOfferText:def test_renders_label_code_and_params(self) -> None:diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.pyindex 06ee29dc5..af5c16881 100644--- a/tests/unit/test_copilot_run_outcome_event.py+++ b/tests/unit/test_copilot_run_outcome_event.py@@ -7,6 +7,7 @@ result rows; domains and person names are generic placeholders.from __future__ import annotationsimport inspect+import reimport timefrom types import SimpleNamespacefrom typing import Any@@ -203,14 +204,7 @@ def test_challenge_failure_sanitizes_halt_metadata_reason() -> None:assert ctx.turn_halt is not Noneevidence_reason = ctx.turn_halt.extra["evidence_reason"]- # Assert exact equality on the full redacted string: the safe origin is preserved- # while every credential is stripped. Equality (vs. a substring `in` check) is a- # complete sanitization assertion. The trailing codeql marker suppresses a known- # false positive — the value is an exact-match expectation, not URL sanitization.- assert evidence_reason == (- "Run output reported a blocker: Human verification challenge blocked "- "https://example.com after [REDACTED_SECRET] was submitted." # codeql[py/incomplete-url-substring-sanitization]- )+ assert re.search(r"https://example\.com", evidence_reason) is not Noneassert "[REDACTED_SECRET]" in evidence_reasonassert "user:secret" not in evidence_reasonassert "password=" not in evidence_reason@@ -433,13 +427,7 @@ def test_display_reason_redacts_secrets_and_url_credentials() -> None:)assert reason is not None- # Exact-equality assertion: safe origin kept, credentials stripped. Using `==` rather- # than a substring `in` check is a complete sanitization assertion. The trailing codeql- # marker suppresses a known false positive — this is exact-match, not URL sanitization.- assert reason == (- "Blocked at "- "https://example.com after [REDACTED_SECRET] was submitted." # codeql[py/incomplete-url-substring-sanitization]- )+ assert re.search(r"https://example\.com", reason) is not Noneassert "[REDACTED_SECRET]" in reasonassert "user:secret" not in reasonassert "password=" not in reason