Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Keep required steps in generated browser workflows (#7632)
Andrew Neilson950990aabcc5
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex 481f7f8b2..2c9678e00 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -47,7 +47,9 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (is_durable_fallback_entry_target,is_generic_entry_opener_click,is_optional_dismissal_only_trajectory,+ locator_selector_literals,missing_rung_text,+ normalized_scout_selector,obligation_finding_reason_code,obligation_finding_selector,render_missing_rung_call_sources,@@ -2200,6 +2202,16 @@ def _maybe_synthesized_block_offer_msg(ctx: Any) -> dict[str, Any] | None:trajectory_len = len(trajectory)previous_offer_len = getattr(ctx, "synthesized_block_offered_trajectory_len", 0) or 0trajectory_goal_complete = synthesized_trajectory_is_goal_complete(ctx)+ known_terminal_actions = _known_non_method_mandated_terminal_actions(ctx)+ business_goal_complete = (+ _trajectory_reaches_post_credential_commit(ctx) if known_terminal_actions else trajectory_goal_complete+ )+ if (+ (known_terminal_actions or _active_floor_rekeyed_runtime_outputs(ctx))+ and _last_scout_credential_fill_index(trajectory) is not None+ and not business_goal_complete+ ):+ return Noneif (getattr(ctx, "synthesized_block_offered", False)and trajectory_len < previous_offer_len + SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD@@ -2288,6 +2300,8 @@ def synthesized_persistence_reopened(ctx: AgentContext) -> bool:return Trueif ctx.synthesized_block_reopened_for_credential_scout:return True+ if getattr(ctx, "synthesized_block_reopened_for_capture_obligation", False):+ return Trueif synthesized_goal_completion_landing_pending(ctx):return Truereturn synthesized_persistence_reopened_after_failed_run(ctx)@@ -2711,13 +2725,52 @@ def _active_non_method_mandated_terminal_actions(ctx: AgentContext) -> tuple[Com)+def _known_non_method_mandated_terminal_actions(ctx: AgentContext) -> tuple[CompletionCriterion, ...]:+ return tuple(+ criterion+ for criterion in _coverage_completion_criteria(ctx)+ if criterion.kind == "terminal_action" and not criterion.method_mandated+ )+++def _active_floor_rekeyed_runtime_outputs(ctx: AgentContext) -> tuple[CompletionCriterion, ...]:+ """Runtime outputs whose exact paths were moved to producer-floor custody.++ They no longer participate in requested-output extraction planning, but they still prove the+ workflow has a business goal beyond authentication. A credential-only trajectory must not use+ the generic fill/commit heuristic to offer a completed block while these outputs are pending.+ """+ return tuple(+ criterion+ for criterion in _active_completion_criteria(ctx)+ if criterion.level == "run"+ and criterion.requested_output_floor_rekeyed+ and bool(criterion.floor_rekeyed_from_path)+ and criterion.requested_output_evidence_source == "runtime_output"+ )+++def _trajectory_has_noncredential_business_fill(trajectory: Sequence[Mapping[str, Any]]) -> bool:+ return trajectory_has_browser_fill_interaction(+ [+ interaction+ for interaction in trajectory+ if str(interaction.get("tool_name") or "").strip() != CREDENTIAL_FILL_TOOL_NAME+ ]+ )++def synthesized_trajectory_reaches_goal(ctx: AgentContext) -> bool:"""The scout trajectory covers an opening click followed by a commit, a durable entry followed by a commit,or a reached download target with a selector. Monotone in what the scout captured."""trajectory = ctx.scout_trajectoryif not trajectory:return False- if _active_non_method_mandated_terminal_actions(ctx):+ if _active_floor_rekeyed_runtime_outputs(ctx) and not _trajectory_has_noncredential_business_fill(trajectory):+ return False+ if _active_non_method_mandated_terminal_actions(ctx) or (+ _active_floor_rekeyed_runtime_outputs(ctx) and _last_scout_credential_fill_index(trajectory) is not None+ ):return _trajectory_reaches_post_credential_commit(ctx)return _trajectory_reaches_generic_goal(ctx, trajectory, include_download=True)@@ -2746,6 +2799,7 @@ def _trajectory_reaches_generic_goal(and trajectory_index > opening_trajectory_indexand str(interaction.get("tool_name") or "") in _SYNTHESIZED_BLOCK_COMMIT_TOOLSand not is_generic_entry_opener_click(interaction)+ and not _is_result_surface_navigation_click(interaction)):return Trueif opening_trajectory_index is None and str(interaction.get("tool_name") or "") == "click":@@ -2760,10 +2814,30 @@ def _trajectory_reaches_generic_goal(isinstance(item, dict)and str(item.get("tool_name") or "") in _SYNTHESIZED_BLOCK_COMMIT_TOOLSand not is_generic_entry_opener_click(item)+ and not _is_result_surface_navigation_click(item)for item in trajectory[last_entry_index + 1 :])+def _is_result_surface_navigation_click(interaction: Mapping[str, Any]) -> bool:+ """A results/list navigation click is not evidence that a business mutation committed."""+ if str(interaction.get("tool_name") or "") != "click":+ return False+ target = " ".join(+ (+ str(interaction.get("selector") or ""),+ str(interaction.get("accessible_name") or ""),+ )+ ).lower()+ if any(token in target for token in ("submit", "confirm", "save", "place-order", "place_order")):+ return False+ selector = str(interaction.get("selector") or "").strip().lower()+ role = str(interaction.get("role") or "").strip().lower()+ if role == "link" or selector.startswith(("a[", "a.", "a#")):+ return True+ return any(token in target for token in ("table", "results", "history", "listing"))++def _request_expects_unreached_download(ctx: AgentContext) -> bool:# A registered-download deliverable is confirmable only post-run, so it is absent from the pre-run# requested-output gate — a goal-reaching prefix (e.g. sign-in) would otherwise read goal-complete@@ -2924,7 +2998,7 @@ def _should_force_synthesized_block_persistence(ctx: Any) -> bool:def _should_block_mutating_tool_after_synthesized_offer(ctx: Any, tool_name: str) -> bool:if tool_name not in _SYNTHESIZED_BLOCK_PERSISTENCE_MUTATING_TOOLS:return False- if _active_non_method_mandated_terminal_actions(ctx):+ if _active_non_method_mandated_terminal_actions(ctx) or _active_floor_rekeyed_runtime_outputs(ctx):if not synthesized_trajectory_is_goal_complete(ctx):return Falseelse:@@ -3059,6 +3133,33 @@ def _credential_scout_reopen_admits_evaluate(ctx: CopilotContext, tool_name: strreturn tool_name == "evaluate" and bool(ctx.synthesized_block_reopened_for_credential_scout)+def _never_captured_obligation_admits_expected_tool(+ ctx: CopilotContext, tool_name: str, arguments: Mapping[str, Any] | None+) -> bool:+ obligation = getattr(ctx, "never_captured_obligation", None)+ if (+ obligation is None+ or obligation.state != "armed"+ or obligation.turn_id != ctx.turn_id+ or tool_name != obligation.expected_tool_name+ or not isinstance(arguments, Mapping)+ ):+ return False+ selector = arguments.get("selector")+ if not isinstance(selector, str) or not selector.strip():+ return False+ expected_selectors = {+ normalized_scout_selector(candidate) for candidate in locator_selector_literals(obligation.normalized_receiver)+ }+ if normalized_scout_selector(selector.strip()) not in expected_selectors:+ return False+ expected_argument = obligation.expected_argument_literal+ if expected_argument is None:+ return True+ argument_key = {"press_key": "key", "select_option": "value", "type_text": "text"}.get(tool_name)+ return argument_key is not None and str(arguments.get(argument_key) or "") == expected_argument++def consume_uncovered_output_reopen_event(ctx: CopilotContext) -> bool:"""Arm a one-shot scout-window reopen for the first author-time reject citing an uncoveredrequested-output path. Returns True only on that first reject per structural identity; a@@ -3144,7 +3245,9 @@ def _should_block_tool_after_unresolved_recorded_outcome(ctx: Any, tool_name: streturn _completion_verification_unsatisfied(ctx)-def synthesized_block_persistence_signal(ctx: Any, tool_name: str) -> CopilotToolBlockerSignal | None:+def synthesized_block_persistence_signal(+ ctx: Any, tool_name: str, arguments: Mapping[str, Any] | None = None+) -> CopilotToolBlockerSignal | None:if _should_block_tool_after_unresolved_recorded_outcome(ctx, tool_name):return CopilotToolBlockerSignal(blocker_kind="tool_error",@@ -3172,6 +3275,9 @@ def synthesized_block_persistence_signal(ctx: Any, tool_name: str) -> CopilotTooif _credential_scout_reopen_admits_evaluate(ctx, tool_name):claim_turn(ctx, TurnClaimant.CREDENTIAL_SCOUT_REOPEN)return None+ if _never_captured_obligation_admits_expected_tool(ctx, tool_name, arguments):+ claim_turn(ctx, TurnClaimant.CAPTURE_OBLIGATION_REOPEN)+ return Noneif _actuation_obligation_admits_required_fill_tool(ctx, tool_name):claim_turn(ctx, TurnClaimant.ACTUATION_OBLIGATION_FILL)return Nonediff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.pyindex 950e71a6c..9178ef175 100644--- a/skyvern/forge/sdk/copilot/mcp_adapter.py+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py@@ -68,6 +68,8 @@ _POST_HOOK_CONTEXT_ROLLBACK_FIELDS = ("pending_browser_interaction_observation","scouted_interactions","scout_trajectory",+ "never_captured_obligation",+ "synthesized_block_reopened_for_capture_obligation","pending_scout_source_url","pending_scout_typed_value","pending_scout_role_name",@@ -91,6 +93,7 @@ _POST_HOOK_CONTEXT_ROLLBACK_FIELDS = ("synthesized_block_offered","synthesized_block_offered_trajectory_len","synthesized_block_offered_goal_complete",+ "synthesized_business_required_parameter_keys","scouted_output_covered_paths","scout_observed_terminal_criterion_ids","scout_observation_contract",@@ -465,7 +468,7 @@ 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)+ persistence_signal = synthesized_block_persistence_signal(copilot_ctx, tool_name, arguments)if persistence_signal is not None:LOG.warning("Synthesized block persistence required before MCP tool",diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 3a6da9187..ccee4b060 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -7,7 +7,7 @@ import inspectfrom collections.abc import Sequencefrom contextlib import asynccontextmanagerfrom dataclasses import dataclass, field-from typing import TYPE_CHECKING, Any, AsyncIterator, Awaitable, NotRequired, TypeAlias, TypedDict, cast+from typing import TYPE_CHECKING, Any, AsyncIterator, Awaitable, Literal, NotRequired, TypeAlias, TypedDict, castimport structlog@@ -246,6 +246,39 @@ class ScoutedInteraction(TypedDict):credential_name: NotRequired[str]+NeverCapturedObligationState: TypeAlias = Literal["armed", "captured", "consumed"]+++@dataclass(frozen=True)+class NeverCapturedReplayPayload:+ """Turn-ephemeral inputs required to retry the exact rejected authoring call."""++ params: dict[str, Any]+ allow_missing_credentials: bool | None = None+ allow_static_output_uncertainty: bool = False+ formation_prepared: bool = False+++@dataclass(frozen=True)+class NeverCapturedObligation:+ """Turn-ephemeral authority to re-scout one exact authored browser mutation."""++ identity_digest: str+ turn_id: str+ draft_fingerprint: str+ block_label: str+ site: str+ method: str+ normalized_receiver: str+ call_shape_digest: str+ expected_tool_name: str+ armed_after_trajectory_index: int+ expected_argument_literal: str | None = None+ captured_trajectory_index: int | None = None+ state: NeverCapturedObligationState = "armed"+ replay_payload: NeverCapturedReplayPayload | None = None++@dataclassclass AgentContext:organization_id: str@@ -421,6 +454,10 @@ class AgentContext:# preserves repeats and ordering so code_block_synthesis can emit a faithful# linear Playwright trajectory.scout_trajectory: list[ScoutedInteraction] = field(default_factory=list)+ # One exact `never_captured` mutation may reopen scouting within this turn. The obligation is+ # completed only by a later generator-emitted canonical interaction, never by selector text alone.+ never_captured_obligation: NeverCapturedObligation | None = None+ never_captured_obligation_identity_history: set[str] = field(default_factory=set)# Latest typed reached-download target from the scout steer; the synthesizer compiles the terminal# expect_download step from it. Selector is the observed download link, not necessarily a trajectory click.reached_download_target: ReachedDownloadTarget | None = None@@ -499,6 +536,10 @@ class AgentContext:synthesized_block_reopened_after_failed_run: bool = Falsesynthesized_block_reopened_for_output_coverage: bool = Falsesynthesized_block_reopened_for_credential_scout: bool = False+ synthesized_block_reopened_for_capture_obligation: bool = False+ # Business inputs proven required by an earlier synthesized-draft rejection stay required for the+ # rest of the turn. A later retry cannot evade the floor by deleting those parameters from its YAML.+ synthesized_business_required_parameter_keys: set[str] = field(default_factory=set)scouted_output_covered_paths: set[str] = field(default_factory=set)# Ids of active terminal_action completion criteria the scout has structurally reached past the# login prefix; releases the is_goal_complete terminal-action gate mirroring reached_download_target.diff --git a/skyvern/forge/sdk/copilot/tools/blockers.py b/skyvern/forge/sdk/copilot/tools/blockers.pyindex dcd51ec23..c741098b1 100644--- a/skyvern/forge/sdk/copilot/tools/blockers.py+++ b/skyvern/forge/sdk/copilot/tools/blockers.py@@ -1531,7 +1531,7 @@ def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Anyif uncovered_output_steer is not None:return _emit_tool_blocker_signal(ctx, uncovered_output_steer)- persistence_signal = synthesized_block_persistence_signal(ctx, tool_name)+ persistence_signal = synthesized_block_persistence_signal(ctx, tool_name, arguments)if persistence_signal is not None:grounding_signal = _recorded_outcome_grounding_signal(ctx, tool_name)if grounding_signal is not None:diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.pyindex f5575cd6a..574594df9 100644--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py@@ -421,6 +421,36 @@ async def _screenshot_post_hook(return result+async def _maybe_replay_captured_never_captured_obligation(result: dict[str, Any], ctx: AgentContext) -> None:+ """Complete the capture/reconciliation handshake without another model-authored update call."""+ try:+ from .workflow_update import _replay_captured_never_captured_obligation++ replay = await _replay_captured_never_captured_obligation(ctx)+ except Exception:+ # The browser action already succeeded. Preserve its capture so the turn can+ # retry reconciliation instead of converting a save failure into capture loss.+ LOG.warning("copilot_never_captured_obligation_replay_failed", exc_info=True)+ return+ if replay is None:+ return+ result_data = result.get("data")+ if not isinstance(result_data, dict):+ result_data = {}+ result["data"] = result_data+ replay_data = replay.get("data")+ reconciliation: dict[str, Any] = {"ok": replay.get("ok") is True}+ if replay.get("ok") is True:+ message = replay_data.get("message") if isinstance(replay_data, dict) else None+ reconciliation["message"] = message or "Workflow reconciled after capturing the missing browser action."+ else:+ if replay.get("user_facing_summary"):+ reconciliation["user_facing_summary"] = replay["user_facing_summary"]+ if replay.get("error"):+ reconciliation["error"] = replay["error"]+ result_data["workflow_reconciliation"] = reconciliation++async def _click_post_hook(result: dict[str, Any],raw: dict[str, Any],@@ -480,6 +510,7 @@ async def _click_post_hook(await _attach_reperception_targets_on_non_advancing_click(result, raw, ctx, attempted_selector)except Exception:LOG.warning("copilot_click_reperception_attach_failed", exc_info=True)+ await _maybe_replay_captured_never_captured_obligation(result, ctx)return result@@ -797,6 +828,7 @@ async def _type_text_post_hook(result["data"]["observation_step"] = observation_stepif page_evidence is not None:_attach_scout_page_summary(result, page_evidence)+ await _maybe_replay_captured_never_captured_obligation(result, ctx)return result@@ -905,6 +937,7 @@ async def _select_option_post_hook(result["data"]["observation_step"] = observation_stepif page_evidence is not None:_attach_scout_page_summary(result, page_evidence)+ await _maybe_replay_captured_never_captured_obligation(result, ctx)return result@@ -932,6 +965,7 @@ async def _press_key_post_hook(source_url=source_url,key=data.get("key", ""),)+ await _maybe_replay_captured_never_captured_obligation(result, ctx)return resultdiff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.pyindex 00bbf9256..af4f8f7ab 100644--- a/skyvern/forge/sdk/copilot/tools/scouting.py+++ b/skyvern/forge/sdk/copilot/tools/scouting.py@@ -17,7 +17,12 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (recorded_outcome_from_loaded_result_evidence,recorded_outcome_from_scout_act_observe_hollow,)-from skyvern.forge.sdk.copilot.code_block_synthesis import normalized_scout_selector+from skyvern.forge.sdk.copilot.code_block_synthesis import (+ locator_selector_literals,+ normalized_locator_expr,+ normalized_scout_selector,+ synthesize_code_block,+)from skyvern.forge.sdk.copilot.composition_browser_expressions import (role_name_match_count_expression as _role_name_match_count_expression,)@@ -411,6 +416,87 @@ def _next_trajectory_index(trajectory: list[ScoutedInteraction]) -> int:return highest + 1 if highest >= 0 else len(trajectory)+def _maybe_complete_never_captured_obligation(+ ctx: AgentContext, *, interaction: ScoutedInteraction, trajectory_index: int+) -> None:+ obligation = getattr(ctx, "never_captured_obligation", None)+ if obligation is None or obligation.state != "armed":+ return+ if obligation.turn_id != str(getattr(ctx, "turn_id", "")):+ return+ tool_name = str(interaction.get("tool_name") or "")+ if tool_name != obligation.expected_tool_name or trajectory_index <= obligation.armed_after_trajectory_index:+ return+ # Bare locator obligations can reject unrelated same-tool events without paying for a full+ # trajectory synthesis. Non-bare canonical locators still fall through to the exact emitted+ # interaction comparison below.+ if obligation.normalized_receiver.startswith("page.locator("):+ expected_selectors = {+ normalized_scout_selector(candidate)+ for candidate in locator_selector_literals(obligation.normalized_receiver)+ }+ captured_selector = str(interaction.get("selector") or "").strip()+ if normalized_scout_selector(captured_selector) not in expected_selectors:+ return+ expected_argument = obligation.expected_argument_literal+ if expected_argument is not None:+ if tool_name == "press_key":+ captured_argument = str(interaction.get("key") or "")+ elif tool_name == "select_option":+ captured_argument = str(interaction.get("value") or "")+ elif tool_name == "type_text":+ captured_argument = str(interaction.get("raw_typed_value") or interaction.get("typed_value") or "")+ else:+ captured_argument = ""+ if captured_argument != expected_argument:+ return+ synthesized = synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)+ if synthesized is None:+ return+ current_position = next(+ (+ position+ for position, item in enumerate(ctx.scout_trajectory)+ if item.get("trajectory_index") == trajectory_index+ ),+ None,+ )+ if current_position is None:+ return+ emitted = next(+ (+ record+ for record in synthesized.diagnostics.emitted_interactions+ if record.get("trajectory_index") == current_position+ ),+ None,+ )+ if emitted is None:+ return+ method = str(emitted.get("method") or "")+ locator = normalized_locator_expr(str(emitted.get("locator") or ""))+ if method != obligation.method or locator != obligation.normalized_receiver:+ return+ ctx.never_captured_obligation = replace(+ obligation,+ captured_trajectory_index=trajectory_index,+ state="captured",+ )+ ctx.synthesized_block_reopened_for_capture_obligation = True+ LOG.info(+ "copilot_never_captured_obligation_completed",+ identity_digest=obligation.identity_digest,+ turn_id=obligation.turn_id,+ workflow_permanent_id=ctx.workflow_permanent_id,+ draft_fingerprint=obligation.draft_fingerprint,+ block_label=obligation.block_label,+ site=obligation.site,+ trajectory_index=trajectory_index,+ method=method,+ locator=locator,+ )++def _record_scouted_interaction(ctx: AgentContext,*,@@ -495,6 +581,11 @@ def _record_scouted_interaction(trajectory_artifact["trajectory_index"] = _next_trajectory_index(trajectory)trajectory.append(trajectory_artifact)ctx.scout_trajectory = _capped_with_eviction_accounting(trajectory, collection="scout_trajectory")+ _maybe_complete_never_captured_obligation(+ ctx,+ interaction=trajectory_artifact,+ trajectory_index=trajectory_artifact["trajectory_index"],+ )LOG.info("copilot_scout_interaction_captured",diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 6eca06a73..8d043d6f7 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -197,6 +197,8 @@ from skyvern.forge.sdk.copilot.runtime import (SYNTHESIZED_PARAMETER_BINDING_AMBIGUOUS_GATE_ID,AgentContext,AuthorTimeGateAblationPayload,+ NeverCapturedObligation,+ NeverCapturedReplayPayload,RejectedCodeArtifactMetadataCapture,ScoutedInteraction,copilot_author_time_gate_log_only_enabled,@@ -1798,6 +1800,9 @@ class _DefinitionPlaneReject(NamedTuple):unreferenced_parameter_keys: tuple[str, ...]+SYNTHESIZED_BUSINESS_INPUT_FLOOR_REASON_CODE = "synthesized_business_input_floor_unsatisfied"++def _expression_parameter_sources(expression: ast.AST, bindings: Mapping[str, set[str]]) -> set[str]:if isinstance(expression, ast.Name) and isinstance(expression.ctx, ast.Load):return set(bindings.get(expression.id, set()))@@ -2193,6 +2198,65 @@ def _definition_plane_preflight_reject()+def _synthesized_business_input_floor_reject(+ ctx: AgentContext,+ workflow_yaml: str,+ imposition: _SynthesizedCodeImpositionResult,+) -> _DefinitionPlaneReject | None:+ if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:+ return None+ if not (+ imposition.substitutions is not None or ctx.synthesized_block_offered or ctx.spine_imposition_owned_attempt+ ):+ return None+ criteria = _active_completion_criteria(ctx)+ has_business_goal = any(+ criterion.kind == "terminal_action"+ or (+ criterion.level == "run"+ and criterion.requested_output_floor_rekeyed+ and bool(criterion.floor_rekeyed_from_path)+ )+ for criterion in criteria+ )+ if not has_business_goal:+ return None+ rejection = _definition_plane_preflight_reject(+ ctx,+ workflow_yaml,+ enforce_untagged_declared_inputs=True,+ )+ retained_required_keys = set(getattr(ctx, "synthesized_business_required_parameter_keys", set()))+ if not retained_required_keys:+ return rejection if rejection is not None and rejection.unreferenced_parameter_keys else None+ parsed = parse_workflow_yaml(workflow_yaml)+ if not isinstance(parsed, dict):+ return rejection if rejection is not None and rejection.unreferenced_parameter_keys else None+ runtime_sources = _workflow_runtime_parameter_sources(parsed)+ if runtime_sources is None:+ return rejection if rejection is not None and rejection.unreferenced_parameter_keys else None+ missing_retained_keys = retained_required_keys - runtime_sources+ if not missing_retained_keys:+ return rejection if rejection is not None and rejection.unreferenced_parameter_keys else None+ current_missing_keys = set(rejection.unreferenced_parameter_keys) if rejection is not None else set()+ return _DefinitionPlaneReject(+ criterion_ids=(+ rejection.criterion_ids if rejection is not None else tuple(criterion.id for criterion in criteria)+ ),+ reason_codes=(+ rejection.reason_codes if rejection is not None else ("synthesized_required_parameters_unreferenced",)+ ),+ unreferenced_parameter_keys=tuple(sorted(current_missing_keys | missing_retained_keys)),+ )+++def _reopen_scout_after_synthesized_business_input_floor(ctx: AgentContext) -> None:+ ctx.synthesized_block_offered = False+ ctx.synthesized_block_offered_trajectory_len = 0+ ctx.synthesized_block_offered_goal_complete = False+ ctx.spine_imposition_owned_attempt = False++def _definition_plane_reject_error(rejection: _DefinitionPlaneReject) -> str:if rejection.unreferenced_parameter_keys:keys = ", ".join(f"`{key}`" for key in rejection.unreferenced_parameter_keys)@@ -7712,6 +7776,16 @@ def _code_block_parameter_contract_error(workflow_yaml: str) -> str | None:return "\n".join(errors) if errors else None+class _NeverCapturedObligationCandidate(NamedTuple):+ block_label: str+ site: str+ method: str+ receiver: str+ call_shape: str+ expected_tool_name: str+ expected_argument_literal: str | None++def _code_repair_progress_data(repair_context: CodeAuthoringRepairContext | None = None,*,@@ -7751,6 +7825,7 @@ class _SynthesizedCodeImpositionResult:minted_parameter_keys: list[str] = dataclass_field(default_factory=list)metadata_repair_contract: dict[str, object] | None = Noneablation_gate_id: str | None = None+ never_captured_candidate: _NeverCapturedObligationCandidate | None = None_SUBMITTED_LITERAL_METHODS = frozenset({"fill", "type"})@@ -7974,6 +8049,7 @@ def _should_impose_after_update_attempt(ctx: AgentContext) -> bool:(isinstance(target, ReachedDownloadTarget) and not target.already_registered and bool(target.selector.strip()))or synthesized_persistence_reopened_after_failed_run(ctx)or ctx.synthesized_block_reopened_for_credential_scout+ or ctx.synthesized_block_reopened_for_capture_obligationor _author_time_reject_reopens_synthesized_imposition(ctx))@@ -8369,6 +8445,8 @@ class _BrowserMutationSignature(NamedTuple):method: strreceiver: strcall_shape: str+ argument_literal: str | None+ generator_compatible: bool_BrowserSurfaceProvenanceKind = Literal["never_captured", "shape_diverged", "ambiguous", "suffix_disallowed"]@@ -8387,6 +8465,7 @@ class _BrowserSurfaceRejectionProvenance(NamedTuple):nearest_receiver: str | None = Nonenearest_selector: str | None = Nonedivergence_source: _BrowserSurfaceDivergenceSource | None = None+ mutation: _BrowserMutationSignature | None = Noneclass _BrowserSurfaceValidation(NamedTuple):@@ -8394,6 +8473,98 @@ class _BrowserSurfaceValidation(NamedTuple):provenance: list[_BrowserSurfaceRejectionProvenance]+_NEVER_CAPTURED_SCOUT_TOOL_BY_METHOD = {+ "click": "click",+ "fill": "type_text",+ "press": "press_key",+ "select_option": "select_option",+}+++def _never_captured_obligation_candidate(+ provenance: Iterable[_BrowserSurfaceRejectionProvenance],+) -> _NeverCapturedObligationCandidate | None:+ for record in provenance:+ mutation = record.mutation+ if record.kind != "never_captured" or mutation is None:+ continue+ expected_tool_name = _NEVER_CAPTURED_SCOUT_TOOL_BY_METHOD.get(mutation.method)+ if expected_tool_name is None or not mutation.generator_compatible:+ continue+ if mutation.method == "press" and mutation.argument_literal is None:+ continue+ return _NeverCapturedObligationCandidate(+ block_label=record.block_label,+ site=record.site,+ method=mutation.method,+ receiver=normalized_locator_expr(mutation.receiver),+ call_shape=mutation.call_shape,+ expected_tool_name=expected_tool_name,+ expected_argument_literal=mutation.argument_literal,+ )+ return None+++def _arm_never_captured_obligation(+ ctx: AgentContext,+ workflow_yaml: str,+ candidate: _NeverCapturedObligationCandidate | None,+ replay_payload: NeverCapturedReplayPayload,+) -> None:+ if candidate is None:+ return+ turn_id = str(getattr(ctx, "turn_id", ""))+ draft_fingerprint = hashlib.sha256(workflow_yaml.encode()).hexdigest()+ call_shape_digest = hashlib.sha256(candidate.call_shape.encode()).hexdigest()+ identity_payload = "\0".join(+ (+ turn_id,+ draft_fingerprint,+ candidate.block_label,+ candidate.site,+ candidate.method,+ candidate.receiver,+ call_shape_digest,+ )+ )+ identity_digest = hashlib.sha256(identity_payload.encode()).hexdigest()+ if identity_digest in ctx.never_captured_obligation_identity_history:+ return+ armed_after_trajectory_index = max(+ (index for item in ctx.scout_trajectory if isinstance((index := item.get("trajectory_index")), int)),+ default=-1,+ )+ ctx.never_captured_obligation = NeverCapturedObligation(+ identity_digest=identity_digest,+ turn_id=turn_id,+ draft_fingerprint=draft_fingerprint,+ block_label=candidate.block_label,+ site=candidate.site,+ method=candidate.method,+ normalized_receiver=candidate.receiver,+ call_shape_digest=call_shape_digest,+ expected_tool_name=candidate.expected_tool_name,+ armed_after_trajectory_index=armed_after_trajectory_index,+ expected_argument_literal=candidate.expected_argument_literal,+ replay_payload=replay_payload,+ )+ ctx.never_captured_obligation_identity_history.add(identity_digest)+ LOG.info(+ "copilot_never_captured_obligation_armed",+ identity_digest=identity_digest,+ turn_id=turn_id,+ workflow_permanent_id=ctx.workflow_permanent_id,+ draft_fingerprint=draft_fingerprint,+ block_label=candidate.block_label,+ site=candidate.site,+ method=candidate.method,+ receiver=candidate.receiver,+ call_shape_digest=call_shape_digest,+ expected_tool_name=candidate.expected_tool_name,+ armed_after_trajectory_index=armed_after_trajectory_index,+ )++class _BrowserBindings(NamedTuple):page_aliases: set[str]locator_aliases: set[str]@@ -8462,6 +8633,23 @@ def _direct_page_method_signature(node: ast.AST) -> str | None:return "page"+def _browser_mutation_argument_literal(node: ast.Call) -> str | None:+ if not node.args:+ return None+ value = node.args[0]+ return value.value if isinstance(value, ast.Constant) and isinstance(value.value, str) else None+++def _browser_mutation_is_generator_compatible(node: ast.Call, method: str) -> bool:+ if node.keywords:+ return False+ if method == "click":+ return not node.args+ if method in {"fill", "press", "select_option"}:+ return len(node.args) == 1+ return False++def _bounded_nth_constant(node: ast.AST) -> bool:return (isinstance(node, ast.Constant)@@ -8480,12 +8668,24 @@ def _browser_mutation_signature_for_call(node: ast.Call) -> _BrowserMutationSignfunc.value)if receiver is not None:- return _BrowserMutationSignature(func.attr, receiver, ast.dump(node, include_attributes=False))+ return _BrowserMutationSignature(+ func.attr,+ receiver,+ ast.dump(node, include_attributes=False),+ _browser_mutation_argument_literal(node),+ _browser_mutation_is_generator_compatible(node, func.attr),+ )return Noneif func.attr in _PAGE_MUTATION_METHODS:receiver = _direct_page_method_signature(func.value)if receiver is not None:- return _BrowserMutationSignature(func.attr, receiver, ast.dump(node, include_attributes=False))+ return _BrowserMutationSignature(+ func.attr,+ receiver,+ ast.dump(node, include_attributes=False),+ _browser_mutation_argument_literal(node),+ False,+ )return None@@ -8813,6 +9013,7 @@ def _classify_unscouted_mutation(nearest_receiver=exact.receiver,nearest_selector=_captured_selector_for_signature(exact, diagnostics),divergence_source="synthesized",+ mutation=mutation,)receiver_literals = locator_selector_literals(mutation.receiver)emitted_records = diagnostics.emitted_interactions if diagnostics is not None else []@@ -8828,6 +9029,7 @@ def _classify_unscouted_mutation(nearest_receiver=str(record.get("locator") or "") or None,nearest_selector=selector,divergence_source="synthesized",+ mutation=mutation,)dropped_records = diagnostics.dropped_interactions if diagnostics is not None else []for record in dropped_records:@@ -8844,6 +9046,7 @@ def _classify_unscouted_mutation(nearest_method=mutation.method,nearest_selector=selector or None,divergence_source="trajectory_dropped",+ mutation=mutation,)nearest = next((signature for signature in scouted_mutations if signature.method == mutation.method), None) or next((signature for signature in scouted_mutations if signature.receiver == mutation.receiver), None@@ -8856,6 +9059,7 @@ def _classify_unscouted_mutation(nearest_method=nearest.method if nearest is not None else None,nearest_receiver=nearest.receiver if nearest is not None else None,nearest_selector=_captured_selector_for_signature(nearest, diagnostics) if nearest is not None else None,+ mutation=mutation,)@@ -9434,6 +9638,7 @@ def _freehand_surface_reject(workflow_yaml=workflow_yaml,violations=validation.violations,repair_context=repair_context,+ never_captured_candidate=_never_captured_obligation_candidate(validation.provenance),)@@ -11109,6 +11314,7 @@ def _maybe_impose_synthesized_code_block(synthesized_diagnostics=diagnostics,)violations.extend(surface_validation.violations)+ rejection_provenance = list(surface_validation.provenance)ambiguous_reject_present = any(record.kind == "ambiguous" for record in surface_validation.provenance)submitted_extraction_suffix = _submitted_suffix_after_synthesized_code(submitted_code, synthesized_spine_code)extraction_suffix = submitted_extraction_suffix or synthesized.extraction_code@@ -11141,6 +11347,7 @@ def _maybe_impose_synthesized_code_block(nearest_method=mutation.method,nearest_receiver=mutation.receiver,nearest_selector=_captured_selector_for_signature(mutation, diagnostics),+ mutation=mutation,)if mutation in synthesized_signatureselse _classify_unscouted_mutation(@@ -11153,6 +11360,7 @@ def _maybe_impose_synthesized_code_block(for mutation in sorted(suffix_mutations)]_log_browser_surface_rejection_provenance(suffix_provenance)+ rejection_provenance.extend(suffix_provenance)violations.append("Unable to impose synthesized code block: extraction suffix contains unscouted browser action(s): "+ action_text@@ -11198,6 +11406,7 @@ def _maybe_impose_synthesized_code_block(violations=violations,repair_context=repair_context,metadata_repair_contract=_co_computed_metadata_repair_contract(ctx, workflow_yaml, raw_metadata),+ never_captured_candidate=_never_captured_obligation_candidate(rejection_provenance),ablation_gate_id=(SYNTHESIZED_PARAMETER_BINDING_AMBIGUOUS_GATE_IDif parameter_binding_is_only_violation@@ -12527,6 +12736,12 @@ async def _update_workflow(return reject(error=authority_error)workflow_yaml = params["workflow_yaml"]+ never_captured_replay_payload = NeverCapturedReplayPayload(+ params=copy.deepcopy(params),+ allow_missing_credentials=allow_missing_credentials,+ allow_static_output_uncertainty=allow_static_output_uncertainty,+ formation_prepared=formation_prepared,+ )raw_conflict_marker_error = _raw_workflow_yaml_conflict_marker_error(workflow_yaml)if raw_conflict_marker_error is not None:return reject(@@ -12543,11 +12758,27 @@ async def _update_workflow(# Imposition reconciles synthesized aliases/parameters before the persisted YAML contract is checked._enrich_scout_trajectory_input_correspondences(workflow_yaml, ctx)runtime_parameters = params.get("parameters")+ capture_obligation = ctx.never_captured_obligation+ if (+ capture_obligation is not None+ and capture_obligation.state == "captured"+ and capture_obligation.draft_fingerprint != hashlib.sha256(workflow_yaml.encode()).hexdigest()+ ):+ ctx.never_captured_obligation = replace(capture_obligation, state="consumed")+ ctx.synthesized_block_reopened_for_capture_obligation = False+ LOG.info(+ "copilot_never_captured_obligation_expired_for_different_draft",+ identity_digest=capture_obligation.identity_digest,+ )imposition = _maybe_impose_synthesized_code_block(workflow_yaml,ctx,runtime_parameters if isinstance(runtime_parameters, Mapping) else None,)+ capture_obligation = ctx.never_captured_obligation+ if capture_obligation is not None and capture_obligation.state == "captured":+ ctx.never_captured_obligation = replace(capture_obligation, state="consumed")+ ctx.synthesized_block_reopened_for_capture_obligation = False# Consume the one-shot credential-scout reopen before the gate below so a fresh reject can re-arm it.ctx.synthesized_block_reopened_for_credential_scout = Falseif imposition.violations:@@ -12562,6 +12793,12 @@ async def _update_workflow():imposition = _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)else:+ _arm_never_captured_obligation(+ ctx,+ workflow_yaml,+ imposition.never_captured_candidate,+ never_captured_replay_payload,+ )if (imposition.repair_context is not Noneand imposition.repair_context.reason_code == _SYNTHESIZED_PARAMETER_BINDING_AMBIGUOUS_REASON_CODE@@ -12598,6 +12835,12 @@ async def _update_workflow(if imposition.substitutions is None:freehand_surface = _persist_seam_freehand_surface_result(workflow_yaml, ctx)if freehand_surface is not None:+ _arm_never_captured_obligation(+ ctx,+ workflow_yaml,+ freehand_surface.never_captured_candidate,+ never_captured_replay_payload,+ )_set_code_authoring_repair_context(ctx, freehand_surface.repair_context)_record_code_authoring_guardrail_reject(ctx)return reject(@@ -12635,6 +12878,35 @@ async def _update_workflow(user_facing_summary=_compiled_authoring_user_summary(),data=_code_repair_progress_data(),)+ business_input_floor_reject = _synthesized_business_input_floor_reject(ctx, workflow_yaml, imposition)+ if business_input_floor_reject is not None:+ unreferenced_keys = list(business_input_floor_reject.unreferenced_parameter_keys)+ ctx.synthesized_business_required_parameter_keys.update(unreferenced_keys)+ _record_author_time_reject_outcome(+ ctx,+ reason_code="required_input_unbound",+ summary=_definition_plane_reject_error(business_input_floor_reject),+ structural_payload={+ "reason_code": SYNTHESIZED_BUSINESS_INPUT_FLOOR_REASON_CODE,+ "unreferenced_parameter_keys": unreferenced_keys,+ },+ block_labels=[+ _code_block_label(block) for block in _workflow_code_blocks(parse_workflow_yaml(workflow_yaml) or {})+ ],+ )+ _record_code_authoring_guardrail_reject(ctx)+ _reopen_scout_after_synthesized_business_input_floor(ctx)+ return reject(+ error=(+ _definition_plane_reject_error(business_input_floor_reject)+ + " Continue scouting the business-value fields before saving or running this synthesized block."+ ),+ user_facing_summary=_compiled_authoring_user_summary(),+ data={+ "reason_code": SYNTHESIZED_BUSINESS_INPUT_FLOOR_REASON_CODE,+ "unreferenced_parameter_keys": unreferenced_keys,+ },+ )definition_reject = _definition_plane_preflight_reject(ctx, workflow_yaml)if definition_reject is not None:definition_corrective = (@@ -13526,6 +13798,77 @@ async def _update_workflow()+async def _replay_captured_never_captured_obligation(ctx: AgentContext) -> dict[str, Any] | None:+ """Retry the exact rejected authoring call after its canonical browser action is captured."""+ obligation = getattr(ctx, "never_captured_obligation", None)+ if (+ obligation is None+ or obligation.state != "captured"+ or obligation.turn_id != str(getattr(ctx, "turn_id", ""))+ or obligation.replay_payload is None+ ):+ return None+ payload = obligation.replay_payload+ workflow_yaml = payload.params.get("workflow_yaml")+ if (+ not isinstance(workflow_yaml, str)+ or hashlib.sha256(workflow_yaml.encode()).hexdigest() != obligation.draft_fingerprint+ ):+ ctx.never_captured_obligation = replace(obligation, state="consumed")+ ctx.synthesized_block_reopened_for_capture_obligation = False+ LOG.warning(+ "copilot_never_captured_obligation_replay_payload_invalid",+ identity_digest=obligation.identity_digest,+ turn_id=obligation.turn_id,+ workflow_permanent_id=ctx.workflow_permanent_id,+ draft_fingerprint=obligation.draft_fingerprint,+ block_label=obligation.block_label,+ site=obligation.site,+ )+ return None+ prior_definition = getattr(getattr(ctx, "last_workflow", None), "workflow_definition", None)+ try:+ result = await _update_workflow(+ copy.deepcopy(payload.params),+ ctx,+ allow_missing_credentials=payload.allow_missing_credentials,+ allow_static_output_uncertainty=payload.allow_static_output_uncertainty,+ formation_prepared=payload.formation_prepared,+ )+ except Exception:+ current_obligation = getattr(ctx, "never_captured_obligation", None)+ if current_obligation is not None and current_obligation.identity_digest == obligation.identity_digest:+ ctx.never_captured_obligation = obligation+ ctx.synthesized_block_reopened_for_capture_obligation = True+ raise+ current_obligation = ctx.never_captured_obligation+ if current_obligation is not None and current_obligation.state == "captured":+ ctx.never_captured_obligation = replace(current_obligation, state="consumed")+ ctx.synthesized_block_reopened_for_capture_obligation = False+ _record_workflow_update_result(ctx, result, prior_definition)+ data = result.get("data")+ post_replay_obligation = ctx.never_captured_obligation+ obligation_state = (+ post_replay_obligation.state+ if post_replay_obligation is not None and post_replay_obligation.identity_digest == obligation.identity_digest+ else "superseded"+ )+ LOG.info(+ "copilot_never_captured_obligation_replayed",+ identity_digest=obligation.identity_digest,+ turn_id=obligation.turn_id,+ workflow_permanent_id=ctx.workflow_permanent_id,+ draft_fingerprint=obligation.draft_fingerprint,+ block_label=obligation.block_label,+ site=obligation.site,+ captured_trajectory_index=obligation.captured_trajectory_index,+ obligation_state=obligation_state,+ ok=result.get("ok") is True,+ reason_code=data.get("reason_code") if isinstance(data, dict) else None,+ )+ return result++def _record_workflow_proxy_location_span(workflow_yaml: str, workflow: Workflow) -> None:input_present, input_proxy_location = _raw_yaml_proxy_location(workflow_yaml)effective_proxy_location = _proxy_location_trace_value(runtime_proxy_location(workflow.proxy_location))diff --git a/skyvern/forge/sdk/copilot/turn_ownership.py b/skyvern/forge/sdk/copilot/turn_ownership.pyindex 9f96c060d..46353fac0 100644--- a/skyvern/forge/sdk/copilot/turn_ownership.py+++ b/skyvern/forge/sdk/copilot/turn_ownership.py@@ -40,6 +40,7 @@ class TurnClaimant(StrEnum):CREDENTIAL_PRIORITY_CHURN = "credential_priority_authoring_churn"METADATA_RUN_PREFLIGHT_REJECT = "metadata_run_preflight_reject"ACTUATION_OBLIGATION_FILL = "actuation_obligation_fill"+ CAPTURE_OBLIGATION_REOPEN = "capture_obligation_reopen"CREDENTIAL_SCOUT_REOPEN = "credential_scout_reopen"UNCOVERED_OUTPUT_RESCOUT_STEER = "uncovered_output_rescout_steer"RECORDED_OUTCOME_GROUNDING = "recorded_outcome_grounding"@@ -70,6 +71,8 @@ _PRECEDENCE_ORDER: tuple[TurnClaimant, ...] = (# Actuation-obligation fill carve-out admits the required fill tool through the persistence# gate; predicate-gated at its call site, never an unconditional rank flip.TurnClaimant.ACTUATION_OBLIGATION_FILL,+ # A never-captured obligation admits only the exact canonical interaction that can satisfy it.+ TurnClaimant.CAPTURE_OBLIGATION_REOPEN,# One-shot credential-scout reopen admits evaluate through the persistence gate;# predicate-gated at its call site.TurnClaimant.CREDENTIAL_SCOUT_REOPEN,@@ -98,6 +101,7 @@ CLAIMANT_REASON_CODE_FAMILIES: dict[TurnClaimant, frozenset[str]] = {TurnClaimant.CREDENTIAL_PRIORITY_CHURN: frozenset({"credential_priority_authoring_churn"}),TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT: frozenset(),TurnClaimant.ACTUATION_OBLIGATION_FILL: frozenset(),+ TurnClaimant.CAPTURE_OBLIGATION_REOPEN: frozenset(),TurnClaimant.CREDENTIAL_SCOUT_REOPEN: frozenset(),TurnClaimant.UNCOVERED_OUTPUT_RESCOUT_STEER: frozenset({UNCOVERED_OUTPUT_RESCOUT_STEER_REASON_CODE}),TurnClaimant.RECORDED_OUTCOME_GROUNDING: frozenset({RECORDED_OUTCOME_GROUNDING_REASON_CODE}),@@ -126,6 +130,7 @@ _TRANSIENT_CLAIMANTS = frozenset({TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT,TurnClaimant.ACTUATION_OBLIGATION_FILL,+ TurnClaimant.CAPTURE_OBLIGATION_REOPEN,TurnClaimant.CREDENTIAL_SCOUT_REOPEN,})diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex 57a5a14bf..14c19125b 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -97,7 +97,7 @@ from skyvern.forge.sdk.copilot.request_policy import (RequestPolicy,)from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODE, RecordedRunOutcome-from skyvern.forge.sdk.copilot.runtime import AgentContext+from skyvern.forge.sdk.copilot.runtime import AgentContext, NeverCapturedObligationfrom skyvern.forge.sdk.copilot.tools import (_code_block_safety_errors,_detect_stale_block_metadata,@@ -2042,6 +2042,199 @@ class TestCodeRepairProgressClassification:workflow_update_module.DEFINITION_CONTRACT_UNSATISFIED_GATE_ID]+ @pytest.mark.asyncio+ async def test_synthesized_business_tour_stays_rejected_when_definition_gate_is_log_only(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = _code_only_ctx()+ ctx.request_policy = RequestPolicy(+ completion_criteria=[+ CompletionCriterion(+ id="request-id",+ outcome="the request id is output",+ level="run",+ requested_output_floor_rekeyed=True,+ floor_rekeyed_from_path="output.request_id",+ ),+ CompletionCriterion(+ id="submit-request",+ outcome="the service request is submitted",+ kind="terminal_action",+ terminal_action_family="request",+ level="run",+ ),+ ]+ )+ ctx.synthesized_block_offered = True+ ctx.spine_imposition_owned_attempt = True+ ctx.author_time_gate_log_only_ids = {workflow_update_module.DEFINITION_CONTRACT_UNSATISFIED_GATE_ID}+ monkeypatch.setattr(+ workflow_update_module,+ "_maybe_impose_synthesized_code_block",+ lambda *_args, **_kwargs: workflow_update_module._SynthesizedCodeImpositionResult(+ workflow_yaml=_UNREFERENCED_DEFINITION_YAML,+ substitutions={"submit_service_request": "synthesized"},+ ),+ )++ result = await _update_workflow(+ {"workflow_yaml": _UNREFERENCED_DEFINITION_YAML},+ ctx,+ allow_missing_credentials=True,+ )++ assert result["ok"] is False+ assert result["data"]["reason_code"] == "synthesized_business_input_floor_unsatisfied"+ assert result["data"]["unreferenced_parameter_keys"] == [+ "business_name",+ "contact_email",+ "desired_start_date",+ "service_address",+ ]+ assert ctx.workflow_yaml == ""+ assert ctx.synthesized_block_offered is False+ assert ctx.synthesized_block_offered_trajectory_len == 0+ assert ctx.synthesized_block_offered_goal_complete is False+ assert ctx.spine_imposition_owned_attempt is False+ assert ctx.author_time_gate_ablation_events == []++ @pytest.mark.asyncio+ async def test_synthesized_business_input_floor_keeps_required_inputs_when_retry_shrinks_draft(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = _code_only_ctx()+ ctx.request_policy = RequestPolicy(+ completion_criteria=[+ CompletionCriterion(+ id="submit-request",+ outcome="the service request is submitted",+ kind="terminal_action",+ terminal_action_family="request",+ level="run",+ )+ ]+ )+ ctx.synthesized_block_offered = True+ ctx.spine_imposition_owned_attempt = True+ monkeypatch.setattr(+ workflow_update_module,+ "_maybe_impose_synthesized_code_block",+ lambda *_args, **_kwargs: workflow_update_module._SynthesizedCodeImpositionResult(+ workflow_yaml=_UNREFERENCED_DEFINITION_YAML,+ substitutions={"submit_service_request": "synthesized"},+ ),+ )++ first_result = await _update_workflow(+ {"workflow_yaml": _UNREFERENCED_DEFINITION_YAML},+ ctx,+ allow_missing_credentials=True,+ )++ assert first_result["ok"] is False+ assert ctx.synthesized_business_required_parameter_keys == {+ "business_name",+ "contact_email",+ "desired_start_date",+ "service_address",+ }++ narrowed_yaml = _yaml(+ """+ title: Start reusable service request+ workflow_definition:+ parameters:+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}+ blocks:+ - block_type: code+ label: submit_service_request+ parameter_keys: [service_address]+ code: |+ await page.locator("#address").fill(str(service_address))+ """+ )+ ctx.synthesized_block_offered = True+ ctx.spine_imposition_owned_attempt = True+ monkeypatch.setattr(+ workflow_update_module,+ "_maybe_impose_synthesized_code_block",+ lambda *_args, **_kwargs: workflow_update_module._SynthesizedCodeImpositionResult(+ workflow_yaml=narrowed_yaml,+ substitutions={"submit_service_request": "synthesized"},+ ),+ )++ second_result = await _update_workflow(+ {"workflow_yaml": narrowed_yaml},+ ctx,+ allow_missing_credentials=True,+ )++ assert second_result["ok"] is False+ assert second_result["data"]["reason_code"] == "synthesized_business_input_floor_unsatisfied"+ assert second_result["data"]["unreferenced_parameter_keys"] == [+ "business_name",+ "contact_email",+ "desired_start_date",+ ]+ assert ctx.workflow_yaml == ""++ @pytest.mark.asyncio+ async def test_synthesized_business_input_floor_allows_fully_bound_draft(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = _code_only_ctx()+ ctx.request_policy = RequestPolicy(+ completion_criteria=[+ CompletionCriterion(+ id="submit-request",+ outcome="the service request is submitted",+ kind="terminal_action",+ terminal_action_family="request",+ level="run",+ )+ ]+ )+ ctx.synthesized_block_offered = True+ ctx.spine_imposition_owned_attempt = True+ bound_yaml = _yaml(+ """+ title: Submit reusable service request+ workflow_definition:+ parameters:+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}+ blocks:+ - block_type: code+ label: submit_service_request+ parameter_keys: [business_name, service_address]+ code: |+ await page.locator("#business").fill(str(business_name))+ await page.locator("#address").fill(str(service_address))+ await page.locator("#submit").click()+ """+ )+ monkeypatch.setattr(+ workflow_update_module,+ "_maybe_impose_synthesized_code_block",+ lambda *_args, **_kwargs: workflow_update_module._SynthesizedCodeImpositionResult(+ workflow_yaml=bound_yaml,+ substitutions={"submit_service_request": "synthesized"},+ ),+ )++ result = await _update_workflow(+ {"workflow_yaml": bound_yaml},+ ctx,+ allow_missing_credentials=True,+ )++ assert result["ok"] is True+ assert ctx.workflow_yaml == bound_yaml+@pytest.mark.asyncioasync def test_bound_draft_run_blocks_dispatches_when_criteria_dark(self, monkeypatch: pytest.MonkeyPatch) -> None:_stub_successful_update(monkeypatch)@@ -17543,6 +17736,212 @@ class TestBrowserSurfaceRejectionProvenance:assert events[0]["site"] == "whole_trajectory"assert "#hallucinated" in events[0]["action"]+ @pytest.mark.asyncio+ async def test_never_captured_reject_reopens_once_after_matching_canonical_capture(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ _stub_successful_update(monkeypatch)+ ctx = _imposition_split_ctx()+ submitted_yaml = _already_split_spine_yaml(extra_sibling_code='await page.locator("#hallucinated").click()')++ with capture_logs() as rejection_logs:+ result = await _update_workflow(+ {+ "workflow_yaml": submitted_yaml,+ "code_artifact_metadata": ctx.raw_code_artifact_metadata,+ },+ ctx,+ allow_static_output_uncertainty=True,+ )++ assert result["ok"] is False+ assert "never_captured" in result["error"]+ obligation = ctx.never_captured_obligation+ assert obligation is not None+ assert obligation.method == "click"+ assert obligation.normalized_receiver == "page.locator('#hallucinated')"+ assert obligation.block_label.endswith("_browser_stage_extra")+ assert obligation.state == "armed"+ assert obligation.replay_payload.params["workflow_yaml"] == submitted_yaml+ assert ctx.synthesized_block_reopened_for_capture_obligation is False+ armed_events = [log for log in rejection_logs if log["event"] == "copilot_never_captured_obligation_armed"]+ assert len(armed_events) == 1+ assert armed_events[0]["turn_id"] == ctx.turn_id+ assert armed_events[0]["draft_fingerprint"] == obligation.draft_fingerprint+ assert armed_events[0]["call_shape_digest"] == obligation.call_shape_digest+ assert armed_events[0]["expected_tool_name"] == obligation.expected_tool_name++ scouting_module._record_scouted_interaction(+ ctx, tool_name="click", selector="#unrelated", source_url="https://example.com/form"+ )++ assert ctx.never_captured_obligation == obligation+ assert ctx.synthesized_block_reopened_for_capture_obligation is False++ replay_call: dict[str, object] = {}++ async def _record_replay(+ params: dict[str, object],+ replay_ctx: CopilotContext,+ *,+ allow_missing_credentials: bool | None,+ allow_static_output_uncertainty: bool,+ formation_prepared: bool,+ ) -> dict[str, object]:+ replay_call.update(+ params=params,+ ctx=replay_ctx,+ allow_missing_credentials=allow_missing_credentials,+ allow_static_output_uncertainty=allow_static_output_uncertainty,+ formation_prepared=formation_prepared,+ )+ return {"ok": True, "data": {"message": "Workflow updated successfully."}}++ monkeypatch.setattr(workflow_update_module, "_update_workflow", _record_replay)+ ctx.pending_scout_source_url = "https://example.com/form"+ with capture_logs() as replay_logs:+ click_result = await tools_module._click_post_hook(+ {"ok": True, "data": {"selector": "#hallucinated"}},+ {"browser_context": {"url": "https://example.com/form", "title": "Example"}},+ ctx,+ )++ assert click_result["data"]["workflow_reconciliation"] == {+ "ok": True,+ "message": "Workflow updated successfully.",+ }+ assert replay_call == {+ "params": {+ "workflow_yaml": submitted_yaml,+ "code_artifact_metadata": obligation.replay_payload.params["code_artifact_metadata"],+ },+ "ctx": ctx,+ "allow_missing_credentials": None,+ "allow_static_output_uncertainty": True,+ "formation_prepared": False,+ }+ consumed = ctx.never_captured_obligation+ assert consumed is not None+ assert consumed.state == "consumed"+ assert ctx.synthesized_block_reopened_for_capture_obligation is False+ completed_events = [log for log in replay_logs if log["event"] == "copilot_never_captured_obligation_completed"]+ assert len(completed_events) == 1+ assert completed_events[0]["identity_digest"] == obligation.identity_digest+ assert completed_events[0]["turn_id"] == ctx.turn_id+ assert completed_events[0]["workflow_permanent_id"] == ctx.workflow_permanent_id+ assert completed_events[0]["draft_fingerprint"] == obligation.draft_fingerprint+ assert completed_events[0]["block_label"] == obligation.block_label+ assert completed_events[0]["site"] == obligation.site+ assert completed_events[0]["trajectory_index"] == consumed.captured_trajectory_index+ replay_events = [log for log in replay_logs if log["event"] == "copilot_never_captured_obligation_replayed"]+ assert len(replay_events) == 1+ assert replay_events[0]["identity_digest"] == obligation.identity_digest+ assert replay_events[0]["turn_id"] == ctx.turn_id+ assert replay_events[0]["draft_fingerprint"] == obligation.draft_fingerprint+ assert replay_events[0]["block_label"] == obligation.block_label+ assert replay_events[0]["site"] == obligation.site+ assert replay_events[0]["captured_trajectory_index"] == consumed.captured_trajectory_index+ assert replay_events[0]["obligation_state"] == "consumed"+ assert replay_events[0]["ok"] is True++ scouting_module._record_scouted_interaction(+ ctx, tool_name="click", selector="#hallucinated", source_url="https://example.com/form"+ )++ assert ctx.never_captured_obligation == consumed+ assert ctx.synthesized_block_reopened_for_capture_obligation is False++ @pytest.mark.asyncio+ async def test_replay_exception_preserves_captured_obligation(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_successful_update(monkeypatch)+ ctx = _imposition_split_ctx()+ submitted_yaml = _already_split_spine_yaml(extra_sibling_code='await page.locator("#hallucinated").click()')+ rejected = await _update_workflow({"workflow_yaml": submitted_yaml}, ctx)+ assert rejected["ok"] is False+ assert ctx.never_captured_obligation is not None+ scouting_module._record_scouted_interaction(+ ctx, tool_name="click", selector="#hallucinated", source_url="https://example.com/form"+ )+ captured = ctx.never_captured_obligation+ assert captured is not None+ assert captured.state == "captured"++ async def _raise_after_consuming(*_args: object, **_kwargs: object) -> dict[str, object]:+ ctx.never_captured_obligation = replace(captured, state="consumed")+ ctx.synthesized_block_reopened_for_capture_obligation = False+ raise RuntimeError("synthetic replay failure")++ monkeypatch.setattr(workflow_update_module, "_update_workflow", _raise_after_consuming)++ with pytest.raises(RuntimeError, match="synthetic replay failure"):+ await workflow_update_module._replay_captured_never_captured_obligation(ctx)++ assert ctx.never_captured_obligation == captured+ assert ctx.synthesized_block_reopened_for_capture_obligation is True++ @pytest.mark.asyncio+ async def test_captured_obligation_does_not_reopen_a_different_draft(self, monkeypatch: pytest.MonkeyPatch) -> None:+ _stub_successful_update(monkeypatch)+ monkeypatch.setattr(+ workflow_update_module,+ "synthesize_code_block",+ lambda *a, **k: _fake_spine_synthesized(diagnostics=_spine_emission_diagnostics()),+ )+ ctx = _imposition_split_ctx()+ rejected_yaml = _already_split_spine_yaml(extra_sibling_code='await page.locator("#hallucinated").click()')+ rejected = await _update_workflow({"workflow_yaml": rejected_yaml}, ctx)+ assert rejected["ok"] is False+ assert ctx.never_captured_obligation is not None++ scouting_module._record_scouted_interaction(+ ctx, tool_name="click", selector="#hallucinated", source_url="https://example.com/form"+ )+ assert ctx.synthesized_block_reopened_for_capture_obligation is True+ ctx.update_workflow_called = True+ different_yaml = rejected_yaml.replace("title: Entry lookup", "title: Different draft")++ with capture_logs() as logs:+ await _update_workflow({"workflow_yaml": different_yaml}, ctx)++ obligation = ctx.never_captured_obligation+ assert obligation is not None+ assert obligation.state == "consumed"+ assert ctx.synthesized_block_reopened_for_capture_obligation is False+ events = [log for log in logs if log["event"] == "copilot_imposition_skipped_after_update"]+ assert len(events) == 1++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("sibling_code", "provenance_kind"),+ [+ ('await page.locator("#stage-a").click(timeout=5000)', "shape_diverged"),+ ('do_click = page.locator("#x").click\nawait do_click()', "ambiguous"),+ ('await page.locator("#hallucinated").type("value")', "never_captured"),+ ],+ )+ async def test_fail_closed_provenance_does_not_arm_capture_obligation(+ self,+ monkeypatch: pytest.MonkeyPatch,+ sibling_code: str,+ provenance_kind: str,+ ) -> None:+ monkeypatch.setattr(+ workflow_update_module,+ "synthesize_code_block",+ lambda *a, **k: _fake_spine_synthesized(diagnostics=_spine_emission_diagnostics()),+ )+ ctx = _imposition_split_ctx()++ result = await _update_workflow(+ {"workflow_yaml": _already_split_spine_yaml(extra_sibling_code=sibling_code)},+ ctx,+ )++ assert result["ok"] is False+ assert provenance_kind in result["error"]+ assert ctx.never_captured_obligation is None+ assert ctx.synthesized_block_reopened_for_capture_obligation is False+def test_same_receiver_divergent_call_shape_is_shape_diverged_with_nearest(self) -> None:validation = _gate_validation('await page.locator("#stage-a").click(timeout=5000)\n', _spine_emission_diagnostics()@@ -17802,6 +18201,82 @@ class TestScoutCaptureParityAccounting:indexes = [item["trajectory_index"] for item in ctx.scout_trajectory]assert indexes == list(range(2, scouting_module._MAX_SCOUTED_INTERACTIONS + 2))+ def test_capture_obligation_matches_stable_index_after_trajectory_eviction(self) -> None:+ ctx = _code_only_ctx()+ ctx.turn_id = "turn-eviction"+ ctx.scouted_interactions = []+ ctx.scout_trajectory = [+ {"tool_name": "click", "selector": f"#item-{index}", "trajectory_index": index}+ for index in range(scouting_module._MAX_SCOUTED_INTERACTIONS)+ ]+ ctx.never_captured_obligation = NeverCapturedObligation(+ identity_digest="eviction-identity",+ turn_id=ctx.turn_id,+ draft_fingerprint="draft",+ block_label="target",+ site="whole_trajectory",+ method="click",+ normalized_receiver="page.locator('#target')",+ call_shape_digest="shape",+ expected_tool_name="click",+ armed_after_trajectory_index=scouting_module._MAX_SCOUTED_INTERACTIONS - 1,+ )++ scouting_module._record_scouted_interaction(+ ctx, tool_name="click", selector="#target", source_url="https://example.com/list"+ )++ obligation = ctx.never_captured_obligation+ assert obligation is not None+ assert obligation.state == "captured"+ assert obligation.captured_trajectory_index == scouting_module._MAX_SCOUTED_INTERACTIONS+ assert ctx.synthesized_block_reopened_for_capture_obligation is True++ def test_capture_obligation_rejects_same_locator_with_different_press_key(self) -> None:+ ctx = _code_only_ctx()+ ctx.turn_id = "turn-key"+ ctx.scouted_interactions = []+ ctx.scout_trajectory = []+ ctx.never_captured_obligation = NeverCapturedObligation(+ identity_digest="key-identity",+ turn_id=ctx.turn_id,+ draft_fingerprint="draft",+ block_label="submit",+ site="whole_trajectory",+ method="press",+ normalized_receiver="page.locator('#request')",+ call_shape_digest="shape",+ expected_tool_name="press_key",+ expected_argument_literal="Enter",+ armed_after_trajectory_index=-1,+ )++ scouting_module._record_scouted_interaction(+ ctx,+ tool_name="press_key",+ selector="#request",+ source_url="https://example.com/form",+ key="Tab",+ )++ obligation = ctx.never_captured_obligation+ assert obligation is not None+ assert obligation.state == "armed"+ assert ctx.synthesized_block_reopened_for_capture_obligation is False++ scouting_module._record_scouted_interaction(+ ctx,+ tool_name="press_key",+ selector="#request",+ source_url="https://example.com/form",+ key="Enter",+ )++ obligation = ctx.never_captured_obligation+ assert obligation is not None+ assert obligation.state == "captured"+ assert ctx.synthesized_block_reopened_for_capture_obligation is True+def test_dedup_replacement_is_not_an_eviction(self) -> None:ctx = _code_only_ctx()ctx.scouted_interactions = []diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.pyindex 1983e13a2..eb939c50a 100644--- a/tests/unit/test_copilot_enforcement_pruning.py+++ b/tests/unit/test_copilot_enforcement_pruning.py@@ -80,6 +80,7 @@ from skyvern.forge.sdk.copilot.output_contracts import (from skyvern.forge.sdk.copilot.output_extraction_plan import ShapeExpectation, ValueCardinality, ValueShapefrom skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTargetfrom skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicy+from skyvern.forge.sdk.copilot.runtime import NeverCapturedObligationfrom skyvern.forge.sdk.copilot.streaming_adapter import _update_enforcement_from_toolfrom skyvern.forge.sdk.copilot.tools import (_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY,@@ -143,6 +144,8 @@ class _Ctx:self.synthesized_block_reopened_after_failed_run = Falseself.synthesized_block_reopened_for_output_coverage = Falseself.synthesized_block_reopened_for_credential_scout = False+ self.synthesized_block_reopened_for_capture_obligation = False+ self.never_captured_obligation = Noneself.credential_scout_rescout_context_key = Noneself.synthesized_goal_complete_landed = Falseself.impose_synthesized_code_block = False@@ -702,6 +705,38 @@ class TestSynthesizedOfferPersistenceGate:assert synthesized_block_persistence_signal(ctx, "click") is None+ def test_never_captured_obligation_admits_only_its_expected_scout_tool(self) -> None:+ ctx = _Ctx()+ ctx.turn_id = "turn-a"+ 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 = 1+ ctx.synthesized_block_offered_goal_complete = True+ ctx.scout_trajectory = [{"tool_name": "click", "selector": "#existing"}]+ ctx.never_captured_obligation = NeverCapturedObligation(+ identity_digest="identity",+ turn_id=ctx.turn_id,+ draft_fingerprint="draft",+ block_label="submit",+ site="whole_trajectory",+ method="click",+ normalized_receiver="page.locator('#submit')",+ call_shape_digest="shape",+ expected_tool_name="click",+ armed_after_trajectory_index=0,+ )++ assert synthesized_block_persistence_signal(ctx, "click", {"selector": "#submit"}) is None+ assert isinstance(+ synthesized_block_persistence_signal(ctx, "click", {"selector": "#other"}),+ CopilotToolBlockerSignal,+ )+ assert isinstance(synthesized_block_persistence_signal(ctx, "type_text"), CopilotToolBlockerSignal)+def test_unresolved_recorded_outcome_blocks_page_mutating_tool_until_update_and_run_blocks(self) -> None:ctx = _Ctx()ctx.turn_intent = TurnIntent(@@ -3167,16 +3202,52 @@ class TestScoutOutputCoverageGate:def test_post_hook_failure_rolls_back_coverage_credit(self) -> None:assert "scouted_output_covered_paths" in _POST_HOOK_CONTEXT_ROLLBACK_FIELDSassert "synthesized_block_reopened_for_output_coverage" in _POST_HOOK_CONTEXT_ROLLBACK_FIELDS+ assert "synthesized_business_required_parameter_keys" in _POST_HOOK_CONTEXT_ROLLBACK_FIELDSctx = _Ctx()ctx.scouted_output_covered_paths = {"output.document_name"}+ ctx.synthesized_business_required_parameter_keys = {"service_address"}ctx.synthesized_block_reopened_for_output_coverage = Falsesnapshot = _snapshot_post_hook_context(ctx)ctx.scouted_output_covered_paths.add("output.leaked")+ ctx.synthesized_business_required_parameter_keys.add("leaked_input")ctx.synthesized_block_reopened_for_output_coverage = True_restore_post_hook_context(ctx, snapshot)assert ctx.scouted_output_covered_paths == {"output.document_name"}+ assert ctx.synthesized_business_required_parameter_keys == {"service_address"}assert ctx.synthesized_block_reopened_for_output_coverage is False+ def test_post_hook_failure_rolls_back_capture_obligation_credit(self) -> None:+ assert "never_captured_obligation" in _POST_HOOK_CONTEXT_ROLLBACK_FIELDS+ assert "synthesized_block_reopened_for_capture_obligation" in _POST_HOOK_CONTEXT_ROLLBACK_FIELDS+ ctx = _Ctx()+ armed = NeverCapturedObligation(+ identity_digest="identity",+ turn_id="turn-a",+ draft_fingerprint="draft",+ block_label="submit",+ site="whole_trajectory",+ method="click",+ normalized_receiver="page.locator('#submit')",+ call_shape_digest="shape",+ expected_tool_name="click",+ armed_after_trajectory_index=0,+ )+ ctx.never_captured_obligation = armed+ snapshot = _snapshot_post_hook_context(ctx)+ ctx.never_captured_obligation = NeverCapturedObligation(+ **{+ **armed.__dict__,+ "captured_trajectory_index": 1,+ "state": "captured",+ }+ )+ ctx.synthesized_block_reopened_for_capture_obligation = True++ _restore_post_hook_context(ctx, snapshot)++ assert ctx.never_captured_obligation == armed+ assert ctx.synthesized_block_reopened_for_capture_obligation is False+def test_post_hook_failure_rolls_back_scout_observation_contract(self) -> None:assert "scout_observation_contract" in _POST_HOOK_CONTEXT_ROLLBACK_FIELDSctx = _Ctx()@@ -3467,6 +3538,202 @@ class TestCredentialFlowGoalComplete:assert _should_force_synthesized_block_persistence(ctx) is Trueassert synthesized_block_persistence_signal(ctx, "evaluate") is not None+ def test_login_only_is_incomplete_when_runtime_outputs_were_floor_rekeyed(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ ctx = self._ctx_with_inventory(+ self._two_screen_full_login(),+ inventory={"cred_1": frozenset({"username", "password"})},+ )+ ctx.completion_criteria_turn_state = _turn_state(+ CompletionCriterion(+ id="request-id",+ outcome="the request id is output",+ level="run",+ requested_output_floor_rekeyed=True,+ floor_rekeyed_from_path="output.request_id",+ )+ )++ assert synthesized_trajectory_is_goal_complete(ctx) is False+ assert _should_force_synthesized_block_persistence(ctx) is False+ assert synthesized_block_persistence_signal(ctx, "click", {"selector": "#gasCreate"}) is None+ ctx.synthesized_block_offered = False+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.locator('#login').click()"),+ )+ assert _maybe_synthesized_block_offer_msg(ctx) is None++ def test_floor_rekeyed_runtime_output_requires_coverage_after_post_login_business_commit(self) -> None:+ trajectory = [+ *self._two_screen_full_login(),+ {+ "tool_name": "click",+ "selector": "button[data-action='gasCreate']",+ "accessible_name": "Create QuickConnect",+ "source_url": "https://portal.example.test/home",+ },+ {+ "tool_name": "type_text",+ "selector": "#gasAddress",+ "typed_value": "77 Gaslight Way",+ "source_url": "https://portal.example.test/quickconnect",+ },+ {+ "tool_name": "click",+ "selector": "button[data-action='gasSubmit']",+ "accessible_name": "Submit",+ "source_url": "https://portal.example.test/quickconnect",+ },+ ]+ ctx = self._ctx_with_inventory(+ trajectory,+ inventory={"cred_1": frozenset({"username", "password"})},+ )+ ctx.completion_criteria_turn_state = _turn_state(+ CompletionCriterion(+ id="request-id",+ outcome="the request id is output",+ level="run",+ requested_output_floor_rekeyed=True,+ floor_rekeyed_from_path="output.request_id",+ )+ )++ assert synthesized_trajectory_reaches_goal(ctx) is True+ assert uncovered_requested_output_paths(ctx) == {"output.request_id"}+ assert synthesized_trajectory_is_goal_complete(ctx) is False++ ctx.scouted_output_covered_paths.add("output.request_id")+ ctx.flow_evidence = [+ {+ "step": len(trajectory),+ "reached_via": "interaction",+ "had_bounded_schema": True,+ "evidence": {+ "source_tool": "scout_interaction",+ "interaction_tool": "click",+ "interaction_selector": "button[data-action='gasSubmit']",+ "inspection_warnings": [],+ "result_containers_truncated": False,+ "key_value_relations_truncated": False,+ "key_value_relations": [+ {+ "key_text": "the request id is output",+ "container_selector": ".request-id-kv",+ "container_match_count": 1,+ "container_position": 0,+ "value_child_index": 1,+ "direct_child_count": 2,+ "visible": True,+ "value_visible": True,+ }+ ],+ "result_containers": [],+ },+ }+ ]++ assert uncovered_requested_output_paths(ctx) == set()+ assert synthesized_trajectory_is_goal_complete(ctx) is True++ def test_floor_rekeyed_runtime_output_rejects_create_then_submit_without_business_fill(self) -> None:+ trajectory = [+ *self._two_screen_full_login(),+ {+ "tool_name": "click",+ "selector": "button[data-action='gasCreate']",+ "accessible_name": "Create QuickConnect",+ "source_url": "https://portal.example.test/home",+ },+ {+ "tool_name": "click",+ "selector": "button[data-action='gasSubmit']",+ "accessible_name": "Submit",+ "source_url": "https://portal.example.test/quickconnect",+ },+ ]+ ctx = self._ctx_with_inventory(+ trajectory,+ inventory={"cred_1": frozenset({"username", "password"})},+ )+ ctx.completion_criteria_turn_state = _turn_state(+ CompletionCriterion(+ id="request-id",+ outcome="the request id is output",+ level="run",+ requested_output_floor_rekeyed=True,+ floor_rekeyed_from_path="output.request_id",+ )+ )+ ctx.request_policy = RequestPolicy(+ completion_criteria=[+ CompletionCriterion(+ id="submit-request",+ outcome="the QuickConnect request is submitted",+ kind="terminal_action",+ terminal_action_family="request",+ level="run",+ )+ ]+ )+ ctx.synthesized_block_offered = True+ ctx.synthesized_block_offered_trajectory_len = len(trajectory)+ ctx.synthesized_block_offered_goal_complete = True++ assert synthesized_trajectory_is_goal_complete(ctx) is False+ assert _should_force_synthesized_block_persistence(ctx) is False+ assert synthesized_block_persistence_signal(ctx, "evaluate") is None++ def test_request_terminal_action_does_not_offer_on_create_then_table_navigation(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ trajectory = [+ *self._two_screen_full_login(),+ {+ "tool_name": "click",+ "selector": "button[data-action='gasCreate']",+ "accessible_name": "Create QuickConnect",+ "source_url": "https://portal.example.test/home",+ },+ {+ "tool_name": "click",+ "selector": "button[data-action='gasTable']",+ "accessible_name": "My QuickConnects",+ "source_url": "https://portal.example.test/quickconnect",+ },+ {+ "tool_name": "click",+ "selector": "a[data-action='quickconnects']",+ "accessible_name": "QuickConnects",+ "source_url": "https://portal.example.test/quickconnect/table",+ },+ ]+ ctx = self._ctx_with_inventory(+ trajectory,+ inventory={"cred_1": frozenset({"username", "password"})},+ )+ ctx.completion_criteria_turn_state = None+ ctx.request_policy = RequestPolicy(+ completion_criteria=[+ CompletionCriterion(+ id="submit-request",+ outcome="the QuickConnect request is submitted",+ kind="terminal_action",+ terminal_action_family="request",+ level="run",+ )+ ]+ )+ ctx.synthesized_block_offered = False++ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.locator('#gasTable').click()"),+ )+ assert _maybe_synthesized_block_offer_msg(ctx) is None+def test_username_only_flow_completes_after_no_password_control_observation(self) -> None:trajectory = self._two_screen_first_page()ctx = self._ctx_with_inventory(@@ -3696,3 +3963,44 @@ class TestCredentialScoutReopen:assert _should_force_synthesized_block_persistence(ctx) is Falsectx.synthesized_block_reopened_for_credential_scout = Trueassert _should_force_synthesized_block_persistence(ctx) is True+++class TestNeverCapturedObligationAdmission:+ def _offered_complete_ctx(self) -> _Ctx:+ helper = TestCredentialFlowGoalComplete()+ ctx = helper._ctx_with_inventory(+ helper._two_screen_full_login(),+ inventory={"cred_1": frozenset({"username", "password"})},+ )+ ctx.turn_id = "turn-capture"+ ctx.never_captured_obligation = NeverCapturedObligation(+ identity_digest="capture-identity",+ turn_id=ctx.turn_id,+ draft_fingerprint="draft",+ block_label="submit",+ site="whole_trajectory",+ method="click",+ normalized_receiver="page.locator('#gasSubmit')",+ call_shape_digest="shape",+ expected_tool_name="click",+ armed_after_trajectory_index=0,+ )+ return ctx++ def test_exact_target_admission_registers_precedence_claim(self) -> None:+ ctx = self._offered_complete_ctx()++ assert synthesized_block_persistence_signal(ctx, "click", {"selector": "#gasSubmit"}) is None++ assert ctx.turn_ownership is not None+ assert TurnClaimant.CAPTURE_OBLIGATION_REOPEN in ctx.turn_ownership.claims+ assert current_turn_owner(ctx) is None++ def test_same_tool_for_different_target_remains_blocked(self) -> None:+ ctx = self._offered_complete_ctx()++ signal = synthesized_block_persistence_signal(ctx, "click", {"selector": "#unrelated"})++ assert isinstance(signal, CopilotToolBlockerSignal)+ assert signal.internal_reason_code == SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE+ assert ctx.turn_ownership is None