Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-12054): harness engine swap — copilot scout-loop recovery behind enable_self_healing (#7462)
pedrohsdbb96e444a4781
diff --git a/skyvern/config.py b/skyvern/config.pyindex 0673e2dd6..1d3b0a1dc 100644--- a/skyvern/config.py+++ b/skyvern/config.py@@ -80,6 +80,7 @@ class Settings(BaseSettings):# Script reviewer settingsSCRIPT_REVIEW_DAILY_CAP: int = 5 # Max script reviews per wpid per day (all review types)+ SELF_HEAL_DAILY_CAP: int = 5ADDITIONAL_MODULES: list[str] = []@@ -223,6 +224,8 @@ class Settings(BaseSettings):MCP_CODE_ONLY_MODE: bool = False# Default for the bounded code-block self-heal; off by default.ENABLE_CODE_BLOCK_SELF_HEALING: bool = False+ SELF_HEAL_MAX_ACTIONS: int = 15+ SELF_HEAL_WALL_CLOCK_BUDGET_SECONDS: int = 300PORT: int = 8000ALLOWED_ORIGINS: list[str] = ["*"]ALLOWED_ORIGIN_REGEX: str | None = Nonediff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.pyindex 2f601c25f..b2a8aa383 100644--- a/skyvern/forge/agent_functions.py+++ b/skyvern/forge/agent_functions.py@@ -964,6 +964,11 @@ class AgentFunction:"""Return an org-scoped API key; returns None in the base implementation."""return None+ async def resolve_self_heal_api_key(self, organization_id: str) -> str | None:+ del organization_id+ api_key = settings.SKYVERN_API_KEY+ return api_key if api_key and api_key != "PLACEHOLDER" else None+async def setup_browser_context_extensions(self, browser_context: Any, **kwargs: Any) -> None:"""Attach cloud-only listeners/route handlers to a fresh BrowserContext. OSS no-op."""diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 2c847b1d3..719d70405 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -193,6 +193,7 @@ from skyvern.forge.sdk.copilot.turn_intent import (classify_turn_intent,turn_intent_defers_authoring_live_fill,)+from skyvern.forge.sdk.copilot.turn_origin import TurnOriginfrom skyvern.forge.sdk.copilot.turn_outcome import (apply_repeated_reply_guard,derive_response_kind,@@ -3250,6 +3251,13 @@ async def _translate_to_agent_result(turn_intent = ctx.turn_intent if isinstance(ctx.turn_intent, TurnIntent) else Nonemay_update_workflow = turn_intent is None or turn_intent.authority.may_update_workflow+ if resp_type == "REPLACE_WORKFLOW" and ctx.turn_origin == TurnOrigin.runtime_self_heal:+ LOG.warning("copilot suppressed inline REPLACE_WORKFLOW on runtime self-heal turn")+ user_response = _with_inline_reject_note(+ user_response,+ "Runtime self-heal cannot update workflow definitions; retrying in read-only recovery mode.",+ )+ resp_type = "REPLY"if resp_type == "REPLACE_WORKFLOW" and turn_intent is not None and not turn_intent.authority.may_update_workflow:# A no-mutation turn (e.g. DIAGNOSE) must not stage a draft even via an inline REPLACE_WORKFLOW, which# bypasses the may_update_workflow=False authority enforced on the update_workflow tool. Downgrade to a@@ -3825,6 +3833,88 @@ def _fallback_llm_key(config: CopilotConfig, current_llm_key: str) -> str | Nonereturn fallback_key+async def _run_agent_loop_with_surface(+ *,+ ctx: Any,+ stream: EventSourceStream,+ chat_id: str,+ user_message: str,+ system_prompt: Callable[[object, object], str] | str,+ model_name: str,+ run_config: Any,+ llm_key: str,+ copilot_config: CopilotConfig,+ native_tools: list[Any],+ alias_map: dict[str, str],+ overlays: dict[str, Any],+ output_guardrails: list[Any],+ allow_untested_retry: bool = False,+) -> Any:+ from agents import Agent+ from agents.mcp import MCPServerManager++ from skyvern.cli.mcp_tools import mcp as skyvern_mcp+ from skyvern.forge.sdk.copilot.enforcement import run_with_enforcement+ from skyvern.forge.sdk.copilot.hooks import CopilotRunHooks+ from skyvern.forge.sdk.copilot.mcp_adapter import SkyvernOverlayMCPServer+ from skyvern.forge.sdk.copilot.session_factory import create_copilot_session++ mcp_server = SkyvernOverlayMCPServer(+ transport=skyvern_mcp,+ overlays=overlays,+ alias_map=alias_map,+ allowlist=frozenset(alias_map.values()),+ context_provider=lambda: ctx,+ )+ ctx.discovery_mcp_server = mcp_server+ agent = Agent(+ name="workflow-copilot",+ instructions=system_prompt,+ tools=native_tools,+ mcp_servers=[mcp_server],+ model=model_name,+ output_guardrails=output_guardrails,+ )+ session = create_copilot_session(chat_id)+ model_token = _copilot_model_name.set(model_name)+ try:+ async with MCPServerManager([mcp_server]) as manager:+ agent.mcp_servers = list(manager.active_servers)+ attempts = 2 if allow_untested_retry else 1+ for attempt in range(attempts):+ try:+ result = await run_with_enforcement(+ agent=agent,+ initial_input=user_message,+ ctx=ctx,+ stream=stream,+ max_turns=copilot_config.max_turns,+ hooks=CopilotRunHooks(ctx),+ run_config=run_config,+ session=session,+ copilot_config=copilot_config,+ )+ break+ except Exception as exc:+ if (+ attempt + 1 < attempts+ and getattr(ctx, "last_workflow", None) is None+ and isinstance(exc, LiteLLMNotFoundError)+ ):+ LOG.warning("Retrying untested draft agent loop after model lookup failure")+ continue+ raise+ LOG.info(+ "Copilot agent model attempt succeeded",+ workflow_permanent_id=getattr(ctx, "workflow_permanent_id", None),+ llm_key=llm_key,+ )+ return result+ finally:+ _copilot_model_name.reset(model_token)+ session.close()++def _build_request_policy_clarification_result(policy: RequestPolicy,prior_global_llm_context: str | None,@@ -4131,6 +4221,49 @@ def _build_copilot_output_guardrails(]+def _build_self_heal_output_guardrails(+ OutputGuardrailCls: Any,+ GuardrailFunctionOutputCls: Any,+) -> list[Any]:+ # Self-heal final output is machine-consumed, not user-facing chat text.+ # Chat output policy requires CopilotContext and fails closed in headless runs; self-heal only trips on mutate/ask-human.+ def self_heal_output_guardrail(_context: Any, _agent: Any, agent_output: Any) -> Any:+ try:+ final_text = extract_final_text(agent_output)+ except Exception:+ final_text = _agent_output_to_text(agent_output)++ action_data = parse_final_response(final_text)+ response_type = str(action_data.get("type") or "REPLY").strip().upper()+ if response_type not in COPILOT_RESPONSE_TYPES:+ response_type = "REPLY"++ raw_upper = final_text.upper()+ replace_marker_present = "REPLACE_WORKFLOW" in raw_upper+ user_response = action_data.get("user_response")+ parse_failed = response_type == "REPLY" and (+ str(user_response or "") == final_text or str(user_response or "") == "Done."+ )+ tripwire_triggered = response_type in {"REPLACE_WORKFLOW", "ASK_QUESTION"} or (+ parse_failed and replace_marker_present+ )++ trace_data = {+ "response_type": response_type,+ "tripwire_triggered": tripwire_triggered,+ "origin": "runtime_self_heal",+ }+ LOG.info("self-heal output guardrail verdict", **trace_data)+ return GuardrailFunctionOutputCls(output_info=trace_data, tripwire_triggered=tripwire_triggered)++ return [+ OutputGuardrailCls(+ guardrail_function=self_heal_output_guardrail,+ name="self_heal_output_guardrail",+ )+ ]++def _output_policy_verdict_from_guardrail_exception(exc: BaseException) -> OutputPolicyVerdict:guardrail_result = getattr(exc, "guardrail_result", None)guardrail_output = getattr(guardrail_result, "output", None)@@ -4513,7 +4646,6 @@ async def _run_copilot_turn_impl(MaxTurnsExceeded,OutputGuardrailTripwireTriggered,)- from agents.mcp import MCPServerManagerfrom agents.run_context import RunContextWrapperexcept ModuleNotFoundError as e:if e.name == "agents":@@ -4690,7 +4822,6 @@ async def _run_copilot_turn_impl(ctx=ctx,)- from skyvern.cli.mcp_tools import mcp as skyvern_mcpfrom skyvern.forge.sdk.copilot.enforcement import (CopilotBuiltUnverified,CopilotGoalSatisfied,@@ -4698,12 +4829,8 @@ async def _run_copilot_turn_impl(CopilotTotalTimeoutError,CopilotUnrecoverableToolError,gate_decision_trace_fields,- run_with_enforcement,)- from skyvern.forge.sdk.copilot.hooks import CopilotRunHooks- from skyvern.forge.sdk.copilot.mcp_adapter import SkyvernOverlayMCPServerfrom skyvern.forge.sdk.copilot.model_resolver import resolve_model_config- from skyvern.forge.sdk.copilot.session_factory import create_copilot_sessionfrom skyvern.forge.sdk.copilot.tools import (NATIVE_TOOLS,_build_skyvern_mcp_overlays,@@ -4806,62 +4933,22 @@ async def _run_copilot_turn_impl(attempt_run_config: Any,attempt_llm_key: str,) -> RunResultStreaming:- mcp_server = SkyvernOverlayMCPServer(- transport=skyvern_mcp,- overlays=overlays,+ return await _run_agent_loop_with_surface(+ ctx=ctx,+ stream=stream,+ chat_id=chat_id,+ user_message=user_message,+ system_prompt=system_prompt,+ model_name=attempt_model_name,+ run_config=attempt_run_config,+ llm_key=attempt_llm_key,+ copilot_config=copilot_config,+ native_tools=native_tools,alias_map=alias_map,- allowlist=frozenset(alias_map.values()),- context_provider=lambda: ctx,- )- # The discovery walker reaches the connected FastMCP client through- # ctx, without exposing private overlay state.- ctx.discovery_mcp_server = mcp_server- agent = Agent(- name="workflow-copilot",- instructions=system_prompt,- tools=native_tools,- mcp_servers=[mcp_server],- model=attempt_model_name,+ overlays=overlays,output_guardrails=output_guardrails,+ allow_untested_retry=ctx.allow_untested_workflow_draft,)- session = create_copilot_session(chat_id)- model_token = _copilot_model_name.set(attempt_model_name)- try:- async with MCPServerManager([mcp_server]) as manager:- agent.mcp_servers = list(manager.active_servers)- attempts = 2 if ctx.allow_untested_workflow_draft else 1- for attempt in range(attempts):- try:- result = await run_with_enforcement(- agent=agent,- initial_input=user_message,- ctx=ctx,- stream=stream,- max_turns=copilot_config.max_turns,- hooks=CopilotRunHooks(ctx),- run_config=attempt_run_config,- session=session,- copilot_config=copilot_config,- )- break- except Exception as exc:- if (- attempt + 1 < attempts- and ctx.last_workflow is None- and isinstance(exc, LiteLLMNotFoundError)- ):- LOG.warning("Retrying untested draft agent loop after model lookup failure")- continue- raise- LOG.info(- "Copilot agent model attempt succeeded",- workflow_permanent_id=chat_request.workflow_permanent_id,- llm_key=attempt_llm_key,- )- return result- finally:- _copilot_model_name.reset(model_token)- session.close()try:with trace_context:diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex b800b6ef4..e84b382ec 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -61,6 +61,7 @@ if TYPE_CHECKING:from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcomefrom skyvern.forge.sdk.copilot.schema_incompatibility import SchemaIncompatibilityfrom skyvern.forge.sdk.copilot.turn_halt import TurnHalt+ from skyvern.forge.sdk.copilot.turn_intent import TurnIntentfrom skyvern.forge.sdk.copilot.turn_ownership import GatePrecedenceConflictEvent, TurnClaimant, TurnOwnershipfrom skyvern.forge.sdk.core.event_source_stream import EventSourceStreamfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession@@ -242,6 +243,7 @@ class AgentContext:turn_origin: TurnOrigin = TurnOrigin.interactiveinjected_browser_state: BrowserState | None = Noneheal_workflow_run_id: str | None = None+ turn_intent: TurnIntent | None = None# Ephemeral carrier for SDK-action run reuse, bounded by browser sessions touched in one Copilot run.sdk_action_workflow_run_ids_by_browser_session: dict[SdkActionWorkflowRunCacheKey, str] = field(default_factory=dict@@ -648,6 +650,33 @@ async def _resolve_self_heal_browser_state(ctx: AgentContext) -> tuple[str, Browreturn session_id, browser_state, page+async def resolve_browser_state_for_context(+ ctx: AgentContext,+ *,+ session_id: str | None = None,+) -> BrowserState | None:+ resolved_session_id = session_id if session_id is not None else ctx.browser_session_id+ if not resolved_session_id:+ return None+ if ctx.turn_origin == TurnOrigin.runtime_self_heal or is_self_heal_session_id(resolved_session_id):+ try:+ _resolved_session_id, browser_state, _ = await _resolve_self_heal_browser_state(ctx)+ if _resolved_session_id != resolved_session_id:+ LOG.info(+ "Resolved self-heal browser session id differs from requested",+ requested_session_id=resolved_session_id,+ resolved_session_id=_resolved_session_id,+ organization_id=ctx.organization_id,+ )+ return browser_state+ except HealAdoptionFailed:+ return None+ return await app.PERSISTENT_SESSIONS_MANAGER.get_browser_state(+ session_id=resolved_session_id,+ organization_id=ctx.organization_id,+ )++@asynccontextmanagerasync def mcp_browser_context(ctx: AgentContext) -> AsyncIterator[None]:"""Push copilot browser state into the MCP session ContextVar for tool calls."""@@ -684,10 +713,7 @@ async def mcp_browser_context(ctx: AgentContext) -> AsyncIterator[None]:ctx.browser_session_id = browser_session_idsdk_action_workflow_run_cache_key = (ctx.organization_id, browser_session_id)else:- browser_state = await app.PERSISTENT_SESSIONS_MANAGER.get_browser_state(- session_id=browser_session_id,- organization_id=ctx.organization_id,- )+ browser_state = await resolve_browser_state_for_context(ctx, session_id=browser_session_id)if not browser_state or not _browser_context_is_attachable(browser_state.browser_context):# Keep the session id out of the raised message -- it can propagate# to LLM- or user-visible output -- but log it for operators.@@ -726,6 +752,12 @@ async def mcp_browser_context(ctx: AgentContext) -> AsyncIterator[None]:# new SkyvernBrowser's pages[-1] fallback.state._active_page = working_pageregister_copilot_session(browser_session_id, state)+ if is_self_heal_session_id(browser_session_id):+ LOG.info(+ "registered self-heal browser session",+ session_id=browser_session_id,+ organization_id=ctx.organization_id,+ )try:async with scoped_session(state):yield@@ -737,6 +769,8 @@ async def mcp_browser_context(ctx: AgentContext) -> AsyncIterator[None]:else:ctx.sdk_action_workflow_run_ids_by_browser_session.pop(sdk_action_workflow_run_cache_key, None)unregister_copilot_session(browser_session_id)+ if is_self_heal_session_id(browser_session_id):+ LOG.info("unregistered self-heal browser session", session_id=browser_session_id)finally:reset_api_key_override(override_token)diff --git a/skyvern/forge/sdk/copilot/self_heal_recovery.py b/skyvern/forge/sdk/copilot/self_heal_recovery.pynew file mode 100644index 000000000..bfffb03d5--- /dev/null+++ b/skyvern/forge/sdk/copilot/self_heal_recovery.py@@ -0,0 +1,486 @@+from __future__ import annotations++import asyncio+import json+import time+import uuid+from dataclasses import dataclass, field+from typing import TYPE_CHECKING, Any++import structlog++from skyvern.forge import app+from skyvern.forge.sdk.copilot import llm_config+from skyvern.forge.sdk.copilot.config import CopilotConfig+from skyvern.forge.sdk.copilot.runtime import AgentContext, ScoutedInteraction+from skyvern.forge.sdk.copilot.terminal_predicates import outcome_fully_verified+from skyvern.forge.sdk.copilot.turn_origin import HealAdoptionFailed, TurnOrigin++if TYPE_CHECKING:+ from skyvern.forge.sdk.copilot.turn_intent import TurnIntent++LOG = structlog.get_logger()++_SELF_HEAL_MCP_TOOL_ALLOWLIST = frozenset(+ {+ "navigate_browser",+ "get_browser_screenshot",+ "evaluate",+ "click",+ "type_text",+ "scroll",+ "console_messages",+ "select_option",+ "press_key",+ }+)+++class _NoopEventSourceStream:+ async def send(self, data: Any) -> bool:+ del data+ return True++ async def is_disconnected(self) -> bool:+ return False++ async def close(self) -> None:+ return None+++@dataclass(slots=True)+class SelfHealRecoveryResult:+ success: bool+ action_count: int+ wall_clock_ms: int+ verified: bool = False+ performed_mutation: bool = False+ scout_trajectory: list[ScoutedInteraction] = field(default_factory=list)+ failure_note: str | None = None+++def _runtime_self_heal_intent() -> TurnIntent:+ from skyvern.forge.sdk.copilot.turn_intent import (+ TurnIntent,+ TurnIntentAuthority,+ TurnIntentExpectedOutput,+ TurnIntentMode,+ TurnIntentReasonCode,+ )++ authority = TurnIntentAuthority(+ may_update_workflow=False,+ may_run_blocks=False,+ may_answer_without_mutation=True,+ requires_user_input=False,+ may_read_run_context=False,+ )+ return TurnIntent(+ mode=TurnIntentMode.BUILD,+ user_goal="runtime self-heal recovery",+ authority=authority,+ expected_output=TurnIntentExpectedOutput.EXPLANATION,+ reason_codes=[TurnIntentReasonCode.REQUEST_POLICY_DERIVED],+ confidence=1.0,+ )+++def _self_heal_recovery_prompt(goal: str) -> str:+ return (+ "You are performing runtime self-heal recovery for a failed code block.\n"+ "Recover this goal on the current live page and stop:\n"+ f"{goal}\n\n"+ "Constraints:\n"+ "- Browser/scout tools only.\n"+ "- Never ask the user for input.\n"+ "- Never propose or mutate workflow YAML.\n"+ '- Final answer must be strict JSON: {"type":"REPLY","user_response":"<short completion claim>"}.\n'+ )+++def _self_heal_tool_surface() -> tuple[dict[str, str], dict[str, Any]]:+ from skyvern.forge.sdk.copilot.tools import _build_skyvern_mcp_overlays, get_skyvern_mcp_alias_map++ alias_map = get_skyvern_mcp_alias_map()+ overlays = _build_skyvern_mcp_overlays()+ return (+ {name: target for name, target in alias_map.items() if name in _SELF_HEAL_MCP_TOOL_ALLOWLIST},+ {name: overlay for name, overlay in overlays.items() if name in _SELF_HEAL_MCP_TOOL_ALLOWLIST},+ )+++def _classify_terminal_reply(final_text: str) -> str:+ from skyvern.forge.sdk.copilot.output_utils import parse_final_response++ response_type = ""+ stripped = final_text.strip()+ if stripped:+ try:+ parsed = json.loads(stripped, strict=False)+ except Exception:+ parsed = parse_final_response(final_text)+ if parsed.get("user_response") == final_text:+ return "unparseable_terminal"+ if isinstance(parsed, dict):+ response_type = str(parsed.get("type") or "").strip().upper()++ if response_type == "ASK_QUESTION":+ return "asked_user_question"+ if response_type == "REPLACE_WORKFLOW":+ return "proposed_workflow_mutation"+ if response_type == "REPLY":+ return "reply"+ return "unparseable_terminal"+++def _count_successful_self_heal_browser_calls(ctx: AgentContext) -> int:+ count = 0+ for activity in getattr(ctx, "tool_activity", []):+ if not isinstance(activity, dict):+ continue+ tool_name = str(activity.get("tool") or "").strip()+ if tool_name not in _SELF_HEAL_MCP_TOOL_ALLOWLIST:+ continue+ summary = str(activity.get("summary") or "").strip()+ if summary.startswith("Failed:"):+ continue+ count += 1+ return count+++def _effective_action_count(ctx: AgentContext) -> int:+ return max(len(ctx.scout_trajectory), _count_successful_self_heal_browser_calls(ctx))+++_SELF_HEAL_MUTATING_TOOLS = frozenset({"click", "type_text", "select_option", "press_key", "evaluate"})+++def _performed_mutation_during_self_heal(ctx: AgentContext) -> bool:+ for activity in getattr(ctx, "tool_activity", []):+ if not isinstance(activity, dict):+ continue+ tool_name = str(activity.get("tool") or "").strip()+ # evaluate runs arbitrary JS (form.submit(), dispatched clicks), so it can commit a side+ # effect without a click/type call; treat it as mutating so the fail-closed floor+ # suppression is not bypassed.+ if tool_name not in _SELF_HEAL_MUTATING_TOOLS:+ continue+ summary = str(activity.get("summary") or "").strip()+ if summary.startswith("Failed:"):+ continue+ return True+ return False+++async def _seed_completion_criteria(+ ctx: AgentContext,+ *,+ composed_goal: str,+ organization_id: str,+ llm_handler: Any,+ copilot_config: Any,+ workflow_run_id: str,+ workflow_run_block_id: str,+) -> bool:+ try:+ from skyvern.forge.sdk.copilot.request_policy import build_request_policy++ # A runtime heal is verified from the post-recovery page, so criteria must be phrased as+ # the observable end state (what is or is not present), not the actions taken to reach it.+ # An action-phrased criterion ("the Accept button is clicked") is unverifiable from a page+ # snapshot and forces every heal to regress to the floor.+ verification_request = (+ f"{composed_goal}\n\n"+ "Define completion criteria strictly as the observable end state of the page once this "+ "is achieved (what becomes visible, or is no longer visible), never as the actions taken."+ )+ policy = await build_request_policy(+ user_message=verification_request,+ workflow_yaml="",+ chat_history=[],+ global_llm_context="",+ organization_id=organization_id,+ handler=llm_handler,+ config=copilot_config,+ )+ ctx.request_policy = policy+ # verification_seeded must mean "there is something to grade", not merely "the call+ # returned". Current main's criteria generator is conservative, and a machine-written heal+ # goal can yield zero gradeable criteria, which makes verified=True unreachable and would+ # silently regress every such heal to the floor. Surface it as a distinct signal instead.+ if not policy.graded_completion_criteria():+ LOG.warning(+ "Runtime self-heal produced no gradeable completion criteria; verification cannot pass",+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ )+ return False+ return True+ except Exception:+ LOG.warning(+ "Runtime self-heal completion-verification seeding failed",+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ exc_info=True,+ )+ return False+++async def _run_post_loop_verification_from_browser_state(ctx: AgentContext, *, browser_state: Any) -> None:+ try:+ page = await browser_state.get_or_create_page()+ from skyvern.forge.sdk.copilot.composition_browser_expressions import COMPOSITION_STRIPPED_HTML_EXPRESSION+ from skyvern.forge.sdk.copilot.tools.completion import _maybe_run_completion_verification_from_page_observation+ from skyvern.forge.sdk.copilot.tools.page_observation import _record_composition_page_observation++ html = await page.evaluate(COMPOSITION_STRIPPED_HTML_EXPRESSION)+ url = page.url+ title = await page.title()+ observed_data = {+ "html": html,+ "url": url,+ "title": title,+ }+ # Deterministic post-loop evidence capture keeps runtime self-heal verification+ # independent from MCP evaluate-hook timing and MCP server lifecycle.+ _record_composition_page_observation(+ ctx,+ source_tool="self_heal_verify",+ url=url,+ title=title,+ observed_data=observed_data,+ append_to_flow=True,+ reached_via="auto",+ )+ await _maybe_run_completion_verification_from_page_observation(+ ctx,+ url=url,+ title=title,+ observed_data=observed_data,+ )+ except Exception:+ LOG.warning("self-heal post-loop verification capture failed", exc_info=True)+++def _terminal_failure_note(final_text: str) -> str | None:+ terminal_kind = _classify_terminal_reply(final_text)+ if terminal_kind == "reply":+ return None+ return terminal_kind+++async def run_self_heal_recovery(+ *,+ block: Any,+ workflow_run_context: Any,+ workflow_run_id: str,+ workflow_run_block_id: str,+ organization_id: str,+ browser_state: Any,+ failing_line: int | None,+ api_key: str,+ max_actions: int,+ wall_clock_budget_seconds: int,+) -> SelfHealRecoveryResult:+ if max_actions <= 0:+ return SelfHealRecoveryResult(+ success=False,+ verified=False,+ action_count=0,+ wall_clock_ms=0,+ scout_trajectory=[],+ failure_note="max_actions_exhausted",+ )++ composed_goal = block._compose_heal_goal(workflow_run_context=workflow_run_context, failing_line=failing_line)+ stream = _NoopEventSourceStream()+ ctx = AgentContext(+ organization_id=organization_id,+ workflow_id=workflow_run_context.workflow_id,+ workflow_permanent_id=workflow_run_context.workflow_permanent_id,+ workflow_yaml="",+ browser_session_id=None,+ stream=stream,+ api_key=api_key,+ turn_origin=TurnOrigin.runtime_self_heal,+ injected_browser_state=browser_state,+ heal_workflow_run_id=workflow_run_id,+ )+ ctx.turn_intent = _runtime_self_heal_intent()++ copilot_config = app.AGENT_FUNCTION.get_copilot_config() or CopilotConfig()+ copilot_config.max_turns = min(copilot_config.max_turns, max_actions + 1)+ llm_handler = await llm_config.resolve_main_copilot_handler(+ workflow_run_context.workflow_permanent_id, organization_id+ )+ from skyvern.forge.sdk.copilot.model_resolver import resolve_model_config++ model_name, run_config, llm_key, _supports_vision = resolve_model_config(+ llm_handler,+ copilot_config=copilot_config,+ )+ alias_map, overlays = _self_heal_tool_surface()+ if not alias_map:+ return SelfHealRecoveryResult(+ success=False,+ verified=False,+ action_count=0,+ wall_clock_ms=0,+ scout_trajectory=[],+ failure_note="tool_surface_unavailable",+ )+ verification_seeded = False++ started = time.monotonic()+ try:+ async with asyncio.timeout(wall_clock_budget_seconds):+ from agents import GuardrailFunctionOutput, OutputGuardrail++ from skyvern.forge.sdk.copilot.agent import (+ _build_self_heal_output_guardrails,+ _run_agent_loop_with_surface,+ )++ output_guardrails = _build_self_heal_output_guardrails(OutputGuardrail, GuardrailFunctionOutput)++ from agents.exceptions import ModelBehaviorError++ try:+ result = await _run_agent_loop_with_surface(+ ctx=ctx,+ stream=stream,+ chat_id=f"selfheal:{workflow_run_id}:{uuid.uuid4().hex}",+ user_message=_self_heal_recovery_prompt(composed_goal),+ system_prompt="You are a browser-only runtime self-heal recovery agent.",+ model_name=model_name,+ run_config=run_config,+ llm_key=llm_key,+ copilot_config=copilot_config,+ native_tools=[],+ alias_map=alias_map,+ overlays=overlays,+ output_guardrails=output_guardrails,+ allow_untested_retry=False,+ )+ except ModelBehaviorError:+ # The model can emit an out-of-surface tool call (e.g. update_workflow) after+ # already fixing the page; the SDK raises it as fatal. The browser work may+ # satisfy the goal, so grade the live page and let the judge be authoritative.+ LOG.warning(+ "Runtime self-heal agent made an out-of-surface tool call; grading page anyway",+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ )+ result = None+ # Seed completion criteria AFTER the loop: build_request_policy classifies the heal+ # goal as an authoring request, so pre-loop seeding drives the browser-only agent to+ # call workflow-authoring tools (update_workflow) absent from its surface. Post-loop,+ # only the judge reads the criteria.+ verification_seeded = await _seed_completion_criteria(+ ctx,+ composed_goal=composed_goal,+ organization_id=organization_id,+ llm_handler=llm_handler,+ copilot_config=copilot_config,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ )+ ctx.post_run_page_observation_after_failed_test = True+ await _run_post_loop_verification_from_browser_state(ctx, browser_state=browser_state)+ except HealAdoptionFailed:+ raise+ except asyncio.TimeoutError:+ wall_clock_ms = int((time.monotonic() - started) * 1000)+ return SelfHealRecoveryResult(+ success=False,+ verified=False,+ action_count=_effective_action_count(ctx),+ wall_clock_ms=wall_clock_ms,+ performed_mutation=_performed_mutation_during_self_heal(ctx),+ scout_trajectory=list(ctx.scout_trajectory),+ failure_note="wall_clock_budget_exhausted",+ )+ except Exception as exc:+ wall_clock_ms = int((time.monotonic() - started) * 1000)+ LOG.warning(+ "Runtime self-heal recovery turn failed",+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ error_type=type(exc).__name__,+ exc_info=True,+ )+ return SelfHealRecoveryResult(+ success=False,+ verified=False,+ action_count=_effective_action_count(ctx),+ wall_clock_ms=wall_clock_ms,+ performed_mutation=_performed_mutation_during_self_heal(ctx),+ scout_trajectory=list(ctx.scout_trajectory),+ failure_note=type(exc).__name__,+ )++ wall_clock_ms = int((time.monotonic() - started) * 1000)+ from skyvern.forge.sdk.copilot.output_utils import extract_final_text++ final_text = extract_final_text(result) if result is not None else ""+ action_count = _effective_action_count(ctx)+ verified = verification_seeded and outcome_fully_verified(ctx)+ if action_count > max_actions:+ return SelfHealRecoveryResult(+ success=False,+ verified=False,+ action_count=action_count,+ wall_clock_ms=wall_clock_ms,+ performed_mutation=_performed_mutation_during_self_heal(ctx),+ scout_trajectory=list(ctx.scout_trajectory),+ failure_note="max_actions_exhausted",+ )+ if result is not None:+ terminal_failure_note = _terminal_failure_note(final_text)+ if terminal_failure_note is not None:+ return SelfHealRecoveryResult(+ success=False,+ verified=False,+ action_count=action_count,+ wall_clock_ms=wall_clock_ms,+ performed_mutation=_performed_mutation_during_self_heal(ctx),+ scout_trajectory=list(ctx.scout_trajectory),+ failure_note=terminal_failure_note,+ )+ elif not verified:+ # The loop ended on an out-of-surface tool call, so there is no clean terminal reply.+ # Success then rests entirely on the judge; an unverified page is a real failure.+ return SelfHealRecoveryResult(+ success=False,+ verified=False,+ action_count=action_count,+ wall_clock_ms=wall_clock_ms,+ performed_mutation=_performed_mutation_during_self_heal(ctx),+ scout_trajectory=list(ctx.scout_trajectory),+ failure_note="out_of_surface_tool_call",+ )+ if action_count < 1:+ return SelfHealRecoveryResult(+ success=False,+ verified=False,+ action_count=action_count,+ wall_clock_ms=wall_clock_ms,+ performed_mutation=_performed_mutation_during_self_heal(ctx),+ scout_trajectory=list(ctx.scout_trajectory),+ failure_note="no_action_progress",+ )+ if verified:+ unverified_note = None+ elif not verification_seeded:+ unverified_note = "no_gradeable_criteria"+ else:+ unverified_note = "goal_unverified"+ return SelfHealRecoveryResult(+ success=True,+ verified=verified,+ action_count=action_count,+ wall_clock_ms=wall_clock_ms,+ performed_mutation=_performed_mutation_during_self_heal(ctx),+ scout_trajectory=list(ctx.scout_trajectory),+ failure_note=unverified_note,+ )diff --git a/skyvern/forge/sdk/copilot/terminal_predicates.py b/skyvern/forge/sdk/copilot/terminal_predicates.pyindex efd895391..9f6ffa4d8 100644--- a/skyvern/forge/sdk/copilot/terminal_predicates.py+++ b/skyvern/forge/sdk/copilot/terminal_predicates.py@@ -1,6 +1,6 @@"""Leaf predicates for terminal outcome verification.-These read only ``CopilotContext`` fields and have no copilot-module imports, so+These read only ``AgentContext`` fields and have no copilot-module imports, sothe diagnosis, enforcement, and agent layers can all key barrier decisions on thesame judge verdict without an import cycle."""@@ -10,20 +10,20 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGif TYPE_CHECKING:- from skyvern.forge.sdk.copilot.context import CopilotContext+ from skyvern.forge.sdk.copilot.runtime import AgentContext-def artifact_health_blocked(ctx: CopilotContext) -> bool:+def artifact_health_blocked(ctx: AgentContext) -> bool:reason = ctx.last_artifact_health_blocker_reasonreturn isinstance(reason, str) and bool(reason.strip())-def outcome_criteria_evaluated(ctx: CopilotContext) -> bool:+def outcome_criteria_evaluated(ctx: AgentContext) -> bool:result = ctx.completion_verification_resultreturn result is not None and result.status == "evaluated"-def _has_same_run_committed_demonstrated_outcome(ctx: CopilotContext) -> bool:+def _has_same_run_committed_demonstrated_outcome(ctx: AgentContext) -> bool:outcome = getattr(ctx, "last_run_outcome", None)run_id = getattr(ctx, "last_run_blocks_workflow_run_id", None)return (@@ -34,7 +34,7 @@ def _has_same_run_committed_demonstrated_outcome(ctx: CopilotContext) -> bool:)-def outcome_fully_verified(ctx: CopilotContext) -> bool:+def outcome_fully_verified(ctx: AgentContext) -> bool:"""Whether the judge confirmed every outcome criterion from this run's evidence.The verdict is authoritative over run status: a run that reached the goal isdiff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.pyindex 9094efaad..45ec4bc4e 100644--- a/skyvern/forge/sdk/copilot/tools/_shared.py+++ b/skyvern/forge/sdk/copilot/tools/_shared.py@@ -9,7 +9,6 @@ from urllib.parse import urlparseimport structlogimport yaml-from skyvern.forge import appfrom skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.composition_browser_expressions import (COMPOSITION_STRIPPED_HTML_EXPRESSION as _COMPOSITION_STRIPPED_HTML_EXPRESSION,@@ -26,7 +25,7 @@ from skyvern.forge.sdk.copilot.composition_browser_expressions import (from skyvern.forge.sdk.copilot.composition_evidence import has_bounded_page_schema, parse_composition_structuredfrom skyvern.forge.sdk.copilot.context import CopilotContextfrom skyvern.forge.sdk.copilot.enforcement import TOTAL_TIMEOUT_SECONDS, _elapsed_run_seconds-from skyvern.forge.sdk.copilot.runtime import AgentContext+from skyvern.forge.sdk.copilot.runtime import AgentContext, resolve_browser_state_for_contextfrom skyvern.forge.sdk.copilot.task_output_envelope import (_TASK_ENVELOPE_BLOCK_TYPES,_TASK_OUTPUT_PAYLOAD_FIELDS,@@ -454,10 +453,7 @@ async def _fallback_page_info(ctx: AgentContext, session_id_override: str | Noneif not session_id:return "", ""try:- browser_state = await app.PERSISTENT_SESSIONS_MANAGER.get_browser_state(- session_id=session_id,- organization_id=ctx.organization_id,- )+ browser_state = await resolve_browser_state_for_context(ctx, session_id=session_id)if not browser_state:return "", ""page = await browser_state.get_or_create_page()diff --git a/skyvern/forge/sdk/copilot/tools/frontier.py b/skyvern/forge/sdk/copilot/tools/frontier.pyindex 7a7c33787..5d9b2d449 100644--- a/skyvern/forge/sdk/copilot/tools/frontier.py+++ b/skyvern/forge/sdk/copilot/tools/frontier.py@@ -30,6 +30,7 @@ from skyvern.forge.sdk.copilot.failure_tracking import (from skyvern.forge.sdk.copilot.output_utils import INTERNAL_VALIDATION_FAILURE_PREFIXfrom skyvern.forge.sdk.copilot.runtime import (AgentContext,+ resolve_browser_state_for_context,)from skyvern.forge.sdk.copilot.workflow_yaml import _process_workflow_yamlfrom skyvern.forge.sdk.workflow.models.block import BlockTypeVar, get_all_blocks@@ -1193,10 +1194,7 @@ async def _workflow_with_runtime_frontier_starter_url_seed(current_page_url: str | None = Nonetry:- browser_state = await app.PERSISTENT_SESSIONS_MANAGER.get_browser_state(- session_id=session_id,- organization_id=ctx.organization_id,- )+ browser_state = await resolve_browser_state_for_context(ctx, session_id=session_id)if browser_state is not None:page = await browser_state.get_working_page()# Playwright Page.url is exposed as a dynamic property at this boundary.diff --git a/skyvern/forge/sdk/copilot/tools/guardrails.py b/skyvern/forge/sdk/copilot/tools/guardrails.pyindex ef8503f74..1bcfb1d1b 100644--- a/skyvern/forge/sdk/copilot/tools/guardrails.py+++ b/skyvern/forge/sdk/copilot/tools/guardrails.py@@ -30,6 +30,7 @@ from skyvern.forge.sdk.copilot.turn_intent import (TurnIntent,TurnIntentMode,)+from skyvern.forge.sdk.copilot.turn_origin import TurnOriginfrom skyvern.forge.sdk.workflow.models.parameter import (OutputParameter,WorkflowParameter,@@ -637,6 +638,22 @@ def _authority_tool_error(*,ignore_request_policy_error: bool = False,) -> str | None:+ if ctx.turn_origin == TurnOrigin.runtime_self_heal:+ return _emit_tool_blocker_signal(+ ctx,+ _build_turn_intent_signal(+ tool_name=tool_name,+ classifier_mode="runtime_self_heal",+ reason_code="runtime_self_heal_native_tool_blocked",+ agent_steering_text=(+ "Runtime self-heal allows browser MCP tools only; do not call native copilot tools."+ ),+ user_facing_reason="Runtime self-heal cannot use this tool.",+ recovery_hint="stop",+ blocker_kind="tool_error",+ renders_final_reply=False,+ ),+ )# Request-policy precedes turn-intent unless explicitly ignored.turn_intent_signal = _turn_intent_tool_error(ctx, tool_name)request_policy_signal = _request_policy_tool_error(ctx, tool_name)diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.pyindex 459a70ee4..f9113d293 100644--- a/skyvern/forge/sdk/copilot/tools/scouting.py+++ b/skyvern/forge/sdk/copilot/tools/scouting.py@@ -12,7 +12,6 @@ from urllib.parse import urlparseimport structlogfrom skyvern.config import settings-from skyvern.forge import appfrom skyvern.forge.sdk.copilot.build_test_outcome import (record_build_test_outcome,recorded_outcome_from_loaded_result_evidence,@@ -59,6 +58,7 @@ from skyvern.forge.sdk.copilot.runtime import (AgentContext,PendingBrowserInteractionObservation,ScoutedInteraction,+ resolve_browser_state_for_context,)from ._shared import (@@ -127,10 +127,7 @@ async def _live_working_page_url(ctx: AgentContext) -> str | None:if not ctx.browser_session_id:return Nonetry:- browser_state = await app.PERSISTENT_SESSIONS_MANAGER.get_browser_state(- session_id=ctx.browser_session_id,- organization_id=ctx.organization_id,- )+ browser_state = await resolve_browser_state_for_context(ctx, session_id=ctx.browser_session_id)if not browser_state:return Nonepage = await browser_state.get_or_create_page()diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.pyindex 2c5ae1455..5ed2e47b2 100644--- a/skyvern/forge/sdk/workflow/models/block.py+++ b/skyvern/forge/sdk/workflow/models/block.py@@ -101,6 +101,9 @@ from skyvern.forge.sdk.api.llm.exceptions import (from skyvern.forge.sdk.api.llm.schema_validator import validate_schemafrom skyvern.forge.sdk.artifact.models import ArtifactTypefrom skyvern.forge.sdk.copilot.block_goal_wrapping import compose_mini_goal+from skyvern.forge.sdk.copilot.runtime import _browser_context_is_attachable+from skyvern.forge.sdk.copilot.self_heal_recovery import SelfHealRecoveryResult, run_self_heal_recovery+from skyvern.forge.sdk.copilot.turn_origin import HealAdoptionFailed, TurnOriginfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.aiohttp_helper import aiohttp_requestfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContext@@ -168,7 +171,7 @@ from skyvern.forge.sdk.workflow.secret_encryption import (is_encrypted_secret,)from skyvern.schemas.runs import RunEngine-from skyvern.schemas.self_heal import HealClassification, HealSkipReason, OutputObligation+from skyvern.schemas.self_heal import HealClassification, HealSkipReason, HealStatus, OutputObligationfrom skyvern.schemas.workflows import (AIFallbackMode,BlockResult,@@ -181,6 +184,7 @@ from skyvern.schemas.workflows import ()from skyvern.services import otp_servicefrom skyvern.services.error_detection_service import detect_user_defined_errors_for_task+from skyvern.services.self_heal_cap import check_and_increment_self_heal_capfrom skyvern.utils.strings import generate_random_stringfrom skyvern.utils.templating import get_missing_variablesfrom skyvern.utils.token_counter import count_tokens@@ -4066,6 +4070,35 @@ async def wrapper({default_args}):return line_urlreturn ""+ def _matched_step_index_for_failing_line(self, failing_line: int | None) -> int | None:+ if failing_line is None:+ return None+ matched_step = self._match_step_for_failing_line(failing_line)+ if matched_step is None:+ return None+ steps = self.steps or []+ for idx, step in enumerate(steps):+ if step is matched_step:+ return idx+ return None++ def _compose_heal_goal(self, *, workflow_run_context: WorkflowRunContext, failing_line: int | None) -> str:+ safe_main = workflow_run_context.mask_secrets_in_data(self.prompt or "")+ matched_step = self._match_step_for_failing_line(failing_line) if failing_line is not None else None+ if matched_step is None or not matched_step.description:+ return safe_main+ steps = self.steps or []+ matched_index = next((idx for idx, step in enumerate(steps) if step is matched_step), None)+ if matched_index is None:+ matched_index = len(steps) - 1+ descriptions = [matched_step.description] + [+ step.description for step in steps[matched_index + 1 :] if step.description+ ]+ safe_mini = "\nThen: ".join(+ workflow_run_context.mask_secrets_in_data(description) for description in descriptions+ )+ return compose_mini_goal(main_goal=safe_main, mini_goal=safe_mini)+async def _self_heal_enabled(self, workflow_run_context: WorkflowRunContext) -> bool:# User-facing per-workflow setting, restricted to copilot-authored workflows —# pre-copilot code blocks must never gain agentic recovery from the toggle alone.@@ -4197,27 +4230,10 @@ async def wrapper({default_args}):escalation_step: Step | None = Nonerecovery_block_id: str | None = Nonetry:- # block.prompt is the operative goal; a confidently-matched step only narrows it. The match- # is advisory (spans are display-oriented and render-shifted), so any miss heals on the prompt.- safe_main = workflow_run_context.mask_secrets_in_data(self.prompt)- matched_step = self._match_step_for_failing_line(failing_line) if failing_line is not None else None- if matched_step is not None and matched_step.description:- # The heal owns the failing step plus every subsequent authored step — a- # step-only goal would complete the block while trailing steps ran by no one.- steps = self.steps or []- # Identity scan, not .index(): value equality would match an earlier duplicate step.- matched_index = next((i for i, step in enumerate(steps) if step is matched_step), None)- if matched_index is None:- matched_index = len(steps) - 1 # defensive; matched_step always comes from self.steps- descriptions = [matched_step.description] + [- step.description for step in steps[matched_index + 1 :] if step.description- ]- safe_mini = "\nThen: ".join(- workflow_run_context.mask_secrets_in_data(description) for description in descriptions- )- navigation_goal = compose_mini_goal(main_goal=safe_main, mini_goal=safe_mini)- else:- navigation_goal = safe_main+ navigation_goal = self._compose_heal_goal(+ workflow_run_context=workflow_run_context,+ failing_line=failing_line,+ )workflow_system_prompt = (None@@ -4423,6 +4439,117 @@ async def wrapper({default_args}):skip_reason=self._secure_skip_reason_for_error_code(failure.error_code),)+ @staticmethod+ def _workflow_definition_hash(workflow_definition: Any) -> str:+ if hasattr(workflow_definition, "model_dump"):+ payload = workflow_definition.model_dump(mode="json")+ else:+ payload = workflow_definition+ normalized = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str)+ return hashlib.sha256(normalized.encode("utf-8")).hexdigest()++ async def _self_heal_mutation_guard_snapshot(+ self,+ *,+ workflow_permanent_id: str,+ organization_id: str,+ ) -> tuple[int, str]:+ workflow = await app.DATABASE.workflows.get_workflow_by_permanent_id(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ )+ if workflow is None:+ raise RuntimeError("workflow_not_found_for_self_heal_guard")+ versions = await app.DATABASE.workflows.get_workflow_versions_by_permanent_id(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ )+ return len(versions), self._workflow_definition_hash(workflow.workflow_definition)++ @staticmethod+ def _output_obligation_for_heal_result(result: BlockResult | None) -> OutputObligation:+ if result is None or not result.success:+ return OutputObligation.none+ if result.output_parameter_value is not None:+ return OutputObligation.observed+ return OutputObligation.vestigial++ @staticmethod+ def _heal_parameter_binding_keys(workflow_run_context: WorkflowRunContext) -> list[str]:+ # Episode metadata is best-effort; it must never fail the heal path.+ try:+ return sorted(str(key) for key in workflow_run_context.parameters.keys())+ except Exception:+ return []++ async def _write_heal_episode_safe(+ self,+ *,+ organization_id: str,+ workflow_permanent_id: str,+ workflow_id: str,+ workflow_run_id: str,+ workflow_run_block_id: str,+ block_label: str,+ engine: str,+ status: Literal["fired_completed", "fired_failed", "fired_unverified", "skipped"],+ skip_reason: HealSkipReason | None,+ parameter_binding_keys: list[str],+ exception_class: str | None,+ failing_line: int | None,+ matched_step_index: int | None,+ failure_message: str | None,+ wall_clock_ms: int | None,+ action_count: int | None,+ output_obligation: OutputObligation,+ ) -> None:+ LOG.info(+ "self-heal episode",+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=block_label,+ engine=engine,+ status=status,+ skip_reason=skip_reason.value if skip_reason is not None else None,+ origin=TurnOrigin.runtime_self_heal.value,+ )+ try:+ await app.DATABASE.self_heal.create_heal_episode(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=block_label,+ engine=engine,+ status=HealStatus(status),+ skip_reason=skip_reason,+ snapshot_available=False,+ parameter_binding_keys=parameter_binding_keys,+ exception_class=exception_class,+ failing_line=failing_line,+ matched_step_index=matched_step_index,+ failure_message=failure_message,+ wall_clock_ms=wall_clock_ms,+ action_count=action_count,+ output_obligation=output_obligation,+ )+ except Exception:+ LOG.warning(+ "self-heal episode persistence failed; continuing",+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=block_label,+ engine=engine,+ status=status,+ exc_info=True,+ )+async def _resolve_failure_with_heal(self,*,@@ -4439,13 +4566,60 @@ async def wrapper({default_args}):browser_state: BrowserState | None = None,page: Page | None = None,) -> BlockResult:- healed: BlockResult | None = None- if classification.healable:- live_browser_state = browser_state or app.BROWSER_MANAGER.get_for_workflow_run(- workflow_run_id=workflow_run_id+ async def _finalize_heal_result(result: BlockResult | None) -> BlockResult:+ if result is not None:+ output_obligation = self._output_obligation_for_heal_result(result)+ # Record output before finalizing so a failed write fails closed, never leaving a+ # completed block without the output downstream consumers require.+ if output_obligation in {OutputObligation.observed, OutputObligation.vestigial}:+ await self.record_output_parameter_value(+ workflow_run_context,+ workflow_run_id,+ result.output_parameter_value,+ )+ await recorder.finalize(success=result.success)+ return result+ await recorder.finalize(success=False)+ return await build_failure_result()++ if not classification.healable:+ return await _finalize_heal_result(None)+ if not await self._self_heal_enabled(workflow_run_context):+ return await _finalize_heal_result(None)+ if not organization_id:+ return await _finalize_heal_result(None)++ workflow_permanent_id = workflow_run_context.workflow_permanent_id+ workflow_id = workflow_run_context.workflow_id+ exception_for_heal = exception or RuntimeError("CodeBlock failed")+ exception_class = type(exception_for_heal).__name__+ matched_step_index = self._matched_step_index_for_failing_line(failing_line)+ parameter_binding_keys = self._heal_parameter_binding_keys(workflow_run_context)+ live_browser_state = browser_state or app.BROWSER_MANAGER.get_for_workflow_run(workflow_run_id=workflow_run_id)++ async def _record_harness_skip(skip_reason: HealSkipReason, failure_message: str | None = None) -> None:+ await self._write_heal_episode_safe(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=self.label,+ engine="harness",+ status="skipped",+ skip_reason=skip_reason,+ parameter_binding_keys=parameter_binding_keys,+ exception_class=exception_class,+ failing_line=failing_line,+ matched_step_index=matched_step_index,+ failure_message=failure_message,+ wall_clock_ms=None,+ action_count=None,+ output_obligation=OutputObligation.none,)- exception_for_heal = exception or RuntimeError("CodeBlock failed")- healed = await self._attempt_self_heal(++ async def _run_floor_recovery() -> BlockResult | None:+ floor_result = await self._attempt_self_heal(exception=exception_for_heal,failing_line=failing_line,recording_page=recorder.recording_page,@@ -4459,26 +4633,252 @@ async def wrapper({default_args}):page=page,record_output_parameter=False,)- if healed is not None:- output_obligation = OutputObligation.none- if healed.success:- output_obligation = (- OutputObligation.observed- if healed.output_parameter_value is not None- else OutputObligation.vestigial- )- # Record output before finalizing so a failed write fails closed, never leaving a- # completed block without the output downstream consumers require.- if output_obligation in {OutputObligation.observed, OutputObligation.vestigial}:- await self.record_output_parameter_value(- workflow_run_context,- workflow_run_id,- healed.output_parameter_value,+ floor_output_obligation = self._output_obligation_for_heal_result(floor_result)+ await self._write_heal_episode_safe(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=self.label,+ engine="floor",+ status="fired_completed" if floor_result is not None and floor_result.success else "fired_failed",+ skip_reason=None,+ parameter_binding_keys=parameter_binding_keys,+ exception_class=exception_class,+ failing_line=failing_line,+ matched_step_index=matched_step_index,+ failure_message=floor_result.failure_reason if floor_result is not None else "floor_no_result",+ wall_clock_ms=None,+ action_count=None,+ output_obligation=floor_output_obligation,+ )+ return floor_result++ api_key = await app.AGENT_FUNCTION.resolve_self_heal_api_key(organization_id)+ if not api_key:+ await _record_harness_skip(+ HealSkipReason.credential_unavailable, failure_message="self_heal_api_key_missing"+ )+ return await _finalize_heal_result(await _run_floor_recovery())++ browser_context = (+ getattr(live_browser_state, "browser_context", None) if live_browser_state is not None else None+ )+ if live_browser_state is None or not _browser_context_is_attachable(browser_context):+ await _record_harness_skip(HealSkipReason.adoption_failed, failure_message="self_heal_browser_unavailable")+ return await _finalize_heal_result(await _run_floor_recovery())+ # Reserve cap only once harness preconditions are satisfied so transient infra skips+ # do not consume slots; cap limits harness attempts, not floor fallback attempts.+ cap_reserved = await check_and_increment_self_heal_cap(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ )+ if cap_reserved is None:+ await _record_harness_skip(HealSkipReason.capped, failure_message="self_heal_daily_cap_exceeded")+ return await _finalize_heal_result(await _run_floor_recovery())++ recovery: SelfHealRecoveryResult | None = None+ try:+ before_snapshot = await self._self_heal_mutation_guard_snapshot(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ )+ recovery = await run_self_heal_recovery(+ block=self,+ workflow_run_context=workflow_run_context,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ browser_state=live_browser_state,+ failing_line=failing_line,+ api_key=api_key,+ max_actions=settings.SELF_HEAL_MAX_ACTIONS,+ wall_clock_budget_seconds=settings.SELF_HEAL_WALL_CLOCK_BUDGET_SECONDS,+ )+ after_snapshot = await self._self_heal_mutation_guard_snapshot(+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ )+ if before_snapshot != after_snapshot:+ raise RuntimeError("workflow_mutated_during_runtime_self_heal")++ if recovery.success:+ # Compute the obligation from a non-persisted result: an unverified or+ # fail-closed outcome must never leave the block row marked completed, so the+ # block row is written only on the verified path below.+ harness_result = await self.build_block_result(+ success=True,+ failure_reason=None,+ output_parameter_value=None,+ status=BlockStatus.completed,+ workflow_run_block_id=None,+ organization_id=organization_id,+ )+ harness_output_obligation = self._output_obligation_for_heal_result(harness_result)+ if not recovery.verified:+ await self._write_heal_episode_safe(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=self.label,+ engine="harness",+ status="fired_unverified",+ skip_reason=None,+ parameter_binding_keys=parameter_binding_keys,+ exception_class=exception_class,+ failing_line=failing_line,+ matched_step_index=matched_step_index,+ failure_message=recovery.failure_note,+ wall_clock_ms=recovery.wall_clock_ms,+ action_count=recovery.action_count,+ output_obligation=harness_output_obligation,+ )+ # Fail closed when an unverified harness run already mutated controls:+ # rerunning floor could duplicate side effects (submit/send/delete).+ if recovery.performed_mutation:+ LOG.info(+ "Runtime self-heal unverified after mutating actions; suppressing floor fallback",+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ block_label=self.label,+ origin=TurnOrigin.runtime_self_heal.value,+ )+ return await _finalize_heal_result(None)+ return await _finalize_heal_result(await _run_floor_recovery())+ # Verified: only now write status=completed to the block row.+ harness_result = await self.build_block_result(+ success=True,+ failure_reason=None,+ output_parameter_value=None,+ status=BlockStatus.completed,+ workflow_run_block_id=workflow_run_block_id,+ organization_id=organization_id,+ )+ await self._write_heal_episode_safe(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=self.label,+ engine="harness",+ status="fired_completed",+ skip_reason=None,+ parameter_binding_keys=parameter_binding_keys,+ exception_class=exception_class,+ failing_line=failing_line,+ matched_step_index=matched_step_index,+ failure_message=None,+ wall_clock_ms=recovery.wall_clock_ms,+ action_count=recovery.action_count,+ output_obligation=harness_output_obligation,+ )+ return await _finalize_heal_result(harness_result)++ await self._write_heal_episode_safe(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=self.label,+ engine="harness",+ status="fired_failed",+ skip_reason=None,+ parameter_binding_keys=parameter_binding_keys,+ exception_class=exception_class,+ failing_line=failing_line,+ matched_step_index=matched_step_index,+ failure_message=recovery.failure_note,+ wall_clock_ms=recovery.wall_clock_ms,+ action_count=recovery.action_count,+ output_obligation=OutputObligation.none,+ )+ # A failed harness turn that already mutated controls must not hand off to floor:+ # rerunning could duplicate the side effect (submit/send/delete).+ if recovery.performed_mutation:+ LOG.info(+ "Runtime self-heal failed after mutating actions; suppressing floor fallback",+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ block_label=self.label,+ origin=TurnOrigin.runtime_self_heal.value,+ )+ return await _finalize_heal_result(None)+ return await _finalize_heal_result(await _run_floor_recovery())+ except HealAdoptionFailed as exc:+ await self._write_heal_episode_safe(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=self.label,+ engine="harness",+ status="fired_failed",+ skip_reason=None,+ parameter_binding_keys=parameter_binding_keys,+ exception_class=exception_class,+ failing_line=failing_line,+ matched_step_index=matched_step_index,+ failure_message=str(exc),+ wall_clock_ms=None,+ action_count=None,+ output_obligation=OutputObligation.none,+ )+ return await _finalize_heal_result(await _run_floor_recovery())+ except Exception as exc:+ LOG.error(+ "Runtime self-heal harness recovery failed",+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ block_label=self.label,+ origin=TurnOrigin.runtime_self_heal.value,+ error_type=type(exc).__name__,+ exc_info=True,+ )+ await self._write_heal_episode_safe(+ organization_id=organization_id,+ workflow_permanent_id=workflow_permanent_id,+ workflow_id=workflow_id,+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ block_label=self.label,+ engine="harness",+ status="fired_failed",+ skip_reason=None,+ parameter_binding_keys=parameter_binding_keys,+ exception_class=exception_class,+ failing_line=failing_line,+ matched_step_index=matched_step_index,+ failure_message=type(exc).__name__,+ wall_clock_ms=None,+ action_count=None,+ output_obligation=OutputObligation.none,+ )+ # If the harness already mutated a control before the error (e.g. the workflow-mutation+ # guard tripped after a click), a floor rerun could duplicate the side effect.+ if recovery is not None and recovery.performed_mutation:+ LOG.info(+ "Runtime self-heal errored after mutating actions; suppressing floor fallback",+ workflow_run_id=workflow_run_id,+ workflow_run_block_id=workflow_run_block_id,+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ block_label=self.label,+ origin=TurnOrigin.runtime_self_heal.value,)- await recorder.finalize(success=healed.success)- return healed- await recorder.finalize(success=False)- return await build_failure_result()+ return await _finalize_heal_result(None)+ return await _finalize_heal_result(await _run_floor_recovery())async def execute(self,diff --git a/skyvern/schemas/self_heal.py b/skyvern/schemas/self_heal.pyindex da81758a5..77bc95039 100644--- a/skyvern/schemas/self_heal.py+++ b/skyvern/schemas/self_heal.py@@ -152,10 +152,10 @@ def resolve_block_outcome(statuses = {episode.status for episode in episodes}if HealStatus.fired_completed in statuses:return "healed"- if HealStatus.fired_unverified in statuses:- return "unverified"if HealStatus.fired_failed in statuses:return "failed"+ if HealStatus.fired_unverified in statuses:+ return "unverified"if HealStatus.skipped in statuses:return "skipped"return "none"diff --git a/skyvern/services/self_heal_cap.py b/skyvern/services/self_heal_cap.pynew file mode 100644index 000000000..ba0fea9c0--- /dev/null+++ b/skyvern/services/self_heal_cap.py@@ -0,0 +1,70 @@+from __future__ import annotations++from datetime import UTC, datetime, timedelta++import structlog++from skyvern.config import settings+from skyvern.forge.sdk.cache.factory import CacheFactory++try:+ from redis.exceptions import LockError as _RedisLockError+except ImportError:++ class _RedisLockError(Exception): # type: ignore[no-redef]+ pass+++LOG = structlog.get_logger()++__all__ = ["check_and_increment_self_heal_cap", "self_heal_daily_cap_key"]+++def self_heal_daily_cap_key(workflow_permanent_id: str, organization_id: str | None = None) -> str:+ today = datetime.now(UTC).strftime("%Y-%m-%d")+ org_scope = organization_id or "global"+ return f"self_heal:daily_cap:{org_scope}:{workflow_permanent_id}:{today}"+++async def check_and_increment_self_heal_cap(+ *, workflow_permanent_id: str, organization_id: str | None = None+) -> int | None:+ try:+ cache = CacheFactory.get_cache()+ if cache is None:+ # Unconfigured cache (OSS/local) fails open — the heal toggle still gates; a configured+ # cache that errors fails closed below, preserving the atomic reservation in prod.+ LOG.warning(+ "self-heal cap cache is not configured; allowing heal uncapped",+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ )+ return 1+ cap = int(settings.SELF_HEAL_DAILY_CAP)+ cap_key = self_heal_daily_cap_key(workflow_permanent_id, organization_id)+ org_scope = organization_id or "global"+ lock = cache.get_lock(f"self_heal_cap:{org_scope}:{workflow_permanent_id}", blocking_timeout=2, timeout=5)+ async with lock:+ raw_count = await cache.get(cap_key)+ current = int(raw_count) if raw_count is not None else 0+ if current >= cap:+ return None+ new_count = current + 1+ await cache.set(cap_key, str(new_count), ex=timedelta(hours=48))+ return new_count+ except _RedisLockError:+ LOG.warning(+ "self-heal cap lock acquisition failed; failing closed",+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ exc_info=True,+ )+ return None+ except Exception:+ LOG.warning(+ "self-heal cap check_and_increment failed; failing closed",+ workflow_permanent_id=workflow_permanent_id,+ organization_id=organization_id,+ exc_info=True,+ )+ return Nonediff --git a/tests/unit/copilot/test_self_heal_recovery.py b/tests/unit/copilot/test_self_heal_recovery.pynew file mode 100644index 000000000..08ad50502--- /dev/null+++ b/tests/unit/copilot/test_self_heal_recovery.py@@ -0,0 +1,647 @@+from __future__ import annotations++import asyncio+import json+from types import SimpleNamespace+from typing import cast+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.forge.sdk.copilot import agent as agent_module+from skyvern.forge.sdk.copilot.config import CopilotConfig+from skyvern.forge.sdk.copilot.context import CopilotContext+from skyvern.forge.sdk.copilot.self_heal_recovery import run_self_heal_recovery+from skyvern.forge.sdk.copilot.tools import _authority_tool_error+from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentAuthority, TurnIntentMode+from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin+++class _FakeCodeBlock:+ def _compose_heal_goal(self, *, workflow_run_context: object, failing_line: int | None) -> str:+ del workflow_run_context, failing_line+ return "Recover the page state"+++def _fake_context() -> SimpleNamespace:+ return SimpleNamespace(+ workflow_id="wf_1",+ workflow_permanent_id="wpid_1",+ parameters={},+ )+++def _patch_recovery_common(+ monkeypatch: pytest.MonkeyPatch,+ *,+ verified: bool = True,+) -> None:+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.request_policy.build_request_policy",+ AsyncMock(+ return_value=SimpleNamespace(+ completion_criteria=["criterion"],+ graded_completion_criteria=lambda: ["criterion"],+ )+ ),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.outcome_fully_verified",+ lambda _ctx: verified,+ )+++async def test_seed_completion_criteria_false_when_no_gradeable_criteria(monkeypatch: pytest.MonkeyPatch) -> None:+ from skyvern.forge.sdk.copilot.self_heal_recovery import _seed_completion_criteria++ # A conservative generator can return a policy with zero gradeable criteria; seeding must+ # report that as unseeded (verification can't pass) rather than a successful seed.+ async def _seed(criteria: list) -> bool:+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.request_policy.build_request_policy",+ AsyncMock(return_value=SimpleNamespace(graded_completion_criteria=lambda: criteria)),+ )+ return await _seed_completion_criteria(+ SimpleNamespace(request_policy=None),+ composed_goal="recover the page",+ organization_id="o_1",+ llm_handler=None,+ copilot_config=None,+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ )++ assert await _seed([]) is False+ assert await _seed(["c0"]) is True+++async def test_recovery_uses_browser_only_surface_and_no_native_tools(monkeypatch: pytest.MonkeyPatch) -> None:+ captured: dict[str, object] = {}+ _patch_recovery_common(monkeypatch, verified=True)++ async def _fake_loop(**kwargs: object) -> object:+ captured.update(kwargs)+ ctx = kwargs["ctx"]+ assert hasattr(ctx, "scout_trajectory")+ ctx.scout_trajectory.append({"tool_name": "click", "selector": "#ok"})+ return object()++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _fake_loop)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.output_utils.extract_final_text",+ lambda _result: '{"type":"REPLY"}',+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=object(),+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=10,+ )++ assert result.success is True+ assert result.verified is True+ assert captured["native_tools"] == []+ alias_map = cast(dict[str, str], captured["alias_map"])+ assert set(alias_map) == {+ "navigate_browser",+ "get_browser_screenshot",+ "evaluate",+ "click",+ "type_text",+ "scroll",+ "console_messages",+ "select_option",+ "press_key",+ }+ assert "get_block_schema" not in alias_map+++async def test_recovery_passes_non_empty_output_guardrails(monkeypatch: pytest.MonkeyPatch) -> None:+ captured: dict[str, object] = {}+ _patch_recovery_common(monkeypatch, verified=True)++ async def _fake_loop(**kwargs: object) -> object:+ captured.update(kwargs)+ ctx = kwargs["ctx"]+ assert hasattr(ctx, "scout_trajectory")+ ctx.scout_trajectory.append({"tool_name": "click", "selector": "#ok"})+ return object()++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _fake_loop)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.output_utils.extract_final_text",+ lambda _result: '{"type":"REPLY"}',+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=object(),+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=10,+ )++ assert result.success is True+ assert result.verified is True+ output_guardrails = captured["output_guardrails"]+ assert isinstance(output_guardrails, list)+ assert len(output_guardrails) == 1+ assert output_guardrails[0].name == "self_heal_output_guardrail"+++async def test_recovery_fails_closed_on_ask_question(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_recovery_common(monkeypatch, verified=True)++ async def _fake_loop(**kwargs: object) -> object:+ ctx = kwargs["ctx"]+ assert hasattr(ctx, "scout_trajectory")+ ctx.scout_trajectory.append({"tool_name": "click", "selector": "#ok"})+ return object()++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _fake_loop)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.output_utils.extract_final_text",+ lambda _result: '{"type":"ASK_QUESTION","user_response":"What should I do?"}',+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=object(),+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=10,+ )++ assert result.success is False+ assert result.failure_note == "asked_user_question"+++async def test_recovery_replace_workflow_terminal_has_distinct_failure_note(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_recovery_common(monkeypatch, verified=True)++ async def _fake_loop(**kwargs: object) -> object:+ ctx = kwargs["ctx"]+ ctx.scout_trajectory.append({"tool_name": "click", "selector": "#ok"})+ return object()++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _fake_loop)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.output_utils.extract_final_text",+ lambda _result: '{"type":"REPLACE_WORKFLOW","workflow_yaml":"blocks: []"}',+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=object(),+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=10,+ )++ assert result.success is False+ assert result.failure_note == "proposed_workflow_mutation"+++async def test_recovery_unparseable_terminal_has_distinct_failure_note(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_recovery_common(monkeypatch, verified=True)++ async def _fake_loop(**kwargs: object) -> object:+ ctx = kwargs["ctx"]+ ctx.scout_trajectory.append({"tool_name": "click", "selector": "#ok"})+ return object()++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _fake_loop)+ monkeypatch.setattr("skyvern.forge.sdk.copilot.output_utils.extract_final_text", lambda _result: "nonsense")+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=object(),+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=10,+ )++ assert result.success is False+ assert result.failure_note == "unparseable_terminal"+++async def test_recovery_marks_terminal_reply_unverified_when_judge_not_satisfied(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_recovery_common(monkeypatch, verified=False)++ async def _fake_loop(**kwargs: object) -> object:+ ctx = kwargs["ctx"]+ ctx.scout_trajectory.append({"tool_name": "click", "selector": "#ok"})+ return object()++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _fake_loop)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.output_utils.extract_final_text",+ lambda _result: '{"type":"REPLY","user_response":"done"}',+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=object(),+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=10,+ )++ assert result.success is True+ assert result.verified is False+ assert result.failure_note == "goal_unverified"+++async def test_recovery_navigation_only_counts_as_progress(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_recovery_common(monkeypatch, verified=True)++ async def _fake_loop(**kwargs: object) -> object:+ ctx = kwargs["ctx"]+ ctx.tool_activity.append({"tool": "navigate_browser", "summary": "Navigated to http://example.test"})+ return object()++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _fake_loop)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.output_utils.extract_final_text",+ lambda _result: '{"type":"REPLY","user_response":"done"}',+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=object(),+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=10,+ )++ assert result.success is True+ assert result.verified is True+ assert result.action_count == 1+++def test_evaluate_tool_counts_as_self_heal_mutation() -> None:+ from skyvern.forge.sdk.copilot.self_heal_recovery import _performed_mutation_during_self_heal++ # evaluate runs arbitrary JS, so a successful evaluate must count as a mutation for the+ # fail-closed floor-suppression guard; read-only tools and failed calls must not.+ assert _performed_mutation_during_self_heal(+ SimpleNamespace(tool_activity=[{"tool": "evaluate", "summary": "Ran document.forms[0].submit()"}])+ )+ assert not _performed_mutation_during_self_heal(+ SimpleNamespace(tool_activity=[{"tool": "get_browser_screenshot", "summary": "Screenshot taken"}])+ )+ assert not _performed_mutation_during_self_heal(+ SimpleNamespace(tool_activity=[{"tool": "evaluate", "summary": "Failed: page.evaluate timed out"}])+ )+++async def test_recovery_runs_post_loop_verification_from_browser_state_without_evaluate_tool(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _patch_recovery_common(monkeypatch, verified=True)+ completion_verify_mock = AsyncMock(return_value=None)+ record_observation_mock = MagicMock(return_value=7)++ async def _fake_loop(**kwargs: object) -> object:+ ctx = kwargs["ctx"]+ ctx.tool_activity.extend(+ [+ {"tool": "click", "summary": "Clicked #next"},+ {"tool": "type_text", "summary": "Typed into #email"},+ ]+ )+ return object()++ page = SimpleNamespace(+ url="https://example.test/dashboard",+ evaluate=AsyncMock(return_value="<main>done</main>"),+ title=AsyncMock(return_value="Dashboard"),+ )+ browser_state = SimpleNamespace(get_or_create_page=AsyncMock(return_value=page))++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _fake_loop)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.output_utils.extract_final_text",+ lambda _result: '{"type":"REPLY","user_response":"done"}',+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools.page_observation._record_composition_page_observation",+ record_observation_mock,+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools.completion._maybe_run_completion_verification_from_page_observation",+ completion_verify_mock,+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=browser_state,+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=10,+ )++ assert result.success is True+ assert result.verified is True+ assert result.performed_mutation is True+ record_observation_mock.assert_called_once()+ completion_verify_mock.assert_awaited_once()+ assert completion_verify_mock.await_args.kwargs["observed_data"] == {+ "html": "<main>done</main>",+ "url": "https://example.test/dashboard",+ "title": "Dashboard",+ }+++async def test_recovery_fails_closed_on_wall_clock_budget(monkeypatch: pytest.MonkeyPatch) -> None:+ _patch_recovery_common(monkeypatch, verified=True)++ async def _slow_loop(**kwargs: object) -> object:+ await asyncio.sleep(0.05)+ return object()++ monkeypatch.setattr("skyvern.forge.sdk.copilot.agent._run_agent_loop_with_surface", _slow_loop)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.llm_config.resolve_main_copilot_handler",+ AsyncMock(return_value=None),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda *args, **kwargs: ("gpt-test", object(), "llm_key", True),+ )+ monkeypatch.setattr("skyvern.forge.sdk.copilot.self_heal_recovery.app", SimpleNamespace(AGENT_FUNCTION=MagicMock()))+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.self_heal_recovery.app.AGENT_FUNCTION.get_copilot_config",+ lambda: CopilotConfig(),+ )++ result = await run_self_heal_recovery(+ block=_FakeCodeBlock(),+ workflow_run_context=_fake_context(),+ workflow_run_id="wr_1",+ workflow_run_block_id="wrb_1",+ organization_id="org_1",+ browser_state=object(),+ failing_line=8,+ api_key="sk-test",+ max_actions=15,+ wall_clock_budget_seconds=0,+ )++ assert result.success is False+ assert result.verified is False+ assert result.failure_note == "wall_clock_budget_exhausted"+++def test_runtime_self_heal_guardrail_rejects_native_tool_call() -> None:+ ctx = CopilotContext(+ organization_id="org_1",+ workflow_id="wf_1",+ workflow_permanent_id="wpid_1",+ workflow_yaml="",+ browser_session_id=None,+ stream=SimpleNamespace(), # type: ignore[arg-type]+ turn_origin=TurnOrigin.runtime_self_heal,+ turn_intent=TurnIntent(+ mode=TurnIntentMode.BUILD,+ authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),+ ),+ )++ payload = _authority_tool_error(ctx, "update_workflow")++ assert payload is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "runtime_self_heal_native_tool_blocked"+++async def test_runtime_self_heal_inline_replace_is_downgraded(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ agent_module,+ "extract_final_text",+ lambda _result: json.dumps({"type": "REPLACE_WORKFLOW", "user_response": "replace", "workflow_yaml": "x"}),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools._process_workflow_yaml",+ AsyncMock(side_effect=AssertionError("inline replace must not process workflow in runtime self-heal")),+ )+ ctx = CopilotContext(+ organization_id="org_1",+ workflow_id="wf_1",+ workflow_permanent_id="wpid_1",+ workflow_yaml="",+ browser_session_id=None,+ stream=SimpleNamespace(), # type: ignore[arg-type]+ turn_origin=TurnOrigin.runtime_self_heal,+ )+ chat_request = SimpleNamespace(workflow_id="wf_1", workflow_permanent_id="wpid_1", workflow_yaml="")++ agent_result = await agent_module._translate_to_agent_result(+ object(),+ ctx,+ global_llm_context=None,+ chat_request=chat_request,+ organization_id="org_1",+ )++ assert agent_result.response_type == "REPLY"+ assert "runtime self-heal" in agent_result.user_response.lower()+++def test_build_copilot_output_guardrails_returns_real_output_guardrail_instances() -> None:+ from agents import GuardrailFunctionOutput, OutputGuardrail++ guardrails = agent_module._build_copilot_output_guardrails(OutputGuardrail, GuardrailFunctionOutput)++ assert isinstance(guardrails, list)+ assert len(guardrails) > 0+ assert all(isinstance(guardrail, OutputGuardrail) for guardrail in guardrails)+++ ("final_text", "expected_tripwire"),+ [+ pytest.param('{"type":"REPLY","user_response":"done"}', False, id="reply_passes"),+ pytest.param(+ '{"type":"REPLACE_WORKFLOW","workflow_yaml":"blocks: []","user_response":"updated"}',+ True,+ id="replace_workflow_trips",+ ),+ pytest.param('{"type":"ASK_QUESTION","user_response":"Need input?"}', True, id="ask_question_trips"),+ pytest.param("garbage output with no marker", False, id="garbage_without_replace_marker_passes"),+ pytest.param("garbage REPLACE_WORKFLOW marker only", True, id="garbage_with_replace_marker_trips"),+ ],+)+async def test_self_heal_output_guardrail_runtime_verdicts(final_text: str, expected_tripwire: bool) -> None:+ from agents import GuardrailFunctionOutput, OutputGuardrail+ from agents.run_context import RunContextWrapper++ guardrails = agent_module._build_self_heal_output_guardrails(OutputGuardrail, GuardrailFunctionOutput)+ fake_result = SimpleNamespace(final_output=final_text, new_items=[])+ result = await guardrails[0].run(+ RunContextWrapper(context=SimpleNamespace()),+ SimpleNamespace(),+ fake_result,+ )++ assert result.output.tripwire_triggered is expected_tripwirediff --git a/tests/unit/copilot/test_turn_origin_seam.py b/tests/unit/copilot/test_turn_origin_seam.pyindex 9de51dc0d..290916342 100644--- a/tests/unit/copilot/test_turn_origin_seam.py+++ b/tests/unit/copilot/test_turn_origin_seam.py@@ -4,8 +4,14 @@ from types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMockimport pytest+from structlog.testing import capture_logs-from skyvern.forge.sdk.copilot.runtime import AgentContext, ensure_browser_session, mcp_browser_context+from skyvern.forge.sdk.copilot.runtime import (+ AgentContext,+ ensure_browser_session,+ mcp_browser_context,+ resolve_browser_state_for_context,+)from skyvern.forge.sdk.copilot.turn_origin import (HealAdoptionFailed,TurnOrigin,@@ -146,11 +152,19 @@ async def test_self_heal_injected_state_assigns_synthetic_session_and_mcp_registassert result is Noneassert ctx.browser_session_id == expected_session_id- async with mcp_browser_context(ctx):- assert register_mock.call_args.args[0] == expected_session_id+ with capture_logs() as logs:+ async with mcp_browser_context(ctx):+ assert register_mock.call_args.args[0] == expected_session_idunregister_mock.assert_called_once_with(expected_session_id)manager.get_browser_state.assert_not_awaited()+ registered = [entry for entry in logs if entry["event"] == "registered self-heal browser session"]+ unregistered = [entry for entry in logs if entry["event"] == "unregistered self-heal browser session"]+ assert len(registered) == 1+ assert registered[0]["session_id"] == expected_session_id+ assert registered[0]["organization_id"] == "org_1"+ assert len(unregistered) == 1+ assert unregistered[0]["session_id"] == expected_session_id@pytest.mark.asyncio@@ -243,3 +257,39 @@ async def test_ensure_browser_session_interactive_still_auto_creates(monkeypatchassert result is Noneassert ctx.browser_session_id == "pbs_new"manager.create_session.assert_awaited_once()+++ ("origin", "session_id"),+ [+ pytest.param(TurnOrigin.runtime_self_heal, "selfheal:wr_123", id="runtime_self_heal_origin"),+ pytest.param(TurnOrigin.interactive, "selfheal:wr_123", id="selfheal_prefix_session"),+ ],+)+async def test_resolve_browser_state_for_context_skips_persistent_lookup_for_self_heal_paths(+ monkeypatch: pytest.MonkeyPatch,+ origin: TurnOrigin,+ session_id: str | None,+) -> None:+ import skyvern.forge.sdk.copilot.runtime as runtime++ fake_browser_state = SimpleNamespace(+ browser_context=_FakeBrowserContext(),+ get_working_page=AsyncMock(return_value=MagicMock()),+ )+ persistent_lookup = AsyncMock(side_effect=AssertionError("persistent lookup must not run for self-heal paths"))+ manager = SimpleNamespace(get_browser_state=persistent_lookup)+ monkeypatch.setattr(runtime, "app", SimpleNamespace(PERSISTENT_SESSIONS_MANAGER=manager))++ ctx = _make_ctx(+ turn_origin=origin,+ injected_browser_state=fake_browser_state,+ heal_workflow_run_id="wr_123",+ browser_session_id=session_id,+ )++ resolved = await resolve_browser_state_for_context(ctx, session_id=session_id)++ assert resolved is fake_browser_state+ persistent_lookup.assert_not_awaited()diff --git a/tests/unit/forge/sdk/db/test_self_heal_schema.py b/tests/unit/forge/sdk/db/test_self_heal_schema.pyindex 220d63ac7..022ca3d8b 100644--- a/tests/unit/forge/sdk/db/test_self_heal_schema.py+++ b/tests/unit/forge/sdk/db/test_self_heal_schema.py@@ -122,6 +122,8 @@ def _episode_for_run(("episodes", "expected"),[([HealStatus.fired_completed, HealStatus.fired_failed], "healed"),+ ([HealStatus.fired_unverified, HealStatus.fired_failed], "failed"),+ ([HealStatus.fired_unverified], "unverified"),([HealStatus.fired_unverified, HealStatus.skipped], "unverified"),([HealStatus.fired_failed, HealStatus.skipped], "failed"),([HealStatus.skipped], "skipped"),diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 87710324b..b76321a4b 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -105,6 +105,7 @@ from skyvern.forge.sdk.copilot.turn_intent import (TurnIntentMode,TurnIntentReasonCode,)+from skyvern.forge.sdk.copilot.turn_origin import TurnOriginfrom skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidencefrom skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcomefrom skyvern.forge.sdk.schemas.workflow_copilot import (@@ -2662,6 +2663,30 @@ class TestTranslateToAgentResultGating:assert agent_result.updated_workflow is Noneassert "confirm and i'll apply" in agent_result.user_response.lower()+ def test_inline_replace_workflow_suppressed_on_runtime_self_heal_turn(self, monkeypatch) -> None:+ def _must_not_process(**kwargs):+ raise AssertionError("inline REPLACE_WORKFLOW was processed on runtime self-heal")++ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._process_workflow_yaml", _must_not_process)+ ctx = _ctx(turn_origin=TurnOrigin.runtime_self_heal)+ result = _fake_run_result(+ {+ "type": "REPLACE_WORKFLOW",+ "user_response": "here is a replacement",+ "workflow_yaml": "new: yaml",+ }+ )+ agent_result = asyncio.run(+ agent_module._translate_to_agent_result(+ result, ctx, global_llm_context=None, chat_request=_chat_request(), organization_id="org-1"+ )+ )++ assert agent_result.response_type == "REPLY"+ assert ctx.last_workflow is None+ assert agent_result.updated_workflow is None+ assert "runtime self-heal" in agent_result.user_response.lower()+def test_inline_replace_workflow_rejects_stale_block_metadata(self, monkeypatch) -> None:# Inline REPLACE_WORKFLOW bypasses _update_workflow, so it must also# reject a corrected workflow whose labels/titles still describe thediff --git a/tests/unit/test_copilot_discovery.py b/tests/unit/test_copilot_discovery.pyindex e921c9dd9..d9270d8ad 100644--- a/tests/unit/test_copilot_discovery.py+++ b/tests/unit/test_copilot_discovery.py@@ -15,11 +15,13 @@ from skyvern.forge.sdk.copilot.tools import (_resolve_discovery_entry_url,discovery,)+from skyvern.forge.sdk.copilot.turn_origin import TurnOriginfrom skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidenceclass _Ctx:def __init__(self, server: object) -> None:+ self.turn_origin = TurnOrigin.interactiveself.discovery_mcp_server = serverself.discovery_started_monotonic = Noneself.discovery_step_count = 0diff --git a/tests/unit/test_copilot_turn_intent_tool_gate.py b/tests/unit/test_copilot_turn_intent_tool_gate.pyindex 9e760eca2..bb8dc3ff7 100644--- a/tests/unit/test_copilot_turn_intent_tool_gate.py+++ b/tests/unit/test_copilot_turn_intent_tool_gate.py@@ -24,6 +24,7 @@ from skyvern.forge.sdk.copilot.turn_intent import (TurnIntentAuthority,TurnIntentMode,)+from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin# Tokens that must never appear in any LLM-visible string emitted by an# authority gate. The previous prose path leaked all of these.@@ -484,6 +485,22 @@ def test_get_run_results_routes_through_authority_dispatcher_but_request_policy_assert ctx.blocker_signal is None+def test_runtime_self_heal_origin_blocks_native_tool_calls() -> None:+ intent = TurnIntent(+ mode=TurnIntentMode.BUILD,+ authority=TurnIntentAuthority(may_update_workflow=False, may_run_blocks=False),+ )+ ctx = _ctx(intent)+ ctx.turn_origin = TurnOrigin.runtime_self_heal++ payload = _authority_tool_error(ctx, "update_workflow")++ assert payload is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "runtime_self_heal_native_tool_blocked"+ assert ctx.blocker_signal.blocker_kind == "tool_error"++@pytest.mark.parametrize("mode",[diff --git a/tests/unit/test_copilot_watchdog.py b/tests/unit/test_copilot_watchdog.pyindex 8d0eabe02..cd44acde9 100644--- a/tests/unit/test_copilot_watchdog.py+++ b/tests/unit/test_copilot_watchdog.py@@ -44,6 +44,7 @@ from skyvern.forge.sdk.copilot.tools import (_tool_loop_error,_watchdog_error_message,)+from skyvern.forge.sdk.copilot.turn_origin import TurnOrigindef _fake_run(status: str = "running", modified_at: datetime | None = None) -> Any:@@ -259,7 +260,9 @@ async def test_fallback_page_info_uses_persistent_session_state_without_sdk_recosession_manager = SimpleNamespace(get_browser_state=AsyncMock(return_value=browser_state))monkeypatch.setattr(forge_app, "PERSISTENT_SESSIONS_MANAGER", session_manager)- ctx = SimpleNamespace(organization_id="o_test", browser_session_id="pbs_copilot")+ ctx = SimpleNamespace(+ organization_id="o_test", browser_session_id="pbs_copilot", turn_origin=TurnOrigin.interactive+ )current_url, page_title = await _fallback_page_info(ctx)diff --git a/tests/unit/test_self_heal_cap.py b/tests/unit/test_self_heal_cap.pynew file mode 100644index 000000000..13a995754--- /dev/null+++ b/tests/unit/test_self_heal_cap.py@@ -0,0 +1,86 @@+from __future__ import annotations++from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, MagicMock++import pytest++from skyvern.forge.sdk.cache.factory import CacheFactory+from skyvern.services import self_heal_cap+++class TestSelfHealCap:+ @pytest.fixture(autouse=True)+ def setup(self) -> Iterator[None]:+ self.mock_cache = AsyncMock()+ self._original_cache = CacheFactory.get_cache()+ CacheFactory.set_cache(self.mock_cache)+ yield+ CacheFactory.set_cache(self._original_cache)++ def test_self_heal_daily_cap_key_scopes_org_wpid_and_utc_day(self) -> None:+ today = datetime.now(UTC).strftime("%Y-%m-%d")+ assert (+ self_heal_cap.self_heal_daily_cap_key("wpid_abc", "org_1") == f"self_heal:daily_cap:org_1:wpid_abc:{today}"+ )+ assert self_heal_cap.self_heal_daily_cap_key("wpid_abc") == f"self_heal:daily_cap:global:wpid_abc:{today}"++ @pytest.mark.asyncio+ async def test_check_and_increment_self_heal_cap_acquires_slot_under_cap(self) -> None:+ self.mock_cache.get = AsyncMock(return_value="4")+ mock_lock = AsyncMock()+ mock_lock.__aenter__ = AsyncMock(return_value=mock_lock)+ mock_lock.__aexit__ = AsyncMock(return_value=False)+ self.mock_cache.get_lock = MagicMock(return_value=mock_lock)++ result = await self_heal_cap.check_and_increment_self_heal_cap(+ workflow_permanent_id="wpid_abc",+ organization_id="org_1",+ )++ assert result == 5+ self.mock_cache.get_lock.assert_called_once_with("self_heal_cap:org_1:wpid_abc", blocking_timeout=2, timeout=5)+ self.mock_cache.set.assert_awaited_once()+ args, kwargs = self.mock_cache.set.call_args+ assert "self_heal:daily_cap:org_1:wpid_abc" in args[0]+ assert args[1] == "5"+ assert kwargs.get("ex") == timedelta(hours=48)++ @pytest.mark.asyncio+ async def test_check_and_increment_self_heal_cap_returns_none_at_cap(self, monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr("skyvern.config.settings.SELF_HEAL_DAILY_CAP", 5, raising=False)+ self.mock_cache.get = AsyncMock(return_value="5")+ mock_lock = AsyncMock()+ mock_lock.__aenter__ = AsyncMock(return_value=mock_lock)+ mock_lock.__aexit__ = AsyncMock(return_value=False)+ self.mock_cache.get_lock = MagicMock(return_value=mock_lock)++ result = await self_heal_cap.check_and_increment_self_heal_cap(workflow_permanent_id="wpid_abc")++ assert result is None+ self.mock_cache.set.assert_not_called()++ @pytest.mark.asyncio+ async def test_check_and_increment_self_heal_cap_lock_error_fails_closed(self) -> None:+ mock_lock = AsyncMock()+ mock_lock.__aenter__ = AsyncMock(side_effect=self_heal_cap._RedisLockError("busy"))+ mock_lock.__aexit__ = AsyncMock(return_value=False)+ self.mock_cache.get_lock = MagicMock(return_value=mock_lock)++ result = await self_heal_cap.check_and_increment_self_heal_cap(+ workflow_permanent_id="wpid_abc",+ organization_id="org_1",+ )++ assert result is None+ self.mock_cache.get.assert_not_called()+ self.mock_cache.set.assert_not_called()++ @pytest.mark.asyncio+ async def test_check_and_increment_self_heal_cap_unconfigured_cache_fails_open(self) -> None:+ CacheFactory.set_cache(None)++ result = await self_heal_cap.check_and_increment_self_heal_cap(workflow_permanent_id="wpid_abc")++ assert result == 1diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.pyindex 764eac346..a0e7915e9 100644--- a/tests/unit/workflow/test_code_block_escalation.py+++ b/tests/unit/workflow/test_code_block_escalation.py@@ -14,9 +14,11 @@ from unittest.mock import AsyncMock, MagicMockimport pytestfrom playwright.async_api import TimeoutError as PlaywrightTimeoutError+from structlog.testing import capture_logsfrom skyvern.forge import appfrom skyvern.forge.agent_functions import CodeBlockEngineFailure, CodeBlockEngineResult+from skyvern.forge.sdk.copilot.self_heal_recovery import SelfHealRecoveryResultfrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.skyvern_context import SkyvernContextfrom skyvern.forge.sdk.schemas.files import FileInfo@@ -24,7 +26,7 @@ from skyvern.forge.sdk.schemas.tasks import TaskStatusfrom skyvern.forge.sdk.workflow.context_manager import WorkflowRunContextfrom skyvern.forge.sdk.workflow.models.block import BlockResult, BlockStatus, BlockType, CodeBlock, CodeBlockStepfrom skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType-from skyvern.schemas.self_heal import HealSkipReason+from skyvern.schemas.self_heal import HealClassification, HealSkipReason, OutputObligationfrom skyvern.webeye.actions.actions import ActionSECRET_VALUE = "hunter2-super-secret"@@ -123,6 +125,7 @@ def _install_db_fakes("recovery_block_kwargs": None,"recovery_block_updates": [],"workflow_run_block_updates": [],+ "heal_episodes": [],}async def _create_task(**kwargs: object) -> _FakeTask:@@ -189,6 +192,12 @@ def _install_db_fakes(monkeypatch.setattr(app.DATABASE.workflow_runs, "create_or_update_workflow_run_output_parameter", AsyncMock(return_value=None))++ async def _create_heal_episode(**kwargs: object) -> None:+ state["heal_episodes"].append(kwargs)+ return None++ monkeypatch.setattr(app.DATABASE.self_heal, "create_heal_episode", AsyncMock(side_effect=_create_heal_episode))return state@@ -1741,3 +1750,619 @@ async def test_secure_infra_failure_without_metadata_finalizes_failed_and_recordassert record_output_mock.await_count == 0assert BlockStatus.completed not in block_statusesheal_mock.assert_not_awaited()+++async def test_chokepoint_cap_denied_records_skipped_episode_and_falls_back_to_floor_after_preconditions(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ floor_result = await block.build_block_result(+ success=True,+ failure_reason=None,+ output_parameter_value={"ok": True},+ status=BlockStatus.completed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )+ heal_mock = AsyncMock(return_value=floor_result)+ call_order: list[str] = []+ monkeypatch.setattr(block, "_attempt_self_heal", heal_mock)++ async def _resolve_api_key(_organization_id: str) -> str:+ call_order.append("api_key")+ return "sk-live"++ async def _check_cap(**kwargs: object) -> None:+ del kwargs+ call_order.append("cap")+ return None++ def _attachable(_context: object) -> bool:+ call_order.append("browser_attachable")+ return True++ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(side_effect=_check_cap),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(side_effect=_resolve_api_key))+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block._browser_context_is_attachable", _attachable)+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "get_for_workflow_run",+ MagicMock(return_value=SimpleNamespace(browser_context=object())),+ )++ async def _build_failure() -> BlockResult:+ raise AssertionError("should not use failure result when floor succeeds")++ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is True+ assert call_order == ["api_key", "browser_attachable", "cap"]+ assert len(state["heal_episodes"]) == 2+ harness_episode = state["heal_episodes"][0]+ floor_episode = state["heal_episodes"][1]+ assert harness_episode["engine"] == "harness"+ assert harness_episode["status"] == "skipped"+ assert harness_episode["skip_reason"] == HealSkipReason.capped+ assert floor_episode["engine"] == "floor"+ assert floor_episode["status"] == "fired_completed"+ heal_mock.assert_awaited_once()+++async def test_chokepoint_missing_api_key_records_skip_and_falls_back_to_floor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ floor_result = await block.build_block_result(+ success=True,+ failure_reason=None,+ output_parameter_value={"ok": True},+ status=BlockStatus.completed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )+ monkeypatch.setattr(block, "_attempt_self_heal", AsyncMock(return_value=floor_result))+ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value=None))+ monkeypatch.setattr(app.BROWSER_MANAGER, "get_for_workflow_run", MagicMock(return_value=object()))++ async def _build_failure() -> BlockResult:+ raise AssertionError("should not use failure result when floor succeeds")++ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is True+ assert len(state["heal_episodes"]) == 2+ harness_episode = state["heal_episodes"][0]+ floor_episode = state["heal_episodes"][1]+ assert harness_episode["engine"] == "harness"+ assert harness_episode["status"] == "skipped"+ assert harness_episode["skip_reason"] == HealSkipReason.credential_unavailable+ assert floor_episode["engine"] == "floor"+ assert floor_episode["status"] == "fired_completed"+ assert floor_episode["output_obligation"] == OutputObligation.observed.value+++async def test_chokepoint_harness_failure_records_fired_failed_and_falls_back_to_floor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ monkeypatch.setattr(block, "_attempt_self_heal", AsyncMock(return_value=None))+ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value="sk-live"))+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block._browser_context_is_attachable", lambda _ctx: True)+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "get_for_workflow_run",+ MagicMock(return_value=SimpleNamespace(browser_context=object())),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.run_self_heal_recovery",+ AsyncMock(+ return_value=SelfHealRecoveryResult(+ success=False,+ action_count=3,+ wall_clock_ms=1200,+ scout_trajectory=[],+ failure_note="no_action_progress",+ )+ ),+ )+ monkeypatch.setattr(block, "_self_heal_mutation_guard_snapshot", AsyncMock(return_value=(1, "abc")))++ async def _build_failure() -> BlockResult:+ return await block.build_block_result(+ success=False,+ failure_reason="fallback failed",+ output_parameter_value=None,+ status=BlockStatus.failed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )++ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is False+ assert len(state["heal_episodes"]) == 2+ harness_episode = state["heal_episodes"][0]+ floor_episode = state["heal_episodes"][1]+ assert harness_episode["engine"] == "harness"+ assert harness_episode["status"] == "fired_failed"+ assert floor_episode["engine"] == "floor"+ assert floor_episode["status"] == "fired_failed"+++async def test_chokepoint_harness_failure_with_mutation_suppresses_floor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ monkeypatch.setattr(block, "_attempt_self_heal", AsyncMock(return_value=None))+ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value="sk-live"))+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block._browser_context_is_attachable", lambda _ctx: True)+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "get_for_workflow_run",+ MagicMock(return_value=SimpleNamespace(browser_context=object())),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.run_self_heal_recovery",+ AsyncMock(+ return_value=SelfHealRecoveryResult(+ success=False,+ performed_mutation=True,+ action_count=2,+ wall_clock_ms=900,+ scout_trajectory=[],+ failure_note="max_actions_exhausted",+ )+ ),+ )+ monkeypatch.setattr(block, "_self_heal_mutation_guard_snapshot", AsyncMock(return_value=(1, "abc")))++ async def _build_failure() -> BlockResult:+ return await block.build_block_result(+ success=False,+ failure_reason="fallback suppressed",+ output_parameter_value=None,+ status=BlockStatus.failed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )++ with capture_logs() as logs:+ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is False+ assert len(state["heal_episodes"]) == 1+ harness_episode = state["heal_episodes"][0]+ assert harness_episode["engine"] == "harness"+ assert harness_episode["status"] == "fired_failed"+ block._attempt_self_heal.assert_not_awaited()+ assert any(+ log.get("event") == "Runtime self-heal failed after mutating actions; suppressing floor fallback"+ for log in logs+ )+++async def test_chokepoint_harness_unverified_records_fired_unverified_and_falls_back_to_floor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ floor_result = await block.build_block_result(+ success=True,+ failure_reason=None,+ output_parameter_value={"ok": True},+ status=BlockStatus.completed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )+ monkeypatch.setattr(block, "_attempt_self_heal", AsyncMock(return_value=floor_result))+ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value="sk-live"))+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block._browser_context_is_attachable", lambda _ctx: True)+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "get_for_workflow_run",+ MagicMock(return_value=SimpleNamespace(browser_context=object())),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.run_self_heal_recovery",+ AsyncMock(+ return_value=SelfHealRecoveryResult(+ success=True,+ verified=False,+ performed_mutation=False,+ action_count=2,+ wall_clock_ms=800,+ scout_trajectory=[],+ failure_note="goal_unverified",+ )+ ),+ )+ monkeypatch.setattr(block, "_self_heal_mutation_guard_snapshot", AsyncMock(return_value=(1, "abc")))++ async def _build_failure() -> BlockResult:+ raise AssertionError("should not use failure result when floor succeeds")++ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is True+ assert len(state["heal_episodes"]) == 2+ harness_episode = state["heal_episodes"][0]+ floor_episode = state["heal_episodes"][1]+ assert harness_episode["engine"] == "harness"+ assert harness_episode["status"] == "fired_unverified"+ assert harness_episode["output_obligation"] == OutputObligation.vestigial.value+ assert floor_episode["engine"] == "floor"+ assert floor_episode["status"] == "fired_completed"+++async def test_chokepoint_harness_unverified_with_mutation_fails_closed_without_floor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ monkeypatch.setattr(block, "_attempt_self_heal", AsyncMock(return_value=None))+ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value="sk-live"))+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block._browser_context_is_attachable", lambda _ctx: True)+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "get_for_workflow_run",+ MagicMock(return_value=SimpleNamespace(browser_context=object())),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.run_self_heal_recovery",+ AsyncMock(+ return_value=SelfHealRecoveryResult(+ success=True,+ verified=False,+ performed_mutation=True,+ action_count=2,+ wall_clock_ms=800,+ scout_trajectory=[],+ failure_note="goal_unverified",+ )+ ),+ )+ monkeypatch.setattr(block, "_self_heal_mutation_guard_snapshot", AsyncMock(return_value=(1, "abc")))++ async def _build_failure() -> BlockResult:+ return await block.build_block_result(+ success=False,+ failure_reason="fallback suppressed",+ output_parameter_value=None,+ status=BlockStatus.failed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )++ with capture_logs() as logs:+ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is False+ assert len(state["heal_episodes"]) == 1+ harness_episode = state["heal_episodes"][0]+ assert harness_episode["engine"] == "harness"+ assert harness_episode["status"] == "fired_unverified"+ assert harness_episode["output_obligation"] == OutputObligation.vestigial.value+ block._attempt_self_heal.assert_not_awaited()+ assert any(+ log.get("event") == "Runtime self-heal unverified after mutating actions; suppressing floor fallback"+ for log in logs+ )+ # The block row must never be left completed when the heal fails closed.+ assert all(update.get("status") != BlockStatus.completed for update in state["workflow_run_block_updates"])+++async def test_chokepoint_mutation_guard_mismatch_fails_harness_and_falls_back_to_floor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ monkeypatch.setattr(block, "_attempt_self_heal", AsyncMock(return_value=None))+ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value="sk-live"))+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block._browser_context_is_attachable", lambda _ctx: True)+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "get_for_workflow_run",+ MagicMock(return_value=SimpleNamespace(browser_context=object())),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.run_self_heal_recovery",+ AsyncMock(+ return_value=SelfHealRecoveryResult(+ success=True,+ action_count=2,+ wall_clock_ms=900,+ scout_trajectory=[],+ failure_note=None,+ )+ ),+ )+ monkeypatch.setattr(+ block,+ "_self_heal_mutation_guard_snapshot",+ AsyncMock(side_effect=[(1, "hash_a"), (2, "hash_b")]),+ )++ async def _build_failure() -> BlockResult:+ return await block.build_block_result(+ success=False,+ failure_reason="fallback failed",+ output_parameter_value=None,+ status=BlockStatus.failed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )++ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is False+ assert len(state["heal_episodes"]) == 2+ assert state["heal_episodes"][0]["engine"] == "harness"+ assert state["heal_episodes"][0]["status"] == "fired_failed"+ assert state["heal_episodes"][1]["engine"] == "floor"+++async def test_chokepoint_mutation_guard_mismatch_with_mutation_suppresses_floor(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ monkeypatch.setattr(block, "_attempt_self_heal", AsyncMock(return_value=None))+ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value="sk-live"))+ monkeypatch.setattr("skyvern.forge.sdk.workflow.models.block._browser_context_is_attachable", lambda _ctx: True)+ monkeypatch.setattr(+ app.BROWSER_MANAGER,+ "get_for_workflow_run",+ MagicMock(return_value=SimpleNamespace(browser_context=object())),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.run_self_heal_recovery",+ AsyncMock(+ return_value=SelfHealRecoveryResult(+ success=True,+ performed_mutation=True,+ action_count=2,+ wall_clock_ms=900,+ scout_trajectory=[],+ failure_note=None,+ )+ ),+ )+ monkeypatch.setattr(+ block,+ "_self_heal_mutation_guard_snapshot",+ AsyncMock(side_effect=[(1, "hash_a"), (2, "hash_b")]),+ )++ async def _build_failure() -> BlockResult:+ return await block.build_block_result(+ success=False,+ failure_reason="fallback suppressed",+ output_parameter_value=None,+ status=BlockStatus.failed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )++ with capture_logs() as logs:+ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is False+ assert len(state["heal_episodes"]) == 1+ assert state["heal_episodes"][0]["engine"] == "harness"+ assert state["heal_episodes"][0]["status"] == "fired_failed"+ block._attempt_self_heal.assert_not_awaited()+ assert any(+ log.get("event") == "Runtime self-heal errored after mutating actions; suppressing floor fallback"+ for log in logs+ )+++async def test_heal_episode_persistence_failure_does_not_change_heal_outcome(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)+ monkeypatch.setattr(app.DATABASE.self_heal, "create_heal_episode", AsyncMock(side_effect=RuntimeError("missing")))+ block = _make_code_block()+ context = _make_context(enable_self_healing=True)+ exception = RuntimeError("boom")+ recorder = SimpleNamespace(recording_page=_recording_page(exception), finalize=AsyncMock())+ floor_result = await block.build_block_result(+ success=True,+ failure_reason=None,+ output_parameter_value={"ok": True},+ status=BlockStatus.completed,+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ )+ monkeypatch.setattr(block, "_attempt_self_heal", AsyncMock(return_value=floor_result))+ monkeypatch.setattr(block, "_self_heal_enabled", AsyncMock(return_value=True))+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value=None))+ monkeypatch.setattr(app.BROWSER_MANAGER, "get_for_workflow_run", MagicMock(return_value=object()))++ async def _build_failure() -> BlockResult:+ raise AssertionError("should not use failure result when floor succeeds")++ with capture_logs() as logs:+ result = await block._resolve_failure_with_heal(+ exception=exception,+ failing_line=2,+ build_failure_result=_build_failure,+ classification=HealClassification(healable=True, skip_reason=None),+ recorder=recorder,+ workflow_run_context=context,+ workflow_run_id="wr_test",+ workflow_run_block_id="wrb_test",+ organization_id="o_test",+ browser_session_id=None,+ )++ assert result.success is True+ assert any(entry.get("event") == "self-heal episode persistence failed; continuing" for entry in logs)diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.pyindex d2aa9a08c..b2394dbb5 100644--- a/tests/unit/workflow/test_code_block_recorder.py+++ b/tests/unit/workflow/test_code_block_recorder.py@@ -595,11 +595,20 @@ async def test_self_heal_success_finalizes_seat_completed(monkeypatch: pytest.Mopage.inner = ExplodingLocator()context = FakeWorkflowRunContext()mocks = _patch_execute_environment(monkeypatch, page, context)+ # The enabled-gate now lives at the chokepoint, ahead of the mocked floor.+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)+ # Force the floor path deterministically so this exercises execute()'s seat-finalization+ # wiring regardless of ambient cap-cache / api-key state leaked by other tests in the suite.+ monkeypatch.setattr(+ "skyvern.forge.sdk.workflow.models.block.check_and_increment_self_heal_cap",+ AsyncMock(return_value=1),+ )+ monkeypatch.setattr(app.AGENT_FUNCTION, "resolve_self_heal_api_key", AsyncMock(return_value=None))# Stub the heal to a success result; this tests execute()'s seat-finalization wiring, not the heal itself.monkeypatch.setattr(CodeBlock,"_attempt_self_heal",- AsyncMock(return_value=SimpleNamespace(success=True, output_parameter_value=None)),+ AsyncMock(return_value=SimpleNamespace(success=True, output_parameter_value=None, failure_reason=None)),)block = _make_code_block("await page.locator('#x').click()", goal="go")@@ -623,6 +632,7 @@ async def test_self_heal_decline_finalizes_seat_failed(monkeypatch: pytest.Monkepage.inner = ExplodingLocator()context = FakeWorkflowRunContext()mocks = _patch_execute_environment(monkeypatch, page, context)+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)monkeypatch.setattr(CodeBlock, "_attempt_self_heal", AsyncMock(return_value=None))block = _make_code_block("await page.locator('#x').click()", goal="go")