Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-12564 Parameterize witnessed account and month in download filenames (#7670)
Andrew Neilson70a6d3a06e98
diff --git a/skyvern/forge/sdk/copilot/authoring_parameter_binding.py b/skyvern/forge/sdk/copilot/authoring_parameter_binding.pyindex a0dc9c2a4..facb16eb1 100644--- a/skyvern/forge/sdk/copilot/authoring_parameter_binding.py+++ b/skyvern/forge/sdk/copilot/authoring_parameter_binding.py@@ -3,7 +3,8 @@ from __future__ import annotationsimport astimport hashlibimport json-from collections.abc import Sequence+from collections.abc import Mapping, Sequence+from dataclasses import dataclassfrom typing import Literalfrom pydantic import BaseModel, ConfigDict, Field@@ -21,6 +22,231 @@ _SELECTION_MATCH_BASES: frozenset[AuthoringParameterBindingMatchBasis] = frozens{"scouted_selection_value", "scouted_option_value"})+SameMonthFileMatchFormat = Literal["identity", "iso_date_to_year_month"]+++@dataclass(frozen=True, slots=True)+class SameMonthFileMatchHole:+ declared_keys: tuple[str, ...]+ matched_literal: str+ position: int+ format_id: SameMonthFileMatchFormat+ source_values: tuple[str, ...]+++@dataclass(frozen=True, slots=True)+class SameMonthFileMatchTransform:+ selector: str+ holes: tuple[SameMonthFileMatchHole, ...]+ date_keys: tuple[str, str]+ expected_declared_keys: tuple[str, ...]+ provenance_fingerprint: str+ date_format_id: Literal["iso_date_to_year_month"] = "iso_date_to_year_month"+++def same_month_file_match_transform_fingerprint(transform: SameMonthFileMatchTransform) -> str:+ payload = {+ "selector": transform.selector,+ "holes": [+ {+ "declared_keys": hole.declared_keys,+ "matched_literal": hole.matched_literal,+ "position": hole.position,+ "format_id": hole.format_id,+ "source_values": hole.source_values,+ }+ for hole in transform.holes+ ],+ "date_keys": transform.date_keys,+ "expected_declared_keys": transform.expected_declared_keys,+ "date_format_id": transform.date_format_id,+ }+ return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest()+++def _iso_date_parts(value: str) -> tuple[int, int, int] | None:+ parts = value.split("-")+ if len(parts) != 3 or tuple(map(len, parts)) != (4, 2, 2) or any(not part.isdigit() for part in parts):+ return None+ year, month, day = (int(part) for part in parts)+ if year < 1 or month < 1 or month > 12:+ return None+ leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)+ days = (31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)+ return (year, month, day) if 1 <= day <= days[month - 1] else None+++def _quoted_content_spans(value: str) -> tuple[tuple[int, int], ...]:+ spans: list[tuple[int, int]] = []+ quote = ""+ start = -1+ index = 0+ while index < len(value):+ character = value[index]+ if quote:+ if character == "\\":+ index += 2+ continue+ if character == quote:+ spans.append((start, index))+ quote = ""+ elif character in ("'", '"'):+ quote = character+ start = index + 1+ index += 1+ return tuple(spans)+++def _quoted_boundary_positions(+ selector: str,+ literal: str,+ quoted_spans: Sequence[tuple[int, int]],+) -> tuple[int, ...]:+ positions: list[int] = []+ start = 0+ while literal:+ position = selector.find(literal, start)+ if position < 0:+ break+ end = position + len(literal)+ left_boundary = position == 0 or not selector[position - 1].isalnum()+ right_boundary = end == len(selector) or not selector[end].isalnum()+ inside_quote = any(span_start <= position and end <= span_end for span_start, span_end in quoted_spans)+ if left_boundary and right_boundary and inside_quote:+ positions.append(position)+ start = position + 1+ return tuple(positions)+++def same_month_file_match_transform_is_valid(transform: SameMonthFileMatchTransform) -> bool:+ if (+ transform.provenance_fingerprint != same_month_file_match_transform_fingerprint(transform)+ or not transform.expected_declared_keys+ or transform.expected_declared_keys != tuple(sorted(set(transform.expected_declared_keys)))+ or len(set(transform.date_keys)) != 2+ or not set(transform.date_keys).issubset(transform.expected_declared_keys)+ ):+ return False+ quoted_spans = _quoted_content_spans(transform.selector)+ covered_keys: set[str] = set()+ cursor = 0+ date_holes = 0+ for hole in transform.holes:+ if (+ hole.position < cursor+ or not hole.matched_literal+ or not hole.declared_keys+ or any(not key or key in covered_keys for key in hole.declared_keys)+ or transform.selector[hole.position : hole.position + len(hole.matched_literal)] != hole.matched_literal+ or _quoted_boundary_positions(transform.selector, hole.matched_literal, quoted_spans) != (hole.position,)+ ):+ return False+ covered_keys.update(hole.declared_keys)+ cursor = hole.position + len(hole.matched_literal)+ if hole.format_id == "identity":+ if len(hole.declared_keys) != 1 or hole.source_values != (hole.matched_literal,):+ return False+ continue+ if hole.format_id != "iso_date_to_year_month" or hole.declared_keys != transform.date_keys:+ return False+ if len(hole.source_values) != 2:+ return False+ date_parts = tuple(_iso_date_parts(value) for value in hole.source_values)+ if any(parts is None for parts in date_parts):+ return False+ start_parts, end_parts = date_parts+ if start_parts is None or end_parts is None or start_parts[:2] != end_parts[:2]:+ return False+ if hole.matched_literal != f"{start_parts[0]:04d}-{start_parts[1]:02d}":+ return False+ date_holes += 1+ return date_holes == 1 and covered_keys == set(transform.expected_declared_keys)+++def derive_same_month_file_match_transform(+ *,+ selector: str,+ parameter_values: Mapping[str, str],+ identity_correspondences: Sequence[Mapping[str, object]],+) -> SameMonthFileMatchTransform | None:+ if not selector or not parameter_values or any(not key or not value for key, value in parameter_values.items()):+ return None+ quoted_spans = _quoted_content_spans(selector)+ identity_holes: dict[str, SameMonthFileMatchHole] = {}+ duplicate_identity_keys: set[str] = set()+ for correspondence in identity_correspondences:+ key = correspondence.get("input_key")+ literal = correspondence.get("matched_literal")+ position = correspondence.get("position")+ if (+ not isinstance(key, str)+ or not isinstance(literal, str)+ or not isinstance(position, int)+ or correspondence.get("surface") != "selector"+ or correspondence.get("transform") != "identity"+ or correspondence.get("parameter_value") != parameter_values.get(key)+ or literal != parameter_values.get(key)+ or _quoted_boundary_positions(selector, literal, quoted_spans) != (position,)+ ):+ continue+ if key in identity_holes:+ duplicate_identity_keys.add(key)+ identity_holes[key] = SameMonthFileMatchHole((key,), literal, position, "identity", (literal,))+ if duplicate_identity_keys:+ return None++ parsed_dates = [+ (key, value, parts) for key, value in parameter_values.items() if (parts := _iso_date_parts(value)) is not None+ ]+ candidates: list[SameMonthFileMatchTransform] = []+ for left_index, (left_key, left_value, left_parts) in enumerate(parsed_dates):+ for right_key, right_value, right_parts in parsed_dates[left_index + 1 :]:+ if left_parts[:2] != right_parts[:2]:+ continue+ month_literal = f"{left_parts[0]:04d}-{left_parts[1]:02d}"+ month_positions = _quoted_boundary_positions(selector, month_literal, quoted_spans)+ if len(month_positions) != 1:+ continue+ date_records = sorted(+ ((left_key, left_value, left_parts), (right_key, right_value, right_parts)),+ key=lambda record: (record[2], record[0]),+ )+ date_keys = (date_records[0][0], date_records[1][0])+ if any(key in identity_holes for key in date_keys):+ continue+ holes = [hole for key, hole in identity_holes.items() if key not in date_keys]+ holes.append(+ SameMonthFileMatchHole(+ declared_keys=date_keys,+ matched_literal=month_literal,+ position=month_positions[0],+ format_id="iso_date_to_year_month",+ source_values=(date_records[0][1], date_records[1][1]),+ )+ )+ holes.sort(key=lambda hole: hole.position)+ covered_keys = {key for hole in holes for key in hole.declared_keys}+ if any(left.position + len(left.matched_literal) > right.position for left, right in zip(holes, holes[1:])):+ continue+ candidate = SameMonthFileMatchTransform(+ selector=selector,+ holes=tuple(holes),+ date_keys=date_keys,+ expected_declared_keys=tuple(sorted(covered_keys)),+ provenance_fingerprint="",+ )+ candidates.append(+ SameMonthFileMatchTransform(+ selector=candidate.selector,+ holes=candidate.holes,+ date_keys=candidate.date_keys,+ expected_declared_keys=candidate.expected_declared_keys,+ provenance_fingerprint=same_month_file_match_transform_fingerprint(candidate),+ )+ )+ unique = {candidate: candidate for candidate in candidates}+ return next(iter(unique.values())) if len(unique) == 1 else None+class AuthoringParameterFieldBinding(BaseModel):model_config = ConfigDict(extra="forbid", frozen=True)diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.pyindex 0c733dd7d..2809ef4ac 100644--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py@@ -26,7 +26,10 @@ import structlogfrom skyvern.forge.sdk.copilot.authoring_parameter_binding import (AuthoringParameterBindingSnapshot,+ SameMonthFileMatchTransform,authoring_parameter_binding_fingerprint,+ same_month_file_match_transform_fingerprint,+ same_month_file_match_transform_is_valid,)from skyvern.forge.sdk.copilot.composition_evidence import SCOUT_INTERACTION_EVIDENCE_TOOLfrom skyvern.forge.sdk.copilot.output_extraction_plan import (@@ -47,6 +50,8 @@ _MAX_STEPS = 60_INDENT = " "_DOMCONTENTLOADED = "domcontentloaded"_ENTRY_TARGET_VAR = "_scout_entry_target"+_DOWNLOAD_TARGET_VAR = "_scout_download_target"+_SAME_MONTH_HELPER_VAR = "_scout_same_month_iso"_ENTRY_REUSED_VAR = "_scout_entry_reused_current_page"_ENTRY_RESUME_AFTER_AUTH_VAR = "_scout_entry_resume_after_auth"_ENTRY_RESUME_TARGET_VAR = "_scout_entry_resume_target"@@ -57,6 +62,7 @@ _MONTH_HELPER_VAR = "_scout_month_to_iso"_ENTRY_LOCATOR_VARS = (_ENTRY_TARGET_VAR, _ENTRY_RESUME_TARGET_VAR, _ENTRY_OPENER_VAR)_INTERNAL_SCOUT_VARS = (_ENTRY_TARGET_VAR,+ _DOWNLOAD_TARGET_VAR,_ENTRY_REUSED_VAR,_ENTRY_RESUME_AFTER_AUTH_VAR,_ENTRY_RESUME_TARGET_VAR,@@ -64,6 +70,7 @@ _INTERNAL_SCOUT_VARS = (_OPTIONAL_DISMISSAL_VAR,_READONLY_DEFERRED_VAR,_MONTH_HELPER_VAR,+ _SAME_MONTH_HELPER_VAR,)# Base name for the download var bound by `async with page.expect_download() as <name>:`.@@ -558,6 +565,7 @@ def _get_by_role_expr_strict(role: str, name: str) -> str:LOCATOR_WITNESS_PARAM_SOURCE = "locator_witness"INPUT_TEMPLATED_PROVENANCE_SOURCE = "input_templated"+SAME_MONTH_FILE_MATCH_PROVENANCE_SOURCE = "same_month_file_match"_SCOUT_MONTH_HELPER_NAME = _MONTH_HELPER_VAR_WITNESS_MIN_VALUE_LEN = 3_WITNESS_SAFE_CHARSET_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 ._-]*$")@@ -691,17 +699,12 @@ def _resolve_non_competing_correspondences(raw: list[dict[str, Any]]) -> list[Screturn result-def input_correspondences_for_interaction(- interaction: Mapping[str, Any], declared_params: Mapping[str, str]+def _input_correspondences_for_surfaces(+ *,+ selector: str,+ name: str,+ declared_params: Mapping[str, str],) -> list[ScoutedInputCorrespondence]:- """Witness a declared parameter value observed verbatim (identity, or month-name -> ISO) inside a- quoted selector segment or the accessible name at click time — value containment, never label==header- matching. Empty unless the match is unique across both surfaces, boundary-delimited, safe-charset on- value and literal, whitespace-normalized, and name-safe."""- if str(interaction.get("tool_name") or "") != "click":- return []- selector = str(interaction.get("selector") or "").strip()- name = str(interaction.get("accessible_name") or "").strip()selector_spans = _quoted_content_spans(selector)name_spans = [(0, len(name))] if name else []raw: list[dict[str, Any]] = []@@ -737,6 +740,33 @@ def input_correspondences_for_interaction(return _resolve_non_competing_correspondences(raw)+def input_correspondences_for_selector(+ selector: str,+ declared_params: Mapping[str, str],+) -> list[ScoutedInputCorrespondence]:+ return _input_correspondences_for_surfaces(+ selector=selector.strip(),+ name="",+ declared_params=declared_params,+ )+++def input_correspondences_for_interaction(+ interaction: Mapping[str, Any], declared_params: Mapping[str, str]+) -> list[ScoutedInputCorrespondence]:+ """Witness a declared parameter value observed verbatim (identity, or month-name -> ISO) inside a+ quoted selector segment or the accessible name at click time — value containment, never label==header+ matching. Empty unless the match is unique across both surfaces, boundary-delimited, safe-charset on+ value and literal, whitespace-normalized, and name-safe."""+ if str(interaction.get("tool_name") or "") != "click":+ return []+ return _input_correspondences_for_surfaces(+ selector=str(interaction.get("selector") or "").strip(),+ name=str(interaction.get("accessible_name") or "").strip(),+ declared_params=declared_params,+ )++def _escape_fstring_literal_segment(value: str) -> str:escaped = value.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n").replace("\r", "\\r")escaped = "".join(f"\\x{ord(ch):02x}" if ch in _CONTROL_CODEPOINTS else ch for ch in escaped)@@ -949,6 +979,73 @@ def witness_prelude_lines(keys: Sequence[str], *, include_month_helper: bool) ->return lines+def _same_month_helper_lines() -> list[str]:+ return [+ f"{_INDENT}def {_SAME_MONTH_HELPER_VAR}(_start_value, _end_value):",+ f"{_INDENT * 2}def _parse_iso_date(_value):",+ f"{_INDENT * 3}_parts = str(_value).split({_py_str('-')})",+ f"{_INDENT * 3}if not (len(_parts) == 3 and len(_parts[0]) == 4 and len(_parts[1]) == 2 "+ f"and len(_parts[2]) == 2 and all(_part.isdigit() for _part in _parts)):",+ f'{_INDENT * 4}raise Exception("invalid full date for grounded file match")',+ f"{_INDENT * 3}_year = int(_parts[0])",+ f"{_INDENT * 3}_month = int(_parts[1])",+ f"{_INDENT * 3}_day = int(_parts[2])",+ f"{_INDENT * 3}if _year < 1 or _month < 1 or _month > 12:",+ f'{_INDENT * 4}raise Exception("invalid full date for grounded file match")',+ f"{_INDENT * 3}_leap = _year % 4 == 0 and (_year % 100 != 0 or _year % 400 == 0)",+ f"{_INDENT * 3}_days = (31, 29 if _leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)",+ f"{_INDENT * 3}if _day < 1 or _day > _days[_month - 1]:",+ f'{_INDENT * 4}raise Exception("invalid full date for grounded file match")',+ f"{_INDENT * 3}return (_year, _month, _day)",+ f"{_INDENT * 2}_start = _parse_iso_date(_start_value)",+ f"{_INDENT * 2}_end = _parse_iso_date(_end_value)",+ f"{_INDENT * 2}if _start[0] != _end[0] or _start[1] != _end[1]:",+ f'{_INDENT * 3}raise Exception("grounded file match dates must share one calendar month")',+ f"{_INDENT * 2}return str(_start[0]).zfill(4) + {_py_str('-')} + str(_start[1]).zfill(2)",+ ]+++def build_same_month_file_match_locator(transform: SameMonthFileMatchTransform, selector: str) -> str | None:+ if (+ transform.selector != selector+ or transform.date_format_id != "iso_date_to_year_month"+ or not transform.holes+ or not same_month_file_match_transform_is_valid(transform)+ ):+ return None+ keys: set[str] = set()+ cursor = 0+ segments: list[str] = []+ date_holes = 0+ quoted_spans = _quoted_content_spans(selector)+ for hole in transform.holes:+ if (+ hole.position < cursor+ or not hole.matched_literal+ or selector[hole.position : hole.position + len(hole.matched_literal)] != hole.matched_literal+ or _boundary_delimited_positions(selector, hole.matched_literal, quoted_spans) != [hole.position]+ or not hole.declared_keys+ or any(not grounded_parameter_key_is_safe(key) or key in keys for key in hole.declared_keys)+ ):+ return None+ keys.update(hole.declared_keys)+ segments.append(_escape_fstring_literal_segment(selector[cursor : hole.position]))+ if hole.format_id == "identity" and len(hole.declared_keys) == 1:+ segments.append("{" + hole.declared_keys[0] + "}")+ elif hole.format_id == "iso_date_to_year_month" and hole.declared_keys == transform.date_keys:+ date_holes += 1+ segments.append(+ "{" + _SAME_MONTH_HELPER_VAR + "(" + transform.date_keys[0] + ", " + transform.date_keys[1] + ")}"+ )+ else:+ return None+ cursor = hole.position + len(hole.matched_literal)+ if date_holes != 1 or set(transform.date_keys) - keys:+ return None+ segments.append(_escape_fstring_literal_segment(selector[cursor:]))+ return 'page.locator(f"' + "".join(segments) + '")'++def _locator_expr(interaction: Mapping[str, Any],notes: list[str],@@ -1359,6 +1456,7 @@ def synthesize_code_block(strict_selectors: bool = False,reached_download_target: ReachedDownloadTarget | None = None,parameter_binding_snapshot: AuthoringParameterBindingSnapshot | None = None,+ file_match_transform: SameMonthFileMatchTransform | None = None,) -> SynthesizedCodeBlock | None:"""Deterministically synthesize a code block from a scout trajectory, or None if empty."""if not trajectory:@@ -1394,6 +1492,40 @@ def synthesize_code_block(and not reached_download_target.already_registeredand bool(reached_download_target.selector))+ file_match_locator = ""+ file_match_keys: list[str] = []+ if file_match_transform is not None:+ if file_match_transform.provenance_fingerprint != same_month_file_match_transform_fingerprint(+ file_match_transform+ ):+ return None+ if not compile_download_target or reached_download_target is None:+ LOG.info(+ "copilot_spine_same_month_file_match_transform_dropped",+ reason_code="download_target_unavailable",+ selector_matches_transform=False,+ )+ file_match_transform = None+ else:+ file_match_locator = (+ build_same_month_file_match_locator(+ file_match_transform,+ reached_download_target.selector,+ )+ or ""+ )+ if not file_match_locator:+ LOG.info(+ "copilot_spine_same_month_file_match_transform_dropped",+ reason_code="locator_build_failed",+ selector_matches_transform=file_match_transform.selector == reached_download_target.selector,+ )+ file_match_transform = None+ if file_match_transform is not None:+ for file_match_hole in file_match_transform.holes:+ for key in file_match_hole.declared_keys:+ if key not in file_match_keys:+ file_match_keys.append(key)if compile_download_target and reached_download_target is not None:trajectory, dropped_trailing = _trajectory_prefix_at_anchor(trajectory, reached_download_target.trajectory_anchor@@ -1414,27 +1546,62 @@ def synthesize_code_block(plan = _input_templating_plan(interaction)if plan is None:continue- for hole in plan.holes:- key = str(hole.get("input_key") or "")+ for plan_hole in plan.holes:+ key = str(plan_hole.get("input_key") or "")if not key or key in minted_input_witness_keys:continueminted_input_witness_keys.add(key)- parameters.append(- {- "key": key,- "default_value": str(hole.get("parameter_value") or ""),- "source": LOCATOR_WITNESS_PARAM_SOURCE,- }- )+ parameter = {"key": key, "source": LOCATOR_WITNESS_PARAM_SOURCE}+ # A file-match witness proves usage, not a safe persisted default; the submitted declaration owns it.+ if key not in file_match_keys:+ parameter["default_value"] = str(plan_hole.get("parameter_value") or "")+ parameters.append(parameter)for key in input_templated_keys:used_param_keys.add(key)- if input_templated_keys:- lines.extend(witness_prelude_lines(input_templated_keys, include_month_helper=input_templated_needs_month))+ for key in file_match_keys:+ used_param_keys.add(key)+ if key not in minted_input_witness_keys:+ parameters.append({"key": key})+ prelude_keys = [*input_templated_keys, *(key for key in file_match_keys if key not in input_templated_keys)]+ if prelude_keys:+ lines.extend(witness_prelude_lines(prelude_keys, include_month_helper=input_templated_needs_month))LOG.info("copilot_spine_input_templated_prelude",- witness_keys=input_templated_keys,+ witness_keys=prelude_keys,month_helper=input_templated_needs_month,)+ if file_match_locator and file_match_transform is not None:+ lines.extend(_same_month_helper_lines())+ lines.append(f"{_INDENT}{_DOWNLOAD_TARGET_VAR} = {file_match_locator}")+ LOG.info(+ "copilot_spine_same_month_file_match_transform_applied",+ provenance_source=SAME_MONTH_FILE_MATCH_PROVENANCE_SOURCE,+ parameter_keys=list(file_match_transform.expected_declared_keys),+ )+ diagnostics.locator_provenance.append(+ {+ "trajectory_index": reached_download_target.trajectory_anchor+ if reached_download_target is not None and reached_download_target.trajectory_anchor is not None+ else -1,+ "selector": reached_download_target.selector if reached_download_target is not None else "",+ "emitted_literal": file_match_locator,+ "source": SAME_MONTH_FILE_MATCH_PROVENANCE_SOURCE,+ "date_keys": list(file_match_transform.date_keys),+ "expected_declared_keys": list(file_match_transform.expected_declared_keys),+ "provenance_fingerprint": file_match_transform.provenance_fingerprint,+ "date_format_id": file_match_transform.date_format_id,+ "holes": [+ {+ "declared_keys": list(hole.declared_keys),+ "matched_literal": hole.matched_literal,+ "position": hole.position,+ "format_id": hole.format_id,+ "source_values": list(hole.source_values),+ }+ for hole in file_match_transform.holes+ ],+ }+ )def append_step(description: str, action_type: str, line_start: int) -> None:steps.append(@@ -1501,7 +1668,9 @@ def synthesize_code_block(else 0)download_entry_target = (- f"page.locator({_py_str(reached_download_target.selector)})"+ _DOWNLOAD_TARGET_VAR+ if file_match_locator+ else f"page.locator({_py_str(reached_download_target.selector)})"if compile_download_target and reached_download_target is not Noneelse "")@@ -1985,7 +2154,12 @@ def synthesize_code_block(download_obj = _unique_key(f"{download_var}_file", used_download_vars)download_filename = _unique_key(_DOWNLOAD_FILENAME_VAR_BASE, used_download_vars)lines.append(f"{_INDENT}async with page.expect_download() as {download_var}:")- lines.append(f"{_INDENT * 2}await page.locator({_py_str(reached_download_target.selector)}).click()")+ download_click_target = (+ _DOWNLOAD_TARGET_VAR+ if file_match_locator+ else (f"page.locator({_py_str(reached_download_target.selector)})")+ )+ lines.append(f"{_INDENT * 2}await {download_click_target}.click()")lines.append(f"{_INDENT}{download_obj} = await {download_var}.value")lines.append(f"{_INDENT}{download_filename} = {download_obj}.suggested_filename")lines.append(f"{_INDENT}await {download_obj}.path()")@@ -2788,6 +2962,7 @@ def synthesize_code_block_with_extraction(strict_selectors: bool = False,reached_download_target: ReachedDownloadTarget | None = None,parameter_binding_snapshot: AuthoringParameterBindingSnapshot | None = None,+ file_match_transform: SameMonthFileMatchTransform | None = None,) -> SynthesizedCodeBlock | None:if not _trajectory_contains_reveal(trajectory, extraction_plan):return None@@ -2796,6 +2971,7 @@ def synthesize_code_block_with_extraction(strict_selectors=strict_selectors,reached_download_target=reached_download_target,parameter_binding_snapshot=parameter_binding_snapshot,+ file_match_transform=file_match_transform,)suffix = synthesize_extraction_suffix(extraction_plan)if interaction is None or suffix is None:diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 9efdad026..c20fbb8e7 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -34,10 +34,14 @@ from skyvern.forge.sdk.copilot.authoring_parameter_binding import (AuthoringParameterBindingTerminalTool,AuthoringParameterFieldBinding,AuthoringParameterTerminalBinding,+ SameMonthFileMatchFormat,+ SameMonthFileMatchHole,+ SameMonthFileMatchTransform,authored_selector_parameter_bindings,authoring_parameter_binding_directive_consumed,build_authoring_parameter_binding_directive,build_authoring_parameter_binding_snapshot,+ derive_same_month_file_match_transform,)from skyvern.forge.sdk.copilot.blocker_signal import (CREDENTIAL_SCOUT_VERIFY_REPLY,@@ -88,6 +92,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (CREDENTIAL_FILL_TOOL_NAME,INPUT_TEMPLATED_PROVENANCE_SOURCE,LOCATOR_WITNESS_PARAM_SOURCE,+ SAME_MONTH_FILE_MATCH_PROVENANCE_SOURCE,SCOUTED_SPINE_DROPPED_UNFORGIVEN_REASON_CODE,SCOUTED_SPINE_TRUNCATED_REASON_CODE,SCOUTED_SPINE_UNDER_BUILD_REASON_CODE,@@ -107,10 +112,12 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (artifact_dependency_id,artifact_observation_ref_id,build_input_templated_locator,+ build_same_month_file_match_locator,credential_scout_gap,freeze_requested_output_extraction_candidate,grounded_parameter_key_is_safe,input_correspondences_for_interaction,+ input_correspondences_for_selector,locator_selector_literals,missing_rung_text,normalized_locator_expr,@@ -2439,6 +2446,63 @@ class _AuthoringParameterBindingResolution(NamedTuple):directive: AuthoringParameterBindingDirective | None+def _same_month_file_match_transform(+ parsed: Mapping[str, Any],+ runtime_parameters: Mapping[str, Any] | None,+ *,+ candidate_keys: Sequence[str],+ selector: str,+) -> SameMonthFileMatchTransform | None:+ declared_keys = _declared_string_workflow_parameter_keys(parsed)+ if not set(candidate_keys).issubset(declared_keys):+ return None+ definition = parsed.get("workflow_definition")+ rows = definition.get("parameters") if isinstance(definition, Mapping) else None+ if not isinstance(rows, list):+ return None+ defaults = {+ str(row.get("key") or "").strip(): default+ for row in rows+ if isinstance(row, Mapping) and (default := _string_parameter_default_value(row)) is not None+ }+ supplied = runtime_parameters if isinstance(runtime_parameters, Mapping) else {}+ values: dict[str, str] = {}+ for key in candidate_keys:+ runtime_value = supplied.get(key)+ value = runtime_value if isinstance(runtime_value, str) else defaults.get(key)+ if isinstance(value, str):+ values[key] = value+ correspondences = input_correspondences_for_selector(selector, values)+ return derive_same_month_file_match_transform(+ selector=selector,+ parameter_values=values,+ identity_correspondences=correspondences,+ )+++def _runtime_declared_string_parameter_values(+ parsed: Mapping[str, Any], runtime_parameters: Mapping[str, Any] | None+) -> dict[str, str]:+ definition = parsed.get("workflow_definition")+ rows = definition.get("parameters") if isinstance(definition, Mapping) else None+ if not isinstance(rows, list):+ return {}+ declared_keys = _declared_string_workflow_parameter_keys(parsed)+ supplied = runtime_parameters if isinstance(runtime_parameters, Mapping) else {}+ values: dict[str, str] = {}+ for row in rows:+ if not isinstance(row, Mapping):+ continue+ key = str(row.get("key") or "").strip()+ if key not in declared_keys:+ continue+ runtime_value = supplied.get(key)+ value = runtime_value if isinstance(runtime_value, str) else _string_parameter_default_value(row)+ if isinstance(value, str):+ values[key] = value+ return values++class _SelectionBindingRecord(NamedTuple):declared_key: strmatch_basis: AuthoringParameterBindingMatchBasis@@ -8577,17 +8641,71 @@ def _locator_provenance_is_self_validating(provenance: Mapping[str, Any]) -> booreturn bool(role) and bool(name) and _get_by_role_expr_strict(role, name) == provenance.get("emitted_literal")if source == INPUT_TEMPLATED_PROVENANCE_SOURCE:surface = str(provenance.get("surface") or "")- holes = provenance.get("holes")- if not isinstance(holes, list) or not holes:+ input_holes = provenance.get("holes")+ if not isinstance(input_holes, list) or not input_holes:return Falserecomputed = build_input_templated_locator(surface=surface,selector=str(provenance.get("selector") or ""),role=str(provenance.get("role") or ""),name=str(provenance.get("name") or ""),- holes=holes,+ holes=input_holes,)return recomputed is not None and recomputed == provenance.get("emitted_literal")+ if source == SAME_MONTH_FILE_MATCH_PROVENANCE_SOURCE:+ raw_date_keys = provenance.get("date_keys")+ raw_expected_declared_keys = provenance.get("expected_declared_keys")+ raw_holes = provenance.get("holes")+ date_format_id = provenance.get("date_format_id")+ provenance_fingerprint = provenance.get("provenance_fingerprint")+ if (+ not isinstance(raw_date_keys, list)+ or len(raw_date_keys) != 2+ or any(not isinstance(key, str) for key in raw_date_keys)+ or not isinstance(raw_expected_declared_keys, list)+ or any(not isinstance(key, str) for key in raw_expected_declared_keys)+ or date_format_id != "iso_date_to_year_month"+ or not isinstance(provenance_fingerprint, str)+ or not isinstance(raw_holes, list)+ ):+ return False+ same_month_holes: list[SameMonthFileMatchHole] = []+ for raw_hole in raw_holes:+ if not isinstance(raw_hole, Mapping):+ return False+ declared_keys = raw_hole.get("declared_keys")+ matched_literal = raw_hole.get("matched_literal")+ position = raw_hole.get("position")+ format_id = raw_hole.get("format_id")+ source_values = raw_hole.get("source_values")+ if (+ not isinstance(declared_keys, list)+ or any(not isinstance(key, str) for key in declared_keys)+ or not isinstance(matched_literal, str)+ or not isinstance(position, int)+ or format_id not in {"identity", "iso_date_to_year_month"}+ or not isinstance(source_values, list)+ or any(not isinstance(value, str) for value in source_values)+ ):+ return False+ same_month_holes.append(+ SameMonthFileMatchHole(+ declared_keys=tuple(declared_keys),+ matched_literal=matched_literal,+ position=position,+ format_id=cast(SameMonthFileMatchFormat, format_id),+ source_values=tuple(source_values),+ )+ )+ transform = SameMonthFileMatchTransform(+ selector=str(provenance.get("selector") or ""),+ holes=tuple(same_month_holes),+ date_keys=(raw_date_keys[0], raw_date_keys[1]),+ expected_declared_keys=tuple(raw_expected_declared_keys),+ provenance_fingerprint=provenance_fingerprint,+ )+ recomputed = build_same_month_file_match_locator(transform, transform.selector)+ return recomputed is not None and recomputed == provenance.get("emitted_literal")return False@@ -11356,6 +11474,18 @@ def _maybe_impose_synthesized_code_block(else _AuthoringParameterBindingResolution(None, None))binding_snapshot = binding_resolution.snapshot+ file_match_transform = (+ _same_month_file_match_transform(+ parsed,+ runtime_parameters,+ candidate_keys=sorted(_declared_string_workflow_parameter_keys(parsed)),+ selector=ctx.reached_download_target.selector,+ )+ if ctx.reached_download_target is not None+ and not ctx.reached_download_target.already_registered+ and bool(ctx.reached_download_target.selector)+ else None+ )ctx.authoring_parameter_binding_snapshot = binding_snapshotif prior_directive is not None and binding_snapshot is None:return _SynthesizedCodeImpositionResult(@@ -11383,6 +11513,7 @@ def _maybe_impose_synthesized_code_block()grounding_repair_active = (binding_snapshot is None+ and file_match_transform is Noneand bool(declared_keys)and isinstance(requirement, RecordedOutcomeGroundingRequirement)and requirement.satisfied@@ -11394,7 +11525,16 @@ def _maybe_impose_synthesized_code_block(workflow_yaml=workflow_yaml,violations=["Unable to impose synthesized code block: current-page parameter binding is unresolved."],)- synthesis_trajectory: Sequence[Mapping[str, Any]] = scout_trajectory+ synthesis_values = _runtime_declared_string_parameter_values(parsed, runtime_parameters)+ synthesis_trajectory: list[Mapping[str, Any]] = []+ for interaction in scout_trajectory:+ enriched_interaction = dict(interaction)+ correspondences = input_correspondences_for_interaction(interaction, synthesis_values)+ if correspondences:+ enriched_interaction["input_correspondences"] = correspondences+ else:+ enriched_interaction.pop("input_correspondences", None)+ synthesis_trajectory.append(enriched_interaction)owns_spine = reaches_goalctx.spine_imposition_owned_attempt = owns_spine@@ -11420,6 +11560,7 @@ def _maybe_impose_synthesized_code_block(strict_selectors=True,reached_download_target=ctx.reached_download_target,parameter_binding_snapshot=binding_snapshot,+ file_match_transform=file_match_transform,)if extraction_plan is not Noneelse synthesize_code_block(@@ -11427,6 +11568,7 @@ def _maybe_impose_synthesized_code_block(strict_selectors=True,reached_download_target=ctx.reached_download_target,parameter_binding_snapshot=binding_snapshot,+ file_match_transform=file_match_transform,))if synthesized is None:diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.pyindex c477f560e..1dd9bdcad 100644--- a/tests/unit/test_copilot_code_block_persist_seam.py+++ b/tests/unit/test_copilot_code_block_persist_seam.py@@ -28,8 +28,10 @@ from skyvern.forge.sdk.copilot import enforcement as enforcement_modulefrom skyvern.forge.sdk.copilot import request_policy as request_policy_modulefrom skyvern.forge.sdk.copilot import tools as tools_modulefrom skyvern.forge.sdk.copilot.authoring_parameter_binding import (+ AuthoringParameterBindingCandidate,AuthoringParameterBindingDirective,authored_selector_parameter_bindings,+ build_authoring_parameter_binding_directive,)from skyvern.forge.sdk.copilot.blocker_signal import (CREDENTIAL_SCOUT_VERIFY_REPLY,@@ -523,6 +525,49 @@ def _definition_contract_ctx() -> CopilotContext:return ctx+def _same_month_file_match_case() -> tuple[CopilotContext, str, dict[str, str]]:+ ctx = _definition_contract_ctx()+ _enable_imposition(ctx)+ source_url = "https://example.com/statements"+ ctx.scout_trajectory = [+ {+ "tool_name": "click",+ "selector": "#statement-row",+ "source_url": source_url,+ "trajectory_index": 0,+ }+ ]+ ctx.reached_download_target = ReachedDownloadTarget(+ selector='a[href="/files/invoice_100245_2026-05.pdf"]',+ affordance_text="Download invoice",+ download_kind="attribute",+ source_step="trajectory_recency",+ already_registered=False,+ )+ submitted = _yaml(+ """+ title: Download reusable invoice+ workflow_definition:+ parameters:+ - {parameter_type: workflow, key: account_number, workflow_parameter_type: string, default_value: "stale-account"}+ - {parameter_type: workflow, key: download_start_date, workflow_parameter_type: string, default_value: "2026-06-01"}+ - {parameter_type: workflow, key: download_end_date, workflow_parameter_type: string, default_value: "2026-06-30"}+ blocks:+ - block_type: code+ label: download_invoice+ parameter_keys: []+ code: |+ await page.locator("#statement-row").click()+ """+ )+ values = {+ "account_number": "100245",+ "download_start_date": "2026-05-01",+ "download_end_date": "2026-05-31",+ }+ return ctx, submitted, values++@pytest.mark.parametrize("code",[@@ -1679,6 +1724,260 @@ class TestCodeRepairProgressClassification:assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is Noneassert ctx.authoring_parameter_binding_snapshot is not None+ def test_same_month_file_match_runtime_values_override_defaults_and_satisfy_definition(self) -> None:+ ctx = _definition_contract_ctx()+ _enable_imposition(ctx)+ source_url = "https://example.com/statements"+ ctx.scout_trajectory = [+ {+ "tool_name": "click",+ "selector": "#statement-row",+ "source_url": source_url,+ "trajectory_index": 0,+ }+ ]+ raw_selector = 'a[href="/files/invoice_100245_2026-05.pdf"]'+ ctx.reached_download_target = ReachedDownloadTarget(+ selector=raw_selector,+ affordance_text="Download invoice",+ download_kind="attribute",+ source_step="trajectory_recency",+ already_registered=False,+ )+ submitted = _yaml(+ """+ title: Download reusable invoice+ workflow_definition:+ parameters:+ - {parameter_type: workflow, key: account_number, workflow_parameter_type: string, default_value: "stale-account"}+ - {parameter_type: workflow, key: download_start_date, workflow_parameter_type: string, default_value: "2026-06-01"}+ - {parameter_type: workflow, key: download_end_date, workflow_parameter_type: string, default_value: "2026-06-30"}+ blocks:+ - block_type: code+ label: download_invoice+ parameter_keys: []+ code: |+ await page.locator("#statement-row").click()+ """+ )++ result = workflow_update_module._maybe_impose_synthesized_code_block(+ submitted,+ ctx,+ runtime_parameters={+ "account_number": "100245",+ "download_start_date": "2026-05-01",+ "download_end_date": "2026-05-31",+ },+ )++ assert result.violations == []+ parsed = parse_workflow_yaml(result.workflow_yaml)+ assert isinstance(parsed, dict)+ block = _single_code_block(parsed)+ code = str(block["code"])+ assert set(block["parameter_keys"]) == {+ "account_number",+ "download_start_date",+ "download_end_date",+ }+ assert code.count("_scout_download_target = page.locator(") == 1+ assert "_scout_entry_target = _scout_download_target" in code+ assert "await _scout_download_target.click()" in code+ assert "100245" not in code+ assert "2026-05" not in code+ assert workflow_update_module._definition_plane_preflight_reject(ctx, result.workflow_yaml) is None+ assert ctx.authoring_parameter_binding_snapshot is None++ def test_same_month_file_match_rebinds_account_already_referenced_by_navigation(self) -> None:+ ctx, _, values = _same_month_file_match_case()+ source_url = "https://example.com/statements"+ ctx.scout_trajectory = [+ {+ "tool_name": "click",+ "selector": '[data-account="100245"]',+ "source_url": source_url,+ "trajectory_index": 0,+ }+ ]+ submitted = _yaml(+ """+ title: Download reusable invoice+ workflow_definition:+ parameters:+ - {parameter_type: workflow, key: account_number, workflow_parameter_type: string, default_value: "stale-account"}+ - {parameter_type: workflow, key: download_start_date, workflow_parameter_type: string, default_value: "2026-06-01"}+ - {parameter_type: workflow, key: download_end_date, workflow_parameter_type: string, default_value: "2026-06-30"}+ blocks:+ - block_type: code+ label: download_invoice+ parameter_keys: [account_number]+ code: |+ await page.locator(f'[data-account="{account_number}"]').click()+ """+ )++ result = workflow_update_module._maybe_impose_synthesized_code_block(+ submitted,+ ctx,+ runtime_parameters=values,+ )++ assert result.violations == []+ parsed = parse_workflow_yaml(result.workflow_yaml)+ assert isinstance(parsed, dict)+ block = _single_code_block(parsed)+ code = str(block["code"])+ assert set(block["parameter_keys"]) == set(values)+ assert 'f"[data-account=\\"{account_number}\\"]"' in code+ assert 'f"a[href=\\"/files/invoice_{account_number}_{_scout_same_month_iso(' in code+ assert "100245" not in code+ assert "2026-05" not in code+ synthesized = ctx.imposition_synthesized_block+ assert synthesized is not None+ assert {parameter["key"] for parameter in synthesized.parameters} == set(values)+ assert all("default_value" not in parameter for parameter in synthesized.parameters)+ assert workflow_update_module._definition_plane_preflight_reject(ctx, result.workflow_yaml) is None+ assert (+ workflow_update_module._metadata_contract_run_preflight_reject(+ ctx,+ result.workflow_yaml,+ ctx.raw_code_artifact_metadata,+ values,+ )+ is None+ )++ def test_same_month_file_match_rebinds_literal_when_other_block_references_all_keys(self) -> None:+ ctx, _, values = _same_month_file_match_case()+ submitted = _yaml(+ """+ title: Download reusable invoice+ workflow_definition:+ parameters:+ - {parameter_type: workflow, key: account_number, workflow_parameter_type: string, default_value: "100245"}+ - {parameter_type: workflow, key: download_start_date, workflow_parameter_type: string, default_value: "2026-05-01"}+ - {parameter_type: workflow, key: download_end_date, workflow_parameter_type: string, default_value: "2026-05-31"}+ blocks:+ - block_type: text_prompt+ label: prepare_invoice_request+ parameter_keys: [account_number, download_start_date, download_end_date]+ prompt: "Inputs: {{ parameters.account_number }}, {{ parameters.download_start_date }}, {{ parameters.download_end_date }}"+ - block_type: code+ label: download_invoice+ parameter_keys: []+ code: |+ await page.locator("#statement-row").click()+ await page.locator('a[href="/files/invoice_100245_2026-05.pdf"]').click()+ """+ )+ assert workflow_update_module._definition_plane_preflight_reject(ctx, submitted) is None++ with capture_logs() as logs:+ result = workflow_update_module._maybe_impose_synthesized_code_block(+ submitted,+ ctx,+ runtime_parameters=values,+ )++ assert result.violations == []+ parsed = parse_workflow_yaml(result.workflow_yaml)+ assert isinstance(parsed, dict)+ code = str(_single_code_block(parsed)["code"])+ assert "100245" not in code+ assert "2026-05" not in code+ assert any(+ log.get("event") == "copilot_spine_same_month_file_match_transform_applied"+ and log.get("provenance_source") == "same_month_file_match"+ for log in logs+ )++ def test_same_month_file_match_rejects_stale_pending_directive_before_persistence(self) -> None:+ ctx, submitted, values = _same_month_file_match_case()+ keys = tuple(values)+ directive = build_authoring_parameter_binding_directive(+ structural_key="stale-structural-key",+ source_origin="https://example.com",+ candidates=[AuthoringParameterBindingCandidate(declared_key="account_number", field_selector="#account")],+ )+ ctx.last_code_authoring_repair_context = CodeAuthoringRepairContext(+ block_label="download_invoice",+ reason_code="synthesized_parameter_binding_ambiguous",+ unresolved_names=list(keys),+ parameter_keys=list(keys),+ parameter_binding_directive=directive,+ )++ result = workflow_update_module._maybe_impose_synthesized_code_block(+ submitted,+ ctx,+ runtime_parameters=values,+ )++ assert result.workflow_yaml == submitted+ assert result.violations == [+ "Unable to impose synthesized code block: stored parameter binding directive is stale."+ ]+ assert result.repair_context is ctx.last_code_authoring_repair_context++ def test_same_month_file_match_persistence_provenance_rejects_missing_identity_hole(self) -> None:+ ctx, submitted, values = _same_month_file_match_case()+ result = workflow_update_module._maybe_impose_synthesized_code_block(+ submitted,+ ctx,+ runtime_parameters=values,+ )+ assert result.violations == []+ synthesized = ctx.imposition_synthesized_block+ assert synthesized is not None+ provenance = next(+ record+ for record in synthesized.diagnostics.locator_provenance+ if record.get("source") == code_block_synthesis_module.SAME_MONTH_FILE_MATCH_PROVENANCE_SOURCE+ )+ tampered = dict(provenance)+ tampered["holes"] = [hole for hole in provenance["holes"] if hole["format_id"] != "identity"]++ assert workflow_update_module._locator_provenance_is_self_validating(provenance)+ assert not workflow_update_module._locator_provenance_is_self_validating(tampered)++ def test_same_month_file_match_rejects_ambiguous_fresh_directive_before_persistence(self) -> None:+ ctx, submitted, values = _same_month_file_match_case()+ source_url = "https://example.com/statements"+ ctx.scout_trajectory.append(+ {+ "tool_name": "click",+ "selector": "#submit",+ "source_url": source_url,+ "trajectory_index": 1,+ }+ )+ ctx.composition_page_evidence = {+ "source_tool": "inspect_page_for_composition",+ "current_url": source_url,+ "forms": [+ {+ "fields": [{"selector": "#account", "value": values["account_number"]}],+ "submit_controls": [{"selector": "#submit"}],+ }+ ],+ }++ result = workflow_update_module._maybe_impose_synthesized_code_block(+ submitted,+ ctx,+ runtime_parameters=values,+ )++ assert result.workflow_yaml == submitted+ assert result.violations == [+ "Unable to impose synthesized code block: current-page parameter binding is ambiguous."+ ]+ assert result.repair_context is not None+ assert result.repair_context.reason_code == "synthesized_parameter_binding_ambiguous"+ assert result.repair_context.parameter_binding_directive is not None+ assert result.repair_context.parameter_binding_directive.source_origin == "https://example.com"+def test_selection_resolution_binds_witnessed_click_value(self) -> None:ctx = SimpleNamespace(scout_trajectory=[diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.pyindex fa664ce82..673932775 100644--- a/tests/unit/test_copilot_code_block_synthesis.py+++ b/tests/unit/test_copilot_code_block_synthesis.py@@ -11,10 +11,12 @@ import jsonimport keywordimport sysimport textwrap+from dataclasses import replacefrom types import ModuleType, SimpleNamespacefrom typing import Anyimport pytest+from structlog.testing import capture_logsfrom skyvern.forge.sdk.copilot.authoring_parameter_binding import (_SELECTION_MATCH_BASES,@@ -26,6 +28,8 @@ from skyvern.forge.sdk.copilot.authoring_parameter_binding import (authoring_parameter_binding_directive_consumed,build_authoring_parameter_binding_directive,build_authoring_parameter_binding_snapshot,+ derive_same_month_file_match_transform,+ same_month_file_match_transform_fingerprint,)from skyvern.forge.sdk.copilot.code_block_preflight import preflight_code_blockfrom skyvern.forge.sdk.copilot.code_block_security import author_time_code_security_errors@@ -80,9 +84,11 @@ from skyvern.forge.sdk.copilot.output_extraction_plan import (RevealAnchor,)from skyvern.forge.sdk.copilot.reached_download_target import ReachedDownloadTarget+from skyvern.forge.sdk.copilot.run_outcome import run_outcome_display_reasonfrom skyvern.forge.sdk.copilot.tools import _normalize_code_artifact_metadatafrom skyvern.forge.sdk.copilot.tools.scouting import _fill_carry_to_interaction, _with_trajectory_anchorfrom skyvern.forge.sdk.copilot.tools.workflow_update import _code_block_safety_errors+from skyvern.forge.sdk.workflow.exceptions import CustomizedCodeExceptionfrom skyvern.forge.sdk.workflow.models.block import CodeBlock, CodeBlockStep@@ -3127,6 +3133,358 @@ class TestDownloadRungSynthesis:assert "expect_download" not in result.code+_SAME_MONTH_SELECTOR = 'a[href="/files/invoice_100245_2026-05.pdf"]'+_SAME_MONTH_VALUES = {+ "account_number": "100245",+ "download_start_date": "2026-05-01",+ "download_end_date": "2026-05-31",+}+++def _same_month_file_match_transform(*, selector: str = _SAME_MONTH_SELECTOR, values: dict[str, str] | None = None):+ parameter_values = values or _SAME_MONTH_VALUES+ correspondences = input_correspondences_for_interaction(+ {"tool_name": "click", "selector": selector}, parameter_values+ )+ return derive_same_month_file_match_transform(+ selector=selector,+ parameter_values=parameter_values,+ identity_correspondences=correspondences,+ )+++def test_same_month_file_match_admits_one_complete_relation() -> None:+ transform = _same_month_file_match_transform()++ assert transform is not None+ assert transform.selector == _SAME_MONTH_SELECTOR+ assert transform.date_format_id == "iso_date_to_year_month"+ assert [hole.declared_keys for hole in transform.holes] == [+ ("account_number",),+ ("download_start_date", "download_end_date"),+ ]+ assert [hole.matched_literal for hole in transform.holes] == ["100245", "2026-05"]+++ ("selector", "values"),+ [+ (+ _SAME_MONTH_SELECTOR,+ {**_SAME_MONTH_VALUES, "download_end_date": "2026-06-01"},+ ),+ (+ _SAME_MONTH_SELECTOR,+ {**_SAME_MONTH_VALUES, "download_start_date": "2026-02-30"},+ ),+ (+ _SAME_MONTH_SELECTOR,+ {key: value for key, value in _SAME_MONTH_VALUES.items() if key != "download_end_date"},+ ),+ (+ 'a[href="/files/invoice_100245.pdf"]',+ _SAME_MONTH_VALUES,+ ),+ (+ 'a[href="/files/invoice_100245_2026-05_2026-05.pdf"]',+ _SAME_MONTH_VALUES,+ ),+ (+ 'a[href="/files/invoice_100245_2026-05_2026-06.pdf"]',+ {+ "account_number": "100245",+ "first_start": "2026-05-01",+ "first_end": "2026-05-31",+ "second_start": "2026-06-01",+ "second_end": "2026-06-30",+ },+ ),+ ],+ ids=[+ "cross-month",+ "invalid-calendar-date",+ "missing-date",+ "absent-month-token",+ "repeated-month-token",+ "competing-date-pairs",+ ],+)+def test_same_month_file_match_rejects_inadmissible_relations(selector: str, values: dict[str, str]) -> None:+ assert _same_month_file_match_transform(selector=selector, values=values) is None+++def test_same_month_file_match_ignores_declared_keys_without_a_literal_witness() -> None:+ transform = _same_month_file_match_transform(values={**_SAME_MONTH_VALUES, "region": "west"})++ assert transform is not None+ assert transform.expected_declared_keys == tuple(sorted(_SAME_MONTH_VALUES))+ assert {key for hole in transform.holes for key in hole.declared_keys} == set(_SAME_MONTH_VALUES)+++def test_same_month_file_match_reuses_one_stable_download_locator() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None++ result = synthesize_code_block(+ [_nav_click()],+ reached_download_target=_download_target(selector=_SAME_MONTH_SELECTOR),+ file_match_transform=transform,+ )++ assert result is not None+ assert result.code.count("_scout_download_target = page.locator(") == 1+ assert "_scout_entry_target = _scout_download_target" in result.code+ assert "await _scout_download_target.click()" in result.code+ assert "100245" not in result.code+ assert "2026-05" not in result.code+ assert "account_number" in result.code+ assert "download_start_date" in result.code+ assert "download_end_date" in result.code+ assert {parameter["key"] for parameter in result.parameters} == set(_SAME_MONTH_VALUES)+ CodeBlock.is_safe_code(+ "async def _block(page, account_number, download_start_date, download_end_date):\n" + result.code+ )+++def test_same_month_file_match_selector_drift_preserves_literal_fallback() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ drifted_target = _download_target(selector='a[href="/files/invoice_literal_fallback.pdf"]')+ baseline = synthesize_code_block([_nav_click()], reached_download_target=drifted_target)++ with capture_logs() as logs:+ result = synthesize_code_block(+ [_nav_click()],+ reached_download_target=drifted_target,+ file_match_transform=transform,+ )++ assert baseline is not None and result is not None+ assert result.code == baseline.code+ assert result.parameters == baseline.parameters+ assert {+ "event": "copilot_spine_same_month_file_match_transform_dropped",+ "reason_code": "locator_build_failed",+ "selector_matches_transform": False,+ "log_level": "info",+ } in logs+++def test_same_month_file_match_extraction_consumer_reuses_stable_download_locator() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ result = synthesize_code_block_with_extraction(+ [_interaction("click", selector="#show-details", source_url=_BILLS_URL)],+ _extraction_plan(),+ reached_download_target=_download_target(selector=_SAME_MONTH_SELECTOR),+ file_match_transform=transform,+ )++ assert result is not None+ assert result.interaction_code.count("_scout_download_target = page.locator(") == 1+ assert "_scout_entry_target = _scout_download_target" in result.interaction_code+ assert "await _scout_download_target.click()" in result.interaction_code+++def test_same_month_file_match_tampered_span_fails_synthesis_validation() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ first_hole = transform.holes[0]+ tampered = replace(+ transform,+ holes=(replace(first_hole, position=first_hole.position + 1), *transform.holes[1:]),+ )++ assert (+ synthesize_code_block(+ [_nav_click()],+ reached_download_target=_download_target(selector=_SAME_MONTH_SELECTOR),+ file_match_transform=tampered,+ )+ is None+ )+++def test_same_month_file_match_direct_synthesis_falls_back_for_missing_identity_hole() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ missing_identity = replace(transform, holes=tuple(hole for hole in transform.holes if hole.format_id != "identity"))+ missing_identity = replace(+ missing_identity,+ provenance_fingerprint=same_month_file_match_transform_fingerprint(missing_identity),+ )++ target = _download_target(selector=_SAME_MONTH_SELECTOR)+ baseline = synthesize_code_block([_nav_click()], reached_download_target=target)+ result = synthesize_code_block(+ [_nav_click()],+ reached_download_target=target,+ file_match_transform=missing_identity,+ )++ assert baseline is not None and result is not None+ assert result.code == baseline.code+++def test_same_month_file_match_extraction_synthesis_falls_back_for_missing_identity_hole() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ missing_identity = replace(transform, holes=tuple(hole for hole in transform.holes if hole.format_id != "identity"))+ missing_identity = replace(+ missing_identity,+ provenance_fingerprint=same_month_file_match_transform_fingerprint(missing_identity),+ )++ trajectory = [_interaction("click", selector="#show-details", source_url=_BILLS_URL)]+ target = _download_target(selector=_SAME_MONTH_SELECTOR)+ baseline = synthesize_code_block_with_extraction(trajectory, _extraction_plan(), reached_download_target=target)+ result = synthesize_code_block_with_extraction(+ trajectory,+ _extraction_plan(),+ reached_download_target=target,+ file_match_transform=missing_identity,+ )++ assert baseline is not None and result is not None+ assert result.interaction_code == baseline.interaction_code+++def test_same_month_file_match_falls_back_for_refingerprinted_identity_provenance_tamper() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ identity_hole = transform.holes[0]+ tampered = replace(+ transform,+ holes=(replace(identity_hole, source_values=("different-account",)), *transform.holes[1:]),+ )+ tampered = replace(tampered, provenance_fingerprint=same_month_file_match_transform_fingerprint(tampered))++ target = _download_target(selector=_SAME_MONTH_SELECTOR)+ baseline = synthesize_code_block([_nav_click()], reached_download_target=target)+ result = synthesize_code_block(+ [_nav_click()],+ reached_download_target=target,+ file_match_transform=tampered,+ )++ assert baseline is not None and result is not None+ assert result.code == baseline.code+++ ("start", "end"),+ [+ ("2026-02-30", "2026-02-28"),+ ("2026-05-01", "2026-06-01"),+ ("2026/05/01", "2026-05-31"),+ ],+)+def test_same_month_file_match_runtime_dates_fail_before_locator_construction(start: str, end: str) -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ result = synthesize_code_block(+ [_nav_click()],+ reached_download_target=_download_target(selector=_SAME_MONTH_SELECTOR),+ file_match_transform=transform,+ )+ assert result is not None+ prefix = result.code.split(" _scout_entry_target =", 1)[0]++ class _Page:+ def __init__(self) -> None:+ self.locators: list[str] = []++ def locator(self, selector: str) -> str:+ self.locators.append(selector)+ return selector++ namespace: dict[str, Any] = {"Exception": Exception}+ exec(+ "def _build(page, account_number, download_start_date, download_end_date):\n"+ + prefix+ + " return _scout_download_target\n",+ namespace,+ )+ page = _Page()+ with pytest.raises(Exception):+ namespace["_build"](page, "100248", start, end)+ assert page.locators == []+++def test_same_month_file_match_cross_month_error_remains_operator_visible() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ result = synthesize_code_block(+ [_nav_click()],+ reached_download_target=_download_target(selector=_SAME_MONTH_SELECTOR),+ file_match_transform=transform,+ )+ assert result is not None+ prefix = result.code.split(" _scout_entry_target =", 1)[0]++ class _Page:+ def locator(self, selector: str) -> str:+ return selector++ namespace: dict[str, Any] = {"Exception": Exception}+ exec(+ "def _build(page, account_number, download_start_date, download_end_date):\n"+ + prefix+ + " return _scout_download_target\n",+ namespace,+ )+ with pytest.raises(Exception) as raised:+ namespace["_build"](_Page(), "100248", "2024-02-01", "2024-03-01")++ failure_reason = CustomizedCodeException(raised.value).message+ assert run_outcome_display_reason(failure_reason) == (+ "Failed to execute code block. Reason: Exception: grounded file match dates must share one calendar month"+ )+++def test_same_month_file_match_runtime_formats_calendar_valid_leap_month() -> None:+ transform = _same_month_file_match_transform()+ assert transform is not None+ result = synthesize_code_block(+ [_nav_click()],+ reached_download_target=_download_target(selector=_SAME_MONTH_SELECTOR),+ file_match_transform=transform,+ )+ assert result is not None+ prefix = result.code.split(" _scout_entry_target =", 1)[0]++ class _Page:+ def __init__(self) -> None:+ self.locators: list[str] = []++ def locator(self, selector: str) -> str:+ self.locators.append(selector)+ return selector++ namespace: dict[str, Any] = {"Exception": Exception}+ exec(+ "def _build(page, account_number, download_start_date, download_end_date):\n"+ + prefix+ + " return _scout_download_target\n",+ namespace,+ )+ page = _Page()+ assert namespace["_build"](page, "100248", "2024-02-01", "2024-02-29") == (+ 'a[href="/files/invoice_100248_2024-02.pdf"]'+ )+ assert page.locators == ['a[href="/files/invoice_100248_2024-02.pdf"]']+++def test_download_target_literal_fallback_is_byte_identical_without_transform() -> None:+ target = _download_target(selector=_SAME_MONTH_SELECTOR)+ baseline = synthesize_code_block([_nav_click()], reached_download_target=target)+ explicit_none = synthesize_code_block([_nav_click()], reached_download_target=target, file_match_transform=None)++ assert baseline is not None and explicit_none is not None+ assert explicit_none.code == baseline.code+ assert explicit_none.parameters == baseline.parameters++def _readonly_type(**overrides: Any) -> dict[str, Any]:base = _interaction("type_text",