Skip to content

Automate browser based workflows with AI

SKY-11838: Copilot: recognize scouted extraction data by value format, not just page labels (#7374)

Andrew Neilsone204dc095f28
diff --git a/skyvern/forge/sdk/copilot/build_test_outcome.py b/skyvern/forge/sdk/copilot/build_test_outcome.py
index fb4893ba4..028eceb69 100644
--- a/skyvern/forge/sdk/copilot/build_test_outcome.py
+++ b/skyvern/forge/sdk/copilot/build_test_outcome.py
@@ -22,7 +22,11 @@ from skyvern.forge.sdk.copilot.completion_verification import (
from skyvern.forge.sdk.copilot.composition_evidence import has_bounded_page_schema
from skyvern.forge.sdk.copilot.context import CodeAuthoringRepairContext
from skyvern.forge.sdk.copilot.request_policy import redact_raw_secrets_for_prompt
-from skyvern.forge.sdk.copilot.result_evidence import LoadedResultCompositionEvidence
+from skyvern.forge.sdk.copilot.result_evidence import (
+ LoadedResultCompositionEvidence,
+ ScoutObservationContract,
+ scout_observation_contract_valid,
+)
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome, RunOutcomeReasonCode
LOG = structlog.get_logger()
@@ -438,6 +442,7 @@ def arm_recorded_outcome_grounding_requirement(ctx: object) -> RecordedOutcomeGr
)
if workflow_run_id is None:
ctx.composition_page_evidence = None # type: ignore[attr-defined]
+ ctx.scout_observation_contract = None # type: ignore[attr-defined]
ctx.recorded_outcome_grounding_requirement = requirement # type: ignore[attr-defined]
LOG.info(
"copilot recorded outcome grounding armed",
@@ -465,6 +470,9 @@ def recorded_outcome_grounding_requires_current_page(ctx: object) -> bool:
evidence = getattr(ctx, "composition_page_evidence", None)
if isinstance(evidence, dict) and _evidence_current_url(evidence):
return True
+ contract = getattr(ctx, "scout_observation_contract", None)
+ if scout_observation_contract_valid(contract):
+ return True
observed_urls = getattr(ctx, "observed_browser_urls", None)
return isinstance(observed_urls, list) and any(isinstance(url, str) and url.strip() for url in observed_urls)
@@ -474,9 +482,12 @@ def maybe_satisfy_recorded_outcome_grounding_requirement(ctx: object) -> bool:
if not isinstance(requirement, RecordedOutcomeGroundingRequirement):
return False
evidence = getattr(ctx, "composition_page_evidence", None)
+ contract = getattr(ctx, "scout_observation_contract", None)
payload = _grounding_payload_from_evidence(requirement, evidence)
if payload is None:
- _log_grounding_rejection(requirement, evidence)
+ payload = _grounding_payload_from_scout_contract(requirement, contract)
+ if payload is None:
+ _log_grounding_rejection(requirement, evidence, contract)
return False
satisfied_requirement = requirement.model_copy(update={"satisfied": True, "payload": payload})
ctx.recorded_outcome_grounding_requirement = satisfied_requirement # type: ignore[attr-defined]
@@ -492,11 +503,15 @@ def maybe_satisfy_recorded_outcome_grounding_requirement(ctx: object) -> bool:
return True
-def _log_grounding_rejection(requirement: RecordedOutcomeGroundingRequirement, evidence: object) -> None:
+def _log_grounding_rejection(
+ requirement: RecordedOutcomeGroundingRequirement,
+ evidence: object,
+ contract: object = None,
+) -> None:
evidence_dict = evidence if isinstance(evidence, dict) else {}
LOG.info(
"copilot recorded outcome grounding rejected",
- reject_reason=_grounding_reject_reason(requirement, evidence),
+ reject_reason=_grounding_reject_reason(requirement, evidence, contract),
structural_key=requirement.structural_key,
requirement_workflow_run_id=requirement.workflow_run_id,
evidence_workflow_run_id=evidence_dict.get("workflow_run_id"),
@@ -509,18 +524,66 @@ def _log_grounding_rejection(requirement: RecordedOutcomeGroundingRequirement, e
def _grounding_reject_reason(
requirement: RecordedOutcomeGroundingRequirement,
evidence: object,
+ contract: object = None,
+) -> Literal["not_inspect_source", "degraded_page", "run_id_mismatch", "no_url"]:
+ if isinstance(evidence, dict) and evidence.get("source_tool") == _INSPECT_PAGE_SOURCE_TOOL:
+ if _evidence_current_url(evidence) is None:
+ return "no_url"
+ run_id = requirement.workflow_run_id
+ if isinstance(run_id, str) and run_id:
+ if evidence.get("observed_after_workflow_run") is not True or evidence.get("workflow_run_id") != run_id:
+ return "run_id_mismatch"
+ return "degraded_page"
+ if isinstance(contract, ScoutObservationContract):
+ return _scout_contract_reject_reason(requirement, contract)
+ return "not_inspect_source"
+
+
+def _scout_contract_reject_reason(
+ requirement: RecordedOutcomeGroundingRequirement,
+ contract: ScoutObservationContract,
) -> Literal["not_inspect_source", "degraded_page", "run_id_mismatch", "no_url"]:
- if not isinstance(evidence, dict) or evidence.get("source_tool") != _INSPECT_PAGE_SOURCE_TOOL:
+ if not scout_observation_contract_valid(contract):
return "not_inspect_source"
- if _evidence_current_url(evidence) is None:
+ if not contract.source_url.strip():
return "no_url"
run_id = requirement.workflow_run_id
if isinstance(run_id, str) and run_id:
- if evidence.get("observed_after_workflow_run") is not True or evidence.get("workflow_run_id") != run_id:
+ if not contract.observed_after_workflow_run or contract.workflow_run_id != run_id:
return "run_id_mismatch"
return "degraded_page"
+def _grounding_payload_from_scout_contract(
+ requirement: RecordedOutcomeGroundingRequirement,
+ contract: object,
+) -> RecordedOutcomeGroundingPayload | None:
+ if not isinstance(contract, ScoutObservationContract) or not scout_observation_contract_valid(contract):
+ return None
+ run_id = requirement.workflow_run_id
+ if isinstance(run_id, str) and run_id:
+ if not contract.observed_after_workflow_run or contract.workflow_run_id != run_id:
+ return None
+ capture_degraded = not contract.has_bounded_page_schema
+ diagnostic_reason: Literal["none", "empty_page", "challenge_gated", "capture_degraded"] = (
+ "capture_degraded" if capture_degraded else "none"
+ )
+ return RecordedOutcomeGroundingPayload(
+ repeated_structural_key=requirement.structural_key,
+ source_tool=contract.source_tool,
+ observed_after_workflow_run=contract.observed_after_workflow_run,
+ workflow_run_id=contract.workflow_run_id,
+ capture_degraded=capture_degraded,
+ target_url=requirement.required_target_url,
+ source_url=contract.source_url,
+ requirement_workflow_run_id=requirement.workflow_run_id,
+ payload_workflow_run_id=contract.workflow_run_id,
+ diagnostic_reason=diagnostic_reason,
+ current_origin=_origin(contract.source_url),
+ current_url_present=True,
+ )
+
+
def _grounding_payload_from_evidence(
requirement: RecordedOutcomeGroundingRequirement,
evidence: object,
diff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
index 4535b8a2c..fec7dfe7d 100644
--- a/skyvern/forge/sdk/copilot/composition_browser_expressions.py
+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
@@ -444,6 +444,8 @@ const resultEntry = (node, tag) => {
cells: Array.from(row.querySelectorAll(':scope > th, :scope > td')).slice(0, MAX_TABLE_HEADERS).map((cell, columnIndex) => ({
column_index: columnIndex,
visible: elementVisible(cell),
+ has_text: !!nodeText(cell),
+ text: nodeText(cell),
})),
}));
const sampleRows = rows.map((r) => Array.from(r.children || []).map((c) => nodeText(c)).filter(Boolean).join(' ') || nodeText(r)).filter(resultRowTextIsContent).slice(0, MAX_RESULT_SAMPLE_ROWS);
@@ -483,7 +485,7 @@ for (const node of all) {
let position = -1;
try { position = Array.from(document.querySelectorAll(selector)).indexOf(node); } catch (e) { position = -1; }
if (position < 0) continue;
- keyValueRelations.push({ key_text: keyText, container_selector: selector, container_match_count: matches, container_position: position, value_child_index: 1, direct_child_count: children.length, visible: true, value_visible: elementVisible(children[1]) });
+ keyValueRelations.push({ key_text: keyText, value_text: valueText, container_selector: selector, container_match_count: matches, container_position: position, value_child_index: 1, direct_child_count: children.length, visible: true, value_visible: elementVisible(children[1]) });
}
const challengeControls = [];
diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.py
index 51821740e..a4211b7cf 100644
--- a/skyvern/forge/sdk/copilot/composition_evidence.py
+++ b/skyvern/forge/sdk/copilot/composition_evidence.py
@@ -645,6 +645,43 @@ def has_actionable_steer_content(evidence: dict[str, Any]) -> bool:
return isinstance(clickable_controls, list) and bool(clickable_controls)
+def has_witnessed_value_content(evidence: dict[str, Any]) -> bool:
+ """True when the capture carries binder-consumable rendered value content under the mint's own
+ witnesses: a key_value_relations entry with non-empty value_text, or a result_containers sample-row
+ cell with text. Truncated or warned captures void the matching channel, mirroring the mint."""
+ warnings = evidence.get("inspection_warnings")
+ if isinstance(warnings, list) and warnings:
+ return False
+ if evidence.get("key_value_relations_truncated") is not True:
+ relations = evidence.get("key_value_relations")
+ if isinstance(relations, list):
+ for relation in relations:
+ if not isinstance(relation, dict):
+ continue
+ value_text = relation.get("value_text")
+ if isinstance(value_text, str) and value_text.strip():
+ return True
+ if evidence.get("result_containers_truncated") is not True:
+ containers = evidence.get("result_containers")
+ if isinstance(containers, list):
+ for container in containers:
+ if not isinstance(container, dict):
+ continue
+ rows = container.get("rows")
+ if not isinstance(rows, list):
+ continue
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ cells = row.get("cells")
+ if not isinstance(cells, list):
+ continue
+ for cell in cells:
+ if isinstance(cell, dict) and cell.get("has_text") is True:
+ return True
+ return False
+
+
def _is_scout_interaction_evidence(evidence: dict[str, Any]) -> bool:
# A scout interaction that resolved a concrete selector proves the page rendered
# and the element was actionable, so it is non-hollow evidence of the reached
@@ -1509,6 +1546,7 @@ def _key_value_relations(soup: Any) -> tuple[list[dict[str, Any]], bool]:
relations.append(
{
"key_text": key_text,
+ "value_text": value_text,
"container_selector": selector,
"container_match_count": match_count,
"container_position": position,
@@ -1561,7 +1599,12 @@ def _result_container_entry(node: Any, *, soup: Any) -> dict[str, Any]:
"visible": True,
"has_row_header": row.select_one(":scope > th") is not None,
"cells": [
- {"column_index": column_index, "visible": True}
+ {
+ "column_index": column_index,
+ "visible": True,
+ "has_text": bool(_node_text(_cell)),
+ "text": _schema_text(_node_text(_cell), 120),
+ }
for column_index, _cell in enumerate(row.select(":scope > td")[:_MAX_TABLE_HEADERS])
],
}
@@ -2123,7 +2166,14 @@ def _structured_result_containers(value: Any) -> list[dict[str, Any]]:
column_index = raw_cell.get("column_index")
if not isinstance(column_index, int) or isinstance(column_index, bool) or column_index < 0:
continue
- cells.append({"column_index": column_index, "visible": raw_cell.get("visible") is True})
+ cells.append(
+ {
+ "column_index": column_index,
+ "visible": raw_cell.get("visible") is True,
+ "has_text": raw_cell.get("has_text") is True,
+ "text": _schema_text(_structured_str(raw_cell.get("text")), 120),
+ }
+ )
rows.append(
{
"row_index": row_index,
@@ -2198,6 +2248,7 @@ def _structured_key_value_relations(value: Any) -> list[dict[str, Any]]:
relations.append(
{
"key_text": key_text,
+ "value_text": _schema_text(_structured_str(item.get("value_text")), 240),
"container_selector": selector,
"container_match_count": match_count,
"container_position": position,
diff --git a/skyvern/forge/sdk/copilot/config.py b/skyvern/forge/sdk/copilot/config.py
index 4cfa0a910..33afa02f3 100644
--- a/skyvern/forge/sdk/copilot/config.py
+++ b/skyvern/forge/sdk/copilot/config.py
@@ -6,6 +6,7 @@ from dataclasses import dataclass, field
from enum import StrEnum
from skyvern.config import settings
+from skyvern.forge.sdk.copilot.output_extraction_plan import ShapeExpectation
class BlockAuthoringPolicy(StrEnum):
@@ -375,6 +376,7 @@ class CopilotConfig:
block_authoring_policy: BlockAuthoringPolicy = BlockAuthoringPolicy.STANDARD
impose_synthesized_code_block: bool = False
requested_output_path_aliases: dict[str, str] = field(default_factory=dict)
+ requested_output_shape_expectations: dict[str, ShapeExpectation] = field(default_factory=dict)
credential_pause_enabled: bool = field(default_factory=_default_credential_pause_enabled)
credential_pause_timeout_seconds: int = field(default_factory=_default_credential_pause_timeout_seconds)
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index aba3eade8..9ba76f801 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -57,7 +57,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (
)
from skyvern.forge.sdk.copilot.completion_criteria_store import requested_output_paths
from skyvern.forge.sdk.copilot.completion_verification import only_structural_requested_output_abstentions
-from skyvern.forge.sdk.copilot.composition_evidence import interactive_challenge_controls
+from skyvern.forge.sdk.copilot.composition_evidence import has_bounded_page_schema, interactive_challenge_controls
from skyvern.forge.sdk.copilot.config import (
DEFAULT_ENFORCEMENT_NUDGES,
DEFAULT_TOKEN_BUDGET,
@@ -98,6 +98,7 @@ from skyvern.forge.sdk.copilot.output_contracts import OutputContractAdvisorySta
from skyvern.forge.sdk.copilot.output_extraction_plan import (
RequestedOutputExtractionPlan,
derive_requested_output_extraction_plan,
+ resolve_shape_expectations_by_path,
)
from skyvern.forge.sdk.copilot.output_policy import (
completion_criterion_requires_browser_fill_delivery,
@@ -118,7 +119,10 @@ from skyvern.forge.sdk.copilot.request_policy import (
)
from skyvern.forge.sdk.copilot.result_evidence import (
COVERAGE_TOKEN_RE,
+ ScoutObservationContract,
covered_output_paths_in_result_containers,
+ mint_scout_observation_contract,
+ scout_observation_bound_paths,
)
from skyvern.forge.sdk.copilot.run_outcome import (
TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,
@@ -2262,6 +2266,9 @@ def synthesized_persistence_reopened(ctx: AgentContext) -> bool:
return synthesized_persistence_reopened_after_failed_run(ctx)
+# Intentionally distinct from request_policy._OUTPUT_GENERIC_WORDS: this list filters output-path leaf
+# tokens for coverage token matching, so it keeps phrase words the other list drops. Not unified — the
+# consumers differ.
_COVERAGE_GENERIC_TOKENS = frozenset(
{
"output",
@@ -2370,15 +2377,21 @@ def uncovered_requested_output_paths(ctx: AgentContext) -> set[str]:
return {path for path in requested if path not in covered and tokens_by_path.get(path)}
-def requested_output_extraction_plan(ctx: AgentContext) -> RequestedOutputExtractionPlan | None:
+def _requested_output_labels_by_path(ctx: AgentContext) -> dict[str, tuple[str, ...]]:
requested_paths = _requested_output_paths_for_ctx(ctx)
- if not requested_paths:
- return None
labels_by_path: dict[str, tuple[str, ...]] = {}
for criterion in _pre_run_gated_completion_criteria(ctx):
if criterion.output_path in requested_paths and criterion.outcome.strip():
labels_by_path.setdefault(criterion.output_path, ())
labels_by_path[criterion.output_path] += (criterion.outcome.strip(),)
+ return labels_by_path
+
+
+def requested_output_extraction_plan(ctx: AgentContext) -> RequestedOutputExtractionPlan | None:
+ requested_paths = _requested_output_paths_for_ctx(ctx)
+ if not requested_paths:
+ return None
+ labels_by_path = _requested_output_labels_by_path(ctx)
if set(labels_by_path) != requested_paths:
return None
return derive_requested_output_extraction_plan(
@@ -2410,31 +2423,73 @@ def requested_scalar_output_extraction_plan(ctx: AgentContext) -> RequestedOutpu
def requested_output_extraction_plan_changed(ctx: AgentContext, current: RequestedOutputExtractionPlan | None) -> bool:
if current is None or len(ctx.flow_evidence) < 2:
return False
- labels_by_path: dict[str, tuple[str, ...]] = {}
- requested_paths = _requested_output_paths_for_ctx(ctx)
- for criterion in _pre_run_gated_completion_criteria(ctx):
- if criterion.output_path in requested_paths and criterion.outcome.strip():
- labels_by_path.setdefault(criterion.output_path, ())
- labels_by_path[criterion.output_path] += (criterion.outcome.strip(),)
previous = derive_requested_output_extraction_plan(
flow_evidence=ctx.flow_evidence[:-1],
- labels_by_path=labels_by_path,
+ labels_by_path=_requested_output_labels_by_path(ctx),
)
return previous is not None and previous.identity != current.identity
-def record_scouted_output_coverage(ctx: AgentContext, page_evidence: dict[str, Any]) -> None:
- coverage_tokens = _requested_output_coverage_tokens(ctx)
- if not coverage_tokens:
+def mint_scout_observation_contract_for_ctx(
+ ctx: AgentContext,
+ page_evidence: dict[str, Any],
+ *,
+ url: str,
+) -> ScoutObservationContract | None:
+ labels_by_path = _requested_output_labels_by_path(ctx)
+ if not labels_by_path:
+ return None
+ copilot_config = getattr(ctx, "copilot_config", None)
+ shape_registry = copilot_config.requested_output_shape_expectations if copilot_config is not None else None
+ shape_expectations_by_path = resolve_shape_expectations_by_path(set(labels_by_path), shape_registry)
+ return mint_scout_observation_contract(
+ page_evidence,
+ labels_by_path=labels_by_path,
+ url=url,
+ has_bounded_page_schema=has_bounded_page_schema(page_evidence),
+ shape_expectations_by_path=shape_expectations_by_path or None,
+ )
+
+
+def record_scouted_output_coverage(
+ ctx: AgentContext,
+ page_evidence: dict[str, Any],
+ *,
+ contract: ScoutObservationContract | None = None,
+ include_lexical: bool = True,
+) -> None:
+ lexical_covered: set[str] = set()
+ if include_lexical:
+ coverage_tokens = _requested_output_coverage_tokens(ctx)
+ if coverage_tokens:
+ lexical_covered = covered_output_paths_in_result_containers(
+ page_evidence.get("result_containers"), coverage_tokens
+ )
+ contract_covered: set[str] = set()
+ bound_paths = scout_observation_bound_paths(contract)
+ if bound_paths:
+ contract_covered = bound_paths & _requested_output_paths_for_ctx(ctx)
+ candidate = lexical_covered | contract_covered
+ if not candidate:
return
- newly_covered = covered_output_paths_in_result_containers(page_evidence.get("result_containers"), coverage_tokens)
+ newly_covered = candidate - ctx.scouted_output_covered_paths
if not newly_covered:
return
ctx.scouted_output_covered_paths.update(newly_covered)
+ value_grounded = newly_covered & contract_covered
+ lexical_new = newly_covered & lexical_covered
+ if value_grounded and lexical_new:
+ provenance = "both"
+ elif value_grounded:
+ provenance = "value_grounded"
+ else:
+ provenance = "lexical"
LOG.info(
"copilot_scouted_output_coverage_credited",
newly_covered_paths=sorted(newly_covered),
- source_url=page_evidence.get("current_url") or "",
+ provenance=provenance,
+ value_grounded_paths=sorted(value_grounded),
+ source_url=page_evidence.get("current_url") or (contract.source_url if contract is not None else "") or "",
)
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index dba02cf08..6f9d58828 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -82,6 +82,7 @@ _POST_HOOK_CONTEXT_ROLLBACK_FIELDS = (
"synthesized_block_offered_trajectory_len",
"synthesized_block_offered_goal_complete",
"scouted_output_covered_paths",
+ "scout_observation_contract",
"requested_output_extraction_candidate",
"synthesized_block_reopened_for_output_coverage",
"uncovered_output_rescout_context_key",
diff --git a/skyvern/forge/sdk/copilot/output_extraction_plan.py b/skyvern/forge/sdk/copilot/output_extraction_plan.py
index 5a6aba2f1..c235082d4 100644
--- a/skyvern/forge/sdk/copilot/output_extraction_plan.py
+++ b/skyvern/forge/sdk/copilot/output_extraction_plan.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import hashlib
+import re
from dataclasses import dataclass
from enum import StrEnum
from typing import Any, TypeGuard
@@ -13,6 +14,26 @@ class LiveReadKind(StrEnum):
TABLE_COLUMN = "table_column"
+class ValueShape(StrEnum):
+ NUMERIC_ID = "numeric_id"
+ POSTAL_ADDRESS = "postal_address"
+ CATEGORICAL_TOKEN = "categorical_token"
+ DATE = "date"
+ FREE_TEXT = "free_text"
+
+
+class ValueCardinality(StrEnum):
+ SCALAR = "scalar"
+ COLUMN = "column"
+
+
+@dataclass(frozen=True, slots=True)
+class ShapeExpectation:
+ shape: ValueShape
+ cardinality: ValueCardinality
+ id_digit_length: int | None = None
+
+
@dataclass(frozen=True, slots=True)
class RevealAnchor:
selector: str = ""
@@ -98,6 +119,8 @@ def output_path_segments(path: str) -> tuple[tuple[str, bool], ...]:
def _exact_path(label: str, labels_by_path: dict[str, tuple[str, ...]]) -> str | None:
+ # Binds only on exact label==page-label equality; disjoint goal and page vocabularies bind nothing.
+ # A content value-witness binder would be the non-lexical upgrade.
matches = [path for path, labels in labels_by_path.items() if label in labels]
return matches[0] if len(matches) == 1 else None
@@ -242,6 +265,251 @@ def _array_prefix(path: str) -> tuple[tuple[str, bool], ...]:
return ()
+def array_parent_path(path: str) -> str | None:
+ prefix = _array_prefix(path)
+ if not prefix:
+ return None
+ return ".".join(name for name, _ in prefix)
+
+
+_DATE_PATTERNS = (
+ re.compile(r"^\d{4}-\d{2}-\d{2}$"),
+ re.compile(r"^\d{1,2}/\d{1,2}/\d{4}$"),
+ re.compile(r"^\d{1,2}-\d{1,2}-\d{4}$"),
+)
+_ZIP_PATTERN = re.compile(r"^\d{5}(?:-\d{4})?$")
+_STATE_TOKEN_PATTERN = re.compile(r"^[A-Z]{2}$")
+
+
+def _is_numeric_id(text: str, digit_length: int | None) -> bool:
+ if digit_length is None or digit_length <= 0:
+ return False
+ compact = text.replace(" ", "")
+ return compact.isdigit() and len(compact) == digit_length
+
+
+def _is_date(text: str) -> bool:
+ stripped = text.strip()
+ return any(pattern.match(stripped) for pattern in _DATE_PATTERNS)
+
+
+def _is_postal_address(text: str) -> bool:
+ tokens = text.split()
+ if len(tokens) < 3 or not tokens[0][:1].isdigit():
+ return False
+ if sum(1 for token in tokens if token.isalpha()) < 2:
+ return False
+ return any(_ZIP_PATTERN.match(token) for token in tokens) or any(
+ _STATE_TOKEN_PATTERN.match(token) for token in tokens
+ )
+
+
+def _is_categorical_token(text: str) -> bool:
+ stripped = text.strip()
+ if "," in stripped:
+ return False
+ tokens = stripped.split()
+ return 1 <= len(tokens) <= 3 and all(token.isalpha() for token in tokens)
+
+
+def value_matches_shape(text: str, expectation: ShapeExpectation) -> bool:
+ if expectation.shape == ValueShape.NUMERIC_ID:
+ return _is_numeric_id(text, expectation.id_digit_length)
+ if expectation.shape == ValueShape.POSTAL_ADDRESS:
+ return _is_postal_address(text)
+ if expectation.shape == ValueShape.CATEGORICAL_TOKEN:
+ return _is_categorical_token(text)
+ if expectation.shape == ValueShape.DATE:
+ return _is_date(text)
+ return False
+
+
+def _column_values_match_shape(values: list[str], expectation: ShapeExpectation) -> bool:
+ if not values or not all(value_matches_shape(value, expectation) for value in values):
+ return False
+ if expectation.shape == ValueShape.CATEGORICAL_TOKEN:
+ return len(set(values)) < len(values)
+ return True
+
+
+def resolve_shape_expectations_by_path(
+ paths: set[str], registry: dict[str, ShapeExpectation] | None
+) -> dict[str, ShapeExpectation]:
+ if not registry:
+ return {}
+ resolved: dict[str, ShapeExpectation] = {}
+ for path in _leaf_paths(paths):
+ segments = output_path_segments(path)
+ if not segments:
+ continue
+ expectation = registry.get(segments[-1][0])
+ if expectation is None:
+ continue
+ is_column = bool(_array_prefix(path))
+ if is_column != (expectation.cardinality == ValueCardinality.COLUMN):
+ continue
+ resolved[path] = expectation
+ return resolved
+
+
+def _key_value_shape_bindings(
+ packet: dict[str, Any], shape_expectations_by_path: dict[str, ShapeExpectation]
+) -> list[LiveReadBinding]:
+ scalar_paths = {
+ path: expectation
+ for path, expectation in shape_expectations_by_path.items()
+ if expectation.cardinality == ValueCardinality.SCALAR
+ }
+ relations = packet.get("key_value_relations")
+ if not scalar_paths or not isinstance(relations, list):
+ return []
+ bindings: list[LiveReadBinding] = []
+ for relation in relations:
+ if (
+ not isinstance(relation, dict)
+ or relation.get("visible") is not True
+ or relation.get("value_visible") is not True
+ ):
+ continue
+ label = relation.get("key_text")
+ selector = relation.get("container_selector")
+ match_count = relation.get("container_match_count")
+ position = relation.get("container_position")
+ child_index = relation.get("value_child_index")
+ child_count = relation.get("direct_child_count")
+ value_text = relation.get("value_text")
+ if not isinstance(label, str) or not isinstance(selector, str):
+ continue
+ if not _is_int(match_count) or not _is_int(position) or not _is_int(child_index) or not _is_int(child_count):
+ continue
+ if match_count <= position or position < 0 or child_index < 0 or child_count <= child_index:
+ continue
+ if not isinstance(value_text, str) or not value_text.strip():
+ continue
+ for path, expectation in scalar_paths.items():
+ if value_matches_shape(value_text, expectation):
+ bindings.append(
+ LiveReadBinding(
+ path,
+ LiveReadKind.KEY_VALUE,
+ selector,
+ match_count,
+ position,
+ child_index,
+ child_count,
+ relation_label=label,
+ )
+ )
+ return bindings
+
+
+def _table_shape_bindings(
+ packet: dict[str, Any], shape_expectations_by_path: dict[str, ShapeExpectation]
+) -> list[LiveReadBinding]:
+ column_paths = {
+ path: expectation
+ for path, expectation in shape_expectations_by_path.items()
+ if expectation.cardinality == ValueCardinality.COLUMN
+ }
+ containers = packet.get("result_containers")
+ if not column_paths or not isinstance(containers, list):
+ return []
+ bindings: list[LiveReadBinding] = []
+ for container in containers:
+ if (
+ not isinstance(container, dict)
+ or container.get("visible") is not True
+ or container.get("span_free") is not True
+ or container.get("nested_table_free") is not True
+ ):
+ continue
+ selector, row_selector = container.get("selector"), container.get("row_selector")
+ match_count, row_count = container.get("selector_match_count"), container.get("row_count")
+ headers, rows, sample_rows = container.get("headers"), container.get("rows"), container.get("sample_rows")
+ if (
+ not isinstance(selector, str)
+ or not isinstance(row_selector, str)
+ or not _is_int(match_count)
+ or match_count != 1
+ ):
+ continue
+ if not _is_int(row_count) or row_count <= 0 or container.get("rows_truncated") is not False:
+ continue
+ if not isinstance(headers, list) or not isinstance(rows, list) or len(rows) != row_count:
+ continue
+ if (
+ not isinstance(sample_rows, list)
+ or len(sample_rows) != row_count
+ or not all(isinstance(value, str) for value in sample_rows)
+ ):
+ continue
+ header_label_list = [
+ header["text"] for header in headers if isinstance(header, dict) and isinstance(header.get("text"), str)
+ ]
+ header_labels = tuple(header_label_list)
+ if len(header_labels) != len(headers):
+ continue
+ row_cell_counts: list[int] = []
+ column_texts: dict[int, list[str]] = {}
+ valid = True
+ for row_index, row in enumerate(rows):
+ if (
+ not isinstance(row, dict)
+ or row.get("row_index") != row_index
+ or row.get("visible") is not True
+ or row.get("has_row_header") is not False
+ ):
+ valid = False
+ break
+ cells = row.get("cells")
+ if (
+ not isinstance(cells, list)
+ or len(cells) != len(headers)
+ or any(
+ not isinstance(cell, dict)
+ or cell.get("column_index") != column_index
+ or cell.get("visible") is not True
+ for column_index, cell in enumerate(cells)
+ )
+ ):
+ valid = False
+ break
+ row_cell_counts.append(len(cells))
+ for column_index, cell in enumerate(cells):
+ cell_text = cell.get("text")
+ column_texts.setdefault(column_index, []).append(cell_text if isinstance(cell_text, str) else "")
+ if not valid or len(row_cell_counts) != row_count:
+ continue
+ for header in headers:
+ header_column_index = header.get("column_index") if isinstance(header, dict) else None
+ if (
+ not isinstance(header, dict)
+ or not isinstance(header.get("text"), str)
+ or not _is_int(header_column_index)
+ ):
+ continue
+ values = column_texts.get(header_column_index, [])
+ for path, expectation in column_paths.items():
+ if _column_values_match_shape(values, expectation):
+ bindings.append(
+ LiveReadBinding(
+ path,
+ LiveReadKind.TABLE_COLUMN,
+ selector,
+ match_count,
+ 0,
+ row_selector=row_selector,
+ row_count=row_count,
+ column_index=header_column_index,
+ relation_label=header["text"],
+ headers=header_labels,
+ row_cell_counts=tuple(row_cell_counts),
+ row_identities=tuple(sample_rows),
+ )
+ )
+ return bindings
+
+
def _plan_from_entry(
entry: dict[str, Any], *, labels_by_path: dict[str, tuple[str, ...]]
) -> RequestedOutputExtractionPlan | None:
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 32c2c280d..9c3ecd9c6 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -251,6 +251,9 @@ _OUTPUT_FIELD_WORDS = frozenset(
"amount amounts domain domains name names number numbers owner owners phone phones rate rates specialties specialty "
"status statuses taxonomy total totals url urls website websites".split()
)
+# Intentionally distinct from enforcement._COVERAGE_GENERIC_TOKENS: this list filters intent prose when
+# parsing requested-output field names, so it drops phrase-level noise ("each", "profile", "structured");
+# the coverage list filters path leaf tokens only. Not unified — the consumers differ.
_OUTPUT_GENERIC_WORDS = frozenset(
"a all an data detail details each entity final for information its of output outputs profile record records "
"result results structured the value values".split()
diff --git a/skyvern/forge/sdk/copilot/result_evidence.py b/skyvern/forge/sdk/copilot/result_evidence.py
index 6ea4a4bad..bd5cb4a74 100644
--- a/skyvern/forge/sdk/copilot/result_evidence.py
+++ b/skyvern/forge/sdk/copilot/result_evidence.py
@@ -10,6 +10,17 @@ from copy import deepcopy
from dataclasses import dataclass
from typing import Any
+from skyvern.forge.sdk.copilot.output_extraction_plan import (
+ LiveReadBinding,
+ LiveReadKind,
+ ShapeExpectation,
+ _key_value_bindings,
+ _key_value_shape_bindings,
+ _table_bindings,
+ _table_shape_bindings,
+ array_parent_path,
+)
+
# Browser UI chrome, not Google Chrome. Keep this to generic empty-state and control text.
_RESULT_CONTAINER_UI_CHROME_TOKENS = frozenset(
{
@@ -89,6 +100,36 @@ class LoadedResultCompositionEvidence:
source_url: str = ""
+_SCOUT_OBSERVATION_SOURCE_TOOL = "evaluate"
+_SCOUT_INTERACTION_SOURCE_TOOL = "scout_interaction"
+_SCOUT_WITNESS_KEY_VALUE = "capture_nonempty_value"
+_SCOUT_WITNESS_TABLE = "cell_text_present"
+_SCOUT_VALUE_WITNESSES = frozenset({_SCOUT_WITNESS_KEY_VALUE, _SCOUT_WITNESS_TABLE})
+_SHAPE_CHANNEL = "shape"
+_LEXICAL_CHANNEL = "lexical"
+
+
+@dataclass(frozen=True)
+class ScoutObservedBinding:
+ output_path: str
+ kind: str
+ selector: str
+ selector_index: int
+ matched_label: str
+ value_witness: str
+
+
+@dataclass(frozen=True)
+class ScoutObservationContract:
+ bindings: tuple[ScoutObservedBinding, ...]
+ source_tool: str
+ source_url: str
+ has_bounded_page_schema: bool
+ structure_signature: str
+ workflow_run_id: str | None = None
+ observed_after_workflow_run: bool = False
+
+
def _is_meaningful_data(value: Any, *, _depth: int = 0) -> bool:
if _depth > _MAX_MEANINGFUL_DATA_DEPTH:
return False
@@ -424,3 +465,230 @@ def covered_output_paths_in_result_containers(
if path not in covered and tokens and (tokens & value_tokens):
covered.add(path)
return covered
+
+
+def _scout_binding_signature_payload(binding: ScoutObservedBinding) -> dict[str, object]:
+ return {
+ "output_path": binding.output_path,
+ "kind": binding.kind,
+ "selector": binding.selector,
+ "selector_index": binding.selector_index,
+ "matched_label": binding.matched_label,
+ "value_witness": binding.value_witness,
+ }
+
+
+def _scout_observation_structure_signature(
+ bindings: tuple[ScoutObservedBinding, ...],
+ *,
+ source_url: str,
+ workflow_run_id: str | None,
+ observed_after_workflow_run: bool,
+) -> str:
+ return _structure_signature(
+ {
+ "bindings": [_scout_binding_signature_payload(binding) for binding in bindings],
+ "source_tool": _SCOUT_OBSERVATION_SOURCE_TOOL,
+ "source_url": source_url,
+ "workflow_run_id": workflow_run_id,
+ "observed_after_workflow_run": observed_after_workflow_run,
+ }
+ )
+
+
+def scout_observation_contract_valid(contract: ScoutObservationContract | None) -> bool:
+ if contract is None or contract.source_tool != _SCOUT_OBSERVATION_SOURCE_TOOL or not contract.source_url.strip():
+ return False
+ if not contract.bindings:
+ return False
+ for binding in contract.bindings:
+ if not binding.output_path.startswith("output."):
+ return False
+ if binding.kind not in (LiveReadKind.KEY_VALUE, LiveReadKind.TABLE_COLUMN):
+ return False
+ if binding.value_witness not in _SCOUT_VALUE_WITNESSES:
+ return False
+ expected = _scout_observation_structure_signature(
+ contract.bindings,
+ source_url=contract.source_url,
+ workflow_run_id=contract.workflow_run_id,
+ observed_after_workflow_run=contract.observed_after_workflow_run,
+ )
+ return contract.structure_signature == expected
+
+
+def scout_observation_bound_paths(contract: ScoutObservationContract | None) -> set[str]:
+ if not scout_observation_contract_valid(contract):
+ return set()
+ assert contract is not None
+ paths = {binding.output_path for binding in contract.bindings}
+ parents = {parent for path in paths if (parent := array_parent_path(path)) is not None}
+ return paths | parents
+
+
+def _table_binding_value_witnessed(packet: Mapping[str, Any], binding: LiveReadBinding) -> bool:
+ containers = packet.get("result_containers")
+ if not isinstance(containers, list):
+ return False
+ for container in containers:
+ if not isinstance(container, Mapping) or container.get("selector") != binding.selector:
+ continue
+ if not _result_container_has_content(container):
+ return False
+ rows = container.get("rows")
+ if not isinstance(rows, list):
+ return False
+ for row in rows:
+ if not isinstance(row, Mapping):
+ continue
+ cells = row.get("cells")
+ if not isinstance(cells, list) or binding.column_index >= len(cells):
+ continue
+ cell = cells[binding.column_index]
+ if isinstance(cell, Mapping) and cell.get("has_text") is True:
+ return True
+ return False
+ return False
+
+
+def _binding_carrier(binding: LiveReadBinding) -> tuple[str, str, int, int]:
+ return (str(binding.kind), binding.selector, binding.selector_index, binding.column_index)
+
+
+def _kv_relation_for_binding(packet: Mapping[str, Any], binding: LiveReadBinding) -> Mapping[str, Any] | None:
+ relations = packet.get("key_value_relations")
+ if not isinstance(relations, list):
+ return None
+ for relation in relations:
+ if (
+ isinstance(relation, Mapping)
+ and relation.get("container_selector") == binding.selector
+ and relation.get("container_position") == binding.selector_index
+ and relation.get("key_text") == binding.relation_label
+ ):
+ return relation
+ return None
+
+
+def _kv_binding_value_text_dropped(packet: Mapping[str, Any], binding: LiveReadBinding) -> bool:
+ relation = _kv_relation_for_binding(packet, binding)
+ if relation is None or "value_text" not in relation:
+ return False
+ value_text = relation.get("value_text")
+ return not isinstance(value_text, str) or not value_text.strip()
+
+
+def mint_scout_observation_contract(
+ page_evidence: Mapping[str, Any],
+ *,
+ labels_by_path: dict[str, tuple[str, ...]],
+ url: str,
+ has_bounded_page_schema: bool,
+ workflow_run_id: str | None = None,
+ observed_after_workflow_run: bool = False,
+ shape_expectations_by_path: dict[str, ShapeExpectation] | None = None,
+) -> ScoutObservationContract | None:
+ """Bind requested output paths from one page capture via two additive channels: a lexical label-match
+ channel and a non-lexical value-shape channel that activates on any capture carrying binder-consumable
+ witnessed value content (bounded schema or a witnessed value), regardless of interaction ordinal.
+ Lexical candidates take precedence per path, surviving shape bindings require a >=2 distinct-path
+ quorum, and truncated or warned captures void the mint."""
+ if not isinstance(page_evidence, Mapping) or not url.strip() or not labels_by_path:
+ return None
+ if page_evidence.get("result_containers_truncated") is not False:
+ return None
+ if page_evidence.get("key_value_relations_truncated") is not False:
+ return None
+ warnings = page_evidence.get("inspection_warnings")
+ if isinstance(warnings, list) and warnings:
+ return None
+ packet = dict(page_evidence)
+
+ lexical_by_path: dict[str, list[LiveReadBinding]] = {}
+ for binding in _key_value_bindings(packet, labels_by_path):
+ lexical_by_path.setdefault(binding.output_path, []).append(binding)
+ for binding in _table_bindings(packet, labels_by_path):
+ lexical_by_path.setdefault(binding.output_path, []).append(binding)
+
+ # Local import: composition_evidence pulls in the output_utils -> context -> result_evidence
+ # chain, so importing it at module scope would form a circular import.
+ from skyvern.forge.sdk.copilot.composition_evidence import has_witnessed_value_content
+
+ shape_by_path: dict[str, list[LiveReadBinding]] = {}
+ if shape_expectations_by_path and (has_bounded_page_schema or has_witnessed_value_content(packet)):
+ for binding in _key_value_shape_bindings(packet, shape_expectations_by_path):
+ shape_by_path.setdefault(binding.output_path, []).append(binding)
+ for binding in _table_shape_bindings(packet, shape_expectations_by_path):
+ shape_by_path.setdefault(binding.output_path, []).append(binding)
+ for path, shape_bindings in shape_by_path.items():
+ lexical_carriers = {_binding_carrier(binding) for binding in lexical_by_path.get(path, [])}
+ if lexical_carriers:
+ shape_by_path[path] = [
+ binding for binding in shape_bindings if _binding_carrier(binding) not in lexical_carriers
+ ]
+
+ resolved: list[tuple[LiveReadBinding, str]] = []
+ for output_path in sorted(set(lexical_by_path) | set(shape_by_path)):
+ lexical = lexical_by_path.get(output_path, [])
+ shape = shape_by_path.get(output_path, [])
+ if len(lexical) == 1:
+ resolved.append((lexical[0], _LEXICAL_CHANNEL))
+ elif not lexical and len(shape) == 1:
+ resolved.append((shape[0], _SHAPE_CHANNEL))
+
+ gated: list[tuple[LiveReadBinding, str]] = []
+ for binding, channel in resolved:
+ if binding.kind == LiveReadKind.TABLE_COLUMN:
+ if not _table_binding_value_witnessed(packet, binding):
+ continue
+ elif _kv_binding_value_text_dropped(packet, binding):
+ continue
+ gated.append((binding, channel))
+
+ carrier_indices: dict[tuple[str, str, int, int], list[int]] = {}
+ for index, (binding, _channel) in enumerate(gated):
+ carrier_indices.setdefault(_binding_carrier(binding), []).append(index)
+ dropped: set[int] = set()
+ for indices in carrier_indices.values():
+ if len(indices) < 2 or all(gated[index][1] != _SHAPE_CHANNEL for index in indices):
+ continue
+ if any(gated[index][1] == _LEXICAL_CHANNEL for index in indices):
+ dropped.update(index for index in indices if gated[index][1] == _SHAPE_CHANNEL)
+ else:
+ dropped.update(indices)
+ survivors = [entry for index, entry in enumerate(gated) if index not in dropped]
+
+ shape_paths = {binding.output_path for binding, channel in survivors if channel == _SHAPE_CHANNEL}
+ if len(shape_paths) < 2:
+ survivors = [(binding, channel) for binding, channel in survivors if channel != _SHAPE_CHANNEL]
+
+ bindings: list[ScoutObservedBinding] = []
+ for binding, _channel in survivors:
+ witness = _SCOUT_WITNESS_TABLE if binding.kind == LiveReadKind.TABLE_COLUMN else _SCOUT_WITNESS_KEY_VALUE
+ bindings.append(
+ ScoutObservedBinding(
+ output_path=binding.output_path,
+ kind=str(binding.kind),
+ selector=binding.selector,
+ selector_index=binding.selector_index,
+ matched_label=binding.relation_label,
+ value_witness=witness,
+ )
+ )
+ if not bindings:
+ return None
+ frozen_bindings = tuple(bindings)
+ return ScoutObservationContract(
+ bindings=frozen_bindings,
+ source_tool=_SCOUT_OBSERVATION_SOURCE_TOOL,
+ source_url=url,
+ has_bounded_page_schema=has_bounded_page_schema,
+ structure_signature=_scout_observation_structure_signature(
+ frozen_bindings,
+ source_url=url,
+ workflow_run_id=workflow_run_id,
+ observed_after_workflow_run=observed_after_workflow_run,
+ ),
+ workflow_run_id=workflow_run_id,
+ observed_after_workflow_run=observed_after_workflow_run,
+ )
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 4544d9fbc..1f2a53973 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -57,7 +57,7 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.copilot.output_extraction_plan import FrozenRequestedOutputExtractionCandidate
from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
- from skyvern.forge.sdk.copilot.result_evidence import LoadedResultCompositionEvidence
+ from skyvern.forge.sdk.copilot.result_evidence import LoadedResultCompositionEvidence, ScoutObservationContract
from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
from skyvern.forge.sdk.copilot.schema_incompatibility import SchemaIncompatibility
from skyvern.forge.sdk.copilot.turn_halt import TurnHalt
@@ -445,6 +445,7 @@ class AgentContext:
synthesized_block_reopened_for_output_coverage: bool = False
synthesized_block_reopened_for_credential_scout: bool = False
scouted_output_covered_paths: set[str] = field(default_factory=set)
+ scout_observation_contract: ScoutObservationContract | None = None
uncovered_output_rescout_context_key: str | None = None
uncovered_output_rescout_steer_key: str | None = None
credential_scout_rescout_context_key: str | None = None
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index 3aac217da..98982108e 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -788,6 +788,7 @@ async def _evaluate_post_hook(
raw: dict[str, Any],
ctx: AgentContext,
) -> dict[str, Any]:
+ ctx.scout_observation_contract = None
data = result.get("data")
if not result.get("ok") or not isinstance(data, dict) or not data:
_reset_evaluate_tracker(ctx)
diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.py
index 0d5581a24..aeed99331 100644
--- a/skyvern/forge/sdk/copilot/tools/scouting.py
+++ b/skyvern/forge/sdk/copilot/tools/scouting.py
@@ -28,11 +28,13 @@ from skyvern.forge.sdk.copilot.composition_evidence import (
SCOUT_INTERACTION_EVIDENCE_TOOL,
has_actionable_steer_content,
has_bounded_page_schema,
+ has_witnessed_value_content,
)
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy
from skyvern.forge.sdk.copilot.context import FillCarry
from skyvern.forge.sdk.copilot.enforcement import (
_RECENT_TOOL_OUTPUT_CHAR_CAP,
+ mint_scout_observation_contract_for_ctx,
record_scouted_output_coverage,
register_no_progress_interaction_click,
reset_no_progress_interaction_count,
@@ -615,6 +617,13 @@ def _scout_act_observe_no_payload_result(*, started: float, timeout_seconds: flo
return "timeout" if time.monotonic() - started >= timeout_seconds else "no_payload"
+def _evidence_list_len(packet: dict[str, Any] | None, key: str) -> int:
+ if not isinstance(packet, dict):
+ return 0
+ value = packet.get(key)
+ return len(value) if isinstance(value, list) else 0
+
+
def _mint_current_loaded_result_source(
ctx: AgentContext,
page_evidence: dict[str, Any] | None,
@@ -663,6 +672,12 @@ async def _scout_act_observe_page_evidence(ctx: AgentContext, *, url: str) -> di
ctx.last_scout_act_observe_recapture_result = "not_attempted_no_budget"
else:
ctx.last_scout_act_observe_recapture_attempted = True
+ # A card that renders asynchronously after the click is absent from the first
+ # capture; settle briefly so the single recapture can witness it before crediting.
+ settle_seconds = min(settings.COPILOT_CLICK_SETTLE_DELAY_SECONDS, remaining_seconds)
+ if settle_seconds > 0:
+ await asyncio.sleep(settle_seconds)
+ remaining_seconds = timeout_seconds - (time.monotonic() - started)
try:
recaptured = await _composition_get_structured_evidence(
ctx, inspected_url=url, current_url=url, timeout_seconds=remaining_seconds
@@ -694,6 +709,8 @@ async def _scout_act_observe_page_evidence(ctx: AgentContext, *, url: str) -> di
outcome=outcome,
duration_ms=int((time.monotonic() - started) * 1000),
url=url,
+ result_container_count=_evidence_list_len(parsed, "result_containers"),
+ key_value_relation_count=_evidence_list_len(parsed, "key_value_relations"),
recapture_attempted=ctx.last_scout_act_observe_recapture_attempted,
recapture_result=ctx.last_scout_act_observe_recapture_result,
)
@@ -721,11 +738,18 @@ async def _register_scout_interaction_observation(
page_evidence: dict[str, Any] | None = None
if tool_name in _ACT_OBSERVE_TOOLS:
parsed = await _scout_act_observe_page_evidence(ctx, url=url)
- if parsed is not None and has_bounded_page_schema(parsed):
+ # Admission (credit axis) is decoupled from the hollow outcome (no-progress axis): a page
+ # that rendered witnessed value content is bindable even when it exposes no actionable schema.
+ if parsed is not None and (has_bounded_page_schema(parsed) or has_witnessed_value_content(parsed)):
# Identity keys overwrite the parsed packet so the entry stays a
# scout_interaction observation, with the schema merged before append.
evidence = {**parsed, **evidence}
page_evidence = evidence
+ contract = mint_scout_observation_contract_for_ctx(ctx, parsed, url=url)
+ ctx.scout_observation_contract = contract
+ record_scouted_output_coverage(
+ ctx, parsed, contract=contract, include_lexical=has_actionable_steer_content(parsed)
+ )
# The schema is already attached; leaving the marker set would let a
# later evaluate/inspect mint a second interaction credit for one click.
_clear_pending_browser_interaction_observation(ctx)
@@ -1275,10 +1299,16 @@ async def _maybe_steer_evaluate_to_action(
if isinstance(page_evidence, _UnsetEvidence)
else page_evidence
)
- if parsed is None or not has_actionable_steer_content(parsed):
+ if parsed is None:
+ _reset_evaluate_tracker(ctx)
+ return False
+ contract = mint_scout_observation_contract_for_ctx(ctx, parsed, url=url)
+ ctx.scout_observation_contract = contract
+ if not has_actionable_steer_content(parsed):
+ record_scouted_output_coverage(ctx, parsed, contract=contract, include_lexical=False)
_reset_evaluate_tracker(ctx)
return False
- record_scouted_output_coverage(ctx, parsed)
+ record_scouted_output_coverage(ctx, parsed, contract=contract)
_record_scout_page_observation(ctx, parsed)
loaded_results = _mint_current_loaded_result_source(ctx, parsed, url=url)
if loaded_results is not None:
diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.py
index 9cb47b0f6..372d2c28d 100644
--- a/tests/unit/test_copilot_composition_evidence.py
+++ b/tests/unit/test_copilot_composition_evidence.py
@@ -32,12 +32,17 @@ from skyvern.forge.sdk.copilot.composition_evidence import (
composition_page_evidence_error,
has_actionable_steer_content,
has_bounded_page_schema,
+ has_witnessed_value_content,
merge_visual_composition_evidence,
normalize_block_observation_refs,
page_evidence_needs_visual_fallback,
parse_composition_html,
parse_composition_structured,
)
+from skyvern.forge.sdk.copilot.result_evidence import (
+ loaded_result_composition_evidence_from_page,
+ loaded_result_composition_target_summary,
+)
from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
from skyvern.forge.sdk.copilot.tools.blockers import _artifact_challenge_flag_from_result
from skyvern.forge.sdk.copilot.turn_intent import TurnIntent, TurnIntentMode
@@ -2256,6 +2261,7 @@ def test_structured_preserves_live_key_and_table_binding_shape() -> None:
"key_value_relations": [
{
"key_text": "Record Identifier",
+ "value_text": "record-abc",
"container_selector": ".kv",
"container_match_count": 1,
"container_position": 0,
@@ -2290,8 +2296,54 @@ def test_structured_preserves_live_key_and_table_binding_shape() -> None:
assert parsed["result_containers"][0]["rows"][1]["cells"][1] == {
"column_index": 1,
"visible": True,
+ "has_text": False,
+ "text": "",
+ }
+
+
+def test_structured_result_containers_pass_through_cell_has_text() -> None:
+ payload = {
+ "page_title": "Records",
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [
+ {
+ "tag": "table",
+ "selector": "#records",
+ "selector_match_count": 1,
+ "visible": True,
+ "span_free": True,
+ "nested_table_free": True,
+ "row_selector": "#records > tbody > tr",
+ "headers": [{"text": "Status", "column_index": 0}],
+ "row_count": 1,
+ "rows_truncated": False,
+ "rows": [
+ {
+ "row_index": 0,
+ "visible": True,
+ "has_row_header": False,
+ "cells": [{"column_index": 0, "visible": True, "has_text": True}],
+ }
+ ],
+ "sample_rows": ["Active"],
+ }
+ ],
+ "result_containers_truncated": False,
+ "key_value_relations": [],
+ "key_value_relations_truncated": False,
+ "challenge_controls": [],
+ "modal_overlays": [],
+ "visual_obstruction_candidates": [],
+ "visible_text_excerpt": "Records",
+ "anti_bot_indicators": [],
}
+ parsed = parse_composition_structured(payload, inspected_url="u", current_url="u")
+
+ assert parsed is not None
+ assert parsed["result_containers"][0]["rows"][0]["cells"][0]["has_text"] is True
+
def test_html_packet_excludes_hidden_bindings_and_preserves_revealed_structure() -> None:
details = """
@@ -2332,13 +2384,29 @@ def test_html_packet_excludes_hidden_bindings_and_preserves_revealed_structure()
"visible": True,
"has_row_header": False,
"cells": [
- {"column_index": 0, "visible": True},
- {"column_index": 1, "visible": True},
+ {"column_index": 0, "visible": True, "has_text": True, "text": "Record One"},
+ {"column_index": 1, "visible": True, "has_text": True, "text": "Ready"},
],
}
]
+def test_html_parse_marks_empty_cell_without_text() -> None:
+ details = """
+ <table id="records">
+ <thead><tr><th>Address</th><th>Status</th></tr></thead>
+ <tbody><tr><td>Record One</td><td></td></tr></tbody>
+ </table>
+ """
+ parsed = parse_composition_html(
+ details, inspected_url="https://example.com/records", current_url="https://example.com/records"
+ )
+
+ cells = parsed["result_containers"][0]["rows"][0]["cells"]
+ assert cells[0]["has_text"] is True
+ assert cells[1]["has_text"] is False
+
+
def test_structured_detects_modal_overlay_with_dismiss_controls() -> None:
payload = {
"page_title": "",
@@ -3013,3 +3081,189 @@ class TestSemanticChallengeSplit:
assert state["requires_human_verification"] is True
assert state["gates_submit_controls"] is True
assert {"text": "Search", "disabled": True} in state["gated_submit_controls"]
+
+
+def test_html_key_value_relation_captures_bounded_value_text() -> None:
+ long_value = "Z" * 400
+ details = f'<div class="kv"><div>Reference</div><div>{long_value}</div></div>'
+ parsed = parse_composition_html(details, inspected_url="https://example.com/p", current_url="https://example.com/p")
+
+ relation = parsed["key_value_relations"][0]
+ assert relation["key_text"] == "Reference"
+ assert relation["value_text"].startswith("Z")
+ assert len(relation["value_text"]) <= 240
+
+
+def test_html_table_cell_captures_bounded_text() -> None:
+ long_cell = "Y" * 400
+ details = f"""
+ <table id="records">
+ <thead><tr><th>Address</th></tr></thead>
+ <tbody><tr><td>{long_cell}</td></tr></tbody>
+ </table>
+ """
+ parsed = parse_composition_html(details, inspected_url="https://example.com/r", current_url="https://example.com/r")
+
+ cell = parsed["result_containers"][0]["rows"][0]["cells"][0]
+ assert cell["has_text"] is True
+ assert cell["text"].startswith("Y")
+ assert len(cell["text"]) <= 120
+
+
+def test_structured_passes_value_text_and_cell_text_with_caps() -> None:
+ payload = {
+ "page_title": "Records",
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [
+ {
+ "tag": "table",
+ "selector": "#records",
+ "selector_match_count": 1,
+ "visible": True,
+ "span_free": True,
+ "nested_table_free": True,
+ "row_selector": "#records > tbody > tr",
+ "headers": [{"text": "Address", "column_index": 0}],
+ "row_count": 1,
+ "rows_truncated": False,
+ "rows": [
+ {
+ "row_index": 0,
+ "visible": True,
+ "has_row_header": False,
+ "cells": [{"column_index": 0, "visible": True, "has_text": True, "text": "C" * 400}],
+ }
+ ],
+ "sample_rows": ["C" * 400],
+ }
+ ],
+ "result_containers_truncated": False,
+ "key_value_relations": [
+ {
+ "key_text": "Reference",
+ "value_text": "V" * 400,
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+ ],
+ "key_value_relations_truncated": False,
+ "challenge_controls": [],
+ "modal_overlays": [],
+ "visual_obstruction_candidates": [],
+ "visible_text_excerpt": "Records",
+ "anti_bot_indicators": [],
+ }
+
+ parsed = parse_composition_structured(payload, inspected_url="u", current_url="u")
+
+ assert parsed is not None
+ assert len(parsed["key_value_relations"][0]["value_text"]) <= 240
+ assert len(parsed["result_containers"][0]["rows"][0]["cells"][0]["text"]) <= 120
+
+
+def test_captured_value_and_cell_text_stay_out_of_loaded_result_summary() -> None:
+ details = """
+ <div class="kv"><div>Reference</div><div>secret-ref-value</div></div>
+ <table id="records">
+ <thead><tr><th>Address</th></tr></thead>
+ <tbody><tr><td>secret-cell-value</td></tr></tbody>
+ </table>
+ """
+ parsed = parse_composition_html(details, inspected_url="https://example.com/r", current_url="https://example.com/r")
+ evidence = loaded_result_composition_evidence_from_page(parsed, source_tool="evaluate", source_url="u")
+ assert evidence is not None
+ serialized = json.dumps(loaded_result_composition_target_summary(evidence))
+ assert '"value_text"' not in serialized
+ assert '"cells"' not in serialized
+
+
+def _kv_value_content_packet() -> dict[str, Any]:
+ return {
+ "key_value_relations": [
+ {
+ "key_text": "Ref Code",
+ "value_text": "AB-2931",
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+ ],
+ "key_value_relations_truncated": False,
+ "result_containers": [],
+ "result_containers_truncated": False,
+ "inspection_warnings": [],
+ }
+
+
+def _table_cell_content_packet() -> dict[str, Any]:
+ return {
+ "key_value_relations": [],
+ "key_value_relations_truncated": False,
+ "result_containers": [
+ {
+ "tag": "table",
+ "selector": "#rows",
+ "rows": [
+ {
+ "row_index": 0,
+ "cells": [{"column_index": 0, "has_text": True, "text": "value"}],
+ }
+ ],
+ }
+ ],
+ "result_containers_truncated": False,
+ "inspection_warnings": [],
+ }
+
+
+def test_has_witnessed_value_content_true_on_kv_value_text() -> None:
+ packet = _kv_value_content_packet()
+ assert has_witnessed_value_content(packet) is True
+ assert has_bounded_page_schema(packet) is False
+ assert has_actionable_steer_content(packet) is False
+
+
+def test_has_witnessed_value_content_true_on_table_cell_text() -> None:
+ packet = _table_cell_content_packet()
+ assert has_witnessed_value_content(packet) is True
+ assert has_bounded_page_schema(packet) is True
+
+
+def test_has_witnessed_value_content_false_on_truncated_kv() -> None:
+ packet = _kv_value_content_packet()
+ packet["key_value_relations_truncated"] = True
+ assert has_witnessed_value_content(packet) is False
+
+
+def test_has_witnessed_value_content_false_on_inspection_warnings() -> None:
+ packet = _kv_value_content_packet()
+ packet["inspection_warnings"] = ["capture_incomplete"]
+ assert has_witnessed_value_content(packet) is False
+
+
+def test_has_witnessed_value_content_false_on_empty_capture() -> None:
+ packet = {
+ "key_value_relations": [],
+ "key_value_relations_truncated": False,
+ "result_containers": [],
+ "result_containers_truncated": False,
+ "inspection_warnings": [],
+ }
+ assert has_witnessed_value_content(packet) is False
+ assert has_bounded_page_schema(packet) is False
+
+
+def test_has_witnessed_value_content_false_on_blank_value_text() -> None:
+ packet = _kv_value_content_packet()
+ packet["key_value_relations"][0]["value_text"] = " "
+ assert has_witnessed_value_content(packet) is False
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index db616681d..a07a45778 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -15,6 +15,7 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from agents import RunConfig
+from structlog.testing import capture_logs
from skyvern.config import settings
from skyvern.forge.sdk.copilot.blocker_signal import (
@@ -29,6 +30,7 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (
)
from skyvern.forge.sdk.copilot.code_block_synthesis import SynthesizedCodeBlock
from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdict
+from skyvern.forge.sdk.copilot.composition_evidence import parse_composition_html
from skyvern.forge.sdk.copilot.config import (
SYNTHESIZED_OFFER_REFRESH_STEP_THRESHOLD,
BlockAuthoringPolicy,
@@ -51,6 +53,7 @@ from skyvern.forge.sdk.copilot.enforcement import (
_uncovered_output_reject_admits_evaluate,
arm_credential_scout_reopen,
consume_uncovered_output_reopen_event,
+ mint_scout_observation_contract_for_ctx,
record_scouted_output_coverage,
run_with_enforcement,
synthesized_block_persistence_signal,
@@ -71,6 +74,7 @@ from skyvern.forge.sdk.copilot.output_contracts import (
OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODE,
OutputContractAdvisoryState,
)
+from skyvern.forge.sdk.copilot.output_extraction_plan import ShapeExpectation, ValueCardinality, ValueShape
from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget
from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicy
from skyvern.forge.sdk.copilot.streaming_adapter import _update_enforcement_from_tool
@@ -140,6 +144,7 @@ class _Ctx:
self.synthesized_goal_complete_landed = False
self.impose_synthesized_code_block = False
self.scouted_output_covered_paths: set[str] = set()
+ self.scout_observation_contract: object | None = None
self.flow_evidence: list[dict[str, object]] = []
self.copilot_config: CopilotConfig | None = None
self.uncovered_output_rescout_context_key = None
@@ -2272,6 +2277,55 @@ class TestGoalLikelyNeedsMoreBlocks:
assert self._check(123, 1) is False # type: ignore[arg-type]
+LISTING_DETAIL_URL = "http://localhost:8901/record/1457803926"
+
+# Generic multi-field detail DOM: exercises the contract's label/header binding vs the
+# coverage-token channel. No specific vertical or PII (see CLAUDE.md OSS-sync rules).
+LISTING_DETAIL_HTML = """
+<html><head><title>Regional Records Directory</title></head><body>
+<div class="layout">
+ <div class="panel">
+ <h1>Search Results</h1>
+ <p class="muted">Showing 1 result in <strong>Example Region</strong>.</p>
+ <div class="result-card" id="recordCard">
+ <div>
+ <div class="rc-name">Northgate Unit 7</div>
+ <div class="muted">Facility</div>
+ <div>Northgate Holdings, LLC</div>
+ <div class="muted">general listing</div>
+ <div class="small">100 Example Ave # 200, Example City, EX 00001</div>
+ <div class="small muted">12.34 units away &middot; <a class="link">1-800-555-0102</a></div>
+ <div id="recordDetails">
+ <div class="kv"><div class="k">Reference Number</div><div>1457803926</div></div>
+ <div class="kv"><div class="k">Region</div><div>North</div></div>
+ <div class="kv"><div class="k">Category</div><div>Standard</div></div>
+ <div class="kv"><div class="k">Tier</div><div>Two</div></div>
+ <div class="kv"><div class="k">Effective date</div><div>01/01/2024</div></div>
+ <h3>Locations</h3>
+ <p class="muted small">Approval status per location for Northgate Holdings, LLC.</p>
+ <table>
+ <thead><tr><th>Site</th><th>Address</th><th>Status</th></tr></thead>
+ <tbody>
+ <tr><td>Northgate Holdings, LLC</td><td>100 Example Ave # 200, Example City, EX 00001</td><td><span class="status-ok">Approved</span></td></tr>
+ <tr><td>Northgate Holdings, LLC</td><td>240 Sample Blvd, Example City, EX 00002</td><td><span class="status-ok">Approved</span></td></tr>
+ <tr><td>Southgate Group</td><td>512 Test St, Other City, EX 00003</td><td><span class="status-no">Not Approved</span></td></tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ <div class="rc-flags"></div>
+ </div>
+ </div>
+ <div class="panel filter-side">
+ <h2>Filter Options</h2>
+ <div class="fld"><label for="refInput">Search by Name, Group, or Reference Number</label><input id="refInput" type="text"/></div>
+ <div class="fld"><label>Reference Number</label><input type="text" value="1457803926"/></div>
+ </div>
+</div>
+</body></html>
+"""
+
+
def _criterion(output_path: str, outcome: str) -> CompletionCriterion:
return CompletionCriterion(id=output_path, outcome=outcome, output_path=output_path)
@@ -2448,6 +2502,276 @@ class TestScoutOutputCoverageGate:
assert synthesized_trajectory_is_goal_complete(ctx) is False
assert _should_force_synthesized_block_persistence(ctx) is False
+ @staticmethod
+ def _kv_page(*, key_text: str, url: str, value_prose: str) -> dict[str, object]:
+ return {
+ "current_url": url,
+ "inspection_warnings": [],
+ "result_containers_truncated": False,
+ "key_value_relations_truncated": False,
+ "key_value_relations": [
+ {
+ "key_text": key_text,
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+ ],
+ "result_containers": [{"selector": "#detail", "text_excerpt": value_prose}],
+ }
+
+ def test_contract_credits_output_path_without_lexical_overlap(self) -> None:
+ ctx = self._authoring_ctx(_criterion("output.overall_credentialing_result", "Overall Credentialing Result"))
+ page = self._kv_page(
+ key_text="Overall Credentialing Result",
+ url="https://example.com/provider",
+ value_prose="Status: Credentialed",
+ )
+ contract = mint_scout_observation_contract_for_ctx(
+ ctx,
+ page,
+ url="https://example.com/provider",
+ )
+ assert contract is not None
+
+ record_scouted_output_coverage(ctx, page)
+ assert ctx.scouted_output_covered_paths == set()
+
+ with capture_logs() as logs:
+ record_scouted_output_coverage(ctx, page, contract=contract)
+ assert ctx.scouted_output_covered_paths == {"output.overall_credentialing_result"}
+ assert uncovered_requested_output_paths(ctx) == set()
+ credited = next(entry for entry in logs if entry["event"] == "copilot_scouted_output_coverage_credited")
+ assert credited["provenance"] == "value_grounded"
+ assert credited["value_grounded_paths"] == ["output.overall_credentialing_result"]
+
+ @staticmethod
+ def _shape_registry_config() -> CopilotConfig:
+ return CopilotConfig(
+ requested_output_shape_expectations={
+ "widget_id": ShapeExpectation(ValueShape.NUMERIC_ID, ValueCardinality.SCALAR, id_digit_length=8),
+ "depot": ShapeExpectation(ValueShape.POSTAL_ADDRESS, ValueCardinality.COLUMN),
+ "phase": ShapeExpectation(ValueShape.CATEGORICAL_TOKEN, ValueCardinality.COLUMN),
+ }
+ )
+
+ @staticmethod
+ def _shape_scout_page() -> dict[str, object]:
+ def _row(row_index: int, depot: str, phase: str) -> dict[str, object]:
+ return {
+ "row_index": row_index,
+ "visible": True,
+ "has_row_header": False,
+ "cells": [
+ {"column_index": 0, "visible": True, "has_text": True, "text": depot},
+ {"column_index": 1, "visible": True, "has_text": True, "text": phase},
+ ],
+ }
+
+ return {
+ "current_url": "https://example.com/sites",
+ "source_tool": "scout_interaction",
+ "interaction_selector": "#reveal",
+ "inspection_warnings": [],
+ "result_containers_truncated": False,
+ "key_value_relations_truncated": False,
+ "key_value_relations": [
+ {
+ "key_text": "Ref Code",
+ "value_text": "12345678",
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+ ],
+ "result_containers": [
+ {
+ "tag": "table",
+ "selector": "#sites",
+ "selector_match_count": 1,
+ "visible": True,
+ "span_free": True,
+ "nested_table_free": True,
+ "headers": [
+ {"text": "Loc", "column_index": 0},
+ {"text": "Stage", "column_index": 1},
+ ],
+ "row_selector": "#sites tbody tr",
+ "row_count": 3,
+ "rows_truncated": False,
+ "sample_rows": ["r0", "r1", "r2"],
+ "rows": [
+ _row(0, "12 Peak Way Reno NV 89501", "Complete"),
+ _row(1, "8 Oak Loop Boston MA", "Complete"),
+ _row(2, "40 Fir Trail Fremont CA", "Pending"),
+ ],
+ }
+ ],
+ }
+
+ def test_shape_channel_credits_value_grounded_and_drains_derived_parent(self) -> None:
+ ctx = self._authoring_ctx(
+ _criterion("output.widget_id", "the eight digit widget reference"),
+ _criterion("output.sites", "the list of build sites"),
+ _criterion("output.sites[].depot", "each depot postal location"),
+ _criterion("output.sites[].phase", "each build stage token"),
+ )
+ ctx.copilot_config = self._shape_registry_config()
+ page = self._shape_scout_page()
+
+ no_registry_ctx = self._authoring_ctx(
+ _criterion("output.widget_id", "the eight digit widget reference"),
+ _criterion("output.sites", "the list of build sites"),
+ _criterion("output.sites[].depot", "each depot postal location"),
+ _criterion("output.sites[].phase", "each build stage token"),
+ )
+ assert mint_scout_observation_contract_for_ctx(no_registry_ctx, page, url=page["current_url"]) is None
+
+ contract = mint_scout_observation_contract_for_ctx(ctx, page, url=page["current_url"])
+ assert contract is not None
+
+ with capture_logs() as logs:
+ record_scouted_output_coverage(ctx, page, contract=contract)
+ assert ctx.scouted_output_covered_paths == {
+ "output.widget_id",
+ "output.sites",
+ "output.sites[].depot",
+ "output.sites[].phase",
+ }
+ assert uncovered_requested_output_paths(ctx) == set()
+ credited = next(entry for entry in logs if entry["event"] == "copilot_scouted_output_coverage_credited")
+ assert credited["provenance"] == "value_grounded"
+ assert any(path == "output.sites" for path in credited["value_grounded_paths"])
+
+ def test_inspect_sourced_packet_shape_grounds_value_regardless_of_interaction(self) -> None:
+ page = self._shape_scout_page()
+ page["source_tool"] = "inspect_page_for_composition"
+ page.pop("interaction_selector", None)
+
+ # First-load capture (no prior interaction) grounds value by shape via witnessed content.
+ landing_ctx = self._authoring_ctx(
+ _criterion("output.widget_id", "the eight digit widget reference"),
+ _criterion("output.sites", "the list of build sites"),
+ _criterion("output.sites[].depot", "each depot postal location"),
+ _criterion("output.sites[].phase", "each build stage token"),
+ )
+ landing_ctx.copilot_config = self._shape_registry_config()
+ landing_ctx.scout_trajectory = []
+ landing_contract = mint_scout_observation_contract_for_ctx(landing_ctx, page, url=page["current_url"])
+ assert landing_contract is not None
+ with capture_logs() as landing_logs:
+ record_scouted_output_coverage(landing_ctx, page, contract=landing_contract)
+ landing_credited = next(
+ entry for entry in landing_logs if entry["event"] == "copilot_scouted_output_coverage_credited"
+ )
+ assert landing_credited["provenance"] == "value_grounded"
+
+ ctx = self._authoring_ctx(
+ _criterion("output.widget_id", "the eight digit widget reference"),
+ _criterion("output.sites", "the list of build sites"),
+ _criterion("output.sites[].depot", "each depot postal location"),
+ _criterion("output.sites[].phase", "each build stage token"),
+ )
+ ctx.copilot_config = self._shape_registry_config()
+ contract = mint_scout_observation_contract_for_ctx(ctx, page, url=page["current_url"])
+ assert contract is not None
+
+ with capture_logs() as logs:
+ record_scouted_output_coverage(ctx, page, contract=contract)
+ credited = next(entry for entry in logs if entry["event"] == "copilot_scouted_output_coverage_credited")
+ assert credited["provenance"] == "value_grounded"
+ assert any(path == "output.sites" for path in credited["value_grounded_paths"])
+
+ def test_two_partial_contracts_accumulate_coverage(self) -> None:
+ ctx = self._authoring_ctx(
+ _criterion("output.overall_credentialing_result", "Overall Credentialing Result"),
+ _criterion("output.npi", "NPI"),
+ )
+ first = self._kv_page(
+ key_text="Overall Credentialing Result", url="https://example.com/p1", value_prose="Credentialed"
+ )
+ second = self._kv_page(key_text="NPI", url="https://example.com/p2", value_prose="1234567890")
+
+ first_contract = mint_scout_observation_contract_for_ctx(
+ ctx,
+ first,
+ url="https://example.com/p1",
+ )
+ record_scouted_output_coverage(ctx, first, contract=first_contract)
+ assert ctx.scouted_output_covered_paths == {"output.overall_credentialing_result"}
+
+ second_contract = mint_scout_observation_contract_for_ctx(
+ ctx,
+ second,
+ url="https://example.com/p2",
+ )
+ record_scouted_output_coverage(ctx, second, contract=second_contract)
+ assert ctx.scouted_output_covered_paths == {"output.overall_credentialing_result", "output.npi"}
+ assert uncovered_requested_output_paths(ctx) == set()
+
+ def test_realistic_multifield_dom_contract_binds_and_credits_value_grounded(self) -> None:
+ page_evidence = parse_composition_html(
+ LISTING_DETAIL_HTML,
+ inspected_url=LISTING_DETAIL_URL,
+ current_url=LISTING_DETAIL_URL,
+ )
+ ref_relations = [
+ relation for relation in page_evidence["key_value_relations"] if relation["key_text"] == "Reference Number"
+ ]
+ assert len(ref_relations) == 1
+
+ criteria = (
+ _criterion("output.reference_number", "Reference Number"),
+ _criterion("output.row_statuses", "Status"),
+ )
+
+ ctx = self._authoring_ctx(*criteria)
+ contract = mint_scout_observation_contract_for_ctx(
+ ctx,
+ page_evidence,
+ url=LISTING_DETAIL_URL,
+ )
+ assert contract is not None
+ bindings_by_path = {binding.output_path: binding for binding in contract.bindings}
+ # The contract binds the reference-number KV and the status column by label/header match,
+ # crediting them as value_grounded from the realistic multi-field capture.
+ assert set(bindings_by_path) == {"output.reference_number", "output.row_statuses"}
+ assert bindings_by_path["output.reference_number"].kind == "key_value"
+ assert bindings_by_path["output.row_statuses"].kind == "table_column"
+
+ with capture_logs() as logs:
+ record_scouted_output_coverage(ctx, page_evidence, contract=contract)
+ assert {"output.reference_number", "output.row_statuses"} <= ctx.scouted_output_covered_paths
+ assert uncovered_requested_output_paths(ctx) == set()
+ credited = next(entry for entry in logs if entry["event"] == "copilot_scouted_output_coverage_credited")
+ assert set(credited["value_grounded_paths"]) >= {"output.reference_number", "output.row_statuses"}
+
+ def test_include_lexical_false_credits_contract_only(self) -> None:
+ ctx = self._authoring_ctx(_criterion("output.document_name", "Document Name"))
+ page = self._kv_page(
+ key_text="Document Name", url="https://example.com/doc", value_prose="Document Name Resale Certificate"
+ )
+ contract = mint_scout_observation_contract_for_ctx(
+ ctx,
+ page,
+ url="https://example.com/doc",
+ )
+ assert contract is not None
+
+ record_scouted_output_coverage(ctx, page, include_lexical=False)
+ assert ctx.scouted_output_covered_paths == set()
+
+ record_scouted_output_coverage(ctx, page, contract=contract, include_lexical=False)
+ assert ctx.scouted_output_covered_paths == {"output.document_name"}
+
def test_empty_shell_selector_tokens_do_not_credit(self) -> None:
ctx = self._authoring_ctx(_criterion("output.document_name", "the order status document name is captured"))
page_evidence = {
@@ -2736,6 +3060,15 @@ class TestScoutOutputCoverageGate:
assert ctx.scouted_output_covered_paths == {"output.document_name"}
assert ctx.synthesized_block_reopened_for_output_coverage is False
+ def test_post_hook_failure_rolls_back_scout_observation_contract(self) -> None:
+ assert "scout_observation_contract" in _POST_HOOK_CONTEXT_ROLLBACK_FIELDS
+ ctx = _Ctx()
+ ctx.scout_observation_contract = None
+ snapshot = _snapshot_post_hook_context(ctx)
+ ctx.scout_observation_contract = object()
+ _restore_post_hook_context(ctx, snapshot)
+ assert ctx.scout_observation_contract is None
+
class TestAdvisoryRunDispatchForceLane:
"""A granted output-contract advisory run is forced onto update_and_run_blocks through the same
diff --git a/tests/unit/test_copilot_output_extraction_plan.py b/tests/unit/test_copilot_output_extraction_plan.py
index 536846ca3..f7c97d8ec 100644
--- a/tests/unit/test_copilot_output_extraction_plan.py
+++ b/tests/unit/test_copilot_output_extraction_plan.py
@@ -6,9 +6,31 @@ from skyvern.forge.sdk.copilot.composition_evidence import parse_composition_str
from skyvern.forge.sdk.copilot.mcp_adapter import _restore_post_hook_context, _snapshot_post_hook_context
from skyvern.forge.sdk.copilot.output_extraction_plan import (
LiveReadKind,
+ ShapeExpectation,
+ ValueCardinality,
+ ValueShape,
+ _key_value_shape_bindings,
+ _table_shape_bindings,
+ array_parent_path,
derive_requested_output_extraction_plan,
+ resolve_shape_expectations_by_path,
+ value_matches_shape,
)
+_SYNTHETIC_SHAPE_REGISTRY = {
+ "widget_id": ShapeExpectation(ValueShape.NUMERIC_ID, ValueCardinality.SCALAR, id_digit_length=8),
+ "depot": ShapeExpectation(ValueShape.POSTAL_ADDRESS, ValueCardinality.COLUMN),
+ "phase": ShapeExpectation(ValueShape.CATEGORICAL_TOKEN, ValueCardinality.COLUMN),
+ "final_phase": ShapeExpectation(ValueShape.CATEGORICAL_TOKEN, ValueCardinality.SCALAR),
+}
+_SYNTHETIC_REQUESTED_PATHS = {
+ "output.widget_id",
+ "output.sites",
+ "output.sites[].depot",
+ "output.sites[].phase",
+ "output.final_phase",
+}
+
LABELS_BY_PATH = {
"output.record_id": ("Record Identifier",),
"output.records[].detail": ("Detail",),
@@ -221,3 +243,160 @@ def test_jit_plan_cannot_see_flow_evidence_rolled_back_after_failed_hook() -> No
)
is None
)
+
+
+def test_numeric_id_matches_only_exact_digit_length() -> None:
+ expectation = _SYNTHETIC_SHAPE_REGISTRY["widget_id"]
+ assert value_matches_shape("12345678", expectation) is True
+ assert value_matches_shape("1234567", expectation) is False
+ assert value_matches_shape("123456789", expectation) is False
+ assert value_matches_shape("1234abcd", expectation) is False
+
+
+def test_postal_address_requires_number_lead_alpha_and_region_token() -> None:
+ expectation = _SYNTHETIC_SHAPE_REGISTRY["depot"]
+ assert value_matches_shape("221 Baker Street Boston MA", expectation) is True
+ assert value_matches_shape("500 Industrial Way Fremont CA", expectation) is True
+ assert value_matches_shape("500 Industrial Way Fremont 94538", expectation) is True
+ assert value_matches_shape("Industrial Way Fremont CA", expectation) is False
+ assert value_matches_shape("500 Way", expectation) is False
+
+
+def test_categorical_token_excludes_digits_commas_and_long_phrases() -> None:
+ expectation = _SYNTHETIC_SHAPE_REGISTRY["final_phase"]
+ assert value_matches_shape("Complete", expectation) is True
+ assert value_matches_shape("In Progress", expectation) is True
+ assert value_matches_shape("Not Yet Started Phase", expectation) is False
+ assert value_matches_shape("Phase 2", expectation) is False
+ assert value_matches_shape("Acme, Inc", expectation) is False
+
+
+def test_free_text_expectation_never_matches() -> None:
+ expectation = ShapeExpectation(ValueShape.FREE_TEXT, ValueCardinality.SCALAR)
+ assert value_matches_shape("anything at all", expectation) is False
+
+
+def test_resolve_maps_leaf_segments_and_enforces_cardinality_and_leaf_only() -> None:
+ resolved = resolve_shape_expectations_by_path(_SYNTHETIC_REQUESTED_PATHS, _SYNTHETIC_SHAPE_REGISTRY)
+ assert resolved == {
+ "output.widget_id": _SYNTHETIC_SHAPE_REGISTRY["widget_id"],
+ "output.sites[].depot": _SYNTHETIC_SHAPE_REGISTRY["depot"],
+ "output.sites[].phase": _SYNTHETIC_SHAPE_REGISTRY["phase"],
+ "output.final_phase": _SYNTHETIC_SHAPE_REGISTRY["final_phase"],
+ }
+ assert "output.sites" not in resolved
+
+
+def test_resolve_excludes_cardinality_mismatch() -> None:
+ registry = {"widget_id": ShapeExpectation(ValueShape.NUMERIC_ID, ValueCardinality.COLUMN, id_digit_length=8)}
+ assert resolve_shape_expectations_by_path({"output.widget_id"}, registry) == {}
+
+
+def test_resolve_returns_empty_without_registry() -> None:
+ assert resolve_shape_expectations_by_path(_SYNTHETIC_REQUESTED_PATHS, None) == {}
+ assert resolve_shape_expectations_by_path(_SYNTHETIC_REQUESTED_PATHS, {}) == {}
+
+
+def test_array_parent_path_only_for_array_leaves() -> None:
+ assert array_parent_path("output.sites[].depot") == "output.sites"
+ assert array_parent_path("output.widget_id") is None
+
+
+def _shape_kv_relation(value_text: str) -> dict[str, object]:
+ return {
+ "key_text": "Reference",
+ "value_text": value_text,
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+
+
+def test_key_value_shape_binding_matches_scalar_shape_on_value_text() -> None:
+ resolved = resolve_shape_expectations_by_path(_SYNTHETIC_REQUESTED_PATHS, _SYNTHETIC_SHAPE_REGISTRY)
+ bindings = _key_value_shape_bindings({"key_value_relations": [_shape_kv_relation("12345678")]}, resolved)
+ assert [binding.output_path for binding in bindings] == ["output.widget_id"]
+ assert bindings[0].kind == LiveReadKind.KEY_VALUE
+
+
+def test_key_value_shape_binding_requires_present_value_text() -> None:
+ resolved = resolve_shape_expectations_by_path(_SYNTHETIC_REQUESTED_PATHS, _SYNTHETIC_SHAPE_REGISTRY)
+ relation = _shape_kv_relation("12345678")
+ del relation["value_text"]
+ assert _key_value_shape_bindings({"key_value_relations": [relation]}, resolved) == []
+
+
+def _shape_table_packet() -> dict[str, object]:
+ return {
+ "result_containers": [
+ {
+ "tag": "table",
+ "selector": "#sites",
+ "selector_match_count": 1,
+ "visible": True,
+ "span_free": True,
+ "nested_table_free": True,
+ "row_selector": "#sites tbody tr",
+ "headers": [
+ {"text": "Location", "column_index": 0},
+ {"text": "Stage", "column_index": 1},
+ ],
+ "row_count": 3,
+ "rows_truncated": False,
+ "sample_rows": ["r0", "r1", "r2"],
+ "rows": [
+ {
+ "row_index": 0,
+ "visible": True,
+ "has_row_header": False,
+ "cells": [
+ {
+ "column_index": 0,
+ "visible": True,
+ "has_text": True,
+ "text": "221 Baker Street Boston MA",
+ },
+ {"column_index": 1, "visible": True, "has_text": True, "text": "Complete"},
+ ],
+ },
+ {
+ "row_index": 1,
+ "visible": True,
+ "has_row_header": False,
+ "cells": [
+ {"column_index": 0, "visible": True, "has_text": True, "text": "17 Elm Avenue Boston MA"},
+ {"column_index": 1, "visible": True, "has_text": True, "text": "Complete"},
+ ],
+ },
+ {
+ "row_index": 2,
+ "visible": True,
+ "has_row_header": False,
+ "cells": [
+ {"column_index": 0, "visible": True, "has_text": True, "text": "9 Oak Road Reno NV 89501"},
+ {"column_index": 1, "visible": True, "has_text": True, "text": "Pending"},
+ ],
+ },
+ ],
+ }
+ ]
+ }
+
+
+def test_table_shape_bindings_match_columns_by_value_shape() -> None:
+ resolved = resolve_shape_expectations_by_path(_SYNTHETIC_REQUESTED_PATHS, _SYNTHETIC_SHAPE_REGISTRY)
+ bindings = _table_shape_bindings(_shape_table_packet(), resolved)
+ bound = {binding.output_path: binding.column_index for binding in bindings}
+ assert bound == {"output.sites[].depot": 0, "output.sites[].phase": 1}
+
+
+def test_categorical_column_requires_repetition() -> None:
+ resolved = resolve_shape_expectations_by_path(_SYNTHETIC_REQUESTED_PATHS, _SYNTHETIC_SHAPE_REGISTRY)
+ packet = _shape_table_packet()
+ packet["result_containers"][0]["rows"][1]["cells"][1]["text"] = "Started"
+ bindings = _table_shape_bindings(packet, resolved)
+ assert [binding.output_path for binding in bindings] == ["output.sites[].depot"]
diff --git a/tests/unit/test_copilot_recorded_outcome_grounding.py b/tests/unit/test_copilot_recorded_outcome_grounding.py
index 7b344a8f4..e0051ce6a 100644
--- a/tests/unit/test_copilot_recorded_outcome_grounding.py
+++ b/tests/unit/test_copilot_recorded_outcome_grounding.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from dataclasses import replace
from types import SimpleNamespace
import pytest
@@ -27,6 +28,10 @@ from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
)
from skyvern.forge.sdk.copilot.enforcement import MAX_CODE_AUTHORING_GUARDRAIL_REJECTS
from skyvern.forge.sdk.copilot.failure_tracking import ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE
+from skyvern.forge.sdk.copilot.result_evidence import (
+ ScoutObservationContract,
+ mint_scout_observation_contract,
+)
from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module
from skyvern.forge.sdk.copilot.tools.blockers import _tool_loop_error
from skyvern.forge.sdk.copilot.tools.run_execution import _update_repair_loop_state
@@ -159,6 +164,43 @@ def _contract() -> DiagnosisRepairContract:
)
+def _scout_contract(
+ *,
+ has_bounded_page_schema: bool = True,
+ workflow_run_id: str | None = None,
+ observed_after_workflow_run: bool = False,
+) -> ScoutObservationContract:
+ page = {
+ "current_url": "https://example.com/results",
+ "inspection_warnings": [],
+ "result_containers_truncated": False,
+ "key_value_relations_truncated": False,
+ "key_value_relations": [
+ {
+ "key_text": "NPI",
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+ ],
+ "result_containers": [],
+ }
+ contract = mint_scout_observation_contract(
+ page,
+ labels_by_path={"output.npi": ("NPI",)},
+ url="https://example.com/results",
+ has_bounded_page_schema=has_bounded_page_schema,
+ workflow_run_id=workflow_run_id,
+ observed_after_workflow_run=observed_after_workflow_run,
+ )
+ assert contract is not None
+ return contract
+
+
def _bounded_inspect_evidence(**updates: object) -> dict[str, object]:
evidence: dict[str, object] = {
"source_tool": "inspect_page_for_composition",
@@ -969,3 +1011,73 @@ def test_update_repair_loop_state_clears_stale_requirement_when_outcome_not_auth
assert ctx.recorded_outcome_grounding_requirement is None
assert ctx.recorded_outcome_binding_constraint is None
+
+
+def test_scout_contract_grounds_no_run_requirement_after_composition_miss() -> None:
+ outcome = _outcome(phase="scout_evaluate", workflow_run_id=None, attempted_tool="evaluate")
+ ctx = _ctx(outcome)
+ arm_recorded_outcome_grounding_requirement(ctx)
+ ctx.composition_page_evidence = None
+ ctx.scout_observation_contract = _scout_contract()
+
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
+ payload = ctx.recorded_outcome_grounding_requirement.payload
+ assert payload is not None
+ assert payload.source_tool == "evaluate"
+ assert payload.capture_degraded is False
+ assert "source_tool: evaluate" in _recorded_build_test_outcome_prompt(ctx)
+
+
+def test_degraded_scout_contract_admitted_with_capture_degraded_recorded() -> None:
+ outcome = _outcome(phase="scout_evaluate", workflow_run_id=None, attempted_tool="evaluate")
+ ctx = _ctx(outcome)
+ arm_recorded_outcome_grounding_requirement(ctx)
+ ctx.composition_page_evidence = None
+ ctx.scout_observation_contract = _scout_contract(has_bounded_page_schema=False)
+
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
+ payload = ctx.recorded_outcome_grounding_requirement.payload
+ assert payload is not None
+ assert payload.capture_degraded is True
+ assert payload.diagnostic_reason == "capture_degraded"
+
+
+def test_arming_no_run_requirement_clears_prior_scout_contract() -> None:
+ outcome = _outcome(phase="scout_evaluate", workflow_run_id=None, attempted_tool="evaluate")
+ ctx = _ctx(outcome)
+ ctx.scout_observation_contract = _scout_contract()
+
+ arm_recorded_outcome_grounding_requirement(ctx)
+
+ assert ctx.scout_observation_contract is None
+ ctx.composition_page_evidence = None
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is False
+
+
+def test_run_required_requirement_rejects_unstamped_scout_contract() -> None:
+ outcome = _outcome()
+ ctx = _ctx(outcome)
+ arm_recorded_outcome_grounding_requirement(ctx)
+ ctx.composition_page_evidence = None
+ ctx.scout_observation_contract = _scout_contract()
+
+ with capture_logs() as logs:
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is False
+
+ event = next(log for log in logs if log["event"] == "copilot recorded outcome grounding rejected")
+ assert event["reject_reason"] == "run_id_mismatch"
+
+
+def test_tampered_scout_contract_rejected_by_grounding_lane() -> None:
+ outcome = _outcome(phase="scout_evaluate", workflow_run_id=None, attempted_tool="evaluate")
+ ctx = _ctx(outcome)
+ arm_recorded_outcome_grounding_requirement(ctx)
+ ctx.composition_page_evidence = None
+ contract = _scout_contract()
+ ctx.scout_observation_contract = replace(contract, source_url="https://evil.example.com/injected")
+
+ with capture_logs() as logs:
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is False
+
+ event = next(log for log in logs if log["event"] == "copilot recorded outcome grounding rejected")
+ assert event["reject_reason"] == "not_inspect_source"
diff --git a/tests/unit/test_copilot_result_evidence.py b/tests/unit/test_copilot_result_evidence.py
index 16b004c6a..ef4a0e7a7 100644
--- a/tests/unit/test_copilot_result_evidence.py
+++ b/tests/unit/test_copilot_result_evidence.py
@@ -1,13 +1,33 @@
from __future__ import annotations
import json
+from dataclasses import replace
+from skyvern.forge.sdk.copilot.composition_evidence import SCOUT_INTERACTION_EVIDENCE_TOOL
+from skyvern.forge.sdk.copilot.output_extraction_plan import ShapeExpectation, ValueCardinality, ValueShape
from skyvern.forge.sdk.copilot.result_evidence import (
_COMPOSITION_TARGET_SUMMARY_CHAR_BUDGET,
+ _SCOUT_INTERACTION_SOURCE_TOOL,
+ ScoutObservedBinding,
loaded_result_composition_evidence_from_page,
loaded_result_composition_target_summary,
+ mint_scout_observation_contract,
+ scout_observation_bound_paths,
+ scout_observation_contract_valid,
)
+_SHAPE_REGISTRY_BY_PATH = {
+ "output.widget_id": ShapeExpectation(ValueShape.NUMERIC_ID, ValueCardinality.SCALAR, id_digit_length=8),
+ "output.sites[].depot": ShapeExpectation(ValueShape.POSTAL_ADDRESS, ValueCardinality.COLUMN),
+ "output.sites[].phase": ShapeExpectation(ValueShape.CATEGORICAL_TOKEN, ValueCardinality.COLUMN),
+}
+_SHAPE_LABELS_BY_PATH = {
+ "output.widget_id": ("the eight digit widget identifier",),
+ "output.sites": ("the list of build sites",),
+ "output.sites[].depot": ("each site depot postal address",),
+ "output.sites[].phase": ("each site current build phase",),
+}
+
def test_loaded_result_evidence_counts_populated_tables() -> None:
evidence = loaded_result_composition_evidence_from_page(
@@ -372,3 +392,438 @@ def test_deep_result_container_payload_does_not_recurse_unbounded() -> None:
)
assert evidence is None
+
+
+def _kv_relation(key_text: str, *, position: int = 0) -> dict[str, object]:
+ return {
+ "key_text": key_text,
+ "container_selector": ".kv",
+ "container_match_count": 7,
+ "container_position": position,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+
+
+def _kv_page_evidence(*, key_text: str = "Overall Credentialing Result") -> dict[str, object]:
+ return {
+ "current_url": "https://example.com/provider",
+ "inspection_warnings": [],
+ "result_containers_truncated": False,
+ "key_value_relations_truncated": False,
+ "key_value_relations": [_kv_relation(key_text)],
+ "result_containers": [],
+ }
+
+
+def _table_row(row_index: int, *, status_has_text: bool) -> dict[str, object]:
+ return {
+ "row_index": row_index,
+ "visible": True,
+ "has_row_header": False,
+ "cells": [
+ {"column_index": 0, "visible": True, "has_text": True},
+ {"column_index": 1, "visible": True, "has_text": status_has_text},
+ ],
+ }
+
+
+def _table_page_evidence(*, status_has_text: bool = True) -> dict[str, object]:
+ return {
+ "current_url": "https://example.com/records",
+ "inspection_warnings": [],
+ "result_containers_truncated": False,
+ "key_value_relations_truncated": False,
+ "key_value_relations": [],
+ "result_containers": [
+ {
+ "tag": "table",
+ "selector": "#records",
+ "selector_match_count": 1,
+ "visible": True,
+ "span_free": True,
+ "nested_table_free": True,
+ "headers": [
+ {"text": "Record", "column_index": 0},
+ {"text": "Status", "column_index": 1},
+ ],
+ "row_selector": "#records tbody tr",
+ "row_count": 2,
+ "rows_truncated": False,
+ "sample_rows": ["Row 0 Active", "Row 1 Active"],
+ "rows": [
+ _table_row(0, status_has_text=status_has_text),
+ _table_row(1, status_has_text=status_has_text),
+ ],
+ }
+ ],
+ }
+
+
+def test_mint_binds_key_value_path_via_capture_invariant_without_bounded_schema() -> None:
+ contract = mint_scout_observation_contract(
+ _kv_page_evidence(),
+ labels_by_path={"output.overall_credentialing_result": ("Overall Credentialing Result",)},
+ url="https://example.com/provider",
+ has_bounded_page_schema=False,
+ )
+
+ assert contract is not None
+ assert scout_observation_contract_valid(contract)
+ assert scout_observation_bound_paths(contract) == {"output.overall_credentialing_result"}
+ assert contract.has_bounded_page_schema is False
+ assert contract.bindings[0].value_witness == "capture_nonempty_value"
+ assert contract.bindings[0].kind == "key_value"
+
+
+def test_mint_binds_table_column_only_with_cell_text_witness() -> None:
+ contract = mint_scout_observation_contract(
+ _table_page_evidence(status_has_text=True),
+ labels_by_path={"output.statuses": ("Status",)},
+ url="https://example.com/records",
+ has_bounded_page_schema=True,
+ )
+
+ assert contract is not None
+ assert scout_observation_bound_paths(contract) == {"output.statuses"}
+ assert contract.bindings[0].value_witness == "cell_text_present"
+ assert contract.bindings[0].kind == "table_column"
+
+
+def test_mint_excludes_table_column_when_bound_cells_lack_text() -> None:
+ contract = mint_scout_observation_contract(
+ _table_page_evidence(status_has_text=False),
+ labels_by_path={"output.statuses": ("Status",)},
+ url="https://example.com/records",
+ has_bounded_page_schema=True,
+ )
+
+ assert contract is None
+
+
+def test_mint_binds_only_labeled_paths_and_excludes_unbound() -> None:
+ contract = mint_scout_observation_contract(
+ _kv_page_evidence(),
+ labels_by_path={
+ "output.overall_credentialing_result": ("Overall Credentialing Result",),
+ "output.npi": ("NPI",),
+ },
+ url="https://example.com/provider",
+ has_bounded_page_schema=False,
+ )
+
+ assert contract is not None
+ assert scout_observation_bound_paths(contract) == {"output.overall_credentialing_result"}
+
+
+def test_mint_excludes_ambiguous_path_with_two_candidates() -> None:
+ evidence = _table_page_evidence(status_has_text=True)
+ evidence["key_value_relations"] = [_kv_relation("Status")]
+ contract = mint_scout_observation_contract(
+ evidence,
+ labels_by_path={"output.statuses": ("Status",)},
+ url="https://example.com/records",
+ has_bounded_page_schema=True,
+ )
+
+ assert contract is None
+
+
+def test_mint_returns_none_on_truncated_or_warned_capture() -> None:
+ truncated = _kv_page_evidence()
+ truncated["result_containers_truncated"] = True
+ warned = _kv_page_evidence()
+ warned["inspection_warnings"] = ["partial capture"]
+ labels = {"output.overall_credentialing_result": ("Overall Credentialing Result",)}
+
+ assert (
+ mint_scout_observation_contract(
+ truncated, labels_by_path=labels, url="https://example.com/x", has_bounded_page_schema=True
+ )
+ is None
+ )
+ assert (
+ mint_scout_observation_contract(
+ warned, labels_by_path=labels, url="https://example.com/x", has_bounded_page_schema=True
+ )
+ is None
+ )
+
+
+def test_mint_returns_none_without_url_or_labels() -> None:
+ labels = {"output.overall_credentialing_result": ("Overall Credentialing Result",)}
+ assert (
+ mint_scout_observation_contract(
+ _kv_page_evidence(), labels_by_path=labels, url=" ", has_bounded_page_schema=True
+ )
+ is None
+ )
+ assert (
+ mint_scout_observation_contract(
+ _kv_page_evidence(), labels_by_path={}, url="https://example.com/x", has_bounded_page_schema=True
+ )
+ is None
+ )
+
+
+def test_tampered_contract_is_rejected_by_validation_and_bound_paths() -> None:
+ contract = mint_scout_observation_contract(
+ _kv_page_evidence(),
+ labels_by_path={"output.overall_credentialing_result": ("Overall Credentialing Result",)},
+ url="https://example.com/provider",
+ has_bounded_page_schema=True,
+ )
+ assert contract is not None
+
+ forged_binding = ScoutObservedBinding(
+ output_path="output.injected",
+ kind="key_value",
+ selector=".kv",
+ selector_index=0,
+ matched_label="Injected",
+ value_witness="capture_nonempty_value",
+ )
+ tampered = replace(contract, bindings=contract.bindings + (forged_binding,))
+
+ assert scout_observation_contract_valid(tampered) is False
+ assert scout_observation_bound_paths(tampered) == set()
+
+
+def test_scout_interaction_source_tool_constant_matches_production() -> None:
+ assert _SCOUT_INTERACTION_SOURCE_TOOL == SCOUT_INTERACTION_EVIDENCE_TOOL
+
+
+def _shape_table_container() -> dict[str, object]:
+ def _row(row_index: int, depot: str, phase: str) -> dict[str, object]:
+ return {
+ "row_index": row_index,
+ "visible": True,
+ "has_row_header": False,
+ "cells": [
+ {"column_index": 0, "visible": True, "has_text": True, "text": depot},
+ {"column_index": 1, "visible": True, "has_text": True, "text": phase},
+ ],
+ }
+
+ return {
+ "tag": "table",
+ "selector": "#sites",
+ "selector_match_count": 1,
+ "visible": True,
+ "span_free": True,
+ "nested_table_free": True,
+ "headers": [
+ {"text": "Loc", "column_index": 0},
+ {"text": "Stage", "column_index": 1},
+ ],
+ "row_selector": "#sites tbody tr",
+ "row_count": 3,
+ "rows_truncated": False,
+ "sample_rows": ["r0", "r1", "r2"],
+ "rows": [
+ _row(0, "12 Main Street Reno NV 89501", "Complete"),
+ _row(1, "8 Oak Avenue Boston MA", "Complete"),
+ _row(2, "40 Pine Road Fremont CA", "Pending"),
+ ],
+ }
+
+
+def _shape_interaction_packet(**overrides: object) -> dict[str, object]:
+ packet: dict[str, object] = {
+ "current_url": "https://example.com/sites",
+ "source_tool": SCOUT_INTERACTION_EVIDENCE_TOOL,
+ "interaction_selector": "#reveal",
+ "inspection_warnings": [],
+ "result_containers_truncated": False,
+ "key_value_relations_truncated": False,
+ "key_value_relations": [
+ {
+ "key_text": "Ref Code",
+ "value_text": "12345678",
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+ ],
+ "result_containers": [_shape_table_container()],
+ }
+ packet.update(overrides)
+ return packet
+
+
+def _mint_shape(
+ packet: dict[str, object],
+ *,
+ registry: dict[str, ShapeExpectation] | None = _SHAPE_REGISTRY_BY_PATH,
+ bounded: bool = True,
+) -> object:
+ return mint_scout_observation_contract(
+ packet,
+ labels_by_path=_SHAPE_LABELS_BY_PATH,
+ url="https://example.com/sites",
+ has_bounded_page_schema=bounded,
+ shape_expectations_by_path=registry,
+ )
+
+
+def test_shape_channel_binds_zero_overlap_paths_and_lexical_alone_zero_binds() -> None:
+ packet = _shape_interaction_packet()
+
+ assert _mint_shape(packet, registry=None) is None
+
+ contract = _mint_shape(packet)
+ assert contract is not None
+ assert scout_observation_bound_paths(contract) == {
+ "output.widget_id",
+ "output.sites",
+ "output.sites[].depot",
+ "output.sites[].phase",
+ }
+
+
+def test_shape_channel_activates_regardless_of_interaction_but_requires_witnessed_content() -> None:
+ # No interaction ordinal is required: a witnessed structured first-load capture binds by value shape.
+ contract = _mint_shape(_shape_interaction_packet())
+ assert contract is not None
+ assert scout_observation_bound_paths(contract) == {
+ "output.widget_id",
+ "output.sites",
+ "output.sites[].depot",
+ "output.sites[].phase",
+ }
+ # Witnessed value content (or a bounded schema) is still required.
+ content_free = _shape_interaction_packet(key_value_relations=[], result_containers=[])
+ assert _mint_shape(content_free, bounded=False) is None
+
+
+def test_shape_channel_activates_on_content_witnessed_reveal_without_bounded_schema() -> None:
+ contract = _mint_shape(_shape_interaction_packet(), bounded=False)
+ assert contract is not None
+ assert scout_observation_bound_paths(contract) == {
+ "output.widget_id",
+ "output.sites",
+ "output.sites[].depot",
+ "output.sites[].phase",
+ }
+
+
+def test_shape_binding_below_quorum_drops() -> None:
+ single_path_registry = {"output.widget_id": _SHAPE_REGISTRY_BY_PATH["output.widget_id"]}
+ packet = _shape_interaction_packet(result_containers=[])
+ assert _mint_shape(packet, registry=single_path_registry) is None
+
+
+def test_ambiguous_shape_value_drops_path() -> None:
+ packet = _shape_interaction_packet(
+ key_value_relations=[
+ {
+ "key_text": "Ref Code",
+ "value_text": "12345678",
+ "container_selector": ".kv",
+ "container_match_count": 2,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ },
+ {
+ "key_text": "Alt Code",
+ "value_text": "87654321",
+ "container_selector": ".kv",
+ "container_match_count": 2,
+ "container_position": 1,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ },
+ ]
+ )
+ contract = _mint_shape(packet)
+ assert contract is not None
+ assert "output.widget_id" not in scout_observation_bound_paths(contract)
+ assert "output.sites[].depot" in scout_observation_bound_paths(contract)
+
+
+def test_present_but_empty_value_text_drops_kv_while_absent_key_still_mints() -> None:
+ empty_value = _shape_interaction_packet()
+ empty_value["key_value_relations"][0]["value_text"] = " "
+ contract = _mint_shape(empty_value)
+ assert contract is not None
+ assert "output.widget_id" not in scout_observation_bound_paths(contract)
+
+ lexical_labels = {"output.overall_result": ("Ref Code",)}
+ legacy_relation = {
+ "key_text": "Ref Code",
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+ legacy_contract = mint_scout_observation_contract(
+ {
+ "current_url": "https://example.com/x",
+ "inspection_warnings": [],
+ "result_containers_truncated": False,
+ "key_value_relations_truncated": False,
+ "key_value_relations": [legacy_relation],
+ "result_containers": [],
+ },
+ labels_by_path=lexical_labels,
+ url="https://example.com/x",
+ has_bounded_page_schema=False,
+ )
+ assert legacy_contract is not None
+ assert scout_observation_bound_paths(legacy_contract) == {"output.overall_result"}
+
+
+def test_lexical_precedence_keeps_lexical_binding_over_disagreeing_shape() -> None:
+ labels = dict(_SHAPE_LABELS_BY_PATH)
+ labels["output.widget_id"] = ("Ref Code",)
+ packet = _shape_interaction_packet(
+ key_value_relations=[
+ {
+ "key_text": "Ref Code",
+ "value_text": "not-an-id",
+ "container_selector": ".kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ },
+ {
+ "key_text": "Serial",
+ "value_text": "12345678",
+ "container_selector": ".serial",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ },
+ ]
+ )
+ contract = mint_scout_observation_contract(
+ packet,
+ labels_by_path=labels,
+ url="https://example.com/sites",
+ has_bounded_page_schema=True,
+ shape_expectations_by_path=_SHAPE_REGISTRY_BY_PATH,
+ )
+ assert contract is not None
+ widget_binding = next(b for b in contract.bindings if b.output_path == "output.widget_id")
+ assert widget_binding.selector == ".kv"
+ assert widget_binding.matched_label == "Ref Code"
diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.py
index 0a4f3ff24..32a0fc141 100644
--- a/tests/unit/test_copilot_scout_act_observe.py
+++ b/tests/unit/test_copilot_scout_act_observe.py
@@ -13,13 +13,16 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
+from structlog.testing import capture_logs
from skyvern.config import settings
from skyvern.forge.sdk.copilot import tools as tools_module
from skyvern.forge.sdk.copilot.composition_evidence import (
_auto_credit_interaction_observation,
has_bounded_page_schema,
+ has_witnessed_value_content,
)
+from skyvern.forge.sdk.copilot.config import CopilotConfig
from skyvern.forge.sdk.copilot.context import (
FillCarry,
StructuredContext,
@@ -28,7 +31,11 @@ from skyvern.forge.sdk.copilot.context import (
from skyvern.forge.sdk.copilot.enforcement import (
_RECENT_TOOL_OUTPUT_CHAR_CAP,
MAX_NO_PROGRESS_INTERACTION_ATTEMPTS,
+ record_scouted_output_coverage,
)
+from skyvern.forge.sdk.copilot.output_extraction_plan import ShapeExpectation, ValueCardinality, ValueShape
+from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion
+from skyvern.forge.sdk.copilot.result_evidence import scout_observation_bound_paths
from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.copilot.tools import _click_post_hook
from skyvern.forge.sdk.copilot.tools import scouting as scouting_module
@@ -82,6 +89,28 @@ def _bounded_extractor_payload() -> dict[str, Any]:
}
+def _kv_only_extractor_payload() -> dict[str, Any]:
+ return {
+ "page_title": "Provider Record",
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [],
+ "key_value_relations": [
+ {
+ "key_text": "Ref Code",
+ "value_text": "AB-2931",
+ "container_selector": ".record .kv",
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+ ],
+ }
+
+
def _ctx(*, server: Any = None, source_url: str | None = _SOURCE_URL) -> SimpleNamespace:
return SimpleNamespace(
pending_browser_interaction_observation=None,
@@ -95,6 +124,11 @@ def _ctx(*, server: Any = None, source_url: str | None = _SOURCE_URL) -> SimpleN
fill_carry_rebound_done=False,
pending_scout_source_url=source_url,
flow_evidence=[],
+ completion_criteria_turn_state=None,
+ last_code_authoring_repair_context=None,
+ copilot_config=None,
+ scout_observation_contract=None,
+ scouted_output_covered_paths=set(),
)
@@ -489,6 +523,150 @@ class TestActObserveSuccess:
assert page["modal_dismiss_controls"] == ["Accept"]
assert len(json.dumps(result)) <= _RECENT_TOOL_OUTPUT_CHAR_CAP
+ @pytest.mark.asyncio
+ async def test_content_witnessed_kv_reveal_admitted_without_bounded_schema(self) -> None:
+ ctx = _ctx(server=_server_returning(_kv_only_extractor_payload()))
+
+ result = await _run_click(ctx)
+
+ assert result["ok"] is True
+ assert ctx.last_scout_act_observe_outcome == "hollow"
+ assert not hasattr(ctx, "latest_recorded_build_test_outcome")
+ assert ctx.pending_browser_interaction_observation is None
+ assert len(ctx.flow_evidence) == 1
+ entry = ctx.flow_evidence[0]
+ assert entry["reached_via"] == "interaction"
+ assert entry["had_bounded_schema"] is False
+ evidence = entry["evidence"]
+ assert evidence["source_tool"] == "scout_interaction"
+ assert has_bounded_page_schema(evidence) is False
+ assert has_witnessed_value_content(evidence) is True
+
+
+def _zero_overlap_kv_relation(key_text: str, value_text: str, selector: str) -> dict[str, Any]:
+ return {
+ "key_text": key_text,
+ "value_text": value_text,
+ "container_selector": selector,
+ "container_match_count": 1,
+ "container_position": 0,
+ "value_child_index": 1,
+ "direct_child_count": 2,
+ "visible": True,
+ "value_visible": True,
+ }
+
+
+def _zero_overlap_kv_packet() -> dict[str, Any]:
+ return {
+ "current_url": _LANDING_URL,
+ "source_tool": "scout_interaction",
+ "interaction_selector": "#reveal",
+ "inspection_warnings": [],
+ "result_containers_truncated": False,
+ "key_value_relations_truncated": False,
+ "key_value_relations": [
+ _zero_overlap_kv_relation("Ref Code", "12345678", ".kv-ref"),
+ _zero_overlap_kv_relation("Site", "12 Peak Way Reno NV 89501", ".kv-site"),
+ ],
+ "result_containers": [],
+ }
+
+
+_ZERO_OVERLAP_BOUND_PATHS = {"output.widget_id", "output.address"}
+
+
+def _zero_overlap_requested_output_ctx() -> SimpleNamespace:
+ ctx = _ctx()
+ ctx.completion_criteria_turn_state = SimpleNamespace(
+ decision=SimpleNamespace(
+ criteria=(
+ CompletionCriterion(
+ id="output.widget_id",
+ outcome="the eight digit widget reference",
+ output_path="output.widget_id",
+ ),
+ CompletionCriterion(
+ id="output.address",
+ outcome="the mailing address of the site",
+ output_path="output.address",
+ ),
+ )
+ )
+ )
+ ctx.copilot_config = CopilotConfig(
+ requested_output_shape_expectations={
+ "widget_id": ShapeExpectation(ValueShape.NUMERIC_ID, ValueCardinality.SCALAR, id_digit_length=8),
+ "address": ShapeExpectation(ValueShape.POSTAL_ADDRESS, ValueCardinality.SCALAR),
+ }
+ )
+ ctx.scout_trajectory = [{"tool_name": "click", "selector": "#reveal", "trajectory_index": 0}]
+ return ctx
+
+
+class TestActObserveCoverageCredit:
+ @pytest.mark.asyncio
+ async def test_click_admit_branch_credits_value_grounded_on_witnessed_reveal(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(
+ scouting_module, "_scout_act_observe_page_evidence", AsyncMock(return_value=_zero_overlap_kv_packet())
+ )
+ ctx = _zero_overlap_requested_output_ctx()
+
+ with capture_logs() as logs:
+ step, page_evidence = await _register_scout_interaction_observation(
+ ctx, tool_name="click", selector="#reveal", source_url=_SOURCE_URL, url=_LANDING_URL
+ )
+
+ assert page_evidence is not None
+ assert has_witnessed_value_content(page_evidence) is True
+ assert ctx.scout_observation_contract is not None
+ assert scout_observation_bound_paths(ctx.scout_observation_contract) == _ZERO_OVERLAP_BOUND_PATHS
+ assert ctx.scouted_output_covered_paths == _ZERO_OVERLAP_BOUND_PATHS
+ credited = next(entry for entry in logs if entry["event"] == "copilot_scouted_output_coverage_credited")
+ assert credited["provenance"] == "value_grounded"
+ assert sorted(credited["value_grounded_paths"]) == sorted(_ZERO_OVERLAP_BOUND_PATHS)
+
+ @pytest.mark.asyncio
+ async def test_second_record_for_same_paths_emits_nothing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ scouting_module, "_scout_act_observe_page_evidence", AsyncMock(return_value=_zero_overlap_kv_packet())
+ )
+ ctx = _zero_overlap_requested_output_ctx()
+
+ await _register_scout_interaction_observation(
+ ctx, tool_name="click", selector="#reveal", source_url=_SOURCE_URL, url=_LANDING_URL
+ )
+ assert ctx.scouted_output_covered_paths == _ZERO_OVERLAP_BOUND_PATHS
+
+ with capture_logs() as logs:
+ record_scouted_output_coverage(
+ ctx, _zero_overlap_kv_packet(), contract=ctx.scout_observation_contract, include_lexical=False
+ )
+ assert not any(entry["event"] == "copilot_scouted_output_coverage_credited" for entry in logs)
+ assert ctx.scouted_output_covered_paths == _ZERO_OVERLAP_BOUND_PATHS
+
+ @pytest.mark.asyncio
+ async def test_unwitnessed_reveal_mints_and_credits_nothing(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ scouting_module,
+ "_scout_act_observe_page_evidence",
+ AsyncMock(return_value={"current_url": _LANDING_URL, "forms": [], "key_value_relations": []}),
+ )
+ ctx = _zero_overlap_requested_output_ctx()
+ ctx.last_scout_act_observe_outcome = None
+
+ with capture_logs() as logs:
+ step, page_evidence = await _register_scout_interaction_observation(
+ ctx, tool_name="click", selector="#reveal", source_url=_SOURCE_URL, url=_LANDING_URL
+ )
+
+ assert page_evidence is None
+ assert ctx.scout_observation_contract is None
+ assert ctx.scouted_output_covered_paths == set()
+ assert not any(entry["event"] == "copilot_scouted_output_coverage_credited" for entry in logs)
+
class TestActObserveDegrade:
@pytest.mark.asyncio
@@ -676,6 +854,72 @@ class TestActObserveDegrade:
assert not hasattr(ctx, "latest_recorded_build_test_outcome")
+class TestActObserveRecaptureSettle:
+ @pytest.mark.asyncio
+ async def test_bounded_settle_paid_before_single_recapture(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.6)
+ sleeps: list[float] = []
+
+ async def record_sleep(seconds: float) -> None:
+ sleeps.append(seconds)
+
+ monkeypatch.setattr(scouting_module.asyncio, "sleep", record_sleep)
+ ctx = _ctx(
+ server=_server_returning_sequence([{"page_title": "Loading", "forms": []}, _bounded_extractor_payload()])
+ )
+
+ parsed = await _scout_act_observe_page_evidence(ctx, url=_LANDING_URL)
+
+ assert sleeps == [0.6]
+ assert ctx.last_scout_act_observe_outcome == "attached"
+ assert parsed is not None and has_bounded_page_schema(parsed)
+
+ @pytest.mark.asyncio
+ async def test_zero_settle_pays_no_sleep(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.0)
+ sleeps: list[float] = []
+
+ async def record_sleep(seconds: float) -> None:
+ sleeps.append(seconds)
+
+ monkeypatch.setattr(scouting_module.asyncio, "sleep", record_sleep)
+ ctx = _ctx(
+ server=_server_returning_sequence([{"page_title": "Loading", "forms": []}, _bounded_extractor_payload()])
+ )
+
+ await _scout_act_observe_page_evidence(ctx, url=_LANDING_URL)
+
+ assert sleeps == []
+ assert ctx.last_scout_act_observe_outcome == "attached"
+
+ @pytest.mark.asyncio
+ async def test_attached_first_capture_pays_no_settle(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "COPILOT_CLICK_SETTLE_DELAY_SECONDS", 0.6)
+ sleeps: list[float] = []
+
+ async def record_sleep(seconds: float) -> None:
+ sleeps.append(seconds)
+
+ monkeypatch.setattr(scouting_module.asyncio, "sleep", record_sleep)
+ ctx = _ctx(server=_server_returning(_bounded_extractor_payload()))
+
+ await _scout_act_observe_page_evidence(ctx, url=_LANDING_URL)
+
+ assert sleeps == []
+ assert ctx.last_scout_act_observe_outcome == "attached"
+
+ @pytest.mark.asyncio
+ async def test_capture_log_carries_container_and_relation_counts(self) -> None:
+ ctx = _ctx(server=_server_returning(_kv_only_extractor_payload()))
+
+ with capture_logs() as logs:
+ await _scout_act_observe_page_evidence(ctx, url=_LANDING_URL)
+
+ probe = next(entry for entry in logs if entry["event"] == "copilot_scout_act_observe")
+ assert probe["result_container_count"] == 0
+ assert probe["key_value_relation_count"] == 1
+
+
class TestActObserveNoRace:
@pytest.mark.asyncio
async def test_appended_entry_never_mutates_after_hook_returns(self, monkeypatch: pytest.MonkeyPatch) -> None: