Skip to content

Automate browser based workflows with AI

Fix conditional block reviewer routing and add hardcoded value detection (#4949)

pedrohsdbdb7fcdd63762
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 450ea28a8..9db00614d 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -1334,12 +1334,18 @@ class WorkflowService:
except Exception:
LOG.debug("Failed to extract form field metadata for fallback episode", exc_info=True)
+ # Conditional blocks must use "conditional_agent" fallback type so the
+ # script reviewer routes them to the simpler conditional-specific prompt
+ # instead of the general reviewer (which would generate inappropriate
+ # browser-automation code like page.classify for pure-Python conditionals).
+ fallback_type = "conditional_agent" if isinstance(block, ConditionalBlock) else "full_block"
+
episode = await app.DATABASE.create_fallback_episode(
organization_id=organization_id,
workflow_permanent_id=workflow.workflow_permanent_id,
workflow_run_id=workflow_run_id,
block_label=block.label,
- fallback_type="full_block",
+ fallback_type=fallback_type,
script_revision_id=script_revision_id,
error_message=error_message[:2000],
classify_result=classify_result,
@@ -1952,9 +1958,12 @@ class WorkflowService:
# Record conditional episode so the script reviewer can learn the
# expression→result mapping and potentially convert it to Python code.
+ # This fires both when the block requires_agent (first run) and when
+ # cached code failed and agent fallback re-ran the conditional
+ # (fallback_episode_id is set when the script path failed).
if (
is_script_run
- and block_requires_agent
+ and (block_requires_agent or fallback_episode_id)
and workflow_run_block_result.status == BlockStatus.completed
and branch_metadata
and workflow.adaptive_caching
@@ -4610,6 +4619,20 @@ class WorkflowService:
try:
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.get_workflow_run_parameters(
+ workflow_run_id=workflow_run.workflow_run_id,
+ )
+ for wf_param, run_param in run_param_tuples:
+ if isinstance(run_param.value, str) and run_param.value:
+ run_parameter_values[wf_param.key] = run_param.value
+ except Exception:
+ LOG.debug("Failed to load run parameter values for hardcoded-value check", exc_info=True)
+
# Split episodes by type: regular fallback vs conditional_agent
regular_episodes = [ep for ep in episodes if ep.fallback_type != "conditional_agent"]
conditional_episodes = [ep for ep in episodes if ep.fallback_type == "conditional_agent"]
@@ -4626,6 +4649,7 @@ class WorkflowService:
episodes=regular_episodes,
stale_branches=stale_branches,
historical_episodes=historical_episodes,
+ run_parameter_values=run_parameter_values,
)
if regular_updates:
updated_blocks.update(regular_updates)
@@ -4636,6 +4660,7 @@ class WorkflowService:
organization_id=workflow.organization_id,
workflow_permanent_id=workflow.workflow_permanent_id,
conditional_episodes=conditional_episodes,
+ run_parameter_values=run_parameter_values,
)
if conditional_updates:
conditional_blocks.update(conditional_updates)
diff --git a/skyvern/services/script_reviewer.py b/skyvern/services/script_reviewer.py
index 0a507f9cd..25aff1f9e 100644
--- a/skyvern/services/script_reviewer.py
+++ b/skyvern/services/script_reviewer.py
@@ -79,6 +79,7 @@ class ScriptReviewer:
episodes: list[ScriptFallbackEpisode],
stale_branches: list[ScriptBranchHit] | None = None,
historical_episodes: list[ScriptFallbackEpisode] | None = None,
+ run_parameter_values: dict[str, str] | None = None,
) -> dict[str, str] | None:
"""Review fallback episodes and generate updated code for affected blocks.
@@ -149,6 +150,7 @@ class ScriptReviewer:
stale_branches=stale_by_block.get(block_label),
all_parameter_keys=all_parameter_keys,
historical_episodes=history_by_block.get(block_label),
+ run_parameter_values=run_parameter_values,
)
if updated_code:
updated_blocks[block_label] = updated_code
@@ -169,6 +171,7 @@ class ScriptReviewer:
organization_id: str,
workflow_permanent_id: str,
conditional_episodes: list[ScriptFallbackEpisode],
+ run_parameter_values: dict[str, str] | None = None,
) -> dict[str, str] | None:
"""Review conditional blocks that ran via agent and generate Python code if possible.
@@ -195,6 +198,7 @@ class ScriptReviewer:
block_label=block_label,
episode=episode,
organization_id=organization_id,
+ run_parameter_values=run_parameter_values,
)
if code:
updated_blocks[block_label] = code
@@ -211,6 +215,7 @@ class ScriptReviewer:
block_label: str,
episode: ScriptFallbackEpisode,
organization_id: str,
+ run_parameter_values: dict[str, str] | None = None,
) -> str | None:
"""Generate Python code for a conditional block based on its expression patterns.
@@ -301,6 +306,16 @@ class ScriptReviewer:
)
return None
+ # Validate no hardcoded parameter values
+ hardcoded_error = self._validate_no_hardcoded_values(code, run_parameter_values)
+ if hardcoded_error is not None:
+ LOG.warning(
+ "ScriptReviewer: conditional code has hardcoded parameter values",
+ block_label=block_label,
+ error=hardcoded_error,
+ )
+ return None
+
LOG.info(
"ScriptReviewer: generated conditional code",
block_label=block_label,
@@ -383,6 +398,7 @@ class ScriptReviewer:
stale_branches: list[ScriptBranchHit] | None = None,
all_parameter_keys: list[str] | None = None,
historical_episodes: list[ScriptFallbackEpisode] | None = None,
+ run_parameter_values: dict[str, str] | None = None,
) -> str | None:
"""Review a single block's fallback episodes and generate updated code."""
LOG.info(
@@ -644,6 +660,19 @@ class ScriptReviewer:
current_prompt = self._build_retry_prompt(updated_code, regression_error, function_signature)
continue
+ # Validate no hardcoded parameter values (catch leaked run-specific data)
+ hardcoded_error = self._validate_no_hardcoded_values(updated_code, run_parameter_values)
+ if hardcoded_error is not None:
+ LOG.warning(
+ "ScriptReviewer: hardcoded parameter value detected, retrying",
+ block_label=block_label,
+ attempt=attempt,
+ error=hardcoded_error,
+ )
+ if attempt < max_attempts:
+ current_prompt = self._build_retry_prompt(updated_code, hardcoded_error, function_signature)
+ continue
+
LOG.info(
"ScriptReviewer: generated updated code for block",
block_label=block_label,
@@ -1312,6 +1341,57 @@ class ScriptReviewer:
return None
+ # Regex to extract string literals (single or double quoted, excluding escaped quotes)
+ _STRING_LITERAL_RE: re.Pattern[str] = re.compile(r"""(?<![\\])(['"])((?:(?!\1)[^\\]|\\.)*)(\1)""")
+
+ def _validate_no_hardcoded_values(
+ self,
+ code: str,
+ run_parameter_values: dict[str, str] | None,
+ ) -> str | None:
+ """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.
+ """
+ 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):
+ literal_value = match.group(2)
+ if literal_value:
+ code_literals.add(literal_value)
+
+ 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:
+ continue
+ # Check if the parameter value appears as a string literal
+ if param_value in code_literals:
+ hardcoded.append((param_key, param_value))
+
+ if not hardcoded:
+ return None
+
+ examples = "; ".join(f"'{value[:50]}' should be context.parameters['{key}']" for key, value in hardcoded[:3])
+ return (
+ f"CRITICAL: Generated code contains hardcoded parameter values that are specific to this run. "
+ f"These values will break when the workflow runs with different parameters. "
+ f"Found {len(hardcoded)} hardcoded value(s): {examples}. "
+ f"Replace ALL hardcoded parameter values with context.parameters['key'] references."
+ )
+
def _auto_fix_missing_else(self, code: str, navigation_goal: str) -> str | None:
"""Auto-inject missing `else` branches after page.classify() if/elif chains.
diff --git a/tests/unit/test_script_reviewer_validators.py b/tests/unit/test_script_reviewer_validators.py
new file mode 100644
index 000000000..274bf043c
--- /dev/null
+++ b/tests/unit/test_script_reviewer_validators.py
@@ -0,0 +1,109 @@
+"""Tests for ScriptReviewer validation methods."""
+
+from skyvern.services.script_reviewer import ScriptReviewer
+
+
+class TestValidateNoHardcodedValues:
+ """Tests for _validate_no_hardcoded_values."""
+
+ def setup_method(self) -> None:
+ self.reviewer = ScriptReviewer()
+
+ def test_no_params_returns_none(self) -> None:
+ code = 'await page.click(selector="button")'
+ assert self.reviewer._validate_no_hardcoded_values(code, None) is None
+ assert self.reviewer._validate_no_hardcoded_values(code, {}) is None
+
+ def test_short_values_ignored(self) -> None:
+ """Values shorter than 5 chars should not trigger (too many false positives)."""
+ code = """
+async def block_fn(page, context):
+ if 'yes' == 'yes':
+ return {"next_block_label": "send_email", "branch_index": 0}
+"""
+ params = {"flag": "yes", "ok": "true"}
+ assert self.reviewer._validate_no_hardcoded_values(code, params) is None
+
+ def test_detects_hardcoded_email(self) -> None:
+ """Should catch a hardcoded email that should be context.parameters['recipient']."""
+ code = """
+async def block_fn(page, context):
+ recipient = '[email protected]'
+ if recipient != "":
+ return {"next_block_label": "send_email", "branch_index": 0}
+"""
+ params = {"recipient": "[email protected]"}
+ error = self.reviewer._validate_no_hardcoded_values(code, params)
+ assert error is not None
+ assert "hardcoded" in error.lower()
+ assert "recipient" in error
+ assert "context.parameters" in error
+
+ def test_detects_hardcoded_url(self) -> None:
+ """Should catch a hardcoded URL that should be context.parameters['website_url']."""
+ code = """
+async def login(page, context):
+ await page.goto('https://portal.vendor.com/login')
+ await page.fill(selector='input[name="email"]', value=context.parameters['email'])
+"""
+ params = {"website_url": "https://portal.vendor.com/login", "email": "[email protected]"}
+ error = self.reviewer._validate_no_hardcoded_values(code, params)
+ assert error is not None
+ assert "website_url" in error
+
+ def test_allows_context_parameters_reference(self) -> None:
+ """Using context.parameters['key'] should NOT trigger the validator."""
+ code = """
+async def block_fn(page, context):
+ recipient = context.parameters.get('recipient', '')
+ if recipient != "":
+ return {"next_block_label": "send_email", "branch_index": 0}
+"""
+ params = {"recipient": "[email protected]"}
+ assert self.reviewer._validate_no_hardcoded_values(code, params) is None
+
+ def test_allows_non_parameter_literals(self) -> None:
+ """String literals that aren't parameter values should be fine."""
+ code = """
+async def block_fn(page, context):
+ await page.click(selector='button:has-text("Sign in")', ai='fallback', prompt='Click sign in')
+"""
+ params = {"email": "[email protected]", "password": "secret123"}
+ assert self.reviewer._validate_no_hardcoded_values(code, params) is None
+
+ def test_ignores_comments(self) -> None:
+ """Values in comments should not trigger."""
+ code = """
+async def block_fn(page, context):
+ # [email protected] is the test email
+ recipient = context.parameters.get('recipient', '')
+ if recipient != "":
+ return {"next_block_label": "send_email", "branch_index": 0}
+"""
+ params = {"recipient": "[email protected]"}
+ assert self.reviewer._validate_no_hardcoded_values(code, params) is None
+
+ def test_detects_multiple_hardcoded_values(self) -> None:
+ """Should report multiple hardcoded values."""
+ code = """
+async def block_fn(page, context):
+ await page.goto('https://portal.vendor.com/login')
+ await page.fill(selector='input', value='[email protected]')
+"""
+ params = {
+ "website_url": "https://portal.vendor.com/login",
+ "recipient": "[email protected]",
+ }
+ error = self.reviewer._validate_no_hardcoded_values(code, params)
+ assert error is not None
+ assert "2 hardcoded" in error
+
+ def test_allows_block_labels_and_keywords(self) -> None:
+ """Common structural strings like block labels should not trigger."""
+ code = """
+async def block_fn(page, context):
+ return {"next_block_label": "send_email", "branch_index": 0}
+"""
+ # Even if "send_email" is technically a value somewhere, it's a block label
+ params = {"account_number": "12345678"}
+ assert self.reviewer._validate_no_hardcoded_values(code, params) is None