Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-10983 gate run credentials before dispatch (#6549)
Andrew Neilson6d84d5931b80
diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.pyindex 0e2af2583..2c3137183 100644--- a/skyvern/forge/sdk/copilot/blocker_signal.py+++ b/skyvern/forge/sdk/copilot/blocker_signal.py@@ -210,6 +210,7 @@ _LOOP_PROGRESS_TOOLS = frozenset(})_ACTIVE_TERMINAL_REPLACEABLE_REASON_CODES = frozenset({"tool_error_per_tool_budget_rerun"})+_TERMINAL_CHALLENGE_REPLACEABLE_REASON_CODES = frozenset({"tool_error_post_budget_challenge_result_evidence"})def _should_stash_over_existing(@@ -223,6 +224,11 @@ def _should_stash_over_existing(and existing.internal_reason_code in _ACTIVE_TERMINAL_REPLACEABLE_REASON_CODES):return True+ if (+ incoming.internal_reason_code == "tool_error_post_budget_challenge_blocker"+ and existing.internal_reason_code in _TERMINAL_CHALLENGE_REPLACEABLE_REASON_CODES+ ):+ return Truereturn Falsediff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex 17d86b93f..59ca7a3f1 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -488,6 +488,7 @@ def build_artifact_metadata_skeleton("status": "observed_not_verified","depends_on": [dependency_id],"covered_criteria": [_FILL_CRITERION_ID],+ "goal_value_paths": ["<fill: output JSON path(s) carrying requested goal values>"],"observation_refs": [observation_ref_id],}],@@ -504,6 +505,7 @@ def build_artifact_metadata_skeleton("id": "expectation:<fill>","text": "<fill: what terminal verification must observe>","criteria_ids": [_FILL_CRITERION_ID],+ "goal_value_paths": ["<fill: output JSON path(s) carrying requested goal values>"],}],}@@ -552,6 +554,7 @@ def render_synthesized_offer_text(parts.append("Pass this `code_artifact_metadata` for the block (the scouted page evidence is filled in; ""replace the `<fill: ...>` slots with the terminal goal and outcome this block delivers, then "+ "include `goal_value_paths` for the output JSON fields carrying requested goal values, then ""submit it whole — the validator returns every remaining violation at once):")parts.append("```json")diff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.pyindex a91843324..e0a0c963f 100644--- a/skyvern/forge/sdk/copilot/composition_browser_expressions.py+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py@@ -329,15 +329,32 @@ for (const link of document.querySelectorAll('a[href]')) {}const resultContainers = [];-for (const node of all) {- if (resultContainers.length >= MAX_RESULT_CONTAINERS) break;- const tag = (node.tagName || '').toLowerCase();- if (SKIP_TAGS.has(tag)) continue;- const identity = (attr(node, 'id') + ' ' + classesFor(node).join(' ')).toLowerCase();- if (tag === 'table' || RESULT_CONTAINER_HINTS.some((h) => identity.includes(h))) {- resultContainers.push({ tag: tag, id: attr(node, 'id'), selector: selectorFor(node), is_table: tag === 'table' });- }-}+const resultRowTextIsContent = (s) => {+ const text = lower(String(s || '').replace(/\s+/g, ' ').trim());+ return !!text && !['0 results', 'no matching records', 'no records found', 'no results', 'no results found', 'nothing found'].some((p) => text.includes(p));+};+const resultEntry = (node, tag) => {+ const entry = { tag: tag, id: attr(node, 'id'), selector: selectorFor(node), is_table: tag === 'table' };+ if (tag === 'table') {+ let rows = Array.from(node.querySelectorAll('tbody tr')).filter((r) => r.querySelector('td'));+ if (!rows.length) rows = Array.from(node.querySelectorAll('tr')).filter((r) => r.querySelector('td'));+ const sampleRows = rows.map((r) => Array.from(r.children || []).map((c) => nodeText(c)).filter(Boolean).join(' ') || nodeText(r)).filter(resultRowTextIsContent).slice(0, 5);+ if (sampleRows.length) { entry.row_count = sampleRows.length; entry.sample_rows = sampleRows; }+ } else {+ const text = nodeText(node);+ if (text) entry.text_excerpt = text;+ }+ return entry;+ };+ for (const node of all) {+ if (resultContainers.length >= MAX_RESULT_CONTAINERS) break;+ const tag = (node.tagName || '').toLowerCase();+ if (SKIP_TAGS.has(tag)) continue;+ const identity = (attr(node, 'id') + ' ' + classesFor(node).join(' ')).toLowerCase();+ if (tag === 'table' || RESULT_CONTAINER_HINTS.some((h) => identity.includes(h))) {+ resultContainers.push(resultEntry(node, tag));+ }+ }const challengeControls = [];const seenChallenge = new Set();diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.pyindex ea9bd557f..0baf3119f 100644--- a/skyvern/forge/sdk/copilot/composition_evidence.py+++ b/skyvern/forge/sdk/copilot/composition_evidence.py@@ -79,6 +79,16 @@ _ANTI_BOT_PATTERNS = ("access denied","are you a robot",)+_EMPTY_RESULT_TEXT_PATTERNS: frozenset[str] = frozenset(+ {+ "0 results",+ "no matching records",+ "no records found",+ "no results",+ "no results found",+ "nothing found",+ }+)_MAX_VISUAL_SUMMARY_CHARS = 500_MAX_VISUAL_OMISSIONS = 5_ANTI_BOT_SCAN_BYTES = 250_000@@ -1350,6 +1360,11 @@ def _page_title(soup: Any) -> str:return " ".join(parts)[:240]+def _result_row_text_is_content(text: str) -> bool:+ normalized = " ".join(text.lower().split())+ return bool(normalized) and not any(pattern in normalized for pattern in _EMPTY_RESULT_TEXT_PATTERNS)++def _result_container_entry(node: Any) -> dict[str, Any]:tag_name = str(getattr(node, "name", "") or "").lower()node_id = str(node.get("id") or "")@@ -1368,6 +1383,18 @@ def _result_container_entry(node: Any) -> dict[str, Any]:f"{selector} tbody tr a",f"{selector} tbody tr td:first-child",]+ data_rows = [row for row in node.select("tbody tr") if row.find("td") is not None]+ if not data_rows:+ data_rows = [row for row in node.select("tr") if row.find("td") is not None]+ sample_rows = [_schema_text(_node_text(row), 240) for row in data_rows]+ sample_rows = [row for row in sample_rows if _result_row_text_is_content(row)][:5]+ if sample_rows:+ entry["row_count"] = len(sample_rows)+ entry["sample_rows"] = sample_rows+ else:+ text_excerpt = _schema_text(_node_text(node), 240)+ if text_excerpt:+ entry["text_excerpt"] = text_excerptreturn entry@@ -1827,6 +1854,23 @@ def _structured_result_containers(value: Any) -> list[dict[str, Any]]:"id": _structured_str(node.get("id"))[:120],"selector": selector,}+ sample_rows = [+ _schema_text(_structured_str(row), 240)+ for row in (node.get("sample_rows") or [])+ if isinstance(row, str) and _result_row_text_is_content(row)+ ][:5]+ if sample_rows:+ row_count = node.get("row_count")+ entry["row_count"] = row_count if isinstance(row_count, int) and row_count > 0 else len(sample_rows)+ entry["sample_rows"] = sample_rows+ text_excerpt = _schema_text(+ _structured_str(+ node.get("text_excerpt") or node.get("content_excerpt") or node.get("sample_text") or node.get("text")+ ),+ 240,+ )+ if text_excerpt:+ entry["text_excerpt"] = text_excerptif tag_name == "table" or node.get("is_table") is True:entry["row_selector"] = f"{selector} tbody tr"entry["expand_toggle_candidates"] = [diff --git a/skyvern/forge/sdk/copilot/tools/blockers.py b/skyvern/forge/sdk/copilot/tools/blockers.pyindex 0e56f2f30..6eb2fc5c7 100644--- a/skyvern/forge/sdk/copilot/tools/blockers.py+++ b/skyvern/forge/sdk/copilot/tools/blockers.py@@ -1,6 +1,7 @@from __future__ import annotationsimport json+import refrom collections.abc import Mappingfrom typing import Any@@ -394,6 +395,260 @@ def _post_run_result_evidence_summary(evidence: dict[str, Any]) -> str | None:return f"{len(containers)} result container(s){hint_text}"+_POST_BUDGET_CHALLENGE_RESULT_EVIDENCE_REASON = "tool_error_post_budget_challenge_result_evidence"+_POST_BUDGET_CHALLENGE_BLOCKER_REASON = "tool_error_post_budget_challenge_blocker"+_CHALLENGE_STOP_TERMS = frozenset(+ {+ "anti bot",+ "anti-bot",+ "captcha",+ "challenge",+ "disabled search",+ "disabled submit",+ "human verification",+ "turnstile",+ "verification",+ }+)+_VISIBLE_TEXT_CHROME_TOKENS = frozenset(+ {+ "and",+ "are",+ "bot",+ "button",+ "captcha",+ "challenge",+ "clear",+ "control",+ "disabled",+ "enter",+ "first",+ "form",+ "full",+ "human",+ "last",+ "lookup",+ "name",+ "reset",+ "search",+ "select",+ "state",+ "submit",+ "verification",+ "verify",+ "you",+ "your",+ }+)+_RESULT_CONTAINER_CHROME_TOKENS = _VISIBLE_TEXT_CHROME_TOKENS | frozenset(+ {"found", "matching", "record", "records", "result", "results"}+)+++def _safe_signature_text(value: Any, max_chars: int = 180) -> str:+ text = "" if value is None else str(value).strip()+ return text[:max_chars]+++def _signature_json(value: Any) -> str:+ return json.dumps(value, sort_keys=True, separators=(",", ":"), default=str)+++def _diagnosis_stop_has_challenge_evidence(ctx: Any, reason: str) -> bool:+ contract = getattr(ctx, "latest_diagnosis_repair_contract", None)+ repair_decision = getattr(contract, "repair_decision", None)+ if _enum_or_string_name(getattr(repair_decision, "next_action", None)) != "stop":+ return False++ diagnosis_input = getattr(contract, "diagnosis_input", None)+ diagnosis_result = getattr(contract, "diagnosis_result", None)+ verification_result = getattr(contract, "verification_result", None)+ categories = getattr(diagnosis_input, "failure_categories", None)+ category_text = (+ " ".join(str(category) for category in categories if category) if isinstance(categories, list) else ""+ )+ haystack = " ".join(+ part+ for part in (+ reason,+ category_text,+ _enum_or_string_name(getattr(diagnosis_result, "suspected_failure_type", None)),+ getattr(diagnosis_result, "root_cause_summary", None),+ getattr(verification_result, "remaining_blocker", None),+ getattr(ctx, "last_test_anti_bot", None),+ )+ if isinstance(part, str) and part+ )+ normalized = haystack.replace("_", " ").lower()+ return any(term in normalized for term in _CHALLENGE_STOP_TERMS)+++def _challenge_control_signature(control: dict[str, Any]) -> dict[str, Any]:+ return {+ "label": _composition_control_label(control),+ "disabled": control.get("disabled") is True,+ }+++def _post_budget_challenge_signature(evidence: dict[str, Any], reason: str) -> str:+ challenge_state = evidence.get("challenge_state")+ challenge = challenge_state if isinstance(challenge_state, dict) else {}+ gated_controls = [+ _challenge_control_signature(control)+ for control in challenge.get("gated_submit_controls") or []+ if isinstance(control, dict)+ ]+ disabled_controls = [+ _challenge_control_signature(control) for control in _disabled_submit_controls_from_evidence(evidence)+ ]+ return _signature_json(+ {+ "reason": reason,+ "challenge": {+ "detected": challenge.get("detected") is True,+ "gates_submit_controls": challenge.get("gates_submit_controls") is True,+ "kind": _safe_signature_text(challenge.get("kind"), 80),+ "requires_human_verification": challenge.get("requires_human_verification") is True,+ },+ "disabled_submit_controls": sorted(disabled_controls, key=lambda item: item["label"]),+ "gated_submit_controls": sorted(gated_controls, key=lambda item: item["label"]),+ }+ )+++def _post_budget_result_evidence_signature(evidence: dict[str, Any], result_evidence: str) -> str:+ containers = [container for container in evidence.get("result_containers") or [] if isinstance(container, dict)]+ normalized_containers: list[dict[str, Any]] = []+ for container in containers[:5]:+ normalized_containers.append(+ {+ "id": _safe_signature_text(container.get("id"), 120),+ "row_count": container.get("row_count") if isinstance(container.get("row_count"), int) else None,+ "selector": _safe_signature_text(container.get("selector"), 160),+ "tag": _safe_signature_text(container.get("tag"), 40),+ }+ )+ return _signature_json({"containers": normalized_containers, "summary": result_evidence})+++def _result_container_has_content(container: dict[str, Any]) -> bool:+ row_count = container.get("row_count")+ if isinstance(row_count, int) and row_count > 0:+ return True+ for key in ("sample_rows", "rows", "items"):+ value = container.get(key)+ if isinstance(value, list) and _is_meaningful_extracted_data(value):+ return True+ for key in ("content_excerpt", "sample_text", "text", "text_excerpt", "visible_results_evidence"):+ value = container.get(key)+ if isinstance(value, str):+ tokens = {token for token in re.findall(r"[a-z0-9]{2,}", value.lower()) if token}+ if tokens - set(_RESULT_CONTAINER_CHROME_TOKENS):+ return True+ continue+ if value:+ return True+ return False+++def _visible_text_excerpt_has_result_content(evidence: dict[str, Any]) -> bool:+ text = evidence.get("visible_text_excerpt")+ if not isinstance(text, str) or not text.strip():+ return False+ tokens = {token for token in re.findall(r"[a-z0-9]{2,}", text.lower()) if token}+ if not tokens:+ return False+ control_tokens: set[str] = set(_VISIBLE_TEXT_CHROME_TOKENS)+ for form in evidence.get("forms") or []:+ if not isinstance(form, dict):+ continue+ for field in form.get("fields") or []:+ if not isinstance(field, dict):+ continue+ for key in ("label", "name", "placeholder", "value"):+ value = field.get(key)+ if isinstance(value, str):+ control_tokens.update(re.findall(r"[a-z0-9]{2,}", value.lower()))+ for option in field.get("options") or []:+ if isinstance(option, dict):+ for key in ("text", "value"):+ value = option.get(key)+ if isinstance(value, str):+ control_tokens.update(re.findall(r"[a-z0-9]{2,}", value.lower()))+ for control in _disabled_submit_controls_from_evidence(evidence):+ control_tokens.update(re.findall(r"[a-z0-9]{2,}", _composition_control_label(control).lower()))+ challenge_state = evidence.get("challenge_state")+ if isinstance(challenge_state, dict):+ control_tokens.update(re.findall(r"[a-z0-9]{2,}", str(challenge_state.get("kind") or "").lower()))+ for indicator in challenge_state.get("indicators") or []:+ if isinstance(indicator, str):+ control_tokens.update(re.findall(r"[a-z0-9]{2,}", indicator.lower()))+ for indicator in evidence.get("anti_bot_indicators") or []:+ if isinstance(indicator, str):+ control_tokens.update(re.findall(r"[a-z0-9]{2,}", indicator.lower()))+ return bool(tokens - control_tokens)+++def _post_run_result_evidence_has_content(evidence: dict[str, Any]) -> bool:+ containers = [container for container in evidence.get("result_containers") or [] if isinstance(container, dict)]+ if any(_result_container_has_content(container) for container in containers):+ return True+ if containers and _visible_text_excerpt_has_result_content(evidence):+ return True+ for key in ("visible_results_evidence", "result_text_excerpt"):+ value = evidence.get(key)+ if isinstance(value, str) and value.strip():+ return True+ return False+++def _has_prior_matching_challenge_result_evidence(+ ctx: Any, *, challenge_signature: str, result_evidence_signature: str+) -> bool:+ history = getattr(ctx, "tool_blocker_signals", None)+ if not isinstance(history, list):+ return False+ for signal in reversed(history):+ if not isinstance(signal, CopilotToolBlockerSignal):+ continue+ if signal.internal_reason_code != _POST_BUDGET_CHALLENGE_RESULT_EVIDENCE_REASON:+ continue+ extra = signal.extra+ if (+ extra.get("challenge_signature") == challenge_signature+ and extra.get("result_evidence_signature") == result_evidence_signature+ and extra.get("result_evidence_populated") is not True+ ):+ return True+ return False+++def _terminal_challenge_signal(+ *, reason: str, arguments: dict[str, Any] | None, tool_name: str, extra: dict[str, Any] | None = None+) -> CopilotToolBlockerSignal:+ requested_labels = _requested_block_label_set(arguments)+ labels_text = f" Requested labels: {', '.join(sorted(requested_labels))}." if requested_labels else ""+ agent_steering = (+ "The prior block-running tool hit a failed/budgeted frontier, and bounded current-page inspection "+ f"now shows: {reason}.{labels_text} Do NOT call "+ f"{tool_name} again in this turn, do NOT try another proxy/location from this evidence state, and "+ "do NOT claim results or no-results were verified. REPLY now with a blocker explanation "+ "that names the observed challenge/disabled control and summarizes the tested workflow state."+ )+ return CopilotToolBlockerSignal(+ blocker_kind="tool_error",+ agent_steering_text=agent_steering,+ user_facing_reason=_terminal_challenge_user_facing_reason(reason),+ recovery_hint="report_blocker_to_user",+ cleared_by_tools=frozenset(),+ preserves_workflow_draft=True,+ renders_final_reply=True,+ internal_reason_code=_POST_BUDGET_CHALLENGE_BLOCKER_REASON,+ blocked_tool=tool_name,+ extra=extra or {},+ )++_TERMINAL_CHALLENGE_FALLBACK_USER_FACING = ("A page barrier was still blocking the workflow's next step after the last run, ""so I stopped without claiming results."@@ -441,6 +696,33 @@ def _post_budget_terminal_challenge_signal(# evidence, the answer-from-observed-page path outranks a terminal claim.result_evidence = _post_run_result_evidence_summary(evidence)if result_evidence:+ challenge_signature = _post_budget_challenge_signature(evidence, reason)+ result_evidence_signature = _post_budget_result_evidence_signature(evidence, result_evidence)+ result_evidence_populated = _post_run_result_evidence_has_content(evidence)+ extra = {+ "challenge_signature": challenge_signature,+ "result_evidence_populated": result_evidence_populated,+ "result_evidence_signature": result_evidence_signature,+ }+ if (+ not result_evidence_populated+ and _diagnosis_stop_has_challenge_evidence(ctx, reason)+ and _has_prior_matching_challenge_result_evidence(+ ctx,+ challenge_signature=challenge_signature,+ result_evidence_signature=result_evidence_signature,+ )+ ):+ return _terminal_challenge_signal(+ reason=reason,+ arguments=arguments,+ tool_name=tool_name,+ extra={+ **extra,+ "escalated_from_reason_code": _POST_BUDGET_CHALLENGE_RESULT_EVIDENCE_REASON,+ },+ )+agent_steering = ("The prior block-running tool hit a failed/budgeted frontier, and bounded current-page inspection "f"shows: {reason} — but the SAME observed page also contains result evidence: {result_evidence}. "@@ -459,30 +741,12 @@ def _post_budget_terminal_challenge_signal(| frozenset({"get_run_results", "update_workflow", "update_and_run_blocks"}),preserves_workflow_draft=True,renders_final_reply=False,- internal_reason_code="tool_error_post_budget_challenge_result_evidence",+ internal_reason_code=_POST_BUDGET_CHALLENGE_RESULT_EVIDENCE_REASON,blocked_tool=tool_name,+ extra=extra,)- requested_labels = _requested_block_label_set(arguments)- labels_text = f" Requested labels: {', '.join(sorted(requested_labels))}." if requested_labels else ""- agent_steering = (- "The prior block-running tool hit a failed/budgeted frontier, and bounded current-page inspection "- f"now shows: {reason}.{labels_text} Do NOT call "- f"{tool_name} again in this turn, do NOT try another proxy/location from this evidence state, and "- "do NOT claim results or no-results were verified. REPLY now with a blocker explanation "- "that names the observed challenge/disabled control and summarizes the tested workflow state."- )- return CopilotToolBlockerSignal(- blocker_kind="tool_error",- agent_steering_text=agent_steering,- user_facing_reason=_terminal_challenge_user_facing_reason(reason),- recovery_hint="report_blocker_to_user",- cleared_by_tools=frozenset(),- preserves_workflow_draft=True,- renders_final_reply=True,- internal_reason_code="tool_error_post_budget_challenge_blocker",- blocked_tool=tool_name,- )+ return _terminal_challenge_signal(reason=reason, arguments=arguments, tool_name=tool_name)_RECONCILIATION_REQUIRES_INPUT_USER_FACING = (@@ -689,7 +953,7 @@ def _is_blocker_term_key(key: object) -> bool:def _code_output_contains_collection(value: Any, *, depth: int = 0) -> bool:if depth > 5:return False- if isinstance(value, (list, tuple, set)):+ if isinstance(value, (list, tuple)):return Trueif isinstance(value, dict):return any(@@ -723,6 +987,93 @@ def _code_output_has_goal_content(value: Any, *, depth: int = 0) -> bool:return False+def _metadata_string_list(value: Any) -> list[str]:+ if not isinstance(value, list):+ return []+ return [str(item).strip() for item in value if str(item).strip()]+++def _metadata_goal_value_paths(value: Any) -> list[str]:+ # Keep in sync with workflow_update._artifact_goal_value_paths; duplicated+ # locally to avoid importing the authoring validator into runtime blockers.+ return [path for path in _metadata_string_list(value) if not path.casefold().startswith("<fill")]+++def _goal_value_paths_for_code_block(copilot_ctx: Any | None, label: Any) -> list[str]:+ if copilot_ctx is None or not isinstance(label, str):+ return []+ metadata = getattr(copilot_ctx, "code_artifact_metadata", None)+ if not isinstance(metadata, dict):+ return []+ entry = metadata.get(label)+ if not isinstance(entry, dict):+ return []++ paths: list[str] = []+ seen: set[str] = set()+ for row_group in (entry.get("claimed_outcomes"), entry.get("terminal_verifier_expectations")):+ rows = [row for row in row_group if isinstance(row, dict)] if isinstance(row_group, list) else []+ for row in rows:+ for path in _metadata_goal_value_paths(row.get("goal_value_paths")):+ if path not in seen:+ seen.add(path)+ paths.append(path)+ return paths+++_GOAL_PATH_INDEX_PATTERN = re.compile(r"\[\d+\]")+++def _normalize_goal_value_path(path: str) -> list[str]:+ normalized = path.strip()+ if normalized.startswith("$."):+ normalized = normalized[2:]+ elif normalized.startswith("$"):+ normalized = normalized[1:]+ normalized = normalized.replace("[*]", "[]")+ normalized = _GOAL_PATH_INDEX_PATTERN.sub("[]", normalized)+ return [part for part in normalized.split(".") if part]+++def _iter_goal_value_path_values(value: Any, path_parts: list[str]) -> list[Any]:+ if not path_parts:+ return [value]+ current_part = path_parts[0]+ if isinstance(value, (list, tuple, set)):+ child_parts = path_parts[1:] if current_part == "[]" else path_parts+ expanded_values: list[Any] = []+ for item in value:+ expanded_values.extend(_iter_goal_value_path_values(item, child_parts))+ return expanded_values++ if current_part == "[]":+ return []++ expand_collection = current_part.endswith("[]")+ key = current_part[:-2] if expand_collection else current_part+ if not isinstance(value, Mapping) or key not in value:+ return []++ next_value = value.get(key)+ remaining = path_parts[1:]+ if expand_collection:+ if isinstance(next_value, (list, tuple)):+ child_values: list[Any] = []+ for item in next_value:+ child_values.extend(_iter_goal_value_path_values(item, remaining))+ return child_values+ return []+ return _iter_goal_value_path_values(next_value, remaining)+++def _code_output_goal_paths_have_content(value: Any, goal_value_paths: list[str]) -> bool:+ for path in goal_value_paths:+ values = _iter_goal_value_path_values(value, _normalize_goal_value_path(path))+ if not any(_code_output_has_goal_content(item) for item in values):+ return False+ return True++def _active_block_run_budget_seconds(ctx: AgentContext) -> int:remaining = _copilot_seconds_remaining(ctx)if remaining is None:@@ -1066,7 +1417,9 @@ def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any_build_loop_blocker_signal = build_loop_blocker_signal-def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[dict] | None]:+def _analyze_run_blocks(+ result: dict[str, Any], copilot_ctx: Any | None = None+) -> tuple[str | None, bool, list[dict] | None]:"""Single-pass analysis of run result blocks.Returns ``(anti_bot_match, has_empty_data_blocks, failure_categories)``@@ -1109,6 +1462,7 @@ def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[has_data_blocks = Falseany_data_output = False+ missing_metadata_goal_content = Falseblocks = data.get("blocks")if isinstance(blocks, list):@@ -1136,6 +1490,19 @@ def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[structured_blocker = _structured_blocker_message(extracted, include_flag_keys=True)if structured_blocker:texts_to_scan.append(structured_blocker)+ goal_value_paths = _goal_value_paths_for_code_block(copilot_ctx, block.get("label"))+ if goal_value_paths:+ has_data_blocks = True+ if _code_output_goal_paths_have_content(extracted, goal_value_paths):+ any_data_output = True+ else:+ # Terminal goal paths are conjunctive: one missing+ # declared field means the block did not prove the+ # requested outcome, even if another path had data.+ missing_metadata_goal_content = True+ # Goal-path contracts supersede the generic collection-shape+ # fallback below; they are the stronger outcome evidence check.+ continue# A code output joins the emptiness denominator only when it declares a# collection shape; action-only outputs are exempt.if _code_output_contains_collection(extracted):@@ -1151,5 +1518,5 @@ def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[anti_bot_match = cat.get("reasoning", "anti-bot pattern detected")break- empty_data_blocks = has_data_blocks and not any_data_output+ empty_data_blocks = (has_data_blocks and not any_data_output) or missing_metadata_goal_contentreturn anti_bot_match, empty_data_blocks, categoriesdiff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.pyindex 23922187e..ce64a9474 100644--- a/skyvern/forge/sdk/copilot/tools/completion.py+++ b/skyvern/forge/sdk/copilot/tools/completion.py@@ -163,7 +163,7 @@ def _is_outcome_evidence_candidate(copilot_ctx: Any, result: dict[str, Any]) ->return Falseif _run_blocks_structured_blocker_message(result):return False- _anti_bot, empty_data_blocks, _categories = _analyze_run_blocks(result)+ _anti_bot, empty_data_blocks, _categories = _analyze_run_blocks(result, copilot_ctx)return not empty_data_blocksdiff --git a/skyvern/forge/sdk/copilot/tools/credentials.py b/skyvern/forge/sdk/copilot/tools/credentials.pyindex 3fb6e81ff..faf023447 100644--- a/skyvern/forge/sdk/copilot/tools/credentials.py+++ b/skyvern/forge/sdk/copilot/tools/credentials.py@@ -9,6 +9,7 @@ import yamlfrom skyvern.forge import appfrom skyvern.forge.sdk.copilot.request_policy import RequestPolicyfrom skyvern.forge.sdk.copilot.runtime import AgentContext+from skyvern.forge.sdk.copilot.workflow_credential_utils import workflow_blocksfrom skyvern.forge.sdk.schemas.credentials import Credentialfrom skyvern.forge.sdk.workflow.models.parameter import WorkflowParameterTypefrom skyvern.utils.yaml_loader import safe_load_no_dates@@ -78,7 +79,11 @@ def _extract_credential_ids_from_workflow_parameters(parameters: Any) -> list[stdef _extract_credential_ids_from_workflow_definition(workflow_definition: Any) -> list[str]:definition = _workflow_definition_as_dict(workflow_definition)- return _extract_credential_ids_from_workflow_parameters(definition.get("parameters"))+ found = _extract_credential_ids_from_workflow_parameters(definition.get("parameters"))+ for block in workflow_blocks({"workflow_definition": definition}):+ found.extend(_extract_credential_ids_from_workflow_parameters(block.get("parameters")))+ found.extend(_extract_credential_ids_from_tool_value(block.get("credential_id")))+ return list(dict.fromkeys(found))def _parsed_workflow_definition(workflow_yaml: str | None) -> dict[str, Any] | None:@@ -100,7 +105,7 @@ def _extract_credential_ids_from_workflow_yaml(workflow_yaml: str | None) -> lisworkflow_definition = _parsed_workflow_definition(workflow_yaml)if workflow_definition is None:return []- return _extract_credential_ids_from_workflow_parameters(workflow_definition.get("parameters"))+ return _extract_credential_ids_from_workflow_definition(workflow_definition)_MISBINDING_WORKFLOW_LOCATION = "workflow"@@ -192,6 +197,36 @@ def _missing_credential_reference_tool_error(missing_credential_ids: list[str]))+def _unapproved_credential_reference_tool_error(unapproved_credential_ids: list[str]) -> str:+ formatted_ids = ", ".join(f"`{credential_id}`" for credential_id in unapproved_credential_ids)+ id_word = "ID" if len(unapproved_credential_ids) == 1 else "IDs"+ return (+ "Credential approval blocked this Copilot run before dispatch. "+ f"Reason codes: unapproved_credential_reference. Unapproved credential {id_word}: {formatted_ids}. "+ "Ask the user to select or confirm the saved credential for this request before running the workflow."+ )+++def _approved_run_credential_ids(request_policy: RequestPolicy | None) -> set[str]:+ if request_policy is None:+ return set()+ return {+ credential.credential_id+ for credential in request_policy.resolved_credentials+ if isinstance(getattr(credential, "credential_id", None), str)+ }+++def _credential_run_approval_error(credential_ids: list[str], request_policy: RequestPolicy | None) -> str | None:+ if not credential_ids:+ return None+ approved_ids = _approved_run_credential_ids(request_policy)+ unapproved_ids = [credential_id for credential_id in credential_ids if credential_id not in approved_ids]+ if not unapproved_ids:+ return None+ return _unapproved_credential_reference_tool_error(unapproved_ids)++async def _credential_ids_validation_error(credential_ids: list[str], ctx: AgentContext) -> str | None:if not credential_ids:return Nonediff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex 753803e4f..1d67866d3 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -97,6 +97,7 @@ from .composition_capture import ()from .credentials import (_credential_ids_validation_error,+ _credential_run_approval_error,_extract_credential_ids_from_tool_value,_extract_credential_ids_from_workflow_definition,)@@ -656,6 +657,13 @@ async def _run_blocks_and_collect_debug(+ _extract_credential_ids_from_workflow_definition(workflow.workflow_definition)))+ credential_approval_error = _credential_run_approval_error(+ credential_ids,+ getattr(ctx, "request_policy", None),+ )+ if credential_approval_error is not None:+ return {"ok": False, "error": credential_approval_error}+credential_error = await _credential_ids_validation_error(credential_ids, ctx)if credential_error is not None:return {"ok": False, "error": credential_error}@@ -1437,7 +1445,7 @@ def _record_run_blocks_result(copilot_ctx.post_run_current_page_inspection_workflow_run_id = Nonestructured_blocker = _run_blocks_structured_blocker_message(result)- anti_bot_match, empty_data_blocks, failure_categories = _analyze_run_blocks(result)+ anti_bot_match, empty_data_blocks, failure_categories = _analyze_run_blocks(result, copilot_ctx)record_gate_decision(copilot_ctx,{@@ -1544,34 +1552,36 @@ def _record_run_blocks_result(display_reason=run_outcome_display_reason(copilot_ctx.last_test_failure_reason),),)- copilot_ctx.failed_test_nudge_count = 0- copilot_ctx.null_data_streak_count = 0- copilot_ctx.probable_site_block_streak_count = 0- copilot_ctx.last_failed_workflow_yaml = None- # Real success: clear the signature latch so a subsequent bad URL in- # the same session can re-fire the stop nudge.- copilot_ctx.non_retriable_nav_error_last_emitted_signature = Noneunverified = _unverified_current_workflow_labels(copilot_ctx)copilot_ctx.last_unverified_block_labels = unverifiedoutcome_unverified_reason = _outcome_unverified_reason(copilot_ctx, completion_verification)- if outcome_unverified_reason is not None and _outcome_failure_warrants_repair(- copilot_ctx, completion_verification- ):+ if outcome_unverified_reason is not None:# The workflow already has a confirmation block, yet the produced# evidence does not demonstrate the outcome (or contradicts it). Treat# it as a suspicious success so the existing repair/partial machinery# fires. A mid-build run with no confirmation block yet falls through to- # keep-building below; terminal success stays withheld either way via- # the verification result.- copilot_ctx.last_test_suspicious_success = True- copilot_ctx.last_test_failure_reason = outcome_unverified_reason- if isinstance(data, dict):- data.setdefault("failure_reason", outcome_unverified_reason)- elif not unverified:+ # keep-building below. It still does not count as a verified success,+ # so preserve streak state until produced evidence demonstrates the+ # outcome; terminal success stays withheld either way via the+ # verification result.+ if _outcome_failure_warrants_repair(copilot_ctx, completion_verification):+ copilot_ctx.last_test_suspicious_success = True+ copilot_ctx.last_test_failure_reason = outcome_unverified_reason+ if isinstance(data, dict):+ data.setdefault("failure_reason", outcome_unverified_reason)+ else:+ copilot_ctx.failed_test_nudge_count = 0+ copilot_ctx.null_data_streak_count = 0+ copilot_ctx.probable_site_block_streak_count = 0+ copilot_ctx.last_failed_workflow_yaml = None+ # Real success: clear the signature latch so a subsequent bad URL in+ # the same session can re-fire the stop nudge.+ copilot_ctx.non_retriable_nav_error_last_emitted_signature = None+ if outcome_unverified_reason is None and not unverified:copilot_ctx.last_full_workflow_test_ok = Truecopilot_ctx.last_good_workflow = copilot_ctx.last_workflowcopilot_ctx.last_good_workflow_yaml = copilot_ctx.last_workflow_yaml- else:+ elif outcome_unverified_reason is None:copilot_ctx.last_test_failure_reason = ("The last run verified only the current browser frontier; unverified workflow blocks remain: "+ ", ".join(unverified[:8])diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 13500bd1e..b09953fe1 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -100,6 +100,13 @@ class CodeArtifactClaimedOutcome(BaseModel):depends_on: list[str] = Field(default_factory=list, description="Page-dependency ids this claim relies on.")covered_criteria: list[str] = Field(default_factory=list, description="Completion-criterion ids this claim covers.")criteria_ids: list[str] = Field(default_factory=list)+ goal_value_paths: list[str] = Field(+ default_factory=list,+ description=(+ "Output JSON paths that carry the goal values for this claim, for example "+ "`records[].number` or `records[].expiration_date`."+ ),+ )evidence_refs: list[str] = Field(default_factory=list)observation_refs: list[str] = Field(default_factory=list)required_tokens: list[str] = Field(default_factory=list)@@ -148,6 +155,10 @@ class CodeArtifactTerminalVerifierExpectation(BaseModel):text: str = ""criteria_ids: list[str] = Field(default_factory=list)claimed_outcome_ids: list[str] = Field(default_factory=list)+ goal_value_paths: list[str] = Field(+ default_factory=list,+ description="Output JSON paths terminal verification should treat as goal-value evidence.",+ )class CodeArtifactExplorationObservation(BaseModel):@@ -372,7 +383,13 @@ def _normalize_code_artifact_metadata_detailed(item_violations.append(f"Artifact metadata for `{label}` requires non-empty `{field_name}`.")if not dumped.get("evidence_refs") and not dumped.get("observation_refs"):item_violations.append(f"Artifact metadata for `{label}` requires `evidence_refs` or `observation_refs`.")- item_violations.extend(_code_artifact_metadata_shape_errors(label, dumped))+ item_violations.extend(+ _code_artifact_metadata_shape_errors(+ label,+ dumped,+ reject_unfilled_goal_value_paths=impose_defaults,+ )+ )if item_violations:violations.extend(item_violations)offending_labels.append(label)@@ -417,6 +434,9 @@ def _impose_code_artifact_metadata_defaults(dependency_id = artifact_dependency_id(label)observation_ref_id = artifact_observation_ref_id(label)declared_goal = str(artifact.get("declared_goal") or "").strip()+ default_goal_value_paths = _first_artifact_goal_value_paths(artifact.get("claimed_outcomes")) or (+ _first_artifact_goal_value_paths(artifact.get("terminal_verifier_expectations"))+ )dependencies = _artifact_mutable_rows(artifact.get("page_dependencies"))for index, dependency in enumerate(dependencies):@@ -460,6 +480,8 @@ def _impose_code_artifact_metadata_defaults("observation_refs": [observation_ref_id],}]+ if default_goal_value_paths:+ artifact["claimed_outcomes"][0]["goal_value_paths"] = list(default_goal_value_paths)claims = _artifact_mutable_rows(artifact.get("claimed_outcomes"))criteria = _artifact_mutable_rows(artifact.get("completion_criteria"))@@ -493,6 +515,8 @@ def _impose_code_artifact_metadata_defaults(and not _artifact_string_list(claim.get("criteria_ids"))):claim["covered_criteria"] = list(criterion_ids)+ if default_goal_value_paths and not _artifact_string_list(claim.get("goal_value_paths")):+ claim["goal_value_paths"] = list(default_goal_value_paths)status = str(claim.get("status") or "").strip()if (status not in {"missing", "satisfied"}@@ -535,6 +559,8 @@ def _impose_code_artifact_metadata_defaults(and not _artifact_string_list(expectation.get("claimed_outcome_ids"))):expectation["criteria_ids"] = list(criterion_ids)+ if default_goal_value_paths and not _artifact_string_list(expectation.get("goal_value_paths")):+ expectation["goal_value_paths"] = list(default_goal_value_paths)if not _artifact_mutable_rows(artifact.get("evidence_refs")) and not _artifact_mutable_rows(artifact.get("observation_refs")@@ -587,6 +613,9 @@ def _imposed_artifact_skeleton("block_label": label,"artifact_id": _artifact_id_for_block_label(label),"declared_goal": _block_goal_fallback(label, block),+ "terminal_verifier_expectations": [+ {"goal_value_paths": ["<fill: output JSON path(s) carrying requested goal values>"]}+ ],}block_id = str(block.get("block_id") or block.get("id") or "").strip()if block_id:@@ -1044,9 +1073,23 @@ def _maybe_impose_synthesized_code_block(workflow_yaml: str, ctx: AgentContext))-def _code_artifact_metadata_shape_errors(label: str, artifact: Mapping[str, Any]) -> list[str]:+def _code_artifact_metadata_shape_errors(+ label: str,+ artifact: Mapping[str, Any],+ *,+ reject_unfilled_goal_value_paths: bool = False,+) -> list[str]:"""Return every shape violation for one artifact; the caller aggregates them."""errors: list[str] = []+ criteria_rows = _artifact_rows(artifact.get("completion_criteria"))+ terminal_criterion_ids = {+ str(row.get("id") or "").strip()+ for row in criteria_rows+ if row.get("terminal") is True or str(row.get("level") or "").strip() == "terminal"+ } - {""}+ # Populated while validating claimed outcomes, then used by terminal+ # verifier expectations below to require goal paths for terminal claims.+ terminal_claim_ids: set[str] = set()for field_name, ref_key in (("evidence_refs", "evidence_ref"), ("observation_refs", "observation_ref")):for index, ref in enumerate(_artifact_rows(artifact.get(field_name))):if not str(ref.get(ref_key) or "").strip():@@ -1074,8 +1117,28 @@ def _code_artifact_metadata_shape_errors(label: str, artifact: Mapping[str, Any]claim_criteria = _artifact_string_list(claim.get("covered_criteria")) or _artifact_string_list(claim.get("criteria_ids"))+ claim_goal_value_paths = (+ _artifact_goal_value_paths(claim.get("goal_value_paths"))+ if reject_unfilled_goal_value_paths+ else _artifact_string_list(claim.get("goal_value_paths"))+ )if not claim_criteria:errors.append(f"Artifact metadata claim `{claim_id}` for `{label}` requires covered criterion ids.")+ if set(claim_criteria) & terminal_criterion_ids:+ if claim_id:+ terminal_claim_ids.add(claim_id)+ if reject_unfilled_goal_value_paths and _artifact_has_unfilled_goal_value_path(+ claim.get("goal_value_paths")+ ):+ errors.append(+ f"Artifact metadata claim `{claim_id or index}` for `{label}` has unfilled "+ "`goal_value_paths`; replace `<fill...>` placeholders with output JSON paths."+ )+ elif not claim_goal_value_paths:+ errors.append(+ f"Artifact metadata claim `{claim_id or index}` for `{label}` covers a terminal criterion "+ "and requires `goal_value_paths`."+ )claim_evidence_refs = _artifact_string_list(claim.get("evidence_refs"))claim_observation_refs = _artifact_string_list(claim.get("observation_refs"))if claim.get("status") == "satisfied" and not claim_evidence_refs:@@ -1106,13 +1169,31 @@ def _code_artifact_metadata_shape_errors(label: str, artifact: Mapping[str, Any]for index, expectation in enumerate(_artifact_rows(artifact.get("terminal_verifier_expectations"))):expectation_id = str(expectation.get("id") or "").strip()- if not _artifact_string_list(expectation.get("criteria_ids")) and not _artifact_string_list(- expectation.get("claimed_outcome_ids")- ):+ expectation_criteria = _artifact_string_list(expectation.get("criteria_ids"))+ expectation_claims = _artifact_string_list(expectation.get("claimed_outcome_ids"))+ expectation_goal_value_paths = (+ _artifact_goal_value_paths(expectation.get("goal_value_paths"))+ if reject_unfilled_goal_value_paths+ else _artifact_string_list(expectation.get("goal_value_paths"))+ )+ if not expectation_criteria and not expectation_claims:errors.append(f"Artifact metadata terminal verifier expectation `{expectation_id or index}` for `{label}` ""requires `criteria_ids` or `claimed_outcome_ids`.")+ if set(expectation_criteria) & terminal_criterion_ids or set(expectation_claims) & terminal_claim_ids:+ if reject_unfilled_goal_value_paths and _artifact_has_unfilled_goal_value_path(+ expectation.get("goal_value_paths")+ ):+ errors.append(+ f"Artifact metadata terminal verifier expectation `{expectation_id or index}` for `{label}` "+ "has unfilled `goal_value_paths`; replace `<fill...>` placeholders with output JSON paths."+ )+ elif not expectation_goal_value_paths:+ errors.append(+ f"Artifact metadata terminal verifier expectation `{expectation_id or index}` for `{label}` "+ "requires `goal_value_paths` for terminal criteria."+ )for index, observation in enumerate(_artifact_rows(artifact.get("exploration_observations"))):if observation.get("status") != "observed_not_verified":@@ -1132,6 +1213,30 @@ def _artifact_rows(value: Any) -> list[Mapping[str, Any]]:return [row for row in value if isinstance(row, Mapping)] if isinstance(value, list) else []+def _first_artifact_goal_value_paths(value: Any) -> list[str]:+ # Best-effort default propagation: preserve the first explicit contract+ # instead of inventing a union that may mix unrelated output shapes.+ for row in _artifact_rows(value):+ paths = _artifact_goal_value_paths(row.get("goal_value_paths"))+ if paths:+ return paths+ return []+++def _artifact_goal_value_paths(value: Any) -> list[str]:+ # Keep in sync with blockers._metadata_goal_value_paths; duplicated locally+ # so authoring validation does not depend on runtime blocker helpers.+ return [path for path in _artifact_string_list(value) if not _is_unfilled_artifact_placeholder(path)]+++def _artifact_has_unfilled_goal_value_path(value: Any) -> bool:+ return any(_is_unfilled_artifact_placeholder(path) for path in _artifact_string_list(value))+++def _is_unfilled_artifact_placeholder(value: str) -> bool:+ return value.casefold().startswith("<fill")++def _artifact_string_list(value: Any) -> list[str]:if not isinstance(value, list):return []diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex 611867e4c..72f93a4d5 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -33,6 +33,7 @@ from skyvern.forge.sdk.copilot.recoverable_failure import build_recoverable_failfrom skyvern.forge.sdk.copilot.request_policy import (_REDACTED_REFUSED_SECRET_TURN,TRANSCRIPT_ANCHOR_CHAR_CAP,+ RequestPolicy,_classify_request,build_transcript_context,redact_raw_secrets_for_prompt,@@ -3296,6 +3297,349 @@ workflow_definition:get_credentials_by_ids.assert_not_called()+class TestRunBlocksCredentialApproval:+ @staticmethod+ def _workflow(+ credential_id: str | None = None,+ *,+ parameters: list[dict[str, object]] | None = None,+ blocks: list[dict[str, object]] | None = None,+ ) -> SimpleNamespace:+ workflow_parameters = parameters+ if workflow_parameters is None and credential_id is not None:+ workflow_parameters = [+ {+ "parameter_type": "workflow",+ "workflow_parameter_type": "credential_id",+ "key": "login_credentials",+ "default_value": credential_id,+ }+ ]+ return SimpleNamespace(+ workflow_id="wf-1",+ workflow_definition={+ "parameters": workflow_parameters or [],+ "blocks": blocks or [{"label": "login"}],+ },+ get_output_parameter=lambda label: SimpleNamespace(label=label) if label == "login" else None,+ )++ @staticmethod+ def _db(+ *,+ workflow: object,+ credentials: list[object] | None = None,+ organization_lookup: object = AssertionError("org lookup called"),+ ) -> SimpleNamespace:+ if isinstance(organization_lookup, BaseException):+ get_organization = AsyncMock(side_effect=organization_lookup)+ else:+ get_organization = AsyncMock(return_value=organization_lookup)+ return SimpleNamespace(+ workflows=SimpleNamespace(get_workflow_by_permanent_id=AsyncMock(return_value=workflow)),+ credentials=SimpleNamespace(get_credentials_by_ids=AsyncMock(return_value=credentials or [])),+ organizations=SimpleNamespace(get_organization=get_organization),+ )++ @pytest.mark.asyncio+ async def test_run_blocks_rejects_unapproved_workflow_credential_before_dispatch(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug+ from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module++ workflow = self._workflow("cred_unapproved")+ database = self._db(+ workflow=workflow,+ credentials=[SimpleNamespace(credential_id="cred_unapproved")],+ )+ execute_workflow = AsyncMock(side_effect=AssertionError("execute_workflow called"))+ prepare_workflow = AsyncMock(side_effect=AssertionError("prepare_workflow called"))+ monkeypatch.setattr(run_execution_module.app, "DATABASE", database)+ monkeypatch.setattr(+ run_execution_module.app,+ "WORKFLOW_SERVICE",+ SimpleNamespace(prepare_workflow=prepare_workflow, execute_workflow=execute_workflow),+ )++ ctx = _ctx(request_policy=RequestPolicy(resolved_credentials=[]))+ result = await _run_blocks_and_collect_debug(+ {"block_labels": ["login"], "parameters": {}},+ ctx,+ )++ assert result["ok"] is False+ assert "unapproved_credential_reference" in result["error"]+ database.credentials.get_credentials_by_ids.assert_not_called()+ database.organizations.get_organization.assert_not_called()+ prepare_workflow.assert_not_called()+ execute_workflow.assert_not_called()++ @pytest.mark.asyncio+ async def test_run_blocks_rejects_unapproved_runtime_parameter_before_dispatch(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug+ from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module++ workflow = self._workflow("cred_resolved")+ database = self._db(workflow=workflow, credentials=[SimpleNamespace(credential_id="cred_resolved")])+ execute_workflow = AsyncMock(side_effect=AssertionError("execute_workflow called"))+ prepare_workflow = AsyncMock(side_effect=AssertionError("prepare_workflow called"))+ monkeypatch.setattr(run_execution_module.app, "DATABASE", database)+ monkeypatch.setattr(+ run_execution_module.app,+ "WORKFLOW_SERVICE",+ SimpleNamespace(prepare_workflow=prepare_workflow, execute_workflow=execute_workflow),+ )++ ctx = _ctx(request_policy=RequestPolicy(resolved_credentials=[SimpleNamespace(credential_id="cred_resolved")]))+ result = await _run_blocks_and_collect_debug(+ {"block_labels": ["login"], "parameters": {"override_credentials": "cred_unapproved"}},+ ctx,+ )++ assert result["ok"] is False+ assert "unapproved_credential_reference" in result["error"]+ database.credentials.get_credentials_by_ids.assert_not_called()+ database.organizations.get_organization.assert_not_called()+ prepare_workflow.assert_not_called()+ execute_workflow.assert_not_called()++ @pytest.mark.asyncio+ async def test_run_blocks_rejects_unapproved_block_credential_parameter_before_dispatch(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug+ from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module++ workflow = self._workflow(+ parameters=[],+ blocks=[+ {+ "label": "login",+ "parameters": [+ {+ "parameter_type": "credential",+ "key": "login_credentials",+ "credential_id": "cred_unapproved",+ }+ ],+ }+ ],+ )+ database = self._db(+ workflow=workflow,+ credentials=[SimpleNamespace(credential_id="cred_unapproved")],+ )+ prepare_workflow = AsyncMock(side_effect=AssertionError("prepare_workflow called"))+ execute_workflow = AsyncMock(side_effect=AssertionError("execute_workflow called"))+ monkeypatch.setattr(run_execution_module.app, "DATABASE", database)+ monkeypatch.setattr(+ run_execution_module.app,+ "WORKFLOW_SERVICE",+ SimpleNamespace(prepare_workflow=prepare_workflow, execute_workflow=execute_workflow),+ )++ ctx = _ctx(request_policy=RequestPolicy(resolved_credentials=[]))+ result = await _run_blocks_and_collect_debug(+ {"block_labels": ["login"], "parameters": {}},+ ctx,+ )++ assert result["ok"] is False+ assert "unapproved_credential_reference" in result["error"]+ database.credentials.get_credentials_by_ids.assert_not_called()+ database.organizations.get_organization.assert_not_called()+ prepare_workflow.assert_not_called()+ execute_workflow.assert_not_called()++ @pytest.mark.asyncio+ async def test_run_blocks_rejects_unapproved_direct_block_credential_id_before_dispatch(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug+ from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module++ workflow = self._workflow(+ parameters=[],+ blocks=[{"label": "login", "block_type": "google_sheets_read", "credential_id": "cred_unapproved"}],+ )+ database = self._db(+ workflow=workflow,+ credentials=[SimpleNamespace(credential_id="cred_unapproved")],+ )+ prepare_workflow = AsyncMock(side_effect=AssertionError("prepare_workflow called"))+ execute_workflow = AsyncMock(side_effect=AssertionError("execute_workflow called"))+ monkeypatch.setattr(run_execution_module.app, "DATABASE", database)+ monkeypatch.setattr(+ run_execution_module.app,+ "WORKFLOW_SERVICE",+ SimpleNamespace(prepare_workflow=prepare_workflow, execute_workflow=execute_workflow),+ )++ ctx = _ctx(request_policy=RequestPolicy(resolved_credentials=[]))+ result = await _run_blocks_and_collect_debug(+ {"block_labels": ["login"], "parameters": {}},+ ctx,+ )++ assert result["ok"] is False+ assert "unapproved_credential_reference" in result["error"]+ database.credentials.get_credentials_by_ids.assert_not_called()+ database.organizations.get_organization.assert_not_called()+ prepare_workflow.assert_not_called()+ execute_workflow.assert_not_called()++ @pytest.mark.asyncio+ async def test_run_blocks_rejects_unapproved_branch_block_credential_before_dispatch(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug+ from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module++ workflow = self._workflow(+ parameters=[],+ blocks=[+ {+ "label": "choose_path",+ "branch_conditions": [+ {+ "condition": "needs login",+ "blocks": [+ {+ "label": "login",+ "parameters": [+ {+ "parameter_type": "credential",+ "key": "login_credentials",+ "credential_id": "cred_unapproved",+ }+ ],+ }+ ],+ }+ ],+ }+ ],+ )+ database = self._db(+ workflow=workflow,+ credentials=[SimpleNamespace(credential_id="cred_unapproved")],+ )+ prepare_workflow = AsyncMock(side_effect=AssertionError("prepare_workflow called"))+ execute_workflow = AsyncMock(side_effect=AssertionError("execute_workflow called"))+ monkeypatch.setattr(run_execution_module.app, "DATABASE", database)+ monkeypatch.setattr(+ run_execution_module.app,+ "WORKFLOW_SERVICE",+ SimpleNamespace(prepare_workflow=prepare_workflow, execute_workflow=execute_workflow),+ )++ ctx = _ctx(request_policy=RequestPolicy(resolved_credentials=[]))+ result = await _run_blocks_and_collect_debug(+ {"block_labels": ["login"], "parameters": {}},+ ctx,+ )++ assert result["ok"] is False+ assert "unapproved_credential_reference" in result["error"]+ database.credentials.get_credentials_by_ids.assert_not_called()+ database.organizations.get_organization.assert_not_called()+ prepare_workflow.assert_not_called()+ execute_workflow.assert_not_called()++ @pytest.mark.asyncio+ async def test_update_and_run_blocks_rejects_unapproved_credential_at_shared_run_seam(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot import tools as tools_module+ from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module++ workflow = self._workflow("cred_unapproved")+ database = self._db(+ workflow=workflow,+ credentials=[SimpleNamespace(credential_id="cred_unapproved")],+ )+ prepare_workflow = AsyncMock(side_effect=AssertionError("prepare_workflow called"))+ execute_workflow = AsyncMock(side_effect=AssertionError("execute_workflow called"))+ monkeypatch.setattr(run_execution_module.app, "DATABASE", database)+ monkeypatch.setattr(+ run_execution_module.app,+ "WORKFLOW_SERVICE",+ SimpleNamespace(prepare_workflow=prepare_workflow, execute_workflow=execute_workflow),+ )+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *args: False)+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *args, **kwargs: None)+ monkeypatch.setattr(tools_module, "_tool_loop_error", lambda *args, **kwargs: None)+ monkeypatch.setattr(tools_module, "_update_and_run_blocks_composition_evidence_precheck", lambda *args: None)+ monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", AsyncMock(return_value=None))+ monkeypatch.setattr(tools_module, "_pre_run_workflow_coverage_error", lambda *args: None)+ monkeypatch.setattr(tools_module, "_plan_frontier", lambda *args: (["login"], {}, "login"))+ monkeypatch.setattr(tools_module, "_frontier_run_size_error", lambda *args: None)+ monkeypatch.setattr(tools_module, "_verify_and_record_run_blocks_result", AsyncMock(return_value=None))+ monkeypatch.setattr(+ tools_module,+ "_tool_visible_result_after_completion_verification",+ lambda _ctx, result, _completion: result,+ )+ monkeypatch.setattr(tools_module, "_record_diagnosis_repair_contract", lambda *args, **kwargs: None)+ monkeypatch.setattr(tools_module, "enqueue_screenshot_from_result", lambda *args, **kwargs: None)++ async def fake_update_workflow(*args: object, **kwargs: object) -> dict[str, object]:+ ctx = args[1]+ ctx.staged_workflow = workflow+ ctx.last_workflow = workflow+ ctx.last_update_block_count = 1+ return {"ok": True, "_workflow": workflow, "data": {"block_count": 1}}++ monkeypatch.setattr(tools_module, "_update_workflow", fake_update_workflow)++ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(+ SimpleNamespace(+ context=_ctx(request_policy=RequestPolicy(resolved_credentials=[])),+ tool_name="update_and_run_blocks",+ ),+ json.dumps(+ {+ "workflow_yaml": """+workflow_definition:+ parameters:+ - parameter_type: workflow+ workflow_parameter_type: credential_id+ key: login_credentials+ default_value: cred_unapproved+ blocks:+ - block_type: login+ label: login+""",+ "block_labels": ["login"],+ "parameters": {},+ }+ ),+ )++ payload = json.loads(result)+ assert payload["ok"] is False+ assert "unapproved_credential_reference" in payload["error"]+ database.credentials.get_credentials_by_ids.assert_not_called()+ database.organizations.get_organization.assert_not_called()+ prepare_workflow.assert_not_called()+ execute_workflow.assert_not_called()++ @pytest.mark.asyncio+ async def test_resolved_credential_reaches_existing_run_validation_path(self, monkeypatch) -> None:+ from skyvern.forge.sdk.copilot.tools import _run_blocks_and_collect_debug+ from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module++ workflow = self._workflow("cred_resolved")+ database = self._db(+ workflow=workflow,+ credentials=[SimpleNamespace(credential_id="cred_resolved")],+ organization_lookup=None,+ )+ monkeypatch.setattr(run_execution_module.app, "DATABASE", database)++ ctx = _ctx(request_policy=RequestPolicy(resolved_credentials=[SimpleNamespace(credential_id="cred_resolved")]))+ result = await _run_blocks_and_collect_debug(+ {"block_labels": ["login"], "parameters": {}},+ ctx,+ )++ assert result["ok"] is False+ assert result["error"] == "Organization not found"+ database.credentials.get_credentials_by_ids.assert_awaited_once_with(["cred_resolved"], organization_id="org-1")+ database.organizations.get_organization.assert_awaited_once_with(organization_id="org-1")++class TestResponseTypeClassificationRuleReachesAgent:"""Pin the classifier rule that selects ASK_QUESTION when `user_response` asks the user for required input — the agent.py null-out gate keys on `resp_type == "ASK_QUESTION"` and depends on this prompt text."""diff --git a/tests/unit/test_copilot_code_artifact_metadata_violations.py b/tests/unit/test_copilot_code_artifact_metadata_violations.pyindex c2595d8c9..d43d15ed9 100644--- a/tests/unit/test_copilot_code_artifact_metadata_violations.py+++ b/tests/unit/test_copilot_code_artifact_metadata_violations.py@@ -5,6 +5,7 @@ OSS-synced: only example.* / RFC-2606 placeholder targets and synthetic labels.from __future__ import annotations+import copyimport reimport textwrap@@ -47,6 +48,7 @@ def _valid_metadata(label: str) -> dict:"status": "observed_not_verified","depends_on": ["dependency:p"],"covered_criteria": ["criterion:c"],+ "goal_value_paths": ["records[].number"],"observation_refs": ["obs1"],}],@@ -54,7 +56,9 @@ def _valid_metadata(label: str) -> dict:{"id": "dependency:p", "scope": "page", "status": "observed_not_verified", "observation_refs": ["obs1"]}],"completion_criteria": [{"id": "criterion:c", "text": "c", "level": "terminal"}],- "terminal_verifier_expectations": [{"id": "exp", "text": "e", "criteria_ids": ["criterion:c"]}],+ "terminal_verifier_expectations": [+ {"id": "exp", "text": "e", "criteria_ids": ["criterion:c"], "goal_value_paths": ["records[].number"]}+ ],"observation_refs": [{"observation_ref": "obs1",@@ -151,6 +155,25 @@ class TestAccumulateAllViolations:assert error is Noneassert list(normalized.keys()) == ["my_block"]+ def test_terminal_goal_value_path_placeholders_are_rejected(self) -> None:+ metadata = _valid_metadata("my_block")+ metadata["claimed_outcomes"][0]["goal_value_paths"] = [+ "<fill: output JSON path(s) carrying requested goal values>"+ ]+ metadata["terminal_verifier_expectations"][0]["goal_value_paths"] = [+ "<fill: output JSON path(s) carrying requested goal values>"+ ]++ normalized, error = _normalize_code_artifact_metadata(+ [metadata], _code_block_yaml("my_block"), impose_defaults=True, scout_trajectory=_SCOUT_TRAJECTORY+ )++ assert normalized == {}+ assert error is not None+ assert "claim `claim:x`" in error+ assert "terminal verifier expectation `exp`" in error+ assert "has unfilled `goal_value_paths`" in error+def test_empty_metadata_is_noop(self) -> None:assert _normalize_code_artifact_metadata(None, _code_block_yaml("my_block")) == ({}, None)assert _normalize_code_artifact_metadata([], _code_block_yaml("my_block")) == ({}, None)@@ -175,9 +198,24 @@ def _assert_passes_full_validator(row: dict) -> None:assert list(renormalized.keys()) == [row["block_label"]]+def _assert_passes_skeleton_validator(row: dict) -> None:+ """Skeleton rows may keep fill-placeholders until the authoring imposition pass."""+ placeholder = row["terminal_verifier_expectations"][0]["goal_value_paths"][0]+ assert placeholder.startswith("<fill:")+ validator_row = copy.deepcopy(row)+ validator_row["claimed_outcomes"][0]["goal_value_paths"] = [placeholder]+ # This helper exercises the non-imposition validator path, where skeleton+ # placeholders are intentionally preserved for the later authoring pass.+ _assert_passes_full_validator(validator_row)++class TestSeamImposition:def test_minimal_metadata_is_fully_defaulted(self) -> None:- metadata = {"block_label": "my_block", "declared_goal": "Search the registry and expand result rows"}+ metadata = {+ "block_label": "my_block",+ "declared_goal": "Search the registry and expand result rows",+ "terminal_verifier_expectations": [{"goal_value_paths": ["records[].number"]}],+ }normalized, error = _normalize_code_artifact_metadata([metadata], _code_block_yaml("my_block"), impose_defaults=True, scout_trajectory=_SCOUT_TRAJECTORY)@@ -191,6 +229,28 @@ class TestSeamImposition:assert row["observation_refs"]_assert_passes_full_validator(row)+ def test_unfilled_goal_value_path_is_not_propagated_as_default(self) -> None:+ metadata = {+ "block_label": "my_block",+ "declared_goal": "Search the registry and expand result rows",+ "claimed_outcomes": [+ {+ "text": "records visible",+ "goal_value_paths": ["<fill: output JSON path(s) carrying requested goal values>"],+ }+ ],+ }++ normalized, error = _normalize_code_artifact_metadata(+ [metadata], _code_block_yaml("my_block"), impose_defaults=True, scout_trajectory=_SCOUT_TRAJECTORY+ )++ assert normalized == {}+ assert error is not None+ assert "has unfilled `goal_value_paths`" in error+ assert "terminal verifier expectation" in error+ assert "requires `goal_value_paths` for terminal criteria" in error+def test_omitted_page_dependencies_filled_from_trajectory(self) -> None:metadata = _valid_metadata("my_block")metadata.pop("page_dependencies")@@ -299,6 +359,7 @@ class TestSeamImposition:metadata = {"block_label": "my_block","declared_goal": "g",+ "terminal_verifier_expectations": [{"goal_value_paths": ["records[].number"]}],"observation_refs": [{"observation_ref": "obs1", "status": "observed_not_verified"}],}normalized, error = _normalize_code_artifact_metadata(@@ -315,7 +376,7 @@ class TestSeamImposition:metadata = {"block_label": "my_block","declared_goal": "g",- "claimed_outcomes": [{"text": "rows visible"}],+ "claimed_outcomes": [{"text": "rows visible", "goal_value_paths": ["records[].number"]}],"completion_criteria": [{"text": "rows shown"}],}normalized, error = _normalize_code_artifact_metadata(@@ -398,7 +459,7 @@ class TestStaleLabelRekey:assert row["declared_goal"]assert row["page_dependencies"]assert row["observation_refs"]- _assert_passes_full_validator(row)+ _assert_passes_skeleton_validator(row)def test_partial_coverage_gets_skeleton_for_uncovered_label_when_imposing(self) -> None:yaml = textwrap.dedent(@@ -423,7 +484,7 @@ class TestStaleLabelRekey:)assert error is Noneassert sorted(normalized.keys()) == ["block_one", "block_two"]- _assert_passes_full_validator(normalized["block_two"])+ _assert_passes_skeleton_validator(normalized["block_two"])def test_duplicate_label_keeps_first_entry(self) -> None:first = _valid_metadata("my_block")diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex 325b496ae..2d82eaea1 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -223,6 +223,30 @@ def _submit_interaction(}+def _terminal_metadata(label: str, declared_goal: str) -> dict:+ goal_value_paths = ["records[].number"]+ return {+ "block_label": label,+ "declared_goal": declared_goal,+ "claimed_outcomes": [+ {+ "id": f"claim:{label}",+ "scope": "outcome",+ "text": declared_goal,+ "status": "observed_not_verified",+ "goal_value_paths": goal_value_paths,+ }+ ],+ "terminal_verifier_expectations": [+ {+ "id": f"expectation:{label}",+ "text": declared_goal,+ "goal_value_paths": goal_value_paths,+ }+ ],+ }++class TestCodeSafetySeam:def test_import_in_new_code_block_is_a_seam_error(self) -> None:errors = _code_block_safety_errors(_IMPORTING_CODE_YAML, None)@@ -257,7 +281,7 @@ class TestCodeSafetySeam:@pytest.mark.asyncioasync def test_code_rejection_does_not_salvage_metadata_into_ctx(self) -> None:ctx = _code_only_ctx()- metadata = [{"block_label": "search_registry", "declared_goal": "search the registry"}]+ metadata = [_terminal_metadata("search_registry", "search the registry")]result = await _update_workflow({"workflow_yaml": _IMPORTING_CODE_YAML, "code_artifact_metadata": metadata}, ctx)@@ -442,7 +466,7 @@ class TestSeamSalvageIntoContext:""")metadata = [- {"block_label": "block_one", "declared_goal": "search the registry"},+ _terminal_metadata("block_one", "search the registry"),{"block_label": "block_two","declared_goal": "expand the result rows",@@ -492,15 +516,15 @@ class TestSeamSalvageIntoContext:)ctx = _code_only_ctx()ctx.workflow_yaml = draft_yaml- stored_block_b = {"block_label": "block_b", "declared_goal": "expand the result rows"}+ stored_block_b = _terminal_metadata("block_b", "expand the result rows")ctx.code_artifact_metadata = {- "block_a": {"block_label": "block_a", "declared_goal": "search the registry"},+ "block_a": _terminal_metadata("block_a", "search the registry"),"block_b": stored_block_b,}ctx.workflow_verification_evidence.code_artifact_metadata = dict(ctx.code_artifact_metadata)metadata = [- {"block_label": "block_a", "declared_goal": "search the registry"},- {"block_label": "ghost", "declared_goal": "does not exist"},+ _terminal_metadata("block_a", "search the registry"),+ _terminal_metadata("ghost", "does not exist"),]result = await _update_workflow({"workflow_yaml": submitted_yaml, "code_artifact_metadata": metadata}, ctx)@@ -517,7 +541,7 @@ class TestSeamSalvageIntoContext:@pytest.mark.asyncioasync def test_minimal_metadata_with_trajectory_produces_no_violation_error(self) -> None:ctx = _code_only_ctx()- metadata = [{"block_label": "search_registry", "declared_goal": "search the registry"}]+ metadata = [_terminal_metadata("search_registry", "search the registry")]result = await _update_workflow({"workflow_yaml": _SAFE_CODE_YAML, "code_artifact_metadata": metadata}, ctx)# The seam may reject later (credential checks need the app); the metadata# contract itself must not be the rejection.@@ -536,7 +560,7 @@ class TestStaleLabelSeamFlow:# path can bounce the submission back to the model.ctx = _code_only_ctx()ctx.workflow_yaml = _SAFE_CODE_YAML- metadata = [{"block_label": "search_certificant_stale", "declared_goal": "search the registry"}]+ metadata = [_terminal_metadata("search_certificant_stale", "search the registry")]result = await _update_workflow({"workflow_yaml": _SAFE_CODE_YAML, "code_artifact_metadata": metadata}, ctx)@@ -557,8 +581,7 @@ class TestStaleLabelSeamFlow:ctx.scout_trajectory = []metadata = [{- "block_label": "search_registry",- "declared_goal": "search the registry",+ **_terminal_metadata("search_registry", "search the registry"),"observation_refs": [{"observation_ref": "obs1", "status": "observed_not_verified"}],}]diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.pyindex 6e771b474..d49925f2c 100644--- a/tests/unit/test_copilot_completion_verification.py+++ b/tests/unit/test_copilot_completion_verification.py@@ -467,8 +467,10 @@ def test_record_run_blocks_keeps_building_on_mid_build_no_evidence() -> None:# A nav-only WIP that has not added a confirmation block yet must keep building,# not enter repair...assert ctx.last_test_suspicious_success is False- assert ctx.last_full_workflow_test_ok is True- # ...but terminal success stays withheld because the outcome is unverified.+ # ...but terminal success and good-workflow promotion stay withheld because+ # the outcome is unverified.+ assert ctx.last_full_workflow_test_ok is False+ assert ctx.last_good_workflow is Noneassert _completion_contract_not_violated(ctx) is Falsediff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.pyindex 3aa143a93..de71f98a4 100644--- a/tests/unit/test_copilot_composition_evidence.py+++ b/tests/unit/test_copilot_composition_evidence.py@@ -1983,6 +1983,33 @@ def test_structured_parses_forms_labels_options_and_submit() -> None:assert has_bounded_page_schema(parsed) is True+def test_structured_preserves_populated_result_container_content() -> None:+ payload = {+ "page_title": "Lookup",+ "forms": [],+ "navigation_targets": [],+ "result_containers": [+ {"tag": "table", "selector": "#results", "row_count": 1, "sample_rows": ["Jane Doe Active"]},+ {"tag": "div", "selector": "#records", "text": "Record A ready"},+ ],+ "challenge_controls": [],+ "modal_overlays": [],+ "visual_obstruction_candidates": [],+ "visible_text_excerpt": "Jane Doe Active Record A ready",+ "anti_bot_indicators": [],+ }++ parsed = parse_composition_structured(+ payload, inspected_url="https://example.com/lookup", current_url="https://example.com/lookup"+ )++ assert parsed is not None+ table, records = parsed["result_containers"]+ assert table["row_count"] == 1+ assert table["sample_rows"] == ["Jane Doe Active"]+ assert records["text_excerpt"] == "Record A ready"++def test_structured_detects_modal_overlay_with_dismiss_controls() -> None:payload = {"page_title": "",@@ -2207,6 +2234,10 @@ def _ac_projection(evidence: dict[str, Any]) -> dict[str, Any]:"forms": forms,"navigation_targets": sorted(target["href"] for target in evidence["navigation_targets"]),"result_containers": sorted((rc["tag"], rc["selector"]) for rc in evidence["result_containers"]),+ "result_content": sorted(+ (rc["selector"], rc.get("row_count"), tuple(rc.get("sample_rows") or []), rc.get("text_excerpt", ""))+ for rc in evidence["result_containers"]+ ),"modal_selectors": sorted((overlay["selector"], bool(overlay.get("dismiss_controls"))) for overlay in evidence["modal_overlays"]),diff --git a/tests/unit/test_copilot_per_tool_budget.py b/tests/unit/test_copilot_per_tool_budget.pyindex 6ad1a68e5..1221cdd3f 100644--- a/tests/unit/test_copilot_per_tool_budget.py+++ b/tests/unit/test_copilot_per_tool_budget.py@@ -22,6 +22,15 @@ from types import SimpleNamespaceimport pytestfrom skyvern.forge.sdk.copilot.context import CopilotContext+from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (+ DiagnosisFailureType,+ DiagnosisInput,+ DiagnosisRepairContract,+ DiagnosisResult,+ RepairDecision,+ RepairNextAction,+ VerificationResult,+)from skyvern.forge.sdk.copilot.enforcement import (MAX_PER_TOOL_BUDGET_NUDGES,POST_ANTI_BOT_FAILED_TEST_NUDGE,@@ -1100,16 +1109,51 @@ def _armed_post_run_context() -> CopilotContext:return ctx+def _anti_bot_stop_contract() -> DiagnosisRepairContract:+ return DiagnosisRepairContract(+ diagnosis_input=DiagnosisInput(+ source_tool="update_and_run_blocks",+ workflow_run_id="wr_blocked",+ run_status="failed",+ failure_categories=["ANTI_BOT_DETECTION"],+ ),+ diagnosis_result=DiagnosisResult(+ suspected_failure_type=DiagnosisFailureType.REPAIRABLE_BLOCK_FAILURE,+ root_cause_summary="human-verification challenge blocked a disabled submit control",+ confidence=0.85,+ evidence_references=["failure_category:ANTI_BOT_DETECTION"],+ ),+ repair_decision=RepairDecision(+ next_action=RepairNextAction.STOP,+ proposed_change_summary="Stop retrying the current failure and report the blocker.",+ ),+ verification_result=VerificationResult(+ run_status="failed",+ remaining_blocker="human-verification challenge blocked a disabled submit control",+ ),+ )+++_BLOCK_LABEL_ARGS = {"block_labels": ["submit_registry_search"]}+_RESULT_CONTAINER_SHELL = [{"tag": "table", "selector": "#results", "row_selector": "#results tbody tr"}]+++def _stash_prior_result_evidence_bounce(ctx: CopilotContext) -> None:+ ctx.composition_page_evidence = _challenge_gated_post_run_evidence(result_containers=_RESULT_CONTAINER_SHELL)+ prior = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")+ assert prior is not None+ assert prior.internal_reason_code == "tool_error_post_budget_challenge_result_evidence"+ ctx.tool_blocker_signals.append(prior)++def test_terminal_challenge_routes_to_answer_path_when_result_evidence_in_same_packet() -> None:ctx = _armed_post_run_context()ctx.composition_page_evidence = _challenge_gated_post_run_evidence(- result_containers=[{"tag": "table", "selector": "#results", "row_selector": "#results tbody tr"}],+ result_containers=_RESULT_CONTAINER_SHELL,visible_text_excerpt="SAMPLE, PERSON Anytown, XY Exampleland Certified Active",)- signal = _post_budget_terminal_challenge_signal(- ctx, {"block_labels": ["submit_registry_search"]}, "update_and_run_blocks"- )+ signal = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")assert signal is not Noneassert signal.internal_reason_code == "tool_error_post_budget_challenge_result_evidence"@@ -1119,6 +1163,162 @@ def test_terminal_challenge_routes_to_answer_path_when_result_evidence_in_same_passert "result container" in signal.agent_steering_text+def test_terminal_challenge_first_container_shell_bounce_stays_retryable() -> None:+ ctx = _armed_post_run_context()+ ctx.latest_diagnosis_repair_contract = _anti_bot_stop_contract()+ ctx.composition_page_evidence = _challenge_gated_post_run_evidence(result_containers=_RESULT_CONTAINER_SHELL)++ signal = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")++ assert signal is not None+ assert signal.internal_reason_code == "tool_error_post_budget_challenge_result_evidence"+ assert signal.renders_final_reply is False+ assert signal.extra["challenge_signature"]+ assert signal.extra["result_evidence_signature"]+ assert signal.extra["result_evidence_populated"] is False+++def test_terminal_challenge_repeated_container_shell_with_stop_contract_escalates() -> None:+ ctx = _armed_post_run_context()+ _stash_prior_result_evidence_bounce(ctx)+ ctx.latest_diagnosis_repair_contract = _anti_bot_stop_contract()++ signal = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")++ assert signal is not None+ assert signal.internal_reason_code == "tool_error_post_budget_challenge_blocker"+ assert signal.renders_final_reply is True+ assert signal.recovery_hint == "report_blocker_to_user"+ assert signal.cleared_by_tools == frozenset()+ assert signal.extra["escalated_from_reason_code"] == "tool_error_post_budget_challenge_result_evidence"+ assert "human verification" in signal.user_facing_reason and "Search" in signal.user_facing_reason+++def test_terminal_challenge_changed_evidence_resets_container_shell_escalation() -> None:+ ctx = _armed_post_run_context()+ _stash_prior_result_evidence_bounce(ctx)+ ctx.latest_diagnosis_repair_contract = _anti_bot_stop_contract()+ ctx.composition_page_evidence = _challenge_gated_post_run_evidence(+ forms=[{"submit_controls": [{"text": "Lookup", "selector": "#lookup", "disabled": True}]}],+ challenge_state={+ "detected": True,+ "kind": "human_verification",+ "requires_human_verification": True,+ "gates_submit_controls": True,+ "gated_submit_controls": [{"text": "Lookup", "selector": "#lookup", "disabled": True}],+ },+ result_containers=[{"tag": "table", "selector": "#results", "row_selector": "#results tbody tr"}],+ )++ signal = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")++ assert signal is not None+ assert signal.internal_reason_code == "tool_error_post_budget_challenge_result_evidence"+ assert signal.renders_final_reply is False+++ "evidence_extra",+ [+ {+ "result_containers": [+ {+ "tag": "table",+ "selector": "#results",+ "row_selector": "#results tbody tr",+ "row_count": 1,+ "sample_rows": ["JANE DOE Active"],+ }+ ]+ },+ {+ "result_containers": _RESULT_CONTAINER_SHELL,+ "visible_text_excerpt": "SAMPLE, PERSON Anytown, XY Exampleland Certified Active",+ },+ ],+)+def test_terminal_challenge_populated_results_stay_retryable_after_stop_contract(+ evidence_extra: dict[str, object],+) -> None:+ ctx = _armed_post_run_context()+ ctx.composition_page_evidence = _challenge_gated_post_run_evidence(**evidence_extra)+ prior = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")+ assert prior is not None+ ctx.tool_blocker_signals.append(prior)+ ctx.latest_diagnosis_repair_contract = _anti_bot_stop_contract()++ signal = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")++ assert signal is not None+ assert signal.internal_reason_code == "tool_error_post_budget_challenge_result_evidence"+ assert signal.renders_final_reply is False+ assert signal.extra["result_evidence_populated"] is True+++def test_terminal_challenge_chrome_visible_text_does_not_defeat_stop_escalation() -> None:+ ctx = _armed_post_run_context()+ ctx.composition_page_evidence = _challenge_gated_post_run_evidence(+ forms=[+ {+ "fields": [+ {"label": "License Number", "name": "license_number"},+ {"label": "County", "name": "county", "options": [{"text": "County", "value": "county"}]},+ ],+ "submit_controls": [{"text": "Search", "selector": "#search", "disabled": True}],+ }+ ],+ result_containers=_RESULT_CONTAINER_SHELL,+ visible_text_excerpt="License Number County Search Verify you are human",+ )+ prior = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")+ assert prior is not None+ ctx.tool_blocker_signals.append(prior)+ ctx.latest_diagnosis_repair_contract = _anti_bot_stop_contract()++ signal = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")++ assert signal is not None+ assert signal.internal_reason_code == "tool_error_post_budget_challenge_blocker"+ assert signal.renders_final_reply is True+++def test_terminal_challenge_non_table_result_heading_does_not_defeat_stop_escalation() -> None:+ ctx = _armed_post_run_context()+ ctx.composition_page_evidence = _challenge_gated_post_run_evidence(+ result_containers=[{"tag": "div", "selector": "#results", "text_excerpt": "Search results"}],+ )+ prior = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")+ assert prior is not None+ ctx.tool_blocker_signals.append(prior)+ ctx.latest_diagnosis_repair_contract = _anti_bot_stop_contract()++ signal = _post_budget_terminal_challenge_signal(ctx, _BLOCK_LABEL_ARGS, "update_and_run_blocks")++ assert signal is not None+ assert signal.internal_reason_code == "tool_error_post_budget_challenge_blocker"+ assert signal.renders_final_reply is True+++def test_tool_loop_error_replaces_retryable_container_shell_with_terminal_challenge_stop() -> None:+ ctx = _armed_post_run_context()+ ctx.composition_page_evidence = _challenge_gated_post_run_evidence(result_containers=_RESULT_CONTAINER_SHELL)++ first = _tool_loop_error(ctx, "update_and_run_blocks", _BLOCK_LABEL_ARGS)+ assert first is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "tool_error_post_budget_challenge_result_evidence"+ assert ctx.blocker_signal.renders_final_reply is False++ ctx.latest_diagnosis_repair_contract = _anti_bot_stop_contract()+ second = _tool_loop_error(ctx, "update_and_run_blocks", _BLOCK_LABEL_ARGS)++ assert second is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "tool_error_post_budget_challenge_blocker"+ assert ctx.blocker_signal.renders_final_reply is True+ assert ctx.blocker_signal.recovery_hint == "report_blocker_to_user"++def test_terminal_challenge_fires_without_result_evidence_and_names_observed_facts() -> None:ctx = _armed_post_run_context()ctx.composition_page_evidence = _challenge_gated_post_run_evidence()diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.pyindex 3d07e6c73..f34fded5f 100644--- a/tests/unit/test_copilot_run_outcome_event.py+++ b/tests/unit/test_copilot_run_outcome_event.py@@ -205,7 +205,7 @@ async def test_mid_build_fall_through_still_emits_not_demonstrated(monkeypatch:assert [frame.verdict for frame in frames] == ["evaluating", "not_demonstrated"]assert frames[-1].reason_code == "outcome_not_demonstrated"assert ctx.last_test_suspicious_success is False- assert ctx.last_full_workflow_test_ok is True+ assert ctx.last_full_workflow_test_ok is False@pytest.mark.asynciodiff --git a/tests/unit/test_copilot_run_output_content_gate.py b/tests/unit/test_copilot_run_output_content_gate.pyindex 58d37092c..9359903be 100644--- a/tests/unit/test_copilot_run_output_content_gate.py+++ b/tests/unit/test_copilot_run_output_content_gate.py@@ -119,6 +119,93 @@ def _genuine_success_run_result() -> dict[str, Any]:)+def _all_null_goal_fields_run_result() -> dict[str, Any]:+ return _run_result(+ [+ _code_block(+ "expand_result_rows",+ {+ "search_completed": True,+ "no_results": False,+ "certification_records": [+ {+ "name": "Generic Credential A",+ "number": None,+ "expiration_date": None,+ "evidence_text": "Navigation menu text: Generic Credential A",+ },+ {+ "name": "Generic Credential B",+ "number": "",+ "expiration_date": None,+ "evidence_text": "Footer text from registry.example.com",+ },+ ],+ },+ )+ ]+ )+++def _goal_field_success_run_result() -> dict[str, Any]:+ return _run_result(+ [+ _code_block(+ "expand_result_rows",+ {+ "search_completed": True,+ "certification_records": [+ {+ "name": "DOE, JANE",+ "number": "12345",+ "expiration_date": "2027-01-31",+ "evidence_text": "DOE, JANE - credential 12345 expires 2027-01-31",+ }+ ],+ },+ )+ ]+ )+++def _partial_goal_field_run_result() -> dict[str, Any]:+ return _run_result(+ [+ _code_block(+ "expand_result_rows",+ {+ "search_completed": True,+ "certification_records": [+ {+ "name": "DOE, JANE",+ "number": "12345",+ "expiration_date": None,+ "evidence_text": "DOE, JANE - credential 12345",+ }+ ],+ },+ )+ ]+ )+++def _top_level_goal_field_success_run_result() -> dict[str, Any]:+ return _run_result(+ [+ _code_block(+ "expand_result_rows",+ [+ {+ "name": "DOE, JANE",+ "number": "12345",+ "expiration_date": "2027-01-31",+ }+ ],+ )+ ]+ )++def _terminal_metadata_entry(label: str = "search_registry_person") -> dict[str, Any]:return {"block_label": label,@@ -138,6 +225,28 @@ def _terminal_metadata_entry(label: str = "search_registry_person") -> dict[str,}+def _terminal_metadata_with_goal_fields(label: str = "expand_result_rows") -> dict[str, Any]:+ entry = _terminal_metadata_entry(label)+ goal_value_paths = ["certification_records[].number", "certification_records[].expiration_date"]+ entry["claimed_outcomes"][0]["goal_value_paths"] = goal_value_paths+ entry["terminal_verifier_expectations"] = [+ {+ "id": "expectation:goal",+ "text": "Terminal verification observes requested registry fields.",+ "criteria_ids": ["criterion:goal_0"],+ "goal_value_paths": goal_value_paths,+ }+ ]+ return entry+++def _terminal_metadata_with_top_level_goal_fields(label: str = "expand_result_rows") -> dict[str, Any]:+ entry = _terminal_metadata_entry(label)+ goal_value_paths = ["$[*].number", "$[0].expiration_date"]+ entry["claimed_outcomes"][0]["goal_value_paths"] = goal_value_paths+ return entry++def test_blocked_flag_run_reports_structured_blocker() -> None:blocker = _run_blocks_structured_blocker_message(_blocked_flag_run_result())assert blocker is not None@@ -224,6 +333,83 @@ def test_genuine_success_run_keeps_clean_path() -> None:assert ctx.last_full_workflow_test_ok is True+def test_all_null_metadata_goal_fields_are_flagged_as_no_goal_content() -> None:+ result = _all_null_goal_fields_run_result()+ ctx = _ctx(result["data"]["blocks"])+ ctx.code_artifact_metadata = {"expand_result_rows": _terminal_metadata_with_goal_fields()}++ assert _run_blocks_structured_blocker_message(result) is None+ _, empty_data_blocks, _ = _analyze_run_blocks(result, ctx)+ assert empty_data_blocks is True+ assert _is_outcome_evidence_candidate(ctx, result) is False++ _record_run_blocks_result(ctx, result, completion_verification=None)++ assert ctx.last_test_ok is None+ assert ctx.last_test_suspicious_success is True+ assert ctx.null_data_streak_count == 1+ assert ctx.last_full_workflow_test_ok is False+ assert getattr(ctx, "last_good_workflow", None) is None+++def test_metadata_goal_fields_with_values_keep_clean_path() -> None:+ result = _goal_field_success_run_result()+ ctx = _ctx(result["data"]["blocks"])+ ctx.code_artifact_metadata = {"expand_result_rows": _terminal_metadata_with_goal_fields()}++ _, empty_data_blocks, _ = _analyze_run_blocks(result, ctx)+ assert empty_data_blocks is False+ assert _is_outcome_evidence_candidate(ctx, result) is True++ _record_run_blocks_result(ctx, result, completion_verification=None)++ assert ctx.last_test_ok is True+ assert ctx.last_test_suspicious_success is False+ assert ctx.last_full_workflow_test_ok is True+++def test_partial_metadata_goal_fields_are_flagged_as_no_goal_content() -> None:+ result = _partial_goal_field_run_result()+ ctx = _ctx(result["data"]["blocks"])+ ctx.code_artifact_metadata = {"expand_result_rows": _terminal_metadata_with_goal_fields()}++ _, empty_data_blocks, _ = _analyze_run_blocks(result, ctx)+ assert empty_data_blocks is True+ assert _is_outcome_evidence_candidate(ctx, result) is False+++def test_top_level_array_goal_value_paths_keep_clean_path() -> None:+ result = _top_level_goal_field_success_run_result()+ ctx = _ctx(result["data"]["blocks"])+ ctx.code_artifact_metadata = {"expand_result_rows": _terminal_metadata_with_top_level_goal_fields()}++ _, empty_data_blocks, _ = _analyze_run_blocks(result, ctx)+ assert empty_data_blocks is False+ assert _is_outcome_evidence_candidate(ctx, result) is True+++def test_array_goal_value_path_does_not_match_scalar_root() -> None:+ result = _run_result([_code_block("expand_result_rows", {"number": "12345"})])+ ctx = _ctx(result["data"]["blocks"])+ ctx.code_artifact_metadata = {"expand_result_rows": _terminal_metadata_with_top_level_goal_fields()}++ _, empty_data_blocks, _ = _analyze_run_blocks(result, ctx)+ assert empty_data_blocks is True+ assert _is_outcome_evidence_candidate(ctx, result) is False+++def test_candidacy_and_recording_agree_on_all_null_metadata_goal_fields() -> None:+ result = _all_null_goal_fields_run_result()+ ctx = _ctx(result["data"]["blocks"])+ ctx.code_artifact_metadata = {"expand_result_rows": _terminal_metadata_with_goal_fields()}++ assert _is_outcome_evidence_candidate(ctx, result) is False++ _record_run_blocks_result(ctx, result, completion_verification=None)+ assert ctx.last_test_ok is None+ assert ctx.last_test_suspicious_success is True++def test_empty_goal_collections_without_blocker_are_flagged() -> None:result = _run_result([_code_block("search_registry_person", {"records": [], "result_count": 0})])ctx = _ctx(result["data"]["blocks"])@@ -341,4 +527,30 @@ def test_judge_no_evidence_keeps_building_without_metadata() -> None:_record_run_blocks_result(ctx, result, completion_verification=_no_evidence("c0"))assert ctx.last_test_suspicious_success is False- assert ctx.last_full_workflow_test_ok is True+ assert ctx.last_full_workflow_test_ok is False+ assert getattr(ctx, "last_good_workflow", None) is None+ assert "failure_reason" not in result["data"]++[email protected]("metadata_shape", ["none", "terminal", "prefix_only"])+def test_judge_unmet_on_detector_clean_run_does_not_reset_streaks_or_promote(metadata_shape: str) -> None:+ result = _genuine_success_run_result()+ ctx = _ctx(result["data"]["blocks"])+ if metadata_shape == "terminal":+ ctx.code_artifact_metadata = {"search_registry_person": _terminal_metadata_entry()}+ elif metadata_shape == "prefix_only":+ entry = _terminal_metadata_entry()+ entry["completion_criteria"][0]["level"] = "prefix"+ entry["completion_criteria"][0]["terminal"] = False+ ctx.code_artifact_metadata = {"search_registry_person": entry}+ ctx.failed_test_nudge_count = 2+ ctx.null_data_streak_count = 3+ ctx.probable_site_block_streak_count = 4++ _record_run_blocks_result(ctx, result, completion_verification=_no_evidence("c0"))++ assert ctx.failed_test_nudge_count == 2+ assert ctx.null_data_streak_count == 3+ assert ctx.probable_site_block_streak_count == 4+ assert ctx.last_full_workflow_test_ok is False+ assert getattr(ctx, "last_good_workflow", None) is None