Skip to content

Automate browser based workflows with AI

fix(SKY-11495): credit validation review fallback floor (#6897)

Andrew Neilson1282faf30054
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
index 4d3862bac..0da6518db 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
@@ -163,6 +163,7 @@ IMPORTANT WORKFLOW RULES:
* Keep `navigation_goal` scoped to one coherent page state change grounded in observed evidence, not one guessed site model and not one block per field. Do not pre-author row/detail expansion from the user's words alone: first run or inspect your way to the actual results page, then use live result-page evidence to decide whether expansion controls exist. If requested details are already visible or no explicit expansion affordance is observed, skip the expansion block and go straight to an `extraction` block. The final stage of visible results -> extract should still use an `extraction` block for data capture, not another `navigation` block. Prefer the most specific block that fits the step — use a more specific block (`action` for a single action, `login` for authentication, `file_download` for downloads, `extraction` for data) over `navigation`, and reach for `navigation` only when the step is best expressed as a goal for the agent to work out rather than a specific named action (see CHOOSING A BLOCK in the knowledge base).
* When extracting table-like or list-like records (locations, affiliations, prices, inventory, line items, statuses), iterate the actual row/item elements (`tr`, `[role="row"]`, or equivalent repeated item containers) and read fields from that same row/item. Do NOT scan broad containers such as `section`, `.card`, `article`, or `li` and then infer fields from mixed text; that can combine several rows into one record. Derive summary fields only from the parsed row objects, not from broad page text.
* When a successful search/open-details block reaches a details or profile page, include the visible details/profile page label in the block's returned `evidence_text`. Keep structured record fields focused on the requested data; use the page label only as supporting evidence.
+* When a validation-only workflow must stop on a pre-submit Review page, the terminal Review block must return page-grounded values, not only booleans. Include an explicit validation-only marker such as `validation_only: true` or `submit_mode: "validation_only"`, include `review_values` or `review_fields` as visible Review-page label/value strings, include `evidence_text` containing the visible Review-page text that verbatim contains those values, include an explicit false submit/finalize-click signal, and do not click Submit/Finalize.
* Save the complete reusable workflow, but run only a small verified frontier when the workflow has several page-changing stages. `update_and_run_blocks` accepts the full YAML plus a subset of `block_labels`; for form/search workflows, first run the entry/form-state frontier, then continue with submit/results, then expansion/extraction. After a verified prefix or a budgeted run that leaves the browser on a later page, preserve the upstream workflow text and run only the missing downstream labels. Do not remove later blocks from the YAML just to shorten a test; do not submit a long chain of all blocks at once when each stage can be verified independently.
* Set `complete_criterion` on every decomposed `navigation` block to the observable post-action page state — without it, smaller blocks still return vague "continue" verdicts.
* Use descriptive, unique labels for blocks (snake_case format).
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index bc482ecee..91c50777a 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -81,6 +81,8 @@ from skyvern.forge.sdk.copilot.data_write_defaults import default_data_write_con
from skyvern.forge.sdk.copilot.enforcement import (
artifact_health_blocked,
outcome_fully_verified,
+ synthesized_persistence_reopened_after_failed_run,
+ synthesized_trajectory_is_goal_complete,
verified_goal_claim_authorized,
)
from skyvern.forge.sdk.copilot.failure_tracking import PER_TOOL_BUDGET_FAILURE_CATEGORY
@@ -722,7 +724,8 @@ def _synthesized_block_offer_prompt(ctx: CopilotContext | None) -> str:
if normalize_block_authoring_policy(ctx.block_authoring_policy) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:
LOG.debug("copilot_synthesized_block_offer_skipped", reason="policy_not_code_only_browser")
return ""
- if ctx.update_workflow_called:
+ reopened_after_failed_run = synthesized_persistence_reopened_after_failed_run(ctx)
+ if ctx.update_workflow_called and not reopened_after_failed_run:
LOG.debug("copilot_synthesized_block_offer_skipped", reason="already_authored")
return ""
if not ctx.scout_trajectory:
@@ -730,7 +733,13 @@ def _synthesized_block_offer_prompt(ctx: CopilotContext | None) -> str:
return ""
trajectory_len = len(ctx.scout_trajectory)
previous_offer_len = ctx.synthesized_block_offered_trajectory_len
- if ctx.synthesized_block_offered and trajectory_len < previous_offer_len + SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD:
+ trajectory_goal_complete = synthesized_trajectory_is_goal_complete(ctx)
+ if (
+ ctx.synthesized_block_offered
+ and trajectory_len < previous_offer_len + SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD
+ and (not trajectory_goal_complete or getattr(ctx, "synthesized_block_offered_goal_complete", False))
+ and not reopened_after_failed_run
+ ):
LOG.debug(
"copilot_synthesized_block_offer_skipped",
reason="already_offered",
@@ -751,6 +760,9 @@ def _synthesized_block_offer_prompt(ctx: CopilotContext | None) -> str:
return ""
ctx.synthesized_block_offered = True
ctx.synthesized_block_offered_trajectory_len = trajectory_len
+ ctx.synthesized_block_offered_goal_complete = trajectory_goal_complete
+ if reopened_after_failed_run:
+ ctx.synthesized_block_reopened_after_failed_run = True
LOG.info(
"copilot_synthesized_block_offer_rendered",
trajectory_len=trajectory_len,
diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.py
index bc82be9ae..cc6ffa5a3 100644
--- a/skyvern/forge/sdk/copilot/blocker_signal.py
+++ b/skyvern/forge/sdk/copilot/blocker_signal.py
@@ -276,6 +276,7 @@ _LOOP_PROGRESS_TOOLS = frozenset(
)
_ACTIVE_TERMINAL_REPLACEABLE_REASON_CODES = frozenset({"tool_error_per_tool_budget_rerun"})
_TERMINAL_CHALLENGE_REPLACEABLE_REASON_CODES = frozenset({"tool_error_post_budget_challenge_result_evidence"})
+SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE = "tool_error_synthesized_block_persistence_required"
def _should_stash_over_existing(
@@ -294,6 +295,12 @@ def _should_stash_over_existing(
and existing.internal_reason_code in _TERMINAL_CHALLENGE_REPLACEABLE_REASON_CODES
):
return True
+ if (
+ existing.internal_reason_code == SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE
+ and not existing.renders_final_reply
+ and incoming.renders_final_reply
+ ):
+ return True
return False
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index 0ae7de371..51ee7ebe1 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -445,7 +445,7 @@ def _credential_param_key(interaction: Mapping[str, Any], used: set[str]) -> str
return _unique_key(_safe_param_base(name or "credential"), used)
-def _is_durable_fallback_entry_target(interaction: Mapping[str, Any]) -> bool:
+def is_durable_fallback_entry_target(interaction: Mapping[str, Any]) -> bool:
tool_name = str(interaction.get("tool_name") or "")
if tool_name not in _DURABLE_FALLBACK_ENTRY_TARGET_TOOLS:
return False
@@ -458,7 +458,7 @@ def _is_durable_fallback_entry_target(interaction: Mapping[str, Any]) -> bool:
return True
-def _is_generic_entry_opener_click(interaction: Mapping[str, Any]) -> bool:
+def is_generic_entry_opener_click(interaction: Mapping[str, Any]) -> bool:
if str(interaction.get("tool_name") or "") != "click":
return False
if str(interaction.get("accessible_name") or "").strip():
@@ -517,7 +517,7 @@ def _has_later_durable_fallback_target(
source_url = str(interaction.get("source_url") or "").strip()
if first_source_url and source_url and source_url != first_source_url:
continue
- if _is_durable_fallback_entry_target(interaction):
+ if is_durable_fallback_entry_target(interaction):
return True
return False
@@ -545,7 +545,7 @@ def _optional_dismissal_locator_expr(interaction: Mapping[str, Any], fallback_lo
def _should_prefer_durable_entry_target(trajectory: Sequence[Mapping[str, Any]]) -> bool:
if not trajectory or not (
- _is_generic_entry_opener_click(trajectory[0])
+ is_generic_entry_opener_click(trajectory[0])
or _is_optional_dismissal_click(trajectory[0])
or _is_structural_dismissal_click(trajectory[0])
):
@@ -580,7 +580,7 @@ def _entry_target_locator(
if not first_locator:
first_locator = locator
first_index = index
- if prefer_durable and _is_durable_fallback_entry_target(interaction):
+ if prefer_durable and is_durable_fallback_entry_target(interaction):
return locator, index
if not prefer_durable:
return locator, index
@@ -611,7 +611,7 @@ def _post_auth_resume_locator(trajectory: Sequence[Mapping[str, Any]], *, strict
for index in range(submit_index + 1, len(trajectory)):
interaction = trajectory[index]
tool_name = str(interaction.get("tool_name") or "")
- if tool_name not in _ENTRY_TARGET_TOOLS or _is_generic_entry_opener_click(interaction):
+ if tool_name not in _ENTRY_TARGET_TOOLS or is_generic_entry_opener_click(interaction):
continue
if tool_name == "press_key" and not interaction.get("selector"):
continue
@@ -716,7 +716,7 @@ def synthesize_code_block(
if fallback_entry_index > entry_index:
for recovery_index in range(entry_index, fallback_entry_index):
recovery_interaction = trajectory[recovery_index]
- if not _is_generic_entry_opener_click(recovery_interaction):
+ if not is_generic_entry_opener_click(recovery_interaction):
continue
recovery_locator = _locator_expr(
recovery_interaction,
diff --git a/skyvern/forge/sdk/copilot/completion_verification.py b/skyvern/forge/sdk/copilot/completion_verification.py
index 93cac0a11..2582f1f0f 100644
--- a/skyvern/forge/sdk/copilot/completion_verification.py
+++ b/skyvern/forge/sdk/copilot/completion_verification.py
@@ -885,6 +885,7 @@ _TERMINAL_RECORD_FAMILY_ACTIONS: dict[TerminalActionFamily, frozenset[str]] = {
"form": frozenset({"form", "submission"}),
"order": frozenset({"order"}),
}
+_VALIDATION_REVIEW_MIN_VALUE_COUNT = 2
def grade_terminal_goal_record_criteria(
@@ -924,7 +925,7 @@ def grade_fallback_floor_reached_end_state_criteria(
eligible_criteria = [criterion for criterion in criteria if is_fallback_floor_base_criterion(criterion)]
if not eligible_criteria:
return []
- evidence_ref = _fallback_floor_reached_end_state_evidence_ref(snapshot)
+ evidence_ref = _fallback_floor_reached_end_state_evidence_ref(snapshot, criteria)
if evidence_ref is None:
return []
return [
@@ -938,16 +939,261 @@ def grade_fallback_floor_reached_end_state_criteria(
]
-def _fallback_floor_reached_end_state_evidence_ref(snapshot: RunEvidenceSnapshot) -> str | None:
+def _fallback_floor_reached_end_state_evidence_ref(
+ snapshot: RunEvidenceSnapshot, criteria: list[CompletionCriterion]
+) -> str | None:
for label, payload in snapshot.block_outputs.items():
- record = _structured_record_payload(payload)
- if record is None:
+ if _fallback_floor_parent_record_poisoned(payload):
continue
- if any(_terminal_goal_record_confirmed(record, family) for family in _TERMINAL_RECORD_FAMILIES):
+ record = _structured_record_payload(payload)
+ if record is not None and any(
+ _terminal_goal_record_confirmed(record, family) for family in _TERMINAL_RECORD_FAMILIES
+ ):
+ return f"block_outputs:{label}"
+ if any(
+ _validation_review_record_confirmed(candidate, criteria)
+ for candidate in _fallback_floor_record_candidates(payload)
+ ):
return f"block_outputs:{label}"
return None
+def _fallback_floor_parent_record_poisoned(payload: Any) -> bool:
+ return isinstance(payload, dict) and (
+ _terminal_goal_record_has_negative_guard(payload) or _structured_record_contradiction(payload) is not None
+ )
+
+
+def _fallback_floor_record_candidates(payload: Any) -> Iterable[dict[str, Any]]:
+ if not isinstance(payload, dict):
+ return
+ yield payload
+ for key, value in payload.items():
+ if isinstance(key, str) and key.endswith("_output") and isinstance(value, dict):
+ yield value
+
+
+def _validation_review_record_confirmed(record: dict[str, Any], criteria: list[CompletionCriterion]) -> bool:
+ if _terminal_goal_record_has_negative_guard(record):
+ return False
+ if _structured_record_contradiction(record):
+ return False
+ if record.get("all_checks_passed") is False:
+ return False
+ review_values = _normalized_review_values(record)
+ if len(review_values) < _VALIDATION_REVIEW_MIN_VALUE_COUNT:
+ return False
+ evidence_text = record.get("evidence_text")
+ if not isinstance(evidence_text, str):
+ return False
+ haystack = _normalize_present_value(evidence_text)
+ if not all(_present_verbatim(value, haystack) for value in review_values):
+ return False
+ if not _validation_review_satisfies_requested_literals(haystack, criteria):
+ return False
+ return (
+ _has_validation_only_page_evidence(record)
+ and _has_review_page_evidence(record)
+ and _has_no_submit_page_evidence(record)
+ )
+
+
+def _normalized_review_values(record: dict[str, Any]) -> list[str]:
+ review_values = record.get("review_values")
+ if not isinstance(review_values, dict):
+ review_values = record.get("review_fields")
+ if not isinstance(review_values, dict):
+ return []
+ normalized: list[str] = []
+ seen: set[str] = set()
+ for _key, value in _walk_record_scalars(review_values):
+ if isinstance(value, bool):
+ continue
+ candidate = _normalize_present_value(str(value))
+ if len(candidate) >= 4 and candidate not in seen:
+ seen.add(candidate)
+ normalized.append(candidate)
+ return normalized
+
+
+def _validation_review_satisfies_requested_literals(
+ normalized_evidence_text: str, criteria: list[CompletionCriterion]
+) -> bool:
+ literal_groups = [
+ _extract_present_value_literals(criterion.outcome)
+ for criterion in criteria
+ if not is_fallback_floor_base_criterion(criterion)
+ ]
+ literal_groups = [literals for literals in literal_groups if literals]
+ if not literal_groups:
+ return True
+ return all(
+ all(_present_verbatim(literal, normalized_evidence_text) for literal in literals) for literals in literal_groups
+ )
+
+
+def _has_validation_only_page_evidence(record: dict[str, Any]) -> bool:
+ for key, value in _walk_record_scalars(record):
+ leaf_tokens = _leaf_key_word_tokens(key)
+ normalized_value = _normalize_present_value(str(value))
+ if leaf_tokens == {"validation", "only"} and value is True:
+ return True
+ if leaf_tokens == {"submit", "mode"} and normalized_value == "validation_only":
+ return True
+ return False
+
+
+def _has_review_page_evidence(record: dict[str, Any]) -> bool:
+ has_grounded_review_page = False
+ for key, value in _walk_record_scalars(record):
+ tokens = _key_word_tokens(key)
+ if _is_review_page_signal(tokens):
+ if _signal_value_is_explicit_false(value):
+ return False
+ if _signal_value_is_explicit_positive(value):
+ has_grounded_review_page = True
+ if _is_review_page_text_field(tokens) and isinstance(value, str):
+ if _present_verbatim("review", _normalize_present_value(value)):
+ has_grounded_review_page = True
+ return has_grounded_review_page
+
+
+def _final_submit_click_held(record: dict[str, Any]) -> bool:
+ held = False
+ for key, value in _walk_record_scalars(record):
+ tokens = _key_word_tokens(key)
+ if not _is_submit_or_finalize_click_signal(tokens):
+ continue
+ if _signal_value_is_meaningful_positive(value):
+ return False
+ if _signal_value_is_explicit_false(value):
+ held = True
+ return held
+
+
+def _submitted_or_confirmation_held(record: dict[str, Any]) -> bool:
+ held = False
+ for key, value in _walk_record_scalars(record):
+ tokens = _key_word_tokens(key)
+ if not (_is_submitted_request_signal(tokens) or _is_confirmation_visible_signal(tokens)):
+ continue
+ if _signal_value_is_meaningful_positive(value):
+ return False
+ if _signal_value_is_explicit_false(value):
+ held = True
+ return held
+
+
+def _submitted_or_confirmation_reached(record: dict[str, Any]) -> bool:
+ for key, value in _walk_record_scalars(record):
+ tokens = _key_word_tokens(key)
+ if not (_is_submitted_request_signal(tokens) or _is_confirmation_visible_signal(tokens)):
+ continue
+ if _signal_value_is_meaningful_positive(value):
+ return True
+ return False
+
+
+def _review_page_with_final_controls_visible(record: dict[str, Any]) -> bool:
+ if not _has_review_page_evidence(record):
+ return False
+ final_controls = record.get("final_controls_visible")
+ if isinstance(final_controls, list):
+ visible = {_normalize_present_value(str(value)) for value in final_controls if isinstance(value, str)}
+ if visible & {"submit request", "submit", "back"}:
+ return True
+ return any(
+ "final" in _key_word_tokens(key)
+ and "submit" in _key_word_tokens(key)
+ and bool({"control", "controls"} & _key_word_tokens(key))
+ and _positive_integer_count(value)
+ for key, value in _walk_record_scalars(record)
+ )
+
+
+def _positive_integer_count(value: Any) -> bool:
+ return isinstance(value, int) and not isinstance(value, bool) and value > 0
+
+
+def _has_no_submit_page_evidence(record: dict[str, Any]) -> bool:
+ if not _final_submit_click_held(record):
+ return False
+ if _submitted_or_confirmation_reached(record):
+ return False
+ if _submitted_or_confirmation_held(record):
+ return True
+ return _review_page_with_final_controls_visible(record)
+
+
+def _is_review_page_signal(tokens: set[str]) -> bool:
+ return (
+ {"review", "visible"} <= tokens
+ or {"review", "reached"} <= tokens
+ or ({"pre", "submit"} <= tokens and ("visible" in tokens or "reached" in tokens))
+ )
+
+
+def _is_review_page_text_field(tokens: set[str]) -> bool:
+ return "page" in tokens and bool(tokens & {"current", "final", "title"})
+
+
+def _is_submit_or_finalize_click_signal(tokens: set[str]) -> bool:
+ return bool(tokens & {"clicked", "click"}) and bool(tokens & {"submit", "finalize", "final"})
+
+
+def _is_submitted_request_signal(tokens: set[str]) -> bool:
+ return {"submitted", "request"} <= tokens
+
+
+def _is_confirmation_visible_signal(tokens: set[str]) -> bool:
+ return "confirmation" in tokens and ("visible" in tokens or "page" in tokens)
+
+
+def _signal_value_is_explicit_false(value: Any) -> bool:
+ if value is False:
+ return True
+ if not isinstance(value, str):
+ return False
+ normalized = _normalize_present_value(value)
+ return normalized in {
+ "false",
+ "no",
+ "none",
+ "absent",
+ "hidden",
+ "not visible",
+ "not reached",
+ "not clicked",
+ "not submitted",
+ "never clicked",
+ "never submitted",
+ }
+
+
+def _signal_value_is_explicit_positive(value: Any) -> bool:
+ if value is True:
+ return True
+ if not isinstance(value, str):
+ return False
+ normalized = _normalize_present_value(value)
+ return normalized in {
+ "true",
+ "yes",
+ "visible",
+ "shown",
+ "displayed",
+ "present",
+ "reached",
+ "loaded",
+ "opened",
+ "current",
+ }
+
+
+def _signal_value_is_meaningful_positive(value: Any) -> bool:
+ return _is_meaningful_record_value(value) and not _signal_value_is_explicit_false(value)
+
+
def _terminal_goal_record_confirmed(record: dict[str, Any], family: TerminalActionFamily) -> bool:
if _terminal_goal_record_has_negative_guard(record):
return False
@@ -1115,6 +1361,11 @@ def _key_word_tokens(key: str) -> set[str]:
return set(re.findall(r"[a-z0-9]+", spaced))
+def _leaf_key_word_tokens(key: str) -> set[str]:
+ leaf = key.rsplit(".", 1)[-1]
+ return _key_word_tokens(leaf)
+
+
def _structured_record_has_identifier(record: dict[str, Any]) -> bool:
for key, value in _walk_record_scalars(record):
value_text = str(value)
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 14a1e2cd1..f227ef346 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -7,14 +7,17 @@ import copy
import json
import re
import time
+from dataclasses import replace
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
import structlog
+from agents import ModelSettings, RunConfig
from agents.run import Runner
from skyvern.forge.sdk.copilot import config as copilot_config_defaults
from skyvern.forge.sdk.copilot.blocker_signal import (
+ SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE,
CopilotToolBlockerSignal,
clear_tool_blocker_signals_for_reason_codes,
compose_loop_blocker_user_facing_reason,
@@ -23,6 +26,8 @@ from skyvern.forge.sdk.copilot.blocker_signal import (
)
from skyvern.forge.sdk.copilot.build_phase import DISCOVERY_PERMITTED_PHASES
from skyvern.forge.sdk.copilot.code_block_synthesis import (
+ is_durable_fallback_entry_target,
+ is_generic_entry_opener_click,
is_optional_dismissal_only_trajectory,
render_synthesized_offer_text,
synthesize_code_block,
@@ -68,6 +73,7 @@ from skyvern.forge.sdk.copilot.output_utils import (
looks_like_workflow_delivery_claim,
parse_final_response,
)
+from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy, request_policy_has_present_completion_contract
from skyvern.forge.sdk.copilot.run_outcome import (
TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,
@@ -157,6 +163,11 @@ SCREENSHOT_SENTINEL = "[copilot:screenshot] "
NUDGE_SENTINEL = "[copilot:nudge] "
SCREENSHOT_PLACEHOLDER = SCREENSHOT_SENTINEL + "[prior screenshot removed to save context]"
TOKEN_BUDGET = DEFAULT_TOKEN_BUDGET
+SYNTHESIZED_BLOCK_PERSISTENCE_TOOL = "update_and_run_blocks"
+_SYNTHESIZED_BLOCK_PERSISTENCE_ALLOWED_TOOLS = frozenset(
+ {SYNTHESIZED_BLOCK_PERSISTENCE_TOOL, "fill_credential_field", "update_workflow"}
+)
+_SYNTHESIZED_BLOCK_COMMIT_TOOLS = frozenset({"click", "press_key"})
# OpenAI detail=high cost per resized image. If we support other providers,
# pull from model config — this value will silently over/undercount otherwise.
# See screenshot_utils.resize_screenshot_b64 for the dimension contract this
@@ -919,6 +930,12 @@ def _turn_intent_can_author_without_user_input(turn_intent: Any) -> bool:
return turn_intent.authority.may_update_workflow
+def _turn_intent_can_update_and_run_without_user_input(turn_intent: Any) -> bool:
+ if not _turn_intent_can_author_without_user_input(turn_intent):
+ return False
+ return bool(turn_intent.authority.may_run_blocks)
+
+
def _has_current_turn_update_or_test_marker(ctx: Any) -> bool:
if bool(getattr(ctx, "update_workflow_called", False)):
return True
@@ -1988,7 +2005,8 @@ def _maybe_synthesized_block_offer_msg(ctx: Any) -> dict[str, Any] | None:
near-duplicate repeats, but a materially longer scout trajectory can refresh
the deterministic code before the model authors the workflow.
"""
- if getattr(ctx, "update_workflow_called", False):
+ reopened_after_failed_run = synthesized_persistence_reopened_after_failed_run(ctx)
+ if getattr(ctx, "update_workflow_called", False) and not reopened_after_failed_run:
return None
if normalize_block_authoring_policy(getattr(ctx, "block_authoring_policy", None)) != (
BlockAuthoringPolicy.CODE_ONLY_BROWSER
@@ -2001,9 +2019,12 @@ def _maybe_synthesized_block_offer_msg(ctx: Any) -> dict[str, Any] | None:
return None
trajectory_len = len(trajectory)
previous_offer_len = getattr(ctx, "synthesized_block_offered_trajectory_len", 0) or 0
+ trajectory_goal_complete = synthesized_trajectory_is_goal_complete(ctx)
if (
getattr(ctx, "synthesized_block_offered", False)
and trajectory_len < previous_offer_len + SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD
+ and (not trajectory_goal_complete or getattr(ctx, "synthesized_block_offered_goal_complete", False))
+ and not reopened_after_failed_run
):
return None
synthesized = synthesize_code_block(
@@ -2014,10 +2035,138 @@ def _maybe_synthesized_block_offer_msg(ctx: Any) -> dict[str, Any] | None:
ctx.synthesized_block_offered = True
ctx.synthesized_block_offered_trajectory_len = trajectory_len
+ ctx.synthesized_block_offered_goal_complete = trajectory_goal_complete
+ if reopened_after_failed_run:
+ ctx.synthesized_block_reopened_after_failed_run = True
goal = getattr(ctx, "block_goal_main_goal", "") or getattr(ctx, "user_message", "") or ""
return {"role": "user", "content": render_synthesized_offer_text(synthesized, trajectory, goal=goal)}
+def _completion_verification_unsatisfied(ctx: Any) -> bool:
+ result = getattr(ctx, "completion_verification_result", None)
+ if result is None or getattr(result, "status", None) != "evaluated":
+ return False
+ is_fully_satisfied = getattr(result, "is_fully_satisfied", None)
+ if callable(is_fully_satisfied) and is_fully_satisfied():
+ return False
+ return True
+
+
+def _last_scout_interaction_commits(trajectory: list[Any]) -> bool:
+ if not trajectory:
+ return False
+ last = trajectory[-1]
+ if not isinstance(last, dict):
+ return False
+ return str(last.get("tool_name") or "") in _SYNTHESIZED_BLOCK_COMMIT_TOOLS and not is_generic_entry_opener_click(
+ last
+ )
+
+
+def synthesized_persistence_reopened_after_failed_run(ctx: Any) -> bool:
+ if getattr(ctx, "synthesized_block_reopened_after_failed_run", False):
+ return True
+ if not getattr(ctx, "update_workflow_called", False):
+ return False
+ if not getattr(ctx, "test_after_update_done", False):
+ return False
+ if getattr(ctx, "last_test_ok", None) is not False:
+ return False
+ if getattr(ctx, "last_test_non_retriable_nav_error", None):
+ return False
+ if not _completion_verification_unsatisfied(ctx):
+ return False
+ trajectory = getattr(ctx, "scout_trajectory", None)
+ if not isinstance(trajectory, list):
+ return False
+ previous_offer_len = getattr(ctx, "synthesized_block_offered_trajectory_len", 0) or 0
+ if len(trajectory) <= previous_offer_len:
+ return False
+ return _last_scout_interaction_commits(trajectory)
+
+
+def synthesized_trajectory_is_goal_complete(ctx: Any) -> bool:
+ """True once the scout trajectory covers a durable data entry followed by a commit, or reaches a download target.
+ Reuses the synthesizer's validity helpers so an entry ``synthesize_code_block`` would drop never counts as complete."""
+ trajectory = getattr(ctx, "scout_trajectory", None)
+ if not isinstance(trajectory, list) or not trajectory:
+ return False
+ download = getattr(ctx, "reached_download_target", None)
+ if isinstance(download, ReachedDownloadTarget) and download.selector:
+ return True
+ last_entry_index: int | None = None
+ for index, item in enumerate(trajectory):
+ if isinstance(item, dict) and is_durable_fallback_entry_target(item):
+ last_entry_index = index
+ if last_entry_index is None:
+ return False
+ return any(
+ isinstance(item, dict)
+ and str(item.get("tool_name") or "") in _SYNTHESIZED_BLOCK_COMMIT_TOOLS
+ and not is_generic_entry_opener_click(item)
+ for item in trajectory[last_entry_index + 1 :]
+ )
+
+
+def _should_force_synthesized_block_persistence(ctx: Any) -> bool:
+ if getattr(ctx, "update_workflow_called", False) and not synthesized_persistence_reopened_after_failed_run(ctx):
+ return False
+ if not _turn_intent_can_update_and_run_without_user_input(getattr(ctx, "turn_intent", None)):
+ return False
+ if normalize_block_authoring_policy(getattr(ctx, "block_authoring_policy", None)) != (
+ BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ):
+ return False
+ if not getattr(ctx, "synthesized_block_offered", False):
+ return False
+ trajectory = getattr(ctx, "scout_trajectory", None) or []
+ if (getattr(ctx, "synthesized_block_offered_trajectory_len", 0) or 0) != len(trajectory):
+ return False
+ if not getattr(ctx, "synthesized_block_offered_goal_complete", False):
+ return False
+ return synthesized_trajectory_is_goal_complete(ctx)
+
+
+def synthesized_block_persistence_signal(ctx: Any, tool_name: str) -> CopilotToolBlockerSignal | None:
+ if tool_name in _SYNTHESIZED_BLOCK_PERSISTENCE_ALLOWED_TOOLS:
+ return None
+ if not _should_force_synthesized_block_persistence(ctx):
+ return None
+ return CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text=(
+ "A synthesized code block offer is already available for this authoring turn. "
+ f"Call {SYNTHESIZED_BLOCK_PERSISTENCE_TOOL} with that block now before any more scouting, "
+ "reading, page evaluation, or browser interaction. This blocker clears only after "
+ f"{SYNTHESIZED_BLOCK_PERSISTENCE_TOOL} succeeds."
+ ),
+ user_facing_reason="I need to save and test the drafted workflow before scouting more.",
+ recovery_hint="retry_with_different_tool",
+ cleared_by_tools=frozenset({SYNTHESIZED_BLOCK_PERSISTENCE_TOOL}),
+ preserves_workflow_draft=True,
+ renders_final_reply=False,
+ internal_reason_code=SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE,
+ blocked_tool=tool_name,
+ extra={
+ "synthesized_block_offered_trajectory_len": (
+ getattr(ctx, "synthesized_block_offered_trajectory_len", 0) or 0
+ ),
+ },
+ )
+
+
+def _runner_kwargs_with_forced_tool_choice(runner_kwargs: dict[str, Any], tool_name: str) -> dict[str, Any]:
+ run_config = runner_kwargs.get("run_config")
+ if isinstance(run_config, RunConfig):
+ model_settings = run_config.model_settings
+ if isinstance(model_settings, ModelSettings):
+ forced_settings = replace(model_settings, tool_choice=tool_name)
+ else:
+ forced_settings = ModelSettings(tool_choice=tool_name)
+ return {**runner_kwargs, "run_config": replace(run_config, model_settings=forced_settings)}
+ return {**runner_kwargs, "run_config": RunConfig(model_settings=ModelSettings(tool_choice=tool_name))}
+
+
def _assemble_enforcement_messages(
screenshot_msg: dict[str, Any] | None,
nudge_content: str | None,
@@ -2086,6 +2235,39 @@ async def run_with_enforcement(
"enforcement_iteration",
data={"iteration": iteration, "elapsed_seconds": round(elapsed, 3)},
):
+ force_synthesized_block_persistence = _should_force_synthesized_block_persistence(ctx)
+ current_runner_kwargs = (
+ _runner_kwargs_with_forced_tool_choice(runner_kwargs, SYNTHESIZED_BLOCK_PERSISTENCE_TOOL)
+ if force_synthesized_block_persistence
+ else runner_kwargs
+ )
+ effective_run_config = current_runner_kwargs.get("run_config")
+ effective_model_settings = (
+ effective_run_config.model_settings if isinstance(effective_run_config, RunConfig) else None
+ )
+ turn_intent = getattr(ctx, "turn_intent", None)
+ turn_intent_authority = getattr(turn_intent, "authority", None)
+ LOG.info(
+ "copilot synthesized persistence force decision",
+ force_synthesized_block_persistence=force_synthesized_block_persistence,
+ forced_tool_name=(SYNTHESIZED_BLOCK_PERSISTENCE_TOOL if force_synthesized_block_persistence else None),
+ chosen_tool_name=(SYNTHESIZED_BLOCK_PERSISTENCE_TOOL if force_synthesized_block_persistence else None),
+ turn_intent_mode=getattr(getattr(turn_intent, "mode", None), "value", None),
+ turn_intent_may_update_workflow=getattr(turn_intent_authority, "may_update_workflow", None),
+ turn_intent_may_run_blocks=getattr(turn_intent_authority, "may_run_blocks", None),
+ turn_intent_requires_user_input=getattr(turn_intent_authority, "requires_user_input", None),
+ block_authoring_policy=getattr(
+ normalize_block_authoring_policy(getattr(ctx, "block_authoring_policy", None)),
+ "value",
+ None,
+ ),
+ synthesized_block_offered=getattr(ctx, "synthesized_block_offered", False),
+ synthesized_block_offered_trajectory_len=(
+ getattr(ctx, "synthesized_block_offered_trajectory_len", 0) or 0
+ ),
+ update_workflow_called=getattr(ctx, "update_workflow_called", False),
+ effective_tool_choice=getattr(effective_model_settings, "tool_choice", None),
+ )
try:
result = await _run_streamed_with_deadline(
agent,
@@ -2093,7 +2275,7 @@ async def run_with_enforcement(
ctx,
session,
tracked_stream,
- runner_kwargs,
+ current_runner_kwargs,
start_time,
iteration,
)
@@ -2136,7 +2318,7 @@ async def run_with_enforcement(
ctx,
session,
tracked_stream,
- runner_kwargs,
+ current_runner_kwargs,
start_time,
iteration,
)
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index 63f2b85b8..ebcb616ea 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -30,6 +30,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import (
from skyvern.forge.sdk.copilot.build_phase import _phase_blocker_signal
from skyvern.forge.sdk.copilot.enforcement import (
register_no_progress_interaction_click,
+ synthesized_block_persistence_signal,
terminal_challenge_blocker_signal_from_current_page_evidence,
)
from skyvern.forge.sdk.copilot.loop_detection import (
@@ -75,6 +76,7 @@ _POST_HOOK_CONTEXT_ROLLBACK_FIELDS = (
"reached_download_target",
"synthesized_block_offered",
"synthesized_block_offered_trajectory_len",
+ "synthesized_block_offered_goal_complete",
"consecutive_no_progress_interaction_count",
)
@@ -314,6 +316,22 @@ class SkyvernOverlayMCPServer(MCPServer):
)
return _copilot_to_call_tool_result({"ok": False, "error": terminal_challenge_payload})
+ persistence_signal = synthesized_block_persistence_signal(copilot_ctx, tool_name)
+ if persistence_signal is not None:
+ LOG.warning(
+ "Synthesized block persistence required before MCP tool",
+ tool_name=tool_name,
+ synthesized_block_offered_trajectory_len=getattr(
+ copilot_ctx,
+ "synthesized_block_offered_trajectory_len",
+ None,
+ ),
+ )
+ payload = stash_blocker_signal(copilot_ctx, persistence_signal)
+ result = {"ok": False, "error": payload}
+ record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, result)
+ return _copilot_to_call_tool_result(result)
+
loop_error = detect_failed_tool_step_loop_for_ctx(copilot_ctx, tool_name, arguments)
if loop_error:
LOG.warning(
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index d4ef5a7d2..a0ab45709 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -290,6 +290,8 @@ class AgentContext:
reached_download_target: ReachedDownloadTarget | None = None
synthesized_block_offered: bool = False
synthesized_block_offered_trajectory_len: int = 0
+ synthesized_block_offered_goal_complete: bool = False
+ synthesized_block_reopened_after_failed_run: bool = False
# Count of times the scout-act download gate rejected a download-intent block this turn. Bounds
# the author->scout->re-author cycle so a genuinely un-scoutable affordance halts honestly.
download_scout_required_rejections: int = 0
diff --git a/skyvern/forge/sdk/copilot/streaming_adapter.py b/skyvern/forge/sdk/copilot/streaming_adapter.py
index 4890cec4f..9ce594d64 100644
--- a/skyvern/forge/sdk/copilot/streaming_adapter.py
+++ b/skyvern/forge/sdk/copilot/streaming_adapter.py
@@ -461,6 +461,8 @@ def _update_enforcement_from_tool(
ctx.update_workflow_called = True
ctx.test_after_update_done = False
ctx.post_update_nudge_count = 0
+ if tool_name in ("update_workflow", "update_and_run_blocks") and has_blocks:
+ ctx.synthesized_block_reopened_after_failed_run = False
if tool_name in ("run_blocks_and_collect_debug", "update_and_run_blocks"):
ctx.test_after_update_done = True
diff --git a/skyvern/forge/sdk/copilot/tools/blockers.py b/skyvern/forge/sdk/copilot/tools/blockers.py
index 29df0fc81..9194855bf 100644
--- a/skyvern/forge/sdk/copilot/tools/blockers.py
+++ b/skyvern/forge/sdk/copilot/tools/blockers.py
@@ -23,6 +23,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
from skyvern.forge.sdk.copilot.composition_evidence import interactive_challenge_controls
from skyvern.forge.sdk.copilot.enforcement import (
TOTAL_TIMEOUT_SECONDS,
+ synthesized_block_persistence_signal,
terminal_challenge_blocker_signal_from_current_page_evidence,
)
from skyvern.forge.sdk.copilot.failure_tracking import (
@@ -1464,6 +1465,10 @@ def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any
if current_page_challenge_signal is not None:
return _emit_tool_blocker_signal(ctx, current_page_challenge_signal)
+ persistence_signal = synthesized_block_persistence_signal(ctx, tool_name)
+ if persistence_signal is not None:
+ return _emit_tool_blocker_signal(ctx, persistence_signal)
+
detected = detect_failed_tool_step_loop_for_ctx(ctx, tool_name, arguments or {})
if detected is not None:
return _emit_tool_blocker_signal(
diff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.py
index 25dacce66..878d54527 100644
--- a/skyvern/forge/sdk/copilot/tools/completion.py
+++ b/skyvern/forge/sdk/copilot/tools/completion.py
@@ -24,6 +24,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
grade_registered_download_criteria,
grade_structured_record_criteria,
grade_terminal_goal_record_criteria,
+ is_fallback_floor_base_criterion,
is_registered_download_completion_criterion,
registered_download_completion_criterion,
structural_unfired_contingent_criterion_ids,
@@ -67,6 +68,14 @@ LOG = structlog.get_logger()
_TYPED_DOWNLOAD_KINDS = frozenset({DOWNLOAD_KIND_REGISTERED, DOWNLOAD_KIND_ATTRIBUTE, DOWNLOAD_KIND_EXTENSION})
_REGISTERED_DOWNLOAD_REQUESTED_OUTPUT_PATHS = frozenset(f"output.{key}" for key in REGISTERED_DOWNLOAD_OUTPUT_KEYS)
+_VALIDATION_REVIEW_OUTPUT_CONTRACT_HINT = (
+ " For validation-only pre-submit Review pages, do not repair by returning only booleans such as "
+ "pre_submit_review_reached, submit_control_visible, submit_or_finalize_clicked, or per-field *_verified flags. "
+ "The Review block output must include an explicit validation-only marker such as `validation_only: true` or "
+ '`submit_mode: "validation_only"`, `review_values` or `review_fields` as visible Review-page label/value '
+ "strings, `evidence_text` containing the visible Review-page text that verbatim contains those values, and an "
+ "explicit false submit/finalize-click signal. Stop on the Review page; do not click Submit/Finalize."
+)
def _completion_request_policy(copilot_ctx: Any) -> Any | None:
@@ -745,6 +754,35 @@ def _merge_run_verdicts_if_requested_output_exists(
)
+def _filter_judged_fallback_floor_satisfaction(
+ run_criteria: list[CompletionCriterion],
+ judged_result: CompletionVerificationResult,
+ deterministic_result: CompletionVerificationResult | None,
+) -> list[CriterionVerdict]:
+ deterministic_satisfied_ids = {
+ verdict.criterion_id
+ for verdict in (deterministic_result.verdicts if deterministic_result is not None else [])
+ if verdict.satisfied
+ }
+ fallback_floor_ids = {criterion.id for criterion in run_criteria if is_fallback_floor_base_criterion(criterion)}
+ verdicts: list[CriterionVerdict] = []
+ for verdict in judged_result.verdicts:
+ if verdict.criterion_id in fallback_floor_ids and verdict.satisfied:
+ if verdict.criterion_id in deterministic_satisfied_ids:
+ verdicts.append(verdict)
+ else:
+ verdicts.append(
+ CriterionVerdict(
+ criterion_id=verdict.criterion_id,
+ state="unsatisfied",
+ reason_code="no_evidence",
+ )
+ )
+ continue
+ verdicts.append(verdict)
+ return verdicts
+
+
def _run_criteria_for_verdicts(
run_criteria: list[CompletionCriterion], *verdict_groups: list[CriterionVerdict]
) -> list[CompletionCriterion]:
@@ -1012,7 +1050,13 @@ async def _maybe_run_completion_verification(
verdicts = list(requested_output_verdicts)
if deterministic_result is not None:
verdicts.extend(deterministic_result.verdicts)
- verdicts.extend(judged_result.verdicts)
+ verdicts.extend(
+ _filter_judged_fallback_floor_satisfaction(
+ judgeable_run_criteria,
+ judged_result,
+ deterministic_result,
+ )
+ )
run_result = CompletionVerificationResult(
status="evaluated",
criterion_ids=[criterion.id for criterion in run_criteria],
@@ -1061,11 +1105,13 @@ def _outcome_unverified_reason(
criteria: list[CompletionCriterion] = list(policy.completion_criteria) if policy is not None else []
known_good = _known_good_revision_hint(copilot_ctx)
missing_detail = _missing_evidence_detail(completion_verification, criteria)
+ validation_review_hint = _validation_review_output_contract_hint(completion_verification, criteria)
if missing_detail:
return (
"The run completed but did not demonstrate the goal outcome(s). "
f"Missing evidence: {missing_detail}. "
- f"Add or fix the block that produces the missing outcome evidence, then re-run.{known_good}"
+ "Add or fix the block that produces the missing outcome evidence, then "
+ f"re-run.{validation_review_hint}{known_good}"
)
unmet = summarize_unsatisfied_outcomes(completion_verification, criteria)
detail = f": {unmet}" if unmet else ""
@@ -1073,7 +1119,7 @@ def _outcome_unverified_reason(
return (
f"The run completed but did not demonstrate the goal outcome(s){detail}. "
"Add or fix the block that produces the missing outcome evidence, "
- f"then re-run.{known_good}"
+ f"then re-run.{validation_review_hint}{known_good}"
)
# An 'unavailable' result reaches here only when verification was required;
# fail closed and ask for a re-run rather than claim an unverified success.
@@ -1093,6 +1139,19 @@ def _known_good_revision_hint(copilot_ctx: Any) -> str:
return ""
+def _validation_review_output_contract_hint(
+ completion_verification: CompletionVerificationResult, criteria: list[CompletionCriterion]
+) -> str:
+ fallback_floor_ids = {criterion.id for criterion in criteria if is_fallback_floor_base_criterion(criterion)}
+ if not fallback_floor_ids:
+ return ""
+ for verdict in completion_verification.verdicts:
+ if verdict.criterion_id in fallback_floor_ids and verdict.state == "unsatisfied":
+ if verdict.reason_code == "no_evidence":
+ return _VALIDATION_REVIEW_OUTPUT_CONTRACT_HINT
+ return ""
+
+
def _missing_evidence_detail(
completion_verification: CompletionVerificationResult, criteria: list[CompletionCriterion]
) -> str | None:
diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.py
index 997866421..e30f8fa45 100644
--- a/skyvern/forge/sdk/copilot/tools/scouting.py
+++ b/skyvern/forge/sdk/copilot/tools/scouting.py
@@ -1065,6 +1065,7 @@ async def _maybe_attach_reached_download_target(
# The prompt-side offer latched before this download target resolved, so it rendered the
# non-download idiom. Reopen the latch once so the post-turn fallback re-fires carrying it.
ctx.synthesized_block_offered = False
+ ctx.synthesized_block_offered_goal_complete = False
LOG.info("copilot_synthesized_block_offer_latch_reset_for_download", url=url)
if not target.already_registered:
_register_reached_download_scout_interaction(ctx, target, url=url)
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index b0acb673f..75974fecc 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -4714,6 +4714,10 @@ def _record_workflow_update_result(
block_count = data.get("block_count")
if isinstance(block_count, int):
copilot_ctx.last_update_block_count = block_count
+ copilot_ctx.update_workflow_called = True
+ copilot_ctx.synthesized_block_reopened_after_failed_run = False
+ copilot_ctx.test_after_update_done = False
+ copilot_ctx.post_update_nudge_count = 0
copilot_ctx.last_test_ok = None
copilot_ctx.last_test_failure_reason = None
clear_terminal_evidence_on_workflow_edit(copilot_ctx)
diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.py
index fd22a90d1..06eaf9fed 100644
--- a/tests/unit/test_copilot_completion_verification.py
+++ b/tests/unit/test_copilot_completion_verification.py
@@ -25,6 +25,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
combine_verification_results,
evaluate_completion_criteria,
grade_definition_criteria,
+ grade_fallback_floor_reached_end_state_criteria,
grade_present_value_criteria,
grade_record_semantic_consistency,
grade_registered_download_criteria,
@@ -191,6 +192,109 @@ def _terminal_goal_payload(**overrides: Any) -> dict[str, Any]:
return payload
+def _validation_review_payload(**overrides: Any) -> dict[str, Any]:
+ payload = {
+ "all_checks_passed": True,
+ "validation_only": True,
+ "review_page_visible": True,
+ "submit_or_finalize_clicked": False,
+ "submitted_request": False,
+ "confirmation_page_visible": False,
+ "review_values": {
+ "visible_service_address": "1234 Sample Utility Way, Testville, CA 94016",
+ "visible_requested_start_date": "2026-06-22",
+ "visible_account_holder": "EXAMPLE REALTY LABS INC",
+ },
+ "evidence_text": (
+ "Visible Review page showed service address 1234 Sample Utility Way, Testville, CA 94016, "
+ "start date 2026-06-22, and account holder EXAMPLE REALTY LABS INC. "
+ "No Submit Request or final confirmation control was clicked."
+ ),
+ }
+ payload.update(overrides)
+ return payload
+
+
+def _generated_validation_review_payload(**overrides: Any) -> dict[str, Any]:
+ payload = {
+ "pre_submit_review_reached": True,
+ "exact_service_address_verified": True,
+ "requested_start_date_verified": True,
+ "business_name_verified": True,
+ "account_holder_verified": True,
+ "safe_mailing_address_verified": True,
+ "no_payment_or_deposit_gate": True,
+ "validation_only": True,
+ "submit_or_finalize_clicked": False,
+ "terminal_summary": "Pre-submit review reached: True; submit/finalize control clicked: False.",
+ "final_controls_visible": ["Submit Request", "Back"],
+ "review_fields": {
+ "Service Address": "1234 Sample Utility Way, Testville, CA 94016",
+ "Requested Start Date": "2026-06-22",
+ "Business Name": "Example Realty Labs Inc",
+ "Account Holder": "EXAMPLE REALTY LABS INC",
+ },
+ "evidence_text": (
+ "Start Service - Review\n"
+ "Service Address\n1234 Sample Utility Way, Testville, CA 94016\n"
+ "Requested Start Date\n2026-06-22\n"
+ "Business Name\nExample Realty Labs Inc\n"
+ "Account Holder\nEXAMPLE REALTY LABS INC\n"
+ "Submit Request\nBack"
+ ),
+ }
+ payload.update(overrides)
+ return payload
+
+
+def _live_validation_review_output_payload(**overrides: Any) -> dict[str, Any]:
+ payload = {
+ "all_validations_passed": True,
+ "evidence_text": (
+ "Step 1 Find Address\n"
+ "Step 2 About Business\n"
+ "Step 3 Account Information\n"
+ "Step 4 Review\n"
+ "Step 5 Confirmation\n"
+ "Start Service - Review\n\n"
+ "Review all request details before final submission.\n\n"
+ "Service Address\n1234 Sample Utility Way, Testville, CA 94016\n"
+ "Requested Start Date\n2026-06-22\n"
+ "Business Name\nExample Realty Labs Inc\n"
+ "Account Holder\nEXAMPLE REALTY LABS INC\n"
+ "Mailing Address\nPO Box 4300, Harbor City, CA 90210\n"
+ "Tax Identifier\nMasked ending in 4321\n"
+ "Payment / Deposit\nNo payment, deposit, autopay, or unsafe attestation required before review.\n"
+ "Submit Request\nBack"
+ ),
+ "final_submit_controls_present": 1,
+ "pre_submit_review_reached": True,
+ "review_page_label": "Start Service - Review",
+ "submit_mode": "validation_only",
+ "review_values": {
+ "Account Holder": "EXAMPLE REALTY LABS INC",
+ "Business Name": "Example Realty Labs Inc",
+ "Mailing Address": "PO Box 4300, Harbor City, CA 90210",
+ "Payment / Deposit": "No payment, deposit, autopay, or unsafe attestation required before review.",
+ "Requested Start Date": "2026-06-22",
+ "Service Address": "1234 Sample Utility Way, Testville, CA 94016",
+ "Tax Identifier": "Masked ending in 4321",
+ },
+ "submit_finalize_control_clicked": False,
+ "terminal_summary": "Pre-submit review reached: True; submit/finalize control clicked: False",
+ "validations": {
+ "account_holder_verified": True,
+ "business_name_verified": True,
+ "exact_service_address_verified": True,
+ "no_payment_deposit_gate_verified": True,
+ "requested_start_date_verified": True,
+ "safe_mailing_address_verified": True,
+ },
+ }
+ payload.update(overrides)
+ return payload
+
+
def _status_snapshot(
status: str,
*,
@@ -1136,6 +1240,246 @@ def test_terminal_goal_record_does_not_take_literal_criteria_from_present_value(
assert _satisfied_criterion_ids(grade_present_value_criteria(criteria, snapshot)) == {"c0"}
+def test_fallback_floor_accepts_validation_review_evidence() -> None:
+ snapshot = RunEvidenceSnapshot(block_outputs={"submit_request": _validation_review_payload()})
+
+ verdicts = grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot)
+
+ assert verdicts == [
+ CriterionVerdict(
+ criterion_id="__copilot_fallback_floor__run",
+ state="satisfied",
+ reason_code="evidence_confirms",
+ evidence_ref="block_outputs:submit_request",
+ )
+ ]
+
+
+def test_fallback_floor_accepts_generated_validation_review_fields_evidence() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={"validate_business_start_service": _generated_validation_review_payload()}
+ )
+
+ verdicts = grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot)
+
+ assert verdicts == [
+ CriterionVerdict(
+ criterion_id="__copilot_fallback_floor__run",
+ state="satisfied",
+ reason_code="evidence_confirms",
+ evidence_ref="block_outputs:validate_business_start_service",
+ )
+ ]
+
+
+def test_fallback_floor_accepts_live_validation_review_output_parameter_shape() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={"validate_business_start_service_review_output": _live_validation_review_output_payload()}
+ )
+
+ verdicts = grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot)
+
+ assert verdicts == [
+ CriterionVerdict(
+ criterion_id="__copilot_fallback_floor__run",
+ state="satisfied",
+ reason_code="evidence_confirms",
+ evidence_ref="block_outputs:validate_business_start_service_review_output",
+ )
+ ]
+
+
+def test_fallback_floor_rejects_generated_validation_review_after_final_click() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "validate_business_start_service": _generated_validation_review_payload(
+ submit_or_finalize_clicked=True,
+ terminal_summary="Pre-submit review reached: True; submit/finalize control clicked: True.",
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_live_validation_review_confirmation_page() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "validate_business_start_service_review_output": _live_validation_review_output_payload(
+ confirmation_page_visible=True,
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_generated_validation_review_confirmation_page() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "validate_business_start_service": _generated_validation_review_payload(
+ confirmation_page_visible=True,
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_bare_all_checks_passed() -> None:
+ snapshot = RunEvidenceSnapshot(block_outputs={"submit_request": {"all_checks_passed": True}})
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_normal_submit_review_without_validation_only_marker() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "submit_request": _validation_review_payload(
+ validation_only=None,
+ submit_mode=None,
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
[email protected]("marker", ["not_validation_only", "validation_only_disabled", "previous_validation_only"])
+def test_fallback_floor_rejects_validation_only_marker_prefix_suffix_matches(marker: str) -> None:
+ payload = _validation_review_payload(validation_only=None)
+ payload[marker] = True
+ snapshot = RunEvidenceSnapshot(block_outputs={"submit_request": payload})
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_boolean_only_validation_review_evidence() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "validate_business_start_service_review": _live_validation_review_output_payload(
+ all_validations_passed=None,
+ review_values=None,
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_validation_review_submitted_request() -> None:
+ snapshot = RunEvidenceSnapshot(block_outputs={"submit_request": _validation_review_payload(submitted_request=True)})
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_validation_review_confirmation_page_visible() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={"submit_request": _validation_review_payload(confirmation_page_visible=True)}
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_validation_review_submit_or_finalize_click() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={"submit_request": _validation_review_payload(submit_or_finalize_clicked=True)}
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_review_text_without_structured_review_page() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "submit_request": _validation_review_payload(
+ review_page_visible=False,
+ evidence_text=(
+ "No review page was necessary, but values 1234 Sample Utility Way, Testville, CA 94016, "
+ "2026-06-22, and EXAMPLE REALTY LABS INC were checked."
+ ),
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_review_values_without_corroborating_text() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "submit_request": _validation_review_payload(
+ evidence_text="Visible Review page showed safe values and no final click."
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_validation_review_values_contradicting_requested_literals() -> None:
+ criteria = [
+ *build_classifier_fallback_floor([]),
+ _criterion(
+ "c_requested_values",
+ 'Review shows service address "1234 Sample Utility Way, Testville, CA 94016" and start date "2026-06-22".',
+ ),
+ ]
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "submit_request": _validation_review_payload(
+ review_values={
+ "visible_service_address": "100 Wrong Way, Atlanta, GA 30318",
+ "visible_requested_start_date": "2026-07-01",
+ "visible_account_holder": "EXAMPLE REALTY LABS INC",
+ },
+ evidence_text=(
+ "Visible Review page showed service address 100 Wrong Way, Atlanta, GA 30318, "
+ "start date 2026-07-01, and account holder EXAMPLE REALTY LABS INC. "
+ "No Submit Request or final confirmation control was clicked."
+ ),
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(criteria, snapshot) == []
+
+
+ "overrides",
+ [
+ {"error": "review mismatch"},
+ {"failure_reason": "submit disabled"},
+ {"status": "failed"},
+ {"all_checks_passed": False},
+ ],
+)
+def test_fallback_floor_rejects_validation_review_negative_guards(overrides: dict[str, Any]) -> None:
+ snapshot = RunEvidenceSnapshot(block_outputs={"submit_request": _validation_review_payload(**overrides)})
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_validation_review_structured_contradiction() -> None:
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "submit_request": _validation_review_payload(
+ items=[{"item_name": "Service Review Active", "status": "Expired"}],
+ overall_status="Expired",
+ )
+ }
+ )
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
+def test_fallback_floor_rejects_validation_review_nested_under_failed_parent() -> None:
+ payload = {"status": "failed", "error": "submit blocked", "validate_review_output": _validation_review_payload()}
+ snapshot = RunEvidenceSnapshot(block_outputs={"validate_review": payload})
+
+ assert grade_fallback_floor_reached_end_state_criteria(build_classifier_fallback_floor([]), snapshot) == []
+
+
def test_structured_record_goal_content_remains_strict_for_flat_terminal_payload() -> None:
assert structured_record_has_goal_content(_terminal_goal_payload()) is False
@@ -1473,6 +1817,38 @@ def test_outcome_unverified_reason_uses_typed_missing_evidence_not_confirmation_
assert "prefer restoring that revision" in known_good_reason
+def test_outcome_unverified_reason_guides_fallback_floor_review_output_contract() -> None:
+ policy = RequestPolicy(
+ completion_criteria=build_classifier_fallback_floor([]),
+ classifier_status="fallback",
+ )
+ floor_id = policy.completion_criteria[0].id
+ verification = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=[floor_id],
+ verdicts=[
+ CriterionVerdict(
+ criterion_id=floor_id,
+ state="unsatisfied",
+ reason_code="no_evidence",
+ missing_evidence="run output did not include evidence for this criterion",
+ )
+ ],
+ )
+ ctx = SimpleNamespace(request_policy=policy)
+
+ reason = _outcome_unverified_reason(ctx, verification)
+
+ assert reason is not None
+ assert "review_values" in reason
+ assert "review_fields" in reason
+ assert "evidence_text" in reason
+ assert "validation_only" in reason
+ assert "submit_mode" in reason
+ assert "visible Review-page label/value strings" in reason
+ assert "do not click Submit/Finalize" in reason
+
+
def test_outcome_unverified_reason_excludes_structurally_abstained_contingent_missing_evidence() -> None:
policy = RequestPolicy(
completion_criteria=[
@@ -1608,6 +1984,47 @@ def _terminal_goal_output_result(**payload_overrides: Any) -> dict:
}
+def _validation_review_output_result(**payload_overrides: Any) -> dict:
+ return {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_validation_review",
+ "overall_status": "completed",
+ "executed_block_labels": ["submit_request"],
+ "current_url": "https://example.test/review",
+ "page_title": "Start Service - Review",
+ "blocks": [
+ {
+ "label": "submit_request",
+ "block_type": "CODE",
+ "status": "completed",
+ "extracted_data": _validation_review_payload(**payload_overrides),
+ }
+ ],
+ },
+ }
+
+
+def _live_validation_review_output_result(**payload_overrides: Any) -> dict:
+ return {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_validation_review",
+ "overall_status": "completed",
+ "executed_block_labels": ["validate_business_start_service_review"],
+ "current_url": "https://example.test/review",
+ "page_title": "Start Service - Review",
+ "blocks": [],
+ "output": {
+ "extracted_information": [],
+ "validate_business_start_service_review_output": _live_validation_review_output_payload(
+ **payload_overrides
+ ),
+ },
+ },
+ }
+
+
def _requested_output_result(output: Any) -> dict:
return {
"ok": True,
@@ -3568,6 +3985,54 @@ async def test_maybe_run_completion_verification_fallback_floor_uses_recorded_te
assert verification.verdicts[0].evidence_ref == "block_outputs:submit_water_request"
+async def test_maybe_run_completion_verification_fallback_floor_uses_validation_review_evidence(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fail_handler(**_: object) -> object:
+ raise AssertionError("validation review evidence must not call the judge")
+
+ _patch_completion_handler(monkeypatch, fail_handler)
+ ctx = _run_ctx()
+ _set_workflow_labels(ctx, "submit_request")
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=build_classifier_fallback_floor([]),
+ classifier_status="fallback",
+ )
+
+ verification = await _maybe_run_completion_verification(ctx, _validation_review_output_result(), time.monotonic())
+
+ assert verification is not None
+ assert verification.no_gradeable_run_plane is False
+ assert verification.is_fully_satisfied() is True
+ assert verification.verdicts[0].evidence_ref == "block_outputs:submit_request"
+
+
+async def test_maybe_run_completion_verification_fallback_floor_uses_live_output_parameter_review_evidence(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fail_handler(**_: object) -> object:
+ raise AssertionError("live validation review output parameter evidence must not call the judge")
+
+ _patch_completion_handler(monkeypatch, fail_handler)
+ ctx = _run_ctx()
+ _set_workflow_labels(ctx, "validate_business_start_service_review")
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=build_classifier_fallback_floor([]),
+ classifier_status="fallback",
+ )
+
+ verification = await _maybe_run_completion_verification(
+ ctx, _live_validation_review_output_result(), time.monotonic()
+ )
+
+ assert verification is not None
+ assert verification.no_gradeable_run_plane is False
+ assert verification.is_fully_satisfied() is True
+ assert verification.verdicts[0].evidence_ref == "block_outputs:validate_business_start_service_review_output"
+
+
@pytest.mark.asyncio
async def test_maybe_run_completion_verification_terminal_goal_uses_workflow_run_output_parameters(
monkeypatch: pytest.MonkeyPatch,
@@ -3618,7 +4083,7 @@ async def test_maybe_run_completion_verification_terminal_goal_uses_workflow_run
@pytest.mark.asyncio
-async def test_maybe_run_completion_verification_fallback_floor_uses_page_end_state_evidence(
+async def test_maybe_run_completion_verification_fallback_floor_rejects_judged_page_end_state_evidence(
monkeypatch: pytest.MonkeyPatch,
) -> None:
captured: dict[str, str] = {}
@@ -3658,7 +4123,9 @@ async def test_maybe_run_completion_verification_fallback_floor_uses_page_end_st
assert verification is not None
assert verification.no_gradeable_run_plane is False
- assert verification.is_fully_satisfied() is True
+ assert verification.is_fully_satisfied() is False
+ assert verification.verdicts[0].state == "unsatisfied"
+ assert verification.verdicts[0].reason_code == "no_evidence"
assert "observed_end_state_url: https://example.test/review" in captured["prompt"]
assert "observed_end_state_page_title: Start Service - Review" in captured["prompt"]
@@ -3695,6 +4162,61 @@ async def test_maybe_run_completion_verification_fallback_floor_without_evidence
assert verification.verdicts[0].reason_code == "no_evidence"
+async def test_maybe_run_completion_verification_fallback_floor_rejects_judged_login_page_output(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def handler(**_: object) -> object:
+ return {
+ "verdicts": [
+ {
+ "criterion_id": "__copilot_fallback_floor__run",
+ "satisfied": True,
+ "reason_code": "evidence_confirms",
+ "evidence_ref": "open_demo_utility_login_output",
+ }
+ ]
+ }
+
+ _patch_completion_handler(monkeypatch, handler)
+ ctx = _run_ctx()
+ _set_workflow_labels(ctx, "open_demo_utility_login")
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=build_classifier_fallback_floor([]),
+ classifier_status="fallback",
+ )
+ result = {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_login_only",
+ "overall_status": "completed",
+ "executed_block_labels": ["open_demo_utility_login"],
+ "current_url": "http://localhost:8900/utility_services/demo_utility/",
+ "page_title": "Login",
+ "blocks": [
+ {
+ "label": "open_demo_utility_login",
+ "block_type": "CODE",
+ "status": "completed",
+ "extracted_data": {
+ "login_page_reached": True,
+ "evidence_text": "Sample Utility Portal Log in to your account User ID Password",
+ },
+ }
+ ],
+ },
+ }
+
+ verification = await _maybe_run_completion_verification(ctx, result, time.monotonic())
+
+ assert verification is not None
+ assert verification.is_fully_satisfied() is False
+ assert verification.verdicts[0].criterion_id == "__copilot_fallback_floor__run"
+ assert verification.verdicts[0].state == "unsatisfied"
+ assert verification.verdicts[0].reason_code == "no_evidence"
+ assert verification.verdicts[0].evidence_ref is None
+
+
@pytest.mark.asyncio
async def test_maybe_run_completion_verification_mixed_terminal_goal_upgrades_judge_unknown(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index bbd66b3b2..a3d71a8bf 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -14,24 +14,38 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
+from agents import RunConfig
-from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
+from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, stash_blocker_signal
+from skyvern.forge.sdk.copilot.code_block_synthesis import SynthesizedCodeBlock
from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdict
+from skyvern.forge.sdk.copilot.config import SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD, BlockAuthoringPolicy
+from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.enforcement import (
KEEP_RECENT_TOOL_OUTPUTS,
POST_SUSPICIOUS_SUCCESS_NUDGE,
+ SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE,
CopilotGoalSatisfied,
_check_enforcement,
+ _maybe_synthesized_block_offer_msg,
_needs_suspicious_success_nudge,
_prune_input_list,
+ _should_force_synthesized_block_persistence,
_summarize_tool_output,
+ run_with_enforcement,
+ synthesized_block_persistence_signal,
+ synthesized_persistence_reopened_after_failed_run,
+ synthesized_trajectory_is_goal_complete,
)
+from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget
from skyvern.forge.sdk.copilot.tools import (
_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY,
_analyze_run_blocks,
_is_meaningful_extracted_data,
_record_run_blocks_result,
+ _record_workflow_update_result,
)
+from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode
from skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidence
@@ -67,6 +81,679 @@ class _Ctx:
self.completion_verification_result = None
self.last_artifact_health_blocker_reason = None
self.latest_diagnosis_repair_contract = None
+ self.synthesized_block_reopened_after_failed_run = False
+
+
+class TestSynthesizedOfferPersistenceGate:
+ @staticmethod
+ def _unsatisfied_verification() -> CompletionVerificationResult:
+ return CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["fallback"],
+ verdicts=[
+ CriterionVerdict(
+ criterion_id="fallback",
+ state="unsatisfied",
+ reason_code="evidence_contradicts",
+ )
+ ],
+ )
+
+ def _authoring_ctx(
+ self,
+ *,
+ trajectory: list[dict[str, object]],
+ download_target: ReachedDownloadTarget | None,
+ ) -> _Ctx:
+ ctx = _Ctx()
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = len(trajectory)
+ ctx.scout_trajectory = trajectory
+ ctx.reached_download_target = download_target
+ ctx.synthesized_block_offered_goal_complete = synthesized_trajectory_is_goal_complete(ctx)
+ return ctx
+
+ @pytest.mark.asyncio
+ async def test_offer_retry_forces_update_and_run_blocks_tool_choice(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ ctx = _Ctx()
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "type_text",
+ "selector": "input[name='q']",
+ "source_url": "https://example.test/start",
+ "accessible_name": "Search",
+ },
+ {
+ "tool_name": "click",
+ "selector": "button[data-action='search']",
+ "accessible_name": "Search",
+ },
+ ]
+ ctx.synthesized_block_offered = False
+ ctx.synthesized_block_offered_trajectory_len = 0
+ ctx.reached_download_target = None
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+
+ fake_result = MagicMock()
+ fake_result.final_output = None
+ fake_result.new_items = []
+ fake_result.to_input_list.return_value = []
+ run_configs: list[RunConfig | None] = []
+
+ def fake_run_streamed(*args: Any, **kwargs: Any) -> Any:
+ run_configs.append(kwargs.get("run_config"))
+ return fake_result
+
+ async def fake_stream_to_sse(result: Any, s: Any, c: Any) -> None:
+ if len(run_configs) >= 2:
+ c.update_workflow_called = True
+ c.test_after_update_done = True
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",
+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.click('button')"),
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.Runner.run_streamed", fake_run_streamed)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.streaming_adapter.stream_to_sse",
+ fake_stream_to_sse,
+ )
+
+ returned = await run_with_enforcement(
+ agent=MagicMock(),
+ initial_input="hello",
+ ctx=ctx,
+ stream=stream,
+ run_config=RunConfig(),
+ )
+
+ assert returned is fake_result
+ assert len(run_configs) == 2
+ assert run_configs[0].model_settings is None
+ assert run_configs[1].model_settings is not None
+ assert run_configs[1].model_settings.tool_choice == "update_and_run_blocks"
+
+ @pytest.mark.asyncio
+ async def test_diagnose_offer_retry_does_not_force_update_and_run_blocks_tool_choice(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ ctx = _Ctx()
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.DIAGNOSE,
+ authority=TurnIntentAuthority(may_read_run_context=True),
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "click",
+ "selector": "button[data-action='continue']",
+ "source_url": "https://example.test/start",
+ }
+ ]
+ ctx.synthesized_block_offered = False
+ ctx.synthesized_block_offered_trajectory_len = 0
+ ctx.reached_download_target = None
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+
+ fake_result = MagicMock()
+ fake_result.final_output = None
+ fake_result.new_items = []
+ fake_result.to_input_list.return_value = []
+ run_configs: list[RunConfig | None] = []
+
+ def fake_run_streamed(*args: Any, **kwargs: Any) -> Any:
+ run_configs.append(kwargs.get("run_config"))
+ return fake_result
+
+ async def fake_stream_to_sse(result: Any, s: Any, c: Any) -> None:
+ if len(run_configs) >= 2:
+ c.update_workflow_called = True
+ c.test_after_update_done = True
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",
+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.click('button')"),
+ )
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.Runner.run_streamed", fake_run_streamed)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.streaming_adapter.stream_to_sse",
+ fake_stream_to_sse,
+ )
+
+ returned = await run_with_enforcement(
+ agent=MagicMock(),
+ initial_input="hello",
+ ctx=ctx,
+ stream=stream,
+ run_config=RunConfig(),
+ )
+
+ assert returned is fake_result
+ assert len(run_configs) == 2
+ assert run_configs[0].model_settings is None
+ assert run_configs[1].model_settings is None
+
+ def test_authoring_offer_blocks_non_persistence_tool_until_update_and_run_blocks(self) -> None:
+ ctx = _Ctx()
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = 2
+ ctx.synthesized_block_offered_goal_complete = True
+ ctx.scout_trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+
+ signal = synthesized_block_persistence_signal(ctx, "evaluate")
+
+ assert isinstance(signal, CopilotToolBlockerSignal)
+ assert signal.internal_reason_code == SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE
+ assert signal.blocked_tool == "evaluate"
+ assert signal.cleared_by_tools == frozenset({"update_and_run_blocks"})
+ assert signal.recovery_hint == "retry_with_different_tool"
+ assert signal.renders_final_reply is False
+ assert synthesized_block_persistence_signal(ctx, "update_and_run_blocks") is None
+
+ @pytest.mark.parametrize(
+ "ctx_attrs",
+ [
+ {"synthesized_block_offered": False, "synthesized_block_offered_trajectory_len": 0},
+ {"synthesized_block_offered": True, "synthesized_block_offered_trajectory_len": 0},
+ {
+ "synthesized_block_offered": True,
+ "synthesized_block_offered_trajectory_len": 4,
+ "update_workflow_called": True,
+ },
+ ],
+ ids=["no_offer", "zero_trajectory", "update_called"],
+ )
+ def test_non_persistence_tool_unaffected_without_active_offer_or_after_update(
+ self,
+ ctx_attrs: dict[str, object],
+ ) -> None:
+ ctx = _Ctx()
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ for key, value in ctx_attrs.items():
+ setattr(ctx, key, value)
+
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ def test_recorded_workflow_update_clears_synthesized_persistence_gate(self) -> None:
+ ctx = CopilotContext(
+ organization_id="o",
+ workflow_id="w",
+ workflow_permanent_id="wp",
+ workflow_yaml="title: Updated",
+ browser_session_id=None,
+ stream=SimpleNamespace(),
+ )
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = 2
+ ctx.scout_trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx.synthesized_block_offered_goal_complete = True
+
+ _record_workflow_update_result(
+ ctx,
+ {
+ "ok": True,
+ "data": {"block_count": 1},
+ "_workflow": SimpleNamespace(workflow_definition=SimpleNamespace(blocks=[SimpleNamespace()])),
+ },
+ )
+
+ assert ctx.update_workflow_called is True
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ def test_recorded_workflow_update_clears_reopened_synthesized_persistence_latch(self) -> None:
+ ctx = CopilotContext(
+ organization_id="o",
+ workflow_id="w",
+ workflow_permanent_id="wp",
+ workflow_yaml="title: Updated",
+ browser_session_id=None,
+ stream=SimpleNamespace(),
+ )
+ ctx.synthesized_block_reopened_after_failed_run = True
+
+ _record_workflow_update_result(
+ ctx,
+ {
+ "ok": True,
+ "data": {"block_count": 1},
+ "_workflow": SimpleNamespace(workflow_definition=SimpleNamespace(blocks=[SimpleNamespace()])),
+ },
+ )
+
+ assert ctx.synthesized_block_reopened_after_failed_run is False
+
+ def test_stale_shorter_offer_does_not_force_current_goal_complete_trajectory(self) -> None:
+ previous_trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ ]
+ trajectory = [
+ *previous_trajectory,
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.synthesized_block_offered_trajectory_len = len(previous_trajectory)
+ ctx.synthesized_block_offered_goal_complete = False
+
+ assert synthesized_trajectory_is_goal_complete(ctx) is True
+ assert _should_force_synthesized_block_persistence(ctx) is False
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ def test_refreshed_goal_complete_offer_forces_current_trajectory(self) -> None:
+ trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+
+ assert ctx.synthesized_block_offered_trajectory_len == len(trajectory)
+ assert ctx.synthesized_block_offered_goal_complete is True
+ assert _should_force_synthesized_block_persistence(ctx) is True
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is not None
+
+ def test_failed_verified_run_with_new_commit_reopens_synthesized_persistence_gate(self) -> None:
+ previous_trajectory = [
+ {
+ "tool_name": "fill_credential_field",
+ "selector": "#username",
+ "credential_id": "cred_1",
+ "credential_field": "username",
+ },
+ {"tool_name": "click", "selector": "button[data-action='login']", "accessible_name": "Log in"},
+ ]
+ trajectory = [
+ *previous_trajectory,
+ {"tool_name": "click", "selector": "button[data-action='businessToggle']", "accessible_name": "Business"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.update_workflow_called = True
+ ctx.test_after_update_done = True
+ ctx.last_test_ok = False
+ ctx.completion_verification_result = self._unsatisfied_verification()
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = len(previous_trajectory)
+ ctx.synthesized_block_offered_goal_complete = True
+
+ assert synthesized_persistence_reopened_after_failed_run(ctx) is True
+ assert _should_force_synthesized_block_persistence(ctx) is False
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ assert _maybe_synthesized_block_offer_msg(ctx) is not None
+ assert ctx.synthesized_block_offered_trajectory_len == len(trajectory)
+ assert _should_force_synthesized_block_persistence(ctx) is True
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is not None
+
+ def test_failed_verified_run_without_new_commit_keeps_synthesized_persistence_gate_clear(self) -> None:
+ previous_trajectory = [
+ {
+ "tool_name": "fill_credential_field",
+ "selector": "#username",
+ "credential_id": "cred_1",
+ "credential_field": "username",
+ },
+ {"tool_name": "click", "selector": "button[data-action='login']", "accessible_name": "Log in"},
+ ]
+ trajectory = [
+ *previous_trajectory,
+ {
+ "tool_name": "fill_credential_field",
+ "selector": "#password",
+ "credential_id": "cred_1",
+ "credential_field": "password",
+ },
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.update_workflow_called = True
+ ctx.test_after_update_done = True
+ ctx.last_test_ok = False
+ ctx.completion_verification_result = self._unsatisfied_verification()
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = len(previous_trajectory)
+ ctx.synthesized_block_offered_goal_complete = True
+
+ assert synthesized_persistence_reopened_after_failed_run(ctx) is False
+ assert _should_force_synthesized_block_persistence(ctx) is False
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ def test_diagnose_offer_does_not_block_non_persistence_tool(self) -> None:
+ ctx = _Ctx()
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.DIAGNOSE,
+ authority=TurnIntentAuthority(may_read_run_context=True),
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = 4
+
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ @pytest.mark.parametrize(
+ "trajectory, download_target, expected_complete",
+ [
+ ([], None, False),
+ ([{"tool_name": "click", "selector": "a.home", "accessible_name": "Home"}], None, False),
+ ([{"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"}], None, False),
+ (
+ [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {"tool_name": "select_option", "selector": "select#state", "value": "CA"},
+ {"tool_name": "click", "selector": "button[type='submit']", "accessible_name": "Continue"},
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {"tool_name": "select_option", "selector": "select#state", "value": ""},
+ {"tool_name": "click", "selector": "button[type='submit']", "accessible_name": "Continue"},
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {"tool_name": "fill_credential_field", "credential_field": "username"},
+ {"tool_name": "click", "selector": "button[type='submit']", "accessible_name": "Log in"},
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {"tool_name": "fill_credential_field", "credential_id": "cred", "credential_field": "username"},
+ {"tool_name": "fill_credential_field", "credential_id": "cred", "credential_field": "password"},
+ {"tool_name": "click", "selector": "button[type='submit']", "accessible_name": "Log in"},
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {"tool_name": "fill_credential_field", "credential_id": "cred", "credential_field": "username"},
+ {"tool_name": "click", "selector": "button"},
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {"tool_name": "fill_credential_field", "credential_id": "cred", "credential_field": "username"},
+ {"tool_name": "fill_credential_field", "credential_id": "cred", "credential_field": "password"},
+ {"tool_name": "click", "selector": "button[type='submit']", "accessible_name": "Log in"},
+ {"tool_name": "type_text", "selector": "input[name='amount']", "accessible_name": "Amount"},
+ {"tool_name": "click", "selector": "button[data-action='pay']", "accessible_name": "Pay"},
+ ],
+ None,
+ True,
+ ),
+ (
+ [{"tool_name": "click", "selector": "a.report", "accessible_name": "Report"}],
+ ReachedDownloadTarget(
+ selector="a.report",
+ affordance_text="Report",
+ download_kind="extension",
+ source_step="trajectory_recency",
+ already_registered=False,
+ ),
+ True,
+ ),
+ ],
+ ids=[
+ "empty",
+ "navigate_only",
+ "type_text_only",
+ "type_text_then_commit",
+ "select_with_value_then_commit",
+ "select_empty_value_dropped",
+ "credential_missing_id_dropped",
+ "valid_login_fill_and_submit",
+ "valid_fill_generic_opener_only",
+ "post_login_durable_entry_then_commit",
+ "reached_download_target",
+ ],
+ )
+ def test_goal_completeness_drives_force_and_blocker_in_lockstep(
+ self,
+ trajectory: list[dict[str, object]],
+ download_target: ReachedDownloadTarget | None,
+ expected_complete: bool,
+ ) -> None:
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=download_target)
+
+ assert synthesized_trajectory_is_goal_complete(ctx) is expected_complete
+ assert _should_force_synthesized_block_persistence(ctx) is expected_complete
+ blocked = synthesized_block_persistence_signal(ctx, "evaluate") is not None
+ assert blocked is expected_complete
+
+ def test_extract_shaped_lookup_submit_is_goal_complete_without_extract_step(self) -> None:
+ trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='reference']", "accessible_name": "Reference"},
+ {"tool_name": "click", "selector": "button[data-action='lookup']", "accessible_name": "Look up"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+
+ assert not any(
+ str(item.get("tool_name") or "") in {"extract", "get_run_results", "evaluate"} for item in trajectory
+ )
+ assert synthesized_trajectory_is_goal_complete(ctx) is True
+ assert _should_force_synthesized_block_persistence(ctx) is True
+
+ @pytest.mark.parametrize(
+ "guard_attrs",
+ [
+ {"update_workflow_called": True},
+ {"synthesized_block_offered": False},
+ {"block_authoring_policy": BlockAuthoringPolicy.STANDARD},
+ ],
+ ids=["already_authored", "not_offered", "policy_not_code_only"],
+ )
+ def test_early_guards_never_force_even_when_goal_complete(self, guard_attrs: dict[str, object]) -> None:
+ trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ for key, value in guard_attrs.items():
+ setattr(ctx, key, value)
+
+ assert _should_force_synthesized_block_persistence(ctx) is False
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ def test_diagnose_turn_intent_never_forces_even_when_goal_complete(self) -> None:
+ trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.DIAGNOSE,
+ authority=TurnIntentAuthority(may_read_run_context=True),
+ )
+
+ assert _should_force_synthesized_block_persistence(ctx) is False
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ def test_update_only_turn_intent_never_forces_update_and_run_blocks_even_when_goal_complete(self) -> None:
+ trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.DRAFT_ONLY,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=False),
+ )
+
+ assert synthesized_trajectory_is_goal_complete(ctx) is True
+ assert _should_force_synthesized_block_persistence(ctx) is False
+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None
+
+ def test_goal_complete_commit_refreshes_offer_below_threshold(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",
+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.click('button')"),
+ )
+ trajectory = [
+ {"tool_name": "click", "selector": "a.home", "accessible_name": "Home"},
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = 2
+ ctx.synthesized_block_offered_goal_complete = False
+ assert len(trajectory) < 2 + SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD
+
+ message = _maybe_synthesized_block_offer_msg(ctx)
+
+ assert message is not None
+ assert ctx.synthesized_block_offered_trajectory_len == len(trajectory)
+ assert ctx.synthesized_block_offered_goal_complete is True
+
+ def test_goal_complete_offer_refresh_suppresses_near_duplicate_followup(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",
+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.click('button')"),
+ )
+ trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='open']", "accessible_name": "Open"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = 2
+ ctx.synthesized_block_offered_goal_complete = True
+ assert len(trajectory) < 2 + SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD
+
+ message = _maybe_synthesized_block_offer_msg(ctx)
+
+ assert message is None
+ assert ctx.synthesized_block_offered_trajectory_len == 2
+
+ def test_failed_verified_run_with_new_commit_refreshes_offer_below_threshold(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",
+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.click('button')"),
+ )
+ previous_trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ trajectory = [
+ *previous_trajectory,
+ {"tool_name": "click", "selector": "button[data-action='details']", "accessible_name": "Details"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.update_workflow_called = True
+ ctx.test_after_update_done = True
+ ctx.last_test_ok = False
+ ctx.completion_verification_result = self._unsatisfied_verification()
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = len(previous_trajectory)
+ ctx.synthesized_block_offered_goal_complete = True
+ assert len(trajectory) < len(previous_trajectory) + SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD
+
+ message = _maybe_synthesized_block_offer_msg(ctx)
+
+ assert message is not None
+ assert ctx.synthesized_block_offered_trajectory_len == len(trajectory)
+ assert ctx.synthesized_block_reopened_after_failed_run is True
+
+ def test_sub_threshold_offer_stays_suppressed_when_not_goal_complete(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",
+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.click('button')"),
+ )
+ trajectory = [
+ {"tool_name": "click", "selector": "a.home", "accessible_name": "Home"},
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = 1
+ assert len(trajectory) < 1 + SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD
+
+ message = _maybe_synthesized_block_offer_msg(ctx)
+
+ assert message is None
+ assert ctx.synthesized_block_offered_trajectory_len == 1
+
+ def test_terminal_blocker_replaces_nonterminal_synthesized_persistence_blocker(self) -> None:
+ ctx = _Ctx()
+ persistence_signal = CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text="Persist the drafted workflow before more scouting.",
+ user_facing_reason="I need to save and test the drafted workflow before scouting more.",
+ recovery_hint="retry_with_different_tool",
+ cleared_by_tools=frozenset({"update_and_run_blocks"}),
+ preserves_workflow_draft=True,
+ renders_final_reply=False,
+ internal_reason_code=SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE,
+ blocked_tool="click",
+ )
+ terminal_signal = CopilotToolBlockerSignal(
+ blocker_kind="loop_detected",
+ agent_steering_text="Report that repeated repair attempts did not verify the workflow outcome.",
+ user_facing_reason="The workflow was saved and tested, but repeated repairs did not reach the required review page.",
+ recovery_hint="report_blocker_to_user",
+ cleared_by_tools=frozenset(),
+ preserves_workflow_draft=True,
+ renders_final_reply=True,
+ internal_reason_code="repair_ceiling_reached",
+ blocked_tool="update_and_run_blocks",
+ )
+
+ stash_blocker_signal(ctx, persistence_signal)
+ stash_blocker_signal(ctx, terminal_signal)
+
+ assert ctx.blocker_signal is terminal_signal
# ---------------------------------------------------------------------------
diff --git a/tests/unit/test_copilot_loop_detection_blocker.py b/tests/unit/test_copilot_loop_detection_blocker.py
index e589d7fd9..0af98aa18 100644
--- a/tests/unit/test_copilot_loop_detection_blocker.py
+++ b/tests/unit/test_copilot_loop_detection_blocker.py
@@ -14,7 +14,9 @@ from skyvern.forge.sdk.copilot.blocker_signal import (
assert_clean_user_facing_text,
loop_blocker_evidence_from_ctx,
)
+from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.copilot.enforcement import SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE
from skyvern.forge.sdk.copilot.mcp_adapter import SchemaOverlay, SkyvernOverlayMCPServer, _stash_and_emit_loop_blocker
from skyvern.forge.sdk.copilot.output_policy import CopilotOutputKind, evaluate_output_policy
from skyvern.forge.sdk.copilot.result_evidence import LoadedResultCompositionEvidence
@@ -22,6 +24,7 @@ from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REA
from skyvern.forge.sdk.copilot.tools import _build_loop_blocker_signal, _tool_loop_error
from skyvern.forge.sdk.copilot.tools.mcp_hooks import get_skyvern_mcp_alias_map
from skyvern.forge.sdk.copilot.turn_halt import TurnHaltKind
+from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode
_LEAK_TOKENS = ("safe_reason_code", "LOOP DETECTED:")
@@ -544,6 +547,51 @@ async def test_mcp_browser_tool_terminal_challenge_preempts_same_tool_loop() ->
assert ctx.turn_halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE
+async def test_mcp_synthesized_offer_gate_preempts_evaluate_loop_without_terminal_halt() -> None:
+ ctx = _ctx(consecutive_tool_tracker=["evaluate", "evaluate"])
+ ctx.turn_intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = 2
+ ctx.synthesized_block_offered_goal_complete = True
+ ctx.scout_trajectory = [
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx.reached_download_target = None
+ ctx.update_workflow_called = False
+
+ class _UnexpectedClient:
+ async def call_tool(self, name: str, args: dict, raise_on_error: bool = False) -> object:
+ raise AssertionError("persistence gate should skip MCP execution")
+
+ server = SkyvernOverlayMCPServer(
+ transport=None,
+ overlays={},
+ alias_map={},
+ allowlist=frozenset({"evaluate"}),
+ context_provider=lambda: ctx,
+ )
+ server._client = _UnexpectedClient() # type: ignore[assignment]
+
+ result = await server.call_tool("evaluate", {"expression": "document.body.innerText"})
+
+ parsed = json.loads(result.content[0].text)
+ assert result.isError is True
+ assert parsed["ok"] is False
+ signal = ctx.blocker_signal
+ assert isinstance(signal, CopilotToolBlockerSignal)
+ assert signal.internal_reason_code == SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE
+ assert signal.blocked_tool == "evaluate"
+ assert signal.cleared_by_tools == frozenset({"update_and_run_blocks"})
+ assert signal.renders_final_reply is False
+ assert ctx.turn_halt is None
+
+
def test_tool_loop_error_entry_refreshes_stale_held_loop_signal() -> None:
ctx = _ctx()
stale = _build_loop_blocker_signal(_BRANCH_MESSAGES["loop_detected_consecutive_same_tool"], tool_name="evaluate")
diff --git a/tests/unit/test_copilot_streaming_adapter.py b/tests/unit/test_copilot_streaming_adapter.py
index 22afa1354..aa6ee3ba9 100644
--- a/tests/unit/test_copilot_streaming_adapter.py
+++ b/tests/unit/test_copilot_streaming_adapter.py
@@ -11,7 +11,7 @@ from agents.items import RunItem
from agents.stream_events import RunItemStreamEvent
from skyvern.forge.sdk.copilot.context import CopilotContext
-from skyvern.forge.sdk.copilot.streaming_adapter import _sanitize_input, stream_to_sse
+from skyvern.forge.sdk.copilot.streaming_adapter import _sanitize_input, _update_enforcement_from_tool, stream_to_sse
from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotStreamMessageType
@@ -644,6 +644,7 @@ class TestEnforcementStateUpdates:
ctx.post_update_nudge_count = 0
ctx.navigate_called = False
ctx.observation_after_navigate = False
+ ctx.synthesized_block_reopened_after_failed_run = False
return ctx
def test_update_workflow_sets_flags(self) -> None:
@@ -682,6 +683,16 @@ class TestEnforcementStateUpdates:
assert ctx.update_workflow_called is True
assert ctx.test_after_update_done is True
+ def test_persisted_blocks_clear_reopened_synthesized_offer_latch(self) -> None:
+ ctx = self._make_ctx()
+ ctx.synthesized_block_reopened_after_failed_run = True
+ _update_enforcement_from_tool(
+ ctx,
+ "update_and_run_blocks",
+ {"ok": False, "data": {"block_count": 2}},
+ )
+ assert ctx.synthesized_block_reopened_after_failed_run is False
+
def test_navigate_sets_flags(self) -> None:
from skyvern.forge.sdk.copilot.streaming_adapter import _update_enforcement_from_tool