Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-11852): positive independent-evidence carriers for requested-output completion (#7100)
Andrew Neilsonb72f4be7e8bf
diff --git a/skyvern/forge/sdk/copilot/completion_output_grounding.py b/skyvern/forge/sdk/copilot/completion_output_grounding.pyindex f90a7c4ce..8131af96f 100644--- a/skyvern/forge/sdk/copilot/completion_output_grounding.py+++ b/skyvern/forge/sdk/copilot/completion_output_grounding.py@@ -28,6 +28,11 @@ _IGNORED_RUNTIME_FIELD_NAMES = frozenset({"evidence_text"})_INDEPENDENT_EVIDENCE_SOURCES: frozenset[EvidenceSourceKind] = frozenset({"independent_page_evidence", "registered_output_parameter", "registered_artifact_content"})+_POST_RUN_PAGE_OBSERVATION_LABEL = "post_run_page_observation"+_REGISTERED_ARTIFACT_OBSERVATION_LABEL = "registered_artifact_observation"+_MIN_CARRIER_VALUE_CHARS = 4+_MAX_CARRIER_TEXT_CHARS = 20_000+_PAGE_EVIDENCE_STAMP_KEYS = frozenset({"workflow_run_id", "observed_after_workflow_run"})class _GroundingCtx(Protocol):@@ -67,6 +72,13 @@ def grade_requested_output_criteria(verdicts: list[CriterionVerdict] = []for criterion in criteria:path = _normalize_output_path(criterion.output_path)+ # A carrier verdict is already sourced from independent evidence and only returned on a+ # positive confirmation, so the early return skips the self-emission veto path that no+ # longer applies; abstentions fall through to normal authored-path grading.+ carrier_verdict = _carrier_confirmation(criterion, path, snapshot)+ if carrier_verdict is not None:+ verdicts.append(carrier_verdict)+ continueaccepted_labels = ({label for label, paths in authored_paths_by_label.items() if path in paths} if path else set())@@ -253,6 +265,149 @@ def grade_requested_output_criteria(return verdicts+def _carrier_confirmation(+ criterion: CompletionCriterion, path: str, snapshot: RunEvidenceSnapshot+) -> CriterionVerdict | None:+ if _is_judgment_boolean_criterion(criterion):+ return None+ value_text = _carrier_scalar_text(criterion.expected_output_value)+ if value_text is None or len(value_text) < _MIN_CARRIER_VALUE_CHARS:+ return None+ if _carrier_independent_refutation(snapshot, path, criterion.expected_output_value) is not None:+ return None+ trace_fields = _criterion_trace_fields(+ criterion, _criterion_grounding_mode(criterion), criterion.requested_output_evidence_source+ )+ artifact_text = _carrier_surface_text(+ snapshot, _REGISTERED_ARTIFACT_OBSERVATION_LABEL, "registered_artifact_content"+ )+ if artifact_text is not None and _boundary_delimited_present(value_text, artifact_text):+ return CriterionVerdict(+ criterion_id=criterion.id,+ state="satisfied",+ reason_code="evidence_confirms",+ evidence_ref=f"block_outputs:{_REGISTERED_ARTIFACT_OBSERVATION_LABEL}",+ evidence_source="registered_artifact_content",+ **trace_fields,+ )+ page_text = _carrier_surface_text(snapshot, _POST_RUN_PAGE_OBSERVATION_LABEL, "independent_page_evidence")+ if page_text is not None and _boundary_delimited_present(value_text, page_text):+ pre_run_text = snapshot.pre_run_page_reference_text+ if pre_run_text is None:+ return None+ if not _boundary_delimited_present(value_text, _normalized_expected_text(pre_run_text)):+ return CriterionVerdict(+ criterion_id=criterion.id,+ state="satisfied",+ reason_code="evidence_confirms",+ evidence_ref=f"block_outputs:{_POST_RUN_PAGE_OBSERVATION_LABEL}",+ evidence_source="independent_page_evidence",+ **trace_fields,+ )+ return None+++def _carrier_scalar_text(value: ExpectedOutputValue | None) -> str | None:+ if isinstance(value, bool) or value is None:+ return None+ if isinstance(value, (int, float, str)):+ return _normalized_expected_text(value) or None+ return None+++def _carrier_surface_text(snapshot: RunEvidenceSnapshot, label: str, expected_source: EvidenceSourceKind) -> str | None:+ if snapshot.block_output_sources.get(label) != expected_source:+ return None+ payload = snapshot.block_outputs.get(label)+ if not isinstance(payload, Mapping):+ return None+ return _normalized_expected_text(page_evidence_prose_text(payload))+++def _carrier_independent_refutation(+ snapshot: RunEvidenceSnapshot, path: str, expected_value: ExpectedOutputValue | None+) -> tuple[str, EvidenceSourceKind] | None:+ if not path or expected_value is None:+ return None+ independent_outputs = {+ label: payload+ for label, payload in snapshot.block_outputs.items()+ if snapshot.block_output_sources.get(label) == "independent_page_evidence"+ }+ if not independent_outputs:+ return None+ delegated = _independent_evidence_text_refutation(+ independent_outputs, snapshot.block_output_sources, path, expected_value, set()+ )+ if delegated is not None:+ return delegated+ # Refute when the page packet carries a value AT the requested path that mismatches the+ # expected scalar. The shared refutation only reaches this comparison behind an+ # ``evidence_text`` field the page packet never carries, so it is checked directly here+ # (SKY-11868); a free-text-only contradiction remains unmaskable by design.+ if isinstance(expected_value, bool):+ return None+ parts = _path_parts(path)+ for label, payload in independent_outputs.items():+ if not isinstance(payload, Mapping):+ continue+ values, source_path = _runtime_path_values(payload, parts, path, set())+ if values and not any(_value_matches_expected(value, expected_value) for value in values):+ return f"block_outputs:{label}.{source_path}", "independent_page_evidence"+ return None+++def page_evidence_prose_text(evidence: Mapping[str, Any]) -> str:+ parts: list[str] = []+ total = 0+ for key, value in evidence.items():+ if key in _PAGE_EVIDENCE_STAMP_KEYS:+ continue+ for scalar in _iter_prose_scalars(value):+ parts.append(scalar)+ total += len(scalar) + 1+ if total >= _MAX_CARRIER_TEXT_CHARS:+ return " ".join(parts)[:_MAX_CARRIER_TEXT_CHARS]+ return " ".join(parts)+++def _iter_prose_scalars(value: Any) -> list[str]:+ if isinstance(value, bool):+ return []+ if isinstance(value, str):+ return [value] if value.strip() else []+ if isinstance(value, (int, float)):+ return [str(value)]+ if isinstance(value, Mapping):+ collected: list[str] = []+ for item in value.values():+ collected.extend(_iter_prose_scalars(item))+ return collected+ if isinstance(value, list):+ collected = []+ for item in value:+ collected.extend(_iter_prose_scalars(item))+ return collected+ return []+++def _boundary_delimited_present(needle: str, haystack: str) -> bool:+ if not needle or not haystack:+ return False+ length = len(needle)+ start = 0+ while True:+ idx = haystack.find(needle, start)+ if idx == -1:+ return False+ before_ok = idx == 0 or not haystack[idx - 1].isalnum()+ after_index = idx + length+ after_ok = after_index == len(haystack) or not haystack[after_index].isalnum()+ if before_ok and after_ok:+ return True+ start = idx + 1++def _evidence_source_for_ref(output_sources: Mapping[str, EvidenceSourceKind],evidence_ref: str | None,diff --git a/skyvern/forge/sdk/copilot/completion_verification.py b/skyvern/forge/sdk/copilot/completion_verification.pyindex 0a8bf7827..9b77339af 100644--- a/skyvern/forge/sdk/copilot/completion_verification.py+++ b/skyvern/forge/sdk/copilot/completion_verification.py@@ -261,6 +261,7 @@ class RunEvidenceSnapshot:failure_classes: list[str] = field(default_factory=list)failure_reasons: list[str] = field(default_factory=list)page_evidence: dict[str, Any] = field(default_factory=dict)+ pre_run_page_reference_text: str | None = Nonedef has_evidence(self) -> bool:return bool(@@ -1251,13 +1252,23 @@ def grade_terminal_goal_record_corroboration(snapshot: RunEvidenceSnapshot) -> lreturn []+_FALLBACK_FLOOR_CARRIER_SOURCES: frozenset[EvidenceSourceKind] = frozenset(+ {"independent_page_evidence", "registered_artifact_content"}+)++def grade_fallback_floor_reached_end_state_criteria(- criteria: list[CompletionCriterion], snapshot: RunEvidenceSnapshot+ criteria: list[CompletionCriterion],+ snapshot: RunEvidenceSnapshot,+ *,+ carrier_verdicts: tuple[CriterionVerdict, ...] = (),) -> list[CriterionVerdict]:eligible_criteria = [criterion for criterion in criteria if is_fallback_floor_base_criterion(criterion)]if not eligible_criteria:return []evidence_ref = _fallback_floor_reached_end_state_evidence_ref(snapshot, criteria)+ if evidence_ref is None:+ evidence_ref = _fallback_floor_carrier_evidence_ref(snapshot, carrier_verdicts)if evidence_ref is None:return []return [@@ -1296,6 +1307,21 @@ def _fallback_floor_parent_record_poisoned(payload: Any) -> bool:)+def _fallback_floor_carrier_evidence_ref(+ snapshot: RunEvidenceSnapshot, carrier_verdicts: tuple[CriterionVerdict, ...]+) -> str | None:+ if any(_fallback_floor_parent_record_poisoned(payload) for payload in snapshot.block_outputs.values()):+ return None+ for verdict in carrier_verdicts:+ if (+ verdict.state == "satisfied"+ and verdict.reason_code == "evidence_confirms"+ and verdict.evidence_source in _FALLBACK_FLOOR_CARRIER_SOURCES+ ):+ return verdict.evidence_ref or f"carrier:{verdict.criterion_id}"+ return None++def _fallback_floor_record_candidates(payload: Any) -> Iterable[dict[str, Any]]:if not isinstance(payload, dict):returndiff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 0a65d7d58..b11605323 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -124,6 +124,25 @@ class PendingBrowserInteractionObservation:url: str = ""+@dataclass(frozen=True)+class PreRunPageReference:+ text: str+ workflow_run_id: str+++@dataclass(frozen=True)+class RegisteredArtifactEntry:+ artifact_id: str+ file_name: str+ parsed_text: str+++@dataclass(frozen=True)+class RegisteredArtifactEvidence:+ entries: tuple[RegisteredArtifactEntry, ...]+ workflow_run_id: str++class ScoutedInteraction(TypedDict):tool_name: strselector: NotRequired[str]@@ -260,6 +279,11 @@ class AgentContext:verified_terminal_proposal_ready: bool = Falseoutcome_verification_trace_snapshot: dict[str, Any] = field(default_factory=dict)composition_page_evidence: dict[str, Any] | None = None+ # Pre-run page state pinned at the run seam before the post-run capture overwrites the slot;+ # stamped with the graded run id so a stale prior-run pin cannot anchor the absence scan.+ pre_run_page_reference: PreRunPageReference | None = None+ # Parsed text of this run's registered download artifacts, stamped with the run id.+ registered_artifact_evidence: RegisteredArtifactEvidence | None = None# Ordered, bounded list of typed page-evidence packets — one per page observed# while scouting the goal path, each tagged with how that state was reached.# Feeds the per-acted-page composition gate; never persisted into workflow YAML.diff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.pyindex 401a795b6..5296a3794 100644--- a/skyvern/forge/sdk/copilot/tools/completion.py+++ b/skyvern/forge/sdk/copilot/tools/completion.py@@ -11,6 +11,7 @@ from skyvern.forge.sdk.copilot.completion_output_grounding import (split_requested_output_criteria,)from skyvern.forge.sdk.copilot.completion_verification import (+ _FALLBACK_FLOOR_CARRIER_SOURCES,_STRUCTURED_RECORD_CRITERION_IDS,CompletionVerificationResult,CriterionVerdict,@@ -49,6 +50,7 @@ from skyvern.forge.sdk.copilot.reached_download_target import (derive_from_block_outputs,)from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, is_fallback_floor_criterion+from skyvern.forge.sdk.copilot.runtime import PreRunPageReference, RegisteredArtifactEvidencefrom skyvern.forge.sdk.copilot.terminal_predicates import outcome_fully_verifiedfrom skyvern.forge.sdk.copilot.tracing_setup import copilot_span@@ -74,6 +76,7 @@ LOG = structlog.get_logger()_TYPED_DOWNLOAD_KINDS = frozenset({DOWNLOAD_KIND_REGISTERED, DOWNLOAD_KIND_ATTRIBUTE, DOWNLOAD_KIND_EXTENSION})_POST_RUN_PAGE_OBSERVATION_LABEL = "post_run_page_observation"+_REGISTERED_ARTIFACT_OBSERVATION_LABEL = "registered_artifact_observation"# Stamp keys the same-run gate reads; they are dropped from the graded payload so the run id# and observation flag cannot be traversed as observed page content._POST_RUN_PAGE_EVIDENCE_STAMP_KEYS = frozenset({"workflow_run_id", "observed_after_workflow_run"})@@ -771,6 +774,33 @@ def _bind_independent_post_run_page_evidence(block_output_sources[_POST_RUN_PAGE_OBSERVATION_LABEL] = "independent_page_evidence"+def _bind_registered_artifact_evidence(+ evidence: RegisteredArtifactEvidence | None,+ run_id: str | None,+ block_outputs: dict[str, Any],+ block_output_sources: dict[str, EvidenceSourceKind],+) -> None:+ if _REGISTERED_ARTIFACT_OBSERVATION_LABEL in block_outputs:+ return+ if not isinstance(run_id, str) or not run_id:+ return+ if evidence is None or evidence.workflow_run_id != run_id or not evidence.entries:+ return+ block_outputs[_REGISTERED_ARTIFACT_OBSERVATION_LABEL] = {+ "parsed_text": " ".join(entry.parsed_text for entry in evidence.entries),+ "file_names": [entry.file_name for entry in evidence.entries],+ }+ block_output_sources[_REGISTERED_ARTIFACT_OBSERVATION_LABEL] = "registered_artifact_content"+++def _pre_run_page_reference_text(reference: PreRunPageReference | None, run_id: str | None) -> str | None:+ if not isinstance(run_id, str) or not run_id:+ return None+ if reference is None or reference.workflow_run_id != run_id:+ return None+ return reference.text or None++def _build_run_evidence_snapshot(copilot_ctx: Any, result: dict[str, Any]) -> RunEvidenceSnapshot:data = result.get("data")data = data if isinstance(data, dict) else {}@@ -820,6 +850,14 @@ def _build_run_evidence_snapshot(copilot_ctx: Any, result: dict[str, Any]) -> Ru_bind_independent_post_run_page_evidence(copilot_ctx, run_id if isinstance(run_id, str) else None, block_outputs, block_output_sources)+ registered_artifact_evidence = getattr(copilot_ctx, "registered_artifact_evidence", None)+ pre_run_page_reference = getattr(copilot_ctx, "pre_run_page_reference", None)+ _bind_registered_artifact_evidence(+ registered_artifact_evidence if isinstance(registered_artifact_evidence, RegisteredArtifactEvidence) else None,+ run_id if isinstance(run_id, str) else None,+ block_outputs,+ block_output_sources,+ )executed = data.get("executed_block_labels")executed_block_labels = [str(label) for label in executed] if isinstance(executed, list) else []page_title = data.get("page_title")@@ -848,6 +886,22 @@ def _build_run_evidence_snapshot(copilot_ctx: Any, result: dict[str, Any]) -> Rufailed_block_labels=failed_block_labels,failure_classes=artifact_failure_classes,failure_reasons=failure_reasons,+ pre_run_page_reference_text=_pre_run_page_reference_text(+ pre_run_page_reference if isinstance(pre_run_page_reference, PreRunPageReference) else None,+ run_id if isinstance(run_id, str) else None,+ ),+ )+++def _carrier_floor_verdicts(+ requested_output_verdicts: list[CriterionVerdict],+) -> tuple[CriterionVerdict, ...]:+ return tuple(+ verdict+ for verdict in requested_output_verdicts+ if verdict.state == "satisfied"+ and verdict.reason_code == "evidence_confirms"+ and verdict.evidence_source in _FALLBACK_FLOOR_CARRIER_SOURCES)@@ -857,6 +911,7 @@ def _apply_present_value_upgrades(snapshot: RunEvidenceSnapshot,*,include_terminal_goal_records: bool = False,+ carrier_verdicts: tuple[CriterionVerdict, ...] = (),) -> CompletionVerificationResult:"""Upgrade a ``no_evidence``/``unknown`` run verdict to a deterministic present-value``satisfied``. An ``evidence_contradicts`` verdict is left to the judge, a judge@@ -875,7 +930,9 @@ def _apply_present_value_upgrades(upgrades.update({verdict.criterion_id: verdict- for verdict in grade_fallback_floor_reached_end_state_criteria(run_criteria, snapshot)+ for verdict in grade_fallback_floor_reached_end_state_criteria(+ run_criteria, snapshot, carrier_verdicts=carrier_verdicts+ )})upgrades.update(@@ -1009,6 +1066,8 @@ def _run_criteria_for_verdicts(def _deterministic_run_verification_result(run_criteria: list[CompletionCriterion],snapshot: RunEvidenceSnapshot,+ *,+ carrier_verdicts: tuple[CriterionVerdict, ...] = (),) -> tuple[CompletionVerificationResult | None, list[CompletionCriterion]]:"""Return a deterministic run-plane verdict when the typed graders cover it.@@ -1040,7 +1099,9 @@ def _deterministic_run_verification_result(deterministic_by_id[verdict.criterion_id] = verdictfor verdict in grade_structured_record_criteria(run_criteria, snapshot):deterministic_by_id[verdict.criterion_id] = verdict- for verdict in grade_fallback_floor_reached_end_state_criteria(run_criteria, snapshot):+ for verdict in grade_fallback_floor_reached_end_state_criteria(+ run_criteria, snapshot, carrier_verdicts=carrier_verdicts+ ):deterministic_by_id[verdict.criterion_id] = verdictfor verdict in grade_terminal_goal_record_criteria(run_criteria, snapshot):deterministic_by_id[verdict.criterion_id] = verdict@@ -1127,6 +1188,7 @@ async def _maybe_run_completion_verification(if requested_output_criteriaelse [])+ carrier_verdicts = _carrier_floor_verdicts(requested_output_verdicts)if judgeable_run_criteria and all(criterion.id in _STRUCTURED_RECORD_CRITERION_IDS for criterion in judgeable_run_criteria):@@ -1190,7 +1252,7 @@ async def _maybe_run_completion_verification()else:deterministic_result, remaining_criteria = _deterministic_run_verification_result(- judgeable_run_criteria, snapshot+ judgeable_run_criteria, snapshot, carrier_verdicts=carrier_verdicts)if deterministic_result is not None and not remaining_criteria:run_result = _merge_run_verdicts(@@ -1292,6 +1354,7 @@ async def _maybe_run_completion_verification(judgeable_run_criteria,snapshot,include_terminal_goal_records=True,+ carrier_verdicts=carrier_verdicts,)run_result = _merge_run_verdicts(run_criteria,diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex c5a0bda0b..0b98237ef 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -3,9 +3,11 @@ from __future__ import annotationsimport asyncioimport base64import json+import os+import tempfileimport timefrom collections import defaultdict-from collections.abc import Mapping+from collections.abc import Mapping, Sequencefrom dataclasses import dataclass, replacefrom datetime import datetime, timezonefrom typing import Any, Literal@@ -15,7 +17,7 @@ import structlogfrom skyvern.config import settingsfrom skyvern.forge import app-from skyvern.forge.sdk.artifact.models import ArtifactType+from skyvern.forge.sdk.artifact.models import Artifact, ArtifactTypefrom skyvern.forge.sdk.copilot.blocker_signal import (CopilotToolBlockerSignal,clear_blocker_signal_for_reason_codes,@@ -41,6 +43,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (code_contains_credential_fill,trajectory_has_credential_fill,)+from skyvern.forge.sdk.copilot.completion_output_grounding import page_evidence_prose_textfrom skyvern.forge.sdk.copilot.completion_verification import (CompletionVerificationResult,CriterionVerdict,@@ -96,6 +99,9 @@ from skyvern.forge.sdk.copilot.run_outcome import ()from skyvern.forge.sdk.copilot.runtime import (AgentContext,+ PreRunPageReference,+ RegisteredArtifactEntry,+ RegisteredArtifactEvidence,ensure_browser_session,)from skyvern.forge.sdk.copilot.runtime_authoring_repair import (@@ -114,6 +120,7 @@ from skyvern.forge.sdk.executor.factory import AsyncExecutorFactoryfrom skyvern.forge.sdk.routes.workflow_copilot import _process_workflow_yamlfrom skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotRunOutcomeUpdate, WorkflowCopilotStreamMessageTypefrom skyvern.forge.sdk.settings_manager import SettingsManager+from skyvern.forge.sdk.utils.pdf_parser import extract_pdf_filefrom skyvern.forge.sdk.workflow.models.block import CodeBlockfrom skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatusfrom skyvern.schemas.workflows import BlockType@@ -191,6 +198,11 @@ _ACTIVE_RUN_TERMINAL_MONITOR_INITIAL_DELAY_SECONDS = 30.0_ACTIVE_RUN_TERMINAL_MONITOR_INTERVAL_SECONDS = 30.0_ACTIVE_RUN_TERMINAL_MONITOR_MAX_SAMPLES = 8+_MAX_REGISTERED_ARTIFACTS = 3+_MAX_REGISTERED_ARTIFACT_BYTES = 5 * 1024 * 1024+_MAX_REGISTERED_ARTIFACT_TEXT_CHARS = 20_000+_REGISTERED_ARTIFACT_PARSE_EXTENSIONS = frozenset({".txt", ".csv", ".json"})+_POST_RUN_REPAIR_CAPTURE_TIMEOUT_SECONDS = 30.0# Primary exit condition: seconds of no observed progress across the combined@@ -1085,14 +1097,141 @@ async def _attach_registered_output_parameter_values(return values_by_label-async def _capture_and_store_post_run_failure_page(+def _pin_pre_run_page_reference(ctx: CopilotContext, run_id: str) -> None:+ evidence = ctx.composition_page_evidence+ if not isinstance(evidence, Mapping):+ return+ text = page_evidence_prose_text(evidence).strip()+ if not text:+ return+ ctx.pre_run_page_reference = PreRunPageReference(text=text, workflow_run_id=run_id)+++def _artifact_file_name(artifact: Artifact) -> str:+ uri = artifact.uri if isinstance(artifact.uri, str) else ""+ return uri.rsplit("/", 1)[-1] if uri else artifact.artifact_id+++def _parse_registered_artifact_text(file_name: str, artifact_bytes: bytes) -> str | None:+ suffix = os.path.splitext(file_name)[1].lower()+ if suffix == ".pdf":+ temp_file_path: str | None = None+ try:+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:+ temp_file_path = temp_file.name+ temp_file.write(artifact_bytes)+ return extract_pdf_file(temp_file_path, file_identifier=file_name) or None+ except Exception:+ return None+ finally:+ if temp_file_path is not None:+ try:+ os.unlink(temp_file_path)+ except OSError:+ pass+ if suffix in _REGISTERED_ARTIFACT_PARSE_EXTENSIONS:+ try:+ return artifact_bytes.decode("utf-8", errors="ignore") or None+ except Exception:+ return None+ return None+++def _collect_downloaded_artifact_ids(block_outputs_by_label: Mapping[str, Any]) -> list[str]:+ ordered: list[str] = []+ seen: set[str] = set()+ for output in block_outputs_by_label.values():+ if not isinstance(output, dict):+ continue+ raw = output.get("downloaded_file_artifact_ids")+ if not isinstance(raw, list):+ continue+ for artifact_id in raw:+ if isinstance(artifact_id, str) and artifact_id and artifact_id not in seen:+ seen.add(artifact_id)+ ordered.append(artifact_id)+ return ordered+++async def _fetch_registered_download_artifacts(+ *, run_id: str, organization_id: str, downloaded_artifact_ids: Sequence[str] | None+) -> list[Artifact]:+ # The run's own download artifact ids are same-run by construction, so keying off them+ # avoids depending on the DOWNLOAD row's workflow_run_id stamp across repair-iteration run ids.+ if downloaded_artifact_ids:+ artifacts = await app.DATABASE.artifacts.get_artifacts_by_ids(+ list(dict.fromkeys(downloaded_artifact_ids)),+ organization_id=organization_id,+ )+ by_id = {+ artifact.artifact_id: artifact for artifact in artifacts if artifact.artifact_type == ArtifactType.DOWNLOAD+ }+ return [by_id[artifact_id] for artifact_id in dict.fromkeys(downloaded_artifact_ids) if artifact_id in by_id]+ result = await app.DATABASE.artifacts.get_artifacts_for_run(+ run_id,+ organization_id=organization_id,+ artifact_types=[ArtifactType.DOWNLOAD],+ )+ return result if isinstance(result, list) else []+++async def _capture_registered_artifact_evidence(+ ctx: CopilotContext,+ *,+ run_id: str,+ organization_id: str,+ downloaded_artifact_ids: Sequence[str] | None = None,+) -> None:+ try:+ artifacts = await _fetch_registered_download_artifacts(+ run_id=run_id,+ organization_id=organization_id,+ downloaded_artifact_ids=downloaded_artifact_ids,+ )+ except Exception:+ LOG.debug("Registered-artifact evidence fetch failed", run_id=run_id, exc_info=True)+ return+ entries: list[RegisteredArtifactEntry] = []+ total_chars = 0+ for artifact in artifacts[:_MAX_REGISTERED_ARTIFACTS]:+ file_name = _artifact_file_name(artifact)+ suffix = os.path.splitext(file_name)[1].lower()+ if suffix != ".pdf" and suffix not in _REGISTERED_ARTIFACT_PARSE_EXTENSIONS:+ continue+ file_size = artifact.file_size+ if isinstance(file_size, int) and file_size > _MAX_REGISTERED_ARTIFACT_BYTES:+ LOG.debug("Skipping oversize registered artifact", artifact_id=artifact.artifact_id, file_size=file_size)+ continue+ try:+ artifact_bytes = await app.ARTIFACT_MANAGER.retrieve_artifact(artifact)+ except Exception:+ LOG.debug("Registered-artifact retrieve failed", artifact_id=artifact.artifact_id, exc_info=True)+ continue+ if not artifact_bytes or len(artifact_bytes) > _MAX_REGISTERED_ARTIFACT_BYTES:+ continue+ parsed_text = _parse_registered_artifact_text(file_name, artifact_bytes)+ if not parsed_text:+ continue+ remaining = _MAX_REGISTERED_ARTIFACT_TEXT_CHARS - total_chars+ if remaining <= 0:+ break+ clipped = parsed_text[:remaining]+ total_chars += len(clipped)+ entries.append(+ RegisteredArtifactEntry(artifact_id=artifact.artifact_id, file_name=file_name, parsed_text=clipped)+ )+ if entries:+ ctx.registered_artifact_evidence = RegisteredArtifactEvidence(entries=tuple(entries), workflow_run_id=run_id)+++async def _capture_and_store_post_run_page(ctx: CopilotContext,*,run_session_id: str,run_id: str,current_url: str,) -> None:- """Observe-only capture of the run-session failure page; the discovery extractor reads+ """Observe-only capture of the run-session page; the discovery extractor readsctx.browser_session_id per call, so the rebind targets the run session and is restored in a finally.A failed or hollow capture neutralizes stale evidence to None only when it would not cleanly matchthis run_id, so the matcher's destructive clear cannot fire on the pending failure-string context."""@@ -1794,19 +1933,27 @@ async def _run_blocks_and_collect_debug(if (not dispatch_to_worker- and not run_okand run_session_idand _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSERand not ctx.copilot_total_timeout_exceeded):# CDP capture against the run session: worker-owned for dispatched runs, so skip it.- await _capture_and_store_post_run_failure_page(+ _pin_pre_run_page_reference(ctx, workflow_run.workflow_run_id)+ await _capture_and_store_post_run_page(ctx,run_session_id=run_session_id,run_id=workflow_run.workflow_run_id,current_url=current_url,)+ if not dispatch_to_worker and not ctx.copilot_total_timeout_exceeded:+ await _capture_registered_artifact_evidence(+ ctx,+ run_id=workflow_run.workflow_run_id,+ organization_id=ctx.organization_id,+ downloaded_artifact_ids=_collect_downloaded_artifact_ids(block_outputs_by_label),+ )+result_data: dict[str, Any] = {"workflow_run_id": workflow_run.workflow_run_id,"browser_session_id": run_session_id,diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.pyindex e472bc749..565adf9c9 100644--- a/tests/unit/test_copilot_diagnosis_repair_contract.py+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py@@ -2366,7 +2366,7 @@ async def test_bounded_seam_capture_is_stored_stamped_without_touching_budget(monkeypatch.setattr(run_execution_module, "_capture_composition_evidence", fake_capture)- await run_execution_module._capture_and_store_post_run_failure_page(+ await run_execution_module._capture_and_store_post_run_page(ctx, run_session_id="run_session", run_id="wr_failed", current_url="https://example.test/app/results")@@ -2415,7 +2415,7 @@ async def test_failed_seam_capture_neutralizes_non_matching_evidence(monkeypatch.setattr(run_execution_module, "_capture_composition_evidence", fake_capture)- await run_execution_module._capture_and_store_post_run_failure_page(+ await run_execution_module._capture_and_store_post_run_page(ctx, run_session_id="run_session", run_id="wr_failed", current_url="https://example.test/app")assert ctx.composition_page_evidence is None@@ -2437,7 +2437,7 @@ async def test_failed_seam_capture_preserves_clean_matching_evidence(monkeypatch.setattr(run_execution_module, "_capture_composition_evidence", fake_capture)- await run_execution_module._capture_and_store_post_run_failure_page(+ await run_execution_module._capture_and_store_post_run_page(ctx, run_session_id="run_session", run_id="wr_failed", current_url="https://example.test/app")assert ctx.composition_page_evidence is cleandiff --git a/tests/unit/test_copilot_positive_evidence_carriers.py b/tests/unit/test_copilot_positive_evidence_carriers.pynew file mode 100644index 000000000..5f7419ee9--- /dev/null+++ b/tests/unit/test_copilot_positive_evidence_carriers.py@@ -0,0 +1,541 @@+from __future__ import annotations++import os+from types import SimpleNamespace++import pytest++from skyvern.forge.sdk.artifact.models import ArtifactType+from skyvern.forge.sdk.copilot.completion_output_grounding import (+ _boundary_delimited_present,+ grade_requested_output_criteria,+ page_evidence_prose_text,+)+from skyvern.forge.sdk.copilot.completion_verification import (+ CompletionVerificationResult,+ CriterionVerdict,+ RunEvidenceSnapshot,+ grade_fallback_floor_reached_end_state_criteria,+)+from skyvern.forge.sdk.copilot.request_policy import _classifier_fallback_policy, build_classifier_fallback_floor+from skyvern.forge.sdk.copilot.runtime import (+ PreRunPageReference,+ RegisteredArtifactEntry,+ RegisteredArtifactEvidence,+)+from skyvern.forge.sdk.copilot.tools import completion as completion_module+from skyvern.forge.sdk.copilot.tools import run_execution as run_execution_module+from tests.unit.copilot_test_helpers import make_completion_criterion++_POST_RUN_LABEL = "post_run_page_observation"+_ARTIFACT_LABEL = "registered_artifact_observation"+_FLOOR_ID = "__copilot_fallback_floor__run"+++class _GroundingCtx:+ def __init__(self) -> None:+ self.code_artifact_metadata: dict[str, object] = {}+ self.last_workflow_yaml: str | None = None+ self.workflow_yaml: str | None = None+++def _page_snapshot(post_run_text: str, pre_run_text: str | None) -> RunEvidenceSnapshot:+ return RunEvidenceSnapshot(+ block_outputs={_POST_RUN_LABEL: {"visible_text_excerpt": post_run_text}},+ block_output_sources={_POST_RUN_LABEL: "independent_page_evidence"},+ pre_run_page_reference_text=pre_run_text,+ )+++def _artifact_snapshot(parsed_text: str) -> RunEvidenceSnapshot:+ return RunEvidenceSnapshot(+ block_outputs={_ARTIFACT_LABEL: {"parsed_text": parsed_text, "file_names": ["invoice.pdf"]}},+ block_output_sources={_ARTIFACT_LABEL: "registered_artifact_content"},+ )+++def _requested_criterion(value: object) -> object:+ return make_completion_criterion(+ "c_out",+ "the request returns a confirmation number",+ output_path="output.confirmation_number",+ expected_output_value=value,+ )+++def _grade(criterion: object, snapshot: RunEvidenceSnapshot) -> CriterionVerdict:+ verdicts = grade_requested_output_criteria(_GroundingCtx(), [criterion], snapshot)+ assert len(verdicts) == 1+ return verdicts[0]+++def test_page_carrier_confirms_post_run_present_pre_run_absent() -> None:+ snapshot = _page_snapshot("Your confirmation number is WTR-1842-DEMO. Thank you.", "Submit your request below.")+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), snapshot)+ assert verdict.state == "satisfied"+ assert verdict.reason_code == "evidence_confirms"+ assert verdict.evidence_source == "independent_page_evidence"+++def test_page_carrier_is_fully_satisfied_without_self_emission() -> None:+ snapshot = _page_snapshot("Confirmation WTR-1842-DEMO issued.", "Start a new request.")+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), snapshot)+ result = CompletionVerificationResult(status="evaluated", criterion_ids=["c_out"], verdicts=[verdict])+ assert result.is_fully_satisfied() is True+++def test_page_carrier_pre_run_present_does_not_confirm() -> None:+ snapshot = _page_snapshot(+ "Your confirmation number is WTR-1842-DEMO.", "Prior page already showed WTR-1842-DEMO earlier."+ )+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), snapshot)+ assert verdict.reason_code != "evidence_confirms"+++def test_page_carrier_missing_pre_run_pin_abstains() -> None:+ snapshot = _page_snapshot("Your confirmation number is WTR-1842-DEMO.", None)+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), snapshot)+ assert verdict.reason_code != "evidence_confirms"+++def test_artifact_carrier_confirms_without_absence_proof() -> None:+ snapshot = _artifact_snapshot("Invoice INV-4820-XZ total 512.00 USD paid.")+ verdict = _grade(_requested_criterion("INV-4820-XZ"), snapshot)+ assert verdict.state == "satisfied"+ assert verdict.reason_code == "evidence_confirms"+ assert verdict.evidence_source == "registered_artifact_content"+++def test_structured_contradiction_masks_confirmation() -> None:+ # Production packet shape: prose in visible_text_excerpt (no agent-only evidence_text), and a+ # structured value at the requested output_path that contradicts the expected scalar.+ snapshot = RunEvidenceSnapshot(+ block_outputs={+ _POST_RUN_LABEL: {+ "visible_text_excerpt": "confirmation WTR-1842-DEMO shown",+ "output": {"confirmation_number": "OTHER-0000-XX"},+ }+ },+ block_output_sources={_POST_RUN_LABEL: "independent_page_evidence"},+ pre_run_page_reference_text="a blank request form",+ )+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), snapshot)+ assert verdict.reason_code != "evidence_confirms"++[email protected](reason="SKY-11868: free-text-only contradiction is unmaskable without a substring door", strict=True)+def test_free_text_contradiction_masks_confirmation() -> None:+ # The contradicting value lives only in prose, not at a resolvable structured path; the+ # snapshot-absence carrier cannot tell a confirming appearance from a contradicting one in+ # free text without reintroducing the withdrawn substring door.+ snapshot = _page_snapshot("Requested WTR-1842-DEMO but the confirmed number is OTHER-0000-XX.", "empty form")+ verdict = _grade(_requested_criterion("WTR-1842-DEMO"), snapshot)+ assert verdict.reason_code != "evidence_confirms"+++def test_boolean_expected_value_never_confirms() -> None:+ snapshot = _page_snapshot("The submission state is true now.", "empty form")+ verdict = _grade(_requested_criterion(True), snapshot)+ assert verdict.reason_code != "evidence_confirms"+++def test_judgment_boolean_criterion_yields_no_carrier_confirmation() -> None:+ criterion = make_completion_criterion(+ "c_out",+ "the run judged the goal reached",+ output_path="output.goal_reached",+ expected_output_shape="goal_judgment_boolean",+ )+ snapshot = _page_snapshot("Goal reached and confirmed complete.", "empty form")+ verdict = _grade(criterion, snapshot)+ assert verdict.reason_code != "evidence_confirms"+++def test_substring_inside_word_does_not_confirm() -> None:+ snapshot = _page_snapshot("please DEMONSTRATE the workflow now", "empty form")+ verdict = _grade(_requested_criterion("DEMO"), snapshot)+ assert verdict.reason_code != "evidence_confirms"+++def test_sub_four_char_value_excluded() -> None:+ snapshot = _page_snapshot("Selected state: CA. Continue.", "no state selected")+ verdict = _grade(_requested_criterion("CA"), snapshot)+ assert verdict.reason_code != "evidence_confirms"+++def test_punctuation_adjacent_value_confirms() -> None:+ snapshot = _page_snapshot("Reference code: [REF-5521]! saved.", "empty form")+ verdict = _grade(_requested_criterion("REF-5521"), snapshot)+ assert verdict.state == "satisfied"+ assert verdict.evidence_source == "independent_page_evidence"+++def test_no_authored_contract_confirms_with_carrier_and_stays_unproducible_without() -> None:+ criterion = _requested_criterion("WTR-1842-DEMO")+ with_carrier = _grade(criterion, _page_snapshot("Confirmation WTR-1842-DEMO issued.", "empty form"))+ assert with_carrier.reason_code == "evidence_confirms"++ without_carrier = _grade(criterion, RunEvidenceSnapshot())+ assert without_carrier.reason_code == "unproducible"+++def test_boundary_predicate_rejects_alnum_neighbors() -> None:+ assert _boundary_delimited_present("demo", "the demo runs") is True+ assert _boundary_delimited_present("demo", "demonstrate") is False+ assert _boundary_delimited_present("1842", "order #1842.") is True+ assert _boundary_delimited_present("1842", "18429") is False+++def test_page_evidence_prose_text_skips_stamp_keys_and_booleans() -> None:+ text = page_evidence_prose_text(+ {+ "workflow_run_id": "wr_secret",+ "observed_after_workflow_run": True,+ "screenshot_used": True,+ "visible_text_excerpt": "confirmation WTR-1842-DEMO",+ }+ )+ assert "wr_secret" not in text+ assert "True" not in text+ assert "WTR-1842-DEMO" in text+++def _carrier_verdict(source: str) -> CriterionVerdict:+ return CriterionVerdict(+ criterion_id="c_out",+ state="satisfied",+ reason_code="evidence_confirms",+ evidence_ref=f"block_outputs:{_POST_RUN_LABEL}",+ evidence_source=source, # type: ignore[arg-type]+ )+++def test_fallback_floor_threads_carrier_verdict() -> None:+ floor = build_classifier_fallback_floor([])+ snapshot = RunEvidenceSnapshot(block_outputs={"other": {"note": "no terminal record here"}})+ verdicts = grade_fallback_floor_reached_end_state_criteria(+ floor, snapshot, carrier_verdicts=(_carrier_verdict("independent_page_evidence"),)+ )+ assert [v.criterion_id for v in verdicts] == [_FLOOR_ID]+ assert verdicts[0].state == "satisfied"+++def test_fallback_floor_without_carrier_verdict_stays_empty() -> None:+ floor = build_classifier_fallback_floor([])+ snapshot = RunEvidenceSnapshot(block_outputs={"other": {"note": "no terminal record here"}})+ assert grade_fallback_floor_reached_end_state_criteria(floor, snapshot) == []+++def test_fallback_floor_ignores_non_independent_carrier_source() -> None:+ floor = build_classifier_fallback_floor([])+ snapshot = RunEvidenceSnapshot(block_outputs={"other": {"note": "no terminal record here"}})+ assert (+ grade_fallback_floor_reached_end_state_criteria(+ floor, snapshot, carrier_verdicts=(_carrier_verdict("runtime_output"),)+ )+ == []+ )+++def test_fallback_floor_carrier_masked_by_poisoned_record() -> None:+ floor = build_classifier_fallback_floor([])+ snapshot = RunEvidenceSnapshot(block_outputs={"submit": {"error": "submission failed with a blocking challenge"}})+ assert (+ grade_fallback_floor_reached_end_state_criteria(+ floor, snapshot, carrier_verdicts=(_carrier_verdict("independent_page_evidence"),)+ )+ == []+ )+++def test_carrier_floor_verdicts_filter() -> None:+ verdicts = [+ _carrier_verdict("independent_page_evidence"),+ _carrier_verdict("runtime_output"),+ CriterionVerdict(criterion_id="x", state="unsatisfied", reason_code="unproducible"),+ ]+ filtered = completion_module._carrier_floor_verdicts(verdicts)+ assert len(filtered) == 1+ assert filtered[0].evidence_source == "independent_page_evidence"+++def test_floor_call_site_parity_across_seams() -> None:+ floor = build_classifier_fallback_floor([])+ snapshot = RunEvidenceSnapshot(block_outputs={"other": {"note": "no terminal record"}})+ carrier = (_carrier_verdict("independent_page_evidence"),)++ main = grade_fallback_floor_reached_end_state_criteria(floor, snapshot, carrier_verdicts=carrier)+ assert main and main[0].satisfied++ deterministic, _ = completion_module._deterministic_run_verification_result(+ floor, snapshot, carrier_verdicts=carrier+ )+ assert deterministic is not None+ assert any(v.criterion_id == _FLOOR_ID and v.satisfied for v in deterministic.verdicts)++ seeded = CompletionVerificationResult(+ status="evaluated",+ criterion_ids=[_FLOOR_ID],+ verdicts=[CriterionVerdict(criterion_id=_FLOOR_ID, state="unsatisfied", reason_code="no_evidence")],+ )+ upgraded = completion_module._apply_present_value_upgrades(+ seeded, floor, snapshot, include_terminal_goal_records=True, carrier_verdicts=carrier+ )+ assert any(v.criterion_id == _FLOOR_ID and v.satisfied for v in upgraded.verdicts)+++ "message",+ [+ "Read the receipt and return the confirmation number, which is CONF-7712045.",+ "Extract the confirmation number CONF-7712045 from the page and return it as a record.",+ "Capture the order status and confirmation number CONF-7712045 for the entity, grouped per location, with status.",+ ],+)+def test_classifier_fallback_mints_no_typed_requested_output_value(message: str) -> None:+ policy = _classifier_fallback_policy([], raw_secret_present=False, failure_kind="timeout", user_message=message)+ assert policy.classifier_status == "fallback"+ requested = [c for c in policy.completion_criteria if c.id.startswith("__copilot_requested_output__")]+ assert requested+ for criterion in requested:+ assert criterion.expected_output_value is None+ assert criterion.requested_output_evidence_source == "runtime_output"+++def test_registered_artifact_bind_requires_stamp_match() -> None:+ evidence = RegisteredArtifactEvidence(+ entries=(RegisteredArtifactEntry(artifact_id="art_1", file_name="a.txt", parsed_text="INV-4820-XZ"),),+ workflow_run_id="wr_match",+ )+ matched_outputs: dict[str, object] = {}+ matched_sources: dict[str, str] = {}+ completion_module._bind_registered_artifact_evidence(evidence, "wr_match", matched_outputs, matched_sources) # type: ignore[arg-type]+ assert matched_sources.get(_ARTIFACT_LABEL) == "registered_artifact_content"++ stale_outputs: dict[str, object] = {}+ stale_sources: dict[str, str] = {}+ completion_module._bind_registered_artifact_evidence(evidence, "wr_other", stale_outputs, stale_sources) # type: ignore[arg-type]+ assert _ARTIFACT_LABEL not in stale_outputs+++def test_registered_artifact_bind_does_not_overwrite_existing_label() -> None:+ evidence = RegisteredArtifactEvidence(+ entries=(RegisteredArtifactEntry(artifact_id="art_1", file_name="a.txt", parsed_text="INV-4820-XZ"),),+ workflow_run_id="wr_match",+ )+ outputs: dict[str, object] = {_ARTIFACT_LABEL: {"parsed_text": "runtime"}}+ sources: dict[str, str] = {_ARTIFACT_LABEL: "runtime_output"}+ completion_module._bind_registered_artifact_evidence(evidence, "wr_match", outputs, sources) # type: ignore[arg-type]+ assert sources[_ARTIFACT_LABEL] == "runtime_output"+++def test_pre_run_reference_text_stamp_gated() -> None:+ reference = PreRunPageReference(text="prior page text", workflow_run_id="wr_match")+ assert completion_module._pre_run_page_reference_text(reference, "wr_match") == "prior page text"+ assert completion_module._pre_run_page_reference_text(reference, "wr_other") is None+++def test_parse_registered_artifact_text_txt_decode() -> None:+ parsed = run_execution_module._parse_registered_artifact_text("notes.txt", b"INV-4820-XZ total")+ assert parsed == "INV-4820-XZ total"+++def test_parse_registered_artifact_text_unsupported_extension() -> None:+ assert run_execution_module._parse_registered_artifact_text("image.png", b"\x89PNG") is None+++def test_parse_registered_artifact_text_pdf_cleans_temp_file(monkeypatch: pytest.MonkeyPatch) -> None:+ captured: dict[str, str] = {}++ def fake_extract(path: str, *, file_identifier: str) -> str:+ captured["path"] = path+ assert os.path.exists(path)+ return "extracted INV-4820-XZ"++ monkeypatch.setattr(run_execution_module, "extract_pdf_file", fake_extract)+ parsed = run_execution_module._parse_registered_artifact_text("statement.pdf", b"%PDF-1.4 bytes")+ assert parsed == "extracted INV-4820-XZ"+ assert not os.path.exists(captured["path"])+++def test_parse_registered_artifact_text_pdf_cleans_temp_file_on_exception(monkeypatch: pytest.MonkeyPatch) -> None:+ captured: dict[str, str] = {}++ def fake_extract(path: str, *, file_identifier: str) -> str:+ captured["path"] = path+ raise ValueError("bad pdf")++ monkeypatch.setattr(run_execution_module, "extract_pdf_file", fake_extract)+ assert run_execution_module._parse_registered_artifact_text("statement.pdf", b"%PDF") is None+ assert not os.path.exists(captured["path"])+++def _artifact(+ artifact_id: str,+ file_name: str,+ file_size: int | None,+ artifact_type: ArtifactType = ArtifactType.DOWNLOAD,+) -> SimpleNamespace:+ return SimpleNamespace(+ artifact_id=artifact_id,+ uri=f"s3://bucket/{file_name}",+ file_size=file_size,+ artifact_type=artifact_type,+ )+++def _stub_app(+ monkeypatch: pytest.MonkeyPatch,+ artifacts: list[SimpleNamespace],+ retrieved: dict[str, bytes],+ *,+ by_ids: list[SimpleNamespace] | None = None,+) -> list[str]:+ retrieved_ids: list[str] = []++ async def fake_get_artifacts_for_run(+ run_id: str, *, organization_id: str, artifact_types: object+ ) -> list[SimpleNamespace]:+ return artifacts++ async def fake_get_artifacts_by_ids(artifact_ids: list[str], *, organization_id: str) -> list[SimpleNamespace]:+ pool = {artifact.artifact_id: artifact for artifact in (by_ids if by_ids is not None else artifacts)}+ return [pool[artifact_id] for artifact_id in artifact_ids if artifact_id in pool]++ async def fake_retrieve_artifact(artifact: SimpleNamespace) -> bytes:+ retrieved_ids.append(artifact.artifact_id)+ return retrieved.get(artifact.artifact_id, b"")++ fake_app = SimpleNamespace(+ DATABASE=SimpleNamespace(+ artifacts=SimpleNamespace(+ get_artifacts_for_run=fake_get_artifacts_for_run,+ get_artifacts_by_ids=fake_get_artifacts_by_ids,+ )+ ),+ ARTIFACT_MANAGER=SimpleNamespace(retrieve_artifact=fake_retrieve_artifact),+ )+ monkeypatch.setattr(run_execution_module, "app", fake_app)+ return retrieved_ids+++async def test_artifact_producer_binds_parsed_text(monkeypatch: pytest.MonkeyPatch) -> None:+ artifacts = [_artifact("art_1", "receipt.txt", 20)]+ _stub_app(monkeypatch, artifacts, {"art_1": b"INV-4820-XZ paid"})+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(ctx, run_id="wr_1", organization_id="o_1")+ assert ctx.registered_artifact_evidence is not None+ assert ctx.registered_artifact_evidence.workflow_run_id == "wr_1"+ assert ctx.registered_artifact_evidence.entries[0].parsed_text == "INV-4820-XZ paid"+++async def test_artifact_producer_skips_oversize_before_retrieval(monkeypatch: pytest.MonkeyPatch) -> None:+ oversize = run_execution_module._MAX_REGISTERED_ARTIFACT_BYTES + 1+ artifacts = [_artifact("art_big", "big.csv", oversize)]+ retrieved_ids = _stub_app(monkeypatch, artifacts, {"art_big": b"x"})+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(ctx, run_id="wr_1", organization_id="o_1")+ assert retrieved_ids == []+ assert ctx.registered_artifact_evidence is None+++async def test_artifact_producer_caps_artifact_count(monkeypatch: pytest.MonkeyPatch) -> None:+ artifacts = [_artifact(f"art_{i}", f"f{i}.txt", 10) for i in range(5)]+ retrieved_ids = _stub_app(monkeypatch, artifacts, {f"art_{i}": b"INV-4820-XZ" for i in range(5)})+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(ctx, run_id="wr_1", organization_id="o_1")+ assert len(retrieved_ids) == run_execution_module._MAX_REGISTERED_ARTIFACTS+++async def test_artifact_producer_skips_unsupported_extensions(monkeypatch: pytest.MonkeyPatch) -> None:+ artifacts = [_artifact("art_png", "screenshot.png", 10)]+ retrieved_ids = _stub_app(monkeypatch, artifacts, {"art_png": b"binary"})+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(ctx, run_id="wr_1", organization_id="o_1")+ assert retrieved_ids == []+ assert ctx.registered_artifact_evidence is None+++def test_collect_downloaded_artifact_ids_dedupes_across_blocks() -> None:+ block_outputs = {+ "download": {"downloaded_file_artifact_ids": ["art_1", "art_2"]},+ "report": {"downloaded_file_artifact_ids": ["art_2", "art_3"]},+ "noise": {"value": "no ids"},+ "bad": {"downloaded_file_artifact_ids": "not-a-list"},+ }+ assert run_execution_module._collect_downloaded_artifact_ids(block_outputs) == ["art_1", "art_2", "art_3"]+++async def test_artifact_producer_binds_from_downloaded_artifact_ids(monkeypatch: pytest.MonkeyPatch) -> None:+ graded = [_artifact("art_graded", "receipt.txt", 30)]+ _stub_app(monkeypatch, artifacts=[], retrieved={"art_graded": b"CONF-7712045 paid"}, by_ids=graded)+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(+ ctx, run_id="wr_graded", organization_id="o_1", downloaded_artifact_ids=["art_graded"]+ )+ assert ctx.registered_artifact_evidence is not None+ assert ctx.registered_artifact_evidence.workflow_run_id == "wr_graded"+ assert ctx.registered_artifact_evidence.entries[0].parsed_text == "CONF-7712045 paid"+++async def test_artifact_producer_binds_graded_run_across_repair_iteration_ids(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ graded = [_artifact("art_iter2", "receipt.txt", 30)]+ stale_run_scan = [_artifact("art_iter1", "receipt.txt", 30)]+ _stub_app(+ monkeypatch,+ artifacts=stale_run_scan,+ retrieved={"art_iter2": b"CONF-7712045 paid"},+ by_ids=graded,+ )+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(+ ctx, run_id="wr_iter2", organization_id="o_1", downloaded_artifact_ids=["art_iter2"]+ )+ assert ctx.registered_artifact_evidence is not None+ assert ctx.registered_artifact_evidence.workflow_run_id == "wr_iter2"+ assert ctx.registered_artifact_evidence.entries[0].artifact_id == "art_iter2"+++async def test_artifact_producer_id_path_filters_non_download_type(monkeypatch: pytest.MonkeyPatch) -> None:+ non_download = [_artifact("art_screenshot", "page.txt", 30, artifact_type=ArtifactType.SCREENSHOT_LLM)]+ retrieved_ids = _stub_app(+ monkeypatch, artifacts=[], retrieved={"art_screenshot": b"CONF-7712045"}, by_ids=non_download+ )+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(+ ctx, run_id="wr_1", organization_id="o_1", downloaded_artifact_ids=["art_screenshot"]+ )+ assert retrieved_ids == []+ assert ctx.registered_artifact_evidence is None+++async def test_artifact_producer_id_path_skips_oversize(monkeypatch: pytest.MonkeyPatch) -> None:+ oversize = run_execution_module._MAX_REGISTERED_ARTIFACT_BYTES + 1+ graded = [_artifact("art_big", "big.csv", oversize)]+ retrieved_ids = _stub_app(monkeypatch, artifacts=[], retrieved={"art_big": b"x"}, by_ids=graded)+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(+ ctx, run_id="wr_1", organization_id="o_1", downloaded_artifact_ids=["art_big"]+ )+ assert retrieved_ids == []+ assert ctx.registered_artifact_evidence is None+++async def test_artifact_producer_falls_back_to_run_scan_without_ids(monkeypatch: pytest.MonkeyPatch) -> None:+ artifacts = [_artifact("art_1", "receipt.txt", 20)]+ _stub_app(monkeypatch, artifacts, {"art_1": b"INV-4820-XZ paid"}, by_ids=[])+ ctx = SimpleNamespace(registered_artifact_evidence=None)+ await run_execution_module._capture_registered_artifact_evidence(ctx, run_id="wr_1", organization_id="o_1")+ assert ctx.registered_artifact_evidence is not None+ assert ctx.registered_artifact_evidence.entries[0].parsed_text == "INV-4820-XZ paid"