Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(caching-v2): parameterize click prompts using workflow input params (SKY-9295) (#5689)
pedrohsdb7b64e724067f
diff --git a/skyvern/core/script_generations/generate_script.py b/skyvern/core/script_generations/generate_script.pyindex d069560c0..9bb13633b 100644--- a/skyvern/core/script_generations/generate_script.py+++ b/skyvern/core/script_generations/generate_script.py@@ -31,6 +31,7 @@ from skyvern.core.script_generations.parameter_reference_guard import (validate_context_parameter_refs,)from skyvern.forge import app+from skyvern.forge.sdk.workflow.models.parameter import is_sensitive_workflow_parameterfrom skyvern.schemas.workflows import FileStorageTypefrom skyvern.utils.strings import sanitize_identifierfrom skyvern.webeye.actions.action_types import ActionType@@ -89,6 +90,29 @@ def _collect_declared_param_keys(workflow: dict[str, Any]) -> frozenset[str]:return frozenset(keys)+def _collect_secret_param_keys(workflow: dict[str, Any]) -> frozenset[str]:+ """Return the set of parameter keys that carry credential/secret data.++ Routes each declared parameter through ``is_sensitive_workflow_parameter`` —+ the canonical filter that combines ``ParameterType.is_secret_or_credential``+ (aws_secret, bitwarden_*, onepassword, azure_*, credential) with the+ ``workflow_parameter_type=credential_id`` sub-check. Used by+ ``_build_value_to_param_lookup`` to skip emitting ``context.parameters[key]``+ references that would leak secret indirection into persisted prompts.+ """+ keys: set[str] = set()+ defn = workflow.get("workflow_definition") or {}+ if not isinstance(defn, dict):+ return frozenset()+ for param in defn.get("parameters") or []:+ if not isinstance(param, dict):+ continue+ key = param.get("key")+ if key and is_sensitive_workflow_parameter(param):+ keys.add(key)+ return frozenset(keys)++def _collect_upstream_schema_keys(blocks: list[dict[str, Any]]) -> frozenset[str]:"""Return the set of keys introduced by upstream blocks' data_schema.@@ -353,9 +377,17 @@ DOUBLE_INDENT = " " * 8# Short values (e.g. "1", "No", "CA") cause too many false-positive replacements.MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB = 4+# Maximum length. Prevents oversized values (multi-KB JSON payloads, long blobs)+# from being scanned against every prompt; values longer than this would never+# legitimately appear verbatim in a click prompt anyway.+MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB = 500+def _build_value_to_param_lookup(actions_by_task: dict[str, list[dict[str, Any]]],+ workflow_parameters: dict[str, Any] | None = None,+ declared_keys: frozenset[str] | None = None,+ secret_param_keys: frozenset[str] | None = None,) -> dict[str, str]:"""Build a mapping from literal action values to their parameter field names.@@ -365,10 +397,30 @@ def _build_value_to_param_lookup(that click-prompt generation can replace matching literals with``context.parameters['field_name']`` f-string references.- The returned dict is sorted by *descending value length* so that callers who- iterate in order will replace longer matches first, avoiding partial collisions.+ When ``workflow_parameters`` is provided (the run's workflow-level input params),+ its values are also added to the lookup keyed by the parameter name. This catches+ run-specific values that the agent embedded directly in click prompts (e.g.+ ``"Should I download the invoice for account 51410020?"`` where ``51410020``+ came from the ``account_number`` parameter, not from an input_text action).++ ``secret_param_keys`` (sourced from ``ParameterType.is_secret_or_credential`` and+ ``WorkflowParameterType.is_credential_type``) filters out credential/secret param+ keys structurally — substituting ``context.parameters['password']`` into a click+ prompt would leak the indirection. ``declared_keys`` restricts emitted keys to+ those declared in the workflow definition; an undeclared key would crash the+ cached script at runtime when ``context.parameters[...]`` raises ``KeyError``.++ First-writer-wins on duplicate values: action-level field_names are added first+ (more specific — tied to a page interaction); workflow-param keys only fill gaps.+ The rare case of two distinct keys legitimately sharing one value silently picks+ the first writer; downstream reviewer flow re-validates and can correct if the+ pick is wrong.++ The returned dict is sorted by *descending value length* so callers who iterate+ in order replace longer matches first, avoiding partial collisions."""raw: dict[str, str] = {}+for _task_id, actions in actions_by_task.items():for action in actions:field_name = action.get("field_name")@@ -383,11 +435,36 @@ def _build_value_to_param_lookup(value = action.get("option", "")else:continue- if value and len(value) >= MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB:- # First writer wins — the field-level name is more specific than a- # workflow-level parameter that may happen to share the same value.- if value not in raw:- raw[value] = field_name+ if not value:+ continue+ if len(value) < MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB or len(value) > MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB:+ continue+ if value.startswith("cred_"):+ continue+ raw.setdefault(value, field_name)++ if workflow_parameters:+ for param_key, param_value in workflow_parameters.items():+ # Distinguish "no value" (None / empty string) from legitimate falsy+ # values that could appear verbatim in a click prompt — e.g. a+ # boolean param ``auto_renew=False`` referenced in a prompt like+ # ``"Confirm auto-renew is False"``. ``0`` is still skipped by the+ # min-length floor below (``str(0)`` is 1 char).+ if param_value is None or param_value == "":+ continue+ if secret_param_keys and param_key in secret_param_keys:+ continue+ if declared_keys is not None and param_key not in declared_keys:+ continue+ value_str = str(param_value)+ if (+ len(value_str) < MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB+ or len(value_str) > MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB+ ):+ continue+ if value_str.startswith("cred_"):+ continue+ raw.setdefault(value_str, param_key)# Sort by descending value length so longer matches are attempted first.return dict(sorted(raw.items(), key=lambda kv: len(kv[0]), reverse=True))@@ -2933,6 +3010,7 @@ async def generate_workflow_script_python_code(# LLM inventing names.declared_keys = _collect_declared_param_keys(workflow)upstream_keys = _collect_upstream_schema_keys(blocks)+ secret_param_keys = _collect_secret_param_keys(workflow)goal_template_by_task = _collect_goal_templates(blocks)generated_schema, field_mappings = await generate_workflow_parameters_schema(actions_by_task,@@ -2945,7 +3023,15 @@ async def generate_workflow_script_python_code(# Build a lookup from literal parameter values to field names so that click# prompt strings can be parameterized (e.g. patient ID → context.parameters[...]).- value_to_param = _build_value_to_param_lookup(actions_by_task)+ # Pass the run's workflow-level input parameters too so click-prompt literals+ # like "for account 51410020" get substituted with context.parameters[...]+ # references at generation time, not baked in run-specifically.+ value_to_param = _build_value_to_param_lookup(+ actions_by_task,+ workflow_parameters=workflow_run_request.get("parameters") if workflow_run_request else None,+ declared_keys=declared_keys,+ secret_param_keys=secret_param_keys,+ )# --- class + cached params -----------------------------------------model_cls = _build_model(workflow)diff --git a/skyvern/forge/sdk/routes/scripts.py b/skyvern/forge/sdk/routes/scripts.pyindex a6afed7e9..3beb80d6d 100644--- a/skyvern/forge/sdk/routes/scripts.py+++ b/skyvern/forge/sdk/routes/scripts.py@@ -41,7 +41,7 @@ from skyvern.schemas.scripts import (WorkflowScriptSummary,)from skyvern.services import script_service, workflow_script_service-from skyvern.services.script_reviewer import ScriptReviewer, store_review_artifacts+from skyvern.services.script_reviewer import ScriptReviewer, load_filtered_run_param_values, store_review_artifactsfrom skyvern.services.workflow_script_service import (create_script_version_from_review,extract_cached_blocks_from_source,@@ -1343,19 +1343,7 @@ async def review_script_with_instructions(page=1,page_size=50,)- try:- run_param_tuples = await app.DATABASE.workflow_runs.get_workflow_run_parameters(- workflow_run_id=data.workflow_run_id,- )- for wf_param, run_param in run_param_tuples:- if (- run_param.value is not None- and str(run_param.value).strip()- and not wf_param.parameter_type.is_secret_or_credential()- ):- run_parameter_values[wf_param.key] = str(run_param.value)- except Exception:- LOG.warning("Failed to load run parameter values", exc_info=True)+ run_parameter_values = await load_filtered_run_param_values(data.workflow_run_id)# Fall back to any published script if run-specific lookup didn't find oneif not latest_script:diff --git a/skyvern/forge/sdk/workflow/models/parameter.py b/skyvern/forge/sdk/workflow/models/parameter.pyindex 8bac9d821..897b06fdb 100644--- a/skyvern/forge/sdk/workflow/models/parameter.py+++ b/skyvern/forge/sdk/workflow/models/parameter.py@@ -241,6 +241,38 @@ class WorkflowParameterType(StrEnum):raise InvalidWorkflowParameter(expected_parameter_type=self, value=str(value))+def is_sensitive_workflow_parameter(param: dict[str, Any] | Parameter) -> bool:+ """Return True if a workflow parameter carries credential/secret data.++ Accepts either a parameter dict (workflow-definition shape, used by the+ script generator) or a typed ``Parameter`` object (loaded from DB tuples,+ used by the reviewer). Single source of truth for sensitive-parameter+ filtering across both paths — combines ``ParameterType.is_secret_or_credential``+ with the ``workflow_parameter_type==credential_id`` sub-check.+ """+ if isinstance(param, dict):+ ptype: Any = param.get("parameter_type")+ sub: Any = param.get("workflow_parameter_type")+ else:+ ptype = getattr(param, "parameter_type", None)+ sub = getattr(param, "workflow_parameter_type", None)++ if ptype is not None:+ try:+ if ParameterType(ptype).is_secret_or_credential():+ return True+ except (ValueError, TypeError):+ pass+ if ptype == ParameterType.WORKFLOW.value or ptype == ParameterType.WORKFLOW:+ if sub is not None:+ try:+ if WorkflowParameterType(sub).is_credential_type():+ return True+ except (ValueError, TypeError):+ pass+ return False++class WorkflowParameter(Parameter):parameter_type: Literal[ParameterType.WORKFLOW] = ParameterType.WORKFLOWdiff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 21d178f98..fa043944a 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -6268,7 +6268,15 @@ class WorkflowService:historical_episodes: list | None = None,) -> None:"""Run the AI Script Reviewer and create a new script version if successful."""- from skyvern.services.script_reviewer import BlockReviewResult, ScriptReviewer, store_review_artifacts+ # Imports are method-local to defer the script_reviewer module load to+ # the rare path where the reviewer is actually triggered (most workflow+ # runs never invoke it). Pre-existing convention in this method.+ from skyvern.services.script_reviewer import (+ BlockReviewResult,+ ScriptReviewer,+ load_filtered_run_param_values,+ store_review_artifacts,+ )from skyvern.services.workflow_script_service import create_script_version_from_reviewLOG.info(@@ -6283,22 +6291,9 @@ class WorkflowService:reviewer = ScriptReviewer()# Load the workflow run's parameter values so the reviewer can detect- # hardcoded values in generated code (e.g., a customer email that should- # use context.parameters['recipient'] instead of a literal string).- run_parameter_values: dict[str, str] = {}- try:- run_param_tuples = await app.DATABASE.workflow_runs.get_workflow_run_parameters(- workflow_run_id=workflow_run.workflow_run_id,- )- for wf_param, run_param in run_param_tuples:- if (- run_param.value is not None- and str(run_param.value).strip()- and not wf_param.parameter_type.is_secret_or_credential()- ):- run_parameter_values[wf_param.key] = str(run_param.value)- except Exception:- LOG.debug("Failed to load run parameter values for hardcoded-value check", exc_info=True)+ # hardcoded values in generated code. The shared loader filters+ # secret/credential params before passing to the validator.+ run_parameter_values = await load_filtered_run_param_values(workflow_run.workflow_run_id)# Split episodes by type: regular fallback vs conditional_agentregular_episodes = [ep for ep in episodes if ep.fallback_type != "conditional_agent"]diff --git a/skyvern/services/script_reviewer.py b/skyvern/services/script_reviewer.pyindex bd66a3bb1..04ed87f2c 100644--- a/skyvern/services/script_reviewer.py+++ b/skyvern/services/script_reviewer.py@@ -9,13 +9,54 @@ from typing import Literal, Sequenceimport libcst as cstimport structlog+from skyvern.core.script_generations.generate_script import (+ MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB,+ MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB,+)from skyvern.forge import appfrom skyvern.forge.prompts import prompt_enginefrom skyvern.forge.sdk.workflow.models.block import get_all_blocks+from skyvern.forge.sdk.workflow.models.parameter import is_sensitive_workflow_parameterfrom skyvern.schemas.scripts import ScriptBranchHit, ScriptFallbackEpisodeLOG = structlog.get_logger()+# A literal qualifies for substring-match (vs exact-match) only if it has+# whitespace AND is at least 8 characters long. Whitespace is the primary+# discriminator (structural Python identifiers — dict keys, kwargs, status+# enums — never contain whitespace); the length floor only suppresses+# trivially-short whitespace-bearing strings.+PROSE_LITERAL_MIN_LEN = 8+++async def load_filtered_run_param_values(workflow_run_id: str) -> dict[str, str]:+ """Load run-parameter values for the reviewer's hardcoded-value detector.++ Pipeline: fetch ``(WorkflowParameter, RunParameter)`` tuples from the DB,+ drop secret/credential params via the unified ``is_sensitive_workflow_parameter``+ helper, return ``{key -> value}``. Never raises (DB errors are logged and+ swallowed so the reviewer flow continues).+ """+ try:+ param_tuples = await app.DATABASE.workflow_runs.get_workflow_run_parameters(+ workflow_run_id=workflow_run_id,+ )+ except Exception:+ LOG.warning(+ "Failed to load run parameter values",+ workflow_run_id=workflow_run_id,+ exc_info=True,+ )+ return {}+ result: dict[str, str] = {}+ for wf_param, run_param in param_tuples:+ if run_param.value is None or not str(run_param.value).strip():+ continue+ if is_sensitive_workflow_parameter(wf_param):+ continue+ result[wf_param.key] = str(run_param.value)+ return result+@dataclasses.dataclass(frozen=True)class BlockReviewResult:@@ -182,24 +223,10 @@ class ScriptReviewer:if historical_episodes:unique_run_ids = list({ep.workflow_run_id for ep in historical_episodes if ep.workflow_run_id})[:20]- async def _load_run_params(run_id: str) -> tuple[str, dict[str, str]]:- try:- param_tuples = await app.DATABASE.workflow_runs.get_workflow_run_parameters(workflow_run_id=run_id)- params = {- wf_param.key: str(run_param.value)- for wf_param, run_param in param_tuples- if run_param.value is not None- and str(run_param.value).strip()- and not wf_param.parameter_type.is_secret_or_credential()- }- return run_id, params- except Exception:- LOG.warning(- "Failed to load params for historical episode run", workflow_run_id=run_id, exc_info=True- )- return run_id, {}+ async def _load(run_id: str) -> tuple[str, dict[str, str]]:+ return run_id, await load_filtered_run_param_values(run_id)- results = await asyncio.gather(*[_load_run_params(rid) for rid in unique_run_ids])+ results = await asyncio.gather(*[_load(rid) for rid in unique_run_ids])historical_run_params = {rid: params for rid, params in results if params}# Triage failed episodes — skip non-code-fixable failures.@@ -1891,10 +1918,51 @@ class ScriptReviewer:and func.value.value == "page")- # Regex to extract string literals (single or double quoted, excluding escaped quotes).- # Uses separate alternations for single- and double-quoted strings to avoid- # backtracking ambiguity (CodeQL py/redos).- _STRING_LITERAL_RE: re.Pattern[str] = re.compile(r""""([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'""")+ @staticmethod+ def _collect_code_literals(code: str) -> tuple[set[str], set[str]]:+ """Walk ``code`` via libcst and return ``(exact_literals, prose_literals)``.++ Handles single-, double-, and triple-quoted ``cst.SimpleString`` nodes via+ ``evaluated_value``; for ``cst.FormattedString`` (f-strings) concatenates+ the text segments and skips interpolation expressions (their values come+ from ``context.parameters[...]`` at runtime, not from literals). Comments+ are automatically excluded — libcst doesn't expose them as strings.++ On parse failure (the LLM emitted broken Python), returns empty sets so+ the validator skips silently rather than crashing the review pipeline.+ """+ exact: set[str] = set()+ prose: set[str] = set()+ try:+ module = cst.parse_module(code)+ except cst.ParserSyntaxError:+ return exact, prose++ def _add(value: str) -> None:+ if not value:+ return+ exact.add(value)+ if len(value) >= PROSE_LITERAL_MIN_LEN and any(c.isspace() for c in value):+ prose.add(value)++ class _Collector(cst.CSTVisitor):+ def visit_SimpleString(self, node: cst.SimpleString) -> None:+ try:+ value = node.evaluated_value+ except Exception:+ return+ if isinstance(value, str):+ _add(value)++ def visit_FormattedString(self, node: cst.FormattedString) -> bool:+ # Concatenate the f-string's text parts only. Interpolation+ # expressions reference runtime values (``context.parameters[...]``),+ # not literals, so we skip them by returning False (no recursion).+ _add("".join(part.value for part in node.parts if isinstance(part, cst.FormattedStringText)))+ return False++ module.visit(_Collector())+ return exact, prosedef _validate_no_hardcoded_values(self,@@ -1904,34 +1972,36 @@ class ScriptReviewer:"""Detect hardcoded parameter values in generated code.Checks if any workflow parameter value from the current run appears as a- string literal in the code. This catches cases where the LLM copies a- run-specific value (e.g., a customer email) instead of referencing- context.parameters['key'].-- Returns an error message or None if no hardcoded values are found.+ string literal in the code. Catches cases where the LLM copies a run-+ specific value (e.g., a customer email) instead of referencing+ ``context.parameters['key']``.++ Two match modes minimize false positives:+ - **exact match** runs against every string literal — catches cases where+ the value is the entire literal (``selector="invoice_12345"``).+ - **substring match** runs only against *prose* literals (whitespace ++ ≥ ``PROSE_LITERAL_MIN_LEN`` chars) — catches values embedded inside+ longer click prompts (``"Should I download invoice 12345?"``) without+ falsely flagging short structural tokens like ``"next_block_label"``.++ Param values shorter than ``MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB`` or+ longer than ``MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB`` are skipped so the+ validator never flags values the generator wouldn't have parameterized.++ Returns an error message, or None if no hardcoded values are found."""if not run_parameter_values:return None- # Extract all string literals from non-comment lines- code_literals: set[str] = set()- for line in code.split("\n"):- stripped = line.lstrip()- if stripped.startswith("#"):- continue- for match in self._STRING_LITERAL_RE.finditer(line):- # group(1) = double-quoted content, group(2) = single-quoted content- literal_value = match.group(1) or match.group(2)- if literal_value:- code_literals.add(literal_value)+ exact_literals, prose_literals = self._collect_code_literals(code)hardcoded: list[tuple[str, str]] = []for param_key, param_value in run_parameter_values.items():- # Skip short values to avoid false positives (e.g., "yes", "true", "1")- if len(param_value) < 5:+ if len(param_value) < MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB:+ continue+ if len(param_value) > MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB:continue- # Check if the parameter value appears as a string literal- if param_value in code_literals:+ if param_value in exact_literals or any(param_value in literal for literal in prose_literals):hardcoded.append((param_key, param_value))if not hardcoded:diff --git a/tests/unit/test_click_prompt_parameterization.py b/tests/unit/test_click_prompt_parameterization.pyindex 1b8aceb50..fc3cbc36c 100644--- a/tests/unit/test_click_prompt_parameterization.py+++ b/tests/unit/test_click_prompt_parameterization.py@@ -15,7 +15,9 @@ from skyvern.core.script_generations.generate_script import (_action_to_stmt,_build_parameterized_prompt_cst,_build_value_to_param_lookup,+ _collect_secret_param_keys,)+from skyvern.forge.sdk.workflow.models.parameter import is_sensitive_workflow_parameterfrom skyvern.webeye.actions.actions import ActionType@@ -119,6 +121,11 @@ class TestBuildValueToParamLookup:assert keys == ["abcdefghij", "abcdef", "abcd"]def test_first_writer_wins_on_duplicate_values(self) -> None:+ """When two actions have the same text but different field_names, the+ first one wins. This is rare in practice (the LLM tagging the same value+ as two distinct concepts is unusual); silent wrong-binding for the+ second concept is acceptable risk vs the complexity of detecting and+ dropping the value."""actions_by_task = {"task-1": [_make_action(ActionType.INPUT_TEXT, field_name="first_field", text="same-value"),@@ -153,6 +160,196 @@ class TestBuildValueToParamLookup:lookup = _build_value_to_param_lookup({})assert lookup == {}+ # ------------------------------------------------------------------+ # SKY-9295: workflow input parameter values feed the lookup so click+ # prompts containing literal account numbers / dates / etc. get+ # parameterized at generation time instead of baked in run-specifically.+ # ------------------------------------------------------------------++ def test_collects_workflow_parameter_values(self) -> None:+ """Workflow input parameter values populate the lookup keyed by param name."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={+ "account_number": "51410020",+ "download_start_date": "12/8/2025",+ },+ )+ assert lookup == {"51410020": "account_number", "12/8/2025": "download_start_date"}++ def test_workflow_param_short_value_skipped(self) -> None:+ """Short param values (below MIN_PARAM_VALUE_LENGTH) don't pollute the lookup."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={"division": "0", "request_id": "1"},+ )+ assert lookup == {}++ def test_workflow_param_credential_reference_skipped(self) -> None:+ """Values starting with ``cred_`` are credential refs and must not be substituted."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={+ "credentials": "cred_520125108297961972",+ "account_number": "51410020",+ },+ )+ assert "cred_520125108297961972" not in lookup+ assert lookup == {"51410020": "account_number"}++ def test_workflow_param_falsy_value_skipped(self) -> None:+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={"empty_field": "", "null_field": None, "zero_field": 0},+ )+ assert lookup == {}++ def test_workflow_param_non_string_value_coerced(self) -> None:+ """Numeric / non-string param values get coerced to str before length check."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={"account_number": 51410020},+ )+ assert lookup == {"51410020": "account_number"}++ def test_action_field_name_wins_over_workflow_param(self) -> None:+ """When an action and a workflow param share a value, the action's field_name wins."""+ actions_by_task = {+ "task-1": [+ _make_action(ActionType.INPUT_TEXT, field_name="patient_id", text="542-641-668"),+ ]+ }+ lookup = _build_value_to_param_lookup(+ actions_by_task,+ workflow_parameters={"customer_ref": "542-641-668"},+ )+ assert lookup["542-641-668"] == "patient_id"++ def test_workflow_param_supplements_action_lookup(self) -> None:+ """Workflow-level params are ADDED on top of action-derived ones, not replacing."""+ actions_by_task = {+ "task-1": [+ _make_action(ActionType.INPUT_TEXT, field_name="username", text="[email protected]"),+ ]+ }+ lookup = _build_value_to_param_lookup(+ actions_by_task,+ workflow_parameters={"account_number": "51410020"},+ )+ assert lookup == {+ "[email protected]": "username",+ "51410020": "account_number",+ }++ def test_workflow_param_none_arg_preserves_old_behavior(self) -> None:+ """Passing workflow_parameters=None matches the pre-fix call signature."""+ actions_by_task = {+ "task-1": [+ _make_action(ActionType.INPUT_TEXT, field_name="patient_id", text="542-641-668"),+ ]+ }+ lookup = _build_value_to_param_lookup(actions_by_task, workflow_parameters=None)+ assert lookup == {"542-641-668": "patient_id"}++ def test_workflow_param_with_secret_param_keys_skipped(self) -> None:+ """Param keys flagged as secret/credential are skipped even if the value+ doesn't start with ``cred_`` (e.g. an azure_secret param whose runtime+ value is the resolved secret string)."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={+ "azure_password": "supersecret_value_98765",+ "account_number": "51410020",+ },+ secret_param_keys=frozenset({"azure_password"}),+ )+ assert "supersecret_value_98765" not in lookup+ assert lookup == {"51410020": "account_number"}++ def test_workflow_param_undeclared_key_skipped(self) -> None:+ """Param keys not declared in the workflow definition are dropped — emitting+ ``context.parameters[undeclared_key]`` would crash the cached script with+ KeyError at runtime."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={+ "account_number": "51410020",+ "rogue_key": "76543210",+ },+ declared_keys=frozenset({"account_number"}),+ )+ assert "76543210" not in lookup+ assert lookup == {"51410020": "account_number"}++ def test_workflow_param_declared_keys_none_skips_filter(self) -> None:+ """``declared_keys=None`` keeps the legacy permissive behavior — every key+ is allowed (used by paths that don't have access to the workflow definition)."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={"account_number": "51410020"},+ declared_keys=None,+ )+ assert lookup == {"51410020": "account_number"}++ def test_workflow_param_false_boolean_not_dropped(self) -> None:+ """A literal ``False`` is a legitimate prompt token (e.g. "auto-renew=False");+ the falsy guard must only drop ``None`` / empty-string, not all falsy values.+ Note: ``0`` is still skipped, but by the min-length floor (``str(0)`` is 1+ char), not by the falsy guard."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={"auto_renew": False},+ )+ assert lookup == {"False": "auto_renew"}++ def test_workflow_param_first_writer_wins_on_collision(self) -> None:+ """When two workflow params share the same value (rare in practice),+ the first key encountered wins. Silent wrong-binding for the other+ concept is acceptable vs the complexity of detecting + dropping."""+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={+ "recipient": "[email protected]",+ "customer_email": "[email protected]",+ "account_number": "51410020",+ },+ )+ assert lookup["[email protected]"] == "recipient"+ assert lookup["51410020"] == "account_number"++ def test_action_workflow_share_value_action_wins(self) -> None:+ """Action-vs-workflow precedence preserved: when an action's field_name+ and a workflow param key both bind to the same value, the action wins+ (more specific — tied to a specific page interaction)."""+ actions_by_task = {+ "task-1": [+ _make_action(ActionType.INPUT_TEXT, field_name="patient_id", text="542-641-668"),+ ]+ }+ lookup = _build_value_to_param_lookup(+ actions_by_task,+ workflow_parameters={"customer_ref": "542-641-668"},+ )+ assert lookup["542-641-668"] == "patient_id"++ def test_workflow_param_oversized_value_skipped(self) -> None:+ """Values longer than ``MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB`` (multi-KB+ JSON payloads, long blobs) are skipped — they would never legitimately+ appear verbatim in a click prompt and would blow up the per-action find+ loop in ``_build_parameterized_prompt_cst``."""+ from skyvern.core.script_generations.generate_script import MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB++ oversized = "x" * (MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB + 1)+ lookup = _build_value_to_param_lookup(+ {},+ workflow_parameters={+ "huge_payload": oversized,+ "account_number": "51410020",+ },+ )+ assert oversized not in lookup+ assert lookup == {"51410020": "account_number"}+# ---------------------------------------------------------------------------# _build_parameterized_prompt_cst@@ -175,7 +372,7 @@ class TestBuildParameterizedPromptCst:assert result is not Noneassert isinstance(result, cst.FormattedString)code = cst.Module(body=[]).code_for_node(result)- assert "context.parameters" in code+ assert "context.parameters" in code # nosemgrep: incomplete-url-substring-sanitizationassert "patient_id" in codeassert "542-641-668" not in code@@ -287,7 +484,7 @@ class TestActionToStmtClickParameterization:stmt = _action_to_stmt(act, task, value_to_param=value_to_param)code = self._render(stmt)- assert "context.parameters" in code+ assert "context.parameters" in code # nosemgrep: incomplete-url-substring-sanitizationassert "patient_id" in codeassert "542-641-668" not in code# Should be an f-string@@ -339,5 +536,131 @@ class TestActionToStmtClickParameterization:code = self._render(stmt)# Should use context.parameters via the field_name mechanism, not f-string- assert "context.parameters" in code+ assert "context.parameters" in code # nosemgrep: incomplete-url-substring-sanitizationassert "patient_id" in code+++# ---------------------------------------------------------------------------+# is_sensitive_workflow_parameter / _collect_secret_param_keys+# ---------------------------------------------------------------------------+++class TestIsSensitiveWorkflowParameter:+ def test_secret_credential_types_flagged(self) -> None:+ for ptype in (+ "aws_secret",+ "azure_secret",+ "credential",+ "onepassword",+ "azure_vault_credential",+ "bitwarden_login_credential",+ "bitwarden_sensitive_information",+ "bitwarden_credit_card_data",+ ):+ assert is_sensitive_workflow_parameter({"parameter_type": ptype, "key": "x"}), ptype++ def test_workflow_credential_id_flagged(self) -> None:+ """Workflow params declared with workflow_parameter_type=credential_id resolve+ to a credential at runtime — substituting their value into a prompt would+ leak the credential indirection."""+ assert is_sensitive_workflow_parameter(+ {"parameter_type": "workflow", "workflow_parameter_type": "credential_id", "key": "k"}+ )++ def test_regular_workflow_string_not_flagged(self) -> None:+ assert not is_sensitive_workflow_parameter(+ {"parameter_type": "workflow", "workflow_parameter_type": "string", "key": "x"}+ )++ def test_unknown_type_safely_ignored(self) -> None:+ assert not is_sensitive_workflow_parameter({"parameter_type": "not_a_real_type", "key": "x"})+ assert not is_sensitive_workflow_parameter({})++ def test_typed_credential_parameter_object_input(self) -> None:+ """Helper accepts a typed ``CredentialParameter`` object (not just a dict).+ Reviewer-side ingestion paths consume typed Parameter instances loaded+ from ``get_workflow_run_parameters`` tuples."""+ from datetime import datetime++ from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter++ param = CredentialParameter(+ credential_parameter_id="cp_1",+ workflow_id="w_1",+ credential_id="cred_abc",+ key="login",+ created_at=datetime(2026, 1, 1),+ modified_at=datetime(2026, 1, 1),+ )+ assert is_sensitive_workflow_parameter(param)++ def test_typed_aws_secret_parameter_object_input(self) -> None:+ from datetime import datetime++ from skyvern.forge.sdk.workflow.models.parameter import AWSSecretParameter++ param = AWSSecretParameter(+ aws_secret_parameter_id="asp_1",+ workflow_id="w_1",+ aws_key="some/aws/key",+ key="db_password",+ created_at=datetime(2026, 1, 1),+ modified_at=datetime(2026, 1, 1),+ )+ assert is_sensitive_workflow_parameter(param)++ def test_typed_workflow_parameter_credential_id(self) -> None:+ """Typed ``WorkflowParameter`` with ``workflow_parameter_type=CREDENTIAL_ID``+ resolves to a credential at runtime — must be flagged."""+ from datetime import datetime++ from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameter, WorkflowParameterType++ param = WorkflowParameter(+ workflow_parameter_id="wp_1",+ workflow_parameter_type=WorkflowParameterType.CREDENTIAL_ID,+ workflow_id="w_1",+ key="selected_credential",+ created_at=datetime(2026, 1, 1),+ modified_at=datetime(2026, 1, 1),+ )+ assert is_sensitive_workflow_parameter(param)++ def test_typed_workflow_parameter_string_not_flagged(self) -> None:+ from datetime import datetime++ from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameter, WorkflowParameterType++ param = WorkflowParameter(+ workflow_parameter_id="wp_1",+ workflow_parameter_type=WorkflowParameterType.STRING,+ workflow_id="w_1",+ key="account_number",+ created_at=datetime(2026, 1, 1),+ modified_at=datetime(2026, 1, 1),+ )+ assert not is_sensitive_workflow_parameter(param)+++class TestCollectSecretParamKeys:+ def test_collects_only_credential_keys(self) -> None:+ workflow = {+ "workflow_definition": {+ "parameters": [+ {"key": "account_number", "parameter_type": "workflow", "workflow_parameter_type": "string"},+ {"key": "login_creds", "parameter_type": "credential"},+ {"key": "vault", "parameter_type": "azure_vault_credential"},+ {+ "key": "selected_credential_id",+ "parameter_type": "workflow",+ "workflow_parameter_type": "credential_id",+ },+ ]+ }+ }+ keys = _collect_secret_param_keys(workflow)+ assert keys == frozenset({"login_creds", "vault", "selected_credential_id"})++ def test_returns_empty_when_no_definition(self) -> None:+ assert _collect_secret_param_keys({}) == frozenset()+ assert _collect_secret_param_keys({"workflow_definition": None}) == frozenset()diff --git a/tests/unit/test_script_reviewer_validators.py b/tests/unit/test_script_reviewer_validators.pyindex b4da5d7c4..90e6825f1 100644--- a/tests/unit/test_script_reviewer_validators.py+++ b/tests/unit/test_script_reviewer_validators.py@@ -1,5 +1,7 @@"""Tests for ScriptReviewer validation methods."""+import pytest+from skyvern.services.script_reviewer import ScriptReviewer@@ -37,7 +39,7 @@ async def block_fn(page, context):assert error is not Noneassert "hardcoded" in error.lower()assert "recipient" in error- assert "context.parameters" in error+ assert "context.parameters" in error # nosemgrep: incomplete-url-substring-sanitizationdef test_detects_hardcoded_url(self) -> None:"""Should catch a hardcoded URL that should be context.parameters['website_url']."""@@ -108,6 +110,222 @@ async def block_fn(page, context):params = {"account_number": "12345678"}assert self.reviewer._validate_no_hardcoded_values(code, params) is None+ # ------------------------------------------------------------------+ # SKY-9295: substring matching — param values often appear embedded+ # inside longer click-prompt literals like+ # prompt='Should I download invoice 12/8/2025 for account 51410020?'+ # rather than as standalone literals. Pre-fix the matcher used exact+ # set membership (`param_value in code_literals`) and missed these.+ # ------------------------------------------------------------------++ def test_detects_param_embedded_in_click_prompt(self) -> None:+ """Account number embedded inside a click prompt string should trigger."""+ code = """+async def download_invoice(page, context):+ await page.click(+ ai='fallback',+ prompt='Should I download the invoice dated 12/8/2025 for account 51410020?',+ )+"""+ params = {"account_number": "51410020", "download_start_date": "12/8/2025"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is not None+ assert "account_number" in error+ assert "download_start_date" in error++ def test_detects_single_param_embedded_in_prompt(self) -> None:+ """Validator catches a substring even when only one param value is embedded."""+ code = """+async def block_fn(page, context):+ await page.click(prompt='Find the row for vendor CITYO49057A and click it')+"""+ params = {"vendor_code": "CITYO49057A"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is not None+ assert "vendor_code" in error++ def test_substring_match_respects_short_value_guard(self) -> None:+ """Short param values still don't false-positive even with substring matching."""+ # "yes" appears inside "yesterday" but is below the 5-char length guard.+ code = """+async def block_fn(page, context):+ await page.click(prompt='Click the yesterday button')+"""+ params = {"flag": "yes"}+ assert self.reviewer._validate_no_hardcoded_values(code, params) is None++ def test_substring_match_skips_comments(self) -> None:+ """Embedded matches inside comments should still be ignored."""+ code = """+async def block_fn(page, context):+ # Note: 51410020 is the test account number for staging+ await page.click(prompt='Click the next button')+"""+ params = {"account_number": "51410020"}+ assert self.reviewer._validate_no_hardcoded_values(code, params) is None++ def test_substring_match_skips_structural_literals(self) -> None:+ """Substring matching only applies to prose literals (whitespace + ≥20 chars).+ A short structural token like ``'next_block_label'`` should not trigger a+ false positive when a param value happens to be embedded in the token."""+ code = """+async def block_fn(page, context):+ return {"next_block_label": "send_email", "branch_index": 0}+"""+ # "block" (5 chars) is a substring of "next_block_label" but+ # "next_block_label" is a structural keyword, not a prose literal — it+ # has no whitespace and is only 16 chars. The validator must ignore it.+ params = {"target": "block"}+ assert self.reviewer._validate_no_hardcoded_values(code, params) is None++ def test_validator_threshold_matches_generator_threshold(self) -> None:+ """Validator's minimum length must match the generator's substitution+ threshold (``MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB``). A 4-char value+ embedded in a prose literal is hardcoded and should be flagged."""+ from skyvern.core.script_generations.generate_script import MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB++ # Sanity: keep this test honest if the generator threshold ever changes.+ assert MIN_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB == 4++ # Embed "1234" in a prose literal (whitespace + > prose-min-len).+ code = """+async def block_fn(page, context):+ await page.click(prompt='Click the box labeled 1234 to continue')+"""+ params = {"order_code": "1234"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is not None+ assert "order_code" in error++ # ------------------------------------------------------------------+ # SKY-9295 v2: libcst-based literal extraction so triple-quoted f-strings+ # and other multiline prompts are no longer a blind spot.+ # ------------------------------------------------------------------++ def test_validator_catches_hardcoded_in_triple_quoted_prompt(self) -> None:+ """Generator emits triple-quoted f-strings when prompt content has+ newlines or quotes (generate_script.py:547-548). The pre-libcst regex+ scanner missed those. With libcst, literals from triple-quoted f-strings+ are visible to substring matching."""+ code = '''+async def block_fn(page, context):+ await page.click(+ ai='fallback',+ prompt=f"""Find the row for account 51410020+and click the download button""",+ )+'''+ params = {"account_number": "51410020"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is not None+ assert "account_number" in error++ def test_validator_catches_hardcoded_in_fstring_text_segment(self) -> None:+ """Static text segments of an f-string (between {expr} interpolations)+ are scannable; if a parameter value is baked into the text portion, the+ validator must flag it."""+ code = """+async def block_fn(page, context):+ name = context.parameters['name']+ await page.click(prompt=f'Send invoice 51410020 to {name}')+"""+ params = {"account_number": "51410020"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is not None+ assert "account_number" in error++ def test_validator_skips_fstring_interpolation_expression(self) -> None:+ """Interpolation expressions reference runtime values+ (``context.parameters[...]``), not literals — they shouldn't be scanned+ for hardcoded values. A reference to a key by string subscript inside+ an interpolation must NOT be flagged."""+ code = """+async def block_fn(page, context):+ await page.click(prompt=f"Send to {context.parameters['recipient']}")+"""+ params = {"recipient": "[email protected]"}+ # No literal contains "[email protected]"; only the interpolation+ # references the key. Validator must not false-positive.+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is None++ # ------------------------------------------------------------------+ # SKY-9295 v2: prose-literal threshold (whitespace + ≥ PROSE_LITERAL_MIN_LEN+ # chars). The floor is 8 (down from a stricter 20) so short embedded+ # prompts like ``'Click 51410020 now'`` are still caught.+ # ------------------------------------------------------------------++ def test_prose_literal_band_catches_embedded_value(self) -> None:+ """A short prose literal with whitespace catches an embedded param+ value via substring matching."""+ code = """+async def block_fn(page, context):+ await page.click(prompt='Click 51410020 now')+"""+ # "Click 51410020 now" = 18 chars, has whitespace, ≥ 8. Prose-eligible.+ params = {"account_number": "51410020"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is not None+ assert "account_number" in error++ def test_prose_literal_band_below_floor_skips(self) -> None:+ """Whitespace-bearing literals shorter than the prose floor are not+ eligible for substring matching (and exact-match still fails because+ the literal isn't equal to the param value)."""+ # "ok 1234" = 7 chars, < 8 → not prose; not equal to "1234" → not exact-match.+ code = """+async def block_fn(page, context):+ await page.click(prompt='ok 1234')+"""+ params = {"order_code": "1234"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is None++ def test_prose_literal_no_whitespace_skips(self) -> None:+ """Mid-length literals without whitespace are not prose — they're+ structural identifiers (``order_12345_id``, dict keys, etc.)."""+ code = """+async def block_fn(page, context):+ return {"order_12345_id": "value", "branch_index": 0}+"""+ params = {"order_id": "12345"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is None++ def test_prose_literal_band_exact_match_still_fires(self) -> None:+ """A param value that equals an entire short literal is still flagged+ via the exact-match path (which runs against every literal regardless+ of prose status)."""+ code = """+async def block_fn(page, context):+ await page.fill(selector="#code", value="12345")+"""+ params = {"order_code": "12345"}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is not None+ assert "order_code" in error++ # ------------------------------------------------------------------+ # SKY-9295 v2: MAX cap aligned with generator.+ # ------------------------------------------------------------------++ def test_validator_skips_oversized_param_values(self) -> None:+ """Param values longer than ``MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB``+ are skipped — the generator wouldn't have substituted them, so the+ validator must not flag them either (else generator/validator drift+ creates an unfixable diagnostic loop)."""+ from skyvern.core.script_generations.generate_script import MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB++ oversized = "x" * (MAX_PARAM_VALUE_LENGTH_FOR_PROMPT_SUB + 1)+ # Even though the literal contains the oversized value, it must be skipped.+ code = f'''+async def block_fn(page, context):+ note = "{oversized}"+'''+ params = {"huge_payload": oversized}+ error = self.reviewer._validate_no_hardcoded_values(code, params)+ assert error is None+class TestValidateParameterPreservation:"""Tests for _validate_parameter_preservation."""@@ -304,3 +522,111 @@ async def block_fn(page, context):assert error is not Noneassert "wrong_label" in errorassert "-1" in error+++class TestLoadFilteredRunParamValues:+ """Tests for load_filtered_run_param_values (shared loader for 3 reviewer ingestion sites)."""++ def _make_workflow_param(self, key: str) -> object:+ from datetime import datetime++ from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameter, WorkflowParameterType++ return WorkflowParameter(+ workflow_parameter_id=f"wp_{key}",+ workflow_parameter_type=WorkflowParameterType.STRING,+ workflow_id="w_1",+ key=key,+ created_at=datetime(2026, 1, 1),+ modified_at=datetime(2026, 1, 1),+ )++ def _make_credential_param(self, key: str) -> object:+ from datetime import datetime++ from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter++ return CredentialParameter(+ credential_parameter_id=f"cp_{key}",+ workflow_id="w_1",+ credential_id="cred_abc",+ key=key,+ created_at=datetime(2026, 1, 1),+ modified_at=datetime(2026, 1, 1),+ )++ async def _run_with_params(self, monkeypatch: object, param_tuples: list) -> dict[str, str]:+ from skyvern.services.script_reviewer import load_filtered_run_param_values++ async def fake_get(workflow_run_id: str) -> list:+ return param_tuples++ # Patch DATABASE.workflow_runs.get_workflow_run_parameters+ from skyvern.forge import app++ monkeypatch.setattr(app.DATABASE.workflow_runs, "get_workflow_run_parameters", fake_get) # type: ignore[attr-defined]+ return await load_filtered_run_param_values("wr_test")++ @pytest.mark.asyncio+ async def test_filters_sensitive_credential_param(self, monkeypatch: object) -> None:+ from types import SimpleNamespace++ wf_param_secret = self._make_credential_param("login")+ wf_param_normal = self._make_workflow_param("account_number")+ param_tuples = [+ (wf_param_secret, SimpleNamespace(value="cred_xyz")),+ (wf_param_normal, SimpleNamespace(value="51410020")),+ ]+ result = await self._run_with_params(monkeypatch, param_tuples)+ assert result == {"account_number": "51410020"}++ @pytest.mark.asyncio+ async def test_filters_credential_id_subtype(self, monkeypatch: object) -> None:+ from datetime import datetime+ from types import SimpleNamespace++ from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameter, WorkflowParameterType++ wf_param_credential_id = WorkflowParameter(+ workflow_parameter_id="wp_cred",+ workflow_parameter_type=WorkflowParameterType.CREDENTIAL_ID,+ workflow_id="w_1",+ key="selected_credential",+ created_at=datetime(2026, 1, 1),+ modified_at=datetime(2026, 1, 1),+ )+ wf_param_normal = self._make_workflow_param("account_number")+ param_tuples = [+ (wf_param_credential_id, SimpleNamespace(value="cred_abc")),+ (wf_param_normal, SimpleNamespace(value="51410020")),+ ]+ result = await self._run_with_params(monkeypatch, param_tuples)+ assert "selected_credential" not in result+ assert result == {"account_number": "51410020"}++ @pytest.mark.asyncio+ async def test_db_failure_returns_empty(self, monkeypatch: object) -> None:+ from skyvern.forge import app+ from skyvern.services.script_reviewer import load_filtered_run_param_values++ async def fake_get_raises(workflow_run_id: str) -> list:+ raise RuntimeError("DB connection lost")++ monkeypatch.setattr(app.DATABASE.workflow_runs, "get_workflow_run_parameters", fake_get_raises) # type: ignore[attr-defined]+ result = await load_filtered_run_param_values("wr_test")+ assert result == {}++ @pytest.mark.asyncio+ async def test_skips_blank_values(self, monkeypatch: object) -> None:+ from types import SimpleNamespace++ wf_param_a = self._make_workflow_param("blank")+ wf_param_b = self._make_workflow_param("none_val")+ wf_param_c = self._make_workflow_param("real")+ param_tuples = [+ (wf_param_a, SimpleNamespace(value=" ")), # whitespace-only+ (wf_param_b, SimpleNamespace(value=None)),+ (wf_param_c, SimpleNamespace(value="51410020")),+ ]+ result = await self._run_with_params(monkeypatch, param_tuples)+ assert result == {"real": "51410020"}