Skip to content

Automate browser based workflows with AI

fix(SKY-11675): heal to end-of-block and verify heals with action history (#7015)

pedrohsdb81ab9939750e
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 3236350d4..9ddae5fd3 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -2962,7 +2962,12 @@ class ForgeAgent:
# A step-scale mini goal is often action-phrased ("Click X"); once the page
# navigates, page state alone can't certify it — wrapped goals verify with history.
if task.include_action_history_in_verification or unwrapped_goals.big_goal_context is not None:
- actions_and_results_str = await self._get_action_results(task, current_step=step)
+ # Evidence must be complete: the default 1-step window drops earlier actions of a
+ # multi-step goal, making every-action verification unsatisfiable on 3+-step heals.
+ full_run_window = task.max_steps_per_run or settings.MAX_STEPS_PER_RUN
+ actions_and_results_str = await self._get_action_results(
+ task, current_step=step, history_window=full_run_window
+ )
# Check if we should use the termination-aware prompt (experiment)
use_termination_prompt = False
@@ -3012,6 +3017,7 @@ class ForgeAgent:
terminate_criterion=unwrapped_goals.terminate_criterion,
big_goal_context=unwrapped_goals.big_goal_context,
action_history=actions_and_results_str,
+ action_history_evidence=bool(actions_and_results_str),
slim_output=slim_output,
local_datetime=datetime.now(skyvern_context.ensure_context().tz_info).isoformat(),
without_screenshots=not llm_screenshots_enabled,
@@ -4458,8 +4464,12 @@ class ForgeAgent:
return final_navigation_payload
- async def _get_action_results(self, task: Task, current_step: Step | None = None) -> str:
- return json.dumps(await get_action_history(task=task, current_step=current_step))
+ async def _get_action_results(
+ self, task: Task, current_step: Step | None = None, history_window: int | None = None
+ ) -> str:
+ if history_window is None:
+ return json.dumps(await get_action_history(task=task, current_step=current_step))
+ return json.dumps(await get_action_history(task=task, current_step=current_step, history_window=history_window))
async def get_extracted_information_for_task(self, task: Task) -> dict[str, Any] | list | str | None:
"""
diff --git a/skyvern/forge/prompts/skyvern/check-user-goal-with-termination.j2 b/skyvern/forge/prompts/skyvern/check-user-goal-with-termination.j2
index 2cfbb0718..81c4c0c59 100644
--- a/skyvern/forge/prompts/skyvern/check-user-goal-with-termination.j2
+++ b/skyvern/forge/prompts/skyvern/check-user-goal-with-termination.j2
@@ -29,7 +29,9 @@ The user goal above is one step of a larger objective. The larger objective is p
```
{{ big_goal_context }}
```
-Judge the status ONLY against the user goal above: return "complete" as soon as that step is done{{ " according to the complete criterion" if complete_criterion else "" }}, even if the larger objective is not finished yet. Return "terminate" only if that step itself can never be achieved — the larger objective being unfinished is NEVER a reason to continue or to terminate. If the user goal describes an action and the Action History shows that action completed successfully, the step is done — return "complete" even if the acted-on element is no longer on the current page; its absence after a successful action is NOT a reason to terminate.{% endif %}
+Judge the status ONLY against the user goal above: return "complete" as soon as that step is done{{ " according to the complete criterion" if complete_criterion else "" }}, even if the larger objective is not finished yet. Return "terminate" only if that step itself can never be achieved — the larger objective being unfinished is NEVER a reason to continue or to terminate.{% endif %}{% if action_history_evidence %}
+
+If the user goal describes actions, judge it against the Action History: return "complete" only when every described action (including each 'Then:' step) shows as completed successfully — never after only the first of several actions. A successfully completed action counts even when the acted-on element is no longer on the current page, and its absence after a successful action is NOT a reason to terminate.{{ " The complete criterion still governs: action history is supporting evidence for it, not a substitute." if complete_criterion else "" }}{% endif %}
User Details:
```
diff --git a/skyvern/forge/prompts/skyvern/check-user-goal.j2 b/skyvern/forge/prompts/skyvern/check-user-goal.j2
index 94ce95c4a..d4e5fc7a2 100644
--- a/skyvern/forge/prompts/skyvern/check-user-goal.j2
+++ b/skyvern/forge/prompts/skyvern/check-user-goal.j2
@@ -19,7 +19,9 @@ The user goal above is one step of a larger objective. The larger objective is p
```
{{ big_goal_context }}
```
-Certify ONLY the user goal above{{ " according to the complete criterion" if complete_criterion else "" }}: set user_goal_achieved to true as soon as that step is done, even if the larger objective is not finished yet. Do NOT require the larger objective to be complete. If the user goal describes an action and the Action History shows that action completed successfully, the step is done — set user_goal_achieved to true even if the acted-on element is no longer on the current page.{% endif %}
+Certify ONLY the user goal above{{ " according to the complete criterion" if complete_criterion else "" }}: set user_goal_achieved to true as soon as that step is done, even if the larger objective is not finished yet. Do NOT require the larger objective to be complete.{% endif %}{% if action_history_evidence %}
+
+If the user goal describes actions, judge it against the Action History: it is achieved only when every described action (including each 'Then:' step) shows as completed successfully — never after only the first of several actions. A successfully completed action counts even when the acted-on element is no longer on the current page.{{ " The complete criterion still governs: action history is supporting evidence for it, not a substitute." if complete_criterion else "" }}{% endif %}
User Details:
```
diff --git a/skyvern/forge/sdk/copilot/block_goal_wrapping.py b/skyvern/forge/sdk/copilot/block_goal_wrapping.py
index d26304827..7675095da 100644
--- a/skyvern/forge/sdk/copilot/block_goal_wrapping.py
+++ b/skyvern/forge/sdk/copilot/block_goal_wrapping.py
@@ -157,28 +157,33 @@ def unwrap_goal_fields(
complete_criterion: str | None = None,
terminate_criterion: str | None = None,
) -> UnwrappedGoals:
- """Reduce MINI_GOAL_TEMPLATE-wrapped fields to their mini goals plus one
- shared big-goal context for completion verification. Wrapping applies one
- user message across all fields, so the first wrapped field's main goal
- wins. Unwrapped fields pass through untouched and ``big_goal_context``
- stays ``None`` so the verify prompts render byte-identical to today."""
+ """Reduce MINI_GOAL_TEMPLATE-wrapped fields to their mini goals plus one shared
+ big-goal context (first wrapped field's main goal wins). Unwrapped fields pass
+ through untouched, keeping the verify prompts byte-identical to today."""
big_goal: str | None = None
- minis: list[str | None] = []
- for value in (navigation_goal, complete_criterion, terminate_criterion):
+
+ def unwrap_one(value: str | None) -> str | None:
+ nonlocal big_goal
if not value:
- minis.append(value)
- continue
+ return value
parts = _extract_wrapped_goal(value)
if parts is None:
- minis.append(value)
- continue
+ return value
mini_goal, main_goal = parts
- minis.append(mini_goal)
if big_goal is None:
big_goal = main_goal
elif main_goal != big_goal:
- LOG.debug("Wrapped goal fields carry mismatched main goals; first wins")
- unwrapped_navigation_goal, unwrapped_complete_criterion, unwrapped_terminate_criterion = minis
+ # Goal text can carry user-typed content; log shape only, never the strings.
+ LOG.debug(
+ "Wrapped goal fields carry mismatched main goals; first wins",
+ first_main_goal_length=len(big_goal),
+ conflicting_main_goal_length=len(main_goal),
+ )
+ return mini_goal
+
+ unwrapped_navigation_goal = unwrap_one(navigation_goal)
+ unwrapped_complete_criterion = unwrap_one(complete_criterion)
+ unwrapped_terminate_criterion = unwrap_one(terminate_criterion)
return UnwrappedGoals(
unwrapped_navigation_goal, unwrapped_complete_criterion, unwrapped_terminate_criterion, big_goal
)
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index b7499ed20..dc39d43c1 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -4126,7 +4126,19 @@ async def wrapper({default_args}):
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:
- safe_mini = workflow_run_context.mask_secrets_in_data(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
@@ -4157,6 +4169,9 @@ async def wrapper({default_args}):
max_steps_per_run=heal_max_steps,
model=self.model,
workflow_system_prompt=workflow_system_prompt,
+ # Heal goals are action-phrased; after the page navigates, only the action
+ # history can evidence completion.
+ include_action_history_in_verification=True,
)
escalation_task = await app.DATABASE.tasks.update_task(
task_id=escalation_task.task_id,
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index b641baf4e..2d33c164b 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -2126,6 +2126,9 @@ async def _build_after_click_verify_prompt(
navigation_payload=task.navigation_payload,
new_elements_ids=new_element_ids,
without_screenshots=True,
+ # No action_history_evidence: this call site judges mid-action continuation, and the
+ # history here is the menu-opening click — evidence-shortcutting it would certify
+ # the dropdown before the actual selection.
action_history=action_history_str,
slim_output=slim_output,
local_datetime=datetime.now(skyvern_context.ensure_context().tz_info).isoformat(),
diff --git a/tests/unit/test_complete_verify_goal_unwrap.py b/tests/unit/test_complete_verify_goal_unwrap.py
index cb187acf7..616e1f51e 100644
--- a/tests/unit/test_complete_verify_goal_unwrap.py
+++ b/tests/unit/test_complete_verify_goal_unwrap.py
@@ -12,6 +12,7 @@ from zoneinfo import ZoneInfo
import pytest
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
+from skyvern.config import settings
from skyvern.forge.agent import ForgeAgent
from skyvern.forge.sdk.copilot.block_goal_wrapping import compose_mini_goal
from skyvern.forge.sdk.core import skyvern_context
@@ -78,7 +79,8 @@ async def _call_complete_verify(
return "rendered prompt"
monkeypatch.setattr("skyvern.forge.agent.load_prompt_with_elements", capture_prompt)
- monkeypatch.setattr(ForgeAgent, "_get_action_results", AsyncMock(return_value=ACTION_HISTORY_STUB))
+ history_mock = AsyncMock(return_value=ACTION_HISTORY_STUB)
+ monkeypatch.setattr(ForgeAgent, "_get_action_results", history_mock)
llm_response = (
{"status": "complete", "thoughts": "done", "page_info": "ok", "failure_categories": []}
@@ -109,6 +111,9 @@ async def _call_complete_verify(
)
finally:
skyvern_context.reset()
+ captured_kwargs["_history_window"] = (
+ history_mock.call_args.kwargs.get("history_window") if history_mock.call_args else None
+ )
return captured_kwargs
@@ -125,6 +130,10 @@ async def test_wrapped_goal_threads_mini_and_context_legacy_prompt(monkeypatch:
# Step-scale mini goals are often action-phrased; the verifier gets the
# action history even though include_action_history_in_verification is off.
assert captured["action_history"] == ACTION_HISTORY_STUB
+ assert captured["action_history_evidence"] is True
+ # Evidence fetches use the full-run window: a 1-step slice hides earlier
+ # Then-step actions and makes every-action verification unsatisfiable.
+ assert captured["_history_window"] == settings.MAX_STEPS_PER_RUN
@pytest.mark.asyncio
@@ -158,6 +167,8 @@ async def test_unwrapped_goal_passes_through_with_no_context(monkeypatch: pytest
assert captured["terminate_criterion"] is None
assert captured["big_goal_context"] is None
assert captured["action_history"] == ""
+ assert captured["action_history_evidence"] is False
+ assert captured["_history_window"] is None
@pytest.mark.asyncio
@@ -216,6 +227,9 @@ async def test_after_click_verifier_unwraps_wrapped_goal(monkeypatch: pytest.Mon
assert captured["navigation_goal"] == MINI_GOAL
assert captured["big_goal_context"] == MAIN_GOAL
assert captured["template_name"] == "check-user-goal"
+ # The after-click verifier judges mid-action continuation; treating the
+ # menu-opening click as completion evidence would end dropdown flows early.
+ assert "action_history_evidence" not in captured
@pytest.mark.asyncio
diff --git a/tests/unit/test_verifier_goal_unwrap.py b/tests/unit/test_verifier_goal_unwrap.py
index e70a9b125..9a912be7f 100644
--- a/tests/unit/test_verifier_goal_unwrap.py
+++ b/tests/unit/test_verifier_goal_unwrap.py
@@ -134,18 +134,45 @@ def test_render_without_context_is_byte_identical_to_golden(prompt_engine: Promp
@pytest.mark.parametrize("template_name", list(_TEMPLATE_KWARGS))
def test_render_with_context_scopes_judgment_to_mini_goal(prompt_engine: PromptEngine, template_name: str) -> None:
kwargs = {**_TEMPLATE_KWARGS[template_name], "navigation_goal": MINI_GOAL}
- rendered = prompt_engine.load_prompt(template_name, big_goal_context=MAIN_GOAL, **kwargs)
+ rendered = prompt_engine.load_prompt(
+ template_name, big_goal_context=MAIN_GOAL, action_history_evidence=True, **kwargs
+ )
assert MINI_GOAL in rendered
assert MAIN_GOAL in rendered
assert "The user goal above is one step of a larger objective" in rendered
assert "Achieve the following mini goal" not in rendered
- assert "Action History shows that action completed successfully" in rendered
+ # Compound heal goals: the evidence shortcut must demand every described action.
+ assert "every described action (including each 'Then:' step)" in rendered
+ assert "never after only the first of several actions" in rendered
if template_name == "check-user-goal":
assert "Do NOT require the larger objective to be complete" in rendered
else:
assert "NEVER a reason to continue or to terminate" in rendered
[email protected]("template_name", list(_TEMPLATE_KWARGS))
+def test_history_evidence_instruction_renders_without_context(prompt_engine: PromptEngine, template_name: str) -> None:
+ # Bare-prompt heals: history evidence must not depend on the goal being wrapped.
+ kwargs = {**_TEMPLATE_KWARGS[template_name], "navigation_goal": MINI_GOAL}
+ rendered = prompt_engine.load_prompt(template_name, action_history_evidence=True, **kwargs)
+ assert "every described action (including each 'Then:' step)" in rendered
+ assert "The user goal above is one step of a larger objective" not in rendered
+ without = prompt_engine.load_prompt(template_name, big_goal_context=MAIN_GOAL, **kwargs)
+ assert "every described action" not in without
+
+
[email protected]("template_name", list(_TEMPLATE_KWARGS))
+def test_history_evidence_stays_subordinate_to_complete_criterion(
+ prompt_engine: PromptEngine, template_name: str
+) -> None:
+ kwargs = {**_TEMPLATE_KWARGS[template_name], "navigation_goal": MINI_GOAL, "complete_criterion": CRITERION_MINI}
+ rendered = prompt_engine.load_prompt(template_name, action_history_evidence=True, **kwargs)
+ assert "The complete criterion still governs" in rendered
+ without_criterion = {**_TEMPLATE_KWARGS[template_name], "navigation_goal": MINI_GOAL}
+ rendered_no_criterion = prompt_engine.load_prompt(template_name, action_history_evidence=True, **without_criterion)
+ assert "The complete criterion still governs" not in rendered_no_criterion
+
+
def test_render_with_context_and_complete_criterion_mentions_criterion(prompt_engine: PromptEngine) -> None:
kwargs = {
**_CHECK_USER_GOAL_WITH_TERMINATION_KWARGS,
diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.py
index 679653fee..14ac5beca 100644
--- a/tests/unit/workflow/test_code_block_escalation.py
+++ b/tests/unit/workflow/test_code_block_escalation.py
@@ -678,3 +678,115 @@ async def test_recovery_block_finalized_to_non_completed_status(monkeypatch: pyt
assert result is not None and result.success is False
assert any(u.get("status") == BlockStatus.terminated for u in state["recovery_block_updates"])
+
+
+async def test_mid_block_failure_composes_remaining_steps(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)
+ block = _make_code_block(
+ steps=[
+ CodeBlockStep(description="open the portal", line_start=1, line_end=1),
+ CodeBlockStep(description="click the invoices tab", line_start=2, line_end=2),
+ CodeBlockStep(description="download the latest invoice", line_start=3, line_end=3),
+ ]
+ )
+ exc = RuntimeError("rotted selector")
+
+ result = await _heal(block, _make_context(), exc, _recording_page(exc), failing_line=2)
+
+ assert result is not None and result.success is True
+ goal = state["create_task_kwargs"]["navigation_goal"]
+ assert "click the invoices tab" in goal
+ assert "Then: download the latest invoice" in goal
+ # steps before the failure already ran as code — they must not be re-demanded.
+ assert "open the portal" not in goal
+ assert DEFAULT_PROMPT in goal
+
+
+async def test_last_step_failure_keeps_single_step_goal(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)
+ block = _make_code_block(
+ steps=[
+ CodeBlockStep(description="open the portal", line_start=1, line_end=1),
+ CodeBlockStep(description="download the latest invoice", line_start=2, line_end=2),
+ ]
+ )
+ exc = RuntimeError("rotted selector")
+
+ result = await _heal(block, _make_context(), exc, _recording_page(exc), failing_line=2)
+
+ assert result is not None and result.success is True
+ goal = state["create_task_kwargs"]["navigation_goal"]
+ assert "download the latest invoice" in goal
+ assert "Then:" not in goal
+
+
+async def test_remaining_steps_without_descriptions_are_skipped(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)
+ block = _make_code_block(
+ steps=[
+ CodeBlockStep(description="click the invoices tab", line_start=1, line_end=1),
+ CodeBlockStep(description=None, line_start=2, line_end=2),
+ ]
+ )
+ exc = RuntimeError("rotted selector")
+
+ result = await _heal(block, _make_context(), exc, _recording_page(exc), failing_line=1)
+
+ assert result is not None and result.success is True
+ goal = state["create_task_kwargs"]["navigation_goal"]
+ assert "click the invoices tab" in goal
+ assert "Then:" not in goal
+
+
+async def test_remaining_step_descriptions_are_masked(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)
+ block = _make_code_block(
+ steps=[
+ CodeBlockStep(description="open the portal", line_start=1, line_end=1),
+ CodeBlockStep(description=f"submit token {SECRET_VALUE}", line_start=2, line_end=2),
+ ]
+ )
+ exc = RuntimeError("rotted selector")
+
+ result = await _heal(block, _make_context(with_secret=True), exc, _recording_page(exc), failing_line=1)
+
+ assert result is not None and result.success is True
+ goal = state["create_task_kwargs"]["navigation_goal"]
+ assert "open the portal" in goal
+ assert "Then:" in goal
+ assert SECRET_VALUE not in goal
+
+
+ "steps",
+ [
+ pytest.param([CodeBlockStep(description="download", line_start=1, line_end=1)], id="matched_step"),
+ pytest.param(None, id="bare_prompt"),
+ ],
+)
+async def test_escalation_task_verifies_with_action_history(
+ monkeypatch: pytest.MonkeyPatch, steps: list[CodeBlockStep] | None
+) -> None:
+ monkeypatch.setattr("skyvern.config.settings.ENABLE_CODE_BLOCK_SELF_HEALING", True, raising=False)
+ monkeypatch.setattr(CodeBlock, "record_output_parameter_value", AsyncMock(return_value=None))
+ state = _install_db_fakes(monkeypatch, final_status=TaskStatus.completed)
+ block = _make_code_block(steps=steps)
+ exc = RuntimeError("rotted selector")
+
+ result = await _heal(block, _make_context(), exc, _recording_page(exc))
+
+ assert result is not None and result.success is True
+ assert state["create_task_kwargs"]["include_action_history_in_verification"] is True