Skip to content

Automate browser based workflows with AI

SKY-12858 Copilot: list the steps a draft workflow is missing, and add them back after repeated omissions (#7695)

Andrew Neilson3a7746f5407f
diff --git a/skyvern/cli/mcp_tools/__init__.py b/skyvern/cli/mcp_tools/__init__.py
index 30e554342..75dc62eed 100644
--- a/skyvern/cli/mcp_tools/__init__.py
+++ b/skyvern/cli/mcp_tools/__init__.py
@@ -330,6 +330,7 @@ Multi-tab flow: tab_list -> tab_new or click link -> tab_wait_for_new -> tab_swi
## Workflows
Split into multiple blocks — one intent per block. Use **navigation** blocks for actions, **extraction** for data.
+Omit `code_only` or pass null to use this server's default; organization policy may enforce code-only, making rejection intentional.
Call skyvern_block_schema() for available types. Validate with skyvern_block_validate() before creating.
Do NOT use deprecated "task" or "task_v2" block types — use "navigation" for actions, "extraction" for data.
Use {{parameter_key}} to reference workflow parameters. Blocks share a browser session automatically.
diff --git a/skyvern/cli/mcp_tools/_common.py b/skyvern/cli/mcp_tools/_common.py
index 1181d318e..aaf800fd4 100644
--- a/skyvern/cli/mcp_tools/_common.py
+++ b/skyvern/cli/mcp_tools/_common.py
@@ -1,7 +1,4 @@
-"""Backward-compatible re-exports from skyvern.cli.core.
-
-MCP tools import from here; the canonical implementations live in core/.
-"""
+"""Shared helpers for MCP tools: re-exports from skyvern.cli.core plus tool-surface constants."""
from __future__ import annotations
@@ -15,6 +12,18 @@ DIRECT_TARGET_DESCRIPTION = "Direct target: deterministic, 0 LLM calls."
AI_FALLBACK_DESCRIPTION = (
"AI fallback: costs Skyvern LLM calls, slower and nondeterministic — prefer selector when known."
)
+CODE_ONLY_POLICY_HINT = (
+ "If you did not pass code_only=true yourself, this server enforces code-only authoring by "
+ "organization policy — the rejection is intentional, not an error. Do not pass code_only=false "
+ "to bypass it unless the user explicitly asked for agentic (non-code) blocks."
+)
+CODE_ONLY_SCHEMA_GUIDANCE = (
+ "Omit `code_only` or pass null to use this server's default; organization policy may enforce "
+ "code-only, making rejection intentional."
+)
+CODE_ONLY_FIELD_DESCRIPTION = (
+ "When true, structurally reject non-code browser/page block types (code-only mode). " + CODE_ONLY_SCHEMA_GUIDANCE
+)
async def raw_http_get(path: str, params: dict[str, Any] | None = None) -> Any:
diff --git a/skyvern/cli/mcp_tools/blocks.py b/skyvern/cli/mcp_tools/blocks.py
index 5dff4dfeb..0a5e778d6 100644
--- a/skyvern/cli/mcp_tools/blocks.py
+++ b/skyvern/cli/mcp_tools/blocks.py
@@ -51,7 +51,7 @@ from skyvern.schemas.workflows import (
WorkflowTriggerBlockYAML,
)
-from ._common import ErrorCode, make_error, make_result
+from ._common import CODE_ONLY_FIELD_DESCRIPTION, CODE_ONLY_POLICY_HINT, ErrorCode, make_error, make_result
LOG = structlog.get_logger(__name__)
@@ -490,9 +490,9 @@ async def skyvern_block_validate(
Field(description="JSON string of a single block definition to validate"),
],
code_only: Annotated[
- bool,
- Field(description="When true, structurally reject non-code browser/page block types (code-only mode)"),
- ] = False,
+ bool | None,
+ Field(description=CODE_ONLY_FIELD_DESCRIPTION),
+ ] = None,
) -> dict[str, Any]:
"""Validate a single workflow block definition (pass it as a JSON string in block_json) before using
it in skyvern_workflow_create. Returns field-level errors. To look up the schema or fields for a
@@ -540,7 +540,7 @@ async def skyvern_block_validate(
ErrorCode.INVALID_INPUT,
f"Block type(s) {types} are not allowed in code-only mode (offending labels: {labels})",
"In code-only mode, use a `code` block for durable browser/page work instead of "
- "task/navigation/extraction/etc.",
+ "task/navigation/extraction/etc. " + CODE_ONLY_POLICY_HINT,
),
)
diff --git a/skyvern/cli/mcp_tools/prompts.py b/skyvern/cli/mcp_tools/prompts.py
index e050a4646..6ddf90d46 100644
--- a/skyvern/cli/mcp_tools/prompts.py
+++ b/skyvern/cli/mcp_tools/prompts.py
@@ -14,6 +14,8 @@ from typing import Annotated
from pydantic import Field
+from ._common import CODE_ONLY_SCHEMA_GUIDANCE
+
# ---------------------------------------------------------------------------
# build_workflow
# ---------------------------------------------------------------------------
@@ -69,6 +71,7 @@ BAD navigation_goal — describes HOW to do it (Skyvern already knows):
8. **action** — single focused action on the current page (e.g., click one button).
Use skyvern_block_schema() to see full schemas and examples for any block type.
+{CODE_ONLY_SCHEMA_GUIDANCE}
### Engine selection for workflow blocks
@@ -112,6 +115,7 @@ GOOD (3 blocks):
BAD (1 block):
Block 1 (navigation): "Search for the product, click the first result, add to cart, go to checkout,
fill in shipping, enter payment, and submit the order."
+{CODE_ONLY_SCHEMA_GUIDANCE}
### Common workflow shapes
@@ -233,7 +237,7 @@ Before calling skyvern_workflow_create, verify:
6. Login is handled by a login block (not embedded in a navigation goal).
7. You have test parameter values ready for the first skyvern_workflow_run call.
8. Validate blocks with skyvern_block_validate before submitting the full definition.
-"""
+""".replace("{CODE_ONLY_SCHEMA_GUIDANCE}", CODE_ONLY_SCHEMA_GUIDANCE)
# ---------------------------------------------------------------------------
@@ -407,6 +411,7 @@ code_version=2 is also injected by default; YAML definitions use the backend sch
leaves code_version unset, so pass `code_version: 2` explicitly in YAML if you want to opt into \
the v2 caching framework). Set run_with="code" on the workflow (or at run time) to opt into cached \
script execution.
+{CODE_ONLY_SCHEMA_GUIDANCE}
### What this means for workflow design
@@ -430,7 +435,7 @@ in navigation_goal become part of the script literally.
Pass `run_with="code"` to `skyvern_workflow_run` to force cached-script execution for a single run \
without changing the workflow definition (only meaningful once a script exists). Pass \
`run_with="agent"` to force AI execution for debugging or after a site redesign.
-"""
+""".replace("{CODE_ONLY_SCHEMA_GUIDANCE}", CODE_ONLY_SCHEMA_GUIDANCE)
# ---------------------------------------------------------------------------
diff --git a/skyvern/cli/mcp_tools/workflow.py b/skyvern/cli/mcp_tools/workflow.py
index 9aaccc8f3..ca4c1610c 100644
--- a/skyvern/cli/mcp_tools/workflow.py
+++ b/skyvern/cli/mcp_tools/workflow.py
@@ -30,7 +30,7 @@ from skyvern.schemas.workflows import BlockType
from skyvern.schemas.workflows import WorkflowCreateYAMLRequest as WorkflowCreateYAMLRequestSchema
from skyvern.utils.yaml_loader import safe_load_no_dates
-from ._common import ErrorCode, Timer, make_error, make_result
+from ._common import CODE_ONLY_FIELD_DESCRIPTION, CODE_ONLY_POLICY_HINT, ErrorCode, Timer, make_error, make_result
from ._session import get_skyvern
from ._validation import validate_folder_id, validate_run_id, validate_workflow_id, validate_workflow_run_id
from ._workflow_http import (
@@ -484,7 +484,7 @@ def _validate_code_only_workflow_blocks(definition: dict[str, Any], action: str)
ErrorCode.INVALID_INPUT,
f"Block type(s) {types} are not allowed in code-only mode (offending labels: {labels})",
"In code-only mode, use a `code` block for durable browser/page work instead of "
- "task/navigation/extraction/etc.",
+ "task/navigation/extraction/etc. " + CODE_ONLY_POLICY_HINT,
),
)
@@ -1616,12 +1616,9 @@ async def skyvern_workflow_create(
] = "auto",
folder_id: Annotated[str | None, "Folder ID (fld_...) to organize the workflow in"] = None,
code_only: Annotated[
- bool,
- Field(
- description="When true, structurally reject non-code browser/page block types before persisting "
- "(code-only mode)"
- ),
- ] = False,
+ bool | None,
+ Field(description=CODE_ONLY_FIELD_DESCRIPTION),
+ ] = None,
) -> dict[str, Any]:
"""Create a reusable, versioned workflow from a YAML or JSON definition. For multi-page automations,
scheduling, and repeated runs — not one-off trials (use skyvern_run_task for those).
@@ -1635,6 +1632,7 @@ async def skyvern_workflow_create(
skyvern_workflow_list.
One block per step: "navigation" for actions, "extraction" for data. Do NOT use deprecated "task" type.
+ Omit `code_only` or pass null to use this server's default; organization policy may enforce code-only, making rejection intentional.
Call skyvern_block_schema() for block types and schemas. Use {{parameter_key}} for input references.
Defaults to AI agent execution (run_with="agent"). For JSON definitions, code_version=2 is also
injected (YAML definitions go through the backend schema, which currently leaves code_version unset).
@@ -1725,12 +1723,9 @@ async def skyvern_workflow_update(
str, Field(description="Definition format: 'json', 'yaml', or 'auto'")
] = "auto",
code_only: Annotated[
- bool,
- Field(
- description="When true, structurally reject non-code browser/page block types before persisting "
- "(code-only mode)"
- ),
- ] = False,
+ bool | None,
+ Field(description=CODE_ONLY_FIELD_DESCRIPTION),
+ ] = None,
) -> dict[str, Any]:
"""Update an existing workflow's definition. Use when you need to modify a workflow's blocks,
parameters, or configuration. Creates a new version of the workflow.
diff --git a/skyvern/config.py b/skyvern/config.py
index 752b7ab5b..a09369b02 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -4,7 +4,7 @@ import platform
from pathlib import Path
from typing import Any
-from pydantic import Field
+from pydantic import AliasChoices, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
from skyvern import constants
@@ -781,6 +781,22 @@ class Settings(BaseSettings):
# "CRITICAL") to drop its retry/failure records where the OTLP endpoint is
# intentionally unavailable; the default keeps export failures visible.
OTEL_EXPORTER_LOG_LEVEL: str = "WARNING"
+ # Per-export deadline (seconds) for the OTLP span exporter. Must exceed the exporter's
+ # ~31s retry-backoff window (2**n over _MAX_RETRYS) so a brief node-local collector blip
+ # is retried to success instead of logged as a failure; the library default (10s) cuts
+ # the retry sequence short and turns each blip into an error burst.
+ OTEL_EXPORTER_TIMEOUT_SECONDS: float = Field(
+ default=45.0,
+ gt=0,
+ validation_alias=AliasChoices(
+ "OTEL_EXPORTER_TIMEOUT_SECONDS",
+ "OTEL_EXPORTER_OTLP_TRACES_TIMEOUT",
+ "OTEL_EXPORTER_OTLP_TIMEOUT",
+ ),
+ )
+ # BatchSpanProcessor queue depth (library default 2048); enlarged to buffer more spans
+ # while an export is retrying against a briefly unavailable collector.
+ OTEL_BSP_MAX_QUEUE_SIZE: int = 8192
# script generation settings
WORKFLOW_START_BLOCK_LABEL: str = "__start_block__"
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 87ead44d6..2efb3f536 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -108,6 +108,7 @@ from skyvern.forge.sdk.copilot.data_write_defaults import default_data_write_con
from skyvern.forge.sdk.copilot.enforcement import (
BUILT_UNVERIFIED_REPAIR_INERT_TERMINAL_REASON,
SCOUTED_SPINE_TURN_HALT_USER_REASON,
+ _get_scouted_spine_missing_steps_for_halt,
artifact_health_blocked,
log_scouted_spine_unresolved_at_turn_halt,
outcome_fully_verified,
@@ -2139,6 +2140,7 @@ async def _build_goal_satisfied_exit_result(
terminal_reason: str = "verified_goal_satisfied",
exit_site: str = "verified_goal_satisfied",
flush_goal_satisfied: bool = True,
+ name_missing_spine_steps: bool = False,
) -> AgentResult:
# Bypass one extra LLM turn after a full workflow test already satisfies
# the diagnosis contract.
@@ -2163,6 +2165,10 @@ async def _build_goal_satisfied_exit_result(
"I reached the requested outcome, but the workflow has not been tested end-to-end. "
"Review the draft before using it."
)
+ if name_missing_spine_steps and log_scouted_spine_unresolved_at_turn_halt(ctx):
+ user_response = _with_scouted_spine_missing_steps(
+ ctx, user_response, _get_scouted_spine_missing_steps_for_halt(ctx), held_signal_unrelated=True
+ )
final_text, outcome = apply_repeated_reply_guard(
final_text=user_response,
attempted_kind=derive_response_kind(ctx.turn_intent),
@@ -2251,10 +2257,36 @@ async def _build_built_unverified_exit_result(ctx: CopilotContext, global_llm_co
terminal_reason=BUILT_UNVERIFIED_REPAIR_INERT_TERMINAL_REASON,
exit_site=BUILT_UNVERIFIED_REPAIR_INERT_TERMINAL_REASON,
flush_goal_satisfied=False,
+ name_missing_spine_steps=True,
)
_SCOUTED_SPINE_HALT_REPLY_KINDS = frozenset({TurnHaltKind.LOOP_DETECTED, TurnHaltKind.REPAIR_CEILING_REACHED})
+_SCOUTED_SPINE_MISSING_STEPS_PREFIX = "This draft is still missing steps you demonstrated:"
+
+
+def _with_scouted_spine_missing_steps(
+ ctx: CopilotContext,
+ user_response: str,
+ missing_steps: str | None,
+ *,
+ held_signal_unrelated: bool = False,
+) -> str:
+ """Name the demonstrated-but-missing steps on any give-up offer that carries a staged proposal, and
+ anchor them in the held blocker signal so the blocker-override finalizer cannot re-render them away.
+ When the held signal is an unrelated blocker that owns the turn (output policy, timeout, credential),
+ the steps are surfaced in the reply only; its reason and claimant stay intact so the turn's single
+ owner keeps rendering its own reply. Idempotent so a pre-finalizer append plus the finalizer re-render
+ never doubles the note."""
+ if not missing_steps or not ctx.has_staged_proposal:
+ return user_response
+ if _SCOUTED_SPINE_MISSING_STEPS_PREFIX in user_response:
+ return user_response
+ reframed = f"{user_response}\n\n{_SCOUTED_SPINE_MISSING_STEPS_PREFIX} {missing_steps}"
+ if not held_signal_unrelated and isinstance(ctx.blocker_signal, CopilotToolBlockerSignal):
+ ctx.blocker_signal = ctx.blocker_signal.model_copy(update={"user_facing_reason": reframed})
+ ctx.blocker_signal_claimant = None
+ return reframed
def _build_turn_halt_exit_result(
@@ -2263,6 +2295,7 @@ def _build_turn_halt_exit_result(
halt: TurnHalt,
) -> AgentResult:
under_build_open = log_scouted_spine_unresolved_at_turn_halt(ctx)
+ missing_steps = _get_scouted_spine_missing_steps_for_halt(ctx) if under_build_open else None
if halt.kind == TurnHaltKind.DELIVERED_UNVERIFIED:
return _build_wip_exit_result(
ctx,
@@ -2271,15 +2304,15 @@ def _build_turn_halt_exit_result(
unvalidated_reply=_BUILT_UNVERIFIED_COMPLETED_REPLY,
tested_reply=_BUILT_UNVERIFIED_COMPLETED_REPLY,
terminal_reason=f"turn_halt:{halt.kind.value}",
+ missing_spine_steps=missing_steps,
)
signal = halt.blocker_signal
if isinstance(signal, CopilotToolBlockerSignal) and signal.blocker_kind == "loop_detected":
refresh_held_loop_blocker_evidence(ctx)
signal = ctx.blocker_signal if isinstance(ctx.blocker_signal, CopilotToolBlockerSignal) else signal
- if under_build_open and halt.kind in _SCOUTED_SPINE_HALT_REPLY_KINDS:
+ scouted_spine_owns = under_build_open and halt.kind in _SCOUTED_SPINE_HALT_REPLY_KINDS
+ if scouted_spine_owns:
user_response = SCOUTED_SPINE_TURN_HALT_USER_REASON
- # The blocker-override finalizer re-renders from the held signal, so the
- # reframed reason must live there, not just in the local reply.
if isinstance(ctx.blocker_signal, CopilotToolBlockerSignal):
ctx.blocker_signal = ctx.blocker_signal.model_copy(update={"user_facing_reason": user_response})
ctx.blocker_signal_claimant = None
@@ -2287,6 +2320,9 @@ def _build_turn_halt_exit_result(
user_response = signal.user_facing_reason
else:
user_response = "I could not continue this turn safely. Tell me what to change and I'll try again."
+ user_response = _with_scouted_spine_missing_steps(
+ ctx, user_response, missing_steps, held_signal_unrelated=not scouted_spine_owns
+ )
return _build_exit_result(
ctx,
user_response,
@@ -3122,6 +3158,9 @@ def _finalize_result_with_blocker_override(
return preserved
rendered_reply, rendered_resp_type = _render_blocker_reply(local_signal, exit_site=exit_site)
+ rendered_reply = _with_scouted_spine_missing_steps(
+ ctx, rendered_reply, _get_scouted_spine_missing_steps_for_halt(ctx), held_signal_unrelated=True
+ )
rendered_kind = (
CopilotOutputKind.CLARIFICATION_REQUEST
@@ -3488,8 +3527,11 @@ def _build_wip_exit_result(
tested_reply: str,
cancelled: bool = False,
terminal_reason: str | None = None,
+ missing_spine_steps: str | None = None,
) -> AgentResult:
"""Selected non-success exits surface the most recent successfully parsed workflow."""
+ if missing_spine_steps is None:
+ missing_spine_steps = _get_scouted_spine_missing_steps_for_halt(ctx)
internal_tool_instruction_failure = _recorded_failure_is_internal_tool_instruction(ctx)
halted_mid_progress = _halted_mid_progress(ctx, internal_tool_instruction_failure)
recorded_failure_reply = _recorded_failure_reply(
@@ -3509,6 +3551,7 @@ def _build_wip_exit_result(
terminal_reason=effective_terminal,
)
text = _observed_facts_halt_reply(ctx)
+ text = _with_scouted_spine_missing_steps(ctx, text, missing_spine_steps, held_signal_unrelated=True)
return apply_repeated_reply_guard(
final_text=text,
attempted_kind=ResponseKind.CLARIFY,
@@ -4982,6 +5025,9 @@ def _build_output_policy_blocked_result(
composed_from_recorded_evidence = True
if preserved_workflow is not None and add_saved_draft_copy:
user_response = f"{user_response} {_SAVED_DRAFT_OUTPUT_POLICY_SUFFIX}"
+ user_response = _with_scouted_spine_missing_steps(
+ ctx, user_response, _get_scouted_spine_missing_steps_for_halt(ctx), held_signal_unrelated=True
+ )
has_non_actuation_hard_block = any(
reason
not in {
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 036a74c1e..8c1a5e1f7 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -547,6 +547,19 @@ SCOUTED_SPINE_TURN_HALT_USER_REASON = (
)
+def _get_scouted_spine_missing_steps_for_halt(ctx: AgentContext) -> str | None:
+ """Missing-steps text for any give-up offer, covering every open obligation family
+ (uncovered rungs, unforgiven drops, unrecorded indices, truncation), not uncovered rungs alone."""
+ try:
+ findings = _scouted_spine_open_obligation(ctx)
+ except Exception:
+ LOG.warning("copilot_scouted_spine_halt_missing_steps_failed", exc_info=True)
+ return None
+ if not findings:
+ return None
+ return _scouted_spine_missing_text(findings)
+
+
def log_scouted_spine_unresolved_at_turn_halt(ctx: AgentContext) -> bool:
"""Log-only and never raises: a failed obligation read must not block rendering the halt reply."""
try:
@@ -2265,7 +2278,11 @@ def _maybe_synthesized_block_offer_msg(ctx: Any) -> dict[str, Any] | None:
if reopened_after_failed_run:
ctx.synthesized_block_reopened_after_failed_run = True
goal = getattr(ctx, "block_goal_main_goal", "") or getattr(ctx, "user_message", "") or ""
- return {"role": "user", "content": render_synthesized_offer_text(synthesized, trajectory, goal=goal)}
+ offer_text = render_synthesized_offer_text(synthesized, trajectory, goal=goal)
+ missing_steps = _get_scouted_spine_missing_steps_for_halt(ctx)
+ if missing_steps:
+ offer_text += f"\n\n**Note:** This draft is missing these demonstrated steps: {missing_steps}"
+ return {"role": "user", "content": offer_text}
def _completion_verification_unsatisfied(ctx: Any) -> bool:
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index faecaa979..b1c1cb020 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -495,6 +495,8 @@ class AgentContext:
# blocks; None until a persist succeeds this turn. Gates the scouted-spine under-build reject and turn-end nudge.
persisted_draft_browser_calls: list[tuple[str, str]] | None = None
scouted_spine_checkpoint_fired: bool = False
+ scouted_spine_previous_omission_digest: str | None = None
+ scouted_spine_repeated_identical_missing_steps: bool = False
# Author-time output-contract cross-turn state, keyed by the contract signature; set lazily by workflow_update.
output_contract_pinned_block_label_by_signature: dict[str, str] = field(default_factory=dict)
output_contract_reject_count_by_signature: dict[str, int] = field(default_factory=dict)
diff --git a/skyvern/forge/sdk/copilot/tools/credential_fill.py b/skyvern/forge/sdk/copilot/tools/credential_fill.py
index fd8aef126..f6ffefcd6 100644
--- a/skyvern/forge/sdk/copilot/tools/credential_fill.py
+++ b/skyvern/forge/sdk/copilot/tools/credential_fill.py
@@ -162,7 +162,11 @@ async def _resolve_credential_fill_value(
return None, "", f"Credential `{credential_id}` has no `{field}` value."
copilot_ctx.scouted_credential_field_inventory_by_credential_id[credential_id] = frozenset(
field_name
- for field_name, field_value in (("username", credential.username), ("password", credential.password))
+ for field_name, field_value in (
+ ("username", credential.username),
+ ("password", credential.password),
+ ("totp", credential.totp),
+ )
if field_value
)
return value, credential_item.name, None
diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.py
index bf2222aa0..181898e04 100644
--- a/skyvern/forge/sdk/copilot/tools/scouting.py
+++ b/skyvern/forge/sdk/copilot/tools/scouting.py
@@ -697,6 +697,8 @@ def _record_scouted_interaction(
selector=selector or None,
source_url=artifact.get("source_url"),
role=role or None,
+ credential_field=credential_field or None,
+ credential_id=credential_id or None,
total_scouted_interactions=len(ctx.scouted_interactions),
total_scout_trajectory=len(ctx.scout_trajectory),
)
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index 58437d8ed..fee0df361 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -8120,6 +8120,7 @@ class _SynthesizedCodeImpositionResult:
metadata_repair_contract: dict[str, object] | None = None
ablation_gate_id: str | None = None
never_captured_candidate: _NeverCapturedObligationCandidate | None = None
+ omission_digest: str | None = None
_SUBMITTED_LITERAL_METHODS = frozenset({"fill", "type"})
@@ -8337,17 +8338,33 @@ def _submitted_code_block_changed(block: Mapping[str, Any], prior_yaml: str | No
return True
-def _should_impose_after_update_attempt(ctx: AgentContext) -> bool:
+def _should_impose_after_update_attempt(ctx: AgentContext, *, repeated_identical_omission: bool = False) -> bool:
target = ctx.reached_download_target
return (
(isinstance(target, ReachedDownloadTarget) and not target.already_registered and bool(target.selector.strip()))
or synthesized_persistence_reopened_after_failed_run(ctx)
or ctx.synthesized_block_reopened_for_credential_scout
or ctx.synthesized_block_reopened_for_capture_obligation
+ or repeated_identical_omission
or _author_time_reject_reopens_synthesized_imposition(ctx)
)
+def _current_draft_repeats_prior_scouted_spine_omission(workflow_yaml: str, ctx: AgentContext) -> bool:
+ """The repeated-omission imposition arm admits only when the CURRENT draft still leaves the same
+ scouted-spine rungs open: recompute this draft's omission digest and require it non-empty and equal
+ to the immediately-prior reject's digest, so A,A,B never imposes on B off a latch set by a prior draft."""
+ if not ctx.scouted_spine_repeated_identical_missing_steps:
+ return False
+ current = _pre_persist_scouted_spine_result(workflow_yaml, ctx)
+ digest = current.omission_digest if current is not None else None
+ if digest is None or digest != ctx.scouted_spine_previous_omission_digest:
+ ctx.scouted_spine_repeated_identical_missing_steps = False
+ ctx.scouted_spine_previous_omission_digest = None
+ return False
+ return True
+
+
def _author_time_reject_reopens_synthesized_imposition(ctx: AgentContext) -> bool:
latest = ctx.latest_recorded_build_test_outcome
if not (
@@ -9720,6 +9737,28 @@ def _synthesized_resubmission_credential_scout_requirements(
return _credentialed_code_block_scout_gate_errors(probe_yaml, ctx)
+def _record_scouted_spine_omission_reject(ctx: AgentContext, digest: str | None) -> None:
+ if digest is not None and digest == ctx.scouted_spine_previous_omission_digest:
+ ctx.scouted_spine_repeated_identical_missing_steps = True
+ LOG.info("copilot_scouted_spine_repeated_identical_omission", omission_digest=digest)
+ else:
+ ctx.scouted_spine_repeated_identical_missing_steps = False
+ ctx.scouted_spine_previous_omission_digest = digest
+
+
+def _scouted_spine_omission_digest(records: Sequence[Mapping[str, Any]]) -> str:
+ items = sorted(
+ (
+ str(record.get("tool_name") or ""),
+ str(record.get("method") or ""),
+ str(record.get("selector") or record.get("locator") or ""),
+ str(record.get("trajectory_index")),
+ )
+ for record in records
+ )
+ return hashlib.sha256(json.dumps(items).encode()).hexdigest()
+
+
def _scouted_spine_under_build_result(
workflow_yaml: str,
*,
@@ -9783,6 +9822,7 @@ def _scouted_spine_under_build_result(
reason_code=_SCOUTED_SPINE_UNDER_BUILD_REASON_CODE,
selector=str(first_uncovered.get("selector") or "") or None,
),
+ omission_digest=_scouted_spine_omission_digest(uncovered),
)
# Non-uncovered partition findings are synthesizer-side: no draft edit closes them, so a
# repair-convergence-only site routes them to the turn-end obligation halt instead of a churn loop.
@@ -11498,7 +11538,12 @@ def _maybe_impose_synthesized_code_block(
# Goal-completeness gates on the requested-output plan, which materializes mid-turn, so keying availability on
# it would make ownership race the plan; reach is monotone in the scout's capture. Landing still closes the lane.
spine_landing_available = reaches_goal and not ctx.synthesized_goal_complete_landed
- if ctx.update_workflow_called and not spine_landing_available and not _should_impose_after_update_attempt(ctx):
+ repeated_identical_omission = _current_draft_repeats_prior_scouted_spine_omission(workflow_yaml, ctx)
+ if (
+ ctx.update_workflow_called
+ and not spine_landing_available
+ and not _should_impose_after_update_attempt(ctx, repeated_identical_omission=repeated_identical_omission)
+ ):
_log_imposition_skipped_after_update(ctx)
return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)
if ctx.update_workflow_called:
@@ -14212,6 +14257,7 @@ async def _update_workflow(
pre_persist_spine = _pre_persist_scouted_spine_result(workflow_yaml, ctx)
if pre_persist_spine is not None:
+ _record_scouted_spine_omission_reject(ctx, pre_persist_spine.omission_digest)
_set_code_authoring_repair_context(ctx, pre_persist_spine.repair_context)
_record_code_authoring_guardrail_reject(ctx)
return reject(
@@ -14297,6 +14343,8 @@ async def _update_workflow(
ctx.workflow_yaml = workflow_yaml
ctx.persisted_draft_browser_calls = _workflow_yaml_browser_call_pairs(workflow_yaml)
ctx.code_authoring_guardrail_reject_count = 0
+ ctx.scouted_spine_previous_omission_digest = None
+ ctx.scouted_spine_repeated_identical_missing_steps = False
ctx.last_code_authoring_reject_was_credential_priority = False
ctx.last_output_policy_reject_reason_codes = None
ctx.metadata_reject_ladder_state = None
diff --git a/tests/unit/google/test_google_oauth.py b/tests/unit/google/test_google_oauth.py
index 39069f88b..923f74371 100644
--- a/tests/unit/google/test_google_oauth.py
+++ b/tests/unit/google/test_google_oauth.py
@@ -239,8 +239,11 @@ async def test_google_drive_upload_does_not_retry_retryable_create_response(
return httpx.Response(503, headers={"Retry-After": "0"}, json={"error": {"message": "try later"}})
_install_google_drive_transport(monkeypatch, handler)
+ # Keep the backoff mock module-local so unrelated asyncio users cannot look like upload retries.
+ process_sleep = asyncio.sleep
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
+ assert asyncio.sleep is process_sleep
with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
await google_drive_service.upload_file(
@@ -272,7 +275,7 @@ async def test_google_drive_upload_retries_connection_failures_before_request(
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
uploaded = await google_drive_service.upload_file(
access_token="at-1",
@@ -301,7 +304,7 @@ async def test_google_drive_upload_does_not_retry_ambiguous_transport_failure(
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
await google_drive_service.upload_file(
@@ -661,7 +664,7 @@ async def test_google_drive_resumable_initiation_retries_connect_error(
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
uploaded = await google_drive_service.upload_file(
access_token="at-1",
@@ -692,7 +695,7 @@ async def test_google_drive_resumable_initiation_does_not_retry_read_timeout(
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
await google_drive_service.upload_file(
@@ -793,7 +796,7 @@ async def test_google_drive_resumable_requeries_offset_after_double_transport_fa
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
uploaded = await google_drive_service.upload_file(
access_token="at-1",
@@ -879,7 +882,7 @@ async def test_google_drive_resumable_resumes_after_chunk_429(
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
uploaded = await google_drive_service.upload_file(
access_token="at-1",
@@ -923,7 +926,7 @@ async def test_google_drive_resumable_resumes_after_chunk_rate_limit_403(
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
uploaded = await google_drive_service.upload_file(
access_token="at-1",
@@ -1090,7 +1093,7 @@ async def test_google_drive_resumable_non_advancing_308_bails(
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
await asyncio.wait_for(
@@ -1131,7 +1134,7 @@ async def test_google_drive_resumable_malformed_range_after_progress_does_not_re
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
await google_drive_service.upload_file(
@@ -1212,7 +1215,7 @@ async def test_google_drive_resumable_exhausts_attempts_raises(
_install_google_drive_transport(monkeypatch, handler)
sleep_mock = AsyncMock()
- monkeypatch.setattr(google_drive_service.asyncio, "sleep", sleep_mock)
+ monkeypatch.setattr(google_drive_service, "asyncio", SimpleNamespace(sleep=sleep_mock))
with pytest.raises(google_drive_service.GoogleDriveAPIError) as exc_info:
await google_drive_service.upload_file(
diff --git a/tests/unit/test_block_validate_code_only.py b/tests/unit/test_block_validate_code_only.py
index 2ac4dbfc9..6cc333090 100644
--- a/tests/unit/test_block_validate_code_only.py
+++ b/tests/unit/test_block_validate_code_only.py
@@ -5,6 +5,7 @@ from typing import Any
import pytest
+from skyvern.cli.mcp_tools._common import CODE_ONLY_POLICY_HINT
from skyvern.cli.mcp_tools.blocks import skyvern_block_validate
from skyvern.forge.sdk.copilot.tools.banned_blocks import collect_code_only_banned_items
@@ -18,12 +19,23 @@ def _navigation_block() -> dict[str, str]:
}
+def _assert_code_only_rejection(result: dict[str, Any], *, label: str) -> None:
+ assert result["ok"] is False
+ error = result["error"]
+ assert isinstance(error, dict)
+ assert "not allowed in code-only mode" in str(error["message"])
+ assert label in str(error["message"])
+ assert "use a `code` block" in str(error["hint"])
+ # Exact-string on purpose: the guidance text is the behavior surface under test — a
+ # keyword check would pass on inverted advice ("pass code_only=false to continue").
+ assert CODE_ONLY_POLICY_HINT in str(error["hint"])
+
+
@pytest.mark.asyncio
async def test_navigation_block_rejected_in_code_only_mode() -> None:
result = await skyvern_block_validate(json.dumps(_navigation_block()), code_only=True)
- assert result["ok"] is False
- assert "code-only" in result["error"]["message"].lower()
+ _assert_code_only_rejection(result, label="do_search")
@pytest.mark.asyncio
@@ -33,8 +45,7 @@ async def test_label_less_navigation_block_rejected_in_code_only_mode() -> None:
result = await skyvern_block_validate(json.dumps(block), code_only=True)
- assert result["ok"] is False
- assert "code-only" in result["error"]["message"].lower()
+ _assert_code_only_rejection(result, label="(unlabeled)")
@pytest.mark.asyncio
@@ -47,8 +58,7 @@ async def test_task_block_rejected_in_code_only_mode() -> None:
}
result = await skyvern_block_validate(json.dumps(block), code_only=True)
- assert result["ok"] is False
- assert "code-only" in result["error"]["message"].lower()
+ _assert_code_only_rejection(result, label="do_search")
@pytest.mark.asyncio
diff --git a/tests/unit/test_copilot_agent_blocker_renderer.py b/tests/unit/test_copilot_agent_blocker_renderer.py
index bfecdce3e..2ddfa9163 100644
--- a/tests/unit/test_copilot_agent_blocker_renderer.py
+++ b/tests/unit/test_copilot_agent_blocker_renderer.py
@@ -29,6 +29,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import (
build_definition_contract_unsatisfied_blocker_signal,
)
from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdict
+from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.context import AgentResult, CopilotContext, DeliveredUnverifiedPublicOutputs
from skyvern.forge.sdk.copilot.output_contracts import OutputContractAdvisoryState
from skyvern.forge.sdk.copilot.output_policy import (
@@ -955,6 +956,120 @@ def test_delivered_unverified_halt_without_workflow_renders_observed_output() ->
assert observed_outputs["result"] == ctx.delivered_unverified_observed_outputs["result"]
+def test_repair_ceiling_give_up_halt_names_demonstrated_missing_steps() -> None:
+ ctx = _ctx()
+ ctx.last_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=[SimpleNamespace()]))
+ ctx.last_workflow_yaml = "workflow_definition:\n blocks: []\n"
+ ctx.has_staged_proposal = True
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.impose_synthesized_code_block = True
+ ctx.persisted_draft_browser_calls = []
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "click",
+ "selector": "#search-submit",
+ "source_url": "https://example.com/search",
+ "trajectory_index": 0,
+ }
+ ]
+
+ result = _build_turn_halt_exit_result(
+ ctx,
+ global_llm_context=None,
+ halt=TurnHalt(kind=TurnHaltKind.REPAIR_CEILING_REACHED),
+ )
+
+ assert "#search-submit" in result.user_response
+
+
+def test_delivered_unverified_halt_names_demonstrated_missing_steps() -> None:
+ ctx = _ctx()
+ ctx.last_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=[SimpleNamespace()]))
+ ctx.last_workflow_yaml = "workflow_definition:\n blocks: []\n"
+ ctx.last_test_ok = True
+ ctx.delivered_unverified_terminal = True
+ ctx.delivered_unverified_observed_outputs = {"result": {"amount": 0}}
+ ctx.has_staged_proposal = True
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.impose_synthesized_code_block = True
+ ctx.persisted_draft_browser_calls = []
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "click",
+ "selector": "#search-submit",
+ "source_url": "https://example.com/search",
+ "trajectory_index": 0,
+ }
+ ]
+
+ result = _build_turn_halt_exit_result(
+ ctx,
+ global_llm_context=None,
+ halt=TurnHalt(kind=TurnHaltKind.DELIVERED_UNVERIFIED),
+ )
+
+ assert "#search-submit" in result.user_response
+
+
+def _scouted_obligation_ctx() -> CopilotContext:
+ ctx = _ctx()
+ ctx.last_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=[SimpleNamespace()]))
+ ctx.last_workflow_yaml = "workflow_definition:\n blocks: []\n"
+ ctx.has_staged_proposal = True
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.impose_synthesized_code_block = True
+ ctx.persisted_draft_browser_calls = []
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "click",
+ "selector": "#search-submit",
+ "source_url": "https://example.com/search",
+ "trajectory_index": 0,
+ }
+ ]
+ return ctx
+
+
+def test_timeout_wip_exit_names_demonstrated_missing_steps() -> None:
+ ctx = _scouted_obligation_ctx()
+
+ result = agent_module._build_timeout_exit_result(ctx, global_llm_context=None)
+
+ assert "#search-submit" in result.user_response
+
+
+def test_output_policy_blocked_result_names_demonstrated_missing_steps() -> None:
+ ctx = _scouted_obligation_ctx()
+ verdict = OutputPolicyVerdict(
+ allowed=False,
+ output_kind=CopilotOutputKind.REFUSAL,
+ reason_codes=[OutputPolicyReason.UNAPPROVED_CREDENTIAL_REFERENCE],
+ )
+
+ result = _build_output_policy_blocked_result(ctx, verdict, prior_global_llm_context=None, prior_workflow_yaml=None)
+
+ assert "#search-submit" in result.user_response
+
+
+def test_wip_exit_render_path_names_missing_steps_under_unrelated_blocker() -> None:
+ ctx = _scouted_obligation_ctx()
+ unrelated_reason = "I couldn't finish this after several attempts. Tell me what to change and I'll try again."
+ ctx.blocker_signal = CopilotToolBlockerSignal(
+ blocker_kind="authority_denied",
+ agent_steering_text="An unrelated blocker owns the turn.",
+ user_facing_reason=unrelated_reason,
+ recovery_hint="report_blocker_to_user",
+ internal_reason_code="output_contract_actuation_exhausted",
+ blocked_tool="update_workflow",
+ )
+
+ result = _build_wip_exit_result(ctx, None, default_reply="wip", unvalidated_reply="wip", tested_reply="wip")
+
+ assert "#search-submit" in result.user_response
+ assert result.user_response.count("This draft is still missing steps you demonstrated:") == 1
+ assert ctx.blocker_signal.user_facing_reason == unrelated_reason
+
+
def test_delivered_unverified_exit_prioritizes_nested_scalars_and_accounts_for_omissions() -> None:
ctx = _ctx()
ctx.last_workflow = SimpleNamespace(workflow_definition=SimpleNamespace(blocks=[SimpleNamespace()]))
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 84eb17633..fd06f54c8 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -1605,6 +1605,45 @@ class TestVerifiedGoalSatisfiedStop:
assert result.narrative_payload is not None
assert result.narrative_payload["verifiedSuccess"] is False
+ @pytest.mark.asyncio
+ async def test_built_unverified_terminal_names_demonstrated_missing_steps(self) -> None:
+ workflow = object()
+ ctx = _ctx(
+ last_workflow=workflow,
+ last_workflow_yaml="workflow_definition:\n blocks: []\n",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ latest_diagnosis_repair_contract=_unverified_no_repair_contract(),
+ completion_verification_result=CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0"],
+ verdicts=[
+ CriterionVerdict(
+ criterion_id="c0",
+ state="unsatisfied",
+ reason_code="structurally_abstained",
+ )
+ ],
+ ),
+ tool_activity=[{"tool": "update_and_run_blocks", "summary": "OK"}],
+ )
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.impose_synthesized_code_block = True
+ ctx.has_staged_proposal = True
+ ctx.persisted_draft_browser_calls = []
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "click",
+ "selector": "#search-submit",
+ "source_url": "https://example.com/search",
+ "trajectory_index": 0,
+ }
+ ]
+
+ result = await _build_built_unverified_exit_result(ctx, global_llm_context=None)
+
+ assert "#search-submit" in result.user_response
+
def test_corroborated_structural_abstention_avoids_built_unverified_terminal(self) -> None:
ctx = _ctx(
last_test_ok=True,
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index f9d616e36..4964c8f28 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -23983,3 +23983,146 @@ class TestDefinitionContractRecordedPacketReplay:
"I kept the workflow draft, but it does not yet satisfy the required workflow definition. "
"Complete the missing definition requirements before trying again."
)
+
+
+class TestScoutedSpineRepeatedOmissionSeam:
+ @staticmethod
+ def _uncovered_record(selector: str) -> dict[str, object]:
+ return {"tool_name": "click", "method": "click", "selector": selector, "trajectory_index": 1}
+
+ def test_two_consecutive_identical_omissions_set_repeated_flag(self) -> None:
+ ctx = _code_only_ctx()
+ digest = workflow_update_module._scouted_spine_omission_digest([self._uncovered_record("#submit")])
+ workflow_update_module._record_scouted_spine_omission_reject(ctx, digest)
+ assert ctx.scouted_spine_repeated_identical_missing_steps is False
+ assert ctx.scouted_spine_previous_omission_digest == digest
+ workflow_update_module._record_scouted_spine_omission_reject(ctx, digest)
+ assert ctx.scouted_spine_repeated_identical_missing_steps is True
+
+ def test_changed_omission_clears_repeated_flag(self) -> None:
+ ctx = _code_only_ctx()
+ first = workflow_update_module._scouted_spine_omission_digest([self._uncovered_record("#a")])
+ second = workflow_update_module._scouted_spine_omission_digest([self._uncovered_record("#b")])
+ workflow_update_module._record_scouted_spine_omission_reject(ctx, first)
+ workflow_update_module._record_scouted_spine_omission_reject(ctx, first)
+ assert ctx.scouted_spine_repeated_identical_missing_steps is True
+ workflow_update_module._record_scouted_spine_omission_reject(ctx, second)
+ assert ctx.scouted_spine_repeated_identical_missing_steps is False
+ assert ctx.scouted_spine_previous_omission_digest == second
+
+ def test_repeated_flag_reopens_imposition_for_attempt_three(self) -> None:
+ ctx = _code_only_ctx()
+ assert workflow_update_module._should_impose_after_update_attempt(ctx) is False
+ assert workflow_update_module._should_impose_after_update_attempt(ctx, repeated_identical_omission=True) is True
+
+ @staticmethod
+ def _omitting_draft() -> str:
+ return _freehand_block_yaml('print(await page.locator("body").inner_text())')
+
+ def test_two_consecutive_rejections_at_seam_force_attempt_three_impose_or_name(self) -> None:
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ draft = self._omitting_draft()
+
+ first = workflow_update_module._pre_persist_scouted_spine_result(draft, ctx)
+ assert first is not None
+ assert "#search-submit" in first.violations[0]
+ workflow_update_module._record_scouted_spine_omission_reject(ctx, first.omission_digest)
+ assert ctx.scouted_spine_repeated_identical_missing_steps is False
+
+ second = workflow_update_module._pre_persist_scouted_spine_result(draft, ctx)
+ assert second is not None
+ assert second.omission_digest == first.omission_digest
+ workflow_update_module._record_scouted_spine_omission_reject(ctx, second.omission_digest)
+ assert ctx.scouted_spine_repeated_identical_missing_steps is True
+
+ assert workflow_update_module._current_draft_repeats_prior_scouted_spine_omission(draft, ctx) is True
+ assert workflow_update_module._should_impose_after_update_attempt(ctx, repeated_identical_omission=True) is True
+ third = workflow_update_module._pre_persist_scouted_spine_result(draft, ctx)
+ assert third is not None
+ assert "#search-submit" in third.violations[0]
+
+ @pytest.mark.asyncio
+ async def test_third_differing_draft_not_admitted_after_two_identical_omissions(self) -> None:
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "type_text",
+ "selector": "#a",
+ "source_url": "https://example.com/records",
+ "trajectory_index": 0,
+ },
+ {
+ "tool_name": "type_text",
+ "selector": "#b",
+ "source_url": "https://example.com/records",
+ "trajectory_index": 1,
+ },
+ ]
+ omitting = _freehand_block_yaml('await page.goto("https://example.com/records", wait_until="domcontentloaded")')
+ ctx.update_workflow_called = True
+
+ first = await _update_workflow({"workflow_yaml": omitting}, ctx)
+ assert first["ok"] is False
+ assert ctx.scouted_spine_repeated_identical_missing_steps is False
+
+ second = await _update_workflow({"workflow_yaml": omitting}, ctx)
+ assert second["ok"] is False
+ assert ctx.scouted_spine_repeated_identical_missing_steps is True
+ latched_digest = ctx.scouted_spine_previous_omission_digest
+ assert latched_digest is not None
+
+ differing = _freehand_block_yaml('await page.locator("#a").fill("x")')
+ assert ctx.scouted_spine_previous_omission_digest == latched_digest
+ assert workflow_update_module._current_draft_repeats_prior_scouted_spine_omission(omitting, ctx) is True
+ assert workflow_update_module._current_draft_repeats_prior_scouted_spine_omission(differing, ctx) is False
+
+ third = await _update_workflow({"workflow_yaml": differing}, ctx)
+ assert third["ok"] is False
+ assert ctx.spine_imposition_owned_attempt is False
+ assert ctx.scouted_spine_previous_omission_digest != latched_digest
+
+ def test_returning_omission_after_differing_draft_does_not_misfire_imposition(self) -> None:
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "type_text",
+ "selector": "#a",
+ "source_url": "https://example.com/records",
+ "trajectory_index": 0,
+ },
+ {
+ "tool_name": "type_text",
+ "selector": "#b",
+ "source_url": "https://example.com/records",
+ "trajectory_index": 1,
+ },
+ ]
+ omitting = _freehand_block_yaml('await page.goto("https://example.com/records", wait_until="domcontentloaded")')
+ differing = _freehand_block_yaml('await page.locator("#a").fill("x")')
+ omitting_result = workflow_update_module._pre_persist_scouted_spine_result(omitting, ctx)
+ assert omitting_result is not None
+ ctx.scouted_spine_repeated_identical_missing_steps = True
+ ctx.scouted_spine_previous_omission_digest = omitting_result.omission_digest
+
+ assert workflow_update_module._current_draft_repeats_prior_scouted_spine_omission(differing, ctx) is False
+ assert ctx.scouted_spine_repeated_identical_missing_steps is False
+ assert workflow_update_module._current_draft_repeats_prior_scouted_spine_omission(omitting, ctx) is False
+
+ def test_identical_resubmission_no_op_still_names_at_persist_seam(self) -> None:
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ draft = self._omitting_draft()
+ ctx.update_workflow_called = True
+ ctx.last_workflow_yaml = draft
+ ctx.scouted_spine_repeated_identical_missing_steps = True
+
+ imposition = workflow_update_module._maybe_impose_synthesized_code_block(draft, ctx)
+ assert ctx.spine_imposition_owned_attempt is False
+ assert imposition.violations == []
+
+ naming = workflow_update_module._pre_persist_scouted_spine_result(draft, ctx)
+ assert naming is not None
+ assert "#search-submit" in naming.violations[0]
diff --git a/tests/unit/test_copilot_enforcement_hardening.py b/tests/unit/test_copilot_enforcement_hardening.py
index a6199b2d1..0c47fb14b 100644
--- a/tests/unit/test_copilot_enforcement_hardening.py
+++ b/tests/unit/test_copilot_enforcement_hardening.py
@@ -21,12 +21,18 @@ from typing import Any
import pytest
+from skyvern.forge.sdk.copilot.agent import (
+ _finalize_result_with_blocker_override,
+ _with_scouted_spine_missing_steps,
+)
from skyvern.forge.sdk.copilot.blocker_signal import (
CopilotToolBlockerSignal,
clear_terminal_evidence_on_workflow_edit,
maybe_clear_blocker_signal_on_tool_success,
)
-from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.copilot.code_block_synthesis import UNFORGIVEN_DROP_FINDING, ObligationFinding
+from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
+from skyvern.forge.sdk.copilot.context import AgentResult, CopilotContext
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
DiagnosisInput,
DiagnosisRepairContract,
@@ -56,6 +62,7 @@ from skyvern.forge.sdk.copilot.enforcement import (
_prune_input_list,
_record_code_authoring_guardrail_reject,
_recover_from_context_overflow,
+ _scouted_spine_missing_text,
_strip_input_images,
register_no_progress_interaction_click,
reset_no_progress_interaction_count,
@@ -64,12 +71,14 @@ from skyvern.forge.sdk.copilot.enforcement import (
from skyvern.forge.sdk.copilot.output_contracts import OutputContractAdvisoryState
from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODE
from skyvern.forge.sdk.copilot.streaming_adapter import _update_enforcement_from_tool
+from skyvern.forge.sdk.copilot.tools.workflow_update import _pre_persist_scouted_spine_result
from skyvern.forge.sdk.copilot.turn_halt import (
ADVISORY_DISPATCH_STALLED_REASON_CODE,
CopilotTurnHalt,
TurnHaltKind,
expire_output_contract_ladder_at_turn_end,
)
+from skyvern.forge.sdk.copilot.turn_ownership import TurnClaimant
from tests.unit.conftest import make_copilot_context as _fresh_context
# ---------------------------------------------------------------------------
@@ -847,3 +856,117 @@ def test_single_captured_interaction_trajectory_never_reaches_goal() -> None:
]
assert synthesized_trajectory_reaches_goal(ctx) is False
+
+
+def test_scouted_spine_missing_text_renders_non_uncovered_families() -> None:
+ dropped = ObligationFinding(
+ kind=UNFORGIVEN_DROP_FINDING,
+ record={"tool_name": "fill_credential_field", "reason_code": "strict_selector", "trajectory_index": 2},
+ )
+ text = _scouted_spine_missing_text([dropped])
+ assert text
+ assert "fill_credential_field" in text
+
+
+def test_missing_steps_listed_on_give_up_offer_and_anchored_in_held_signal() -> None:
+ ctx = _fresh_context()
+ ctx.has_staged_proposal = True
+ ctx.blocker_signal = CopilotToolBlockerSignal(
+ blocker_kind="loop_detected",
+ agent_steering_text="The repair made no progress.",
+ user_facing_reason="I kept the draft.",
+ recovery_hint="report_blocker_to_user",
+ internal_reason_code="repair_ceiling_reached",
+ blocked_tool="update_workflow",
+ )
+ reply = _with_scouted_spine_missing_steps(ctx, "I kept the draft.", "`fill` on '#totp'")
+ assert "`fill` on '#totp'" in reply
+ assert "`fill` on '#totp'" in ctx.blocker_signal.user_facing_reason
+
+
+def test_missing_steps_not_appended_without_staged_proposal() -> None:
+ ctx = _fresh_context()
+ ctx.has_staged_proposal = False
+ assert _with_scouted_spine_missing_steps(ctx, "base", "`fill` on '#totp'") == "base"
+
+
+def _unrelated_owner_give_up_ctx(internal_reason_code: str) -> tuple[CopilotContext, str]:
+ ctx = _fresh_context()
+ ctx.has_staged_proposal = True
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.impose_synthesized_code_block = True
+ ctx.persisted_draft_browser_calls = []
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "click",
+ "selector": "#search-submit",
+ "source_url": "https://example.com/search",
+ "trajectory_index": 0,
+ }
+ ]
+ unrelated_reason = "I couldn't finish this after several attempts. Tell me what to change and I'll try again."
+ ctx.blocker_signal = CopilotToolBlockerSignal(
+ blocker_kind="authority_denied",
+ agent_steering_text="An unrelated blocker owns the turn.",
+ user_facing_reason=unrelated_reason,
+ recovery_hint="report_blocker_to_user",
+ internal_reason_code=internal_reason_code,
+ blocked_tool="update_workflow",
+ )
+ ctx.blocker_signal_claimant = TurnClaimant.OUTPUT_CONTRACT_ACTUATION
+ return ctx, unrelated_reason
+
+
+def test_finalizer_names_missing_steps_when_unrelated_blocker_renders_give_up() -> None:
+ ctx, unrelated_reason = _unrelated_owner_give_up_ctx("output_contract_actuation_exhausted")
+ result = AgentResult(user_response="agent prose", updated_workflow=None, global_llm_context=None)
+
+ overridden = _finalize_result_with_blocker_override(ctx, result, exit_site="test")
+
+ assert "#search-submit" in overridden.user_response
+ assert ctx.blocker_signal.user_facing_reason == unrelated_reason
+ assert ctx.blocker_signal_claimant is TurnClaimant.OUTPUT_CONTRACT_ACTUATION
+
+
+ "internal_reason_code",
+ ["repair_ceiling_reached", "completion_contract_unsatisfied", "output_contract_actuation_exhausted"],
+)
+def test_finalizer_render_exit_names_missing_steps_per_owner(internal_reason_code: str) -> None:
+ ctx, unrelated_reason = _unrelated_owner_give_up_ctx(internal_reason_code)
+ result = AgentResult(user_response="agent prose", updated_workflow=None, global_llm_context=None)
+
+ overridden = _finalize_result_with_blocker_override(ctx, result, exit_site="test")
+
+ assert "#search-submit" in overridden.user_response
+ assert overridden.user_response.count("This draft is still missing steps you demonstrated:") == 1
+ assert ctx.blocker_signal.user_facing_reason == unrelated_reason
+ assert ctx.blocker_signal_claimant is TurnClaimant.OUTPUT_CONTRACT_ACTUATION
+
+
+def test_same_omission_spine_violation_still_refused_after_change() -> None:
+ ctx = _fresh_context()
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.impose_synthesized_code_block = True
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "click",
+ "selector": "#search-submit",
+ "source_url": "https://example.com/search",
+ "trajectory_index": 0,
+ }
+ ]
+ omitting_draft = (
+ "title: t\n"
+ "workflow_definition:\n"
+ " blocks:\n"
+ " - block_type: code\n"
+ " label: report_only\n"
+ " code: |\n"
+ ' print(await page.locator("body").inner_text())\n'
+ )
+ result = _pre_persist_scouted_spine_result(omitting_draft, ctx)
+ assert result is not None
+ assert result.repair_context is not None
+ assert result.repair_context.reason_code == "scouted_spine_under_build"
+ assert "#search-submit" in result.violations[0]
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index 721479308..626660bb1 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -1162,6 +1162,32 @@ class TestSynthesizedOfferPersistenceGate:
assert ctx.synthesized_block_offered_trajectory_len == len(trajectory)
assert ctx.synthesized_block_offered_goal_complete is True
+ def test_offer_names_missing_steps_when_obligation_open_regardless_of_repeated_flag(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement.synthesize_code_block",
+ lambda *args, **kwargs: SynthesizedCodeBlock(code="await page.click('button')"),
+ )
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.enforcement._get_scouted_spine_missing_steps_for_halt",
+ lambda ctx: "`click` on '#search-submit'",
+ )
+ trajectory = [
+ {"tool_name": "click", "selector": "a.home", "accessible_name": "Home"},
+ {"tool_name": "type_text", "selector": "input[name='q']", "accessible_name": "Search"},
+ {"tool_name": "click", "selector": "button[data-action='search']", "accessible_name": "Search"},
+ ]
+ ctx = self._authoring_ctx(trajectory=trajectory, download_target=None)
+ ctx.synthesized_block_offered = True
+ ctx.synthesized_block_offered_trajectory_len = 2
+ ctx.synthesized_block_offered_goal_complete = False
+
+ message = _maybe_synthesized_block_offer_msg(ctx)
+
+ assert message is not None
+ assert "#search-submit" in message["content"]
+
def test_goal_complete_offer_refresh_suppresses_near_duplicate_followup(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
diff --git a/tests/unit/test_copilot_fill_credential_field.py b/tests/unit/test_copilot_fill_credential_field.py
index 49acf9dd7..aec11953f 100644
--- a/tests/unit/test_copilot_fill_credential_field.py
+++ b/tests/unit/test_copilot_fill_credential_field.py
@@ -145,6 +145,38 @@ class TestResolveCredentialFillValue:
"cred_123": frozenset({"username", "password"})
}
+ @pytest.mark.asyncio
+ async def test_resolve_inventory_includes_totp_when_seed_present(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ self._wire_vault(
+ monkeypatch,
+ PasswordCredential(username=_FAKE_USERNAME, password=_FAKE_PASSWORD, totp=_FAKE_TOTP_SEED),
+ )
+ ctx = _ctx()
+ _, _, error = await tools_module._resolve_credential_fill_value(ctx, "cred_123", "username")
+ assert error is None
+ assert ctx.scouted_credential_field_inventory_by_credential_id == {
+ "cred_123": frozenset({"username", "password", "totp"})
+ }
+
+ @pytest.mark.asyncio
+ async def test_resolve_inventory_excludes_totp_for_runtime_only_otp(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ self._wire_vault(
+ monkeypatch,
+ PasswordCredential(
+ username=_FAKE_USERNAME,
+ password=_FAKE_PASSWORD,
+ totp=None,
+ totp_type=TotpType.EMAIL,
+ totp_identifier="[email protected]",
+ ),
+ )
+ ctx = _ctx()
+ _, _, error = await tools_module._resolve_credential_fill_value(ctx, "cred_123", "username")
+ assert error is None
+ assert ctx.scouted_credential_field_inventory_by_credential_id == {
+ "cred_123": frozenset({"username", "password"})
+ }
+
@pytest.mark.asyncio
async def test_resolve_inventory_excludes_empty_password(self, monkeypatch: pytest.MonkeyPatch) -> None:
self._wire_vault(monkeypatch, PasswordCredential(username=_FAKE_USERNAME, password="", totp=None))
diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.py
index 10e3f770c..2f0085957 100644
--- a/tests/unit/test_copilot_scout_act_observe.py
+++ b/tests/unit/test_copilot_scout_act_observe.py
@@ -1681,6 +1681,25 @@ class TestTerminalActionObservationStampSeam:
assert ctx.scout_observed_terminal_criterion_ids == {"start_service_request"}
assert [log for log in logs if log["event"] == "copilot_reached_terminal_action_observed"]
+ def test_demonstrated_totp_fill_is_recorded_with_a_countable_capture_log(self) -> None:
+ ctx = self._ctx_with(self._terminal_action_criterion())
+ ctx.scout_trajectory = []
+ with capture_logs() as logs:
+ scouting_module._record_scouted_interaction(
+ ctx,
+ tool_name="fill_credential_field",
+ selector="#totpCode",
+ source_url=self._PORTAL_URL,
+ typed_length=6,
+ credential_id="cred_1",
+ credential_field="totp",
+ credential_name="mock-portal-login-totp",
+ )
+ assert ctx.scout_trajectory[-1]["credential_field"] == "totp"
+ capture = next(log for log in logs if log["event"] == "copilot_scout_interaction_captured")
+ assert capture["credential_field"] == "totp"
+ assert capture["credential_id"] == "cred_1"
+
def test_login_only_commit_stamps_nothing(self) -> None:
ctx = self._ctx_with(self._terminal_action_criterion())
ctx.scout_trajectory = [
diff --git a/tests/unit/test_mcp_workflow_guidance.py b/tests/unit/test_mcp_workflow_guidance.py
index f7641bc34..07593bbe6 100644
--- a/tests/unit/test_mcp_workflow_guidance.py
+++ b/tests/unit/test_mcp_workflow_guidance.py
@@ -4,10 +4,11 @@ import inspect
import pytest
+import skyvern.cli.mcp_tools._common as mcp_common
from skyvern.cli.mcp_tools import mcp
from skyvern.cli.mcp_tools.blocks import skyvern_block_schema
from skyvern.cli.mcp_tools.inspection import skyvern_get_html
-from skyvern.cli.mcp_tools.prompts import BUILD_WORKFLOW_CONTENT
+from skyvern.cli.mcp_tools.prompts import BUILD_WORKFLOW_CONTENT, EXTRACT_DATA_CONTENT
from skyvern.cli.mcp_tools.session import skyvern_browser_session_create, skyvern_browser_session_list
from skyvern.cli.mcp_tools.workflow import (
skyvern_workflow_create,
@@ -39,6 +40,19 @@ def test_mcp_instructions_guide_text_prompt_defaults() -> None:
assert "skyvern_observe" in mcp.instructions
+def test_workflow_create_guides_code_only_policy() -> None:
+ assert mcp_common.CODE_ONLY_SCHEMA_GUIDANCE in (skyvern_workflow_create.__doc__ or "")
+
+
+def test_mcp_instructions_guide_code_only_policy() -> None:
+ assert mcp_common.CODE_ONLY_SCHEMA_GUIDANCE in mcp.instructions
+
+
+def test_workflow_prompts_guide_code_only_policy_at_each_authoring_surface() -> None:
+ assert BUILD_WORKFLOW_CONTENT.count(mcp_common.CODE_ONLY_SCHEMA_GUIDANCE) == 2
+ assert EXTRACT_DATA_CONTENT.count(mcp_common.CODE_ONLY_SCHEMA_GUIDANCE) == 1
+
+
@pytest.mark.asyncio
async def test_expected_prompts_registered() -> None:
prompts = await mcp.list_prompts()
diff --git a/tests/unit/test_workflow_persist_code_only.py b/tests/unit/test_workflow_persist_code_only.py
index 3db8c7124..95ee127b8 100644
--- a/tests/unit/test_workflow_persist_code_only.py
+++ b/tests/unit/test_workflow_persist_code_only.py
@@ -6,8 +6,11 @@ from unittest.mock import AsyncMock
import pytest
import yaml
+from fastmcp.tools import FunctionTool
import skyvern.cli.mcp_tools.workflow as workflow_tools
+from skyvern.cli.mcp_tools import mcp
+from skyvern.cli.mcp_tools._common import CODE_ONLY_FIELD_DESCRIPTION, CODE_ONLY_POLICY_HINT
from tests.unit._mcp_test_helpers import patch_get_workflow_by_id as _patch_get_workflow_by_id
from tests.unit._mcp_test_helpers import patch_skyvern_client as _patch_skyvern_client
@@ -112,6 +115,22 @@ def _assert_code_only_rejection(result: dict[str, object], *, label: str) -> Non
assert "not allowed in code-only mode" in str(error["message"])
assert label in str(error["message"])
assert "use a `code` block" in str(error["hint"])
+ # Exact-string on purpose: the guidance text is the behavior surface under test — a
+ # keyword check would pass on inverted advice ("pass code_only=false to continue").
+ assert CODE_ONLY_POLICY_HINT in str(error["hint"])
+
+
+async def test_registered_code_only_tool_schemas_are_nullable_without_false_default() -> None:
+ tools = {tool.name: tool for tool in await mcp.list_tools()}
+
+ for tool_name in ("skyvern_block_validate", "skyvern_workflow_create", "skyvern_workflow_update"):
+ tool = tools[tool_name]
+ assert isinstance(tool, FunctionTool)
+ code_only_schema = tool.parameters["properties"]["code_only"]
+ assert {choice["type"] for choice in code_only_schema["anyOf"]} == {"boolean", "null"}
+ assert code_only_schema.get("default") is None
+ assert code_only_schema["description"] == CODE_ONLY_FIELD_DESCRIPTION
@pytest.mark.asyncio