Skip to content

Automate browser based workflows with AI

SKY-12548: Copilot: carry a typed binding directive across author-time declared-input rejects so the next attempt converges (#7564)

Andrew Neilson290b16c8828c
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 2290104a2..3090a2ee4 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -848,6 +848,13 @@ def _code_authoring_repair_context_prompt(ctx: CopilotContext | None) -> str:
"list the exact key in the code block's parameter_keys, reference the exact key as a bare Python "
"variable in code, do not hardcode the eval value, and rerun via update_and_run_blocks."
)
+ if repair_context.parameter_binding_directive is not None:
+ lines.append("parameter_binding_pairs:")
+ for candidate in repair_context.parameter_binding_directive.candidates:
+ key = _clean_authoring_repair_prompt_atom(candidate.declared_key, max_chars=80)
+ selector = _clean_authoring_repair_prompt_atom(candidate.field_selector, max_chars=160)
+ if key and selector:
+ lines.append(f"- {key} -> {selector}")
if repair_context.reason_code == "synthesized_parameter_binding_ambiguous":
binding_action_lines = _render_unresolved_name_binding_actions(
repair_context.unresolved_names, available_parameter_keys
diff --git a/skyvern/forge/sdk/copilot/authoring_parameter_binding.py b/skyvern/forge/sdk/copilot/authoring_parameter_binding.py
new file mode 100644
index 000000000..e863cd572
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/authoring_parameter_binding.py
@@ -0,0 +1,200 @@
+from __future__ import annotations
+
+import ast
+import hashlib
+import json
+from collections.abc import Sequence
+from typing import Literal
+
+from pydantic import BaseModel, ConfigDict, Field
+
+AuthoringParameterBindingMatchBasis = Literal[
+ "exact_authored_selector",
+ "grounded_input_correspondence",
+ "unique_ephemeral_value",
+]
+AuthoringParameterBindingTerminalTool = Literal["click", "press_key"]
+
+
+class AuthoringParameterFieldBinding(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ declared_key: str
+ field_selector: str
+ field_trajectory_index: int | None = Field(default=None, ge=0)
+ match_basis: AuthoringParameterBindingMatchBasis
+
+
+class AuthoringParameterTerminalBinding(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ tool_name: AuthoringParameterBindingTerminalTool
+ trajectory_index: int = Field(ge=0)
+ selector: str = ""
+ key: str = ""
+
+
+class AuthoringParameterBindingSnapshot(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ structural_key: str
+ source_origin: str
+ field_bindings: tuple[AuthoringParameterFieldBinding, ...]
+ terminal: AuthoringParameterTerminalBinding
+ fingerprint: str
+
+
+class AuthoringParameterBindingCandidate(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ declared_key: str
+ field_selector: str
+
+
+class AuthoringParameterBindingDirective(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ structural_key: str
+ source_origin: str
+ candidates: tuple[AuthoringParameterBindingCandidate, ...]
+ fingerprint: str
+
+
+def authoring_parameter_binding_fingerprint(
+ *,
+ structural_key: str,
+ source_origin: str,
+ field_bindings: Sequence[AuthoringParameterFieldBinding],
+ terminal: AuthoringParameterTerminalBinding,
+) -> str:
+ payload = {
+ "structural_key": structural_key,
+ "source_origin": source_origin,
+ "field_bindings": [
+ {
+ "declared_key": binding.declared_key,
+ "field_selector": binding.field_selector,
+ "field_trajectory_index": binding.field_trajectory_index,
+ "match_basis": binding.match_basis,
+ }
+ for binding in field_bindings
+ ],
+ "terminal": terminal.model_dump(mode="json"),
+ }
+ return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+
+
+def build_authoring_parameter_binding_snapshot(
+ *,
+ structural_key: str,
+ source_origin: str,
+ field_bindings: Sequence[AuthoringParameterFieldBinding],
+ terminal: AuthoringParameterTerminalBinding,
+) -> AuthoringParameterBindingSnapshot:
+ ordered = tuple(sorted(field_bindings, key=lambda binding: binding.declared_key))
+ return AuthoringParameterBindingSnapshot(
+ structural_key=structural_key,
+ source_origin=source_origin,
+ field_bindings=ordered,
+ terminal=terminal,
+ fingerprint=authoring_parameter_binding_fingerprint(
+ structural_key=structural_key,
+ source_origin=source_origin,
+ field_bindings=ordered,
+ terminal=terminal,
+ ),
+ )
+
+
+def build_authoring_parameter_binding_directive(
+ *,
+ structural_key: str,
+ source_origin: str,
+ candidates: Sequence[AuthoringParameterBindingCandidate],
+) -> AuthoringParameterBindingDirective:
+ unique = {(candidate.declared_key, candidate.field_selector): candidate for candidate in candidates}
+ ordered = tuple(unique[key] for key in sorted(unique))
+ payload = {
+ "structural_key": structural_key,
+ "source_origin": source_origin,
+ "candidates": [candidate.model_dump(mode="json") for candidate in ordered],
+ }
+ fingerprint = hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+ return AuthoringParameterBindingDirective(
+ structural_key=structural_key,
+ source_origin=source_origin,
+ candidates=ordered,
+ fingerprint=fingerprint,
+ )
+
+
+def _literal_locator_selector(node: ast.AST) -> str:
+ if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute) or node.func.attr != "locator":
+ return ""
+ if not isinstance(node.func.value, ast.Name) or node.func.value.id != "page" or len(node.args) != 1:
+ return ""
+ argument = node.args[0]
+ return argument.value if isinstance(argument, ast.Constant) and isinstance(argument.value, str) else ""
+
+
+def _fill_parameter_key(node: ast.Call) -> str:
+ if not node.args:
+ return ""
+ argument = node.args[0]
+ if isinstance(argument, ast.Name):
+ return argument.id
+ if (
+ isinstance(argument, ast.Call)
+ and isinstance(argument.func, ast.Name)
+ and argument.func.id == "str"
+ and len(argument.args) == 1
+ and isinstance(argument.args[0], ast.Name)
+ ):
+ return argument.args[0].id
+ return ""
+
+
+def authored_selector_parameter_bindings(code: str, declared_keys: set[str]) -> dict[str, set[str]] | None:
+ try:
+ tree = ast.parse(code)
+ except SyntaxError:
+ return None
+ bindings: dict[str, set[str]] = {}
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call) or not isinstance(node.func, ast.Attribute):
+ continue
+ if node.func.attr not in {"fill", "type"}:
+ continue
+ selector = _literal_locator_selector(node.func.value)
+ parameter_key = _fill_parameter_key(node)
+ if selector and parameter_key in declared_keys:
+ bindings.setdefault(selector, set()).add(parameter_key)
+ return bindings
+
+
+def authoring_parameter_binding_directive_consumed(
+ directive: AuthoringParameterBindingDirective,
+ snapshot: AuthoringParameterBindingSnapshot,
+ *,
+ code: str,
+ parameter_keys: Sequence[str],
+) -> bool:
+ if directive.structural_key != snapshot.structural_key or directive.source_origin != snapshot.source_origin:
+ return False
+ snapshot_pairs = {(binding.declared_key, binding.field_selector) for binding in snapshot.field_bindings}
+ directive_pairs = {(candidate.declared_key, candidate.field_selector) for candidate in directive.candidates}
+ if not directive_pairs or not snapshot_pairs.issubset(directive_pairs):
+ return False
+ if {candidate.declared_key for candidate in directive.candidates} != {
+ binding.declared_key for binding in snapshot.field_bindings
+ }:
+ return False
+ declared_keys = {binding.declared_key for binding in snapshot.field_bindings}
+ if not declared_keys.issubset(parameter_keys):
+ return False
+ authored = authored_selector_parameter_bindings(code, declared_keys)
+ if authored is None:
+ return False
+ return all(
+ binding.declared_key in authored.get(binding.field_selector, set()) for binding in snapshot.field_bindings
+ )
diff --git a/skyvern/forge/sdk/copilot/code_block_synthesis.py b/skyvern/forge/sdk/copilot/code_block_synthesis.py
index b8e01f685..2fc393a04 100644
--- a/skyvern/forge/sdk/copilot/code_block_synthesis.py
+++ b/skyvern/forge/sdk/copilot/code_block_synthesis.py
@@ -24,6 +24,10 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
import structlog
+from skyvern.forge.sdk.copilot.authoring_parameter_binding import (
+ AuthoringParameterBindingSnapshot,
+ authoring_parameter_binding_fingerprint,
+)
from skyvern.forge.sdk.copilot.composition_evidence import SCOUT_INTERACTION_EVIDENCE_TOOL
from skyvern.forge.sdk.copilot.output_extraction_plan import (
FrozenRequestedOutputExtractionCandidate,
@@ -349,6 +353,79 @@ def grounded_submit_rung_binding_fingerprint(
return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
+def _binding_source_origin(source_url: str) -> str:
+ parsed = urlsplit(source_url)
+ return f"{parsed.scheme}://{parsed.netloc}" if parsed.scheme and parsed.netloc else ""
+
+
+def _captured_trajectory_index(interaction: Mapping[str, Any], position: int) -> int:
+ raw_index = interaction.get("trajectory_index")
+ return raw_index if isinstance(raw_index, int) and raw_index >= 0 else position
+
+
+def _validated_authoring_parameter_binding_snapshot(
+ snapshot: AuthoringParameterBindingSnapshot,
+ trajectory: Sequence[Mapping[str, Any]],
+) -> dict[int, tuple[str, str]] | None:
+ if not snapshot.field_bindings:
+ return None
+ terminal_matches = [
+ (position, interaction)
+ for position, interaction in enumerate(trajectory)
+ if _captured_trajectory_index(interaction, position) == snapshot.terminal.trajectory_index
+ ]
+ if len(terminal_matches) != 1:
+ return None
+ _terminal_position, terminal = terminal_matches[0]
+ if _binding_source_origin(str(terminal.get("source_url") or "")) != snapshot.source_origin:
+ return None
+ if str(terminal.get("tool_name") or "") != snapshot.terminal.tool_name:
+ return None
+ if str(terminal.get("selector") or "").strip() != snapshot.terminal.selector:
+ return None
+ if str(terminal.get("key") or "").strip() != snapshot.terminal.key:
+ return None
+ expected = authoring_parameter_binding_fingerprint(
+ structural_key=snapshot.structural_key,
+ source_origin=snapshot.source_origin,
+ field_bindings=snapshot.field_bindings,
+ terminal=snapshot.terminal,
+ )
+ if expected != snapshot.fingerprint:
+ return None
+ by_index: dict[int, tuple[str, str]] = {}
+ declared_keys: set[str] = set()
+ selectors: set[str] = set()
+ for binding in snapshot.field_bindings:
+ if (
+ not grounded_parameter_key_is_safe(binding.declared_key)
+ or not binding.field_selector
+ or binding.declared_key in declared_keys
+ or binding.field_selector in selectors
+ ):
+ return None
+ declared_keys.add(binding.declared_key)
+ selectors.add(binding.field_selector)
+ if binding.field_trajectory_index is None:
+ continue
+ field_matches = [
+ (position, interaction)
+ for position, interaction in enumerate(trajectory)
+ if _captured_trajectory_index(interaction, position) == binding.field_trajectory_index
+ ]
+ if len(field_matches) != 1:
+ return None
+ field_position, interaction = field_matches[0]
+ if _binding_source_origin(str(interaction.get("source_url") or "")) != snapshot.source_origin:
+ return None
+ if str(interaction.get("tool_name") or "") != "type_text":
+ return None
+ if str(interaction.get("selector") or "").strip() != binding.field_selector:
+ return None
+ by_index[field_position] = (binding.declared_key, binding.field_selector)
+ return by_index
+
+
def _validated_submit_rung_binding(
interaction: Mapping[str, Any], trajectory_index: int
) -> tuple[str, tuple[tuple[str, str], ...]] | None:
@@ -1298,6 +1375,7 @@ def synthesize_code_block(
*,
strict_selectors: bool = False,
reached_download_target: ReachedDownloadTarget | None = None,
+ parameter_binding_snapshot: AuthoringParameterBindingSnapshot | None = None,
) -> SynthesizedCodeBlock | None:
"""Deterministically synthesize a code block from a scout trajectory, or None if empty."""
if not trajectory:
@@ -1313,8 +1391,21 @@ def synthesize_code_block(
credential_param_keys: dict[str, str] = {}
used_download_vars: set[str] = set()
grounded_binding_count = sum(1 for interaction in trajectory if "submit_rung_binding" in interaction)
- if grounded_binding_count > 1:
+ if grounded_binding_count > 1 or (grounded_binding_count and parameter_binding_snapshot is not None):
+ return None
+ snapshot_bindings_by_index = (
+ _validated_authoring_parameter_binding_snapshot(parameter_binding_snapshot, trajectory)
+ if parameter_binding_snapshot is not None
+ else {}
+ )
+ if parameter_binding_snapshot is not None and snapshot_bindings_by_index is None:
return None
+ snapshot_bindings_by_index = snapshot_bindings_by_index or {}
+ snapshot_recovery_bindings = (
+ [binding for binding in parameter_binding_snapshot.field_bindings if binding.field_trajectory_index is None]
+ if parameter_binding_snapshot is not None
+ else []
+ )
compile_download_target = (
reached_download_target is not None
and not reached_download_target.already_registered
@@ -1577,6 +1668,27 @@ def synthesize_code_block(
return _INDENT * 2
return _INDENT
+ snapshot_recovery_emitted = False
+
+ def emit_snapshot_recovery(trajectory_index: int, action_indent: str) -> None:
+ nonlocal snapshot_recovery_emitted
+ if (
+ snapshot_recovery_emitted
+ or parameter_binding_snapshot is None
+ or _captured_trajectory_index(trajectory[trajectory_index], trajectory_index)
+ != parameter_binding_snapshot.terminal.trajectory_index
+ ):
+ return
+ for binding in snapshot_recovery_bindings:
+ if binding.declared_key not in used_param_keys:
+ used_param_keys.add(binding.declared_key)
+ parameters.append({"key": binding.declared_key})
+ lines.append(
+ f"{action_indent}await page.locator({_py_str(binding.field_selector)}).fill(str({binding.declared_key}))"
+ )
+ diagnostics.grounded_submit_binding_fingerprints.append(parameter_binding_snapshot.fingerprint)
+ snapshot_recovery_emitted = True
+
for trajectory_index, interaction in enumerate(trajectory):
if emitted >= _MAX_STEPS:
diagnostics.truncated = True
@@ -1600,6 +1712,7 @@ def synthesize_code_block(
tool_name = str(interaction.get("tool_name") or "")
if tool_name == "press_key":
+ emit_snapshot_recovery(trajectory_index, action_indent)
key = str(interaction.get("key") or "").strip()
if not key:
diagnostics.dropped_interactions.append(
@@ -1668,6 +1781,7 @@ def synthesize_code_block(
line_start = len(lines) + 1
if tool_name == "click":
+ emit_snapshot_recovery(trajectory_index, action_indent)
captured_index = interaction.get("trajectory_index")
submit_trajectory_index = (
captured_index if isinstance(captured_index, int) and captured_index >= 0 else trajectory_index
@@ -1715,16 +1829,22 @@ def synthesize_code_block(
record_emission(trajectory_index, tool_name, "click", locator, line_start=line_start)
append_step(f"Click {_step_target(interaction)}", "click", line_start)
elif tool_name == "type_text":
+ snapshot_binding = snapshot_bindings_by_index.get(trajectory_index)
typed_identity = _typed_value_identity(interaction)
- param_key = typed_param_keys.get(typed_identity) if typed_identity is not None else None
+ param_key = snapshot_binding[0] if snapshot_binding is not None else None
if param_key is None:
- param_key = _param_key(interaction, used_param_keys)
+ param_key = typed_param_keys.get(typed_identity) if typed_identity is not None else None
+ if param_key is None or param_key not in used_param_keys:
+ if param_key is None:
+ param_key = _param_key(interaction, used_param_keys)
+ else:
+ used_param_keys.add(param_key)
parameter = {"key": param_key}
typed_value = str(interaction.get("typed_value") or "").strip()
- if typed_value:
+ if typed_value and snapshot_binding is None:
parameter["default_value"] = typed_value
typed_length = interaction.get("typed_length")
- if strict_selectors and typed_length is not None:
+ if strict_selectors and typed_length is not None and snapshot_binding is None:
try:
typed_length_int = int(typed_length)
except (TypeError, ValueError):
@@ -1903,7 +2023,8 @@ def synthesize_code_block(
if not lines:
return None
- if len(diagnostics.grounded_submit_binding_fingerprints) != grounded_binding_count:
+ expected_binding_fingerprint_count = grounded_binding_count + (1 if parameter_binding_snapshot is not None else 0)
+ if len(diagnostics.grounded_submit_binding_fingerprints) != expected_binding_fingerprint_count:
return None
emitted_code = "\n".join(lines)
for scout_var in _INTERNAL_SCOUT_VARS:
@@ -2669,6 +2790,7 @@ def synthesize_code_block_with_extraction(
*,
strict_selectors: bool = False,
reached_download_target: ReachedDownloadTarget | None = None,
+ parameter_binding_snapshot: AuthoringParameterBindingSnapshot | None = None,
) -> SynthesizedCodeBlock | None:
if not _trajectory_contains_reveal(trajectory, extraction_plan):
return None
@@ -2676,6 +2798,7 @@ def synthesize_code_block_with_extraction(
trajectory,
strict_selectors=strict_selectors,
reached_download_target=reached_download_target,
+ parameter_binding_snapshot=parameter_binding_snapshot,
)
suffix = synthesize_extraction_suffix(extraction_plan)
if interaction is None or suffix is None:
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 2dc2740eb..6e2af337f 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -13,6 +13,7 @@ import structlog
from pydantic import BaseModel, Field
from typing_extensions import NotRequired, TypedDict
+from skyvern.forge.sdk.copilot.authoring_parameter_binding import AuthoringParameterBindingDirective
from skyvern.forge.sdk.copilot.build_phase import BuildPhase
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig
from skyvern.forge.sdk.copilot.result_evidence import (
@@ -224,6 +225,7 @@ class CodeAuthoringRepairContext(BaseModel):
spine_stage_count: int | None = None
spine_split_blockers: list[str] = Field(default_factory=list)
output_owner_candidate_labels: list[str] = Field(default_factory=list)
+ parameter_binding_directive: AuthoringParameterBindingDirective | None = None
repair_instruction: str = "add workflow-input-like names to parameter_keys, or stop referencing them."
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index d0fbfe0be..9bdaf1037 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -45,6 +45,7 @@ from skyvern.webeye.browser_state import BrowserState
if TYPE_CHECKING:
from playwright.async_api import Page
+ from skyvern.forge.sdk.copilot.authoring_parameter_binding import AuthoringParameterBindingSnapshot
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.build_test_outcome import (
RecordedBuildTestOutcome,
@@ -373,6 +374,7 @@ class AgentContext:
recorded_persisted_block_run_workflow_run_id: str | None = None
recorded_outcome_grounding_requirement: RecordedOutcomeGroundingRequirement | None = None
recorded_outcome_binding_constraint: RecordedOutcomeBindingConstraint | None = None
+ authoring_parameter_binding_snapshot: AuthoringParameterBindingSnapshot | None = None
consecutive_non_converging_repair_count: int = 0
completion_verification_result: CompletionVerificationResult | None = None
completion_criteria_turn_state: CompletionCriteriaTurnState | None = None
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index da87ba319..c001da09a 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -26,6 +26,19 @@ from pydantic import AliasChoices, BaseModel, Field, ValidationError
from skyvern.forge import app
from skyvern.forge.sdk.api.llm.schema_validator import validate_schema
from skyvern.forge.sdk.copilot.attribution import resolve_copilot_created_by_stamp
+from skyvern.forge.sdk.copilot.authoring_parameter_binding import (
+ AuthoringParameterBindingCandidate,
+ AuthoringParameterBindingDirective,
+ AuthoringParameterBindingMatchBasis,
+ AuthoringParameterBindingSnapshot,
+ AuthoringParameterBindingTerminalTool,
+ AuthoringParameterFieldBinding,
+ AuthoringParameterTerminalBinding,
+ authored_selector_parameter_bindings,
+ authoring_parameter_binding_directive_consumed,
+ build_authoring_parameter_binding_directive,
+ build_authoring_parameter_binding_snapshot,
+)
from skyvern.forge.sdk.copilot.blocker_signal import (
CREDENTIAL_SCOUT_VERIFY_REPLY,
OUTPUT_CONTRACT_REJECT_BUDGET_EXHAUSTED_REASON_CODE,
@@ -83,6 +96,7 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (
_get_by_role_expr_strict,
_is_ignorable_entry_opener_drop,
_is_positional_selector,
+ _is_submit_interaction,
_selector_refines,
artifact_dependency_id,
artifact_observation_ref_id,
@@ -90,7 +104,6 @@ from skyvern.forge.sdk.copilot.code_block_synthesis import (
credential_scout_gap,
freeze_requested_output_extraction_candidate,
grounded_parameter_key_is_safe,
- grounded_submit_rung_binding_fingerprint,
input_correspondences_for_interaction,
locator_selector_literals,
missing_rung_text,
@@ -181,9 +194,7 @@ from skyvern.forge.sdk.copilot.runtime import (
AgentContext,
AuthorTimeGateAblationPayload,
RejectedCodeArtifactMetadataCapture,
- ScoutedFieldParameterBinding,
ScoutedInteraction,
- ScoutedSubmitRungBinding,
copilot_author_time_gate_log_only_enabled,
record_author_time_gate_ablation_event,
)
@@ -200,6 +211,7 @@ from skyvern.forge.sdk.copilot.turn_halt import (
stash_repair_ceiling_turn_halt,
stash_turn_halt_from_blocker_signal,
)
+from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
from skyvern.forge.sdk.copilot.turn_ownership import (
TurnClaimant,
claim_and_stash_blocker_signal,
@@ -1728,6 +1740,8 @@ def _requested_output_child_paths(ctx: AgentContext) -> set[str]:
for criterion in _active_completion_criteria(ctx):
if isinstance(criterion, CompletionCriterion) and _is_judgment_boolean_criterion(criterion):
continue
+ if isinstance(criterion, CompletionCriterion) and criterion.antecedent_family == "blocker":
+ continue
if getattr(criterion, "level", None) == "definition":
continue
if getattr(criterion, "method_mandated", False):
@@ -1757,9 +1771,13 @@ def _contingent_antecedent_child_paths(ctx: AgentContext) -> set[str]:
criterion.output_path and _is_judgment_boolean_criterion(criterion)
):
continue
- path = _canonical_requested_output_path(criterion.contingent_antecedent_output_path)
- if path and _output_path_has_child(path):
- paths.add(path)
+ raw_paths = [criterion.contingent_antecedent_output_path]
+ if criterion.antecedent_family == "blocker":
+ raw_paths.append(criterion.output_path)
+ for raw_path in raw_paths:
+ path = _canonical_requested_output_path(raw_path)
+ if path and _output_path_has_child(path):
+ paths.add(path)
return paths
@@ -2178,6 +2196,44 @@ def _definition_plane_reject_error(rejection: _DefinitionPlaneReject) -> str:
return "The submitted workflow does not satisfy its active definition-level requirements."
+def _definition_plane_structural_payload(
+ workflow_yaml: str,
+ rejection: _DefinitionPlaneReject,
+ code_artifact_metadata: object = None,
+) -> tuple[dict[str, object], str | None]:
+ authored_signature = authored_structure_signature_from_workflow(workflow_yaml, code_artifact_metadata)
+ return (
+ {
+ "reason_code": "definition_contract_unsatisfied",
+ "criterion_ids": rejection.criterion_ids,
+ "definition_reason_codes": rejection.reason_codes,
+ "unreferenced_parameter_keys": rejection.unreferenced_parameter_keys,
+ "authored_structure_signature": authored_signature,
+ },
+ authored_signature,
+ )
+
+
+def _definition_plane_structural_key(
+ workflow_yaml: str,
+ rejection: _DefinitionPlaneReject,
+ code_artifact_metadata: object = None,
+) -> str:
+ structural_payload, authored_signature = _definition_plane_structural_payload(
+ workflow_yaml,
+ rejection,
+ code_artifact_metadata,
+ )
+ outcome = recorded_outcome_from_author_time_reject(
+ reason_code="definition_contract_unsatisfied",
+ block_labels=sorted(_workflow_yaml_code_blocks_by_label(workflow_yaml)),
+ structural_payload=structural_payload,
+ authored_structure_signature=authored_signature,
+ observed_evidence_summary=_definition_plane_reject_error(rejection),
+ )
+ return outcome.structural_key or authored_signature or ""
+
+
def _record_definition_plane_reject(
ctx: AgentContext,
workflow_yaml: str,
@@ -2185,19 +2241,17 @@ def _record_definition_plane_reject(
*,
code_artifact_metadata: object = None,
) -> None:
- authored_signature = authored_structure_signature_from_workflow(workflow_yaml, code_artifact_metadata)
+ structural_payload, authored_signature = _definition_plane_structural_payload(
+ workflow_yaml,
+ rejection,
+ code_artifact_metadata,
+ )
block_labels = sorted(_workflow_yaml_code_blocks_by_label(workflow_yaml))
_record_author_time_reject_outcome(
ctx,
reason_code="definition_contract_unsatisfied",
summary=_definition_plane_reject_error(rejection),
- structural_payload={
- "reason_code": "definition_contract_unsatisfied",
- "criterion_ids": rejection.criterion_ids,
- "definition_reason_codes": rejection.reason_codes,
- "unreferenced_parameter_keys": rejection.unreferenced_parameter_keys,
- "authored_structure_signature": authored_signature,
- },
+ structural_payload=structural_payload,
authored_structure_signature=authored_signature,
block_labels=block_labels,
)
@@ -2279,27 +2333,74 @@ def _stash_unresolved_recorded_outcome_grounding_halt(
return True
-def _trajectory_with_grounded_submit_rung_binding(
+def _scout_trajectory_index(interaction: Mapping[str, Any], position: int) -> int:
+ raw_index = interaction.get("trajectory_index")
+ return raw_index if isinstance(raw_index, int) and raw_index >= 0 else position
+
+
+class _AuthoringParameterBindingResolution(NamedTuple):
+ snapshot: AuthoringParameterBindingSnapshot | None
+ directive: AuthoringParameterBindingDirective | None
+
+
+def _pending_authoring_parameter_binding_directive(
+ ctx: AgentContext,
+) -> tuple[CodeAuthoringRepairContext, AuthoringParameterBindingDirective] | None:
+ repair_context = ctx.last_code_authoring_repair_context
+ if (
+ not isinstance(repair_context, CodeAuthoringRepairContext)
+ or repair_context.reason_code != _SYNTHESIZED_PARAMETER_BINDING_AMBIGUOUS_REASON_CODE
+ or repair_context.parameter_binding_directive is None
+ ):
+ return None
+ return repair_context, repair_context.parameter_binding_directive
+
+
+def _authoring_parameter_binding_resolution(
ctx: AgentContext,
parsed: Mapping[str, Any],
runtime_parameters: Mapping[str, Any] | None,
-) -> tuple[ScoutedInteraction, ...] | None:
+ *,
+ unreferenced_parameter_keys: Sequence[str],
+ carrier_code: str,
+ diagnostic_structural_key: str,
+) -> _AuthoringParameterBindingResolution:
requirement = ctx.recorded_outcome_grounding_requirement
constraint = ctx.recorded_outcome_binding_constraint
+ repeated_grounding_payload = None
+ structural_key = diagnostic_structural_key
if (
- not isinstance(requirement, RecordedOutcomeGroundingRequirement)
- or not requirement.satisfied
- or requirement.payload is None
- or requirement.payload.source_tool != "inspect_page_for_composition"
- or requirement.payload.target_url != "current_page"
- or not isinstance(constraint, RecordedOutcomeBindingConstraint)
- or constraint.repeated_structural_key != requirement.structural_key
+ isinstance(requirement, RecordedOutcomeGroundingRequirement)
+ and requirement.satisfied
+ and requirement.payload is not None
+ and requirement.payload.source_tool == "inspect_page_for_composition"
+ and requirement.payload.target_url == "current_page"
+ and isinstance(constraint, RecordedOutcomeBindingConstraint)
+ and constraint.repeated_structural_key == requirement.structural_key
):
- return None
+ repeated_grounding_payload = requirement.payload
+ structural_key = constraint.repeated_structural_key
+ if not structural_key:
+ return _AuthoringParameterBindingResolution(None, None)
+ target_keys = tuple(sorted(set(unreferenced_parameter_keys)))
+ if not target_keys or any(not grounded_parameter_key_is_safe(key) for key in target_keys):
+ return _AuthoringParameterBindingResolution(None, None)
declared_keys = _declared_string_workflow_parameter_keys(parsed)
- if not declared_keys or any(not grounded_parameter_key_is_safe(key) for key in declared_keys):
- return None
- supplied = runtime_parameters if isinstance(runtime_parameters, Mapping) else {}
+ if not set(target_keys).issubset(declared_keys):
+ return _AuthoringParameterBindingResolution(None, None)
+
+ evidence = ctx.composition_page_evidence
+ forms = evidence.get("forms") if isinstance(evidence, Mapping) else None
+ current_url = str(evidence.get("current_url") or "").strip() if isinstance(evidence, Mapping) else ""
+ source_tool = str(evidence.get("source_tool") or "").strip() if isinstance(evidence, Mapping) else ""
+ if not isinstance(forms, list) or not current_url or source_tool != "inspect_page_for_composition":
+ return _AuthoringParameterBindingResolution(None, None)
+ if repeated_grounding_payload is not None and repeated_grounding_payload.source_url != current_url:
+ return _AuthoringParameterBindingResolution(None, None)
+ source_origin = url_origin(current_url)
+ if source_origin is None:
+ return _AuthoringParameterBindingResolution(None, None)
+
definition = parsed.get("workflow_definition")
rows = definition.get("parameters") if isinstance(definition, Mapping) else None
defaults = (
@@ -2307,103 +2408,188 @@ def _trajectory_with_grounded_submit_rung_binding(
if isinstance(rows, list)
else {}
)
- values: dict[str, str] = {}
- for key in sorted(declared_keys):
- value = supplied.get(key, defaults.get(key))
- if not isinstance(value, str) or not value:
- return None
- values[key] = value
+ supplied = runtime_parameters if isinstance(runtime_parameters, Mapping) else {}
+ ephemeral_values = {key: supplied.get(key, defaults.get(key)) for key in target_keys}
+ authored_bindings = authored_selector_parameter_bindings(carrier_code, set(target_keys))
+ if authored_bindings is None:
+ return _AuthoringParameterBindingResolution(None, None)
- evidence = ctx.composition_page_evidence
- forms = evidence.get("forms") if isinstance(evidence, Mapping) else None
- current_url = str(evidence.get("current_url") or "").strip() if isinstance(evidence, Mapping) else ""
- if not isinstance(forms, list) or not current_url or requirement.payload.source_url != current_url:
- return None
- captured_clicks: list[tuple[int, int, str, str]] = []
- for fallback_index, interaction in enumerate(ctx.scout_trajectory):
- if not isinstance(interaction, Mapping) or interaction.get("tool_name") != "click":
- continue
- raw_index = interaction.get("trajectory_index")
- trajectory_index = raw_index if isinstance(raw_index, int) and raw_index >= 0 else fallback_index
- captured_clicks.append(
- (
- fallback_index,
- trajectory_index,
- str(interaction.get("selector") or "").strip(),
- str(interaction.get("source_url") or "").strip(),
- )
- )
+ terminal_records: list[tuple[int, Mapping[str, Any]]] = []
+ for position, interaction in enumerate(ctx.scout_trajectory):
+ if not isinstance(interaction, Mapping):
+ continue
+ if _is_submit_interaction(interaction) and str(interaction.get("source_url") or "").strip() == current_url:
+ terminal_records.append((position, interaction))
- candidates: list[tuple[int, int, ScoutedSubmitRungBinding]] = []
+ snapshots: list[AuthoringParameterBindingSnapshot] = []
+ candidate_pairs: list[AuthoringParameterBindingCandidate] = []
for form in forms:
if not isinstance(form, Mapping):
continue
fields = [field for field in form.get("fields") or [] if isinstance(field, Mapping)]
- controls = [control for control in form.get("submit_controls") or [] if isinstance(control, Mapping)]
- submit_matches: set[tuple[int, int, str]] = set()
- for control in controls:
- submit_selector = str(control.get("selector") or "").strip()
- if control.get("disabled") is True or not submit_selector:
- continue
- matching_clicks = [
- click for click in captured_clicks if click[2] == submit_selector and click[3] == current_url
- ]
- if len(matching_clicks) == 1:
- submit_matches.add((matching_clicks[0][0], matching_clicks[0][1], submit_selector))
- if len(submit_matches) != 1:
+ active_fields = [
+ field for field in fields if field.get("disabled") is not True and str(field.get("selector") or "").strip()
+ ]
+ field_selectors = {str(field.get("selector") or "").strip() for field in active_fields}
+ submit_selectors = {
+ str(control.get("selector") or "").strip()
+ for control in form.get("submit_controls") or []
+ if isinstance(control, Mapping)
+ and control.get("disabled") is not True
+ and str(control.get("selector") or "").strip()
+ }
+ terminals = [
+ (position, interaction)
+ for position, interaction in terminal_records
+ if (
+ str(interaction.get("tool_name") or "") == "click"
+ and str(interaction.get("selector") or "").strip() in submit_selectors
+ )
+ or (
+ str(interaction.get("tool_name") or "") == "press_key"
+ and str(interaction.get("selector") or "").strip() in field_selectors
+ )
+ ]
+ if len(terminals) != 1:
continue
- submit_position, submit_trajectory_index, submit_selector = next(iter(submit_matches))
- bindings: list[ScoutedFieldParameterBinding] = []
+ terminal_trajectory_index = _scout_trajectory_index(terminals[0][1], terminals[0][0])
+
+ resolved: list[AuthoringParameterFieldBinding] = []
used_selectors: set[str] = set()
- for key, value in values.items():
- matching_fields = [
- field
- for field in fields
- if field.get("disabled") is not True
- and str(field.get("selector") or "").strip()
- and field.get("value") == value
- ]
- if len(matching_fields) != 1:
- bindings = []
- break
- selector = str(matching_fields[0].get("selector") or "").strip()
- if selector in used_selectors:
- bindings = []
- break
- used_selectors.add(selector)
- bindings.append({"parameter_key": key, "field_selector": selector})
- if len(bindings) == len(values):
- fingerprint = grounded_submit_rung_binding_fingerprint(
- repeated_structural_key=constraint.repeated_structural_key,
- source_url=current_url,
- submit_selector=submit_selector,
- submit_trajectory_index=submit_trajectory_index,
- field_bindings=bindings,
+ ambiguous = False
+ for key in target_keys:
+ selector_basis: list[tuple[str, str]] = []
+ authored_selectors = sorted(
+ selector for selector, keys in authored_bindings.items() if key in keys and selector in field_selectors
)
- candidates.append(
- (
- submit_position,
- submit_trajectory_index,
+ if authored_selectors:
+ selector_basis = [(selector, "exact_authored_selector") for selector in authored_selectors]
+ else:
+ correspondence_selectors = sorted(
{
- "repeated_structural_key": constraint.repeated_structural_key,
- "fingerprint": fingerprint,
- "field_bindings": bindings,
- },
+ str(interaction.get("selector") or "").strip()
+ for interaction in ctx.scout_trajectory
+ if isinstance(interaction, Mapping)
+ and str(interaction.get("selector") or "").strip() in field_selectors
+ and any(
+ isinstance(correspondence, Mapping) and correspondence.get("input_key") == key
+ for correspondence in interaction.get("input_correspondences") or []
+ )
+ }
+ )
+ if correspondence_selectors:
+ selector_basis = [
+ (selector, "grounded_input_correspondence") for selector in correspondence_selectors
+ ]
+ else:
+ value = ephemeral_values.get(key)
+ if isinstance(value, str) and value:
+ value_selectors = sorted(
+ str(field.get("selector") or "").strip()
+ for field in active_fields
+ if field.get("value") == value
+ )
+ selector_basis = [(selector, "unique_ephemeral_value") for selector in value_selectors]
+ for selector, _basis in selector_basis:
+ sanitized_selector = _safe_selector_repair_atom(selector)
+ if sanitized_selector:
+ candidate_pairs.append(
+ AuthoringParameterBindingCandidate(
+ declared_key=key,
+ field_selector=sanitized_selector,
+ )
+ )
+ if len(selector_basis) != 1:
+ ambiguous = True
+ continue
+ selector, basis = selector_basis[0]
+ matching_fills = [
+ _scout_trajectory_index(interaction, position)
+ for position, interaction in enumerate(ctx.scout_trajectory)
+ if isinstance(interaction, Mapping)
+ and str(interaction.get("tool_name") or "") == "type_text"
+ and str(interaction.get("source_url") or "").strip() == current_url
+ and str(interaction.get("selector") or "").strip() == selector
+ ]
+ if len(matching_fills) > 1 or selector in used_selectors:
+ ambiguous = True
+ continue
+ if any(fill_index > terminal_trajectory_index for fill_index in matching_fills):
+ ambiguous = True
+ continue
+ used_selectors.add(selector)
+ resolved.append(
+ AuthoringParameterFieldBinding(
+ declared_key=key,
+ field_selector=selector,
+ field_trajectory_index=matching_fills[0] if matching_fills else None,
+ match_basis=cast(AuthoringParameterBindingMatchBasis, basis),
)
)
- if len(candidates) != 1:
- return None
- submit_position, submit_trajectory_index, submit_rung_binding = candidates[0]
- derived = [cast(ScoutedInteraction, dict(interaction)) for interaction in ctx.scout_trajectory]
- derived[submit_position]["submit_rung_binding"] = submit_rung_binding
+ if ambiguous or len(resolved) != len(target_keys):
+ continue
+ terminal_position, terminal_interaction = terminals[0]
+ terminal = AuthoringParameterTerminalBinding(
+ tool_name=cast(AuthoringParameterBindingTerminalTool, str(terminal_interaction.get("tool_name") or "")),
+ trajectory_index=_scout_trajectory_index(terminal_interaction, terminal_position),
+ selector=str(terminal_interaction.get("selector") or "").strip(),
+ key=str(terminal_interaction.get("key") or "").strip(),
+ )
+ snapshots.append(
+ build_authoring_parameter_binding_snapshot(
+ structural_key=structural_key,
+ source_origin=source_origin,
+ field_bindings=resolved,
+ terminal=terminal,
+ )
+ )
+
+ unique_snapshots = {snapshot.fingerprint: snapshot for snapshot in snapshots}
+ directive = (
+ build_authoring_parameter_binding_directive(
+ structural_key=structural_key,
+ source_origin=source_origin,
+ candidates=candidate_pairs,
+ )
+ if candidate_pairs
+ else None
+ )
+ if len(unique_snapshots) != 1:
+ return _AuthoringParameterBindingResolution(None, directive)
+ snapshot = next(iter(unique_snapshots.values()))
LOG.info(
"copilot recorded outcome submit rung bound",
- binding_fingerprint=submit_rung_binding["fingerprint"],
- parameter_keys=[binding["parameter_key"] for binding in submit_rung_binding["field_bindings"]],
- binding_count=len(submit_rung_binding["field_bindings"]),
- submit_trajectory_index=submit_trajectory_index,
+ binding_fingerprint=snapshot.fingerprint,
+ parameter_keys=[binding.declared_key for binding in snapshot.field_bindings],
+ binding_count=len(snapshot.field_bindings),
+ terminal_tool=snapshot.terminal.tool_name,
+ terminal_trajectory_index=snapshot.terminal.trajectory_index,
+ )
+ return _AuthoringParameterBindingResolution(snapshot, directive)
+
+
+def _authoring_parameter_binding_resolution_for_definition(
+ ctx: AgentContext,
+ parsed: Mapping[str, Any],
+ runtime_parameters: Mapping[str, Any] | None,
+ code_artifact_metadata: object = None,
+) -> _AuthoringParameterBindingResolution | None:
+ workflow_yaml = yaml.safe_dump(dict(parsed), sort_keys=False)
+ rejection = _definition_plane_preflight_reject(ctx, workflow_yaml)
+ if rejection is None:
+ return None
+ return _authoring_parameter_binding_resolution(
+ ctx,
+ parsed,
+ runtime_parameters,
+ unreferenced_parameter_keys=rejection.unreferenced_parameter_keys,
+ carrier_code="",
+ diagnostic_structural_key=_definition_plane_structural_key(
+ workflow_yaml,
+ rejection,
+ code_artifact_metadata,
+ ),
)
- return tuple(derived)
def _judgment_output_paths(ctx: AgentContext) -> set[str]:
@@ -2573,6 +2759,9 @@ _METADATA_FAMILY_REJECT_FAMILIES = frozenset(
_MAX_OUTPUT_CONTRACT_ACTUATIONS_WITHOUT_RUN = 3
_OUTPUT_CONTRACT_ABLATION_GATE_ID = "output_contract_actuation"
_METADATA_PREFLIGHT_ABLATION_GATE_ID = "metadata_run_preflight_reject"
+_VALUE_BEARING_ROOT_GUIDANCE_PATH = "output"
+_VALUE_BEARING_PREARM_FINGERPRINT_PREFIX = "value-bearing:prearm:"
+_VALUE_BEARING_GUIDANCE_FINGERPRINT_PREFIX = "value-bearing:guidance:"
@dataclass(frozen=True)
@@ -2800,6 +2989,77 @@ def _return_skeleton_for_required_paths(
return f"return {{{pairs}}}" if pairs else ""
+def _value_bearing_satisfying_templates(
+ *,
+ block_label: str,
+ required_paths: set[str],
+ declaration_paths: set[str],
+ source: str,
+ reason_code: str,
+) -> dict[str, Any]:
+ declaration = _metadata_contract_required_paths(declaration_paths)
+ declaration_children = sorted(
+ child
+ for path in declaration
+ if (child := _output_path_direct_child(path, _VALUE_BEARING_ROOT_GUIDANCE_PATH))
+ and _return_scaffold_name_is_safe(child)
+ )
+ root_declarations_are_direct = len(declaration_children) == len(declaration)
+ if required_paths != {_VALUE_BEARING_ROOT_GUIDANCE_PATH} or not root_declarations_are_direct:
+ return {
+ "code_artifact_metadata": (
+ _metadata_contract_template(
+ block_label=block_label,
+ required_paths=required_paths,
+ source=source,
+ reason_code=reason_code,
+ declaration_paths=declaration_paths,
+ )
+ if block_label
+ else None
+ ),
+ "extraction_schema": _schema_template_for_required_paths(required_paths, declaration_paths),
+ "return_skeleton": _return_skeleton_for_required_paths(required_paths, declaration_paths),
+ }
+ schema = (
+ _schema_template_for_required_paths(declaration, declaration)
+ if declaration
+ else {
+ "type": "object",
+ "properties": {_VALUE_BEARING_ROOT_GUIDANCE_PATH: {}},
+ "required": [_VALUE_BEARING_ROOT_GUIDANCE_PATH],
+ }
+ )
+ metadata_template = (
+ _metadata_contract_template(
+ block_label=block_label,
+ required_paths=set(),
+ source=source,
+ reason_code=reason_code,
+ declaration_paths=declaration,
+ )
+ if block_label
+ else None
+ )
+ if metadata_template is not None:
+ schema_text = json.dumps(schema, sort_keys=True)
+ for field_name in ("claimed_outcomes", "terminal_verifier_expectations"):
+ row = metadata_template[field_name][0]
+ row["goal_value_paths"] = [_VALUE_BEARING_ROOT_GUIDANCE_PATH]
+ row["extraction_schema"] = schema_text
+ declaration_defaults = ", ".join(f'"{child}": None' for child in declaration_children)
+ return_skeleton = (
+ 'return {"' + _VALUE_BEARING_ROOT_GUIDANCE_PATH + '": {' + declaration_defaults + ", **output_value}}"
+ if declaration_defaults
+ else f'return {{"{_VALUE_BEARING_ROOT_GUIDANCE_PATH}": output_value}}'
+ )
+ return {
+ "code_artifact_metadata": metadata_template,
+ "extraction_schema": schema,
+ "return_skeleton": return_skeleton,
+ }
+
+
def _metadata_item_for_block_label(raw_metadata: object, block_label: str) -> Mapping[str, Any] | None:
for raw_item in _code_artifact_metadata_items(raw_metadata):
item = _raw_metadata_item_mapping(raw_item)
@@ -3173,6 +3433,16 @@ class _OutputContractRequiredPaths:
return _OutputContractLiveness.ABSENT
+def _value_bearing_directive_paths(contract: _OutputContractRequiredPaths) -> set[str]:
+ if not contract.observation_paths and (
+ contract.declaration_paths or contract.liveness is _OutputContractLiveness.DEGRADED_EMPTY
+ ):
+ return {_VALUE_BEARING_ROOT_GUIDANCE_PATH}
+ if contract.union:
+ return set(contract.union)
+ return set()
+
+
def _degraded_request_slot_diagnostics(ctx: AgentContext) -> tuple[_DegradedRequestSlotDiagnostic, ...]:
diagnostics: list[_DegradedRequestSlotDiagnostic] = []
request_policy = ctx.request_policy
@@ -3345,6 +3615,52 @@ def _resolve_static_expression(
return _resolve_static_expression(assigned, assignments, uncertain_names, seen_names | {expression.id})
+_RootOutputEnvelopeState = Literal["proven", "absent", "unknown"]
+
+
+def _root_output_expression_state(
+ expression: ast.expr,
+ assignments: Mapping[str, ast.expr],
+ uncertain_names: set[str],
+) -> _RootOutputEnvelopeState:
+ resolved = _resolve_static_expression(expression, assignments, uncertain_names)
+ if resolved is None:
+ return "unknown"
+ if not isinstance(resolved, ast.Dict):
+ return "absent" if isinstance(resolved, (ast.Constant, ast.List, ast.Set, ast.Tuple)) else "unknown"
+ literal_keys: list[str] = []
+ for key in resolved.keys:
+ if not isinstance(key, ast.Constant) or not isinstance(key.value, str):
+ return "unknown"
+ literal_keys.append(key.value)
+ return "proven" if _VALUE_BEARING_ROOT_GUIDANCE_PATH in literal_keys else "absent"
+
+
+def _root_output_envelope_state(code: str) -> _RootOutputEnvelopeState:
+ try:
+ tree = ast.parse(textwrap.dedent(code).strip() or "pass")
+ return_nodes = [node for node in _iter_top_level_scope(tree.body) if isinstance(node, ast.Return)]
+ if not return_nodes:
+ return "absent"
+ states: set[_RootOutputEnvelopeState] = set()
+ for node in return_nodes:
+ if node.value is None:
+ states.add("absent")
+ continue
+ prior_body = [
+ statement for statement in tree.body if (statement.end_lineno or statement.lineno) < node.lineno
+ ]
+ assignments, uncertain_names = _top_level_static_assignments(ast.Module(body=prior_body, type_ignores=[]))
+ states.add(_root_output_expression_state(node.value, assignments, uncertain_names))
+ if "absent" in states:
+ return "absent"
+ if "unknown" in states:
+ return "unknown"
+ return "proven"
+ except (RecursionError, SyntaxError, ValueError):
+ return "unknown"
+
+
_StaticOutputPathState = Literal["value", "empty", "absent", "unknown"]
@@ -3478,7 +3794,7 @@ def _evaluate_output_contract_for_code_block(
return None
runtime_contract = _runtime_output_repair_contract_from_recorded_outcome(ctx)
contract = _output_contract_required_paths_source(ctx)
- required_paths = contract.union
+ required_paths = _value_bearing_directive_paths(contract) if enforce_value_bearing_liveness else set(contract.union)
observation_paths = contract.observation_paths
declaration_paths = contract.declaration_paths
source = contract.source
@@ -3512,11 +3828,25 @@ def _evaluate_output_contract_for_code_block(
declaration_only_contract = bool(declaration_paths) and not observation_paths
if enforce_value_bearing_liveness:
if contract.liveness is _OutputContractLiveness.DEGRADED_EMPTY or declaration_only_contract:
- shape_violations.append(_OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE)
- elif target_block is not None and _statically_lacks_value_bearing_observation_paths(
- target_code, observation_paths
- ):
- shape_violations.append(_OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE)
+ root_envelope_unproved = (
+ required_paths == {_VALUE_BEARING_ROOT_GUIDANCE_PATH}
+ and _root_output_envelope_state(target_code) != "proven"
+ )
+ if (
+ target_block is None
+ or root_envelope_unproved
+ or _statically_lacks_value_bearing_observation_paths(target_code, required_paths)
+ ):
+ shape_violations.append(_OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE)
+ elif target_block is not None:
+ root_envelope_unproved = (
+ observation_paths == {_VALUE_BEARING_ROOT_GUIDANCE_PATH}
+ and _root_output_envelope_state(target_code) != "proven"
+ )
+ if root_envelope_unproved or _statically_lacks_value_bearing_observation_paths(
+ target_code, observation_paths
+ ):
+ shape_violations.append(_OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE)
if not block_label:
shape_violations.append("ambiguous_output_owner" if owner_labels else "missing_output_owner")
elif target_block is None:
@@ -3602,6 +3932,13 @@ def _evaluate_output_contract_for_code_block(
| (required_paths if shape_violations else set())
)
value_bearing_output_required = _OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE in shape_violations
+ satisfying_templates = _value_bearing_satisfying_templates(
+ block_label=block_label,
+ required_paths=required_paths,
+ declaration_paths=declaration_paths,
+ source=source,
+ reason_code=reason_code,
+ )
payload: dict[str, Any] = {
"reason_code": (
_OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE
@@ -3637,21 +3974,7 @@ def _evaluate_output_contract_for_code_block(
"runtime_output_repair_facts": runtime_contract.facts if runtime_contract is not None else [],
"output_owner_labels": owner_labels,
"metadata_repair_contract": metadata_repair_contract,
- "satisfying_templates": {
- "code_artifact_metadata": (
- _metadata_contract_template(
- block_label=block_label,
- required_paths=required_paths,
- source=source,
- reason_code=reason_code,
- declaration_paths=declaration_paths,
- )
- if block_label
- else None
- ),
- "extraction_schema": _schema_template_for_required_paths(required_paths, declaration_paths),
- "return_skeleton": _return_skeleton_for_required_paths(required_paths, declaration_paths),
- },
+ "satisfying_templates": satisfying_templates,
"missing_requested_output_facts": _missing_requested_output_facts(
missing_paths,
reason_code=reason_code,
@@ -3715,6 +4038,7 @@ def _adjudicate_output_contract_ladder_after_reject(
workflow_yaml: str,
current_fingerprint: str,
steer_only: bool = False,
+ structure_directive_paths: set[str] | None = None,
) -> OutputContractActuation | None:
"""Run the actuation ladder at the shared deficiency seam so a signature whose formation
remains incomplete advances toward an advisory-consumed run or a typed terminal within the
@@ -3722,9 +4046,10 @@ def _adjudicate_output_contract_ladder_after_reject(
owner-directive path, not granted an inert run."""
if ctx.turn_halt is not None or ctx.output_contract_bail_actuated_this_call:
return None
- # A statically valueless contract cannot be adjudicated by dispatching a run, so a
- # value-bearing reject never mints an advisory grant that would yield the preflight.
- if _OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE in evaluation.shape_violations:
+ # A statically valueless contract cannot be adjudicated by dispatching a run. The native
+ # reject seam may still ask the same ladder for steer-only structure guidance, but ordinary
+ # callers remain inert so they cannot mint an advisory grant that would yield the preflight.
+ if _OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE in evaluation.shape_violations and not steer_only:
return None
signature = evaluation.canonical_signature
block_label = evaluation.block_label
@@ -3742,7 +4067,11 @@ def _adjudicate_output_contract_ladder_after_reject(
ctx,
blockers=blockers,
target_code=target_code,
- required_paths=evaluation.observation_paths,
+ required_paths=(
+ structure_directive_paths
+ if steer_only and structure_directive_paths is not None
+ else evaluation.observation_paths
+ ),
signature=signature,
current_fingerprint=current_fingerprint,
advisory_run_grantable=blockers == [_OUTPUT_CONTRACT_REJECT_REASON_CODE],
@@ -3831,6 +4160,168 @@ def _metadata_reject_seam_fingerprint(
).hexdigest()
+@dataclass(frozen=True)
+class _ValueBearingEvaluationGuidance:
+ required_output_paths: tuple[str, ...]
+ shape_violations: tuple[str, ...]
+ satisfying_templates: dict[str, Any]
+
+ def fingerprint_payload(self) -> dict[str, Any]:
+ return {
+ "required_output_paths": list(self.required_output_paths),
+ "shape_violations": list(self.shape_violations),
+ "satisfying_templates": self.satisfying_templates,
+ }
+
+
+def _value_bearing_evaluation_guidance(
+ evaluation: _OutputContractEvaluation,
+) -> _ValueBearingEvaluationGuidance | None:
+ raw_paths = evaluation.payload.get("canonical_required_child_paths")
+ raw_shape_violations = evaluation.payload.get("shape_violations")
+ raw_satisfying_templates = evaluation.payload.get("satisfying_templates")
+ if (
+ not isinstance(raw_paths, list)
+ or not raw_paths
+ or any(not isinstance(path, str) or not path for path in raw_paths)
+ or not isinstance(raw_shape_violations, list)
+ or any(not isinstance(violation, str) or not violation for violation in raw_shape_violations)
+ or _OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE not in raw_shape_violations
+ or not isinstance(raw_satisfying_templates, dict)
+ ):
+ return None
+ paths = tuple(sorted(set(raw_paths)))
+ if any(
+ path != _canonical_requested_output_path(path) or _output_path_root(path) != _VALUE_BEARING_ROOT_GUIDANCE_PATH
+ for path in paths
+ ):
+ return None
+ return _ValueBearingEvaluationGuidance(
+ required_output_paths=paths,
+ shape_violations=tuple(raw_shape_violations),
+ satisfying_templates=dict(raw_satisfying_templates),
+ )
+
+
+def _value_bearing_reject_seam_fingerprint(
+ signature: str,
+ guidance: _ValueBearingEvaluationGuidance,
+) -> str:
+ digest = hashlib.sha256(
+ json.dumps(
+ {
+ "directive_family": _OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE,
+ "canonical_output_contract_signature": signature,
+ "guidance": guidance.fingerprint_payload(),
+ },
+ sort_keys=True,
+ ).encode("utf-8")
+ ).hexdigest()
+ return f"{_VALUE_BEARING_GUIDANCE_FINGERPRINT_PREFIX}{digest}"
+
+
+def _value_bearing_reject_directive_payload(
+ *,
+ guidance: _ValueBearingEvaluationGuidance,
+ escalate: bool,
+) -> dict[str, Any]:
+ return {
+ "rung": 2 if escalate else 1,
+ "required_output_paths": list(guidance.required_output_paths),
+ "shape_violations": list(guidance.shape_violations),
+ "satisfying_templates": guidance.satisfying_templates,
+ }
+
+
+def _emit_value_bearing_convergence_directive(
+ *,
+ signature: str,
+ block_label: str,
+ guidance: _ValueBearingEvaluationGuidance,
+ guidance_fingerprint: str,
+ candidate_fingerprint: str,
+ escalate: bool,
+) -> dict[str, Any]:
+ directive = _value_bearing_reject_directive_payload(
+ guidance=guidance,
+ escalate=escalate,
+ )
+ LOG.info(
+ "copilot_output_contract_spine_structure_directive_emitted",
+ directive_family=_OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE,
+ block_label=block_label,
+ canonical_output_contract_signature=signature,
+ canonical_required_child_paths=list(guidance.required_output_paths),
+ guidance_fingerprint=guidance_fingerprint,
+ candidate_fingerprint=candidate_fingerprint,
+ spine_split_blockers=list(guidance.shape_violations),
+ spine_stage_count=None,
+ rung=directive["rung"],
+ )
+ return directive
+
+
+def _value_bearing_definition_reject_corrective(
+ ctx: AgentContext,
+ *,
+ workflow_yaml: str,
+ raw_metadata: object,
+) -> dict[str, Any] | None:
+ if copilot_author_time_gate_log_only_enabled(ctx, _OUTPUT_CONTRACT_ABLATION_GATE_ID):
+ return None
+ evaluation = _evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ raw_metadata,
+ allow_static_return_advisory=True,
+ enforce_value_bearing_liveness=True,
+ )
+ if evaluation is None or _OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE not in evaluation.shape_violations:
+ return None
+ guidance = _value_bearing_evaluation_guidance(evaluation)
+ if guidance is None or not evaluation.canonical_signature or not evaluation.block_label:
+ return None
+ guidance_fingerprint = _value_bearing_reject_seam_fingerprint(
+ evaluation.canonical_signature,
+ guidance,
+ )
+ escalate = _prior_output_contract_directive_unconsumed(
+ ctx,
+ evaluation.canonical_signature,
+ guidance_fingerprint,
+ )
+ actuation = _adjudicate_output_contract_ladder_after_reject(
+ ctx,
+ evaluation,
+ workflow_yaml=workflow_yaml,
+ current_fingerprint=guidance_fingerprint,
+ steer_only=True,
+ structure_directive_paths=set(guidance.required_output_paths),
+ )
+ if actuation is None or actuation.kind != OutputContractActuationKind.STRUCTURE_DIRECTIVE:
+ return None
+ candidate_fingerprint = _output_contract_structural_fingerprint(
+ workflow_yaml,
+ evaluation.canonical_signature,
+ )
+ directive = _emit_value_bearing_convergence_directive(
+ signature=evaluation.canonical_signature,
+ block_label=evaluation.block_label,
+ guidance=guidance,
+ guidance_fingerprint=guidance_fingerprint,
+ candidate_fingerprint=candidate_fingerprint,
+ escalate=escalate,
+ )
+ return {
+ "canonical_output_contract_signature": evaluation.canonical_signature,
+ "canonical_required_child_paths": list(guidance.required_output_paths),
+ "shape_violations": list(guidance.shape_violations),
+ "satisfying_templates": guidance.satisfying_templates,
+ "output_contract_actuation": actuation.kind.value,
+ "value_bearing_convergence_directive": directive,
+ }
+
+
def _adjudicate_metadata_reject_ladder(
ctx: AgentContext,
*,
@@ -3925,7 +4416,14 @@ def _record_output_contract_reject(
# A candidate so incomplete that no required child paths are derivable must still consume the
# reject budget: an empty set would silently skip counting and degrade the turn to the generic
# churn stop (loop_detected) instead of this ladder's typed terminal.
- counted_paths = evaluation.required_paths or {_OUTPUT_CONTRACT_UNDECLARED_SENTINEL_PATH}
+ value_bearing_reject = _OUTPUT_CONTRACT_VALUE_REQUIRED_REASON_CODE in evaluation.shape_violations
+ value_bearing_guidance = _value_bearing_evaluation_guidance(evaluation) if value_bearing_reject else None
+ value_bearing_directive_paths = (
+ set(value_bearing_guidance.required_output_paths) if value_bearing_guidance is not None else set()
+ )
+ counted_paths = (
+ value_bearing_directive_paths or evaluation.required_paths or {_OUTPUT_CONTRACT_UNDECLARED_SENTINEL_PATH}
+ )
count = _record_output_contract_family_reject(
ctx,
counted_paths,
@@ -3936,29 +4434,74 @@ def _record_output_contract_reject(
payload = dict(evaluation.payload)
payload["output_contract_reject_count"] = count
payload["output_contract_reject_budget"] = _MAX_OUTPUT_CONTRACT_REJECTS
+ value_bearing_directive_eligible = bool(
+ value_bearing_reject
+ and evaluation.canonical_signature
+ and evaluation.block_label
+ and value_bearing_guidance is not None
+ )
missing_fields_by_label = (
_metadata_missing_required_fields_by_label(raw_metadata, labels=[evaluation.block_label], missing_labels=[])
if evaluation.block_label
else {}
)
- directive_fingerprint = (
- _metadata_reject_seam_fingerprint(workflow_yaml, evaluation.canonical_signature, missing_fields_by_label)
- if missing_fields_by_label
- else authored_structural_fingerprint
- )
+ if value_bearing_directive_eligible:
+ assert value_bearing_guidance is not None
+ directive_fingerprint = _value_bearing_reject_seam_fingerprint(
+ evaluation.canonical_signature,
+ value_bearing_guidance,
+ )
+ else:
+ directive_fingerprint = (
+ _metadata_reject_seam_fingerprint(workflow_yaml, evaluation.canonical_signature, missing_fields_by_label)
+ if missing_fields_by_label
+ else authored_structural_fingerprint
+ )
directive_escalate = _prior_output_contract_directive_unconsumed(
ctx, evaluation.canonical_signature, directive_fingerprint
)
- actuation = _adjudicate_output_contract_ladder_after_reject(
+ budget_terminal = value_bearing_directive_eligible and _adjudicate_output_contract_budget(
ctx,
- evaluation,
- workflow_yaml=workflow_yaml,
- current_fingerprint=directive_fingerprint,
+ counted_paths,
+ count=count,
+ block_label=evaluation.block_label,
)
+ actuation = (
+ None
+ if budget_terminal
+ else _adjudicate_output_contract_ladder_after_reject(
+ ctx,
+ evaluation,
+ workflow_yaml=workflow_yaml,
+ current_fingerprint=directive_fingerprint,
+ steer_only=value_bearing_directive_eligible,
+ structure_directive_paths=value_bearing_directive_paths if value_bearing_directive_eligible else None,
+ )
+ )
+ value_bearing_directive_emitted = False
if actuation is not None:
payload["output_contract_actuation"] = actuation.kind.value
+ if actuation.kind == OutputContractActuationKind.STRUCTURE_DIRECTIVE and value_bearing_directive_eligible:
+ assert value_bearing_guidance is not None
+ candidate_fingerprint = _output_contract_structural_fingerprint(
+ workflow_yaml, evaluation.canonical_signature
+ )
+ value_bearing_directive = _emit_value_bearing_convergence_directive(
+ signature=evaluation.canonical_signature,
+ block_label=evaluation.block_label,
+ guidance=value_bearing_guidance,
+ guidance_fingerprint=directive_fingerprint,
+ candidate_fingerprint=candidate_fingerprint,
+ escalate=directive_escalate,
+ )
+ payload["value_bearing_convergence_directive"] = value_bearing_directive
+ value_bearing_directive_emitted = True
+ latest_outcome = ctx.latest_recorded_build_test_outcome
+ if isinstance(latest_outcome, RecordedBuildTestOutcome) and latest_outcome.phase == "author_time_reject":
+ record_build_test_outcome(ctx, None)
if (
actuation.kind == OutputContractActuationKind.STRUCTURE_DIRECTIVE
+ and not value_bearing_directive_eligible
and evaluation.block_label
and missing_fields_by_label
):
@@ -3979,10 +4522,19 @@ def _record_output_contract_reject(
# The typed adjudication now owns this same deficiency. Keep the historical reject for
# ceiling/liveness evidence, but do not render it again as a fresh rejection next turn.
record_build_test_outcome(ctx, None)
- if _adjudicate_output_contract_budget(ctx, counted_paths, count=count, block_label=evaluation.block_label):
+ if not value_bearing_directive_eligible:
+ budget_terminal = _adjudicate_output_contract_budget(
+ ctx,
+ counted_paths,
+ count=count,
+ block_label=evaluation.block_label,
+ )
+ if budget_terminal:
payload["reason_code"] = _OUTPUT_CONTRACT_REJECT_BUDGET_REASON_CODE
payload["reject_reason"] = _OUTPUT_CONTRACT_REJECT_BUDGET_REASON_CODE
- if actuation is None or actuation.kind == OutputContractActuationKind.STRUCTURE_DIRECTIVE:
+ if (
+ actuation is None or actuation.kind == OutputContractActuationKind.STRUCTURE_DIRECTIVE
+ ) and not value_bearing_directive_emitted:
structural_payload = _output_contract_author_time_structural_payload(
ctx,
evaluation.required_paths,
@@ -4687,9 +5239,13 @@ def _arm_output_contract_value_bearing_directive(
workflow_yaml: str,
liveness: _OutputContractLiveness,
) -> None:
- fingerprint = _output_contract_structural_fingerprint(workflow_yaml, signature)
- already_armed = ctx.output_contract_armed_directive_fingerprint_by_signature.get(signature) == fingerprint
- _record_armed_directive_fingerprint(ctx, signature, fingerprint)
+ fingerprint = (
+ f"{_VALUE_BEARING_PREARM_FINGERPRINT_PREFIX}{_output_contract_structural_fingerprint(workflow_yaml, signature)}"
+ )
+ armed = ctx.output_contract_armed_directive_fingerprint_by_signature.get(signature)
+ already_armed = armed == fingerprint
+ if not (armed or "").startswith(_VALUE_BEARING_GUIDANCE_FINGERPRINT_PREFIX):
+ _record_armed_directive_fingerprint(ctx, signature, fingerprint)
if already_armed:
return
LOG.info(
@@ -4794,6 +5350,8 @@ def _prior_output_contract_actuation(ctx: AgentContext, signature: str) -> bool:
def _prior_output_contract_directive_unconsumed(ctx: AgentContext, signature: str, current_fingerprint: str) -> bool:
armed = ctx.output_contract_armed_directive_fingerprint_by_signature.get(signature)
+ if (armed or "").startswith(_VALUE_BEARING_PREARM_FINGERPRINT_PREFIX):
+ return False
return bool(armed) and armed == current_fingerprint
@@ -5423,15 +5981,16 @@ def _impose_output_contract_envelope_after_steering(
) -> tuple[str, object, bool]:
ctx.output_contract_bail_actuated_this_call = False
contract = _output_contract_required_paths_source(ctx)
- required_paths = contract.union
+ required_paths = set(contract.union)
+ directive_paths = _value_bearing_directive_paths(contract)
observation_paths = contract.observation_paths
declaration_paths = contract.declaration_paths
source = contract.source
reason_code = contract.reason_code
- if not required_paths:
- return workflow_yaml, raw_code_artifact_metadata, False
- signature = _output_contract_signature(ctx=ctx, required_paths=required_paths)
if contract.liveness is not _OutputContractLiveness.VALUE_REQUIRED:
+ if not directive_paths:
+ return workflow_yaml, raw_code_artifact_metadata, False
+ signature = _output_contract_signature(ctx=ctx, required_paths=directive_paths)
_arm_output_contract_value_bearing_directive(
ctx,
signature=signature,
@@ -5439,6 +5998,9 @@ def _impose_output_contract_envelope_after_steering(
liveness=contract.liveness,
)
return workflow_yaml, raw_code_artifact_metadata, False
+ if not required_paths:
+ return workflow_yaml, raw_code_artifact_metadata, False
+ signature = _output_contract_signature(ctx=ctx, required_paths=required_paths)
# The stamp precedes actuation and ignores advisory state so no
# acceptance route can persist a block that omits the declaration paths.
workflow_yaml, declaration_stamped = _stamp_declaration_contract_defaults(
@@ -5686,12 +6248,36 @@ def _metadata_contract_run_preflight_reject(
else None
)
parsed = parse_workflow_yaml(workflow_yaml)
- grounded_binding_available = (
- isinstance(ctx, AgentContext)
- and isinstance(parsed, Mapping)
- and _trajectory_with_grounded_submit_rung_binding(ctx, parsed, runtime_parameters) is not None
+ binding_resolution = (
+ _authoring_parameter_binding_resolution_for_definition(
+ ctx,
+ parsed,
+ runtime_parameters,
+ raw_code_artifact_metadata,
+ )
+ if isinstance(ctx, AgentContext) and isinstance(parsed, Mapping)
+ else None
)
- if definition_reject is not None and (enforce_untagged_declared_inputs or not grounded_binding_available):
+ binding_path_available = binding_resolution is not None and (
+ binding_resolution.snapshot is not None or binding_resolution.directive is not None
+ )
+ if definition_reject is not None and (enforce_untagged_declared_inputs or not binding_path_available):
+ definition_corrective = (
+ None
+ if copilot_author_time_gate_log_only_enabled(ctx, DEFINITION_CONTRACT_UNSATISFIED_GATE_ID)
+ else _value_bearing_definition_reject_corrective(
+ ctx,
+ workflow_yaml=workflow_yaml,
+ raw_metadata=raw_code_artifact_metadata,
+ )
+ )
+ definition_data = {
+ "reason_code": "definition_contract_unsatisfied",
+ "definition_criterion_ids": list(definition_reject.criterion_ids),
+ "definition_reason_codes": list(definition_reject.reason_codes),
+ "unreferenced_parameter_keys": list(definition_reject.unreferenced_parameter_keys),
+ **(definition_corrective or {}),
+ }
halted = _stash_unresolved_recorded_outcome_grounding_halt(
ctx,
definition_reject.unreferenced_parameter_keys,
@@ -5701,12 +6287,7 @@ def _metadata_contract_run_preflight_reject(
"ok": False,
"error": _definition_plane_reject_error(definition_reject),
"user_facing_summary": _compiled_authoring_user_summary(),
- "data": {
- "reason_code": "definition_contract_unsatisfied",
- "definition_criterion_ids": list(definition_reject.criterion_ids),
- "definition_reason_codes": list(definition_reject.reason_codes),
- "unreferenced_parameter_keys": list(definition_reject.unreferenced_parameter_keys),
- },
+ "data": definition_data,
}
if not _record_definition_plane_ablation_event(
ctx,
@@ -5724,19 +6305,14 @@ def _metadata_contract_run_preflight_reject(
"ok": False,
"error": _definition_plane_reject_error(definition_reject),
"user_facing_summary": _compiled_authoring_user_summary(),
- "data": {
- "reason_code": "definition_contract_unsatisfied",
- "definition_criterion_ids": list(definition_reject.criterion_ids),
- "definition_reason_codes": list(definition_reject.reason_codes),
- "unreferenced_parameter_keys": list(definition_reject.unreferenced_parameter_keys),
- },
+ "data": definition_data,
}
convergence_reject = _recorded_outcome_convergence_reject(
ctx,
workflow_yaml=workflow_yaml,
code_artifact_metadata=raw_code_artifact_metadata,
)
- if convergence_reject is not None and not grounded_binding_available:
+ if convergence_reject is not None and not binding_path_available:
block_labels = sorted(_workflow_yaml_code_blocks_by_label(workflow_yaml))
_record_author_time_reject_outcome(
ctx,
@@ -5812,13 +6388,19 @@ def _metadata_contract_run_preflight_reject(
return None
if evaluation.repair_context is not None:
ctx.last_code_authoring_repair_context = evaluation.repair_context
+ if _metadata_preflight_reject_yields_to_ladder(ctx):
+ return None
+ if "value_bearing_convergence_directive" in payload:
+ return _output_contract_reject_result(
+ evaluation,
+ payload=payload,
+ tool_name="update_and_run_blocks",
+ )
payload = dict(payload)
payload["output_contract_reason_code"] = payload.get("reason_code")
payload["reason_code"] = _METADATA_CONTRACT_REQUIRED_BEFORE_RUN_REASON_CODE
payload["reject_reason"] = _METADATA_CONTRACT_REQUIRED_BEFORE_RUN_REASON_CODE
block_label = evaluation.block_label or "the target output block"
- if _metadata_preflight_reject_yields_to_ladder(ctx):
- return None
return {
"ok": False,
"error": (
@@ -5835,13 +6417,23 @@ def output_contract_value_bearing_run_reject(
code_by_label: Mapping[str, str],
) -> dict[str, Any] | None:
"""Refuses dispatch of a saved workflow whose author contract is statically provably
- valueless (declaration-only, degraded-empty, or statically-all-empty); unknown stays fail-open."""
+ valueless. Observation paths stay fail-open when unknown; a root-only repair must prove its envelope."""
if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:
return None
contract = _output_contract_required_paths_source(ctx)
declaration_only_contract = bool(contract.declaration_paths) and not contract.observation_paths
- statically_valueless = contract.liveness is _OutputContractLiveness.DEGRADED_EMPTY or declaration_only_contract
- if not statically_valueless and contract.liveness is _OutputContractLiveness.VALUE_REQUIRED and code_by_label:
+ root_only_liveness_contract = (
+ contract.liveness is _OutputContractLiveness.DEGRADED_EMPTY or declaration_only_contract
+ )
+ if root_only_liveness_contract:
+ statically_valueless = not code_by_label or all(
+ _root_output_envelope_state(code) != "proven"
+ or _statically_lacks_value_bearing_observation_paths(code, {_VALUE_BEARING_ROOT_GUIDANCE_PATH})
+ for code in code_by_label.values()
+ )
+ else:
+ statically_valueless = False
+ if contract.liveness is _OutputContractLiveness.VALUE_REQUIRED and code_by_label:
statically_valueless = all(
_statically_lacks_value_bearing_observation_paths(code, contract.observation_paths)
for code in code_by_label.values()
@@ -5872,9 +6464,8 @@ def output_contract_value_bearing_run_reject(
)
elif contract.liveness is _OutputContractLiveness.DEGRADED_EMPTY or declaration_only_contract:
error = (
- "Cannot run the saved workflow: every requested value-bearing output has degraded out of "
- "the completion criteria, so no code revision can satisfy the contract. Re-establish at "
- "least one requested value-bearing output before running."
+ "Cannot run the saved workflow: its code does not prove a non-empty top-level `output` "
+ "value. Revise the owning code block to return a real value under `output` before running."
)
else:
error = (
@@ -9637,6 +10228,7 @@ def _synthesized_parameter_binding_repair_context(
parameter_keys: list[str],
scout_trajectory: list[ScoutedInteraction],
synthesized_parameters: list[dict[str, str]],
+ parameter_binding_snapshot: AuthoringParameterBindingSnapshot | None = None,
) -> CodeAuthoringRepairContext:
available_parameter_keys = sorted(_declared_string_workflow_parameter_keys(parsed))
binding_candidates = [synthesized_key] + [key for key in available_parameter_keys if key != synthesized_key]
@@ -9644,6 +10236,7 @@ def _synthesized_parameter_binding_repair_context(
synthesized_key=synthesized_key,
scout_trajectory=scout_trajectory,
synthesized_parameters=synthesized_parameters,
+ parameter_binding_snapshot=parameter_binding_snapshot,
)
selector = _safe_selector_repair_atom(matched_scout.get("selector")) if matched_scout is not None else ""
source_url = str(matched_scout.get("source_url") or "").strip() if matched_scout is not None else ""
@@ -9668,7 +10261,30 @@ def _scout_interaction_for_synthesized_parameter(
synthesized_key: str,
scout_trajectory: list[ScoutedInteraction],
synthesized_parameters: list[dict[str, str]],
+ parameter_binding_snapshot: AuthoringParameterBindingSnapshot | None = None,
) -> ScoutedInteraction | None:
+ if parameter_binding_snapshot is not None:
+ matches = [
+ binding
+ for binding in parameter_binding_snapshot.field_bindings
+ if binding.declared_key == synthesized_key and binding.field_trajectory_index is not None
+ ]
+ if len(matches) != 1:
+ return None
+ trajectory_index = matches[0].field_trajectory_index
+ if trajectory_index is None:
+ return None
+ interactions = [
+ interaction
+ for position, interaction in enumerate(scout_trajectory)
+ if _scout_trajectory_index(interaction, position) == trajectory_index
+ ]
+ if len(interactions) != 1:
+ return None
+ interaction = interactions[0]
+ if str(interaction.get("selector") or "").strip() != matches[0].field_selector:
+ return None
+ return interaction
non_credential_keys = [
str(parameter.get("key") or "").strip()
for parameter in synthesized_parameters
@@ -9694,6 +10310,7 @@ def _reconcile_synthesized_parameters(
submitted_code: str,
synthesized_parameters: list[dict[str, str]],
scout_trajectory: list[ScoutedInteraction],
+ parameter_binding_snapshot: AuthoringParameterBindingSnapshot | None = None,
) -> _SynthesizedParameterReconciliation:
workflow_definition = parsed.get("workflow_definition")
if not isinstance(workflow_definition, dict):
@@ -9740,6 +10357,7 @@ def _reconcile_synthesized_parameters(
parameter_keys=parameter_keys,
scout_trajectory=scout_trajectory,
synthesized_parameters=synthesized_parameters,
+ parameter_binding_snapshot=parameter_binding_snapshot,
)
for synthesized_param in synthesized_parameters:
@@ -9760,13 +10378,18 @@ def _reconcile_synthesized_parameters(
synthesized_key=key,
scout_trajectory=scout_trajectory,
synthesized_parameters=synthesized_parameters,
+ parameter_binding_snapshot=parameter_binding_snapshot,
)
matched_selector = str(matched_scout.get("selector") or "").strip() if matched_scout is not None else ""
- selector_join_alias = _selector_join_parameter_alias_by_authored_fill(
- parameters=parameters,
- submitted_code=submitted_code,
- synthesized_key=key,
- selector=matched_selector,
+ selector_join_alias = (
+ None
+ if parameter_binding_snapshot is not None
+ else _selector_join_parameter_alias_by_authored_fill(
+ parameters=parameters,
+ submitted_code=submitted_code,
+ synthesized_key=key,
+ selector=matched_selector,
+ )
)
if selector_join_alias is not None:
if selector_join_alias in used_selector_join_aliases:
@@ -9801,10 +10424,14 @@ def _reconcile_synthesized_parameters(
continue
if existing is not None:
- alias_key = _matching_string_parameter_key_by_default(
- parameters,
- default_value=synthesized_default,
- exclude_key=key,
+ alias_key = (
+ None
+ if parameter_binding_snapshot is not None
+ else _matching_string_parameter_key_by_default(
+ parameters,
+ default_value=synthesized_default,
+ exclude_key=key,
+ )
)
if alias_key is not None:
aliases[key] = alias_key
@@ -9836,10 +10463,14 @@ def _reconcile_synthesized_parameters(
f"Unable to bind synthesized parameter `{key}`: synthesized default looks credential-like.",
)
continue
- alias_key = _matching_string_parameter_key_by_default(
- parameters,
- default_value=synthesized_default,
- exclude_key=key,
+ alias_key = (
+ None
+ if parameter_binding_snapshot is not None
+ else _matching_string_parameter_key_by_default(
+ parameters,
+ default_value=synthesized_default,
+ exclude_key=key,
+ )
)
if alias_key is not None:
aliases[key] = alias_key
@@ -10016,6 +10647,9 @@ def _maybe_impose_synthesized_code_block(
ctx.spine_imposition_owned_attempt = False
ctx.spine_imposition_carrier_label = None
ctx.imposition_synthesized_block = None
+ ctx.authoring_parameter_binding_snapshot = None
+ if ctx.turn_origin != TurnOrigin.interactive:
+ return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)
if not getattr(ctx, "impose_synthesized_code_block", False):
return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)
if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:
@@ -10040,24 +10674,8 @@ def _maybe_impose_synthesized_code_block(
parsed = parse_workflow_yaml(workflow_yaml)
if not isinstance(parsed, dict):
return _SynthesizedCodeImpositionResult(workflow_yaml=workflow_yaml)
- grounded_trajectory = _trajectory_with_grounded_submit_rung_binding(ctx, parsed, runtime_parameters)
requirement = ctx.recorded_outcome_grounding_requirement
constraint = ctx.recorded_outcome_binding_constraint
- declared_keys = _declared_string_workflow_parameter_keys(parsed)
- if (
- grounded_trajectory is None
- and declared_keys
- and isinstance(requirement, RecordedOutcomeGroundingRequirement)
- and requirement.satisfied
- and isinstance(constraint, RecordedOutcomeBindingConstraint)
- and constraint.repeated_structural_key == requirement.structural_key
- and _stash_unresolved_recorded_outcome_grounding_halt(ctx, declared_keys)
- ):
- return _SynthesizedCodeImpositionResult(
- workflow_yaml=workflow_yaml,
- violations=["Unable to impose synthesized code block: current-page parameter binding is unresolved."],
- )
- synthesis_trajectory: Sequence[Mapping[str, Any]] = grounded_trajectory or scout_trajectory
code_blocks = _workflow_code_blocks(parsed)
prior_source, prior_yaml = _prior_yaml_source(ctx)
code_block = _select_synthesized_imposition_code_block(
@@ -10074,6 +10692,87 @@ def _maybe_impose_synthesized_code_block(
submitted_code = str(code_block.get("code") or "")
ctx.spine_imposition_carrier_label = _code_block_label(code_block)
+ definition_diagnostic = _definition_plane_preflight_reject(ctx, workflow_yaml)
+ carrier_label = _code_block_label(code_block)
+ pending_directive = _pending_authoring_parameter_binding_directive(ctx)
+ active_repair_context, prior_directive = pending_directive or (None, None)
+ if active_repair_context is not None and active_repair_context.block_label != carrier_label:
+ return _SynthesizedCodeImpositionResult(
+ workflow_yaml=workflow_yaml,
+ violations=["Unable to impose synthesized code block: stored parameter binding directive is stale."],
+ repair_context=active_repair_context,
+ )
+ declared_keys = (
+ set(definition_diagnostic.unreferenced_parameter_keys)
+ if definition_diagnostic is not None and definition_diagnostic.unreferenced_parameter_keys
+ else set(active_repair_context.unresolved_names)
+ if active_repair_context is not None
+ else set()
+ )
+ diagnostic_structural_key = (
+ prior_directive.structural_key
+ if prior_directive is not None
+ else _definition_plane_structural_key(
+ workflow_yaml,
+ definition_diagnostic,
+ ctx.raw_code_artifact_metadata,
+ )
+ if definition_diagnostic is not None
+ else ""
+ )
+ binding_resolution = (
+ _authoring_parameter_binding_resolution(
+ ctx,
+ parsed,
+ runtime_parameters,
+ unreferenced_parameter_keys=sorted(declared_keys),
+ carrier_code=submitted_code,
+ diagnostic_structural_key=diagnostic_structural_key,
+ )
+ if declared_keys
+ else _AuthoringParameterBindingResolution(None, None)
+ )
+ binding_snapshot = binding_resolution.snapshot
+ ctx.authoring_parameter_binding_snapshot = binding_snapshot
+ if prior_directive is not None and binding_snapshot is None:
+ return _SynthesizedCodeImpositionResult(
+ workflow_yaml=workflow_yaml,
+ violations=["Unable to impose synthesized code block: stored parameter binding directive is stale."],
+ repair_context=active_repair_context,
+ )
+ if binding_snapshot is None and declared_keys and binding_resolution.directive is not None:
+ binding_repair_context = CodeAuthoringRepairContext(
+ block_label=carrier_label,
+ reason_code=_SYNTHESIZED_PARAMETER_BINDING_AMBIGUOUS_REASON_CODE,
+ unresolved_names=sorted(declared_keys),
+ parameter_keys=sorted(declared_keys),
+ available_parameter_keys=sorted(_declared_string_workflow_parameter_keys(parsed)),
+ parameter_binding_directive=binding_resolution.directive,
+ repair_instruction=(
+ "Use each declared workflow key for its exact selector pair, include every key in parameter_keys, "
+ "and rerun via update_and_run_blocks."
+ ),
+ )
+ return _SynthesizedCodeImpositionResult(
+ workflow_yaml=workflow_yaml,
+ violations=["Unable to impose synthesized code block: current-page parameter binding is ambiguous."],
+ repair_context=binding_repair_context,
+ )
+ grounding_repair_active = (
+ binding_snapshot is None
+ and bool(declared_keys)
+ and isinstance(requirement, RecordedOutcomeGroundingRequirement)
+ and requirement.satisfied
+ and isinstance(constraint, RecordedOutcomeBindingConstraint)
+ and constraint.repeated_structural_key == requirement.structural_key
+ )
+ if grounding_repair_active and _stash_unresolved_recorded_outcome_grounding_halt(ctx, declared_keys):
+ return _SynthesizedCodeImpositionResult(
+ 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
+
owns_spine = reaches_goal
ctx.spine_imposition_owned_attempt = owns_spine
carrier_changed = _submitted_code_block_changed(code_block, prior_yaml)
@@ -10097,12 +10796,14 @@ def _maybe_impose_synthesized_code_block(
extraction_plan,
strict_selectors=True,
reached_download_target=ctx.reached_download_target,
+ parameter_binding_snapshot=binding_snapshot,
)
if extraction_plan is not None
else synthesize_code_block(
synthesis_trajectory,
strict_selectors=True,
reached_download_target=ctx.reached_download_target,
+ parameter_binding_snapshot=binding_snapshot,
)
)
if synthesized is None:
@@ -10287,6 +10988,7 @@ def _maybe_impose_synthesized_code_block(
submitted_code=submitted_code,
synthesized_parameters=synthesized.parameters,
scout_trajectory=scout_trajectory,
+ parameter_binding_snapshot=binding_snapshot,
)
parameter_binding_is_only_violation = not violations and bool(parameter_reconciliation.violations)
violations.extend(parameter_reconciliation.violations)
@@ -10487,6 +11189,36 @@ def _maybe_impose_synthesized_code_block(
selected_extraction_metadata_disposition = "self_authored_extraction_preserved"
elif extraction_suffix or append_selected_extraction:
selected_extraction_metadata_disposition = "sibling_or_suffix_extraction_preserved"
+ if prior_directive is not None and binding_snapshot is not None:
+ binding_artifacts: list[tuple[str, Sequence[str]]] = []
+ for final_block in _workflow_code_blocks(parsed):
+ raw_parameter_keys = final_block.get("parameter_keys")
+ final_parameter_keys = (
+ tuple(str(key) for key in raw_parameter_keys if isinstance(key, str) and key)
+ if isinstance(raw_parameter_keys, list)
+ else ()
+ )
+ binding_artifacts.append((str(final_block.get("code") or ""), final_parameter_keys))
+ if not any(
+ authoring_parameter_binding_directive_consumed(
+ prior_directive,
+ binding_snapshot,
+ code=block_code,
+ parameter_keys=block_parameter_keys,
+ )
+ for block_code, block_parameter_keys in binding_artifacts
+ ):
+ return _SynthesizedCodeImpositionResult(
+ workflow_yaml=workflow_yaml,
+ violations=["Unable to impose synthesized code block: stored parameter binding directive is stale."],
+ repair_context=active_repair_context,
+ )
+ LOG.info(
+ "copilot authoring parameter binding directive consumed",
+ binding_fingerprint=binding_snapshot.fingerprint,
+ directive_fingerprint=prior_directive.fingerprint,
+ parameter_keys=[binding.declared_key for binding in binding_snapshot.field_bindings],
+ )
if extraction_plan is not None:
LOG.info(
"copilot_requested_output_extraction_candidate_imposed",
@@ -11576,6 +12308,8 @@ async def _update_workflow(
allow_static_output_uncertainty: bool = False,
formation_prepared: bool = False,
) -> dict[str, Any]:
+ ctx.output_contract_bail_actuated_this_call = False
+
def reject(
*,
error: str,
@@ -11712,6 +12446,22 @@ async def _update_workflow(
)
definition_reject = _definition_plane_preflight_reject(ctx, workflow_yaml)
if definition_reject is not None:
+ definition_corrective = (
+ None
+ if copilot_author_time_gate_log_only_enabled(ctx, DEFINITION_CONTRACT_UNSATISFIED_GATE_ID)
+ else _value_bearing_definition_reject_corrective(
+ ctx,
+ workflow_yaml=workflow_yaml,
+ raw_metadata=ctx.raw_code_artifact_metadata,
+ )
+ )
+ definition_data = {
+ "reason_code": "definition_contract_unsatisfied",
+ "definition_criterion_ids": list(definition_reject.criterion_ids),
+ "definition_reason_codes": list(definition_reject.reason_codes),
+ "unreferenced_parameter_keys": list(definition_reject.unreferenced_parameter_keys),
+ **(definition_corrective or {}),
+ }
halted = _stash_unresolved_recorded_outcome_grounding_halt(
ctx,
definition_reject.unreferenced_parameter_keys,
@@ -11720,12 +12470,7 @@ async def _update_workflow(
return reject(
error=_definition_plane_reject_error(definition_reject),
user_facing_summary=_compiled_authoring_user_summary(),
- data={
- "reason_code": "definition_contract_unsatisfied",
- "definition_criterion_ids": list(definition_reject.criterion_ids),
- "definition_reason_codes": list(definition_reject.reason_codes),
- "unreferenced_parameter_keys": list(definition_reject.unreferenced_parameter_keys),
- },
+ data=definition_data,
)
if not _record_definition_plane_ablation_event(
ctx,
@@ -11742,12 +12487,7 @@ async def _update_workflow(
return reject(
error=_definition_plane_reject_error(definition_reject),
user_facing_summary=_compiled_authoring_user_summary(),
- data={
- "reason_code": "definition_contract_unsatisfied",
- "definition_criterion_ids": list(definition_reject.criterion_ids),
- "definition_reason_codes": list(definition_reject.reason_codes),
- "unreferenced_parameter_keys": list(definition_reject.unreferenced_parameter_keys),
- },
+ data=definition_data,
)
if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
unrenderable = _code_block_render_reject(workflow_yaml, getattr(ctx, "workflow_yaml", None))
diff --git a/tests/unit/copilot/fixtures/p3_definition_contract_reject_packets.json b/tests/unit/copilot/fixtures/p3_definition_contract_reject_packets.json
new file mode 100644
index 000000000..57ee659fc
--- /dev/null
+++ b/tests/unit/copilot/fixtures/p3_definition_contract_reject_packets.json
@@ -0,0 +1,366 @@
+{
+ "artifact_set": "copilot-status-and-amendments-2026-07-15-ce981015d2",
+ "prompt": "P3",
+ "fixture_site": "telco_apexbiz (localhost mock)",
+ "note": "Byte-exact definition_contract_unsatisfied reject packets extracted from the recorded gauntlet backend.logs. recorded_summary fields are truncated by the source logger; turn_halts carry the only complete unresolved-key lists.",
+ "runs": [
+ {
+ "run": "run1",
+ "source_log": "copilot-status-and-amendments-2026-07-15-ce981015d2/P3/run1/backend.log",
+ "workflow_permanent_id": "wpid_551759210240752682",
+ "workflow_copilot_chat_id": "wcc_551759231715589168",
+ "turn_id": "0ea14e17c78a4c5aba461a4bf875bce6",
+ "block_labels": [
+ "download_matching_invoice_pdf"
+ ],
+ "stored_rejects": [
+ {
+ "source_line": 667,
+ "timestamp": "2026-07-15T21:10:25.755544Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "0a22aed0d6523592032c0017443c21179d8e14df5f61bd29faccabda342500ad",
+ "authored_structure_signature": "2a0aa4e3998a019f1638f10c2cb1767ef9700a561be8ecf21554ae203ec61e81",
+ "raw": "2026-07-15T21:10:25.755544Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=0a22aed0d6523592032c0017443c21179d8e14df5f61bd29faccabda342500ad is_authoritative=True workflow_run_id=None authored_structure_signature=2a0aa4e3998a019f1638f10c2cb1767ef9700a561be8ecf21554ae203ec61e81 entrypoint=unknown"
+ },
+ {
+ "source_line": 704,
+ "timestamp": "2026-07-15T21:11:13.769247Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "8a23f5d48c49f2dc10c31876c38167688ddb46fe9f80c23a2039edab3ea65cee",
+ "authored_structure_signature": "6cfb1d15806cf8d3a14a2c0fb55550a1d0f0b71175ada587782d47ae8dc2faf7",
+ "raw": "2026-07-15T21:11:13.769247Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=8a23f5d48c49f2dc10c31876c38167688ddb46fe9f80c23a2039edab3ea65cee is_authoritative=True workflow_run_id=None authored_structure_signature=6cfb1d15806cf8d3a14a2c0fb55550a1d0f0b71175ada587782d47ae8dc2faf7 entrypoint=unknown"
+ },
+ {
+ "source_line": 739,
+ "timestamp": "2026-07-15T21:12:00.486376Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "0a22aed0d6523592032c0017443c21179d8e14df5f61bd29faccabda342500ad",
+ "authored_structure_signature": "2a0aa4e3998a019f1638f10c2cb1767ef9700a561be8ecf21554ae203ec61e81",
+ "raw": "2026-07-15T21:12:00.486376Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=0a22aed0d6523592032c0017443c21179d8e14df5f61bd29faccabda342500ad is_authoritative=True workflow_run_id=None authored_structure_signature=2a0aa4e3998a019f1638f10c2cb1767ef9700a561be8ecf21554ae203ec61e81 entrypoint=unknown"
+ },
+ {
+ "source_line": 772,
+ "timestamp": "2026-07-15T21:12:35.922113Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "0a22aed0d6523592032c0017443c21179d8e14df5f61bd29faccabda342500ad",
+ "authored_structure_signature": "2a0aa4e3998a019f1638f10c2cb1767ef9700a561be8ecf21554ae203ec61e81",
+ "raw": "2026-07-15T21:12:35.922113Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=0a22aed0d6523592032c0017443c21179d8e14df5f61bd29faccabda342500ad is_authoritative=True workflow_run_id=None authored_structure_signature=2a0aa4e3998a019f1638f10c2cb1767ef9700a561be8ecf21554ae203ec61e81 entrypoint=unknown"
+ }
+ ],
+ "reject_summaries": [
+ {
+ "source_line": 670,
+ "timestamp": "2026-07-15T21:10:25.759931Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `...",
+ "raw": "2026-07-15T21:10:25.759931Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `... total_tokens=570999 workflow_permanent_id=wpid_551759210240752682 turn_id=0ea14e17c78a4c5aba461a4bf875bce6 workflow_copilot_chat_id=wcc_551759231715589168 entrypoint=unknown"
+ },
+ {
+ "source_line": 711,
+ "timestamp": "2026-07-15T21:11:13.773768Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `...",
+ "raw": "2026-07-15T21:11:13.773768Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `... total_tokens=570999 workflow_permanent_id=wpid_551759210240752682 turn_id=0ea14e17c78a4c5aba461a4bf875bce6 workflow_copilot_chat_id=wcc_551759231715589168 entrypoint=unknown"
+ },
+ {
+ "source_line": 742,
+ "timestamp": "2026-07-15T21:12:00.488299Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `...",
+ "raw": "2026-07-15T21:12:00.488299Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `... total_tokens=570999 workflow_permanent_id=wpid_551759210240752682 turn_id=0ea14e17c78a4c5aba461a4bf875bce6 workflow_copilot_chat_id=wcc_551759231715589168 entrypoint=unknown"
+ },
+ {
+ "source_line": 776,
+ "timestamp": "2026-07-15T21:12:35.924560Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `...",
+ "raw": "2026-07-15T21:12:35.924560Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `... total_tokens=570999 workflow_permanent_id=wpid_551759210240752682 turn_id=0ea14e17c78a4c5aba461a4bf875bce6 workflow_copilot_chat_id=wcc_551759231715589168 entrypoint=unknown"
+ },
+ {
+ "source_line": 872,
+ "timestamp": "2026-07-15T21:14:05.779754Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `...",
+ "raw": "2026-07-15T21:14:05.779754Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `... total_tokens=570999 workflow_permanent_id=wpid_551759210240752682 turn_id=0ea14e17c78a4c5aba461a4bf875bce6 workflow_copilot_chat_id=wcc_551759231715589168 entrypoint=unknown"
+ }
+ ],
+ "turn_halts": [
+ {
+ "source_line": 864,
+ "timestamp": "2026-07-15T21:14:05.774759Z",
+ "turn_halt_verdict": "blocked",
+ "unresolved_parameter_keys": [
+ "account_number",
+ "billing_end_date",
+ "billing_start_date"
+ ],
+ "grounding_unresolved": true,
+ "source": "recorded_outcome_regrounding",
+ "raw": "2026-07-15T21:14:05.774759Z [info ] [turn_halt.py :305 ] copilot turn halt stashed [skyvern.forge.sdk.copilot.turn_halt] turn_halt_kind=definition_contract_unsatisfied turn_halt_verdict=blocked turn_halt_extra={'unresolved_parameter_keys': ['account_number', 'billing_end_date', 'billing_start_date'], 'grounding_unresolved': True, 'source': 'recorded_outcome_regrounding'} blocker_kind=tool_error recovery_hint=report_blocker_to_user cleared_by_tools=[] renders_final_reply=True internal_reason_code=definition_contract_unsatisfied blocked_tool=None classifier_mode=None exception_type=None extra={'unresolved_parameter_keys': ['account_number', 'billing_end_date', 'billing_start_date'], 'grounding_unresolved': True} entrypoint=unknown"
+ }
+ ],
+ "scouted_interactions": [
+ {
+ "source_line": 204,
+ "tool_name": "click",
+ "selector": "button.icon-btn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 0
+ },
+ {
+ "source_line": 244,
+ "tool_name": "fill_credential_field",
+ "selector": "#user",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 1
+ },
+ {
+ "source_line": 313,
+ "tool_name": "click",
+ "selector": "#contBtn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 2
+ },
+ {
+ "source_line": 425,
+ "tool_name": "fill_credential_field",
+ "selector": "#pass",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 3
+ },
+ {
+ "source_line": 465,
+ "tool_name": "click",
+ "selector": "#signinBtn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 4
+ },
+ {
+ "source_line": 609,
+ "tool_name": "click",
+ "selector": "#current-statement-row",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 5
+ }
+ ]
+ },
+ {
+ "run": "run2",
+ "source_log": "copilot-status-and-amendments-2026-07-15-ce981015d2/P3/run2/backend.log",
+ "workflow_permanent_id": "wpid_551761624012373050",
+ "workflow_copilot_chat_id": "wcc_551761645487209536",
+ "turn_id": "a95b0af1f2bb472599d908bfd34be177",
+ "block_labels": [
+ "download_matching_invoice_pdf"
+ ],
+ "stored_rejects": [
+ {
+ "source_line": 691,
+ "timestamp": "2026-07-15T21:19:36.330734Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "0ea850bd0b98bc0445c418b76b4a0d26484b865fd0edf6f46b3ebbaae5077e2c",
+ "authored_structure_signature": "d329b9cbbaa1fae0b5932217dd862b73f1ce88dafc5b32ccd999e1cfc9e2b3c2",
+ "raw": "2026-07-15T21:19:36.330734Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=0ea850bd0b98bc0445c418b76b4a0d26484b865fd0edf6f46b3ebbaae5077e2c is_authoritative=True workflow_run_id=None authored_structure_signature=d329b9cbbaa1fae0b5932217dd862b73f1ce88dafc5b32ccd999e1cfc9e2b3c2 entrypoint=unknown"
+ },
+ {
+ "source_line": 726,
+ "timestamp": "2026-07-15T21:20:12.002103Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "47bf1213538d589b34ea1a2c767e27168aeebf28122316ece6e56fb201e5e538",
+ "authored_structure_signature": "76b867325620b851d76fb1b8ab0a976265b95b7b1bf97a85e17a879297ed90e6",
+ "raw": "2026-07-15T21:20:12.002103Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=47bf1213538d589b34ea1a2c767e27168aeebf28122316ece6e56fb201e5e538 is_authoritative=True workflow_run_id=None authored_structure_signature=76b867325620b851d76fb1b8ab0a976265b95b7b1bf97a85e17a879297ed90e6 entrypoint=unknown"
+ },
+ {
+ "source_line": 757,
+ "timestamp": "2026-07-15T21:20:47.993066Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "47bf1213538d589b34ea1a2c767e27168aeebf28122316ece6e56fb201e5e538",
+ "authored_structure_signature": "76b867325620b851d76fb1b8ab0a976265b95b7b1bf97a85e17a879297ed90e6",
+ "raw": "2026-07-15T21:20:47.993066Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=47bf1213538d589b34ea1a2c767e27168aeebf28122316ece6e56fb201e5e538 is_authoritative=True workflow_run_id=None authored_structure_signature=76b867325620b851d76fb1b8ab0a976265b95b7b1bf97a85e17a879297ed90e6 entrypoint=unknown"
+ }
+ ],
+ "reject_summaries": [
+ {
+ "source_line": 698,
+ "timestamp": "2026-07-15T21:19:36.334623Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_period_end`,...",
+ "raw": "2026-07-15T21:19:36.334623Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_period_end`,... total_tokens=103944 workflow_permanent_id=wpid_551761624012373050 turn_id=a95b0af1f2bb472599d908bfd34be177 workflow_copilot_chat_id=wcc_551761645487209536 entrypoint=unknown"
+ },
+ {
+ "source_line": 729,
+ "timestamp": "2026-07-15T21:20:12.004293Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_period_end`,...",
+ "raw": "2026-07-15T21:20:12.004293Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_period_end`,... total_tokens=103944 workflow_permanent_id=wpid_551761624012373050 turn_id=a95b0af1f2bb472599d908bfd34be177 workflow_copilot_chat_id=wcc_551761645487209536 entrypoint=unknown"
+ },
+ {
+ "source_line": 761,
+ "timestamp": "2026-07-15T21:20:47.994841Z",
+ "tool_name": "update_workflow",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_period_end`,...",
+ "raw": "2026-07-15T21:20:47.994841Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_workflow ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_period_end`,... total_tokens=103944 workflow_permanent_id=wpid_551761624012373050 turn_id=a95b0af1f2bb472599d908bfd34be177 workflow_copilot_chat_id=wcc_551761645487209536 entrypoint=unknown"
+ }
+ ],
+ "turn_halts": [],
+ "scouted_interactions": [
+ {
+ "source_line": 165,
+ "tool_name": "click",
+ "selector": "button.icon-btn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 0
+ },
+ {
+ "source_line": 291,
+ "tool_name": "fill_credential_field",
+ "selector": "#user",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 1
+ },
+ {
+ "source_line": 335,
+ "tool_name": "click",
+ "selector": "#contBtn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 2
+ },
+ {
+ "source_line": 430,
+ "tool_name": "fill_credential_field",
+ "selector": "#pass",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 3
+ },
+ {
+ "source_line": 481,
+ "tool_name": "click",
+ "selector": "#signinBtn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 4
+ },
+ {
+ "source_line": 625,
+ "tool_name": "click",
+ "selector": "#current-statement-row",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 5
+ }
+ ]
+ },
+ {
+ "run": "run3",
+ "source_log": "copilot-status-and-amendments-2026-07-15-ce981015d2/P3/run3/backend.log",
+ "workflow_permanent_id": "wpid_551763415013735498",
+ "workflow_copilot_chat_id": "wcc_551763449373473872",
+ "turn_id": "c068547c7c694d4bbec6ebb551d76767",
+ "block_labels": [
+ "download_matching_invoice"
+ ],
+ "stored_rejects": [
+ {
+ "source_line": 643,
+ "timestamp": "2026-07-15T21:26:15.712587Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "e45beae88b1e162ea36d5d193bb41cb130e96e6d4f2e038cf25485cbeb4702d3",
+ "authored_structure_signature": "b4afec68ce4e36632f2b83fdda98fdc4e2c0f335264f241fc11abb63ffef48dd",
+ "raw": "2026-07-15T21:26:15.712587Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=e45beae88b1e162ea36d5d193bb41cb130e96e6d4f2e038cf25485cbeb4702d3 is_authoritative=True workflow_run_id=None authored_structure_signature=b4afec68ce4e36632f2b83fdda98fdc4e2c0f335264f241fc11abb63ffef48dd entrypoint=unknown"
+ },
+ {
+ "source_line": 691,
+ "timestamp": "2026-07-15T21:27:13.679961Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "a31619ea8653e6e40b8a23cb827919f4a9e43ab0c7f32ef6c4c3433e11038788",
+ "authored_structure_signature": "0f163c36bec7c636748540a680c6e7844fbce4e0437c34c91d6db084cce21d2d",
+ "raw": "2026-07-15T21:27:13.679961Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=a31619ea8653e6e40b8a23cb827919f4a9e43ab0c7f32ef6c4c3433e11038788 is_authoritative=True workflow_run_id=None authored_structure_signature=0f163c36bec7c636748540a680c6e7844fbce4e0437c34c91d6db084cce21d2d entrypoint=unknown"
+ },
+ {
+ "source_line": 735,
+ "timestamp": "2026-07-15T21:27:48.351068Z",
+ "reason_code": "definition_contract_unsatisfied",
+ "verdict": "authoring_rejected",
+ "structural_key": "a31619ea8653e6e40b8a23cb827919f4a9e43ab0c7f32ef6c4c3433e11038788",
+ "authored_structure_signature": "0f163c36bec7c636748540a680c6e7844fbce4e0437c34c91d6db084cce21d2d",
+ "raw": "2026-07-15T21:27:48.351068Z [info ] [build_test_outcome.py :265 ] copilot recorded build-test outcome stored [skyvern.forge.sdk.copilot.build_test_outcome] phase=author_time_reject reason_code=definition_contract_unsatisfied verdict=authoring_rejected structural_key=a31619ea8653e6e40b8a23cb827919f4a9e43ab0c7f32ef6c4c3433e11038788 is_authoritative=True workflow_run_id=None authored_structure_signature=0f163c36bec7c636748540a680c6e7844fbce4e0437c34c91d6db084cce21d2d entrypoint=unknown"
+ }
+ ],
+ "reject_summaries": [
+ {
+ "source_line": 650,
+ "timestamp": "2026-07-15T21:26:15.717864Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `...",
+ "raw": "2026-07-15T21:26:15.717864Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `... total_tokens=103992 workflow_permanent_id=wpid_551763415013735498 turn_id=c068547c7c694d4bbec6ebb551d76767 workflow_copilot_chat_id=wcc_551763449373473872 entrypoint=unknown"
+ },
+ {
+ "source_line": 694,
+ "timestamp": "2026-07-15T21:27:13.685243Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `...",
+ "raw": "2026-07-15T21:27:13.685243Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `... total_tokens=103992 workflow_permanent_id=wpid_551763415013735498 turn_id=c068547c7c694d4bbec6ebb551d76767 workflow_copilot_chat_id=wcc_551763449373473872 entrypoint=unknown"
+ },
+ {
+ "source_line": 739,
+ "timestamp": "2026-07-15T21:27:48.352756Z",
+ "tool_name": "update_and_run_blocks",
+ "recorded_summary": "Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `...",
+ "raw": "2026-07-15T21:27:48.352756Z [info ] [hooks.py :95 ] copilot tool completed [skyvern.forge.sdk.copilot.hooks] tool_name=update_and_run_blocks ok=False summary=Failed: The submitted workflow declares reusable parameters that no block references: `account_number`, `billing_end_date`, `... total_tokens=103992 workflow_permanent_id=wpid_551763415013735498 turn_id=c068547c7c694d4bbec6ebb551d76767 workflow_copilot_chat_id=wcc_551763449373473872 entrypoint=unknown"
+ }
+ ],
+ "turn_halts": [],
+ "scouted_interactions": [
+ {
+ "source_line": 150,
+ "tool_name": "click",
+ "selector": "button.icon-btn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 0
+ },
+ {
+ "source_line": 276,
+ "tool_name": "fill_credential_field",
+ "selector": "#user",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 1
+ },
+ {
+ "source_line": 320,
+ "tool_name": "click",
+ "selector": "#contBtn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 2
+ },
+ {
+ "source_line": 421,
+ "tool_name": "fill_credential_field",
+ "selector": "#pass",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 3
+ },
+ {
+ "source_line": 467,
+ "tool_name": "click",
+ "selector": "#signinBtn",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 4
+ },
+ {
+ "source_line": 611,
+ "tool_name": "click",
+ "selector": "#current-statement-row",
+ "source_url": "http://localhost:8900/telco_billing/apexbiz/",
+ "trajectory_index": 5
+ }
+ ]
+ }
+ ]
+}
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index d2260f7de..6d649895f 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -27,6 +27,10 @@ from skyvern.forge.sdk.copilot.agent import (
_synthesized_block_offer_prompt,
_verified_workflow_or_none,
)
+from skyvern.forge.sdk.copilot.authoring_parameter_binding import (
+ AuthoringParameterBindingCandidate,
+ build_authoring_parameter_binding_directive,
+)
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.build_phase import BuildPhase
from skyvern.forge.sdk.copilot.build_test_outcome import RecordedBuildTestOutcome
@@ -845,6 +849,16 @@ workflow_definition:
parameter_keys=["enter_confirmation"],
available_parameter_keys=["confirmation_number"],
binding_candidates=["enter_confirmation", "confirmation_number"],
+ parameter_binding_directive=build_authoring_parameter_binding_directive(
+ structural_key="definition-reject",
+ source_origin="https://example.com",
+ candidates=[
+ AuthoringParameterBindingCandidate(
+ declared_key="confirmation_number",
+ field_selector="#confirmation",
+ )
+ ],
+ ),
)
ctx = _ctx(
block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,
@@ -855,6 +869,8 @@ workflow_definition:
assert "reason_code: synthesized_parameter_binding_ambiguous" in prompt
assert "binding_candidates: enter_confirmation, confirmation_number" in prompt
+ assert "parameter_binding_pairs:" in prompt
+ assert "confirmation_number -> #confirmation" in prompt
assert "declare and use the exact workflow input key" in prompt
assert "include that exact key in the code block's parameter_keys" in prompt
assert "reference it as a bare Python variable in code" in prompt
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index 60241ca5c..d36361a49 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -10,8 +10,11 @@ import hashlib
import inspect
import json
import textwrap
+from collections.abc import Iterable
+from dataclasses import replace
from pathlib import Path
from types import EllipsisType, SimpleNamespace
+from typing import Any
from unittest.mock import AsyncMock, Mock
import pytest
@@ -23,10 +26,15 @@ from skyvern.forge.sdk.copilot import code_block_synthesis as code_block_synthes
from skyvern.forge.sdk.copilot import enforcement as enforcement_module
from skyvern.forge.sdk.copilot import request_policy as request_policy_module
from skyvern.forge.sdk.copilot import tools as tools_module
+from skyvern.forge.sdk.copilot.authoring_parameter_binding import (
+ AuthoringParameterBindingDirective,
+ authored_selector_parameter_bindings,
+)
from skyvern.forge.sdk.copilot.blocker_signal import (
CREDENTIAL_SCOUT_VERIFY_REPLY,
CopilotToolBlockerSignal,
assert_clean_user_facing_text,
+ build_definition_contract_unsatisfied_blocker_signal,
)
from skyvern.forge.sdk.copilot.build_test_outcome import (
BuildTestOutcomeReasonCode,
@@ -112,6 +120,7 @@ from skyvern.forge.sdk.copilot.turn_halt import (
_kind_for_blocker_signal,
stash_repair_ceiling_turn_halt,
)
+from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
from skyvern.forge.sdk.copilot.workflow_credential_utils import parse_workflow_yaml, workflow_blocks
from skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetected
from skyvern.forge.sdk.workflow.models.block import CodeBlock
@@ -1313,6 +1322,49 @@ class TestCodeSafetySeam:
assert ctx.last_code_authoring_repair_context != _stale_unresolved_repair_context()
+def _live_root_value_bearing_ctx() -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.turn_id = "t-live-root-value-bearing-directive"
+ ctx.scout_trajectory = []
+ ctx.request_policy = RequestPolicy(
+ request_slot_failure_kind="invalid_anchor_correction",
+ completion_criteria=[
+ CompletionCriterion(
+ id="3362dc25307750ce8cfcc05e3459f621874ba48d0a4500fbdd67f95d84cace37",
+ outcome="A visible manual-service path is returned as a blocker.",
+ output_path="output.blocker",
+ contingent_on="the site exposes only a manual-service path",
+ contingent_antecedent_output_path="output.blocker",
+ antecedent_family="blocker",
+ ),
+ *[
+ CompletionCriterion(
+ id=f"slot_{index}",
+ outcome=f"The returned record includes slot {index}.",
+ output_path="output",
+ antecedent_family="undecidable",
+ request_slot_id=f"slot_{index}",
+ pinability="unpinnable",
+ mint_disposition="degraded",
+ mint_degrade="undecidable_judgment",
+ requested_output_floor_rekeyed=True,
+ floor_rekeyed_from_path=path,
+ )
+ for index, path in enumerate(
+ (
+ "output.confirmation_number",
+ "output.account_number",
+ "output.selected_start_date",
+ "output.deposit_amount",
+ "output.next_owner",
+ )
+ )
+ ],
+ ],
+ )
+ return ctx
+
+
class TestCodeRepairProgressClassification:
def test_output_safety_clamp_byte_parity(self) -> None:
source = inspect.getsource(workflow_update_module._extraction_code_with_required_static_return)
@@ -1425,768 +1477,1040 @@ class TestCodeRepairProgressClassification:
assert f'page.locator("{selector}").fill(str({key}))' in code
assert code.index(f'page.locator("{selector}").fill') < code.index('page.locator("#submit").click()')
+ def test_recut_binding_is_inert_for_runtime_self_heal(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _definition_contract_ctx()
+ _enable_imposition(ctx)
+ ctx.turn_origin = TurnOrigin.runtime_self_heal
+ ctx.authoring_parameter_binding_snapshot = Mock()
+ monkeypatch.setattr(
+ workflow_update_module,
+ "_authoring_parameter_binding_resolution",
+ Mock(side_effect=AssertionError("runtime self-heal must not resolve authoring bindings")),
+ )
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(
+ _UNREFERENCED_DEFINITION_YAML,
+ ctx,
+ runtime_parameters={"business_name": "Example Co"},
+ )
+
+ assert result.workflow_yaml == _UNREFERENCED_DEFINITION_YAML
+ assert result.violations == []
+ assert result.substitutions is None
+ assert ctx.authoring_parameter_binding_snapshot is None
+
@pytest.mark.asyncio
- async def test_public_update_and_run_consumes_regrounding_in_synthesis(
- self, monkeypatch: pytest.MonkeyPatch
+ @pytest.mark.parametrize("terminal_tool", ["click", "press_key"])
+ async def test_recut_binding_scopes_to_unreferenced_keys_and_rebinds_captured_fills(
+ self, monkeypatch: pytest.MonkeyPatch, terminal_tool: str
) -> None:
_stub_successful_update(monkeypatch)
ctx = _definition_contract_ctx()
_enable_imposition(ctx)
- monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
- monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
- initial_arguments = json.dumps(
- {
- "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
- "block_labels": ["submit_service_request"],
- }
+ submitted = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: account_reference, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: []
+ code: |
+ await page.locator("#open").click()
+ await page.locator("#submit").click()
+ - block_type: code
+ label: retain_account_reference
+ parameter_keys: [account_reference]
+ code: |
+ return {"account_reference": account_reference}
+ """
)
- for _ in range(2):
- result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- initial_arguments,
- )
- assert json.loads(result)["data"]["reason_code"] == "definition_contract_unsatisfied"
- requirement = ctx.recorded_outcome_grounding_requirement
- assert requirement is not None
- assert requirement.phase == "author_time_reject"
source_url = "https://example.com/utility"
ctx.scout_trajectory = [
{"tool_name": "click", "selector": "#open", "source_url": source_url, "trajectory_index": 0},
{"tool_name": "click", "selector": "#submit", "source_url": source_url, "trajectory_index": 1},
]
- runtime_parameters = {
+ for _ in range(2):
+ assert (await _update_workflow({"workflow_yaml": submitted}, ctx))["ok"] is False
+ assert arm_recorded_outcome_grounding_requirement(ctx) is not None
+ values = {
"business_name": "Example Co",
"contact_email": "[email protected]",
"service_address": "1 Example Way",
"desired_start_date": "2026-08-01",
+ "account_reference": "account-1",
}
+ selectors = {
+ "business_name": "#company",
+ "contact_email": "#email",
+ "service_address": "#address",
+ "desired_start_date": "#date",
+ }
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "type_text",
+ "selector": selector,
+ "source_url": source_url,
+ "typed_length": len(values[key]),
+ "trajectory_index": index,
+ }
+ for index, (key, selector) in enumerate(selectors.items())
+ ]
+ terminal_selector = "#submit" if terminal_tool == "click" else "#date"
+ terminal_interaction = {
+ "tool_name": terminal_tool,
+ "selector": terminal_selector,
+ "source_url": source_url,
+ "trajectory_index": len(ctx.scout_trajectory),
+ }
+ if terminal_tool == "press_key":
+ terminal_interaction["key"] = "Enter"
+ ctx.scout_trajectory.append(terminal_interaction)
ctx.composition_page_evidence = {
"source_tool": "inspect_page_for_composition",
"current_url": source_url,
- "page_title": "Utility request",
"forms": [
{
- "fields": [
- {"selector": "#company", "value": runtime_parameters["business_name"]},
- {"selector": "#email", "value": runtime_parameters["contact_email"]},
- {"selector": "#address", "value": runtime_parameters["service_address"]},
- {"selector": "#date", "value": runtime_parameters["desired_start_date"]},
- ],
- "submit_controls": [{"selector": "#submit"}],
+ "fields": [{"selector": selector, "value": values[key]} for key, selector in selectors.items()],
+ "submit_controls": [{"selector": "#submit"}] if terminal_tool == "click" else [],
}
],
- "navigation_targets": [],
- "result_containers": [],
- "challenge_controls": [],
- "anti_bot_indicators": [],
- "observed_after_workflow_run": False,
}
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
- async def _no_prior_definition(_ctx: CopilotContext) -> None:
- return None
-
- dispatched_candidates: list[str] = []
-
- async def _run(_params: object, run_ctx: CopilotContext, **_kwargs: object) -> dict[str, object]:
- dispatched_candidates.append(run_ctx.workflow_yaml or "")
- return {"ok": False, "error": "stop after exact candidate"}
-
- async def _verification(*_args: object, **_kwargs: object) -> None:
- return None
-
- monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", _no_prior_definition)
- monkeypatch.setattr(tools_module, "_plan_frontier", lambda *_args: (["submit_service_request"], {}, None))
- monkeypatch.setattr(tools_module, "_frontier_run_size_error", lambda *_args: None)
- monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _run)
- monkeypatch.setattr(tools_module, "_verify_and_record_run_blocks_result", _verification)
- monkeypatch.setattr(tools_module, "_tool_visible_result_after_completion_verification", lambda _c, r, _v: r)
- with capture_logs() as logs:
- await tools_module.update_and_run_blocks_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- json.dumps(
- {
- "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
- "block_labels": ["submit_service_request"],
- "parameters": runtime_parameters,
- }
- ),
- )
+ result = await _update_workflow(
+ {"workflow_yaml": submitted, "parameters": values},
+ ctx,
+ allow_missing_credentials=True,
+ )
- bound = next(log for log in logs if log["event"] == "copilot recorded outcome submit rung bound")
- consumed = next(
- log for log in logs if log["event"] == "copilot recorded outcome binding consumed by synthesizer"
+ assert result["ok"] is True
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ assert isinstance(parsed, dict)
+ block = next(block for block in workflow_blocks(parsed) if block.get("label") == "submit_service_request")
+ code = str(block["code"])
+ assert block["parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "service_address",
+ "desired_start_date",
+ ]
+ assert "account_reference" not in block["parameter_keys"]
+ terminal_call = (
+ 'page.locator("#submit").click()' if terminal_tool == "click" else 'page.locator("#date").press("Enter")'
)
- assert consumed["binding_fingerprints"] == [bound["binding_fingerprint"]]
- code = str(_single_code_block(parse_workflow_yaml(ctx.workflow_yaml))["code"])
- assert 'page.locator("#company").fill(str(business_name))' in code
- assert 'page.locator("#date").fill(str(desired_start_date))' in code
- assert dispatched_candidates == [ctx.workflow_yaml]
- assert workflow_update_module._definition_plane_preflight_reject(ctx, dispatched_candidates[0]) is None
+ for key, selector in selectors.items():
+ fill = f'page.locator("{selector}").fill(str({key}))'
+ assert code.count(fill) == 1
+ assert code.index(fill) < code.index(terminal_call)
+ assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is None
@pytest.mark.asyncio
- async def test_recut_unbindable_regrounding_halts_before_reauthor(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ async def test_corrective_pass_satisfies_definition_and_scouted_spine_gates_jointly(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
_stub_successful_update(monkeypatch)
ctx = _definition_contract_ctx()
_enable_imposition(ctx)
for _ in range(2):
assert (await _update_workflow({"workflow_yaml": _UNREFERENCED_DEFINITION_YAML}, ctx))["ok"] is False
assert arm_recorded_outcome_grounding_requirement(ctx) is not None
- ctx.blocker_signal = ctx.turn_halt = ctx.turn_ownership = None
+ source_url = "https://example.com/utility"
+ values = {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ }
+ selectors = {
+ "business_name": "#company",
+ "contact_email": "#email",
+ "service_address": "#address",
+ "desired_start_date": "#date",
+ }
ctx.scout_trajectory = [
- {"tool_name": "click", "selector": "#submit", "source_url": "https://example.com/utility"}
+ {
+ "tool_name": "type_text",
+ "selector": selector,
+ "source_url": source_url,
+ "typed_length": len(values[key]),
+ "trajectory_index": index,
+ }
+ for index, (key, selector) in enumerate(selectors.items())
]
+ ctx.scout_trajectory.append(
+ {
+ "tool_name": "click",
+ "selector": "#submit",
+ "source_url": source_url,
+ "trajectory_index": len(ctx.scout_trajectory),
+ }
+ )
+ assert enforcement_module.synthesized_trajectory_reaches_goal(ctx) is True
ctx.composition_page_evidence = {
"source_tool": "inspect_page_for_composition",
- "current_url": "https://example.com/utility",
- "forms": [],
+ "current_url": source_url,
+ "forms": [
+ {
+ "fields": [{"selector": selector, "value": values[key]} for key, selector in selectors.items()],
+ "submit_controls": [{"selector": "#submit"}],
+ }
+ ],
}
assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
- synthesize = Mock(side_effect=AssertionError("must halt before an identical re-author"))
- monkeypatch.setattr(workflow_update_module, "synthesize_code_block_with_extraction", synthesize)
- result = workflow_update_module._maybe_impose_synthesized_code_block(
- _UNREFERENCED_DEFINITION_YAML,
+ result = await _update_workflow(
+ {"workflow_yaml": _UNREFERENCED_DEFINITION_YAML, "parameters": values},
ctx,
- {
- "business_name": "Example Co",
- "contact_email": "[email protected]",
- "service_address": "1 Example Way",
- "desired_start_date": "2026-08-01",
- },
+ allow_missing_credentials=True,
)
- assert result.workflow_yaml == _UNREFERENCED_DEFINITION_YAML
- assert result.violations
- synthesize.assert_not_called()
- assert ctx.blocker_signal.extra["unresolved_parameter_keys"] == [
- "business_name",
- "contact_email",
- "desired_start_date",
- "service_address",
- ]
- assert "safely connect the current page fields" in ctx.blocker_signal.user_facing_reason
+ assert result["ok"] is True
+ assert ctx.spine_imposition_owned_attempt is True
+ assert enforcement_module._scouted_spine_open_obligation(ctx) == []
+ assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is None
+ code = str(_single_code_block(parse_workflow_yaml(ctx.workflow_yaml))["code"])
+ for key, selector in selectors.items():
+ assert code.count(f'page.locator("{selector}").fill(str({key}))') == 1
+ assert 'page.locator("#submit").click()' in code
@pytest.mark.asyncio
- async def test_public_update_and_run_halts_active_author_reject_before_third_identical_author(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
+ async def test_recut_fill_captured_after_terminal_is_not_imposed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _definition_contract_ctx()
_enable_imposition(ctx)
- monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
- monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
- arguments = json.dumps(
- {
- "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
- "block_labels": ["submit_service_request"],
- "parameters": {
- "business_name": "Example Co",
- "contact_email": "[email protected]",
- "service_address": "1 Example Way",
- "desired_start_date": "2026-08-01",
- },
- }
+ source_url = "https://example.com/form"
+ runtime_parameters = {"business_name": "Example Co", "contact_email": "[email protected]"}
+ rejected_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: []
+ code: |
+ await page.locator("#submit").click()
+ """
)
- for _ in range(2):
- result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- arguments,
- )
- assert json.loads(result)["data"]["reason_code"] == "definition_contract_unsatisfied"
- requirement = ctx.recorded_outcome_grounding_requirement
- assert requirement is not None
- assert requirement.phase == "author_time_reject"
- active_structural_key = requirement.structural_key
- ctx.blocker_signal = ctx.turn_halt = ctx.turn_ownership = None
ctx.scout_trajectory = [
- {"tool_name": "click", "selector": "#submit", "source_url": "https://example.com/utility"}
- ]
- ctx.composition_page_evidence = {
- "source_tool": "inspect_page_for_composition",
- "current_url": "https://example.com/utility",
- "forms": [],
- "observed_after_workflow_run": False,
- }
- result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- arguments,
+ {
+ "tool_name": "type_text",
+ "selector": "#company",
+ "source_url": source_url,
+ "typed_length": 10,
+ "trajectory_index": 0,
+ },
+ {"tool_name": "click", "selector": "#submit", "source_url": source_url, "trajectory_index": 1},
+ {
+ "tool_name": "type_text",
+ "selector": "#email",
+ "source_url": source_url,
+ "typed_length": 15,
+ "trajectory_index": 2,
+ },
+ ]
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": source_url,
+ "forms": [
+ {
+ "fields": [
+ {"selector": "#company", "value": runtime_parameters["business_name"]},
+ {"selector": "#email", "value": runtime_parameters["contact_email"]},
+ ],
+ "submit_controls": [{"selector": "#submit"}],
+ }
+ ],
+ }
+
+ result = await _update_workflow(
+ {"workflow_yaml": rejected_yaml, "parameters": runtime_parameters},
+ ctx,
+ allow_missing_credentials=True,
)
- assert json.loads(result)["ok"] is False
- assert ctx.latest_recorded_build_test_outcome.structural_key == active_structural_key
- assert ctx.blocker_signal.internal_reason_code == "definition_contract_unsatisfied"
- assert ctx.blocker_signal.extra["unresolved_parameter_keys"] == [
- "business_name",
- "contact_email",
- "desired_start_date",
- "service_address",
- ]
- assert ctx.turn_halt is not None
- assert ctx.turn_halt.kind.value == "definition_contract_unsatisfied"
+ assert result["ok"] is False
+ directive = ctx.last_code_authoring_repair_context
+ assert directive is not None
+ assert directive.parameter_binding_directive is not None
@pytest.mark.asyncio
- async def test_definition_reject_stays_repairable_at_both_exact_gates(
+ async def test_recut_ambiguous_field_binding_returns_value_free_typed_directive(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
_stub_successful_update(monkeypatch)
- update_ctx = _definition_contract_ctx()
-
- update_result = await _update_workflow({"workflow_yaml": _UNREFERENCED_DEFINITION_YAML}, update_ctx)
-
- assert update_result["ok"] is False
- assert update_result["data"]["unreferenced_parameter_keys"] == [
- "business_name",
- "contact_email",
- "desired_start_date",
- "service_address",
+ ctx = _definition_contract_ctx()
+ _enable_imposition(ctx)
+ for _ in range(2):
+ assert (await _update_workflow({"workflow_yaml": _UNREFERENCED_DEFINITION_YAML}, ctx))["ok"] is False
+ assert arm_recorded_outcome_grounding_requirement(ctx) is not None
+ source_url = "https://example.com/utility"
+ runtime_parameters = {
+ "business_name": "duplicate-value",
+ "contact_email": "duplicate-value",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ }
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#submit", "source_url": source_url, "trajectory_index": 0}
]
- assert update_ctx.blocker_signal is None
- assert update_ctx.turn_halt is None
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": source_url,
+ "forms": [
+ {
+ "fields": [
+ {"selector": "#company", "value": "duplicate-value"},
+ {"selector": "#email", "value": "duplicate-value"},
+ {"selector": "#address", "value": "1 Example Way"},
+ {"selector": "#date", "value": "2026-08-01"},
+ ],
+ "submit_controls": [{"selector": "#submit"}],
+ }
+ ],
+ }
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
- dispatch_ctx = _definition_contract_ctx()
- dispatch_result = workflow_update_module._metadata_contract_run_preflight_reject(
- dispatch_ctx,
- _UNREFERENCED_DEFINITION_YAML,
- [],
+ result = await _update_workflow(
+ {"workflow_yaml": _UNREFERENCED_DEFINITION_YAML, "parameters": runtime_parameters},
+ ctx,
)
- assert dispatch_result is not None
- assert dispatch_result["ok"] is False
- assert dispatch_result["data"]["reason_code"] == "definition_contract_unsatisfied"
- assert dispatch_ctx.blocker_signal is None
- assert dispatch_ctx.turn_halt is None
+ assert result["ok"] is False
+ repair_context = result["data"]["authoring_repair_context"]
+ directive = repair_context["parameter_binding_directive"]
+ assert directive["structural_key"] == ctx.recorded_outcome_binding_constraint.repeated_structural_key
+ assert {tuple(candidate.values()) for candidate in directive["candidates"]} >= {
+ ("business_name", "#company"),
+ ("business_name", "#email"),
+ ("contact_email", "#company"),
+ ("contact_email", "#email"),
+ }
+ assert "duplicate-value" not in str(directive)
+ assert source_url not in str(directive)
+ assert ctx.turn_halt is None
@pytest.mark.asyncio
- async def test_public_update_and_run_definition_reject_returns_to_repair_loop(
+ async def test_recut_typed_directive_is_consumed_by_next_exact_authored_binding(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _definition_contract_ctx()
+ _enable_imposition(ctx)
monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
- arguments = json.dumps(
- {
- "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
- "block_labels": ["submit_service_request"],
- }
+ source_url = "https://example.com/directory"
+ runtime_parameters = {
+ "address_city_county_or_zip_code": "duplicate-value",
+ "contact_name": "duplicate-value",
+ }
+ rejected_yaml = _yaml(
+ """
+ title: Search directory
+ workflow_definition:
+ parameters:
+ - parameter_type: workflow
+ key: address_city_county_or_zip_code
+ workflow_parameter_type: string
+ - parameter_type: workflow
+ key: contact_name
+ workflow_parameter_type: string
+ blocks:
+ - block_type: code
+ label: search_directory
+ parameter_keys: []
+ code: |
+ await page.locator("#submit").click()
+ """
)
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#submit", "source_url": source_url, "trajectory_index": 0}
+ ]
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": source_url,
+ "forms": [
+ {
+ "fields": [
+ {"selector": "#search_location", "value": "duplicate-value"},
+ {"selector": "#contact_name", "value": "duplicate-value"},
+ ],
+ "submit_controls": [{"selector": "#submit"}],
+ }
+ ],
+ }
- for _ in range(2):
- result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ first_result = json.loads(
+ await tools_module.update_and_run_blocks_tool.on_invoke_tool(
SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- arguments,
+ json.dumps(
+ {
+ "workflow_yaml": rejected_yaml,
+ "block_labels": ["search_directory"],
+ "parameters": runtime_parameters,
+ }
+ ),
)
-
- parsed = json.loads(result)
- assert parsed["ok"] is False
- assert parsed["data"]["reason_code"] == "definition_contract_unsatisfied"
- assert ctx.blocker_signal is None
- assert ctx.turn_halt is None
-
- assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
- assert ctx.latest_recorded_build_test_outcome.reason_code == "definition_contract_unsatisfied"
- assert ctx.recorded_outcome_grounding_requirement is not None
-
- third_result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- arguments,
)
- assert json.loads(third_result)["ok"] is False
- assert ctx.blocker_signal.internal_reason_code == "recorded_outcome_grounding_required"
-
- @pytest.mark.asyncio
- @pytest.mark.parametrize("grounded_binding_available", [False, True])
- async def test_public_update_and_run_rejects_unbound_declared_inputs_without_definition_tag(
- self,
- monkeypatch: pytest.MonkeyPatch,
- grounded_binding_available: bool,
- ) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _code_only_ctx()
- ctx.request_policy = RequestPolicy(
- completion_criteria=[CompletionCriterion(id="run", outcome="The service request is submitted.")]
+ assert first_result["ok"] is False
+ directive = ctx.last_code_authoring_repair_context
+ assert directive is not None
+ assert directive.parameter_binding_directive is not None
+ authored_yaml = rejected_yaml.replace(
+ 'parameter_keys: []\n code: |\n await page.locator("#submit").click()',
+ "parameter_keys: [address_city_county_or_zip_code, contact_name]\n"
+ " code: |\n"
+ ' await page.locator("#search_location").fill(str(address_city_county_or_zip_code))\n'
+ ' await page.locator("#contact_name").fill(str(contact_name))\n'
+ ' await page.locator("#submit").click()',
)
- monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
- monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
- dispatched = False
- updated = False
- real_update = tools_module._update_workflow
+ stale_source_url = "https://other.example/directory"
+ ctx.scout_trajectory[0]["source_url"] = stale_source_url
+ ctx.composition_page_evidence["current_url"] = stale_source_url
- async def _observed_update(*args: object, **kwargs: object) -> dict[str, object]:
- nonlocal updated
- result = await real_update(*args, **kwargs)
- updated = bool(result.get("ok"))
- return result
+ stale_result = await _update_workflow(
+ {"workflow_yaml": authored_yaml, "parameters": runtime_parameters},
+ ctx,
+ allow_missing_credentials=True,
+ )
- async def _unexpected_dispatch(*_args: object, **_kwargs: object) -> dict[str, object]:
- nonlocal dispatched
- dispatched = True
- return {"ok": True}
+ assert stale_result["ok"] is False
+ assert "stored parameter binding directive is stale" in stale_result["error"]
+ ctx.scout_trajectory[0]["source_url"] = source_url
+ ctx.composition_page_evidence["current_url"] = source_url
- monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _unexpected_dispatch)
- monkeypatch.setattr(tools_module, "_update_workflow", _observed_update)
- if grounded_binding_available:
- monkeypatch.setattr(
- workflow_update_module,
- "_trajectory_with_grounded_submit_rung_binding",
- lambda *_args, **_kwargs: [{"tool_name": "click", "selector": "#submit"}],
+ with capture_logs() as logs:
+ second_result = await _update_workflow(
+ {"workflow_yaml": authored_yaml, "parameters": runtime_parameters},
+ ctx,
+ allow_missing_credentials=True,
)
- result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- json.dumps(
- {
- "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
- "block_labels": ["submit_service_request"],
- }
- ),
- )
-
- parsed = json.loads(result)
- assert parsed["ok"] is False
- assert parsed["data"]["reason_code"] == "definition_contract_unsatisfied"
- assert parsed["data"]["unreferenced_parameter_keys"] == [
- "business_name",
- "contact_email",
- "desired_start_date",
- "service_address",
- ]
- assert updated is True
- assert dispatched is False
+ assert second_result["ok"] is True
+ assert any(log["event"] == "copilot authoring parameter binding directive consumed" for log in logs)
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ block = _single_code_block(parsed)
+ assert block["parameter_keys"] == ["address_city_county_or_zip_code", "contact_name"]
+ code = str(block["code"])
+ assert code.count('page.locator("#search_location").fill(str(address_city_county_or_zip_code))') == 1
+ assert code.count('page.locator("#contact_name").fill(str(contact_name))') == 1
+ assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is None
@pytest.mark.asyncio
- async def test_public_initial_preflight_preserves_code_safety_precedence_for_untagged_inputs(
+ async def test_public_update_and_run_consumes_regrounding_in_synthesis(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
- ctx = _code_only_ctx()
- ctx.request_policy = RequestPolicy(
- completion_criteria=[CompletionCriterion(id="run", outcome="The service request is submitted.")]
- )
- unsafe_yaml = _UNREFERENCED_DEFINITION_YAML.replace(
- 'await page.locator("#open").click()',
- 'import requests\n await page.locator("#open").click()',
- )
+ _stub_successful_update(monkeypatch)
+ ctx = _definition_contract_ctx()
+ _enable_imposition(ctx)
monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
-
- result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- json.dumps({"workflow_yaml": unsafe_yaml, "block_labels": ["submit_service_request"]}),
+ initial_arguments = json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ }
)
+ for _ in range(2):
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ initial_arguments,
+ )
+ assert json.loads(result)["data"]["reason_code"] == "definition_contract_unsatisfied"
+ requirement = ctx.recorded_outcome_grounding_requirement
+ assert requirement is not None
+ assert requirement.phase == "author_time_reject"
+ source_url = "https://example.com/utility"
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#open", "source_url": source_url, "trajectory_index": 0},
+ {"tool_name": "click", "selector": "#submit", "source_url": source_url, "trajectory_index": 1},
+ ]
+ runtime_parameters = {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ }
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": source_url,
+ "page_title": "Utility request",
+ "forms": [
+ {
+ "fields": [
+ {"selector": "#company", "value": runtime_parameters["business_name"]},
+ {"selector": "#email", "value": runtime_parameters["contact_email"]},
+ {"selector": "#address", "value": runtime_parameters["service_address"]},
+ {"selector": "#date", "value": runtime_parameters["desired_start_date"]},
+ ],
+ "submit_controls": [{"selector": "#submit"}],
+ }
+ ],
+ "navigation_targets": [],
+ "result_containers": [],
+ "challenge_controls": [],
+ "anti_bot_indicators": [],
+ "observed_after_workflow_run": False,
+ }
- parsed = json.loads(result)
- assert parsed["ok"] is False
- assert parsed.get("data", {}).get("reason_code") != "definition_contract_unsatisfied"
- assert "sandbox safety check" in parsed["error"]
-
- def test_recut_dispatch_controls_preserve_passing_and_zero_input_candidates(self) -> None:
- ctx = _definition_contract_ctx()
- ctx.output_contract_actuation_by_signature["p5-advisory"] = OutputContractAdvisoryState.GRANTED
-
- result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, _UNREFERENCED_DEFINITION_YAML, [])
-
- assert result is not None
- assert result["data"]["reason_code"] == "definition_contract_unsatisfied"
- assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
- assert ctx.blocker_signal is None
- assert ctx.turn_halt is None
-
- passing_yaml = _yaml(
- """
- title: Submit reusable service request
- workflow_definition:
- parameters:
- - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
- - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
- - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
- blocks:
- - block_type: code
- label: submit_service_request
- parameter_keys: [business_name, contact_email, service_address, desired_start_date]
- code: |
- await page.locator("#company").fill(str(business_name))
- await page.locator("#email").fill(str(contact_email))
- await page.locator("#address").fill(str(service_address))
- await page.locator("#date").fill(str(desired_start_date))
- await page.locator("#submit").click()
- """
- )
- passing_ctx = _definition_contract_ctx()
- assert workflow_update_module._metadata_contract_run_preflight_reject(passing_ctx, passing_yaml, []) is None
+ async def _no_prior_definition(_ctx: CopilotContext) -> None:
+ return None
- zero_input_ctx = _code_only_ctx()
- zero_input_ctx.request_policy = RequestPolicy(
- completion_criteria=[CompletionCriterion(id="run", outcome="The request is submitted.")]
- )
- zero_input_yaml = _yaml(
- """
- title: Open status page
- workflow_definition:
- parameters: []
- blocks:
- - block_type: code
- label: open_status
- parameter_keys: []
- code: |
- await page.goto("https://example.com/status")
- """
- )
- assert (
- workflow_update_module._metadata_contract_run_preflight_reject(zero_input_ctx, zero_input_yaml, []) is None
+ dispatched_candidates: list[str] = []
+
+ async def _run(_params: object, run_ctx: CopilotContext, **_kwargs: object) -> dict[str, object]:
+ dispatched_candidates.append(run_ctx.workflow_yaml or "")
+ return {"ok": False, "error": "stop after exact candidate"}
+
+ async def _verification(*_args: object, **_kwargs: object) -> None:
+ return None
+
+ monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", _no_prior_definition)
+ monkeypatch.setattr(tools_module, "_plan_frontier", lambda *_args: (["submit_service_request"], {}, None))
+ monkeypatch.setattr(tools_module, "_frontier_run_size_error", lambda *_args: None)
+ monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _run)
+ monkeypatch.setattr(tools_module, "_verify_and_record_run_blocks_result", _verification)
+ monkeypatch.setattr(tools_module, "_tool_visible_result_after_completion_verification", lambda _c, r, _v: r)
+ with capture_logs() as logs:
+ await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ "parameters": runtime_parameters,
+ }
+ ),
+ )
+
+ bound = next(log for log in logs if log["event"] == "copilot recorded outcome submit rung bound")
+ consumed = next(
+ log for log in logs if log["event"] == "copilot recorded outcome binding consumed by synthesizer"
)
+ assert consumed["binding_fingerprints"] == [bound["binding_fingerprint"]]
+ code = str(_single_code_block(parse_workflow_yaml(ctx.workflow_yaml))["code"])
+ assert 'page.locator("#company").fill(str(business_name))' in code
+ assert 'page.locator("#date").fill(str(desired_start_date))' in code
+ assert dispatched_candidates == [ctx.workflow_yaml]
+ assert workflow_update_module._definition_plane_preflight_reject(ctx, dispatched_candidates[0]) is None
- def test_definition_preflight_rejects_partial_parameter_references(self) -> None:
+ @pytest.mark.asyncio
+ async def test_public_update_and_run_consumes_existing_page_binding_before_definition_reject(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _definition_contract_ctx()
- partially_referenced_yaml = _yaml(
- """
- title: Submit reusable service request
- workflow_definition:
- parameters:
- - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
- - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
- - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
- blocks:
- - block_type: code
- label: submit_service_request
- parameter_keys: [business_name]
- code: |
- await page.locator("#company").fill(str(business_name))
- await page.locator("#submit").click()
- """
- )
+ _enable_imposition(ctx)
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ source_url = "https://example.com/utility"
+ runtime_parameters = {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ }
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "type_text",
+ "selector": "#company",
+ "source_url": source_url,
+ "typed_length": 10,
+ "trajectory_index": 0,
+ },
+ {
+ "tool_name": "type_text",
+ "selector": "#email",
+ "source_url": source_url,
+ "typed_length": 15,
+ "trajectory_index": 1,
+ },
+ {"tool_name": "click", "selector": "#submit", "source_url": source_url, "trajectory_index": 2},
+ ]
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": source_url,
+ "forms": [
+ {
+ "fields": [
+ {"selector": "#company", "value": runtime_parameters["business_name"]},
+ {"selector": "#email", "value": runtime_parameters["contact_email"]},
+ {"selector": "#address", "value": runtime_parameters["service_address"]},
+ {"selector": "#date", "value": runtime_parameters["desired_start_date"]},
+ ],
+ "submit_controls": [{"selector": "#submit"}],
+ }
+ ],
+ }
- result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, partially_referenced_yaml, [])
+ async def _no_prior_definition(_ctx: CopilotContext) -> None:
+ return None
- assert result is not None
- assert result["data"]["unreferenced_parameter_keys"] == [
- "contact_email",
- "desired_start_date",
- "service_address",
- ]
+ dispatched_candidates: list[str] = []
- def test_definition_preflight_ignores_parameter_names_in_comments_and_string_literals(self) -> None:
- ctx = _definition_contract_ctx()
- lexical_only_yaml = _yaml(
- """
- title: Submit reusable service request
- workflow_definition:
- parameters:
- - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
- - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
- - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
- blocks:
- - block_type: code
- label: submit_service_request
- parameter_keys: [business_name, contact_email, service_address, desired_start_date]
- code: |
- # contact_email and service_address are not executable references.
- note = "desired_start_date"
- await page.locator("#company").fill(str(business_name))
- await page.locator("#submit").click()
- """
- )
+ async def _run(_params: object, run_ctx: CopilotContext, **_kwargs: object) -> dict[str, object]:
+ dispatched_candidates.append(run_ctx.workflow_yaml or "")
+ return {"ok": False, "error": "stop after exact candidate"}
- result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, lexical_only_yaml, [])
+ async def _verification(*_args: object, **_kwargs: object) -> None:
+ return None
- assert result is not None
- assert result["data"]["unreferenced_parameter_keys"] == [
+ monkeypatch.setattr(tools_module, "_get_prior_workflow_definition", _no_prior_definition)
+ monkeypatch.setattr(tools_module, "_plan_frontier", lambda *_args: (["submit_service_request"], {}, None))
+ monkeypatch.setattr(tools_module, "_frontier_run_size_error", lambda *_args: None)
+ monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _run)
+ monkeypatch.setattr(tools_module, "_verify_and_record_run_blocks_result", _verification)
+ monkeypatch.setattr(tools_module, "_tool_visible_result_after_completion_verification", lambda _c, r, _v: r)
+
+ with capture_logs() as logs:
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ "parameters": runtime_parameters,
+ }
+ ),
+ )
+
+ bound = next(log for log in logs if log["event"] == "copilot recorded outcome submit rung bound")
+ consumed = next(
+ log for log in logs if log["event"] == "copilot recorded outcome binding consumed by synthesizer"
+ )
+ assert consumed["binding_fingerprints"] == [bound["binding_fingerprint"]]
+ assert dispatched_candidates == [ctx.workflow_yaml]
+ assert json.loads(result)["error"] == "stop after exact candidate"
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ block = _single_code_block(parsed)
+ code = str(block["code"])
+ assert block["parameter_keys"] == [
+ "business_name",
"contact_email",
"desired_start_date",
"service_address",
]
+ assert code.count('page.locator("#company").fill(str(business_name))') == 1
+ assert code.count('page.locator("#email").fill(str(contact_email))') == 1
+ assert code.count('page.locator("#address").fill(str(service_address))') == 1
+ assert code.count('page.locator("#date").fill(str(desired_start_date))') == 1
+ assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is None
- def test_definition_preflight_requires_live_parameter_dataflow(self) -> None:
+ @pytest.mark.asyncio
+ async def test_recut_unbindable_regrounding_halts_before_reauthor(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _definition_contract_ctx()
- dead_or_shadowed_yaml = _yaml(
- """
- title: Submit reusable service request
- workflow_definition:
- parameters:
- - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
- blocks:
- - block_type: code
- label: submit_service_request
- parameter_keys: [business_name, contact_email]
- code: |
- if False:
- await page.locator("#company").fill(str(business_name))
- contact_email = "[email protected]"
- await page.locator("#email").fill(str(contact_email))
- await page.locator("#submit").click()
- """
- )
+ _enable_imposition(ctx)
+ for _ in range(2):
+ assert (await _update_workflow({"workflow_yaml": _UNREFERENCED_DEFINITION_YAML}, ctx))["ok"] is False
+ assert arm_recorded_outcome_grounding_requirement(ctx) is not None
+ ctx.blocker_signal = ctx.turn_halt = ctx.turn_ownership = None
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#submit", "source_url": "https://example.com/utility"}
+ ]
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": "https://example.com/utility",
+ "forms": [],
+ }
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
+ synthesize = Mock(side_effect=AssertionError("must halt before an identical re-author"))
+ monkeypatch.setattr(workflow_update_module, "synthesize_code_block_with_extraction", synthesize)
- result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, dead_or_shadowed_yaml, [])
+ result = workflow_update_module._maybe_impose_synthesized_code_block(
+ _UNREFERENCED_DEFINITION_YAML,
+ ctx,
+ {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ },
+ )
- assert result is not None
- assert result["data"]["unreferenced_parameter_keys"] == ["business_name", "contact_email"]
+ assert result.workflow_yaml == _UNREFERENCED_DEFINITION_YAML
+ assert result.violations
+ synthesize.assert_not_called()
+ assert ctx.blocker_signal.extra["unresolved_parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+ assert "safely connect the current page fields" in ctx.blocker_signal.user_facing_reason
- def test_definition_preflight_accepts_parameter_alias_dataflow(self) -> None:
+ @pytest.mark.asyncio
+ async def test_public_update_and_run_halts_active_author_reject_before_third_identical_author(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
ctx = _definition_contract_ctx()
- alias_yaml = _yaml(
- """
- title: Submit reusable service request
- workflow_definition:
- parameters:
- - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- blocks:
- - block_type: code
- label: submit_service_request
- parameter_keys: [business_name]
- code: |
- company = str(business_name)
- await page.locator("#company").fill(company)
- await page.locator("#submit").click()
- """
+ _enable_imposition(ctx)
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ arguments = json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ "parameters": {
+ "business_name": "Example Co",
+ "contact_email": "[email protected]",
+ "service_address": "1 Example Way",
+ "desired_start_date": "2026-08-01",
+ },
+ }
+ )
+ for _ in range(2):
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ arguments,
+ )
+ assert json.loads(result)["data"]["reason_code"] == "definition_contract_unsatisfied"
+ requirement = ctx.recorded_outcome_grounding_requirement
+ assert requirement is not None
+ assert requirement.phase == "author_time_reject"
+ active_structural_key = requirement.structural_key
+ ctx.blocker_signal = ctx.turn_halt = ctx.turn_ownership = None
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#submit", "source_url": "https://example.com/utility"}
+ ]
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": "https://example.com/utility",
+ "forms": [],
+ "observed_after_workflow_run": False,
+ }
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ arguments,
)
- assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, alias_yaml, []) is None
+ assert json.loads(result)["ok"] is False
+ assert ctx.latest_recorded_build_test_outcome.structural_key == active_structural_key
+ assert ctx.blocker_signal.internal_reason_code == "definition_contract_unsatisfied"
+ assert ctx.blocker_signal.extra["unresolved_parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+ assert ctx.turn_halt is not None
+ assert ctx.turn_halt.kind.value == "definition_contract_unsatisfied"
- def test_definition_preflight_tracks_live_control_flow_dataflow(self) -> None:
- ctx = _definition_contract_ctx()
- control_flow_yaml = _yaml(
- """
- title: Submit reusable service request
- workflow_definition:
- parameters:
- - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
- blocks:
- - block_type: code
- label: submit_service_request
- parameter_keys: [business_name, contact_email]
- code: |
- company = business_name
- if page.url:
- company = company.strip()
- else:
- company = company.upper()
- for selector in ["#company"]:
- await page.locator(selector).fill(company)
- try:
- await page.locator("#email").fill(contact_email)
- except Exception:
- raise
- """
- )
+ @pytest.mark.asyncio
+ async def test_definition_reject_stays_repairable_at_both_exact_gates(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ update_ctx = _definition_contract_ctx()
- assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, control_flow_yaml, []) is None
+ update_result = await _update_workflow({"workflow_yaml": _UNREFERENCED_DEFINITION_YAML}, update_ctx)
- def test_definition_preflight_drops_bindings_from_non_fallthrough_branch(self) -> None:
- ctx = _definition_contract_ctx()
- terminal_branch_yaml = _yaml(
- """
- title: Submit reusable service request
- workflow_definition:
- parameters:
- - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- blocks:
- - block_type: code
- label: submit_service_request
- parameter_keys: [business_name]
- code: |
- if page.url.endswith("/done"):
- company = business_name
- if True:
- return {"already_done": True}
- else:
- company = "fixed"
- await page.locator("#company").fill(company)
- """
- )
+ assert update_result["ok"] is False
+ assert update_result["data"]["unreferenced_parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+ assert update_ctx.blocker_signal is None
+ assert update_ctx.turn_halt is None
- result = workflow_update_module._definition_plane_preflight_reject(ctx, terminal_branch_yaml)
+ dispatch_ctx = _definition_contract_ctx()
+ dispatch_result = workflow_update_module._metadata_contract_run_preflight_reject(
+ dispatch_ctx,
+ _UNREFERENCED_DEFINITION_YAML,
+ [],
+ )
- assert result is not None
- assert result.unreferenced_parameter_keys == ("business_name",)
+ assert dispatch_result is not None
+ assert dispatch_result["ok"] is False
+ assert dispatch_result["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert dispatch_ctx.blocker_signal is None
+ assert dispatch_ctx.turn_halt is None
- @pytest.mark.parametrize(
- "terminal_test", ["if 1:\n return {'already_done': True}", "while True:\n return {'already_done': True}"]
- )
- def test_definition_preflight_drops_bindings_from_constant_terminal_control(self, terminal_test: str) -> None:
+ @pytest.mark.asyncio
+ async def test_public_update_and_run_definition_reject_returns_to_repair_loop(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
ctx = _definition_contract_ctx()
- indented_terminal = textwrap.indent(terminal_test, " ")
- workflow_yaml = _yaml(
- "title: Submit reusable service request\n"
- "workflow_definition:\n"
- " parameters:\n"
- " - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}\n"
- " blocks:\n"
- " - block_type: code\n"
- " label: submit_service_request\n"
- " parameter_keys: [business_name]\n"
- " code: |\n"
- " if page.url.endswith('/done'):\n"
- " company = business_name\n"
- f"{indented_terminal}\n"
- " else:\n"
- " company = 'fixed'\n"
- " await page.locator('#company').fill(company)\n"
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ arguments = json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ }
)
- result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
+ for _ in range(2):
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ arguments,
+ )
- assert result is not None
- assert result.unreferenced_parameter_keys == ("business_name",)
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert ctx.blocker_signal is None
+ assert ctx.turn_halt is None
- def test_definition_preflight_ignores_break_in_unreachable_constant_branch(self) -> None:
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "definition_contract_unsatisfied"
+ assert ctx.recorded_outcome_grounding_requirement is not None
+
+ third_result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ arguments,
+ )
+
+ assert json.loads(third_result)["ok"] is False
+ assert ctx.blocker_signal.internal_reason_code == "recorded_outcome_grounding_required"
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("grounded_binding_available", [False, True])
+ async def test_public_update_and_run_rejects_unbound_declared_inputs_without_definition_tag(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ grounded_binding_available: bool,
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[CompletionCriterion(id="run", outcome="The service request is submitted.")]
+ )
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ dispatched = False
+ updated = False
+ real_update = tools_module._update_workflow
+
+ async def _observed_update(*args: object, **kwargs: object) -> dict[str, object]:
+ nonlocal updated
+ result = await real_update(*args, **kwargs)
+ updated = bool(result.get("ok"))
+ return result
+
+ async def _unexpected_dispatch(*_args: object, **_kwargs: object) -> dict[str, object]:
+ nonlocal dispatched
+ dispatched = True
+ return {"ok": True}
+
+ monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _unexpected_dispatch)
+ monkeypatch.setattr(tools_module, "_update_workflow", _observed_update)
+ if grounded_binding_available:
+ monkeypatch.setattr(
+ workflow_update_module,
+ "_authoring_parameter_binding_resolution_for_definition",
+ lambda *_args, **_kwargs: SimpleNamespace(snapshot=Mock(), directive=None),
+ )
+
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps(
+ {
+ "workflow_yaml": _UNREFERENCED_DEFINITION_YAML,
+ "block_labels": ["submit_service_request"],
+ }
+ ),
+ )
+
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert parsed["data"]["unreferenced_parameter_keys"] == [
+ "business_name",
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+ assert updated is True
+ assert dispatched is False
+
+ @pytest.mark.asyncio
+ async def test_public_initial_preflight_preserves_code_safety_precedence_for_untagged_inputs(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[CompletionCriterion(id="run", outcome="The service request is submitted.")]
+ )
+ unsafe_yaml = _UNREFERENCED_DEFINITION_YAML.replace(
+ 'await page.locator("#open").click()',
+ 'import requests\n await page.locator("#open").click()',
+ )
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps({"workflow_yaml": unsafe_yaml, "block_labels": ["submit_service_request"]}),
+ )
+
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed.get("data", {}).get("reason_code") != "definition_contract_unsatisfied"
+ assert "sandbox safety check" in parsed["error"]
+
+ def test_recut_dispatch_controls_preserve_passing_and_zero_input_candidates(self) -> None:
ctx = _definition_contract_ctx()
- workflow_yaml = _yaml(
+ ctx.output_contract_actuation_by_signature["p5-advisory"] = OutputContractAdvisoryState.GRANTED
+
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, _UNREFERENCED_DEFINITION_YAML, [])
+
+ assert result is not None
+ assert result["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert ctx.blocker_signal is None
+ assert ctx.turn_halt is None
+
+ passing_yaml = _yaml(
"""
title: Submit reusable service request
workflow_definition:
parameters:
- {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
blocks:
- block_type: code
label: submit_service_request
- parameter_keys: [business_name]
+ parameter_keys: [business_name, contact_email, service_address, desired_start_date]
code: |
- if page.url.endswith("/done"):
- company = business_name
- while True:
- if False:
- break
- return {"already_done": True}
- else:
- company = "fixed"
- await page.locator("#company").fill(company)
+ await page.locator("#company").fill(str(business_name))
+ await page.locator("#email").fill(str(contact_email))
+ await page.locator("#address").fill(str(service_address))
+ await page.locator("#date").fill(str(desired_start_date))
+ await page.locator("#submit").click()
"""
)
+ passing_ctx = _definition_contract_ctx()
+ assert workflow_update_module._metadata_contract_run_preflight_reject(passing_ctx, passing_yaml, []) is None
- result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
-
- assert result is not None
- assert result.unreferenced_parameter_keys == ("business_name",)
+ zero_input_ctx = _code_only_ctx()
+ zero_input_ctx.request_policy = RequestPolicy(
+ completion_criteria=[CompletionCriterion(id="run", outcome="The request is submitted.")]
+ )
+ zero_input_yaml = _yaml(
+ """
+ title: Open status page
+ workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: code
+ label: open_status
+ parameter_keys: []
+ code: |
+ await page.goto("https://example.com/status")
+ """
+ )
+ assert (
+ workflow_update_module._metadata_contract_run_preflight_reject(zero_input_ctx, zero_input_yaml, []) is None
+ )
- def test_definition_preflight_ignores_break_overridden_by_terminal_finally(self) -> None:
+ def test_definition_preflight_rejects_partial_parameter_references(self) -> None:
ctx = _definition_contract_ctx()
- workflow_yaml = _yaml(
+ partially_referenced_yaml = _yaml(
"""
title: Submit reusable service request
workflow_definition:
parameters:
- {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
blocks:
- block_type: code
label: submit_service_request
parameter_keys: [business_name]
code: |
- if page.url.endswith("/done"):
- company = business_name
- while True:
- try:
- break
- finally:
- return {"already_done": True}
- else:
- company = "fixed"
- await page.locator("#company").fill(company)
+ await page.locator("#company").fill(str(business_name))
+ await page.locator("#submit").click()
"""
)
- result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, partially_referenced_yaml, [])
assert result is not None
- assert result.unreferenced_parameter_keys == ("business_name",)
-
- @pytest.mark.parametrize(
- ("code", "expected_unreferenced"),
- [
- (
- "values = [business_name for business_name in ['fixed']]\n"
- "await page.locator('#company').fill(values[0])",
- ["business_name"],
- ),
- (
- "async def fill_company():\n"
- " await page.locator('#company').fill(str(business_name))\n"
- "await fill_company()",
- [],
- ),
- ],
- )
- def test_definition_preflight_honors_python_scopes(self, code: str, expected_unreferenced: list[str]) -> None:
- ctx = _definition_contract_ctx()
- indented_code = textwrap.indent(code, " ")
- scoped_yaml = _yaml(
- "title: Submit reusable service request\n"
- "workflow_definition:\n"
- " parameters:\n"
- " - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}\n"
- " blocks:\n"
- " - block_type: code\n"
- " label: submit_service_request\n"
- " parameter_keys: [business_name]\n"
- " code: |\n"
- f"{indented_code}\n"
- )
-
- result = workflow_update_module._definition_plane_preflight_reject(ctx, scoped_yaml)
-
- if expected_unreferenced:
- assert result is not None
- assert list(result.unreferenced_parameter_keys) == expected_unreferenced
- else:
- assert result is None
+ assert result["data"]["unreferenced_parameter_keys"] == [
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
- def test_definition_preflight_counts_allowed_non_code_parameter_consumption(self) -> None:
+ def test_definition_preflight_ignores_parameter_names_in_comments_and_string_literals(self) -> None:
ctx = _definition_contract_ctx()
- mixed_yaml = _yaml(
+ lexical_only_yaml = _yaml(
"""
title: Submit reusable service request
workflow_definition:
parameters:
- {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
blocks:
- - block_type: navigation
- label: open_customer
- url: "https://example.com/customer/{{ business_name }}"
- block_type: code
label: submit_service_request
- parameter_keys: [contact_email]
+ parameter_keys: [business_name, contact_email, service_address, desired_start_date]
code: |
- await page.locator("#email").fill(contact_email)
+ # contact_email and service_address are not executable references.
+ note = "desired_start_date"
+ await page.locator("#company").fill(str(business_name))
await page.locator("#submit").click()
"""
)
- assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, mixed_yaml, []) is None
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, lexical_only_yaml, [])
- @pytest.mark.parametrize(
- ("template", "is_consumed"),
- [
- ('{{ "business_name" }}', False),
- ("{% if business_name %}/customer{% endif %}", True),
- ],
- )
- def test_definition_preflight_uses_jinja_semantics(self, template: str, is_consumed: bool) -> None:
+ assert result is not None
+ assert result["data"]["unreferenced_parameter_keys"] == [
+ "contact_email",
+ "desired_start_date",
+ "service_address",
+ ]
+
+ def test_definition_preflight_requires_live_parameter_dataflow(self) -> None:
ctx = _definition_contract_ctx()
- templated_yaml = _yaml(
- f"""
+ dead_or_shadowed_yaml = _yaml(
+ """
title: Submit reusable service request
workflow_definition:
parameters:
- - {{parameter_type: workflow, key: business_name, workflow_parameter_type: string}}
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
blocks:
- - block_type: navigation
- label: open_customer
- url: {json.dumps(template)}
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name, contact_email]
+ code: |
+ if False:
+ await page.locator("#company").fill(str(business_name))
+ contact_email = "[email protected]"
+ await page.locator("#email").fill(str(contact_email))
+ await page.locator("#submit").click()
"""
)
- result = workflow_update_module._definition_plane_preflight_reject(ctx, templated_yaml)
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, dead_or_shadowed_yaml, [])
- assert (result is None) is is_consumed
+ assert result is not None
+ assert result["data"]["unreferenced_parameter_keys"] == ["business_name", "contact_email"]
- @pytest.mark.asyncio
- async def test_definition_preflight_defers_to_repairable_syntax_error(self) -> None:
+ def test_definition_preflight_accepts_parameter_alias_dataflow(self) -> None:
ctx = _definition_contract_ctx()
- malformed_yaml = _yaml(
+ alias_yaml = _yaml(
"""
title: Submit reusable service request
workflow_definition:
@@ -2197,141 +2521,401 @@ class TestCodeRepairProgressClassification:
label: submit_service_request
parameter_keys: [business_name]
code: |
- await page.locator("#company").fill(str(business_name)
+ company = str(business_name)
+ await page.locator("#company").fill(company)
+ await page.locator("#submit").click()
"""
)
- result = await _update_workflow({"workflow_yaml": malformed_yaml}, ctx)
-
- assert result["ok"] is False
- assert "not valid Python" in result["error"]
- assert result.get("data", {}).get("reason_code") != "definition_contract_unsatisfied"
+ assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, alias_yaml, []) is None
- def test_definition_preflight_is_code_first_only(self) -> None:
+ def test_definition_preflight_tracks_live_control_flow_dataflow(self) -> None:
ctx = _definition_contract_ctx()
- ctx.block_authoring_policy = BlockAuthoringPolicy.STANDARD
- standard_yaml = _yaml(
+ control_flow_yaml = _yaml(
"""
title: Submit reusable service request
workflow_definition:
parameters:
- {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
- {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
- - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
- - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
blocks:
- - block_type: task
+ - block_type: code
label: submit_service_request
- url: "{{business_name}}/{{contact_email}}/{{service_address}}/{{desired_start_date}}"
+ parameter_keys: [business_name, contact_email]
+ code: |
+ company = business_name
+ if page.url:
+ company = company.strip()
+ else:
+ company = company.upper()
+ for selector in ["#company"]:
+ await page.locator(selector).fill(company)
+ try:
+ await page.locator("#email").fill(contact_email)
+ except Exception:
+ raise
"""
)
- assert (
- workflow_update_module._metadata_contract_run_preflight_reject(
- ctx,
- standard_yaml,
- [],
- )
- is None
- )
+ assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, control_flow_yaml, []) is None
- @pytest.mark.asyncio
- async def test_code_safety_seam_reject_carries_progress_surface_kind(self) -> None:
- ctx = _code_only_ctx()
- result = await _update_workflow({"workflow_yaml": _REQUESTS_IMPORT_CODE_YAML}, ctx)
- assert result["ok"] is False
- assert result["data"]["surface_kind"] == "code_repair_progress"
- assert result["data"]["progress_text"]
- # The substantive copy is unchanged; the progress text is a separate carrier.
- assert result["user_facing_summary"] == (
- "I need to adjust the workflow's code so it can run safely before testing."
+ def test_definition_preflight_drops_bindings_from_non_fallthrough_branch(self) -> None:
+ ctx = _definition_contract_ctx()
+ terminal_branch_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ if page.url.endswith("/done"):
+ company = business_name
+ if True:
+ return {"already_done": True}
+ else:
+ company = "fixed"
+ await page.locator("#company").fill(company)
+ """
)
- assert result["data"]["progress_text"] != result["user_facing_summary"]
- @pytest.mark.asyncio
- async def test_generated_code_preflight_string_reject_is_not_authoritative(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- monkeypatch.setattr(
- workflow_update_module,
- "_code_block_safety_errors",
- lambda workflow_yaml, prior_yaml: [
- "Code block `search_registry` failed the generated-code preflight check: "
- "AUTHOR_PAGE_EVALUATE: page.evaluate is not allowed."
- ],
- )
- ctx = _code_only_ctx()
- result = await _update_workflow({"workflow_yaml": _SAFE_CODE_YAML}, ctx)
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, terminal_branch_yaml)
- assert result["ok"] is False
- assert ctx.latest_recorded_build_test_outcome is not None
- assert ctx.latest_recorded_build_test_outcome.reason_code == "code_safety_reject"
- assert ctx.latest_recorded_build_test_outcome.is_authoritative is False
- assert ctx.latest_recorded_build_test_outcome.structural_key is None
+ assert result is not None
+ assert result.unreferenced_parameter_keys == ("business_name",)
- def test_code_safety_payload_keeps_typed_security_error_authoritative(self) -> None:
- payload = _code_safety_reject_payload(
- [
- CodeBlockSecurityError(
- "Code block `search_registry` failed the Copilot code security check: page.request is not allowed.",
- block_label="search_registry",
- reason_code="AUTHOR_PAGE_REQUEST",
- surface="page.request",
- )
- ]
+ @pytest.mark.parametrize(
+ "terminal_test", ["if 1:\n return {'already_done': True}", "while True:\n return {'already_done': True}"]
+ )
+ def test_definition_preflight_drops_bindings_from_constant_terminal_control(self, terminal_test: str) -> None:
+ ctx = _definition_contract_ctx()
+ indented_terminal = textwrap.indent(terminal_test, " ")
+ workflow_yaml = _yaml(
+ "title: Submit reusable service request\n"
+ "workflow_definition:\n"
+ " parameters:\n"
+ " - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}\n"
+ " blocks:\n"
+ " - block_type: code\n"
+ " label: submit_service_request\n"
+ " parameter_keys: [business_name]\n"
+ " code: |\n"
+ " if page.url.endswith('/done'):\n"
+ " company = business_name\n"
+ f"{indented_terminal}\n"
+ " else:\n"
+ " company = 'fixed'\n"
+ " await page.locator('#company').fill(company)\n"
)
- assert payload == {
- "code_safety_errors": [
- {
- "block_label": "search_registry",
- "reason_code": "AUTHOR_PAGE_REQUEST",
- "surface": "page.request",
- }
- ]
- }
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
- def test_code_safety_payload_rejects_string_only_preflight_authority(self) -> None:
- payload = _code_safety_reject_payload(
- [
- "Code block `search_registry` failed the generated-code preflight check: "
- "AUTHOR_PAGE_EVALUATE: page.evaluate is not allowed."
- ]
+ assert result is not None
+ assert result.unreferenced_parameter_keys == ("business_name",)
+
+ def test_definition_preflight_ignores_break_in_unreachable_constant_branch(self) -> None:
+ ctx = _definition_contract_ctx()
+ workflow_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ if page.url.endswith("/done"):
+ company = business_name
+ while True:
+ if False:
+ break
+ return {"already_done": True}
+ else:
+ company = "fixed"
+ await page.locator("#company").fill(company)
+ """
)
- assert payload is None
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
- @pytest.mark.asyncio
- async def test_authoritative_recorded_outcome_rejects_unchanged_authored_candidate(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _code_only_ctx()
- ctx.workflow_yaml = _code_yaml('await page.goto("https://example.com/old")')
- signature = authored_structure_signature_from_workflow(_SAFE_CODE_YAML)
- ctx.latest_recorded_build_test_outcome = RecordedBuildTestOutcome(
- phase="persisted_block_run",
- attempted_tool="update_and_run_blocks",
- verdict="repairable_failure",
- reason_code="outcome_not_demonstrated",
- structural_failure_identity="completion:typed-outcome",
- authored_structure_signature=signature,
+ assert result is not None
+ assert result.unreferenced_parameter_keys == ("business_name",)
+
+ def test_definition_preflight_ignores_break_overridden_by_terminal_finally(self) -> None:
+ ctx = _definition_contract_ctx()
+ workflow_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ if page.url.endswith("/done"):
+ company = business_name
+ while True:
+ try:
+ break
+ finally:
+ return {"already_done": True}
+ else:
+ company = "fixed"
+ await page.locator("#company").fill(company)
+ """
)
- result = await _update_workflow({"workflow_yaml": _SAFE_CODE_YAML}, ctx, allow_missing_credentials=True)
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, workflow_yaml)
- assert result["ok"] is False
- assert "left the frontier the last recorded test outcome named unchanged" in result["error"]
- assert ctx.workflow_yaml == _code_yaml('await page.goto("https://example.com/old")')
- assert ctx.has_staged_proposal is False
- assert ctx.latest_recorded_build_test_outcome is not None
- assert ctx.latest_recorded_build_test_outcome.reason_code == "unchanged_after_recorded_outcome"
- assert ctx.latest_recorded_build_test_outcome.structural_key is not None
+ assert result is not None
+ assert result.unreferenced_parameter_keys == ("business_name",)
- @pytest.mark.asyncio
- async def test_repeated_unchanged_authored_candidate_keeps_same_reject_key_and_backstop(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
+ @pytest.mark.parametrize(
+ ("code", "expected_unreferenced"),
+ [
+ (
+ "values = [business_name for business_name in ['fixed']]\n"
+ "await page.locator('#company').fill(values[0])",
+ ["business_name"],
+ ),
+ (
+ "async def fill_company():\n"
+ " await page.locator('#company').fill(str(business_name))\n"
+ "await fill_company()",
+ [],
+ ),
+ ],
+ )
+ def test_definition_preflight_honors_python_scopes(self, code: str, expected_unreferenced: list[str]) -> None:
+ ctx = _definition_contract_ctx()
+ indented_code = textwrap.indent(code, " ")
+ scoped_yaml = _yaml(
+ "title: Submit reusable service request\n"
+ "workflow_definition:\n"
+ " parameters:\n"
+ " - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}\n"
+ " blocks:\n"
+ " - block_type: code\n"
+ " label: submit_service_request\n"
+ " parameter_keys: [business_name]\n"
+ " code: |\n"
+ f"{indented_code}\n"
+ )
+
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, scoped_yaml)
+
+ if expected_unreferenced:
+ assert result is not None
+ assert list(result.unreferenced_parameter_keys) == expected_unreferenced
+ else:
+ assert result is None
+
+ def test_definition_preflight_counts_allowed_non_code_parameter_consumption(self) -> None:
+ ctx = _definition_contract_ctx()
+ mixed_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ blocks:
+ - block_type: navigation
+ label: open_customer
+ url: "https://example.com/customer/{{ business_name }}"
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [contact_email]
+ code: |
+ await page.locator("#email").fill(contact_email)
+ await page.locator("#submit").click()
+ """
+ )
+
+ assert workflow_update_module._metadata_contract_run_preflight_reject(ctx, mixed_yaml, []) is None
+
+ @pytest.mark.parametrize(
+ ("template", "is_consumed"),
+ [
+ ('{{ "business_name" }}', False),
+ ("{% if business_name %}/customer{% endif %}", True),
+ ],
+ )
+ def test_definition_preflight_uses_jinja_semantics(self, template: str, is_consumed: bool) -> None:
+ ctx = _definition_contract_ctx()
+ templated_yaml = _yaml(
+ f"""
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {{parameter_type: workflow, key: business_name, workflow_parameter_type: string}}
+ blocks:
+ - block_type: navigation
+ label: open_customer
+ url: {json.dumps(template)}
+ """
+ )
+
+ result = workflow_update_module._definition_plane_preflight_reject(ctx, templated_yaml)
+
+ assert (result is None) is is_consumed
+
+ @pytest.mark.asyncio
+ async def test_definition_preflight_defers_to_repairable_syntax_error(self) -> None:
+ ctx = _definition_contract_ctx()
+ malformed_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: submit_service_request
+ parameter_keys: [business_name]
+ code: |
+ await page.locator("#company").fill(str(business_name)
+ """
+ )
+
+ result = await _update_workflow({"workflow_yaml": malformed_yaml}, ctx)
+
+ assert result["ok"] is False
+ assert "not valid Python" in result["error"]
+ assert result.get("data", {}).get("reason_code") != "definition_contract_unsatisfied"
+
+ def test_definition_preflight_is_code_first_only(self) -> None:
+ ctx = _definition_contract_ctx()
+ ctx.block_authoring_policy = BlockAuthoringPolicy.STANDARD
+ standard_yaml = _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
+ blocks:
+ - block_type: task
+ label: submit_service_request
+ url: "{{business_name}}/{{contact_email}}/{{service_address}}/{{desired_start_date}}"
+ """
+ )
+
+ assert (
+ workflow_update_module._metadata_contract_run_preflight_reject(
+ ctx,
+ standard_yaml,
+ [],
+ )
+ is None
+ )
+
+ @pytest.mark.asyncio
+ async def test_code_safety_seam_reject_carries_progress_surface_kind(self) -> None:
+ ctx = _code_only_ctx()
+ result = await _update_workflow({"workflow_yaml": _REQUESTS_IMPORT_CODE_YAML}, ctx)
+ assert result["ok"] is False
+ assert result["data"]["surface_kind"] == "code_repair_progress"
+ assert result["data"]["progress_text"]
+ # The substantive copy is unchanged; the progress text is a separate carrier.
+ assert result["user_facing_summary"] == (
+ "I need to adjust the workflow's code so it can run safely before testing."
+ )
+ assert result["data"]["progress_text"] != result["user_facing_summary"]
+
+ @pytest.mark.asyncio
+ async def test_generated_code_preflight_string_reject_is_not_authoritative(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(
+ workflow_update_module,
+ "_code_block_safety_errors",
+ lambda workflow_yaml, prior_yaml: [
+ "Code block `search_registry` failed the generated-code preflight check: "
+ "AUTHOR_PAGE_EVALUATE: page.evaluate is not allowed."
+ ],
+ )
+ ctx = _code_only_ctx()
+ result = await _update_workflow({"workflow_yaml": _SAFE_CODE_YAML}, ctx)
+
+ assert result["ok"] is False
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "code_safety_reject"
+ assert ctx.latest_recorded_build_test_outcome.is_authoritative is False
+ assert ctx.latest_recorded_build_test_outcome.structural_key is None
+
+ def test_code_safety_payload_keeps_typed_security_error_authoritative(self) -> None:
+ payload = _code_safety_reject_payload(
+ [
+ CodeBlockSecurityError(
+ "Code block `search_registry` failed the Copilot code security check: page.request is not allowed.",
+ block_label="search_registry",
+ reason_code="AUTHOR_PAGE_REQUEST",
+ surface="page.request",
+ )
+ ]
+ )
+
+ assert payload == {
+ "code_safety_errors": [
+ {
+ "block_label": "search_registry",
+ "reason_code": "AUTHOR_PAGE_REQUEST",
+ "surface": "page.request",
+ }
+ ]
+ }
+
+ def test_code_safety_payload_rejects_string_only_preflight_authority(self) -> None:
+ payload = _code_safety_reject_payload(
+ [
+ "Code block `search_registry` failed the generated-code preflight check: "
+ "AUTHOR_PAGE_EVALUATE: page.evaluate is not allowed."
+ ]
+ )
+
+ assert payload is None
+
+ @pytest.mark.asyncio
+ async def test_authoritative_recorded_outcome_rejects_unchanged_authored_candidate(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ ctx.workflow_yaml = _code_yaml('await page.goto("https://example.com/old")')
+ signature = authored_structure_signature_from_workflow(_SAFE_CODE_YAML)
+ ctx.latest_recorded_build_test_outcome = RecordedBuildTestOutcome(
+ phase="persisted_block_run",
+ attempted_tool="update_and_run_blocks",
+ verdict="repairable_failure",
+ reason_code="outcome_not_demonstrated",
+ structural_failure_identity="completion:typed-outcome",
+ authored_structure_signature=signature,
+ )
+
+ result = await _update_workflow({"workflow_yaml": _SAFE_CODE_YAML}, ctx, allow_missing_credentials=True)
+
+ assert result["ok"] is False
+ assert "left the frontier the last recorded test outcome named unchanged" in result["error"]
+ assert ctx.workflow_yaml == _code_yaml('await page.goto("https://example.com/old")')
+ assert ctx.has_staged_proposal is False
+ assert ctx.latest_recorded_build_test_outcome is not None
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "unchanged_after_recorded_outcome"
+ assert ctx.latest_recorded_build_test_outcome.structural_key is not None
+
+ @pytest.mark.asyncio
+ async def test_repeated_unchanged_authored_candidate_keeps_same_reject_key_and_backstop(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
_stub_successful_update(monkeypatch)
ctx = _code_only_ctx()
signature = authored_structure_signature_from_workflow(_SAFE_CODE_YAML)
@@ -4932,8 +5516,9 @@ class TestCodeRepairProgressClassification:
assert result is not None
assert result["ok"] is False
- assert result["data"]["reason_code"] == "metadata_contract_required_before_run"
- assert result["data"]["output_contract_reason_code"] == "value_bearing_output_required"
+ assert result["data"]["reason_code"] == "value_bearing_output_required"
+ assert "output_contract_reason_code" not in result["data"]
+ assert result["data"]["value_bearing_convergence_directive"]["rung"] == 1
assert result["data"]["block_label"] == "extract_entry_output"
assert result["data"]["canonical_required_child_paths"] == ["output.flags", "output.record_id"]
assert result["data"]["missing_goal_value_paths"] == ["output.flags", "output.record_id"]
@@ -5077,15 +5662,20 @@ class TestCodeRepairProgressClassification:
assert results[0] is not None
assert results[0]["ok"] is False
- assert results[0]["data"]["reason_code"] == "metadata_contract_required_before_run"
- assert results[0]["data"]["output_contract_reason_code"] == "value_bearing_output_required"
+ assert results[0]["data"]["reason_code"] == "value_bearing_output_required"
+ assert "output_contract_reason_code" not in results[0]["data"]
+ assert results[0]["data"]["value_bearing_convergence_directive"]["rung"] == 1
assert results[0]["data"]["output_contract_reject_count"] == 1
assert results[-1] is not None
assert results[-1]["data"]["output_contract_reject_count"] == 4
+ assert results[-1]["data"]["reason_code"] == "metadata_contract_required_before_run"
+ assert results[-1]["data"]["output_contract_reason_code"] == "value_bearing_output_required"
assert all(
result is None or result["data"]["reason_code"] != "output_contract_reject_budget_exhausted"
for result in results
)
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
def test_metadata_contract_run_preflight_accepts_complete_submitted_metadata(self) -> None:
ctx = _code_only_ctx()
@@ -5224,36 +5814,58 @@ class TestCodeRepairProgressClassification:
assert len([log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]) == 1
assert [log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT] == []
- def test_run_preflight_value_required_reject_arms_no_directive(self) -> None:
- ctx = self._run_preflight_metadata_reject_ctx()
- workflow_yaml = _yaml(
- """
- title: Provider lookup
- workflow_definition:
- blocks:
- - block_type: code
- label: validate_start
- code: |
- return {"output": {"summary": "ok"}}
- """
- )
- metadata = [
- {
- "block_label": "validate_start",
- "claimed_outcomes": [
- {
- "goal_value_paths": ["output"],
- "extraction_schema": '{"type":"object","properties":{"output":{"type":"object"}}}',
- }
- ],
- "terminal_verifier_expectations": [{"goal_value_paths": ["output"]}],
- }
- ]
+ def test_run_preflight_root_only_value_required_emits_without_payload_rewrite(self) -> None:
+ ctx = _live_root_value_bearing_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ [],
+ allow_static_return_advisory=True,
+ enforce_value_bearing_liveness=True,
+ )
+
+ assert evaluation is not None
+ assert evaluation.required_paths == {"output"}
+ assert evaluation.payload["canonical_required_child_paths"] == ["output"]
+ assert evaluation.payload["declaration_only_child_paths"] == ["output.blocker"]
+ assert evaluation.payload["shape_violations"] == ["value_bearing_output_required"]
+ assert evaluation.payload["satisfying_templates"]
+ assert evaluation.payload["satisfying_templates"]["return_skeleton"] == (
+ 'return {"output": {"blocker": None, **output_value}}'
+ )
+ assert evaluation.payload["satisfying_templates"]["extraction_schema"] == {
+ "type": "object",
+ "properties": {
+ "output": {
+ "type": "object",
+ "properties": {"blocker": {"type": ["string", "null"]}},
+ "required": ["blocker"],
+ }
+ },
+ "required": ["output"],
+ }
+ metadata_template = evaluation.payload["satisfying_templates"]["code_artifact_metadata"]
+ assert metadata_template["claimed_outcomes"][0]["goal_value_paths"] == ["output"]
+ assert metadata_template["terminal_verifier_expectations"][0]["goal_value_paths"] == ["output"]
+ assert evaluation.canonical_signature == workflow_update_module._output_contract_signature(
+ ctx=ctx, required_paths={"output"}
+ )
with capture_logs() as logs:
- result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, metadata)
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
assert result is not None and result["ok"] is False
assert "metadata_convergence_directive" not in result["data"]
- assert [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT] == []
+ assert result["data"]["value_bearing_convergence_directive"] == {
+ "rung": 1,
+ "required_output_paths": ["output"],
+ "shape_violations": ["value_bearing_output_required"],
+ "satisfying_templates": result["data"]["satisfying_templates"],
+ }
+ assert result["data"]["canonical_output_contract_signature"] == evaluation.canonical_signature
+ emits = [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(emits) == 1
+ assert emits[0]["directive_family"] == "value_bearing_output_required"
+ assert emits[0]["canonical_required_child_paths"] == ["output"]
def test_cross_seam_write_arm_then_metadata_less_preflight_escalates(self) -> None:
ctx = self._run_preflight_metadata_reject_ctx()
@@ -12457,164 +13069,531 @@ class TestMetadataLessRejectArming:
assert progressed["ok"] is False
assert progressed["data"]["metadata_convergence_directive"]["rung"] == 1
- @pytest.mark.asyncio
- async def test_log_only_mode_leaves_seam_inert(self, monkeypatch: pytest.MonkeyPatch) -> None:
- _stub_successful_update(monkeypatch)
- monkeypatch.setattr(
- workflow_update_module, "copilot_author_time_gate_log_only_enabled", lambda *_args, **_kwargs: True
- )
- ctx = _code_only_ctx()
+ @pytest.mark.asyncio
+ async def test_log_only_mode_leaves_seam_inert(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
+ monkeypatch.setattr(
+ workflow_update_module, "copilot_author_time_gate_log_only_enabled", lambda *_args, **_kwargs: True
+ )
+ ctx = _code_only_ctx()
+ with capture_logs() as logs:
+ result = await _update_workflow(
+ {"workflow_yaml": _metadata_less_output_yaml()}, ctx, allow_missing_credentials=True
+ )
+ assert result["ok"] is False
+ assert "metadata_convergence_directive" not in result["data"]
+ assert not ctx.output_contract_armed_directive_fingerprint_by_signature
+ assert [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT] == []
+
+ @pytest.mark.asyncio
+ async def test_multiple_missing_labels_fail_closed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ result = await _update_workflow(
+ {"workflow_yaml": _metadata_less_two_block_yaml()}, ctx, allow_missing_credentials=True
+ )
+ assert result["ok"] is False
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "metadata_reject"
+ assert "metadata_convergence_directive" not in result["data"]
+
+ @pytest.mark.asyncio
+ async def test_churn_stash_fires_at_cap_with_arming_active(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ yaml_text = _metadata_less_output_yaml()
+ for index in range(MAX_CODE_AUTHORING_GUARDRAIL_REJECTS - 1):
+ result = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
+ assert result["ok"] is False
+ assert result["data"]["metadata_convergence_directive"]["rung"] in (1, 2)
+ assert ctx.code_authoring_guardrail_reject_count == index + 1
+ assert ctx.blocker_signal is None
+ final = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
+ assert final["ok"] is False
+ assert ctx.code_authoring_guardrail_reject_count == MAX_CODE_AUTHORING_GUARDRAIL_REJECTS
+ churn = ctx.blocker_signal
+ assert isinstance(churn, CopilotToolBlockerSignal)
+ assert churn.internal_reason_code == "code_authoring_guardrail_churn"
+
+ @pytest.mark.asyncio
+ async def test_seam_replay_emits_once_then_escalates(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ yaml_text = _metadata_less_output_yaml()
+ with capture_logs() as first_logs:
+ first = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
+ with capture_logs() as second_logs:
+ second = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
+ assert first["data"]["metadata_convergence_directive"]["rung"] == 1
+ assert second["data"]["metadata_convergence_directive"]["rung"] == 2
+ assert len([log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]) == 1
+ second_emits = [log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(second_emits) == 1 and second_emits[0]["rung"] == 2
+ assert not ctx.output_contract_spine_directive_blockers_by_attempt_key
+ assert not ctx.output_contract_actuation_by_signature
+
+ @pytest.mark.asyncio
+ async def test_recorded_reject_identity_arms_and_next_author_consumes(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ yaml_text = _recorded_metadata_reject_yaml()
+ assert not ctx.output_contract_armed_directive_fingerprint_by_signature
+ with capture_logs() as first_logs:
+ first = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
+ assert first["ok"] is False
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "metadata_reject"
+ directive = first["data"]["metadata_convergence_directive"]
+ assert directive["rung"] == 1
+ assert "declared_goal" in directive["missing_fields_by_label"][_RECORDED_METADATA_REJECT_BLOCK_LABEL]
+ assert len([log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]) == 1
+ assert ctx.output_contract_armed_directive_fingerprint_by_signature
+
+ second = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
+ escalated = second["data"]["metadata_convergence_directive"]
+ assert escalated["rung"] == 2
+ assert _RECORDED_METADATA_REJECT_BLOCK_LABEL in escalated["metadata_fill_in_skeleton"]
+
+
+class TestWholeTrajectoryImposition:
+ def test_imposes_over_unscouted_browser_fill_in_selected_block(self) -> None:
+ ctx = _quote_ctx()
+ submitted = _yaml(
+ """
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: quote_flow
+ code: |
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ await page.locator("#electricDate").fill("2026-07-01")
+ await page.locator("#coverage-next").click()
+ """
+ )
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
+ assert "#electricDate" not in code
+ assert code.index('page.locator("#zip")') < code.index('page.locator("#continue")')
+ assert code.index('page.locator("#continue")') < code.index('page.locator("#coverage-next")')
+
+ def test_entry_opener_drop_is_instrumented_not_silently_forgiven(self) -> None:
+ ctx = _quote_ctx()
+ ctx.scout_trajectory.insert(
+ 0,
+ {"tool_name": "click", "selector": "button", "source_url": _QUOTE_URL, "trajectory_index": 0},
+ )
+ submitted = _yaml(
+ """
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: quote_flow
+ code: |
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ await page.locator("#electricDate").fill("2026-07-01")
+ await page.locator("#coverage-next").click()
+ """
+ )
+
+ with capture_logs() as logs:
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ forgiven = result.substitutions["forgiven_entry_opener_drops"]
+ assert [record["reason_code"] for record in forgiven] == ["ambiguous_bare_selector"]
+ assert forgiven[0]["forgiveness"] == "entry_opener_superseded_by_locator_provenance"
+ assert any(entry.get("event") == "copilot_imposition_forgave_entry_opener_drop" for entry in logs)
+
+ def test_imposes_over_unscouted_selected_block_extra_click(self) -> None:
+ ctx = _quote_ctx()
+ submitted = _yaml(
+ """
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: quote_flow
+ code: |
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ await page.locator("#electricDate").click()
+ await page.locator("#coverage-next").click()
+ """
+ )
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
+ assert "#electricDate" not in code
+ assert 'page.locator("#zip")' in code
+ assert 'page.locator("#continue")' in code
+ assert 'page.locator("#coverage-next")' in code
+
+ def test_p10_shaped_selected_surplus_browser_mutations_are_discarded(self) -> None:
+ ctx = _quote_ctx()
+ submitted = _yaml(
+ """
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: quote_flow
+ code: |
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ await page.locator("#electricPlan").select_option("basic")
+ await page.locator("#electricDate").fill("2026-07-01")
+ await page.locator("#coverage-next").click()
+ """
+ )
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
+ assert "#electricPlan" not in code
+ assert "#electricDate" not in code
+ assert result.substitutions["source_trajectory_count"] == 3
+ assert code.index('page.locator("#zip")') < code.index('page.locator("#continue")')
+ assert code.index('page.locator("#continue")') < code.index('page.locator("#coverage-next")')
+
+ def test_wrong_selected_block_receiver_is_overwritten_by_scout_spine(self) -> None:
+ ctx = _quote_ctx()
+ submitted = _yaml(
+ """
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: quote_flow
+ code: |
+ await page.locator("#wrongZip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ await page.locator("#coverage-next").click()
+ """
+ )
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
+ assert "#wrongZip" not in code
+ assert 'page.locator("#zip")' in code
+
+ def test_selected_alias_locator_extra_is_discarded_by_imposition(self) -> None:
+ ctx = _quote_ctx()
+ submitted = _yaml(
+ """
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: quote_flow
+ code: |
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ target = page.locator("#electricDate")
+ await target.fill("2026-07-01")
+ await page.locator("#coverage-next").click()
+ """
+ )
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
+ assert "#electricDate" not in code
+ assert 'target = page.locator("#electricDate")' not in code
+ assert 'page.locator("#zip")' in code
+ assert 'page.locator("#coverage-next")' in code
+
+ def test_selected_helper_extra_is_discarded_by_imposition(self) -> None:
+ ctx = _quote_ctx()
+ submitted = _yaml(
+ """
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: quote_flow
+ code: |
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ async def clear(target):
+ await target.evaluate("node => node.remove()")
+ await clear(target=page.locator("#electricDate"))
+ await page.locator("#coverage-next").click()
+ """
+ )
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
+ assert "#electricDate" not in code
+ assert "async def clear" not in code
+
+ def test_selected_dynamic_extra_is_discarded_by_imposition(self) -> None:
+ ctx = _quote_ctx()
+ submitted = _yaml(
+ """
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: quote_flow
+ code: |
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ await getattr(page.locator("#electricDate"), "fill")("2026-07-01")
+ await page.locator("#coverage-next").click()
+ """
+ )
+
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
+ assert "#electricDate" not in code
+ assert "getattr" not in code
+
+ def test_rejects_extra_changed_block_with_unscouted_browser_mutation(self) -> None:
+ ctx = _records_spine_ctx()
+ submitted = _yaml(
+ f"""
+ title: Records
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
+ code: |
+ await page.locator("#stage-a").click()
+ await page.locator("#stage-b").click()
+ await page.locator("#stage-c").click()
+ - block_type: code
+ label: invented_browser_step
+ code: |
+ await page.locator("#electricDate").fill("2026-07-01")
+ """
+ )
+
+ with capture_logs() as logs:
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert ctx.spine_imposition_owned_attempt is False
+ assert any("unscouted browser action" in violation for violation in result.violations)
+ assert any("never_captured" in violation for violation in result.violations)
+ assert result.substitutions is None
+ events = [log for log in logs if log["event"] == "copilot_browser_surface_rejection_provenance"]
+ assert events and events[0]["kind"] == "never_captured"
+
+ @pytest.mark.parametrize(
+ "sibling_code",
+ [
+ pytest.param(
+ """
+ await page.evaluate("window.localStorage.clear()")
+ """,
+ id="test_rejects_unknown_page_receiver_call",
+ ),
+ pytest.param(
+ """
+ await page.locator("#electricDate").evaluate("node => node.remove()")
+ """,
+ id="test_rejects_unknown_direct_locator_receiver_call",
+ ),
+ pytest.param(
+ """
+ target = page.locator("#electricDate")
+ await target.evaluate("node => node.remove()")
+ """,
+ id="test_rejects_unknown_locator_alias_receiver_call",
+ ),
+ pytest.param(
+ """
+ p = page
+ await p.goto("https://example.com/other")
+ """,
+ id="test_rejects_page_alias_mutation",
+ ),
+ pytest.param(
+ """
+ p = page
+ q = p
+ await q.goto("https://example.com/other")
+ """,
+ id="test_rejects_transitive_page_alias_mutation",
+ ),
+ pytest.param(
+ """
+ target = page.locator("#electricDate")
+ other = target
+ await other.fill("2026-07-01")
+ """,
+ id="test_rejects_transitive_locator_alias_mutation",
+ ),
+ pytest.param(
+ """
+ fill_electric = page.locator("#electricDate").fill
+ await fill_electric("2026-07-01")
+ """,
+ id="test_rejects_bound_method_alias_mutation",
+ ),
+ pytest.param(
+ """
+ fill_electric = page.locator("#electricDate").fill
+ other = fill_electric
+ await other("2026-07-01")
+ """,
+ id="test_rejects_transitive_bound_method_alias_mutation",
+ ),
+ pytest.param(
+ """
+ await getattr(page, "goto")("https://example.com/other")
+ """,
+ id="test_rejects_dynamic_dispatch_on_page",
+ ),
+ pytest.param(
+ """
+ target = page.locator("#electricDate")
+ await getattr(target, "fill")("2026-07-01")
+ """,
+ id="test_rejects_dynamic_dispatch_on_locator_alias",
+ ),
+ pytest.param(
+ """
+ async def clear(target):
+ await target.evaluate("node => node.remove()")
+ await clear(page.locator("#electricDate"))
+ """,
+ id="test_rejects_helper_receiving_browser_object",
+ ),
+ pytest.param(
+ """
+ async def clear(target):
+ await target.evaluate("node => node.remove()")
+ await clear(target=page.locator("#electricDate"))
+ """,
+ id="test_rejects_helper_receiving_browser_keyword_object",
+ ),
+ pytest.param(
+ """
+ async def navigate(page_arg):
+ await page_arg.goto("https://example.com/other")
+ await navigate(page_arg=page)
+ """,
+ id="test_rejects_helper_receiving_page_keyword_object",
+ ),
+ ],
+ )
+ def test_owned_attempt_drops_ambiguous_only_sibling(self, sibling_code: str) -> None:
+ ctx = _quote_ctx()
+ submitted = _submitted_with_sibling_code(sibling_code)
+
with capture_logs() as logs:
- result = await _update_workflow(
- {"workflow_yaml": _metadata_less_output_yaml()}, ctx, allow_missing_credentials=True
- )
- assert result["ok"] is False
- assert "metadata_convergence_directive" not in result["data"]
- assert not ctx.output_contract_armed_directive_fingerprint_by_signature
- assert [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT] == []
-
- @pytest.mark.asyncio
- async def test_multiple_missing_labels_fail_closed(self, monkeypatch: pytest.MonkeyPatch) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _code_only_ctx()
- result = await _update_workflow(
- {"workflow_yaml": _metadata_less_two_block_yaml()}, ctx, allow_missing_credentials=True
- )
- assert result["ok"] is False
- assert ctx.latest_recorded_build_test_outcome.reason_code == "metadata_reject"
- assert "metadata_convergence_directive" not in result["data"]
-
- @pytest.mark.asyncio
- async def test_churn_stash_fires_at_cap_with_arming_active(self, monkeypatch: pytest.MonkeyPatch) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _code_only_ctx()
- yaml_text = _metadata_less_output_yaml()
- for index in range(MAX_CODE_AUTHORING_GUARDRAIL_REJECTS - 1):
- result = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
- assert result["ok"] is False
- assert result["data"]["metadata_convergence_directive"]["rung"] in (1, 2)
- assert ctx.code_authoring_guardrail_reject_count == index + 1
- assert ctx.blocker_signal is None
- final = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
- assert final["ok"] is False
- assert ctx.code_authoring_guardrail_reject_count == MAX_CODE_AUTHORING_GUARDRAIL_REJECTS
- churn = ctx.blocker_signal
- assert isinstance(churn, CopilotToolBlockerSignal)
- assert churn.internal_reason_code == "code_authoring_guardrail_churn"
-
- @pytest.mark.asyncio
- async def test_seam_replay_emits_once_then_escalates(self, monkeypatch: pytest.MonkeyPatch) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _code_only_ctx()
- yaml_text = _metadata_less_output_yaml()
- with capture_logs() as first_logs:
- first = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
- with capture_logs() as second_logs:
- second = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
- assert first["data"]["metadata_convergence_directive"]["rung"] == 1
- assert second["data"]["metadata_convergence_directive"]["rung"] == 2
- assert len([log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]) == 1
- second_emits = [log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
- assert len(second_emits) == 1 and second_emits[0]["rung"] == 2
- assert not ctx.output_contract_spine_directive_blockers_by_attempt_key
- assert not ctx.output_contract_actuation_by_signature
-
- @pytest.mark.asyncio
- async def test_recorded_reject_identity_arms_and_next_author_consumes(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _code_only_ctx()
- yaml_text = _recorded_metadata_reject_yaml()
- assert not ctx.output_contract_armed_directive_fingerprint_by_signature
- with capture_logs() as first_logs:
- first = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
- assert first["ok"] is False
- assert ctx.latest_recorded_build_test_outcome.reason_code == "metadata_reject"
- directive = first["data"]["metadata_convergence_directive"]
- assert directive["rung"] == 1
- assert "declared_goal" in directive["missing_fields_by_label"][_RECORDED_METADATA_REJECT_BLOCK_LABEL]
- assert len([log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]) == 1
- assert ctx.output_contract_armed_directive_fingerprint_by_signature
-
- second = await _update_workflow({"workflow_yaml": yaml_text}, ctx, allow_missing_credentials=True)
- escalated = second["data"]["metadata_convergence_directive"]
- assert escalated["rung"] == 2
- assert _RECORDED_METADATA_REJECT_BLOCK_LABEL in escalated["metadata_fill_in_skeleton"]
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ assert result.violations == []
+ assert result.substitutions is not None
+ blocks = _code_blocks(parse_workflow_yaml(result.workflow_yaml))
+ assert "preserved_code" not in blocks
+ dropped = [log for log in logs if log["event"] == "copilot_spine_stale_rung_dropped"]
+ assert dropped and dropped[0]["dropped_labels"] == ["preserved_code"]
+ assert dropped[0]["dropped_actions"]
-class TestWholeTrajectoryImposition:
- def test_imposes_over_unscouted_browser_fill_in_selected_block(self) -> None:
- ctx = _quote_ctx()
+ def test_unowned_attempt_still_rejects_ambiguous_browser_mutation(self) -> None:
+ ctx = _records_spine_ctx()
submitted = _yaml(
- """
- title: Quote
+ f"""
+ title: Records
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
- await page.locator("#electricDate").fill("2026-07-01")
- await page.locator("#coverage-next").click()
+ await page.locator("#stage-a").click()
+ - block_type: code
+ label: helper_stage
+ code: |
+ target = page.locator("#stage-z")
+ await getattr(target, "fill")("2026-07-01")
"""
)
result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
- assert result.violations == []
- assert result.substitutions is not None
- code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
- assert "#electricDate" not in code
- assert code.index('page.locator("#zip")') < code.index('page.locator("#continue")')
- assert code.index('page.locator("#continue")') < code.index('page.locator("#coverage-next")')
+ assert ctx.spine_imposition_owned_attempt is False
+ assert any("ambiguous browser action" in violation for violation in result.violations)
+ assert result.substitutions is None
- def test_entry_opener_drop_is_instrumented_not_silently_forgiven(self) -> None:
+ def test_preserves_simple_extraction_only_block(self) -> None:
ctx = _quote_ctx()
- ctx.scout_trajectory.insert(
- 0,
- {"tool_name": "click", "selector": "button", "source_url": _QUOTE_URL, "trajectory_index": 0},
- )
submitted = _yaml(
- """
+ f"""
title: Quote
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
await page.locator("#zip").fill(str(zip_code))
await page.locator("#continue").click()
- await page.locator("#electricDate").fill("2026-07-01")
- await page.locator("#coverage-next").click()
+ - block_type: code
+ label: summarize_quote
+ code: |
+ heading = await page.locator("h1").inner_text()
+ return {{"heading": heading}}
"""
)
- with capture_logs() as logs:
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
assert result.violations == []
assert result.substitutions is not None
- forgiven = result.substitutions["forgiven_entry_opener_drops"]
- assert [record["reason_code"] for record in forgiven] == ["ambiguous_bare_selector"]
- assert forgiven[0]["forgiveness"] == "entry_opener_superseded_by_locator_provenance"
- assert any(entry.get("event") == "copilot_imposition_forgave_entry_opener_drop" for entry in logs)
+ blocks = _code_blocks(parse_workflow_yaml(result.workflow_yaml))
+ assert "#coverage-next" in str(blocks[workflow_update_module._SYNTHESIZED_BLOCK_LABEL]["code"])
+ assert str(blocks["summarize_quote"]["code"]).strip() == (
+ 'heading = await page.locator("h1").inner_text()\nreturn {"heading": heading}'
+ )
- def test_imposes_over_unscouted_selected_block_extra_click(self) -> None:
+ def test_preserves_read_only_selected_extraction_suffix_after_exact_spine(self) -> None:
ctx = _quote_ctx()
+ label = workflow_update_module._SYNTHESIZED_BLOCK_LABEL
+ metadata = _terminal_metadata(label, "quote")
+ metadata["claimed_outcomes"][0]["goal_value_paths"] = ["heading"]
+ metadata["terminal_verifier_expectations"][0]["goal_value_paths"] = ["heading"]
+ ctx.raw_code_artifact_metadata = [metadata]
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = (
+ textwrap.dedent(synthesized.code).rstrip()
+ + '\nheading = await page.locator("h1").inner_text()\nreturn {"heading": heading}\n'
+ )
submitted = _yaml(
- """
+ f"""
title: Quote
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: {label}
code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
- await page.locator("#electricDate").click()
- await page.locator("#coverage-next").click()
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
@@ -12622,27 +13601,39 @@ class TestWholeTrajectoryImposition:
assert result.violations == []
assert result.substitutions is not None
- code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
- assert "#electricDate" not in code
- assert 'page.locator("#zip")' in code
- assert 'page.locator("#continue")' in code
- assert 'page.locator("#coverage-next")' in code
+ assert result.substitutions["preserved_extraction_suffix"] is True
+ parsed = parse_workflow_yaml(result.workflow_yaml)
+ code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
+ assert len(code_blocks) > 1
+ assert code_blocks[-1]["label"] == label
+ output_code = str(code_blocks[-1]["code"]).strip()
+ assert output_code == 'heading = await page.locator("h1").inner_text()\nreturn {"heading": heading}'
+ browser_code = "\n".join(str(block.get("code") or "") for block in code_blocks[:-1])
+ assert 'await page.locator("#coverage-next").click()' in browser_code
+ assert all("heading" not in str(block.get("code") or "") for block in code_blocks[:-1])
- def test_p10_shaped_selected_surplus_browser_mutations_are_discarded(self) -> None:
+ def test_preserves_page_read_only_selected_extraction_suffix_after_exact_spine(self) -> None:
ctx = _quote_ctx()
+ label = workflow_update_module._SYNTHESIZED_BLOCK_LABEL
+ metadata = _terminal_metadata(label, "quote")
+ metadata["claimed_outcomes"][0]["goal_value_paths"] = ["heading"]
+ metadata["terminal_verifier_expectations"][0]["goal_value_paths"] = ["heading"]
+ ctx.raw_code_artifact_metadata = [metadata]
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = (
+ textwrap.dedent(synthesized.code).rstrip()
+ + '\nheading = await page.inner_text("h1")\nreturn {"heading": heading}\n'
+ )
submitted = _yaml(
- """
+ f"""
title: Quote
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: {label}
code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
- await page.locator("#electricPlan").select_option("basic")
- await page.locator("#electricDate").fill("2026-07-01")
- await page.locator("#coverage-next").click()
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
@@ -12650,106 +13641,109 @@ class TestWholeTrajectoryImposition:
assert result.violations == []
assert result.substitutions is not None
- code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
- assert "#electricPlan" not in code
- assert "#electricDate" not in code
- assert result.substitutions["source_trajectory_count"] == 3
- assert code.index('page.locator("#zip")') < code.index('page.locator("#continue")')
- assert code.index('page.locator("#continue")') < code.index('page.locator("#coverage-next")')
+ assert result.substitutions["preserved_extraction_suffix"] is True
+ parsed = parse_workflow_yaml(result.workflow_yaml)
+ code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
+ assert len(code_blocks) > 1
+ assert code_blocks[-1]["label"] == label
+ output_code = str(code_blocks[-1]["code"]).strip()
+ assert output_code == 'heading = await page.inner_text("h1")\nreturn {"heading": heading}'
+ browser_code = "\n".join(str(block.get("code") or "") for block in code_blocks[:-1])
+ assert 'await page.locator("#coverage-next").click()' in browser_code
+ assert all("heading" not in str(block.get("code") or "") for block in code_blocks[:-1])
- def test_wrong_selected_block_receiver_is_overwritten_by_scout_spine(self) -> None:
+ def test_rejects_selected_extraction_suffix_browser_mutation(self) -> None:
ctx = _quote_ctx()
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = (
+ textwrap.dedent(synthesized.code).rstrip() + '\nawait page.locator("#electricDate").fill("2026-07-01")\n'
+ )
submitted = _yaml(
- """
+ f"""
title: Quote
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
- await page.locator("#wrongZip").fill(str(zip_code))
- await page.locator("#continue").click()
- await page.locator("#coverage-next").click()
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
- assert result.violations == []
- assert result.substitutions is not None
- code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
- assert "#wrongZip" not in code
- assert 'page.locator("#zip")' in code
+ assert any(
+ "extraction suffix contains unscouted browser action" in violation for violation in result.violations
+ )
+ assert result.substitutions is None
- def test_selected_alias_locator_extra_is_discarded_by_imposition(self) -> None:
+ def test_rejects_selected_extraction_suffix_alias_browser_mutation(self) -> None:
ctx = _quote_ctx()
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = (
+ textwrap.dedent(synthesized.code).rstrip()
+ + '\ntarget = page.locator("#electricDate")\nawait target.fill("2026-07-01")\n'
+ )
submitted = _yaml(
- """
+ f"""
title: Quote
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
- target = page.locator("#electricDate")
- await target.fill("2026-07-01")
- await page.locator("#coverage-next").click()
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
- assert result.violations == []
- assert result.substitutions is not None
- code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
- assert "#electricDate" not in code
- assert 'target = page.locator("#electricDate")' not in code
- assert 'page.locator("#zip")' in code
- assert 'page.locator("#coverage-next")' in code
+ assert any(
+ "extraction suffix contains ambiguous browser action" in violation for violation in result.violations
+ )
+ assert result.substitutions is None
- def test_selected_helper_extra_is_discarded_by_imposition(self) -> None:
+ def test_owned_attempt_drops_ambiguous_helper_browser_mutation(self) -> None:
ctx = _quote_ctx()
submitted = _yaml(
- """
+ f"""
title: Quote
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
await page.locator("#zip").fill(str(zip_code))
await page.locator("#continue").click()
- async def clear(target):
- await target.evaluate("node => node.remove()")
- await clear(target=page.locator("#electricDate"))
- await page.locator("#coverage-next").click()
+ - block_type: code
+ label: helper_step
+ code: |
+ async def fill(locator, value):
+ await locator.fill(value)
+ target = page.locator("#electricDate")
+ await fill(target, "2026-07-01")
"""
)
result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
assert result.violations == []
- assert result.substitutions is not None
- code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
- assert "#electricDate" not in code
- assert "async def clear" not in code
+ assert "helper_step" not in _code_blocks(parse_workflow_yaml(result.workflow_yaml))
- def test_selected_dynamic_extra_is_discarded_by_imposition(self) -> None:
+ def test_multi_screen_trajectory_persists_in_order_with_proven_locators(self) -> None:
ctx = _quote_ctx()
submitted = _yaml(
- """
+ f"""
title: Quote
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
await page.locator("#zip").fill(str(zip_code))
await page.locator("#continue").click()
- await getattr(page.locator("#electricDate"), "fill")("2026-07-01")
- await page.locator("#coverage-next").click()
"""
)
@@ -12757,296 +13751,255 @@ class TestWholeTrajectoryImposition:
assert result.violations == []
assert result.substitutions is not None
- code = str(_single_code_block(parse_workflow_yaml(result.workflow_yaml))["code"])
- assert "#electricDate" not in code
- assert "getattr" not in code
+ block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))
+ code = str(block["code"])
+ assert code.index('page.locator("#zip")') < code.index('page.locator("#continue")')
+ assert code.index('page.locator("#continue")') < code.index('page.locator("#coverage-next")')
- def test_rejects_extra_changed_block_with_unscouted_browser_mutation(self) -> None:
- ctx = _records_spine_ctx()
+ @pytest.mark.asyncio
+ async def test_changed_selected_browser_action_args_do_not_preserve_submitted_extraction(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _quote_ctx()
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = textwrap.dedent(synthesized.code).replace(
+ 'await page.locator("#zip").fill(str(zip_code))',
+ 'await page.locator("#zip").fill("99999")',
+ )
submitted = _yaml(
f"""
- title: Records
+ title: Quote
workflow_definition:
blocks:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
+ parameter_keys: [zip_code]
code: |
- await page.locator("#stage-a").click()
- await page.locator("#stage-b").click()
- await page.locator("#stage-c").click()
- - block_type: code
- label: invented_browser_step
- code: |
- await page.locator("#electricDate").fill("2026-07-01")
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
- with capture_logs() as logs:
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
-
- assert ctx.spine_imposition_owned_attempt is False
- assert any("unscouted browser action" in violation for violation in result.violations)
- assert any("never_captured" in violation for violation in result.violations)
- assert result.substitutions is None
- events = [log for log in logs if log["event"] == "copilot_browser_surface_rejection_provenance"]
- assert events and events[0]["kind"] == "never_captured"
-
- @pytest.mark.parametrize(
- "sibling_code",
- [
- pytest.param(
- """
- await page.evaluate("window.localStorage.clear()")
- """,
- id="test_rejects_unknown_page_receiver_call",
- ),
- pytest.param(
- """
- await page.locator("#electricDate").evaluate("node => node.remove()")
- """,
- id="test_rejects_unknown_direct_locator_receiver_call",
- ),
- pytest.param(
- """
- target = page.locator("#electricDate")
- await target.evaluate("node => node.remove()")
- """,
- id="test_rejects_unknown_locator_alias_receiver_call",
- ),
- pytest.param(
- """
- p = page
- await p.goto("https://example.com/other")
- """,
- id="test_rejects_page_alias_mutation",
- ),
- pytest.param(
- """
- p = page
- q = p
- await q.goto("https://example.com/other")
- """,
- id="test_rejects_transitive_page_alias_mutation",
- ),
- pytest.param(
- """
- target = page.locator("#electricDate")
- other = target
- await other.fill("2026-07-01")
- """,
- id="test_rejects_transitive_locator_alias_mutation",
- ),
- pytest.param(
- """
- fill_electric = page.locator("#electricDate").fill
- await fill_electric("2026-07-01")
- """,
- id="test_rejects_bound_method_alias_mutation",
- ),
- pytest.param(
- """
- fill_electric = page.locator("#electricDate").fill
- other = fill_electric
- await other("2026-07-01")
- """,
- id="test_rejects_transitive_bound_method_alias_mutation",
- ),
- pytest.param(
- """
- await getattr(page, "goto")("https://example.com/other")
- """,
- id="test_rejects_dynamic_dispatch_on_page",
- ),
- pytest.param(
- """
- target = page.locator("#electricDate")
- await getattr(target, "fill")("2026-07-01")
- """,
- id="test_rejects_dynamic_dispatch_on_locator_alias",
- ),
- pytest.param(
- """
- async def clear(target):
- await target.evaluate("node => node.remove()")
- await clear(page.locator("#electricDate"))
- """,
- id="test_rejects_helper_receiving_browser_object",
- ),
- pytest.param(
- """
- async def clear(target):
- await target.evaluate("node => node.remove()")
- await clear(target=page.locator("#electricDate"))
- """,
- id="test_rejects_helper_receiving_browser_keyword_object",
- ),
- pytest.param(
- """
- async def navigate(page_arg):
- await page_arg.goto("https://example.com/other")
- await navigate(page_arg=page)
- """,
- id="test_rejects_helper_receiving_page_keyword_object",
- ),
- ],
- )
- def test_owned_attempt_drops_ambiguous_only_sibling(self, sibling_code: str) -> None:
- ctx = _quote_ctx()
- submitted = _submitted_with_sibling_code(sibling_code)
-
- with capture_logs() as logs:
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
-
- assert result.violations == []
- assert result.substitutions is not None
- blocks = _code_blocks(parse_workflow_yaml(result.workflow_yaml))
- assert "preserved_code" not in blocks
- dropped = [log for log in logs if log["event"] == "copilot_spine_stale_rung_dropped"]
- assert dropped and dropped[0]["dropped_labels"] == ["preserved_code"]
- assert dropped[0]["dropped_actions"]
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "code_artifact_metadata": [
+ _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote")
+ ],
+ },
+ ctx,
+ )
- def test_unowned_attempt_still_rejects_ambiguous_browser_mutation(self) -> None:
- ctx = _records_spine_ctx()
+ assert result["ok"] is True
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ assert isinstance(parsed, dict)
+ code = str(_single_code_block(parsed)["code"])
+ assert 'await page.locator("#zip").fill(str(zip_code))' in code
+ assert 'await page.locator("#zip").fill("99999")' not in code
+
+ @pytest.mark.asyncio
+ async def test_assigned_parameter_key_does_not_preserve_submitted_extraction(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _quote_ctx()
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = (
+ 'zip_code = "99999"\n'
+ + textwrap.dedent(synthesized.code).rstrip()
+ + f'\n{workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output = {{"quote": "Q-001"}}\n'
+ + f"return {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output\n"
+ )
submitted = _yaml(
f"""
- title: Records
+ title: Quote
workflow_definition:
+ parameters:
+ - {{parameter_type: workflow, workflow_parameter_type: string, key: zip_code, default_value: "02110"}}
blocks:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
+ parameter_keys: [zip_code]
code: |
- await page.locator("#stage-a").click()
- - block_type: code
- label: helper_stage
- code: |
- target = page.locator("#stage-z")
- await getattr(target, "fill")("2026-07-01")
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "code_artifact_metadata": [
+ _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote")
+ ],
+ },
+ ctx,
+ )
- assert ctx.spine_imposition_owned_attempt is False
- assert any("ambiguous browser action" in violation for violation in result.violations)
- assert result.substitutions is None
+ assert result["ok"] is False
+ assert "assigns synthesized parameter key(s) `zip_code`" in result["error"]
- def test_preserves_simple_extraction_only_block(self) -> None:
+ @pytest.mark.asyncio
+ async def test_destructured_parameter_key_does_not_preserve_submitted_extraction(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _quote_ctx()
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = (
+ '(zip_code,) = ("99999",)\n'
+ + textwrap.dedent(synthesized.code).rstrip()
+ + f'\n{workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output = {{"quote": "Q-001"}}\n'
+ + f"return {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output\n"
+ )
submitted = _yaml(
f"""
title: Quote
workflow_definition:
+ parameters:
+ - {{parameter_type: workflow, workflow_parameter_type: string, key: zip_code, default_value: "02110"}}
blocks:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
+ parameter_keys: [zip_code]
code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
- - block_type: code
- label: summarize_quote
- code: |
- heading = await page.locator("h1").inner_text()
- return {{"heading": heading}}
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
-
- assert result.violations == []
- assert result.substitutions is not None
- blocks = _code_blocks(parse_workflow_yaml(result.workflow_yaml))
- assert "#coverage-next" in str(blocks[workflow_update_module._SYNTHESIZED_BLOCK_LABEL]["code"])
- assert str(blocks["summarize_quote"]["code"]).strip() == (
- 'heading = await page.locator("h1").inner_text()\nreturn {"heading": heading}'
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "code_artifact_metadata": [
+ _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote")
+ ],
+ },
+ ctx,
)
- def test_preserves_read_only_selected_extraction_suffix_after_exact_spine(self) -> None:
+ assert result["ok"] is False
+ assert "assigns synthesized parameter key(s) `zip_code`" in result["error"]
+
+ @pytest.mark.asyncio
+ async def test_starred_parameter_key_does_not_preserve_submitted_extraction(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _quote_ctx()
- label = workflow_update_module._SYNTHESIZED_BLOCK_LABEL
- metadata = _terminal_metadata(label, "quote")
- metadata["claimed_outcomes"][0]["goal_value_paths"] = ["heading"]
- metadata["terminal_verifier_expectations"][0]["goal_value_paths"] = ["heading"]
- ctx.raw_code_artifact_metadata = [metadata]
synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
assert synthesized is not None
submitted_code = (
- textwrap.dedent(synthesized.code).rstrip()
- + '\nheading = await page.locator("h1").inner_text()\nreturn {"heading": heading}\n'
+ '*zip_code, = ["99999"]\n'
+ + textwrap.dedent(synthesized.code).rstrip()
+ + f'\n{workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output = {{"quote": "Q-001"}}\n'
+ + f"return {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output\n"
)
submitted = _yaml(
f"""
title: Quote
workflow_definition:
+ parameters:
+ - {{parameter_type: workflow, workflow_parameter_type: string, key: zip_code, default_value: "02110"}}
blocks:
- block_type: code
- label: {label}
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
+ parameter_keys: [zip_code]
code: |
{textwrap.indent(submitted_code, " " * 18)}
"""
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "code_artifact_metadata": [
+ _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote")
+ ],
+ },
+ ctx,
+ )
- assert result.violations == []
- assert result.substitutions is not None
- assert result.substitutions["preserved_extraction_suffix"] is True
- parsed = parse_workflow_yaml(result.workflow_yaml)
- code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
- assert len(code_blocks) > 1
- assert code_blocks[-1]["label"] == label
- output_code = str(code_blocks[-1]["code"]).strip()
- assert output_code == 'heading = await page.locator("h1").inner_text()\nreturn {"heading": heading}'
- browser_code = "\n".join(str(block.get("code") or "") for block in code_blocks[:-1])
- assert 'await page.locator("#coverage-next").click()' in browser_code
- assert all("heading" not in str(block.get("code") or "") for block in code_blocks[:-1])
+ assert result["ok"] is False
+ assert "assigns synthesized parameter key(s) `zip_code`" in result["error"]
- def test_preserves_page_read_only_selected_extraction_suffix_after_exact_spine(self) -> None:
+ @pytest.mark.asyncio
+ async def test_alias_reconciled_selected_spine_preserves_submitted_extraction(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _quote_ctx()
- label = workflow_update_module._SYNTHESIZED_BLOCK_LABEL
- metadata = _terminal_metadata(label, "quote")
- metadata["claimed_outcomes"][0]["goal_value_paths"] = ["heading"]
- metadata["terminal_verifier_expectations"][0]["goal_value_paths"] = ["heading"]
- ctx.raw_code_artifact_metadata = [metadata]
synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
assert synthesized is not None
+ label = workflow_update_module._SYNTHESIZED_BLOCK_LABEL
submitted_code = (
- textwrap.dedent(synthesized.code).rstrip()
- + '\nheading = await page.inner_text("h1")\nreturn {"heading": heading}\n'
+ textwrap.dedent(synthesized.code).replace("zip_code", "postal_code").rstrip()
+ + f'\n{label}_output = {{"quote": "Q-001"}}\nreturn {label}_output\n'
)
submitted = _yaml(
f"""
title: Quote
workflow_definition:
+ parameters:
+ - {{parameter_type: workflow, workflow_parameter_type: string, key: postal_code, default_value: "02110"}}
blocks:
- block_type: code
label: {label}
+ parameter_keys: [postal_code]
code: |
{textwrap.indent(submitted_code, " " * 18)}
"""
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "code_artifact_metadata": [
+ {
+ **_terminal_metadata(label, "quote"),
+ "claimed_outcomes": [
+ {
+ **_terminal_metadata(label, "quote")["claimed_outcomes"][0],
+ "goal_value_paths": ["quote"],
+ }
+ ],
+ "terminal_verifier_expectations": [
+ {
+ **_terminal_metadata(label, "quote")["terminal_verifier_expectations"][0],
+ "goal_value_paths": ["quote"],
+ }
+ ],
+ }
+ ],
+ },
+ ctx,
+ )
- assert result.violations == []
- assert result.substitutions is not None
- assert result.substitutions["preserved_extraction_suffix"] is True
- parsed = parse_workflow_yaml(result.workflow_yaml)
+ assert result["ok"] is True
+ substitutions = result["data"]["imposed_substitutions"]
+ assert substitutions["preserved_submitted_extraction_code"] is True
+ assert substitutions["parameter_aliases"] == {"zip_code": "postal_code"}
+ assert "scrubbed_stale_selected_goal_value_paths" not in substitutions
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ assert isinstance(parsed, dict)
code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
assert len(code_blocks) > 1
- assert code_blocks[-1]["label"] == label
- output_code = str(code_blocks[-1]["code"]).strip()
- assert output_code == 'heading = await page.inner_text("h1")\nreturn {"heading": heading}'
- browser_code = "\n".join(str(block.get("code") or "") for block in code_blocks[:-1])
- assert 'await page.locator("#coverage-next").click()' in browser_code
- assert all("heading" not in str(block.get("code") or "") for block in code_blocks[:-1])
+ block = _code_blocks(parsed)[label]
+ browser_code = "\n".join(str(stage.get("code") or "") for stage in code_blocks[:-1])
+ assert all(stage.get("parameter_keys") == ["postal_code"] for stage in code_blocks[:-1])
+ assert "postal_code" in browser_code
+ assert "zip_code" not in browser_code
+ code = str(block["code"])
+ assert f"return {label}_output" in code
+ assert "postal_code" not in code
+ artifact = ctx.code_artifact_metadata[label]
+ assert workflow_update_module._artifact_declares_goal_values(artifact)
- def test_rejects_selected_extraction_suffix_browser_mutation(self) -> None:
+ @pytest.mark.asyncio
+ async def test_metadata_selected_extraction_only_imposes_scout_spine(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- submitted_code = (
- textwrap.dedent(synthesized.code).rstrip() + '\nawait page.locator("#electricDate").fill("2026-07-01")\n'
- )
submitted = _yaml(
f"""
title: Quote
@@ -13055,24 +14008,55 @@ class TestWholeTrajectoryImposition:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
-{textwrap.indent(submitted_code, " " * 18)}
+ records = [{{"number": "Q-001"}}]
"""
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
-
- assert any(
- "extraction suffix contains unscouted browser action" in violation for violation in result.violations
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "code_artifact_metadata": [
+ _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote result")
+ ],
+ },
+ ctx,
)
- assert result.substitutions is None
- def test_rejects_selected_extraction_suffix_alias_browser_mutation(self) -> None:
+ assert result["ok"] is True
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ assert isinstance(parsed, dict)
+ code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
+ assert len(code_blocks) > 1
+ block = _code_blocks(parsed)[workflow_update_module._SYNTHESIZED_BLOCK_LABEL]
+ code = "\n".join(str(stage.get("code") or "") for stage in code_blocks[:-1])
+ output_code = str(block["code"])
+ assert code_blocks[-1]["label"] == workflow_update_module._SYNTHESIZED_BLOCK_LABEL
+ assert result["data"]["imposed_substitutions"]["source_trajectory_count"] == 3
+ assert 'await page.locator("#zip").fill(str(zip_code))' in code
+ assert 'await page.locator("#continue").click()' in code
+ assert 'await page.locator("#coverage-next").click()' in code
+ assert 'records = [{"number": "Q-001"}]' in output_code
+ assert 'return {"records": records}' in output_code
+ assert all("records" not in str(stage.get("code") or "") for stage in code_blocks[:-1])
+
+ @pytest.mark.asyncio
+ async def test_author_metadata_reject_reopens_changed_collapsed_code_block(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- submitted_code = (
- textwrap.dedent(synthesized.code).rstrip()
- + '\ntarget = page.locator("#electricDate")\nawait target.fill("2026-07-01")\n'
+ ctx.update_workflow_called = True
+ ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("metadata_reject")
+ ctx.workflow_yaml = _yaml(
+ f"""
+ title: Quote
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
+ code: |
+ records = [{{"quote": "old"}}]
+ """
)
submitted = _yaml(
f"""
@@ -13082,20 +14066,91 @@ class TestWholeTrajectoryImposition:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
-{textwrap.indent(submitted_code, " " * 18)}
+ records = [{{"number": "Q-001"}}]
"""
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ result = await _update_workflow(
+ {
+ "workflow_yaml": submitted,
+ "code_artifact_metadata": [
+ _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote result")
+ ],
+ },
+ ctx,
+ )
- assert any(
- "extraction suffix contains ambiguous browser action" in violation for violation in result.violations
+ assert result["ok"] is True
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ assert isinstance(parsed, dict)
+ code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
+ block = _code_blocks(parsed)[workflow_update_module._SYNTHESIZED_BLOCK_LABEL]
+ browser_code = "\n".join(str(stage.get("code") or "") for stage in code_blocks[:-1])
+ code = str(block["code"])
+ assert result["data"]["imposed_substitutions"]["source_trajectory_count"] == 3
+ assert result["data"]["imposed_substitutions"]["separated_browser_stage_count"] > 1
+ assert code_blocks[-1]["label"] == workflow_update_module._SYNTHESIZED_BLOCK_LABEL
+ assert 'await page.locator("#zip").fill(str(zip_code))' in browser_code
+ assert 'await page.locator("#continue").click()' in browser_code
+ assert 'await page.locator("#coverage-next").click()' in browser_code
+ assert 'records = [{"number": "Q-001"}]' not in browser_code
+ assert 'records = [{"number": "Q-001"}]' in code
+ assert 'return {"records": records}' in code
+
+ @pytest.mark.asyncio
+ async def test_author_parameter_reject_reopens_and_preserves_typed_violation(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "type_text",
+ "selector": "#provInput",
+ "source_url": "https://example.com/find-care",
+ "typed_length": 13,
+ "role": "textbox",
+ "accessible_name": "Provider Name",
+ "trajectory_index": 0,
+ }
+ ]
+ ctx.update_workflow_called = True
+ ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("synthesized_parameter_binding_ambiguous")
+ ctx.workflow_yaml = _SUBMITTED_LITERAL_YAML
+
+ result = await _update_workflow({"workflow_yaml": _SUBMITTED_UNKNOWN_COMPUTED_LITERAL_YAML}, ctx)
+
+ assert result["ok"] is False
+ assert "Unable to bind synthesized parameter `provider_name`" in result["error"]
+ repair = result["data"]["authoring_repair_context"]
+ assert repair["reason_code"] == "synthesized_parameter_binding_ambiguous"
+ assert repair["unresolved_names"] == ["provider_name"]
+ assert ctx.workflow_yaml == _SUBMITTED_LITERAL_YAML
+
+ def test_author_ambiguous_selector_reject_reopens_strict_imposition_with_typed_repair_context(self) -> None:
+ ctx = _resale_ctx()
+ ctx.update_workflow_called = True
+ ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("code_safety_reject")
+ ctx.last_code_authoring_repair_context = CodeAuthoringRepairContext(
+ block_label="order_status",
+ reason_code="ambiguous_bare_selector",
+ selector="button",
)
- assert result.substitutions is None
- def test_owned_attempt_drops_ambiguous_helper_browser_mutation(self) -> None:
+ result = workflow_update_module._maybe_impose_synthesized_code_block(_resale_submitted_yaml(), ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))
+ assert 'button[data-action=\\"status\\"]' in str(block["code"])
+
+ def test_author_schema_incompatibility_does_not_reopen_collapsed_code_block(self) -> None:
ctx = _quote_ctx()
- submitted = _yaml(
+ ctx.update_workflow_called = True
+ ctx.synthesized_goal_complete_landed = True
+ ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("schema_incompatibility")
+ ctx.workflow_yaml = _yaml(
f"""
title: Quote
workflow_definition:
@@ -13103,25 +14158,9 @@ class TestWholeTrajectoryImposition:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
- - block_type: code
- label: helper_step
- code: |
- async def fill(locator, value):
- await locator.fill(value)
- target = page.locator("#electricDate")
- await fill(target, "2026-07-01")
+ records = [{{"quote": "old"}}]
"""
)
-
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
-
- assert result.violations == []
- assert "helper_step" not in _code_blocks(parse_workflow_yaml(result.workflow_yaml))
-
- def test_multi_screen_trajectory_persists_in_order_with_proven_locators(self) -> None:
- ctx = _quote_ctx()
submitted = _yaml(
f"""
title: Quote
@@ -13130,170 +14169,193 @@ class TestWholeTrajectoryImposition:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
+ records = [{{"quote": "pending"}}]
"""
)
result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
assert result.violations == []
- assert result.substitutions is not None
- block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))
- code = str(block["code"])
- assert code.index('page.locator("#zip")') < code.index('page.locator("#continue")')
- assert code.index('page.locator("#continue")') < code.index('page.locator("#coverage-next")')
+ assert result.substitutions is None
+ assert result.workflow_yaml == submitted
@pytest.mark.asyncio
- async def test_changed_selected_browser_action_args_do_not_preserve_submitted_extraction(
+ async def test_stale_selected_goal_paths_do_not_block_imposed_scout_spine(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
_stub_successful_update(monkeypatch)
ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- submitted_code = textwrap.dedent(synthesized.code).replace(
- 'await page.locator("#zip").fill(str(zip_code))',
- 'await page.locator("#zip").fill("99999")',
- )
submitted = _yaml(
- f"""
+ """
title: Quote
workflow_definition:
blocks:
- block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- parameter_keys: [zip_code]
+ label: quote_flow
code: |
-{textwrap.indent(submitted_code, " " * 18)}
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ await page.locator("#electricDate").fill("2026-07-01")
+ await page.locator("#coverage-next").click()
"""
)
result = await _update_workflow(
{
"workflow_yaml": submitted,
- "code_artifact_metadata": [
- _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote")
- ],
+ "code_artifact_metadata": [_terminal_metadata("quote_flow", "quote result")],
},
ctx,
)
assert result["ok"] is True
+ assert result["data"]["imposed_substitutions"]["scrubbed_stale_selected_goal_value_paths"] is True
parsed = parse_workflow_yaml(ctx.workflow_yaml)
assert isinstance(parsed, dict)
code = str(_single_code_block(parsed)["code"])
+ assert "#electricDate" not in code
assert 'await page.locator("#zip").fill(str(zip_code))' in code
- assert 'await page.locator("#zip").fill("99999")' not in code
+ artifact = ctx.code_artifact_metadata["quote_flow"]
+ assert not workflow_update_module._artifact_declares_goal_values(artifact)
@pytest.mark.asyncio
- async def test_assigned_parameter_key_does_not_preserve_submitted_extraction(
+ async def test_formation_prepared_directory_run_rescaffolds_metadata_after_imposition_scrub(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
_stub_successful_update(monkeypatch)
- ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- submitted_code = (
- 'zip_code = "99999"\n'
- + textwrap.dedent(synthesized.code).rstrip()
- + f'\n{workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output = {{"quote": "Q-001"}}\n'
- + f"return {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output\n"
+ scaffold = Mock(wraps=workflow_update_module._scaffold_metadata_contract_for_update)
+ envelope = Mock(wraps=workflow_update_module._impose_output_contract_envelope_after_steering)
+ monkeypatch.setattr(workflow_update_module, "_scaffold_metadata_contract_for_update", scaffold)
+ monkeypatch.setattr(workflow_update_module, "_impose_output_contract_envelope_after_steering", envelope)
+ ctx = _code_only_ctx()
+ _enable_imposition(ctx)
+ ctx.scout_trajectory = [
+ {
+ "tool_name": "type_text",
+ "selector": "#npi",
+ "source_url": "https://example.com/directory",
+ "typed_length": 10,
+ "typed_value": "1234567890",
+ "role": "textbox",
+ "accessible_name": "NPI",
+ "trajectory_index": 0,
+ },
+ {
+ "tool_name": "click",
+ "selector": "#search_by",
+ "source_url": "https://example.com/directory",
+ "trajectory_index": 1,
+ },
+ ]
+ scouting_module._mint_current_loaded_result_source(
+ ctx,
+ {
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [
+ {"selector": "#coastalCard", "text": "Provider record is visible", "row_count": 1}
+ ],
+ },
+ url="https://example.com/directory",
+ )
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ _typed_completion_criterion(
+ id="requested_npi",
+ output_path="output.npi",
+ level="run",
+ method_mandated=False,
+ kind="outcome",
+ )
+ ]
)
submitted = _yaml(
- f"""
- title: Quote
+ """
+ title: Directory lookup
workflow_definition:
- parameters:
- - {{parameter_type: workflow, workflow_parameter_type: string, key: zip_code, default_value: "02110"}}
blocks:
- block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- parameter_keys: [zip_code]
+ label: directory_flow
code: |
-{textwrap.indent(submitted_code, " " * 18)}
+ await page.locator("#npi").fill(str(npi))
+ await page.locator("#search_by").click()
+ await page.locator("#coastalCard").wait_for(state="visible")
"""
)
+ metadata = [
+ {
+ "block_label": "directory_flow",
+ "claimed_outcomes": [{"goal_value_paths": ["output.npi"]}],
+ "terminal_verifier_expectations": [{"goal_value_paths": ["output.npi"]}],
+ }
+ ]
result = await _update_workflow(
- {
- "workflow_yaml": submitted,
- "code_artifact_metadata": [
- _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote")
- ],
- },
+ {"workflow_yaml": submitted, "code_artifact_metadata": metadata},
ctx,
+ allow_static_output_uncertainty=True,
+ formation_prepared=True,
)
assert result["ok"] is False
- assert "assigns synthesized parameter key(s) `zip_code`" in result["error"]
+ assert envelope.call_count == 1
+ assert scaffold.call_count == 1
+ artifact = workflow_update_module._metadata_item_for_block_label(
+ ctx.raw_code_artifact_metadata, "directory_flow"
+ )
+ assert artifact is not None
+ assert not workflow_update_module._artifact_declares_goal_values(artifact)
@pytest.mark.asyncio
- async def test_destructured_parameter_key_does_not_preserve_submitted_extraction(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- submitted_code = (
- '(zip_code,) = ("99999",)\n'
- + textwrap.dedent(synthesized.code).rstrip()
- + f'\n{workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output = {{"quote": "Q-001"}}\n'
- + f"return {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output\n"
- )
+ async def test_metadata_selected_page_goto_extra_is_discarded(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _quote_ctx()
submitted = _yaml(
- f"""
+ """
title: Quote
workflow_definition:
- parameters:
- - {{parameter_type: workflow, workflow_parameter_type: string, key: zip_code, default_value: "02110"}}
blocks:
- block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- parameter_keys: [zip_code]
+ label: quote_flow
code: |
-{textwrap.indent(submitted_code, " " * 18)}
+ await page.goto("https://example.com/other")
+ records = [{"number": "Q-001"}]
"""
)
result = await _update_workflow(
{
"workflow_yaml": submitted,
- "code_artifact_metadata": [
- _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote")
- ],
+ "code_artifact_metadata": [_terminal_metadata("quote_flow", "quote result")],
},
ctx,
)
- assert result["ok"] is False
- assert "assigns synthesized parameter key(s) `zip_code`" in result["error"]
+ assert result["ok"] is True
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ assert isinstance(parsed, dict)
+ code = str(_single_code_block(parsed)["code"])
+ assert 'page.goto("https://example.com/other")' not in code
+ assert 'records = [{"number": "Q-001"}]' not in code
+ assert 'await page.locator("#zip").fill(str(zip_code))' in code
+ assert result["data"]["imposed_substitutions"]["scrubbed_stale_selected_goal_value_paths"] is True
@pytest.mark.asyncio
- async def test_starred_parameter_key_does_not_preserve_submitted_extraction(
+ async def test_valid_selected_extraction_suffix_keeps_goal_path_metadata(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
_stub_successful_update(monkeypatch)
ctx = _quote_ctx()
synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
assert synthesized is not None
- submitted_code = (
- '*zip_code, = ["99999"]\n'
- + textwrap.dedent(synthesized.code).rstrip()
- + f'\n{workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output = {{"quote": "Q-001"}}\n'
- + f"return {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}_output\n"
- )
+ submitted_code = textwrap.dedent(synthesized.code).rstrip() + '\nreturn {"records": [{"number": "Q-001"}]}\n'
submitted = _yaml(
f"""
title: Quote
workflow_definition:
- parameters:
- - {{parameter_type: workflow, workflow_parameter_type: string, key: zip_code, default_value: "02110"}}
blocks:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- parameter_keys: [zip_code]
code: |
{textwrap.indent(submitted_code, " " * 18)}
"""
@@ -13303,17 +14365,19 @@ class TestWholeTrajectoryImposition:
{
"workflow_yaml": submitted,
"code_artifact_metadata": [
- _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote")
+ _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote result")
],
},
ctx,
)
- assert result["ok"] is False
- assert "assigns synthesized parameter key(s) `zip_code`" in result["error"]
+ assert result["ok"] is True
+ assert result["data"]["imposed_substitutions"]["preserved_extraction_suffix"] is True
+ artifact = ctx.code_artifact_metadata[workflow_update_module._SYNTHESIZED_BLOCK_LABEL]
+ assert workflow_update_module._artifact_declares_goal_values(artifact)
@pytest.mark.asyncio
- async def test_alias_reconciled_selected_spine_preserves_submitted_extraction(
+ async def test_p9_opaque_self_authored_extraction_metadata_is_preserved(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
_stub_successful_update(monkeypatch)
@@ -13322,72 +14386,58 @@ class TestWholeTrajectoryImposition:
assert synthesized is not None
label = workflow_update_module._SYNTHESIZED_BLOCK_LABEL
submitted_code = (
- textwrap.dedent(synthesized.code).replace("zip_code", "postal_code").rstrip()
- + f'\n{label}_output = {{"quote": "Q-001"}}\nreturn {label}_output\n'
+ textwrap.dedent(synthesized.code).rstrip()
+ + f'\n{label}_output = {{"premium": "$123", "eligible": True}}\nreturn {label}_output\n'
)
submitted = _yaml(
f"""
title: Quote
workflow_definition:
- parameters:
- - {{parameter_type: workflow, workflow_parameter_type: string, key: postal_code, default_value: "02110"}}
blocks:
- block_type: code
label: {label}
- parameter_keys: [postal_code]
code: |
{textwrap.indent(submitted_code, " " * 18)}
"""
)
-
- result = await _update_workflow(
- {
- "workflow_yaml": submitted,
- "code_artifact_metadata": [
- {
- **_terminal_metadata(label, "quote"),
- "claimed_outcomes": [
- {
- **_terminal_metadata(label, "quote")["claimed_outcomes"][0],
- "goal_value_paths": ["quote"],
- }
- ],
- "terminal_verifier_expectations": [
- {
- **_terminal_metadata(label, "quote")["terminal_verifier_expectations"][0],
- "goal_value_paths": ["quote"],
- }
- ],
- }
- ],
- },
- ctx,
+ schema = (
+ '{"type":"object","properties":{"premium":{"type":"string"},'
+ '"eligible":{"type":"boolean"}},"required":["premium","eligible"]}'
)
+ metadata = _terminal_metadata(label, "quote result")
+ metadata["claimed_outcomes"][0]["goal_value_paths"] = ["premium", "eligible"]
+ metadata["claimed_outcomes"][0]["extraction_schema"] = schema
+ metadata["claimed_outcomes"][0]["extraction_schema_provenance"] = "self_authored"
+ metadata["terminal_verifier_expectations"][0]["goal_value_paths"] = ["premium", "eligible"]
+ metadata["terminal_verifier_expectations"][0]["extraction_schema"] = schema
+ metadata["terminal_verifier_expectations"][0]["extraction_schema_provenance"] = "self_authored"
+
+ result = await _update_workflow({"workflow_yaml": submitted, "code_artifact_metadata": [metadata]}, ctx)
assert result["ok"] is True
- substitutions = result["data"]["imposed_substitutions"]
- assert substitutions["preserved_submitted_extraction_code"] is True
- assert substitutions["parameter_aliases"] == {"zip_code": "postal_code"}
- assert "scrubbed_stale_selected_goal_value_paths" not in substitutions
+ assert result["data"]["imposed_substitutions"]["preserved_extraction_suffix"] is True
+ assert "scrubbed_stale_selected_goal_value_paths" not in result["data"]["imposed_substitutions"]
+ artifact = ctx.code_artifact_metadata[label]
+ assert artifact["claimed_outcomes"][0]["goal_value_paths"] == ["premium", "eligible"]
+ assert artifact["terminal_verifier_expectations"][0]["goal_value_paths"] == ["premium", "eligible"]
+ assert artifact["claimed_outcomes"][0]["extraction_schema"] == schema
parsed = parse_workflow_yaml(ctx.workflow_yaml)
assert isinstance(parsed, dict)
code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
assert len(code_blocks) > 1
- block = _code_blocks(parsed)[label]
- browser_code = "\n".join(str(stage.get("code") or "") for stage in code_blocks[:-1])
- assert all(stage.get("parameter_keys") == ["postal_code"] for stage in code_blocks[:-1])
- assert "postal_code" in browser_code
- assert "zip_code" not in browser_code
- code = str(block["code"])
+ code = str(_code_blocks(parsed)[label]["code"])
assert f"return {label}_output" in code
- assert "postal_code" not in code
- artifact = ctx.code_artifact_metadata[label]
- assert workflow_update_module._artifact_declares_goal_values(artifact)
+ assert all(label + "_output" not in str(block.get("code") or "") for block in code_blocks[:-1])
@pytest.mark.asyncio
- async def test_metadata_selected_extraction_only_imposes_scout_spine(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ async def test_invalid_selected_extraction_suffix_keeps_goal_path_rejection(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
_stub_successful_update(monkeypatch)
ctx = _quote_ctx()
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = textwrap.dedent(synthesized.code).rstrip() + "\nheading = 'Review'\n"
submitted = _yaml(
f"""
title: Quote
@@ -13396,7 +14446,7 @@ class TestWholeTrajectoryImposition:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
- records = [{{"number": "Q-001"}}]
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
@@ -13410,42 +14460,15 @@ class TestWholeTrajectoryImposition:
ctx,
)
- assert result["ok"] is True
- parsed = parse_workflow_yaml(ctx.workflow_yaml)
- assert isinstance(parsed, dict)
- code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
- assert len(code_blocks) > 1
- block = _code_blocks(parsed)[workflow_update_module._SYNTHESIZED_BLOCK_LABEL]
- code = "\n".join(str(stage.get("code") or "") for stage in code_blocks[:-1])
- output_code = str(block["code"])
- assert code_blocks[-1]["label"] == workflow_update_module._SYNTHESIZED_BLOCK_LABEL
- assert result["data"]["imposed_substitutions"]["source_trajectory_count"] == 3
- assert 'await page.locator("#zip").fill(str(zip_code))' in code
- assert 'await page.locator("#continue").click()' in code
- assert 'await page.locator("#coverage-next").click()' in code
- assert 'records = [{"number": "Q-001"}]' in output_code
- assert 'return {"records": records}' in output_code
- assert all("records" not in str(stage.get("code") or "") for stage in code_blocks[:-1])
+ assert result["ok"] is False
+ assert "does not return a keyed structure" in result["error"]
+ assert "records" in result["error"]
- @pytest.mark.asyncio
- async def test_author_metadata_reject_reopens_changed_collapsed_code_block(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
+ def test_rejects_selected_extraction_suffix_page_mutation(self) -> None:
ctx = _quote_ctx()
- ctx.update_workflow_called = True
- ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("metadata_reject")
- ctx.workflow_yaml = _yaml(
- f"""
- title: Quote
- workflow_definition:
- blocks:
- - block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- code: |
- records = [{{"quote": "old"}}]
- """
- )
+ synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
+ assert synthesized is not None
+ submitted_code = textwrap.dedent(synthesized.code).rstrip() + '\nawait page.goto("https://example.com/other")\n'
submitted = _yaml(
f"""
title: Quote
@@ -13454,101 +14477,21 @@ class TestWholeTrajectoryImposition:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
- records = [{{"number": "Q-001"}}]
+{textwrap.indent(submitted_code, " " * 18)}
"""
)
- result = await _update_workflow(
- {
- "workflow_yaml": submitted,
- "code_artifact_metadata": [
- _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote result")
- ],
- },
- ctx,
- )
-
- assert result["ok"] is True
- parsed = parse_workflow_yaml(ctx.workflow_yaml)
- assert isinstance(parsed, dict)
- code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
- block = _code_blocks(parsed)[workflow_update_module._SYNTHESIZED_BLOCK_LABEL]
- browser_code = "\n".join(str(stage.get("code") or "") for stage in code_blocks[:-1])
- code = str(block["code"])
- assert result["data"]["imposed_substitutions"]["source_trajectory_count"] == 3
- assert result["data"]["imposed_substitutions"]["separated_browser_stage_count"] > 1
- assert code_blocks[-1]["label"] == workflow_update_module._SYNTHESIZED_BLOCK_LABEL
- assert 'await page.locator("#zip").fill(str(zip_code))' in browser_code
- assert 'await page.locator("#continue").click()' in browser_code
- assert 'await page.locator("#coverage-next").click()' in browser_code
- assert 'records = [{"number": "Q-001"}]' not in browser_code
- assert 'records = [{"number": "Q-001"}]' in code
- assert 'return {"records": records}' in code
-
- @pytest.mark.asyncio
- async def test_author_parameter_reject_reopens_and_preserves_typed_violation(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _code_only_ctx()
- _enable_imposition(ctx)
- ctx.scout_trajectory = [
- {
- "tool_name": "type_text",
- "selector": "#provInput",
- "source_url": "https://example.com/find-care",
- "typed_length": 13,
- "role": "textbox",
- "accessible_name": "Provider Name",
- "trajectory_index": 0,
- }
- ]
- ctx.update_workflow_called = True
- ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("synthesized_parameter_binding_ambiguous")
- ctx.workflow_yaml = _SUBMITTED_LITERAL_YAML
-
- result = await _update_workflow({"workflow_yaml": _SUBMITTED_UNKNOWN_COMPUTED_LITERAL_YAML}, ctx)
-
- assert result["ok"] is False
- assert "Unable to bind synthesized parameter `provider_name`" in result["error"]
- repair = result["data"]["authoring_repair_context"]
- assert repair["reason_code"] == "synthesized_parameter_binding_ambiguous"
- assert repair["unresolved_names"] == ["provider_name"]
- assert ctx.workflow_yaml == _SUBMITTED_LITERAL_YAML
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
- def test_author_ambiguous_selector_reject_reopens_strict_imposition_with_typed_repair_context(self) -> None:
- ctx = _resale_ctx()
- ctx.update_workflow_called = True
- ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("code_safety_reject")
- ctx.last_code_authoring_repair_context = CodeAuthoringRepairContext(
- block_label="order_status",
- reason_code="ambiguous_bare_selector",
- selector="button",
+ assert any(
+ "extraction suffix contains unscouted browser action" in violation for violation in result.violations
)
+ assert result.substitutions is None
- result = workflow_update_module._maybe_impose_synthesized_code_block(_resale_submitted_yaml(), ctx)
-
- assert result.violations == []
- assert result.substitutions is not None
- block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))
- assert 'button[data-action=\\"status\\"]' in str(block["code"])
-
- def test_author_schema_incompatibility_does_not_reopen_collapsed_code_block(self) -> None:
- ctx = _quote_ctx()
- ctx.update_workflow_called = True
- ctx.synthesized_goal_complete_landed = True
- ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("schema_incompatibility")
- ctx.workflow_yaml = _yaml(
- f"""
- title: Quote
- workflow_definition:
- blocks:
- - block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- code: |
- records = [{{"quote": "old"}}]
- """
- )
+ @pytest.mark.asyncio
+ async def test_sibling_invalid_goal_paths_still_reject(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _stub_successful_update(monkeypatch)
+ ctx = _quote_ctx()
submitted = _yaml(
f"""
title: Quote
@@ -13557,20 +14500,26 @@ class TestWholeTrajectoryImposition:
- block_type: code
label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
code: |
- records = [{{"quote": "pending"}}]
+ await page.locator("#zip").fill(str(zip_code))
+ await page.locator("#continue").click()
+ - block_type: code
+ label: summarize_quote
+ code: |
+ return await page.locator("h1").inner_text()
"""
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ result = await _update_workflow(
+ {"workflow_yaml": submitted, "code_artifact_metadata": [_terminal_metadata("summarize_quote", "summary")]},
+ ctx,
+ )
- assert result.violations == []
- assert result.substitutions is None
- assert result.workflow_yaml == submitted
+ assert result["ok"] is False
+ assert "summarize_quote" in result["error"]
+ assert "flat text blob" in result["error"]
@pytest.mark.asyncio
- async def test_stale_selected_goal_paths_do_not_block_imposed_scout_spine(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
+ async def test_p10_shaped_stale_metadata_imposes_scout_spine(self, monkeypatch: pytest.MonkeyPatch) -> None:
_stub_successful_update(monkeypatch)
ctx = _quote_ctx()
submitted = _yaml(
@@ -13584,6 +14533,7 @@ class TestWholeTrajectoryImposition:
await page.locator("#zip").fill(str(zip_code))
await page.locator("#continue").click()
await page.locator("#electricDate").fill("2026-07-01")
+ await page.locator("#electricPlan").select_option("basic")
await page.locator("#coverage-next").click()
"""
)
@@ -13597,1358 +14547,2219 @@ class TestWholeTrajectoryImposition:
)
assert result["ok"] is True
- assert result["data"]["imposed_substitutions"]["scrubbed_stale_selected_goal_value_paths"] is True
parsed = parse_workflow_yaml(ctx.workflow_yaml)
assert isinstance(parsed, dict)
code = str(_single_code_block(parsed)["code"])
assert "#electricDate" not in code
- assert 'await page.locator("#zip").fill(str(zip_code))' in code
- artifact = ctx.code_artifact_metadata["quote_flow"]
- assert not workflow_update_module._artifact_declares_goal_values(artifact)
+ assert "#electricPlan" not in code
+ assert code.index('page.locator("#zip")') < code.index('page.locator("#continue")')
+ assert code.index('page.locator("#continue")') < code.index('page.locator("#coverage-next")')
+
+
+class TestBareDropSupersession:
+ def test_selector_refines_css_accepts_identity_qualifiers(self) -> None:
+ for candidate in (
+ 'button[data-action="status"]',
+ "button#submit",
+ "button.primary",
+ 'button[aria-label="Close ]"]', # a literal ] inside the attribute value must not read as a combinator
+ ):
+ assert workflow_update_module._selector_refines("button", candidate) is True
+
+ def test_selector_refines_role_accepts_named_same_role(self) -> None:
+ assert workflow_update_module._selector_refines("role=button", 'role=button[name="Next"]') is True
+
+ def test_selector_refines_rejects_positional_structural_and_cross_shape(self) -> None:
+ bare = "button"
+ for candidate in (
+ "button:nth-child(2)",
+ "button:nth-of-type(2)",
+ "button >> nth=1",
+ "button.primary span",
+ "button#x + button",
+ "button[data-x] > svg",
+ "button:visible",
+ "button:enabled",
+ "button:not(.foo)",
+ 'button:has-text("Next")',
+ "a[href]",
+ "buttonx[id=1]",
+ "button",
+ ):
+ assert workflow_update_module._selector_refines(bare, candidate) is False
+ assert workflow_update_module._selector_refines("role=button", 'role=link[name="Next"]') is False
+ assert workflow_update_module._selector_refines("role=button", 'button[data-action="x"]') is False
+ assert workflow_update_module._selector_refines("button", 'role=button[name="x"]') is False
+ assert workflow_update_module._selector_refines("role=button", 'role=button[name="N"] >> nth=1') is False
+
+ def test_stable_bare_click_refiner_accepts_only_same_kind_text_and_role_anchors(self) -> None:
+ assert (
+ _stable_same_kind_bare_click_refiner("button", "xpath=//button[normalize-space()='Check Order Status']")
+ is True
+ )
+ assert _stable_same_kind_bare_click_refiner("button", 'role=button[name="Next"]') is True
+ for candidate in (
+ "xpath=//a[normalize-space()='Check Order Status']",
+ 'role=link[name="Next"]',
+ "xpath=(//button[normalize-space()='Check Order Status'])[2]",
+ "xpath=//button[contains(normalize-space(), 'Check')]",
+ ):
+ assert _stable_same_kind_bare_click_refiner("button", candidate) is False
+
+ def test_supersession_true_returns_pairing_record(self) -> None:
+ dropped = {
+ "reason_code": "ambiguous_bare_selector",
+ "tool_name": "click",
+ "selector": "button",
+ "trajectory_index": 1,
+ }
+ ctx = _resale_ctx()
+ claimed: set[int] = set()
+ forgiven, record = workflow_update_module._bare_drop_superseded_on_screen(
+ dropped, ctx.scout_trajectory, claimed_refiner_indices=claimed
+ )
+ assert forgiven is True
+ assert record == {
+ "dropped_index": 1,
+ "dropped_selector": "button",
+ "refiner_index": 2,
+ "refiner_selector": 'button[data-action="status"]',
+ "source_url": _RESALE_URL,
+ }
+ assert claimed == {2}
+
+ def test_supersession_false_across_different_source_url(self) -> None:
+ ctx = _resale_ctx()
+ ctx.scout_trajectory[2]["source_url"] = "https://example.com/other"
+ dropped = {
+ "reason_code": "ambiguous_bare_selector",
+ "tool_name": "click",
+ "selector": "button",
+ "trajectory_index": 1,
+ }
+ forgiven, record = workflow_update_module._bare_drop_superseded_on_screen(
+ dropped, ctx.scout_trajectory, claimed_refiner_indices=set()
+ )
+ assert forgiven is False
+ assert record is None
+
+ def test_supersession_false_without_later_refiner(self) -> None:
+ ctx = _resale_ctx(refiner_selector="button:nth-of-type(2)")
+ dropped = {
+ "reason_code": "ambiguous_bare_selector",
+ "tool_name": "click",
+ "selector": "button",
+ "trajectory_index": 1,
+ }
+ forgiven, _ = workflow_update_module._bare_drop_superseded_on_screen(
+ dropped, ctx.scout_trajectory, claimed_refiner_indices=set()
+ )
+ assert forgiven is False
+
+ def test_supersession_false_on_empty_source_url(self) -> None:
+ ctx = _resale_ctx()
+ ctx.scout_trajectory[1]["source_url"] = ""
+ dropped = {
+ "reason_code": "ambiguous_bare_selector",
+ "tool_name": "click",
+ "selector": "button",
+ "trajectory_index": 1,
+ }
+ forgiven, _ = workflow_update_module._bare_drop_superseded_on_screen(
+ dropped, ctx.scout_trajectory, claimed_refiner_indices=set()
+ )
+ assert forgiven is False
+
+ def test_supersession_false_on_out_of_bounds_index(self) -> None:
+ ctx = _resale_ctx()
+ for bad_index in (-1, 99, "1", None):
+ dropped = {
+ "reason_code": "ambiguous_bare_selector",
+ "tool_name": "click",
+ "selector": "button",
+ "trajectory_index": bad_index,
+ }
+ forgiven, _ = workflow_update_module._bare_drop_superseded_on_screen(
+ dropped, ctx.scout_trajectory, claimed_refiner_indices=set()
+ )
+ assert forgiven is False
+
+ def test_imposition_forgives_mid_trajectory_bare_drop_and_records_substitution(self) -> None:
+ ctx = _resale_ctx()
+ result = workflow_update_module._maybe_impose_synthesized_code_block(_resale_submitted_yaml(), ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ forgiven = result.substitutions["forgiven_superseded_bare_drops"]
+ assert forgiven == [
+ {
+ "dropped_index": 1,
+ "dropped_selector": "button",
+ "refiner_index": 2,
+ "refiner_selector": 'button[data-action="status"]',
+ "source_url": _RESALE_URL,
+ }
+ ]
+ block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))
+ assert 'button[data-action=\\"status\\"]' in str(block["code"])
+
+ def test_imposition_keeps_bare_drop_fatal_when_sibling_is_positional(self) -> None:
+ ctx = _resale_ctx(refiner_selector="button:nth-of-type(2)")
+ result = workflow_update_module._maybe_impose_synthesized_code_block(
+ _resale_submitted_yaml("button:nth-of-type(2)"), ctx
+ )
+
+ assert any("ambiguous_bare_selector" in violation for violation in result.violations)
+ assert result.substitutions is None
+
+ def test_imposition_one_refiner_does_not_forgive_two_bare_drops(self) -> None:
+ ctx = _resale_ctx()
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#start", "source_url": _RESALE_URL, "trajectory_index": 0},
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 2},
+ {
+ "tool_name": "click",
+ "selector": 'button[data-action="status"]',
+ "source_url": _RESALE_URL,
+ "trajectory_index": 3,
+ },
+ ]
+ submitted = _yaml(
+ """
+ title: Order status
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: order_status
+ code: |
+ await page.locator("#start").click()
+ await page.locator("button[data-action=\\"status\\"]").click()
+ """
+ )
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert any("ambiguous_bare_selector" in violation for violation in result.violations)
+
+ def test_imposition_two_refiners_forgive_two_bare_drops(self) -> None:
+ ctx = _resale_ctx()
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#start", "source_url": _RESALE_URL, "trajectory_index": 0},
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 2},
+ {
+ "tool_name": "click",
+ "selector": 'button[data-action="open"]',
+ "source_url": _RESALE_URL,
+ "trajectory_index": 3,
+ },
+ {
+ "tool_name": "click",
+ "selector": 'button[data-action="status"]',
+ "source_url": _RESALE_URL,
+ "trajectory_index": 4,
+ },
+ ]
+ submitted = _yaml(
+ """
+ title: Order status
+ workflow_definition:
+ blocks:
+ - block_type: code
+ label: order_status
+ code: |
+ await page.locator("#start").click()
+ await page.locator("button[data-action=\\"open\\"]").click()
+ await page.locator("button[data-action=\\"status\\"]").click()
+ """
+ )
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert result.violations == []
+ assert result.substitutions is not None
+ forgiven = result.substitutions["forgiven_superseded_bare_drops"]
+ assert {record["dropped_index"] for record in forgiven} == {1, 2}
+ assert {record["refiner_index"] for record in forgiven} == {3, 4}
- @pytest.mark.asyncio
- async def test_formation_prepared_directory_run_rescaffolds_metadata_after_imposition_scrub(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
- scaffold = Mock(wraps=workflow_update_module._scaffold_metadata_contract_for_update)
- envelope = Mock(wraps=workflow_update_module._impose_output_contract_envelope_after_steering)
- monkeypatch.setattr(workflow_update_module, "_scaffold_metadata_contract_for_update", scaffold)
- monkeypatch.setattr(workflow_update_module, "_impose_output_contract_envelope_after_steering", envelope)
- ctx = _code_only_ctx()
- _enable_imposition(ctx)
+ def test_imposition_two_exact_text_xpath_button_refiners_forgive_two_bare_drops(self) -> None:
+ ctx = _resale_ctx()
+ first_refiner = "xpath=//button[normalize-space()='Check Order Status']"
+ second_refiner = "xpath=//button[normalize-space()='View / Download']"
ctx.scout_trajectory = [
{
"tool_name": "type_text",
- "selector": "#npi",
- "source_url": "https://example.com/directory",
- "typed_length": 10,
- "typed_value": "1234567890",
- "role": "textbox",
- "accessible_name": "NPI",
+ "selector": "#order-id",
+ "source_url": _RESALE_URL,
+ "typed_length": 6,
+ "typed_value": "abc123",
"trajectory_index": 0,
},
- {
- "tool_name": "click",
- "selector": "#search_by",
- "source_url": "https://example.com/directory",
- "trajectory_index": 1,
- },
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 2},
+ {"tool_name": "click", "selector": first_refiner, "source_url": _RESALE_URL, "trajectory_index": 3},
+ {"tool_name": "click", "selector": second_refiner, "source_url": _RESALE_URL, "trajectory_index": 4},
]
- scouting_module._mint_current_loaded_result_source(
- ctx,
- {
- "forms": [],
- "navigation_targets": [],
- "result_containers": [
- {"selector": "#coastalCard", "text": "Provider record is visible", "row_count": 1}
- ],
- },
- url="https://example.com/directory",
- )
- ctx.request_policy = RequestPolicy(
- completion_criteria=[
- _typed_completion_criterion(
- id="requested_npi",
- output_path="output.npi",
- level="run",
- method_mandated=False,
- kind="outcome",
- )
- ]
- )
submitted = _yaml(
"""
- title: Directory lookup
+ title: Order status
workflow_definition:
blocks:
- block_type: code
- label: directory_flow
+ label: order_status
code: |
- await page.locator("#npi").fill(str(npi))
- await page.locator("#search_by").click()
- await page.locator("#coastalCard").wait_for(state="visible")
+ await page.locator("#order-id").fill(str(order_id))
+ await page.locator("xpath=//button[normalize-space()='Check Order Status']").click()
+ await page.locator("xpath=//button[normalize-space()='View / Download']").click()
"""
)
- metadata = [
- {
- "block_label": "directory_flow",
- "claimed_outcomes": [{"goal_value_paths": ["output.npi"]}],
- "terminal_verifier_expectations": [{"goal_value_paths": ["output.npi"]}],
- }
- ]
- result = await _update_workflow(
- {"workflow_yaml": submitted, "code_artifact_metadata": metadata},
- ctx,
- allow_static_output_uncertainty=True,
- formation_prepared=True,
- )
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
- assert result["ok"] is False
- assert envelope.call_count == 1
- assert scaffold.call_count == 1
- artifact = workflow_update_module._metadata_item_for_block_label(
- ctx.raw_code_artifact_metadata, "directory_flow"
- )
- assert artifact is not None
- assert not workflow_update_module._artifact_declares_goal_values(artifact)
+ assert result.violations == []
+ assert result.substitutions is not None
+ forgiven = result.substitutions["forgiven_superseded_bare_drops"]
+ assert {record["dropped_index"] for record in forgiven} == {1, 2}
+ assert {record["refiner_index"] for record in forgiven} == {3, 4}
+ assert {record["refiner_selector"] for record in forgiven} == {first_refiner, second_refiner}
+ block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))
+ assert first_refiner in str(block["code"])
+ assert second_refiner in str(block["code"])
- @pytest.mark.asyncio
- async def test_metadata_selected_page_goto_extra_is_discarded(self, monkeypatch: pytest.MonkeyPatch) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _quote_ctx()
+ def test_imposition_one_exact_text_xpath_refiner_does_not_forgive_two_bare_drops(self) -> None:
+ ctx = _resale_ctx()
+ refiner = "xpath=//button[normalize-space()='Check Order Status']"
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#start", "source_url": _RESALE_URL, "trajectory_index": 0},
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 2},
+ {"tool_name": "click", "selector": refiner, "source_url": _RESALE_URL, "trajectory_index": 3},
+ ]
submitted = _yaml(
"""
- title: Quote
+ title: Order status
workflow_definition:
blocks:
- block_type: code
- label: quote_flow
+ label: order_status
code: |
- await page.goto("https://example.com/other")
- records = [{"number": "Q-001"}]
+ await page.locator("#start").click()
+ await page.locator("xpath=//button[normalize-space()='Check Order Status']").click()
"""
)
- result = await _update_workflow(
- {
- "workflow_yaml": submitted,
- "code_artifact_metadata": [_terminal_metadata("quote_flow", "quote result")],
- },
- ctx,
- )
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
- assert result["ok"] is True
- parsed = parse_workflow_yaml(ctx.workflow_yaml)
- assert isinstance(parsed, dict)
- code = str(_single_code_block(parsed)["code"])
- assert 'page.goto("https://example.com/other")' not in code
- assert 'records = [{"number": "Q-001"}]' not in code
- assert 'await page.locator("#zip").fill(str(zip_code))' in code
- assert result["data"]["imposed_substitutions"]["scrubbed_stale_selected_goal_value_paths"] is True
+ assert any("ambiguous_bare_selector" in violation for violation in result.violations)
- @pytest.mark.asyncio
- async def test_valid_selected_extraction_suffix_keeps_goal_path_metadata(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- submitted_code = textwrap.dedent(synthesized.code).rstrip() + '\nreturn {"records": [{"number": "Q-001"}]}\n'
+ def test_imposition_positional_xpath_refiner_keeps_bare_drop_fatal(self) -> None:
+ ctx = _resale_ctx()
+ positional_refiner = "xpath=(//button[normalize-space()='Check Order Status'])[2]"
+ ctx.scout_trajectory = [
+ {"tool_name": "click", "selector": "#start", "source_url": _RESALE_URL, "trajectory_index": 0},
+ {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
+ {"tool_name": "click", "selector": positional_refiner, "source_url": _RESALE_URL, "trajectory_index": 2},
+ ]
submitted = _yaml(
- f"""
- title: Quote
+ """
+ title: Order status
workflow_definition:
blocks:
- block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
+ label: order_status
code: |
-{textwrap.indent(submitted_code, " " * 18)}
+ await page.locator("#start").click()
+ await page.locator("xpath=(//button[normalize-space()='Check Order Status'])[2]").click()
"""
)
- result = await _update_workflow(
- {
- "workflow_yaml": submitted,
- "code_artifact_metadata": [
- _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote result")
- ],
- },
- ctx,
- )
+ result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+
+ assert any("ambiguous_bare_selector" in violation for violation in result.violations)
+ assert result.substitutions is None
+
+ @pytest.mark.asyncio
+ async def test_auto_act_non_navigating_reads_role_name(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _auto_act_scout_ctx()
+ captured: dict[str, object] = {}
+
+ async def _fake_resolve(
+ _ctx: AgentContext, selector: str | None, *, allow_browser_read: bool
+ ) -> tuple[str, str]:
+ captured["allow_browser_read"] = allow_browser_read
+ return "button", "Continue"
+
+ monkeypatch.setattr(scouting_module, "_resolve_scout_role_name", _fake_resolve)
+
+ async def _same_url(_ctx: AgentContext) -> str:
+ return "https://example.com/orders"
+
+ monkeypatch.setattr(scouting_module, "_live_working_page_url", _same_url)
+
+ async def _evidence(_ctx: AgentContext, *, url: str) -> dict[str, object] | None:
+ return None
+
+ monkeypatch.setattr(scouting_module, "_scout_act_observe_page_evidence", _evidence)
+
+ acted = await scouting_module._auto_act_on_repeat(
+ ctx,
+ {"data": {}},
+ url="https://example.com/orders",
+ target={"selector": "#continue", "text": "Continue"},
+ )
+
+ assert acted is True
+ assert captured["allow_browser_read"] is True
+ last = ctx.scout_trajectory[-1]
+ assert last["role"] == "button"
+ assert last["accessible_name"] == "Continue"
+
+ @pytest.mark.asyncio
+ async def test_auto_act_navigating_skips_browser_read(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ ctx = _auto_act_scout_ctx()
+ captured: dict[str, object] = {}
+
+ async def _fake_resolve(
+ _ctx: AgentContext, selector: str | None, *, allow_browser_read: bool
+ ) -> tuple[str, str]:
+ captured["allow_browser_read"] = allow_browser_read
+ return "", ""
+
+ monkeypatch.setattr(scouting_module, "_resolve_scout_role_name", _fake_resolve)
+
+ urls = iter(["https://example.com/orders", "https://example.com/status"])
+
+ async def _moving_url(_ctx: AgentContext) -> str:
+ return next(urls)
+
+ monkeypatch.setattr(scouting_module, "_live_working_page_url", _moving_url)
+
+ async def _evidence(_ctx: AgentContext, *, url: str) -> dict[str, object] | None:
+ return None
+
+ monkeypatch.setattr(scouting_module, "_scout_act_observe_page_evidence", _evidence)
+
+ acted = await scouting_module._auto_act_on_repeat(
+ ctx,
+ {"data": {}},
+ url="https://example.com/orders",
+ target={"selector": "#continue", "text": "Continue"},
+ )
+
+ assert acted is True
+ assert captured["allow_browser_read"] is False
+
+
+def _auto_act_scout_ctx() -> AgentContext:
+ ctx = AgentContext.__new__(AgentContext)
+ ctx.browser_session_id = None
+ ctx.scouted_interactions = []
+ ctx.scout_trajectory = []
+ ctx.scout_observed_terminal_criterion_ids = set()
+ ctx.completion_criteria_turn_state = None
+ ctx.discovery_mcp_server = _AutoActClickServer()
+ return ctx
+
+
+class _AutoActClickServer:
+ async def call_internal_tool(self, tool_name: str, args: dict[str, object]) -> dict[str, object]:
+ return {"ok": True, "data": {"selector": args.get("selector")}}
+
- assert result["ok"] is True
- assert result["data"]["imposed_substitutions"]["preserved_extraction_suffix"] is True
- artifact = ctx.code_artifact_metadata[workflow_update_module._SYNTHESIZED_BLOCK_LABEL]
- assert workflow_update_module._artifact_declares_goal_values(artifact)
+def _declaration_stamp_ctx() -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.turn_id = "t-decl"
+ ctx.scout_trajectory = []
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(
+ id="c_record",
+ outcome="The returned record includes record id.",
+ output_path="output.record_id",
+ ),
+ CompletionCriterion(
+ id="c_blocker",
+ outcome="A blocker is reported when the site blocks submission.",
+ contingent_on="the site blocks submission",
+ contingent_antecedent_output_path="output.blocker",
+ ),
+ ]
+ )
+ return ctx
- @pytest.mark.asyncio
- async def test_p9_opaque_self_authored_extraction_metadata_is_preserved(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- label = workflow_update_module._SYNTHESIZED_BLOCK_LABEL
- submitted_code = (
- textwrap.dedent(synthesized.code).rstrip()
- + f'\n{label}_output = {{"premium": "$123", "eligible": True}}\nreturn {label}_output\n'
- )
- submitted = _yaml(
- f"""
- title: Quote
- workflow_definition:
- blocks:
- - block_type: code
- label: {label}
- code: |
-{textwrap.indent(submitted_code, " " * 18)}
- """
- )
- schema = (
- '{"type":"object","properties":{"premium":{"type":"string"},'
- '"eligible":{"type":"boolean"}},"required":["premium","eligible"]}'
- )
- metadata = _terminal_metadata(label, "quote result")
- metadata["claimed_outcomes"][0]["goal_value_paths"] = ["premium", "eligible"]
- metadata["claimed_outcomes"][0]["extraction_schema"] = schema
- metadata["claimed_outcomes"][0]["extraction_schema_provenance"] = "self_authored"
- metadata["terminal_verifier_expectations"][0]["goal_value_paths"] = ["premium", "eligible"]
- metadata["terminal_verifier_expectations"][0]["extraction_schema"] = schema
- metadata["terminal_verifier_expectations"][0]["extraction_schema_provenance"] = "self_authored"
- result = await _update_workflow({"workflow_yaml": submitted, "code_artifact_metadata": [metadata]}, ctx)
+def _degraded_declaration_stamp_ctx() -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.turn_id = "t-degraded-decl"
+ ctx.scout_trajectory = []
+ requested_paths = (
+ "output.confirmation_number",
+ "output.account_number",
+ "output.start_date",
+ "output.deposit_amount",
+ "output.next_owner",
+ )
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ *[
+ CompletionCriterion(
+ id=f"slot_{index}",
+ outcome=f"The returned record includes {path}.",
+ request_slot_id=f"slot_{index}",
+ pinability="unpinnable",
+ mint_disposition="degraded",
+ mint_degrade="undecidable_judgment",
+ requested_output_floor_rekeyed=True,
+ floor_rekeyed_from_path=path,
+ )
+ for index, path in enumerate(requested_paths)
+ ],
+ CompletionCriterion(
+ id="c_blocker",
+ outcome="A blocker is reported when the site blocks submission.",
+ contingent_on="the site blocks submission",
+ contingent_antecedent_output_path="output.blocker",
+ ),
+ ]
+ )
+ return ctx
- assert result["ok"] is True
- assert result["data"]["imposed_substitutions"]["preserved_extraction_suffix"] is True
- assert "scrubbed_stale_selected_goal_value_paths" not in result["data"]["imposed_substitutions"]
- artifact = ctx.code_artifact_metadata[label]
- assert artifact["claimed_outcomes"][0]["goal_value_paths"] == ["premium", "eligible"]
- assert artifact["terminal_verifier_expectations"][0]["goal_value_paths"] == ["premium", "eligible"]
- assert artifact["claimed_outcomes"][0]["extraction_schema"] == schema
- parsed = parse_workflow_yaml(ctx.workflow_yaml)
- assert isinstance(parsed, dict)
- code_blocks = [block for block in workflow_blocks(parsed) if block.get("block_type") == "code"]
- assert len(code_blocks) > 1
- code = str(_code_blocks(parsed)[label]["code"])
- assert f"return {label}_output" in code
- assert all(label + "_output" not in str(block.get("code") or "") for block in code_blocks[:-1])
- @pytest.mark.asyncio
- async def test_invalid_selected_extraction_suffix_keeps_goal_path_rejection(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- submitted_code = textwrap.dedent(synthesized.code).rstrip() + "\nheading = 'Review'\n"
- submitted = _yaml(
- f"""
- title: Quote
- workflow_definition:
- blocks:
- - block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- code: |
-{textwrap.indent(submitted_code, " " * 18)}
- """
- )
+class TestDeclarationContractStamp:
+ @pytest.mark.parametrize("empty_value", ["None", "''", "' '", "[]", "{}", "[None]", "[{}]", "{'a': None}"])
+ def test_static_empty_observation_value_is_non_run_eligible(self, empty_value: str) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml(f'return {{"output": {{"record_id": {empty_value}, "blocker": None}}}}')
+ metadata = [
+ workflow_update_module._metadata_contract_template(
+ block_label="extract_record",
+ required_paths={"output.record_id"},
+ source="requested_output_contract",
+ reason_code="requested_output_contract_missing_output_coverage",
+ declaration_paths={"output.blocker"},
+ )
+ ]
- result = await _update_workflow(
- {
- "workflow_yaml": submitted,
- "code_artifact_metadata": [
- _terminal_metadata(workflow_update_module._SYNTHESIZED_BLOCK_LABEL, "quote result")
- ],
- },
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
ctx,
+ workflow_yaml,
+ metadata,
+ allow_static_return_advisory=True,
+ enforce_value_bearing_liveness=True,
)
- assert result["ok"] is False
- assert "does not return a keyed structure" in result["error"]
- assert "records" in result["error"]
+ assert evaluation is not None
+ assert evaluation.missing_metadata_paths == []
+ assert evaluation.missing_schema_paths == []
+ assert evaluation.missing_return_paths == []
+ assert evaluation.payload["reason_code"] == "value_bearing_output_required"
+ assert evaluation.can_attempt_run is False
- def test_rejects_selected_extraction_suffix_page_mutation(self) -> None:
- ctx = _quote_ctx()
- synthesized = workflow_update_module.synthesize_code_block(ctx.scout_trajectory, strict_selectors=True)
- assert synthesized is not None
- submitted_code = textwrap.dedent(synthesized.code).rstrip() + '\nawait page.goto("https://example.com/other")\n'
- submitted = _yaml(
- f"""
- title: Quote
- workflow_definition:
- blocks:
- - block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- code: |
-{textwrap.indent(submitted_code, " " * 18)}
- """
+ @pytest.mark.parametrize("value", ["0", "False", "'record-123'", "[None, 'x']", "{'a': 'x'}"])
+ def test_static_value_bearing_observation_remains_run_eligible(self, value: str) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml(f'return {{"output": {{"record_id": {value}, "blocker": None}}}}')
+ metadata = [
+ workflow_update_module._metadata_contract_template(
+ block_label="extract_record",
+ required_paths={"output.record_id"},
+ source="requested_output_contract",
+ reason_code="requested_output_contract_missing_output_coverage",
+ declaration_paths={"output.blocker"},
+ )
+ ]
+
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx, workflow_yaml, metadata, enforce_value_bearing_liveness=True
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ assert evaluation is not None
+ assert evaluation.has_deficiencies is False
- assert any(
- "extraction suffix contains unscouted browser action" in violation for violation in result.violations
+ def test_full_metadata_advisory_rejects_declaration_only_return(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ required_paths = {"output.record_id", "output.blocker"}
+ signature = workflow_update_module._stable_output_contract_key(
+ workflow_update_module._output_contract_scope_key(ctx), required_paths
)
- assert result.substitutions is None
+ workflow_update_module._grant_output_contract_advisory_run(ctx, signature)
+ workflow_yaml = _collapsed_spine_yaml('await page.click("#submit")\nreturn {"output": {"blocker": None}}')
+ metadata = [
+ workflow_update_module._metadata_contract_template(
+ block_label="extract_record",
+ required_paths={"output.record_id"},
+ source="requested_output_contract",
+ reason_code="requested_output_contract_missing_output_coverage",
+ declaration_paths={"output.blocker"},
+ )
+ ]
- @pytest.mark.asyncio
- async def test_sibling_invalid_goal_paths_still_reject(self, monkeypatch: pytest.MonkeyPatch) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _quote_ctx()
- submitted = _yaml(
- f"""
- title: Quote
- workflow_definition:
- blocks:
- - block_type: code
- label: {workflow_update_module._SYNTHESIZED_BLOCK_LABEL}
- code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
- - block_type: code
- label: summarize_quote
- code: |
- return await page.locator("h1").inner_text()
- """
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ metadata,
+ allow_static_return_advisory=True,
+ enforce_value_bearing_liveness=True,
)
+ assert evaluation is not None
+ assert evaluation.missing_metadata_paths == []
+ assert evaluation.missing_schema_paths == []
+ assert evaluation.missing_return_paths == ["output.record_id"]
+ assert evaluation.payload["static_return_advisory_paths"] == []
+ assert evaluation.payload["reason_code"] == "value_bearing_output_required"
+ assert evaluation.can_attempt_run is False
+
+ @pytest.mark.asyncio
+ async def test_full_metadata_declaration_only_contract_rejects_at_persist_seam(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('await page.click("#submit")\nreturn {"output": {"blocker": None}}')
+ metadata = [
+ workflow_update_module._metadata_contract_template(
+ block_label="extract_record",
+ required_paths={"output.record_id"},
+ source="requested_output_contract",
+ reason_code="requested_output_contract_missing_output_coverage",
+ declaration_paths={"output.blocker"},
+ )
+ ]
+
result = await _update_workflow(
- {"workflow_yaml": submitted, "code_artifact_metadata": [_terminal_metadata("summarize_quote", "summary")]},
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": metadata},
ctx,
+ allow_missing_credentials=True,
)
assert result["ok"] is False
- assert "summarize_quote" in result["error"]
- assert "flat text blob" in result["error"]
+ assert result["data"]["reason_code"] == "value_bearing_output_required"
+ assert result["data"]["contract_liveness"] == "value_required"
+ assert result["data"]["missing_goal_value_paths"] == []
+ assert result["data"]["missing_extraction_schema_paths"] == []
+ assert result["data"]["missing_code_return_paths"] == ["output.record_id"]
- @pytest.mark.asyncio
- async def test_p10_shaped_stale_metadata_imposes_scout_spine(self, monkeypatch: pytest.MonkeyPatch) -> None:
- _stub_successful_update(monkeypatch)
- ctx = _quote_ctx()
- submitted = _yaml(
- """
- title: Quote
- workflow_definition:
- blocks:
- - block_type: code
- label: quote_flow
- code: |
- await page.locator("#zip").fill(str(zip_code))
- await page.locator("#continue").click()
- await page.locator("#electricDate").fill("2026-07-01")
- await page.locator("#electricPlan").select_option("basic")
- await page.locator("#coverage-next").click()
- """
+ def test_grant_preflight_rejects_declaration_only_return(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ [],
+ allow_static_return_advisory=True,
+ enforce_value_bearing_liveness=True,
)
+ assert evaluation is not None
+ workflow_update_module._grant_output_contract_advisory_run(ctx, evaluation.canonical_signature)
- result = await _update_workflow(
- {
- "workflow_yaml": submitted,
- "code_artifact_metadata": [_terminal_metadata("quote_flow", "quote result")],
- },
+ preflight = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
+
+ assert evaluation.payload["reason_code"] == "value_bearing_output_required"
+ assert evaluation.can_attempt_run is False
+ assert preflight is not None
+ assert preflight["data"]["reason_code"] == "value_bearing_output_required"
+ assert "output_contract_reason_code" not in preflight["data"]
+ assert (
+ workflow_update_module._output_contract_advisory_state(ctx, evaluation.canonical_signature)
+ == OutputContractAdvisoryState.UNUSED
+ )
+ assert evaluation.canonical_signature not in ctx.output_contract_pending_run_evidence
+
+ def test_degraded_requested_slots_make_declaration_only_contract_non_run_eligible(self) -> None:
+ ctx = _degraded_declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
+
+ formed_yaml, metadata, applied = workflow_update_module._impose_output_contract_envelope_after_steering(
+ ctx, workflow_yaml, []
+ )
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
ctx,
+ formed_yaml,
+ metadata,
+ allow_static_return_advisory=True,
+ enforce_value_bearing_liveness=True,
)
- assert result["ok"] is True
- parsed = parse_workflow_yaml(ctx.workflow_yaml)
- assert isinstance(parsed, dict)
- code = str(_single_code_block(parsed)["code"])
- assert "#electricDate" not in code
- assert "#electricPlan" not in code
- assert code.index('page.locator("#zip")') < code.index('page.locator("#continue")')
- assert code.index('page.locator("#continue")') < code.index('page.locator("#coverage-next")')
+ assert applied is False
+ assert formed_yaml == workflow_yaml
+ assert evaluation is not None
+ signature = evaluation.canonical_signature
+ assert ctx.output_contract_armed_directive_fingerprint_by_signature.get(signature) == (
+ workflow_update_module._VALUE_BEARING_PREARM_FINGERPRINT_PREFIX
+ + workflow_update_module._output_contract_structural_fingerprint(workflow_yaml, signature)
+ )
+ assert evaluation.payload["contract_liveness"] == "degraded_empty"
+ assert evaluation.payload["reason_code"] == "value_bearing_output_required"
+ assert evaluation.can_attempt_run is False
+ assert "canonical_evaluation_paths" not in evaluation.payload
+ assert [row["request_slot_id"] for row in evaluation.payload["degraded_request_slots"]] == [
+ "slot_0",
+ "slot_1",
+ "slot_2",
+ "slot_3",
+ "slot_4",
+ ]
+ assert [row["floor_rekeyed_from_path"] for row in evaluation.payload["degraded_request_slots"]] == [
+ "output.confirmation_number",
+ "output.account_number",
+ "output.start_date",
+ "output.deposit_amount",
+ "output.next_owner",
+ ]
+ def test_degraded_declaration_only_directive_arm_is_idempotent(self) -> None:
+ ctx = _degraded_declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
-class TestBareDropSupersession:
- def test_selector_refines_css_accepts_identity_qualifiers(self) -> None:
- for candidate in (
- 'button[data-action="status"]',
- "button#submit",
- "button.primary",
- 'button[aria-label="Close ]"]', # a literal ] inside the attribute value must not read as a combinator
- ):
- assert workflow_update_module._selector_refines("button", candidate) is True
+ first_yaml, _, first_applied = workflow_update_module._impose_output_contract_envelope_after_steering(
+ ctx, workflow_yaml, []
+ )
+ second_yaml, _, second_applied = workflow_update_module._impose_output_contract_envelope_after_steering(
+ ctx, first_yaml, []
+ )
- def test_selector_refines_role_accepts_named_same_role(self) -> None:
- assert workflow_update_module._selector_refines("role=button", 'role=button[name="Next"]') is True
+ assert first_applied is False
+ assert second_applied is False
+ assert first_yaml == workflow_yaml
+ assert second_yaml == workflow_yaml
+ assert len(ctx.output_contract_armed_directive_fingerprint_by_signature) == 1
- def test_selector_refines_rejects_positional_structural_and_cross_shape(self) -> None:
- bare = "button"
- for candidate in (
- "button:nth-child(2)",
- "button:nth-of-type(2)",
- "button >> nth=1",
- "button.primary span",
- "button#x + button",
- "button[data-x] > svg",
- "button:visible",
- "button:enabled",
- "button:not(.foo)",
- 'button:has-text("Next")',
- "a[href]",
- "buttonx[id=1]",
- "button",
- ):
- assert workflow_update_module._selector_refines(bare, candidate) is False
- assert workflow_update_module._selector_refines("role=button", 'role=link[name="Next"]') is False
- assert workflow_update_module._selector_refines("role=button", 'button[data-action="x"]') is False
- assert workflow_update_module._selector_refines("button", 'role=button[name="x"]') is False
- assert workflow_update_module._selector_refines("role=button", 'role=button[name="N"] >> nth=1') is False
+ def test_second_run_request_slot_producer_failure_rejects_blocker_only_return(self) -> None:
+ requested_paths = (
+ "output.confirmation_number",
+ "output.account_number",
+ "output.start_date",
+ "output.deposit_amount",
+ "output.next_owner",
+ )
+ ctx = _code_only_ctx()
+ ctx.turn_id = "t-request-slot-producer-failure"
+ ctx.scout_trajectory = []
+ ctx.request_policy = request_policy_module._classification_from_raw(
+ {
+ "completion_criteria": [
+ {
+ "outcome": f"The returned record includes {path}.",
+ "output_path": path,
+ "request_slot_source_id": "latest_request",
+ "request_slot_source_quote": path,
+ }
+ for path in requested_paths
+ ]
+ },
+ request_slot_failure_kind="invalid_output",
+ )
+ workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
- def test_stable_bare_click_refiner_accepts_only_same_kind_text_and_role_anchors(self) -> None:
- assert (
- _stable_same_kind_bare_click_refiner("button", "xpath=//button[normalize-space()='Check Order Status']")
- is True
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ [],
+ allow_static_return_advisory=True,
+ enforce_value_bearing_liveness=True,
)
- assert _stable_same_kind_bare_click_refiner("button", 'role=button[name="Next"]') is True
- for candidate in (
- "xpath=//a[normalize-space()='Check Order Status']",
- 'role=link[name="Next"]',
- "xpath=(//button[normalize-space()='Check Order Status'])[2]",
- "xpath=//button[contains(normalize-space(), 'Check')]",
- ):
- assert _stable_same_kind_bare_click_refiner("button", candidate) is False
+ preflight = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
- def test_supersession_true_returns_pairing_record(self) -> None:
- dropped = {
- "reason_code": "ambiguous_bare_selector",
- "tool_name": "click",
- "selector": "button",
- "trajectory_index": 1,
- }
- ctx = _resale_ctx()
- claimed: set[int] = set()
- forgiven, record = workflow_update_module._bare_drop_superseded_on_screen(
- dropped, ctx.scout_trajectory, claimed_refiner_indices=claimed
+ assert ctx.request_policy.request_slot_failure_kind == "invalid_output"
+ assert all(criterion.output_path is None for criterion in ctx.request_policy.completion_criteria)
+ assert all(criterion.mint_disposition == "degraded" for criterion in ctx.request_policy.completion_criteria)
+ assert evaluation is not None
+ assert evaluation.payload["contract_liveness"] == "degraded_empty"
+ assert evaluation.payload["reason_code"] == "value_bearing_output_required"
+ assert evaluation.can_attempt_run is False
+ assert "canonical_evaluation_paths" not in evaluation.payload
+ assert [row["floor_rekeyed_from_path"] for row in evaluation.payload["degraded_request_slots"]] == sorted(
+ requested_paths
)
- assert forgiven is True
- assert record == {
- "dropped_index": 1,
- "dropped_selector": "button",
- "refiner_index": 2,
- "refiner_selector": 'button[data-action="status"]',
- "source_url": _RESALE_URL,
+ assert {row["request_slot_failure_kind"] for row in evaluation.payload["degraded_request_slots"]} == {
+ "invalid_output"
}
- assert claimed == {2}
+ assert preflight is not None
+ assert preflight["data"]["reason_code"] == "value_bearing_output_required"
+ assert "output_contract_reason_code" not in preflight["data"]
+
+ @pytest.mark.asyncio
+ async def test_degraded_declaration_only_contract_never_persists_or_dispatches(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ ctx = _degraded_declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
+ persisted = False
+ dispatched = False
+
+ async def _unexpected_update(*_args: object, **_kwargs: object) -> dict[str, object]:
+ nonlocal persisted
+ persisted = True
+ return {"ok": True}
+
+ async def _unexpected_dispatch(*_args: object, **_kwargs: object) -> dict[str, object]:
+ nonlocal dispatched
+ dispatched = True
+ return {"ok": True}
- def test_supersession_false_across_different_source_url(self) -> None:
- ctx = _resale_ctx()
- ctx.scout_trajectory[2]["source_url"] = "https://example.com/other"
- dropped = {
- "reason_code": "ambiguous_bare_selector",
- "tool_name": "click",
- "selector": "button",
- "trajectory_index": 1,
- }
- forgiven, record = workflow_update_module._bare_drop_superseded_on_screen(
- dropped, ctx.scout_trajectory, claimed_refiner_indices=set()
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ monkeypatch.setattr(tools_module, "_update_workflow", _unexpected_update)
+ monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _unexpected_dispatch)
+
+ result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps({"workflow_yaml": workflow_yaml, "block_labels": ["extract_entry_output"]}),
)
- assert forgiven is False
- assert record is None
- def test_supersession_false_without_later_refiner(self) -> None:
- ctx = _resale_ctx(refiner_selector="button:nth-of-type(2)")
- dropped = {
- "reason_code": "ambiguous_bare_selector",
- "tool_name": "click",
- "selector": "button",
- "trajectory_index": 1,
- }
- forgiven, _ = workflow_update_module._bare_drop_superseded_on_screen(
- dropped, ctx.scout_trajectory, claimed_refiner_indices=set()
+ parsed = json.loads(result)
+ assert parsed["ok"] is False
+ assert parsed["data"]["reason_code"] == "value_bearing_output_required"
+ assert "output_contract_reason_code" not in parsed["data"]
+ assert parsed["data"]["contract_liveness"] == "degraded_empty"
+ assert persisted is False
+ assert dispatched is False
+
+ def test_mixed_value_and_declaration_return_remains_valid(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml(
+ 'record_id = await page.locator("#record-id").text_content()\nreturn {"output": {"record_id": record_id}}'
)
- assert forgiven is False
- def test_supersession_false_on_empty_source_url(self) -> None:
- ctx = _resale_ctx()
- ctx.scout_trajectory[1]["source_url"] = ""
- dropped = {
- "reason_code": "ambiguous_bare_selector",
- "tool_name": "click",
- "selector": "button",
- "trajectory_index": 1,
- }
- forgiven, _ = workflow_update_module._bare_drop_superseded_on_screen(
- dropped, ctx.scout_trajectory, claimed_refiner_indices=set()
+ formed_yaml, metadata, applied = workflow_update_module._impose_output_contract_envelope_after_steering(
+ ctx, workflow_yaml, []
)
- assert forgiven is False
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(ctx, formed_yaml, metadata)
- def test_supersession_false_on_out_of_bounds_index(self) -> None:
- ctx = _resale_ctx()
- for bad_index in (-1, 99, "1", None):
- dropped = {
- "reason_code": "ambiguous_bare_selector",
- "tool_name": "click",
- "selector": "button",
- "trajectory_index": bad_index,
- }
- forgiven, _ = workflow_update_module._bare_drop_superseded_on_screen(
- dropped, ctx.scout_trajectory, claimed_refiner_indices=set()
- )
- assert forgiven is False
+ assert applied is True
+ assert evaluation is not None
+ assert evaluation.has_deficiencies is False
+ code = str(workflow_blocks(parse_workflow_yaml(formed_yaml))[0].get("code") or "")
+ assert '"record_id": record_id' in code
+ assert '"blocker": None' in code
- def test_imposition_forgives_mid_trajectory_bare_drop_and_records_substitution(self) -> None:
- ctx = _resale_ctx()
- result = workflow_update_module._maybe_impose_synthesized_code_block(_resale_submitted_yaml(), ctx)
+ def test_formation_does_not_create_declaration_only_scaffold(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('await page.click("#submit")\nreturn {}')
- assert result.violations == []
- assert result.substitutions is not None
- forgiven = result.substitutions["forgiven_superseded_bare_drops"]
- assert forgiven == [
- {
- "dropped_index": 1,
- "dropped_selector": "button",
- "refiner_index": 2,
- "refiner_selector": 'button[data-action="status"]',
- "source_url": _RESALE_URL,
- }
- ]
- block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))
- assert 'button[data-action=\\"status\\"]' in str(block["code"])
+ new_yaml, _metadata, applied = workflow_update_module._impose_output_contract_envelope_after_steering(
+ ctx, workflow_yaml, []
+ )
- def test_imposition_keeps_bare_drop_fatal_when_sibling_is_positional(self) -> None:
- ctx = _resale_ctx(refiner_selector="button:nth-of-type(2)")
- result = workflow_update_module._maybe_impose_synthesized_code_block(
- _resale_submitted_yaml("button:nth-of-type(2)"), ctx
+ assert applied is True
+ assert new_yaml == workflow_yaml
+ code = str(workflow_blocks(parse_workflow_yaml(new_yaml))[0].get("code") or "")
+ assert "blocker" not in code
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(ctx, new_yaml, _metadata)
+ assert evaluation is not None
+ assert evaluation.can_attempt_run is False
+
+ def test_stamp_is_idempotent_across_calls(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('await page.click("#submit")')
+
+ first_yaml, _metadata, _applied = workflow_update_module._impose_output_contract_envelope_after_steering(
+ ctx, workflow_yaml, []
+ )
+ again_yaml, _metadata2, _applied2 = workflow_update_module._impose_output_contract_envelope_after_steering(
+ ctx, first_yaml, []
)
- assert any("ambiguous_bare_selector" in violation for violation in result.violations)
- assert result.substitutions is None
+ assert again_yaml == first_yaml
- def test_imposition_one_refiner_does_not_forgive_two_bare_drops(self) -> None:
- ctx = _resale_ctx()
- ctx.scout_trajectory = [
- {"tool_name": "click", "selector": "#start", "source_url": _RESALE_URL, "trajectory_index": 0},
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 2},
- {
- "tool_name": "click",
- "selector": 'button[data-action="status"]',
- "source_url": _RESALE_URL,
- "trajectory_index": 3,
- },
- ]
- submitted = _yaml(
- """
- title: Order status
- workflow_definition:
- blocks:
- - block_type: code
- label: order_status
- code: |
- await page.locator("#start").click()
- await page.locator("button[data-action=\\"status\\"]").click()
- """
+ def test_stamp_skips_without_single_owner_block(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _yaml(
+ "title: Two blocks\n"
+ "workflow_definition:\n"
+ " blocks:\n"
+ " - block_type: code\n"
+ " label: first\n"
+ " code: |\n"
+ ' await page.click("#a")\n'
+ " - block_type: code\n"
+ " label: second\n"
+ " code: |\n"
+ ' await page.click("#b")\n'
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
- assert any("ambiguous_bare_selector" in violation for violation in result.violations)
+ new_yaml, _metadata, applied = workflow_update_module._impose_output_contract_envelope_after_steering(
+ ctx, workflow_yaml, []
+ )
- def test_imposition_two_refiners_forgive_two_bare_drops(self) -> None:
- ctx = _resale_ctx()
- ctx.scout_trajectory = [
- {"tool_name": "click", "selector": "#start", "source_url": _RESALE_URL, "trajectory_index": 0},
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 2},
- {
- "tool_name": "click",
- "selector": 'button[data-action="open"]',
- "source_url": _RESALE_URL,
- "trajectory_index": 3,
- },
- {
- "tool_name": "click",
- "selector": 'button[data-action="status"]',
- "source_url": _RESALE_URL,
- "trajectory_index": 4,
- },
- ]
- submitted = _yaml(
- """
- title: Order status
- workflow_definition:
- blocks:
- - block_type: code
- label: order_status
- code: |
- await page.locator("#start").click()
- await page.locator("button[data-action=\\"open\\"]").click()
- await page.locator("button[data-action=\\"status\\"]").click()
- """
+ assert applied is False
+ assert new_yaml == workflow_yaml
+
+ def test_stamp_refused_for_statically_empty_observation_code(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": {"record_id": None}}')
+ contract = workflow_update_module._output_contract_required_paths_source(ctx)
+
+ stamped_yaml, applied = workflow_update_module._stamp_declaration_contract_defaults(
+ ctx, workflow_yaml, [], contract, "sig-declaration-stamp"
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
- assert result.violations == []
- assert result.substitutions is not None
- forgiven = result.substitutions["forgiven_superseded_bare_drops"]
- assert {record["dropped_index"] for record in forgiven} == {1, 2}
- assert {record["refiner_index"] for record in forgiven} == {3, 4}
+ assert applied is False
+ assert stamped_yaml == workflow_yaml
- def test_imposition_two_exact_text_xpath_button_refiners_forgive_two_bare_drops(self) -> None:
- ctx = _resale_ctx()
- first_refiner = "xpath=//button[normalize-space()='Check Order Status']"
- second_refiner = "xpath=//button[normalize-space()='View / Download']"
- ctx.scout_trajectory = [
- {
- "tool_name": "type_text",
- "selector": "#order-id",
- "source_url": _RESALE_URL,
- "typed_length": 6,
- "typed_value": "abc123",
- "trajectory_index": 0,
- },
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 2},
- {"tool_name": "click", "selector": first_refiner, "source_url": _RESALE_URL, "trajectory_index": 3},
- {"tool_name": "click", "selector": second_refiner, "source_url": _RESALE_URL, "trajectory_index": 4},
- ]
- submitted = _yaml(
- """
- title: Order status
- workflow_definition:
- blocks:
- - block_type: code
- label: order_status
- code: |
- await page.locator("#order-id").fill(str(order_id))
- await page.locator("xpath=//button[normalize-space()='Check Order Status']").click()
- await page.locator("xpath=//button[normalize-space()='View / Download']").click()
- """
+ def test_stamp_applies_for_runtime_populated_observation_code(self) -> None:
+ ctx = _declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml(
+ 'record_id = await page.inner_text("#record")\nreturn {"output": {"record_id": record_id}}'
+ )
+ contract = workflow_update_module._output_contract_required_paths_source(ctx)
+
+ stamped_yaml, applied = workflow_update_module._stamp_declaration_contract_defaults(
+ ctx, workflow_yaml, [], contract, "sig-declaration-stamp"
)
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ assert applied is True
+ code = str(workflow_blocks(parse_workflow_yaml(stamped_yaml))[0].get("code") or "")
+ assert '"blocker": None' in code
+
- assert result.violations == []
- assert result.substitutions is not None
- forgiven = result.substitutions["forgiven_superseded_bare_drops"]
- assert {record["dropped_index"] for record in forgiven} == {1, 2}
- assert {record["refiner_index"] for record in forgiven} == {3, 4}
- assert {record["refiner_selector"] for record in forgiven} == {first_refiner, second_refiner}
- block = _single_code_block(parse_workflow_yaml(result.workflow_yaml))
- assert first_refiner in str(block["code"])
- assert second_refiner in str(block["code"])
+def test_static_return_synthesis_refuses_statically_none_observation_local() -> None:
+ code = "record_id = None"
- def test_imposition_one_exact_text_xpath_refiner_does_not_forgive_two_bare_drops(self) -> None:
- ctx = _resale_ctx()
- refiner = "xpath=//button[normalize-space()='Check Order Status']"
- ctx.scout_trajectory = [
- {"tool_name": "click", "selector": "#start", "source_url": _RESALE_URL, "trajectory_index": 0},
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 2},
- {"tool_name": "click", "selector": refiner, "source_url": _RESALE_URL, "trajectory_index": 3},
- ]
- submitted = _yaml(
- """
- title: Order status
- workflow_definition:
- blocks:
- - block_type: code
- label: order_status
- code: |
- await page.locator("#start").click()
- await page.locator("xpath=//button[normalize-space()='Check Order Status']").click()
- """
- )
+ keyed, violations = workflow_update_module._extraction_code_with_value_bearing_static_return(
+ code, required_paths={"output.record_id"}, declaration_paths={"output.blocker"}
+ )
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ assert violations
+ assert keyed == code
- assert any("ambiguous_bare_selector" in violation for violation in result.violations)
- def test_imposition_positional_xpath_refiner_keeps_bare_drop_fatal(self) -> None:
- ctx = _resale_ctx()
- positional_refiner = "xpath=(//button[normalize-space()='Check Order Status'])[2]"
- ctx.scout_trajectory = [
- {"tool_name": "click", "selector": "#start", "source_url": _RESALE_URL, "trajectory_index": 0},
- {"tool_name": "click", "selector": "button", "source_url": _RESALE_URL, "trajectory_index": 1},
- {"tool_name": "click", "selector": positional_refiner, "source_url": _RESALE_URL, "trajectory_index": 2},
- ]
- submitted = _yaml(
- """
- title: Order status
- workflow_definition:
- blocks:
- - block_type: code
- label: order_status
- code: |
- await page.locator("#start").click()
- await page.locator("xpath=(//button[normalize-space()='Check Order Status'])[2]").click()
- """
- )
+def test_static_return_synthesis_accepts_runtime_populated_observation_local() -> None:
+ code = 'record_id = await page.inner_text("#record")'
- result = workflow_update_module._maybe_impose_synthesized_code_block(submitted, ctx)
+ keyed, violations = workflow_update_module._extraction_code_with_value_bearing_static_return(
+ code, required_paths={"output.record_id"}, declaration_paths={"output.blocker"}
+ )
- assert any("ambiguous_bare_selector" in violation for violation in result.violations)
- assert result.substitutions is None
+ assert violations == []
+ assert {"output.record_id", "output.blocker"} <= workflow_update_module._code_block_produced_output_paths(keyed)
- @pytest.mark.asyncio
- async def test_auto_act_non_navigating_reads_role_name(self, monkeypatch: pytest.MonkeyPatch) -> None:
- ctx = _auto_act_scout_ctx()
- captured: dict[str, object] = {}
- async def _fake_resolve(
- _ctx: AgentContext, selector: str | None, *, allow_browser_read: bool
- ) -> tuple[str, str]:
- captured["allow_browser_read"] = allow_browser_read
- return "button", "Continue"
+def test_static_return_synthesis_refuses_covered_statically_empty_return() -> None:
+ code = 'return {"output": {"record_id": None, "blocker": None}}'
- monkeypatch.setattr(scouting_module, "_resolve_scout_role_name", _fake_resolve)
+ _, violations = workflow_update_module._extraction_code_with_value_bearing_static_return(
+ code, required_paths={"output.record_id"}, declaration_paths={"output.blocker"}
+ )
- async def _same_url(_ctx: AgentContext) -> str:
- return "https://example.com/orders"
+ assert violations
- monkeypatch.setattr(scouting_module, "_live_working_page_url", _same_url)
- async def _evidence(_ctx: AgentContext, *, url: str) -> dict[str, object] | None:
- return None
+def test_value_bearing_lattice_unpack_after_empty_literal_is_fail_open() -> None:
+ code = 'extra = await collect()\nreturn {"output": {"record_id": None, **extra}}'
- monkeypatch.setattr(scouting_module, "_scout_act_observe_page_evidence", _evidence)
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
- acted = await scouting_module._auto_act_on_repeat(
- ctx,
- {"data": {}},
- url="https://example.com/orders",
- target={"selector": "#continue", "text": "Continue"},
- )
- assert acted is True
- assert captured["allow_browser_read"] is True
- last = ctx.scout_trajectory[-1]
- assert last["role"] == "button"
- assert last["accessible_name"] == "Continue"
+def test_value_bearing_lattice_top_level_unpack_after_output_key_is_fail_open() -> None:
+ code = 'extra = await collect()\nreturn {"output": {"record_id": None}, **extra}'
- @pytest.mark.asyncio
- async def test_auto_act_navigating_skips_browser_read(self, monkeypatch: pytest.MonkeyPatch) -> None:
- ctx = _auto_act_scout_ctx()
- captured: dict[str, object] = {}
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
- async def _fake_resolve(
- _ctx: AgentContext, selector: str | None, *, allow_browser_read: bool
- ) -> tuple[str, str]:
- captured["allow_browser_read"] = allow_browser_read
- return "", ""
- monkeypatch.setattr(scouting_module, "_resolve_scout_role_name", _fake_resolve)
+def test_value_bearing_lattice_empty_literal_after_unpack_stays_refused() -> None:
+ code = 'extra = await collect()\nreturn {"output": {**extra, "record_id": None}}'
- urls = iter(["https://example.com/orders", "https://example.com/status"])
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is True
- async def _moving_url(_ctx: AgentContext) -> str:
- return next(urls)
- monkeypatch.setattr(scouting_module, "_live_working_page_url", _moving_url)
+ "mutation",
+ [
+ "payload, extra = await split()",
+ "*rest, payload = await split()",
+ 'with open("audit.log") as payload:\n pass',
+ "try:\n pass\nexcept ValueError as payload:\n pass",
+ "if (payload := await build()):\n pass",
+ 'payload["output"]["record_id"] = await fetch()',
+ 'payload["output"].update(await fetch())',
+ 'for item in await rows():\n payload["output"]["items"].append(item)',
+ "populate(payload)",
+ "payload.output = await fetch()",
+ 'alias = payload\nalias["output"]["record_id"] = await fetch()',
+ 'alias = payload\nalias["output"].update(await fetch())',
+ 'inner = payload["output"]\ninner["record_id"] = await fetch()',
+ "alias = payload\npopulate(alias)",
+ "first = payload\nsecond = first\nsecond.output = await fetch()",
+ ],
+)
+def test_value_bearing_lattice_mutated_literal_is_fail_open(mutation: str) -> None:
+ code = f'payload = {{"output": {{"record_id": None}}}}\n{mutation}\nreturn payload'
- async def _evidence(_ctx: AgentContext, *, url: str) -> dict[str, object] | None:
- return None
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
+ assert workflow_update_module._statically_valueless_return_envelope(code) is False
- monkeypatch.setattr(scouting_module, "_scout_act_observe_page_evidence", _evidence)
- acted = await scouting_module._auto_act_on_repeat(
- ctx,
- {"data": {}},
- url="https://example.com/orders",
- target={"selector": "#continue", "text": "Continue"},
- )
+def test_value_bearing_lattice_unmutated_literal_stays_refused() -> None:
+ code = 'payload = {"output": {"record_id": None}}\nother = await fetch()\nreturn payload'
- assert acted is True
- assert captured["allow_browser_read"] is False
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is True
+ assert workflow_update_module._statically_valueless_return_envelope(code) is True
-def _auto_act_scout_ctx() -> AgentContext:
- ctx = AgentContext.__new__(AgentContext)
- ctx.browser_session_id = None
- ctx.scouted_interactions = []
- ctx.scout_trajectory = []
- ctx.scout_observed_terminal_criterion_ids = set()
- ctx.completion_criteria_turn_state = None
- ctx.discovery_mcp_server = _AutoActClickServer()
- return ctx
+def test_value_bearing_lattice_unmutated_alias_stays_refused() -> None:
+ code = 'payload = {"output": {"record_id": None}}\nalias = payload\nreturn payload'
+
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is True
+ assert workflow_update_module._statically_valueless_return_envelope(code) is True
-class _AutoActClickServer:
- async def call_internal_tool(self, tool_name: str, args: dict[str, object]) -> dict[str, object]:
- return {"ok": True, "data": {"selector": args.get("selector")}}
+ "aliasing",
+ [
+ 'holder = {}\nholder["slot"] = payload',
+ 'holder = {}\nholder["slot"] = payload\nholder["slot"]["output"]["record_id"] = await fetch()',
+ 'holder = {}\nholder["slot"] = payload\nholder["slot"]["output"].update(await fetch())',
+ 'holder = obj()\nholder.slot = payload\nholder.slot["output"]["record_id"] = await fetch()',
+ ],
+)
+def test_value_bearing_lattice_alias_into_container_target_is_fail_open(aliasing: str) -> None:
+ # Assigning payload into a subscript/attribute target aliases it, so a mutation through the
+ # container could make the return value-bearing; the value name must taint (fail-open), not
+ # resolve to its pre-alias empty literal.
+ code = f'payload = {{"output": {{"record_id": None}}}}\n{aliasing}\nreturn payload'
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
+ assert workflow_update_module._statically_valueless_return_envelope(code) is False
+
+
+def test_value_bearing_lattice_nul_byte_source_is_fail_open() -> None:
+ code = 'return {"output": {"record_id": None}}\x00'
+
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
+ assert workflow_update_module._statically_valueless_return_envelope(code) is False
+
+
+def test_value_bearing_lattice_deep_alias_chain_is_fail_open() -> None:
+ lines = ['v0 = {"output": {"record_id": None}}']
+ lines.extend(f"v{index} = v{index - 1}" for index in range(1, 1500))
+ lines.append("return v1499")
+ code = "\n".join(lines)
+
+ assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
+ assert workflow_update_module._statically_valueless_return_envelope(code) is False
+
+
+ ("code", "expected"),
+ [
+ ('runtime_value = await collect()\nreturn {"output": runtime_value}', "proven"),
+ (
+ 'runtime_value = await collect()\npayload = {"output": runtime_value}\nalias = payload\nreturn alias',
+ "proven",
+ ),
+ ("runtime_value = await collect()\nreturn runtime_value", "unknown"),
+ ('runtime_value = await collect()\nreturn {"request_id": runtime_value}', "absent"),
+ ('runtime_value = await collect()\nreturn {"output.request_id": runtime_value}', "absent"),
+ ('runtime_value = await collect()\noutput_key = "output"\nreturn {output_key: runtime_value}', "unknown"),
+ (
+ 'runtime_value = await collect()\nextra = await collect_extra()\nreturn {"output": runtime_value, **extra}',
+ "unknown",
+ ),
+ (
+ 'if should_return_output:\n return {"output": runtime_value}\nreturn {"request_id": runtime_value}',
+ "absent",
+ ),
+ ('return payload\npayload = {"output": runtime_value}', "unknown"),
+ ("await page.click('#submit')", "absent"),
+ ],
+)
+def test_root_output_envelope_state_requires_literal_root_on_every_return(code: str, expected: str) -> None:
+ assert workflow_update_module._root_output_envelope_state(code) == expected
-def _declaration_stamp_ctx() -> CopilotContext:
- ctx = _code_only_ctx()
- ctx.turn_id = "t-decl"
- ctx.scout_trajectory = []
- ctx.request_policy = RequestPolicy(
- completion_criteria=[
- CompletionCriterion(
- id="c_record",
- outcome="The returned record includes record id.",
- output_path="output.record_id",
- ),
- CompletionCriterion(
- id="c_blocker",
- outcome="A blocker is reported when the site blocks submission.",
- contingent_on="the site blocks submission",
- contingent_antecedent_output_path="output.blocker",
- ),
- ]
- )
- return ctx
+def test_canonical_output_contract_signature_is_single_keyed_under_degraded_slots() -> None:
+ ctx = _degraded_declaration_stamp_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ [],
+ allow_static_return_advisory=True,
+ enforce_value_bearing_liveness=True,
+ )
+ assert evaluation is not None
+ contract = workflow_update_module._output_contract_required_paths_source(ctx)
+ directive_paths = workflow_update_module._value_bearing_directive_paths(contract)
+ signature = workflow_update_module._output_contract_signature(ctx=ctx, required_paths=directive_paths)
-def _degraded_declaration_stamp_ctx() -> CopilotContext:
- ctx = _code_only_ctx()
- ctx.turn_id = "t-degraded-decl"
- ctx.scout_trajectory = []
- requested_paths = (
- "output.confirmation_number",
- "output.account_number",
- "output.start_date",
- "output.deposit_amount",
- "output.next_owner",
+ assert directive_paths == {"output"}
+ assert evaluation.canonical_signature == signature
+ assert evaluation.payload["canonical_output_contract_signature"] == signature
+ assert workflow_update_module._output_contract_pin_key(ctx, workflow_yaml, directive_paths) == signature
+ structural = workflow_update_module._output_contract_author_time_structural_payload(ctx, directive_paths)
+ assert structural is not None
+ assert structural["canonical_output_contract_signature"] == signature
+ workflow_update_module._record_output_contract_family_reject(
+ ctx, directive_paths, reject_family="value_bearing_output_required"
)
- ctx.request_policy = RequestPolicy(
- completion_criteria=[
- *[
- CompletionCriterion(
- id=f"slot_{index}",
- outcome=f"The returned record includes {path}.",
- request_slot_id=f"slot_{index}",
- pinability="unpinnable",
- mint_disposition="degraded",
- mint_degrade="undecidable_judgment",
- requested_output_floor_rekeyed=True,
- floor_rekeyed_from_path=path,
- )
- for index, path in enumerate(requested_paths)
- ],
- CompletionCriterion(
- id="c_blocker",
- outcome="A blocker is reported when the site blocks submission.",
- contingent_on="the site blocks submission",
- contingent_antecedent_output_path="output.blocker",
- ),
- ]
+ assert ctx.output_contract_reject_count_by_signature == {signature: 1}
+ workflow_update_module._record_output_contract_deferral(ctx, directive_paths)
+ assert ctx.output_contract_deferral_count_by_signature == {signature: 1}
+ identity_free = workflow_update_module._stable_output_contract_key(
+ workflow_update_module._output_contract_scope_key(ctx), directive_paths
)
- return ctx
+ assert signature != identity_free
-class TestDeclarationContractStamp:
- @pytest.mark.parametrize("empty_value", ["None", "''", "' '", "[]", "{}", "[None]", "[{}]", "{'a': None}"])
- def test_static_empty_observation_value_is_non_run_eligible(self, empty_value: str) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml(f'return {{"output": {{"record_id": {empty_value}, "blocker": None}}}}')
- metadata = [
- workflow_update_module._metadata_contract_template(
- block_label="extract_record",
- required_paths={"output.record_id"},
- source="requested_output_contract",
- reason_code="requested_output_contract_missing_output_coverage",
- declaration_paths={"output.blocker"},
+class TestValueBearingDefinitionRejectComposition:
+ @staticmethod
+ def _ctx() -> CopilotContext:
+ ctx = _live_root_value_bearing_ctx()
+ ctx.request_policy.completion_criteria.append(
+ CompletionCriterion(
+ id="reusable_inputs",
+ outcome="The workflow uses the service address as a reusable input.",
+ level="definition",
+ output_path="workflow.parameters",
)
- ]
+ )
+ return ctx
- evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
- ctx,
- workflow_yaml,
- metadata,
- allow_static_return_advisory=True,
- enforce_value_bearing_liveness=True,
+ @staticmethod
+ def _workflow_yaml() -> str:
+ return _yaml(
+ """
+ title: Submit reusable service request
+ workflow_definition:
+ parameters:
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ blocks:
+ - block_type: code
+ label: extract_record
+ parameter_keys: []
+ code: |
+ return {"output": None}
+ """
)
- assert evaluation is not None
- assert evaluation.missing_metadata_paths == []
- assert evaluation.missing_schema_paths == []
- assert evaluation.missing_return_paths == []
- assert evaluation.payload["reason_code"] == "value_bearing_output_required"
- assert evaluation.can_attempt_run is False
+ @staticmethod
+ def _assert_composed_reject(result: dict[str, object], *, rung: int) -> None:
+ data = result["data"]
+ assert isinstance(data, dict)
+ assert data["reason_code"] == "definition_contract_unsatisfied"
+ assert data["unreferenced_parameter_keys"] == ["service_address"]
+ assert data["canonical_required_child_paths"] == ["output"]
+ assert data["shape_violations"] == ["value_bearing_output_required"]
+ assert data["satisfying_templates"]
+ assert data["output_contract_actuation"] == "structure_directive"
+ assert data["value_bearing_convergence_directive"] == {
+ "rung": rung,
+ "required_output_paths": ["output"],
+ "shape_violations": ["value_bearing_output_required"],
+ "satisfying_templates": data["satisfying_templates"],
+ }
- @pytest.mark.parametrize("value", ["0", "False", "'record-123'", "[None, 'x']", "{'a': 'x'}"])
- def test_static_value_bearing_observation_remains_run_eligible(self, value: str) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml(f'return {{"output": {{"record_id": {value}, "blocker": None}}}}')
- metadata = [
- workflow_update_module._metadata_contract_template(
- block_label="extract_record",
- required_paths={"output.record_id"},
- source="requested_output_contract",
- reason_code="requested_output_contract_missing_output_coverage",
- declaration_paths={"output.blocker"},
- )
- ]
+ def test_live_request_policy_definition_reject_composes_root_directive_and_escalates(self) -> None:
+ ctx = self._ctx()
+ workflow_yaml = self._workflow_yaml()
- evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
- ctx, workflow_yaml, metadata, enforce_value_bearing_liveness=True
- )
+ with capture_logs() as first_logs:
+ first = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
+ ctx.output_contract_bail_actuated_this_call = False
+ with capture_logs() as second_logs:
+ second = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
- assert evaluation is not None
- assert evaluation.has_deficiencies is False
+ assert first is not None
+ assert second is not None
+ self._assert_composed_reject(first, rung=1)
+ self._assert_composed_reject(second, rung=2)
+ first_emits = [log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ second_emits = [log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(first_emits) == 1
+ assert len(second_emits) == 1
+ assert first_emits[0]["canonical_required_child_paths"] == ["output"]
+ assert second_emits[0]["canonical_required_child_paths"] == ["output"]
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "definition_contract_unsatisfied"
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
- def test_full_metadata_advisory_rejects_declaration_only_return(self) -> None:
- ctx = _declaration_stamp_ctx()
- required_paths = {"output.record_id", "output.blocker"}
- signature = workflow_update_module._stable_output_contract_key(
- workflow_update_module._output_contract_scope_key(ctx), required_paths
+ @pytest.mark.asyncio
+ async def test_public_p5_tool_replay_emits_rungs_then_preserves_definition_route(self) -> None:
+ ctx = self._ctx()
+ workflow_yaml = self._workflow_yaml()
+ metadata: list[dict[str, object]] = []
+ submitted_metadata = json.dumps(metadata, sort_keys=True)
+ tool_ctx = SimpleNamespace(context=ctx, tool_name="update_and_run_blocks")
+ arguments = json.dumps(
+ {
+ "workflow_yaml": workflow_yaml,
+ "block_labels": ["extract_record"],
+ "code_artifact_metadata": metadata,
+ }
)
- workflow_update_module._grant_output_contract_advisory_run(ctx, signature)
- workflow_yaml = _collapsed_spine_yaml('await page.click("#submit")\nreturn {"output": {"blocker": None}}')
- metadata = [
- workflow_update_module._metadata_contract_template(
- block_label="extract_record",
- required_paths={"output.record_id"},
- source="requested_output_contract",
- reason_code="requested_output_contract_missing_output_coverage",
- declaration_paths={"output.blocker"},
- )
- ]
- evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
- ctx,
- workflow_yaml,
- metadata,
- allow_static_return_advisory=True,
- enforce_value_bearing_liveness=True,
- )
+ with capture_logs() as logs:
+ first = json.loads(await tools_module.update_and_run_blocks_tool.on_invoke_tool(tool_ctx, arguments))
+ second = json.loads(await tools_module.update_and_run_blocks_tool.on_invoke_tool(tool_ctx, arguments))
- assert evaluation is not None
- assert evaluation.missing_metadata_paths == []
- assert evaluation.missing_schema_paths == []
- assert evaluation.missing_return_paths == ["output.record_id"]
- assert evaluation.payload["static_return_advisory_paths"] == []
- assert evaluation.payload["reason_code"] == "value_bearing_output_required"
- assert evaluation.can_attempt_run is False
+ self._assert_composed_reject(first, rung=1)
+ self._assert_composed_reject(second, rung=2)
+ emits = [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert [event["rung"] for event in emits] == [1, 2]
+ assert all(event["canonical_required_child_paths"] == ["output"] for event in emits)
+ assert emits[0]["guidance_fingerprint"] == emits[1]["guidance_fingerprint"]
+ assert json.dumps(metadata, sort_keys=True) == submitted_metadata
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "definition_contract_unsatisfied"
+ requirement = ctx.recorded_outcome_grounding_requirement
+ assert requirement is not None
+ assert requirement.phase == "author_time_reject"
+ assert requirement.reason_code == "definition_contract_unsatisfied"
+ assert ctx.output_contract_actuation_by_signature == {}
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.workflow_yaml == ""
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
@pytest.mark.asyncio
- async def test_full_metadata_declaration_only_contract_rejects_at_persist_seam(self) -> None:
+ async def test_update_workflow_definition_reject_returns_same_composed_root_directive(self) -> None:
+ ctx = self._ctx()
+
+ with capture_logs() as logs:
+ result = await _update_workflow(
+ {"workflow_yaml": self._workflow_yaml(), "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ self._assert_composed_reject(result, rung=1)
+ emits = [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(emits) == 1
+ assert emits[0]["canonical_required_child_paths"] == ["output"]
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "definition_contract_unsatisfied"
+ assert ctx.workflow_yaml == ""
+
+
+class TestValueBearingConvergenceDirective:
+ @staticmethod
+ def _directive(
+ data: dict[str, object],
+ *,
+ paths: list[str],
+ rung: int,
+ ) -> dict[str, object]:
+ return {
+ "rung": rung,
+ "required_output_paths": paths,
+ "shape_violations": ["value_bearing_output_required"],
+ "satisfying_templates": data["satisfying_templates"],
+ }
+
+ @staticmethod
+ def _ctx() -> CopilotContext:
ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml('await page.click("#submit")\nreturn {"output": {"blocker": None}}')
+ ctx.request_policy.completion_criteria.append(
+ CompletionCriterion(
+ id="c_account",
+ outcome="The returned record includes account number.",
+ output_path="output.account_number",
+ )
+ )
+ return ctx
+
+ @staticmethod
+ def _workflow_and_metadata() -> tuple[str, list[dict[str, object]]]:
+ workflow_yaml = _collapsed_spine_yaml(
+ 'return {"output": {"record_id": None, "account_number": None, "blocker": None}}'
+ )
metadata = [
workflow_update_module._metadata_contract_template(
block_label="extract_record",
- required_paths={"output.record_id"},
+ required_paths={"output.record_id", "output.account_number"},
source="requested_output_contract",
reason_code="requested_output_contract_missing_output_coverage",
declaration_paths={"output.blocker"},
)
]
+ return workflow_yaml, metadata
- result = await _update_workflow(
- {"workflow_yaml": workflow_yaml, "code_artifact_metadata": metadata},
- ctx,
- allow_missing_credentials=True,
- )
-
- assert result["ok"] is False
- assert result["data"]["reason_code"] == "value_bearing_output_required"
- assert result["data"]["contract_liveness"] == "value_required"
- assert result["data"]["missing_goal_value_paths"] == []
- assert result["data"]["missing_extraction_schema_paths"] == []
- assert result["data"]["missing_code_return_paths"] == ["output.record_id"]
-
- def test_grant_preflight_rejects_declaration_only_return(self) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
- evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
- ctx,
- workflow_yaml,
- [],
- allow_static_return_advisory=True,
- enforce_value_bearing_liveness=True,
- )
- assert evaluation is not None
- workflow_update_module._grant_output_contract_advisory_run(ctx, evaluation.canonical_signature)
-
- preflight = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
-
- assert evaluation.payload["reason_code"] == "value_bearing_output_required"
- assert evaluation.can_attempt_run is False
- assert preflight is not None
- assert preflight["data"]["output_contract_reason_code"] == "value_bearing_output_required"
- assert (
- workflow_update_module._output_contract_advisory_state(ctx, evaluation.canonical_signature)
- == OutputContractAdvisoryState.UNUSED
+ @staticmethod
+ def _degraded_ctx(*floor_paths: str) -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.turn_id = "t-degraded-value-bearing-directive"
+ ctx.scout_trajectory = []
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(
+ id=f"slot_{index}",
+ outcome=f"The returned record includes slot {index}.",
+ output_path="output",
+ request_slot_id=f"slot_{index}",
+ pinability="unpinnable",
+ mint_disposition="degraded",
+ mint_degrade="undecidable_judgment",
+ requested_output_floor_rekeyed=True,
+ floor_rekeyed_from_path=path,
+ )
+ for index, path in enumerate(floor_paths)
+ ]
)
- assert evaluation.canonical_signature not in ctx.output_contract_pending_run_evidence
-
- def test_degraded_requested_slots_make_declaration_only_contract_non_run_eligible(self) -> None:
- ctx = _degraded_declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
+ return ctx
- formed_yaml, metadata, applied = workflow_update_module._impose_output_contract_envelope_after_steering(
- ctx, workflow_yaml, []
+ @staticmethod
+ def _declaration_only_ctx() -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.turn_id = "t-declaration-only-value-bearing-directive"
+ ctx.scout_trajectory = []
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(
+ id="c_blocker",
+ outcome="A blocker is returned when submission is unavailable.",
+ output_path="output.blocker",
+ contingent_on="submission is unavailable",
+ contingent_antecedent_output_path="output.blocker",
+ antecedent_family="blocker",
+ )
+ ]
)
+ return ctx
+
+ @staticmethod
+ def _live_root_request_policy_ctx() -> CopilotContext:
+ return _live_root_value_bearing_ctx()
+
+ @staticmethod
+ def _live_root_evaluation(
+ ctx: CopilotContext,
+ workflow_yaml: str,
+ metadata: list[dict[str, object]],
+ ) -> workflow_update_module._OutputContractEvaluation:
evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
ctx,
- formed_yaml,
+ workflow_yaml,
metadata,
- allow_static_return_advisory=True,
enforce_value_bearing_liveness=True,
)
-
- assert applied is False
- assert formed_yaml == workflow_yaml
assert evaluation is not None
- signature = evaluation.canonical_signature
- assert ctx.output_contract_armed_directive_fingerprint_by_signature.get(
- signature
- ) == workflow_update_module._output_contract_structural_fingerprint(workflow_yaml, signature)
- assert evaluation.payload["contract_liveness"] == "degraded_empty"
- assert evaluation.payload["reason_code"] == "value_bearing_output_required"
- assert evaluation.can_attempt_run is False
- assert [row["request_slot_id"] for row in evaluation.payload["degraded_request_slots"]] == [
- "slot_0",
- "slot_1",
- "slot_2",
- "slot_3",
- "slot_4",
- ]
- assert [row["floor_rekeyed_from_path"] for row in evaluation.payload["degraded_request_slots"]] == [
- "output.confirmation_number",
- "output.account_number",
- "output.start_date",
- "output.deposit_amount",
- "output.next_owner",
- ]
+ assert evaluation.required_paths == {"output"}
+ assert evaluation.payload["canonical_required_child_paths"] == ["output"]
+ assert evaluation.canonical_signature == workflow_update_module._output_contract_signature(
+ ctx=ctx, required_paths={"output"}
+ )
+ return evaluation
- def test_degraded_declaration_only_directive_arm_is_idempotent(self) -> None:
- ctx = _degraded_declaration_stamp_ctx()
+ def test_declaration_only_run_preflight_returns_root_family_guidance_and_accepts_exact_reauthor(self) -> None:
+ ctx = self._declaration_only_ctx()
workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
- first_yaml, _, first_applied = workflow_update_module._impose_output_contract_envelope_after_steering(
- ctx, workflow_yaml, []
+ first = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
+
+ assert first is not None and first["ok"] is False
+ assert first["data"]["contract_liveness"] == "absent"
+ assert first["data"]["canonical_required_child_paths"] == ["output"]
+ assert first["data"]["declaration_only_child_paths"] == ["output.blocker"]
+ assert first["data"]["reason_code"] == "value_bearing_output_required"
+ assert first["data"]["reject_reason"] == "value_bearing_output_required"
+ assert "output_contract_reason_code" not in first["data"]
+ assert first["data"]["value_bearing_convergence_directive"] == self._directive(
+ first["data"], paths=["output"], rung=1
+ )
+ assert first["data"]["satisfying_templates"]["return_skeleton"] == (
+ 'return {"output": {"blocker": None, **output_value}}'
+ )
+ assert first["data"]["satisfying_templates"]["extraction_schema"]["properties"]["output"]["properties"][
+ "blocker"
+ ] == {"type": ["string", "null"]}
+ assert "code_artifact_metadata" in first["error"]
+ assert "return skeleton" in first["error"]
+ assert ctx.output_contract_actuation_by_signature == {}
+ assert ctx.output_contract_pending_run_evidence == {}
+
+ templates = first["data"]["satisfying_templates"]
+ reauthored_code = (
+ 'output_value = {"status": await page.locator("#status").text_content()}\n' + templates["return_skeleton"]
+ )
+ reauthored_yaml = _collapsed_spine_yaml(reauthored_code)
+ ctx.output_contract_bail_actuated_this_call = False
+
+ assert (
+ workflow_update_module._metadata_contract_run_preflight_reject(
+ ctx,
+ reauthored_yaml,
+ [templates["code_artifact_metadata"]],
+ )
+ is None
)
- second_yaml, _, second_applied = workflow_update_module._impose_output_contract_envelope_after_steering(
- ctx, first_yaml, []
+ assert ctx.output_contract_actuation_by_signature == {}
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
+ assert (
+ workflow_update_module.output_contract_value_bearing_run_reject(
+ ctx,
+ {"extract_record": reauthored_code},
+ )
+ is None
)
- assert first_applied is False
- assert second_applied is False
- assert first_yaml == workflow_yaml
- assert second_yaml == workflow_yaml
- assert len(ctx.output_contract_armed_directive_fingerprint_by_signature) == 1
+ def test_degraded_empty_run_preflight_returns_root_family_guidance(self) -> None:
+ ctx = self._degraded_ctx("output.confirmation_number", "output.account_number")
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
- def test_second_run_request_slot_producer_failure_rejects_blocker_only_return(self) -> None:
- requested_paths = (
- "output.confirmation_number",
- "output.account_number",
- "output.start_date",
- "output.deposit_amount",
- "output.next_owner",
- )
- ctx = _code_only_ctx()
- ctx.turn_id = "t-request-slot-producer-failure"
- ctx.scout_trajectory = []
- ctx.request_policy = request_policy_module._classification_from_raw(
- {
- "completion_criteria": [
- {
- "outcome": f"The returned record includes {path}.",
- "output_path": path,
- "request_slot_source_id": "latest_request",
- "request_slot_source_quote": path,
- }
- for path in requested_paths
- ]
- },
- request_slot_failure_kind="invalid_output",
+ result = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
+
+ assert result is not None and result["ok"] is False
+ assert result["data"]["contract_liveness"] == "degraded_empty"
+ assert result["data"]["canonical_required_child_paths"] == ["output"]
+ assert result["data"]["reason_code"] == "value_bearing_output_required"
+ assert result["data"]["reject_reason"] == "value_bearing_output_required"
+ assert "output_contract_reason_code" not in result["data"]
+ assert result["data"]["value_bearing_convergence_directive"] == self._directive(
+ result["data"], paths=["output"], rung=1
)
- workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
+ assert "code_artifact_metadata" in result["error"]
+ assert "return skeleton" in result["error"]
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
+
+ @pytest.mark.parametrize(
+ "code",
+ [
+ 'runtime_value = await collect()\nreturn {"output": runtime_value}',
+ 'runtime_value = await collect()\npayload = {"output": runtime_value}\nalias = payload\nreturn alias',
+ ],
+ )
+ def test_root_only_runtime_envelopes_exit_value_bearing_liveness(self, code: str) -> None:
+ ctx = self._degraded_ctx("output.confirmation_number")
+ workflow_yaml = _collapsed_spine_yaml(code)
+ metadata = [
+ workflow_update_module._metadata_contract_template(
+ block_label="extract_record",
+ required_paths={"output"},
+ source="requested_output_contract",
+ reason_code="requested_output_contract_missing_output_coverage",
+ declaration_paths=set(),
+ )
+ ]
evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
ctx,
workflow_yaml,
- [],
- allow_static_return_advisory=True,
+ metadata,
enforce_value_bearing_liveness=True,
)
- preflight = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, [])
- assert ctx.request_policy.request_slot_failure_kind == "invalid_output"
- assert all(criterion.output_path is None for criterion in ctx.request_policy.completion_criteria)
- assert all(criterion.mint_disposition == "degraded" for criterion in ctx.request_policy.completion_criteria)
assert evaluation is not None
- assert evaluation.payload["contract_liveness"] == "degraded_empty"
- assert evaluation.payload["reason_code"] == "value_bearing_output_required"
- assert evaluation.can_attempt_run is False
- assert [row["floor_rekeyed_from_path"] for row in evaluation.payload["degraded_request_slots"]] == sorted(
- requested_paths
- )
- assert {row["request_slot_failure_kind"] for row in evaluation.payload["degraded_request_slots"]} == {
- "invalid_output"
- }
- assert preflight is not None
- assert preflight["data"]["output_contract_reason_code"] == "value_bearing_output_required"
+ assert "value_bearing_output_required" not in evaluation.shape_violations
+ assert evaluation.payload["reason_code"] == "output_contract_required"
+ assert workflow_update_module.output_contract_value_bearing_run_reject(ctx, {"extract_record": code}) is None
@pytest.mark.asyncio
- async def test_degraded_declaration_only_contract_never_persists_or_dispatches(
- self, monkeypatch: pytest.MonkeyPatch
- ) -> None:
- ctx = _degraded_declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
- persisted = False
- dispatched = False
-
- async def _unexpected_update(*_args: object, **_kwargs: object) -> dict[str, object]:
- nonlocal persisted
- persisted = True
- return {"ok": True}
+ async def test_native_reject_emits_full_sorted_guidance_on_both_rungs(self) -> None:
+ ctx = self._ctx()
+ workflow_yaml, metadata = self._workflow_and_metadata()
- async def _unexpected_dispatch(*_args: object, **_kwargs: object) -> dict[str, object]:
- nonlocal dispatched
- dispatched = True
- return {"ok": True}
+ with capture_logs() as first_logs:
+ first = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": metadata},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
+ with capture_logs() as second_logs:
+ second = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": metadata},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
- monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
- monkeypatch.setattr(tools_module, "_update_workflow", _unexpected_update)
- monkeypatch.setattr(tools_module, "_run_blocks_and_collect_debug", _unexpected_dispatch)
+ assert first["ok"] is False
+ assert first["data"]["value_bearing_convergence_directive"] == self._directive(
+ first["data"],
+ paths=["output.account_number", "output.blocker", "output.record_id"],
+ rung=1,
+ )
+ assert "metadata_convergence_directive" not in first["data"]
+ assert second["data"]["value_bearing_convergence_directive"] == self._directive(
+ first["data"],
+ paths=["output.account_number", "output.blocker", "output.record_id"],
+ rung=2,
+ )
+ first_emits = [log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ second_emits = [log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(first_emits) == 1
+ assert first_emits[0]["directive_family"] == "value_bearing_output_required"
+ assert first_emits[0]["block_label"] == "extract_record"
+ assert first_emits[0]["canonical_output_contract_signature"]
+ assert first_emits[0]["rung"] == 1
+ assert len(second_emits) == 1
+ assert second_emits[0]["directive_family"] == "value_bearing_output_required"
+ assert second_emits[0]["rung"] == 2
+ assert ctx.output_contract_actuation_by_signature == {}
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.output_contract_actuation_count_by_signature == {}
+ assert ctx.output_contract_declick_attempted_by_signature == {}
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
+ assert ctx.workflow_yaml == ""
- result = await tools_module.update_and_run_blocks_tool.on_invoke_tool(
- SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
- json.dumps({"workflow_yaml": workflow_yaml, "block_labels": ["extract_entry_output"]}),
+ @pytest.mark.asyncio
+ async def test_identical_guidance_escalates_across_candidate_changes_and_logs_both_fingerprints(self) -> None:
+ ctx = self._ctx()
+ first_workflow, metadata = self._workflow_and_metadata()
+ second_workflow = _collapsed_spine_yaml(
+ 'return {"output": {"record_id": None, "account_number": None, "unused": None, "blocker": None}}'
)
- parsed = json.loads(result)
- assert parsed["ok"] is False
- assert parsed["data"]["reason_code"] == "metadata_contract_required_before_run"
- assert parsed["data"]["output_contract_reason_code"] == "value_bearing_output_required"
- assert parsed["data"]["contract_liveness"] == "degraded_empty"
- assert persisted is False
- assert dispatched is False
+ with capture_logs() as first_logs:
+ first = await _update_workflow(
+ {"workflow_yaml": first_workflow, "code_artifact_metadata": metadata},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
+ with capture_logs() as second_logs:
+ second = await _update_workflow(
+ {"workflow_yaml": second_workflow, "code_artifact_metadata": metadata},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
- def test_mixed_value_and_declaration_return_remains_valid(self) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml(
- 'record_id = await page.locator("#record-id").text_content()\nreturn {"output": {"record_id": record_id}}'
+ first_directive = first["data"]["value_bearing_convergence_directive"]
+ second_directive = second["data"]["value_bearing_convergence_directive"]
+ assert first_directive == self._directive(
+ first["data"], paths=["output.account_number", "output.blocker", "output.record_id"], rung=1
)
-
- formed_yaml, metadata, applied = workflow_update_module._impose_output_contract_envelope_after_steering(
- ctx, workflow_yaml, []
+ assert second_directive == self._directive(
+ second["data"], paths=["output.account_number", "output.blocker", "output.record_id"], rung=2
)
- evaluation = workflow_update_module._evaluate_output_contract_for_code_block(ctx, formed_yaml, metadata)
+ first_emit = next(log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT)
+ second_emit = next(log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT)
+ assert first_emit["guidance_fingerprint"] == second_emit["guidance_fingerprint"]
+ assert first_emit["candidate_fingerprint"] != second_emit["candidate_fingerprint"]
- assert applied is True
- assert evaluation is not None
- assert evaluation.has_deficiencies is False
- code = str(workflow_blocks(parse_workflow_yaml(formed_yaml))[0].get("code") or "")
- assert '"record_id": record_id' in code
- assert '"blocker": None' in code
+ @pytest.mark.asyncio
+ async def test_emitted_directive_clears_stale_author_time_rendering_but_preserves_history(self) -> None:
+ ctx = self._ctx()
+ workflow_yaml, metadata = self._workflow_and_metadata()
+ record_build_test_outcome(ctx, _author_time_reject_outcome("definition_contract_unsatisfied"))
+ history = list(ctx.recorded_build_test_outcome_history)
- def test_formation_does_not_create_declaration_only_scaffold(self) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml('await page.click("#submit")\nreturn {}')
+ result = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": metadata},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
- new_yaml, _metadata, applied = workflow_update_module._impose_output_contract_envelope_after_steering(
- ctx, workflow_yaml, []
+ assert result["data"]["value_bearing_convergence_directive"] == self._directive(
+ result["data"], paths=["output.account_number", "output.blocker", "output.record_id"], rung=1
)
+ assert ctx.latest_recorded_build_test_outcome is None
+ assert ctx.recorded_build_test_outcome_history == history
- assert applied is True
- assert new_yaml == workflow_yaml
- code = str(workflow_blocks(parse_workflow_yaml(new_yaml))[0].get("code") or "")
- assert "blocker" not in code
- evaluation = workflow_update_module._evaluate_output_contract_for_code_block(ctx, new_yaml, _metadata)
- assert evaluation is not None
- assert evaluation.can_attempt_run is False
+ @pytest.mark.asyncio
+ async def test_degraded_request_slots_emit_only_canonical_root_guidance(self) -> None:
+ ctx = self._degraded_ctx("output.confirmation_number", "output.account_number")
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
- def test_stamp_is_idempotent_across_calls(self) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml('await page.click("#submit")')
+ with capture_logs() as first_logs:
+ first = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
+ with capture_logs() as second_logs:
+ second = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
- first_yaml, _metadata, _applied = workflow_update_module._impose_output_contract_envelope_after_steering(
- ctx, workflow_yaml, []
+ assert first["ok"] is False
+ assert first["data"]["canonical_required_child_paths"] == ["output"]
+ assert "canonical_evaluation_paths" not in first["data"]
+ assert [row["floor_rekeyed_from_path"] for row in first["data"]["degraded_request_slots"]] == [
+ "output.confirmation_number",
+ "output.account_number",
+ ]
+ assert first["data"]["contract_liveness"] == "degraded_empty"
+ assert first["data"]["output_contract_reject_count"] == 1
+ assert first["data"]["value_bearing_convergence_directive"] == self._directive(
+ first["data"], paths=["output"], rung=1
+ )
+ assert first["data"]["output_contract_actuation"] == "structure_directive"
+ assert second["data"]["output_contract_reject_count"] == 2
+ assert second["data"]["value_bearing_convergence_directive"] == self._directive(
+ second["data"], paths=["output"], rung=2
+ )
+ assert second["data"]["output_contract_actuation"] == "structure_directive"
+ first_emits = [log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ second_emits = [log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(first_emits) == 1
+ assert len(second_emits) == 1
+ assert first_emits[0]["canonical_required_child_paths"] == ["output"]
+ assert second_emits[0]["canonical_required_child_paths"] == ["output"]
+ assert ctx.output_contract_actuation_by_signature == {}
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.output_contract_actuation_count_by_signature == {}
+ assert ctx.output_contract_declick_attempted_by_signature == {}
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
+ assert ctx.workflow_yaml == ""
+
+ @pytest.mark.asyncio
+ async def test_root_only_directives_reach_existing_budget_terminal(self) -> None:
+ ctx = self._degraded_ctx("output.confirmation_number", "output.account_number")
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
+ contract = workflow_update_module._output_contract_required_paths_source(ctx)
+ assert contract.union == set()
+ sentinel_signature = workflow_update_module._output_contract_signature(
+ ctx=ctx, required_paths={workflow_update_module._OUTPUT_CONTRACT_UNDECLARED_SENTINEL_PATH}
)
- again_yaml, _metadata2, _applied2 = workflow_update_module._impose_output_contract_envelope_after_steering(
- ctx, first_yaml, []
+ ctx.output_contract_reject_count_by_signature[sentinel_signature] = (
+ workflow_update_module._MAX_OUTPUT_CONTRACT_REJECTS - 1
+ )
+ ctx.output_contract_deferral_count_by_signature[sentinel_signature] = (
+ workflow_update_module._MAX_OUTPUT_CONTRACT_DEFERRALS - 1
)
- assert again_yaml == first_yaml
+ with capture_logs() as logs:
+ result = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
- def test_stamp_skips_without_single_owner_block(self) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _yaml(
- "title: Two blocks\n"
- "workflow_definition:\n"
- " blocks:\n"
- " - block_type: code\n"
- " label: first\n"
- " code: |\n"
- ' await page.click("#a")\n'
- " - block_type: code\n"
- " label: second\n"
- " code: |\n"
- ' await page.click("#b")\n'
+ assert result["data"]["reason_code"] == "output_contract_reject_budget_exhausted"
+ assert result["data"]["reject_reason"] == "output_contract_reject_budget_exhausted"
+ assert "value_bearing_convergence_directive" not in result["data"]
+ assert "output_contract_actuation" not in result["data"]
+ assert [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT] == []
+ assert ctx.turn_halt is not None
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "output_contract_reject_budget_exhausted"
+ assert (
+ ctx.output_contract_reject_count_by_signature[sentinel_signature]
+ == workflow_update_module._MAX_OUTPUT_CONTRACT_REJECTS
)
- new_yaml, _metadata, applied = workflow_update_module._impose_output_contract_envelope_after_steering(
- ctx, workflow_yaml, []
+ def test_live_blocker_budget_routes_to_root_guidance(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
+ evaluation = self._live_root_evaluation(ctx, workflow_yaml, [])
+ blocker_signature = workflow_update_module._output_contract_signature(
+ ctx=ctx, required_paths={"output.blocker"}
+ )
+ ctx.output_contract_reject_count_by_signature[blocker_signature] = (
+ workflow_update_module._MAX_OUTPUT_CONTRACT_REJECTS
+ )
+ ctx.output_contract_deferral_count_by_signature[blocker_signature] = (
+ workflow_update_module._MAX_OUTPUT_CONTRACT_DEFERRALS
)
- assert applied is False
- assert new_yaml == workflow_yaml
-
- def test_stamp_refused_for_statically_empty_observation_code(self) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml('return {"output": {"record_id": None}}')
- contract = workflow_update_module._output_contract_required_paths_source(ctx)
+ payload = workflow_update_module._record_output_contract_reject(
+ ctx,
+ evaluation,
+ summary="Value-bearing output is still required.",
+ workflow_yaml=workflow_yaml,
+ raw_metadata=[],
+ )
- stamped_yaml, applied = workflow_update_module._stamp_declaration_contract_defaults(
- ctx, workflow_yaml, [], contract, "sig-declaration-stamp"
+ root_signature = evaluation.canonical_signature
+ assert root_signature != blocker_signature
+ assert payload["canonical_required_child_paths"] == ["output"]
+ assert payload["declaration_only_child_paths"] == ["output.blocker"]
+ assert payload["value_bearing_convergence_directive"] == self._directive(payload, paths=["output"], rung=1)
+ assert payload["output_contract_reject_count"] == 1
+ assert payload["reason_code"] == "value_bearing_output_required"
+ assert ctx.output_contract_reject_count_by_signature[blocker_signature] == (
+ workflow_update_module._MAX_OUTPUT_CONTRACT_REJECTS
)
+ assert ctx.output_contract_reject_count_by_signature[root_signature] == 1
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
- assert applied is False
- assert stamped_yaml == workflow_yaml
+ def test_emitted_directive_does_not_arm_recorded_outcome_grounding(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
+ evaluation = self._live_root_evaluation(ctx, workflow_yaml, [])
- def test_stamp_applies_for_runtime_populated_observation_code(self) -> None:
- ctx = _declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml(
- 'record_id = await page.inner_text("#record")\nreturn {"output": {"record_id": record_id}}'
+ first = workflow_update_module._record_output_contract_reject(
+ ctx,
+ evaluation,
+ summary="Value-bearing output is still required.",
+ workflow_yaml=workflow_yaml,
+ raw_metadata=[],
)
- contract = workflow_update_module._output_contract_required_paths_source(ctx)
- stamped_yaml, applied = workflow_update_module._stamp_declaration_contract_defaults(
- ctx, workflow_yaml, [], contract, "sig-declaration-stamp"
- )
+ assert first["value_bearing_convergence_directive"] == self._directive(first, paths=["output"], rung=1)
+ assert ctx.latest_recorded_build_test_outcome is None
- assert applied is True
- code = str(workflow_blocks(parse_workflow_yaml(stamped_yaml))[0].get("code") or "")
- assert '"blocker": None' in code
+ ctx.output_contract_bail_actuated_this_call = False
+ second = workflow_update_module._record_output_contract_reject(
+ ctx,
+ evaluation,
+ summary="Value-bearing output is still required.",
+ workflow_yaml=workflow_yaml,
+ raw_metadata=[],
+ )
+ assert second["value_bearing_convergence_directive"] == self._directive(first, paths=["output"], rung=2)
+ assert second["reason_code"] == "value_bearing_output_required"
+ assert ctx.latest_recorded_build_test_outcome is None
-def test_static_return_synthesis_refuses_statically_none_observation_local() -> None:
- code = "record_id = None"
+ @pytest.mark.asyncio
+ async def test_mixed_degraded_diagnostics_do_not_invent_child_guidance(self) -> None:
+ ctx = self._degraded_ctx("output.account_number", "output")
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
- keyed, violations = workflow_update_module._extraction_code_with_value_bearing_static_return(
- code, required_paths={"output.record_id"}, declaration_paths={"output.blocker"}
- )
+ result = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
- assert violations
- assert keyed == code
+ assert result["data"]["value_bearing_convergence_directive"] == self._directive(
+ result["data"], paths=["output"], rung=1
+ )
+ assert "output.account_number" not in result["data"]["canonical_required_child_paths"]
+ assert result["data"]["reason_code"] == "value_bearing_output_required"
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
+ @pytest.mark.asyncio
+ async def test_observation_paths_take_precedence_over_incomplete_degraded_diagnostics(self) -> None:
+ ctx = self._ctx()
+ ctx.request_policy.completion_criteria.append(
+ CompletionCriterion(
+ id="slot_incomplete",
+ outcome="The returned record includes an additional slot.",
+ output_path="output",
+ request_slot_id="slot_incomplete",
+ pinability="unpinnable",
+ mint_disposition="degraded",
+ mint_degrade="undecidable_judgment",
+ requested_output_floor_rekeyed=True,
+ floor_rekeyed_from_path="output",
+ )
+ )
+ workflow_yaml, metadata = self._workflow_and_metadata()
-def test_static_return_synthesis_accepts_runtime_populated_observation_local() -> None:
- code = 'record_id = await page.inner_text("#record")'
+ result = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": metadata},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
- keyed, violations = workflow_update_module._extraction_code_with_value_bearing_static_return(
- code, required_paths={"output.record_id"}, declaration_paths={"output.blocker"}
- )
+ assert result["data"]["value_bearing_convergence_directive"] == self._directive(
+ result["data"],
+ paths=["output.account_number", "output.blocker", "output.record_id"],
+ rung=1,
+ )
- assert violations == []
- assert {"output.record_id", "output.blocker"} <= workflow_update_module._code_block_produced_output_paths(keyed)
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("invalid_path", ["", "output"])
+ async def test_degraded_diagnostics_are_not_directive_path_authority(self, invalid_path: str) -> None:
+ ctx = self._degraded_ctx("output.account_number", invalid_path)
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
+ with capture_logs() as logs:
+ result = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ formation_prepared=True,
+ )
-def test_static_return_synthesis_refuses_covered_statically_empty_return() -> None:
- code = 'return {"output": {"record_id": None, "blocker": None}}'
+ assert result["ok"] is False
+ assert result["data"]["reason_code"] == "value_bearing_output_required"
+ assert result["data"]["output_contract_reject_count"] == 1
+ assert result["data"]["value_bearing_convergence_directive"] == self._directive(
+ result["data"], paths=["output"], rung=1
+ )
+ assert result["data"]["output_contract_actuation"] == "structure_directive"
+ emits = [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(emits) == 1
+ assert emits[0]["canonical_required_child_paths"] == ["output"]
+ assert ctx.output_contract_actuation_by_signature == {}
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
+ assert ctx.workflow_yaml == ""
- _, violations = workflow_update_module._extraction_code_with_value_bearing_static_return(
- code, required_paths={"output.record_id"}, declaration_paths={"output.blocker"}
- )
+ @pytest.mark.asyncio
+ async def test_live_request_policy_evaluation_emits_root_guidance_without_invented_children(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
+ evaluation = self._live_root_evaluation(ctx, workflow_yaml, [])
- assert violations
+ with capture_logs() as logs:
+ result = workflow_update_module._record_output_contract_reject(
+ ctx,
+ evaluation,
+ summary="Value-bearing output is still required.",
+ workflow_yaml=workflow_yaml,
+ raw_metadata=[],
+ )
+ assert result["canonical_required_child_paths"] == ["output"]
+ assert "canonical_evaluation_paths" not in result
+ assert result["reason_code"] == "value_bearing_output_required"
+ assert result["value_bearing_convergence_directive"] == self._directive(result, paths=["output"], rung=1)
+ assert result["output_contract_actuation"] == "structure_directive"
+ emits = [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(emits) == 1
+ assert emits[0]["canonical_required_child_paths"] == ["output"]
+ assert ctx.output_contract_actuation_by_signature == {}
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
+ assert ctx.workflow_yaml == ""
-def test_value_bearing_lattice_unpack_after_empty_literal_is_fail_open() -> None:
- code = 'extra = await collect()\nreturn {"output": {"record_id": None, **extra}}'
+ @pytest.mark.asyncio
+ async def test_live_request_policy_native_preflight_emits_evaluator_root_guidance(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
+ submitted_metadata = [
+ {
+ "artifact_id": "code_artifact:extract_record",
+ "block_label": "extract_record",
+ "claimed_outcomes": [
+ {
+ "goal_value_paths": [
+ "confirmation_number",
+ "account_number",
+ "selected_start_date",
+ "deposit_amount",
+ "next_owner",
+ ],
+ "extraction_schema": json.dumps(
+ {
+ "type": "object",
+ "properties": {
+ "confirmation_number": {"type": "string"},
+ "account_number": {"type": "string"},
+ },
+ }
+ ),
+ }
+ ],
+ }
+ ]
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
+ with capture_logs() as logs:
+ result = await _update_workflow(
+ {"workflow_yaml": workflow_yaml, "code_artifact_metadata": submitted_metadata},
+ ctx,
+ allow_missing_credentials=True,
+ )
+ assert result["data"]["canonical_required_child_paths"] == ["output"]
+ assert result["data"]["value_bearing_convergence_directive"] == self._directive(
+ result["data"], paths=["output"], rung=1
+ )
+ emits = [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(emits) == 1
+ assert emits[0]["canonical_required_child_paths"] == ["output"]
+ assert emits[0]["rung"] == 1
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
-def test_value_bearing_lattice_top_level_unpack_after_output_key_is_fail_open() -> None:
- code = 'extra = await collect()\nreturn {"output": {"record_id": None}, **extra}'
+ def test_p8_bare_dynamic_return_emits_evaluator_root_guidance_on_both_rungs(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ workflow_yaml = _collapsed_spine_yaml(
+ 'rows = await page.locator("[data-testid=quickconnect-row]").all_text_contents()\nreturn rows'
+ )
+ metadata = [
+ workflow_update_module._metadata_contract_template(
+ block_label="extract_record",
+ required_paths={"output.confirmation_number"},
+ source="requested_output_contract",
+ reason_code="requested_output_contract_missing_output_coverage",
+ declaration_paths=set(),
+ )
+ ]
+ submitted_bytes = json.dumps(metadata, sort_keys=True)
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
+ with capture_logs() as first_logs:
+ first = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, metadata)
+ ctx.output_contract_bail_actuated_this_call = False
+ with capture_logs() as second_logs:
+ second = workflow_update_module._metadata_contract_run_preflight_reject(ctx, workflow_yaml, metadata)
+ assert first is not None
+ assert second is not None
+ assert first["data"]["reason_code"] == "value_bearing_output_required"
+ assert second["data"]["reason_code"] == "value_bearing_output_required"
+ assert first["data"]["canonical_required_child_paths"] == ["output"]
+ assert first["data"]["value_bearing_convergence_directive"] == self._directive(
+ first["data"], paths=["output"], rung=1
+ )
+ assert second["data"]["value_bearing_convergence_directive"] == self._directive(
+ first["data"], paths=["output"], rung=2
+ )
+ first_prearms = [
+ log for log in first_logs if log["event"] == "copilot_output_contract_value_bearing_directive_emitted"
+ ]
+ second_prearms = [
+ log for log in second_logs if log["event"] == "copilot_output_contract_value_bearing_directive_emitted"
+ ]
+ first_emits = [log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ second_emits = [log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert first_prearms == []
+ assert second_prearms == []
+ assert len(first_emits) == 1
+ assert len(second_emits) == 1
+ assert first_emits[0]["rung"] == 1
+ assert second_emits[0]["rung"] == 2
+ assert json.dumps(metadata, sort_keys=True) == submitted_bytes
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
-def test_value_bearing_lattice_empty_literal_after_unpack_stays_refused() -> None:
- code = 'extra = await collect()\nreturn {"output": {**extra, "record_id": None}}'
+ @pytest.mark.asyncio
+ async def test_p8_value_bearing_directive_preserves_recorded_outcome_grounding_route(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ ctx.request_policy.completion_criteria.append(
+ CompletionCriterion(
+ id="p8_reusable_inputs",
+ outcome=(
+ "The workflow uses business name, contact email, service address, and desired start date "
+ "as reusable inputs."
+ ),
+ level="definition",
+ output_path="workflow.parameters",
+ )
+ )
+ parameters_yaml = """
+ parameters:
+ - {parameter_type: workflow, key: business_name, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: contact_email, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: service_address, workflow_parameter_type: string}
+ - {parameter_type: workflow, key: desired_start_date, workflow_parameter_type: string}
+ """
+ directive_workflow = _yaml(
+ f"""
+ title: QuickConnect lookup
+ workflow_definition:
+{parameters_yaml}
+ blocks:
+ - block_type: code
+ label: extract_record
+ parameter_keys: [business_name, contact_email, service_address, desired_start_date]
+ code: |
+ rows = await page.locator("[data-testid=quickconnect-row]").all_text_contents()
+ reusable_inputs = (business_name, contact_email, service_address, desired_start_date)
+ return rows if all(reusable_inputs) else rows
+ """
+ )
+ definition_reject_workflow = _yaml(
+ f"""
+ title: QuickConnect lookup
+ workflow_definition:
+{parameters_yaml}
+ blocks:
+ - block_type: code
+ label: extract_record
+ parameter_keys: []
+ code: |
+ return {{"output": {{"confirmation_number": "QC-1042"}}}}
+ """
+ )
+ metadata = [
+ workflow_update_module._metadata_contract_template(
+ block_label="extract_record",
+ required_paths={"output.confirmation_number"},
+ source="requested_output_contract",
+ reason_code="requested_output_contract_missing_output_coverage",
+ declaration_paths=set(),
+ )
+ ]
+ tool_ctx = SimpleNamespace(context=ctx, tool_name="update_and_run_blocks")
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is True
+ def arguments(workflow_yaml: str) -> str:
+ return json.dumps(
+ {
+ "workflow_yaml": workflow_yaml,
+ "block_labels": ["extract_record"],
+ "code_artifact_metadata": metadata,
+ }
+ )
+ with capture_logs() as logs:
+ first = json.loads(
+ await tools_module.update_and_run_blocks_tool.on_invoke_tool(tool_ctx, arguments(directive_workflow))
+ )
+ second = json.loads(
+ await tools_module.update_and_run_blocks_tool.on_invoke_tool(tool_ctx, arguments(directive_workflow))
+ )
- "mutation",
- [
- "payload, extra = await split()",
- "*rest, payload = await split()",
- 'with open("audit.log") as payload:\n pass',
- "try:\n pass\nexcept ValueError as payload:\n pass",
- "if (payload := await build()):\n pass",
- 'payload["output"]["record_id"] = await fetch()',
- 'payload["output"].update(await fetch())',
- 'for item in await rows():\n payload["output"]["items"].append(item)',
- "populate(payload)",
- "payload.output = await fetch()",
- 'alias = payload\nalias["output"]["record_id"] = await fetch()',
- 'alias = payload\nalias["output"].update(await fetch())',
- 'inner = payload["output"]\ninner["record_id"] = await fetch()',
- "alias = payload\npopulate(alias)",
- "first = payload\nsecond = first\nsecond.output = await fetch()",
- ],
-)
-def test_value_bearing_lattice_mutated_literal_is_fail_open(mutation: str) -> None:
- code = f'payload = {{"output": {{"record_id": None}}}}\n{mutation}\nreturn payload'
+ assert first["data"]["value_bearing_convergence_directive"] == self._directive(
+ first["data"], paths=["output"], rung=1
+ )
+ assert second["data"]["value_bearing_convergence_directive"] == self._directive(
+ second["data"], paths=["output"], rung=2
+ )
+ assert ctx.latest_recorded_build_test_outcome is None
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
- assert workflow_update_module._statically_valueless_return_envelope(code) is False
+ for _ in range(2):
+ definition_reject = json.loads(
+ await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ tool_ctx,
+ arguments(definition_reject_workflow),
+ )
+ )
+ assert definition_reject["data"]["reason_code"] == "definition_contract_unsatisfied"
+ assert "value_bearing_convergence_directive" not in definition_reject["data"]
+
+ assert isinstance(ctx.latest_recorded_build_test_outcome, RecordedBuildTestOutcome)
+ assert ctx.latest_recorded_build_test_outcome.reason_code == "definition_contract_unsatisfied"
+ requirement = ctx.recorded_outcome_grounding_requirement
+ assert requirement is not None
+ assert requirement.phase == "author_time_reject"
+ assert requirement.reason_code == "definition_contract_unsatisfied"
+
+ grounding = json.loads(
+ await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ tool_ctx,
+ arguments(definition_reject_workflow),
+ )
+ )
+ assert grounding["ok"] is False
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "recorded_outcome_grounding_required"
+ emits = [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert [event["rung"] for event in emits] == [1, 2]
+ assert all(event["canonical_required_child_paths"] == ["output"] for event in emits)
+
+ def test_value_bearing_guidance_rejects_non_output_root(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ workflow_yaml = _collapsed_spine_yaml('return {"output": None}')
+ evaluation = self._live_root_evaluation(ctx, workflow_yaml, [])
+ payload = dict(evaluation.payload)
+ payload["canonical_required_child_paths"] = ["record_id"]
+
+ assert workflow_update_module._value_bearing_evaluation_guidance(replace(evaluation, payload=payload)) is None
+
+ def test_live_root_native_candidate_churn_preserves_metadata_bytes_and_escalates(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ first_workflow = _collapsed_spine_yaml('return {"output": None}')
+ second_workflow = _collapsed_spine_yaml('return {"output": None, "unused": None}')
+ metadata = [
+ workflow_update_module._metadata_contract_template(
+ block_label="extract_record",
+ required_paths={"output.confirmation_number"},
+ source="requested_output_contract",
+ reason_code="requested_output_contract_missing_output_coverage",
+ declaration_paths=set(),
+ )
+ ]
+ submitted_bytes = json.dumps(metadata, sort_keys=True)
+ first_evaluation = self._live_root_evaluation(ctx, first_workflow, metadata)
+ second_evaluation = self._live_root_evaluation(ctx, second_workflow, metadata)
-def test_value_bearing_lattice_unmutated_literal_stays_refused() -> None:
- code = 'payload = {"output": {"record_id": None}}\nother = await fetch()\nreturn payload'
+ with capture_logs() as logs:
+ first = workflow_update_module._record_output_contract_reject(
+ ctx,
+ first_evaluation,
+ summary="Value-bearing output is still required.",
+ workflow_yaml=first_workflow,
+ raw_metadata=metadata,
+ )
+ ctx.output_contract_bail_actuated_this_call = False
+ with capture_logs() as second_logs:
+ second = workflow_update_module._record_output_contract_reject(
+ ctx,
+ second_evaluation,
+ summary="Value-bearing output is still required.",
+ workflow_yaml=second_workflow,
+ raw_metadata=metadata,
+ )
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is True
- assert workflow_update_module._statically_valueless_return_envelope(code) is True
+ assert first["reason_code"] == "value_bearing_output_required"
+ assert second["reason_code"] == "value_bearing_output_required"
+ assert first["canonical_required_child_paths"] == ["output"]
+ assert first["value_bearing_convergence_directive"] == self._directive(first, paths=["output"], rung=1)
+ assert second["value_bearing_convergence_directive"] == self._directive(first, paths=["output"], rung=2)
+ assert "metadata_convergence_directive" not in first
+ assert "metadata_convergence_directive" not in second
+ assert json.dumps(metadata, sort_keys=True) == submitted_bytes
+ emits = [log for log in logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ second_emits = [log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT]
+ assert len(emits) == 1
+ assert len(second_emits) == 1
+ assert emits[0]["canonical_required_child_paths"] == ["output"]
+ assert emits[0]["guidance_fingerprint"] == second_emits[0]["guidance_fingerprint"]
+ assert emits[0]["candidate_fingerprint"] != second_emits[0]["candidate_fingerprint"]
+ @pytest.mark.asyncio
+ async def test_full_native_prearm_preserves_rung_across_candidate_churn(self) -> None:
+ ctx = self._live_root_request_policy_ctx()
+ first_workflow = _collapsed_spine_yaml('return {"output": None}')
+ second_workflow = _collapsed_spine_yaml('return {"output": None, "unused": None}')
-def test_value_bearing_lattice_unmutated_alias_stays_refused() -> None:
- code = 'payload = {"output": {"record_id": None}}\nalias = payload\nreturn payload'
+ with capture_logs() as first_logs:
+ first = await _update_workflow(
+ {"workflow_yaml": first_workflow, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ )
+ with capture_logs() as second_logs:
+ second = await _update_workflow(
+ {"workflow_yaml": second_workflow, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ )
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is True
- assert workflow_update_module._statically_valueless_return_envelope(code) is True
+ assert first["data"]["value_bearing_convergence_directive"] == self._directive(
+ first["data"], paths=["output"], rung=1
+ )
+ assert second["data"]["value_bearing_convergence_directive"] == self._directive(
+ second["data"], paths=["output"], rung=2
+ )
+ first_prearms = [
+ log for log in first_logs if log["event"] == "copilot_output_contract_value_bearing_directive_emitted"
+ ]
+ second_prearms = [
+ log for log in second_logs if log["event"] == "copilot_output_contract_value_bearing_directive_emitted"
+ ]
+ first_emit = next(log for log in first_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT)
+ second_emit = next(log for log in second_logs if log["event"] == _METADATA_LESS_DIRECTIVE_EVENT)
+ assert len(first_prearms) == 1
+ assert len(second_prearms) == 1
+ assert first_emit["guidance_fingerprint"] == second_emit["guidance_fingerprint"]
+ assert first_emit["candidate_fingerprint"] != second_emit["candidate_fingerprint"]
+ assert ctx.output_contract_armed_directive_fingerprint_by_signature == {
+ first["data"]["canonical_output_contract_signature"]: second_emit["guidance_fingerprint"]
+ }
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.turn_halt is None
+ assert ctx.blocker_signal is None
+ def test_changed_evaluation_guidance_resets_to_rung_one(self) -> None:
+ ctx = self._ctx()
+ workflow_yaml, metadata = self._workflow_and_metadata()
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ metadata,
+ enforce_value_bearing_liveness=True,
+ )
+ assert evaluation is not None
- "aliasing",
- [
- 'holder = {}\nholder["slot"] = payload',
- 'holder = {}\nholder["slot"] = payload\nholder["slot"]["output"]["record_id"] = await fetch()',
- 'holder = {}\nholder["slot"] = payload\nholder["slot"]["output"].update(await fetch())',
- 'holder = obj()\nholder.slot = payload\nholder.slot["output"]["record_id"] = await fetch()',
- ],
-)
-def test_value_bearing_lattice_alias_into_container_target_is_fail_open(aliasing: str) -> None:
- # Assigning payload into a subscript/attribute target aliases it, so a mutation through the
- # container could make the return value-bearing; the value name must taint (fail-open), not
- # resolve to its pre-alias empty literal.
- code = f'payload = {{"output": {{"record_id": None}}}}\n{aliasing}\nreturn payload'
+ first = workflow_update_module._record_output_contract_reject(
+ ctx,
+ evaluation,
+ summary="Value-bearing output is still required.",
+ workflow_yaml=workflow_yaml,
+ raw_metadata=metadata,
+ )
+ changed_templates = dict(evaluation.payload["satisfying_templates"])
+ changed_templates["return_skeleton"] = 'return {"output": {"record_id": refreshed_record_id}}'
+ changed_payload = dict(evaluation.payload)
+ changed_payload["satisfying_templates"] = changed_templates
+ ctx.output_contract_bail_actuated_this_call = False
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
- assert workflow_update_module._statically_valueless_return_envelope(code) is False
+ changed = workflow_update_module._record_output_contract_reject(
+ ctx,
+ replace(evaluation, payload=changed_payload),
+ summary="Value-bearing output is still required.",
+ workflow_yaml=workflow_yaml,
+ raw_metadata=metadata,
+ )
+ assert first["value_bearing_convergence_directive"]["rung"] == 1
+ assert changed["value_bearing_convergence_directive"] == self._directive(
+ changed_payload,
+ paths=["output.account_number", "output.blocker", "output.record_id"],
+ rung=1,
+ )
-def test_value_bearing_lattice_nul_byte_source_is_fail_open() -> None:
- code = 'return {"output": {"record_id": None}}\x00'
+ def test_value_bearing_prearm_and_metadata_family_state_do_not_escalate_first_rung(self) -> None:
+ workflow_yaml, metadata = self._workflow_and_metadata()
+ ctx = self._ctx()
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ metadata,
+ enforce_value_bearing_liveness=True,
+ )
+ assert evaluation is not None
+ signature = evaluation.canonical_signature
+ workflow_update_module._arm_output_contract_value_bearing_directive(
+ ctx,
+ signature=signature,
+ workflow_yaml=workflow_yaml,
+ liveness=workflow_update_module._OutputContractLiveness.DEGRADED_EMPTY,
+ )
+ ctx.output_contract_bail_actuated_this_call = False
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
- assert workflow_update_module._statically_valueless_return_envelope(code) is False
+ payload = workflow_update_module._record_output_contract_reject(
+ ctx,
+ evaluation,
+ summary="Value-bearing output is still required.",
+ authored_structural_fingerprint=workflow_update_module._output_contract_structural_fingerprint(
+ workflow_yaml, signature
+ ),
+ workflow_yaml=workflow_yaml,
+ raw_metadata=None,
+ )
+ assert payload["value_bearing_convergence_directive"]["rung"] == 1
+ assert "metadata_convergence_directive" not in payload
-def test_value_bearing_lattice_deep_alias_chain_is_fail_open() -> None:
- lines = ['v0 = {"output": {"record_id": None}}']
- lines.extend(f"v{index} = v{index - 1}" for index in range(1, 1500))
- lines.append("return v1499")
- code = "\n".join(lines)
+ baseline_ctx = _code_only_ctx()
+ baseline = workflow_update_module._adjudicate_metadata_reject_ladder(
+ baseline_ctx,
+ workflow_yaml=_metadata_less_output_yaml(),
+ raw_metadata=None,
+ missing_labels=["extract_provider"],
+ required_paths={"output.npi"},
+ )
+ crossed_ctx = _code_only_ctx()
+ crossed_signature = workflow_update_module._output_contract_signature(
+ ctx=crossed_ctx, required_paths={"output.npi"}
+ )
+ crossed_ctx.output_contract_armed_directive_fingerprint_by_signature[crossed_signature] = (
+ "value-bearing-family-fingerprint"
+ )
+ crossed = workflow_update_module._adjudicate_metadata_reject_ladder(
+ crossed_ctx,
+ workflow_yaml=_metadata_less_output_yaml(),
+ raw_metadata=None,
+ missing_labels=["extract_provider"],
+ required_paths={"output.npi"},
+ )
- assert workflow_update_module._statically_lacks_value_bearing_observation_paths(code, {"output.record_id"}) is False
- assert workflow_update_module._statically_valueless_return_envelope(code) is False
+ assert baseline == crossed
+ assert json.dumps(baseline, sort_keys=True) == json.dumps(crossed, sort_keys=True)
+ assert baseline is not None and baseline["rung"] == 1
+ def test_empty_signature_retains_fail_closed_reject_without_directive(self) -> None:
+ ctx = self._ctx()
+ workflow_yaml, metadata = self._workflow_and_metadata()
+ evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
+ ctx,
+ workflow_yaml,
+ metadata,
+ enforce_value_bearing_liveness=True,
+ )
+ assert evaluation is not None
+ evaluation = replace(evaluation, canonical_signature="")
-def test_canonical_output_contract_signature_is_single_keyed_under_degraded_slots() -> None:
- ctx = _degraded_declaration_stamp_ctx()
- workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
- evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
- ctx,
- workflow_yaml,
- [],
- allow_static_return_advisory=True,
- enforce_value_bearing_liveness=True,
- )
- assert evaluation is not None
- contract = workflow_update_module._output_contract_required_paths_source(ctx)
- signature = workflow_update_module._output_contract_signature(ctx=ctx, required_paths=contract.union)
+ payload = workflow_update_module._record_output_contract_reject(
+ ctx,
+ evaluation,
+ summary="Value-bearing output is still required.",
+ workflow_yaml=workflow_yaml,
+ raw_metadata=metadata,
+ )
- assert evaluation.canonical_signature == signature
- assert evaluation.payload["canonical_output_contract_signature"] == signature
- assert workflow_update_module._output_contract_pin_key(ctx, workflow_yaml, contract.union) == signature
- structural = workflow_update_module._output_contract_author_time_structural_payload(ctx, contract.union)
- assert structural is not None
- assert structural["canonical_output_contract_signature"] == signature
- workflow_update_module._record_output_contract_family_reject(
- ctx, contract.union, reject_family="value_bearing_output_required"
- )
- assert ctx.output_contract_reject_count_by_signature == {signature: 1}
- workflow_update_module._record_output_contract_deferral(ctx, contract.union)
- assert ctx.output_contract_deferral_count_by_signature == {signature: 1}
- identity_free = workflow_update_module._stable_output_contract_key(
- workflow_update_module._output_contract_scope_key(ctx), contract.union
- )
- assert signature != identity_free
+ assert payload["reason_code"] == "value_bearing_output_required"
+ assert "value_bearing_convergence_directive" not in payload
+ assert "output_contract_actuation" not in payload
+ assert ctx.output_contract_reject_count_by_signature
+ assert ctx.output_contract_armed_directive_fingerprint_by_signature == {}
def test_non_value_deficiency_keeps_granted_advisory_arming_at_preflight() -> None:
@@ -14980,7 +16791,7 @@ def test_non_value_deficiency_keeps_granted_advisory_arming_at_preflight() -> No
)
-def test_degraded_criteria_reject_steers_to_criteria_not_code_repair() -> None:
+def test_degraded_criteria_reject_steers_to_root_output_repair() -> None:
ctx = _degraded_declaration_stamp_ctx()
workflow_yaml = _collapsed_spine_yaml('return {"output": {"blocker": None}}')
evaluation = workflow_update_module._evaluate_output_contract_for_code_block(
@@ -14997,9 +16808,10 @@ def test_degraded_criteria_reject_steers_to_criteria_not_code_repair() -> None:
assert result["ok"] is False
assert result["data"]["reason_code"] == "value_bearing_output_required"
- assert "requested value-bearing output" in result["error"]
- assert "code_artifact_metadata" not in result["error"]
- assert "return skeleton" not in result["error"]
+ assert result["data"]["canonical_required_child_paths"] == ["output"]
+ assert result["data"]["declaration_only_child_paths"] == ["output.blocker"]
+ assert "code_artifact_metadata" in result["error"]
+ assert "return skeleton" in result["error"]
def test_hollow_code_under_live_contract_keeps_code_repair_steering() -> None:
@@ -15312,7 +17124,7 @@ class TestValueBearingDispatchPreflight:
assert reject is None
- def test_run_reject_degraded_criteria_message_names_criteria_side_cause(self) -> None:
+ def test_run_reject_degraded_criteria_message_names_root_output_repair(self) -> None:
ctx = _degraded_declaration_stamp_ctx()
reject = workflow_update_module.output_contract_value_bearing_run_reject(
@@ -15320,8 +17132,8 @@ class TestValueBearingDispatchPreflight:
)
assert reject is not None
- assert "requested value-bearing output" in reject["error"]
- assert "Revise the owning code block" not in reject["error"]
+ assert "non-empty top-level `output`" in reject["error"]
+ assert "Revise the owning code block" in reject["error"]
assert reject["data"]["reason_code"] == "value_bearing_output_required"
def test_run_reject_zero_criteria_message_never_references_a_contract(self) -> None:
@@ -20240,3 +22052,345 @@ class TestRecordedGauntletPacketReplay:
_wizard_block_yaml(include_business_block=True), ctx
)
assert result is None
+
+
+_P3_PACKET_FIXTURE = json.loads(
+ (Path(__file__).parent / "copilot" / "fixtures" / "p3_definition_contract_reject_packets.json").read_text()
+)
+_P3_PACKETS_BY_RUN = {run["run"]: run for run in _P3_PACKET_FIXTURE["runs"]}
+_P3_REPLAY_BINDINGS: dict[str, dict[str, tuple[str, str]]] = {
+ "run1": {
+ "account_number": ("#accountNumberFilter", "100245"),
+ "billing_start_date": ("#billingPeriodStart", "2026-05-01"),
+ "billing_end_date": ("#billingPeriodEnd", "2026-05-31"),
+ },
+ "run2": {
+ "account_number": ("#accountNumberFilter", "100245"),
+ "billing_period_start": ("#billingPeriodStart", "2026-05-01"),
+ "billing_period_end": ("#billingPeriodEnd", "2026-05-31"),
+ },
+ "run3": {
+ "account_number": ("#accountNumberFilter", "100245"),
+ "billing_start_date": ("#billingPeriodStart", "2026-05-01"),
+ "billing_end_date": ("#billingPeriodEnd", "2026-05-31"),
+ },
+}
+
+
+def _p3_definition_ctx() -> CopilotContext:
+ ctx = _code_only_ctx()
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ CompletionCriterion(
+ id="c0",
+ outcome="The workflow uses the account number and the billing period dates as reusable inputs.",
+ level="definition",
+ output_path="workflow.parameters",
+ )
+ ]
+ )
+ return ctx
+
+
+def _p3_recorded_clicks(packet: dict[str, Any]) -> list[dict[str, Any]]:
+ return [interaction for interaction in packet["scouted_interactions"] if interaction["tool_name"] == "click"]
+
+
+def _p3_draft_yaml(packet: dict[str, Any], declared_keys: Iterable[str]) -> str:
+ code = "".join(
+ f'await page.locator("{interaction["selector"]}").click()\n' for interaction in _p3_recorded_clicks(packet)
+ )
+ return yaml.safe_dump(
+ {
+ "title": "Download matching statement invoice",
+ "workflow_definition": {
+ "parameters": [
+ {"parameter_type": "workflow", "key": key, "workflow_parameter_type": "string"}
+ for key in sorted(declared_keys)
+ ],
+ "blocks": [
+ {
+ "block_type": "code",
+ "label": packet["block_labels"][0],
+ "parameter_keys": [],
+ "code": code,
+ }
+ ],
+ },
+ },
+ sort_keys=False,
+ )
+
+
+def _p3_scout_trajectory(packet: dict[str, Any]) -> list[dict[str, Any]]:
+ return [
+ {
+ "tool_name": interaction["tool_name"],
+ "selector": interaction["selector"],
+ "source_url": interaction["source_url"],
+ "trajectory_index": interaction["trajectory_index"],
+ }
+ for interaction in _p3_recorded_clicks(packet)
+ ]
+
+
+def _p3_composition_evidence(
+ packet: dict[str, Any],
+ bindings: dict[str, tuple[str, str]],
+ *,
+ extra_fields: list[dict[str, str]] | None = None,
+) -> dict[str, Any]:
+ clicks = _p3_recorded_clicks(packet)
+ return {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": clicks[0]["source_url"],
+ "forms": [
+ {
+ "fields": [{"selector": selector, "value": value} for selector, value in bindings.values()]
+ + (extra_fields or []),
+ "submit_controls": [{"selector": clicks[-1]["selector"]}],
+ }
+ ],
+ }
+
+
+def _recorded_summary_prefix(recorded_summary: str) -> str:
+ return recorded_summary[:-3] if recorded_summary.endswith("...") else recorded_summary
+
+
+class TestDefinitionContractRecordedPacketReplay:
+ @pytest.mark.parametrize("run_name", ["run1", "run2", "run3"])
+ def test_recorded_packets_reproduce_definition_plane_reject_byte_prefix(self, run_name: str) -> None:
+ packet = _P3_PACKETS_BY_RUN[run_name]
+ bindings = _P3_REPLAY_BINDINGS[run_name]
+ ctx = _p3_definition_ctx()
+ draft = _p3_draft_yaml(packet, bindings)
+
+ rejection = workflow_update_module._definition_plane_preflight_reject(ctx, draft)
+
+ assert rejection is not None
+ assert rejection.unreferenced_parameter_keys == tuple(sorted(bindings))
+ error = workflow_update_module._definition_plane_reject_error(rejection)
+ assert packet["reject_summaries"]
+ for summary in packet["reject_summaries"]:
+ assert ("Failed: " + error).startswith(_recorded_summary_prefix(summary["recorded_summary"]))
+ for stored in packet["stored_rejects"]:
+ assert stored["reason_code"] == "definition_contract_unsatisfied"
+ assert stored["verdict"] == "authoring_rejected"
+
+ def test_run1_recorded_reject_error_is_byte_identical_to_recorded_halt_keys(self) -> None:
+ packet = _P3_PACKETS_BY_RUN["run1"]
+ recorded_keys = packet["turn_halts"][0]["unresolved_parameter_keys"]
+ assert sorted(_P3_REPLAY_BINDINGS["run1"]) == recorded_keys
+ ctx = _p3_definition_ctx()
+ draft = _p3_draft_yaml(packet, recorded_keys)
+
+ rejection = workflow_update_module._definition_plane_preflight_reject(ctx, draft)
+
+ assert rejection is not None
+ assert workflow_update_module._definition_plane_reject_error(rejection) == (
+ "The submitted workflow declares reusable parameters that no block references: "
+ "`account_number`, `billing_end_date`, `billing_start_date`."
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("run_name", ["run1", "run2", "run3"])
+ async def test_recorded_packets_converge_next_attempt_into_bound_dataflow(
+ self, monkeypatch: pytest.MonkeyPatch, run_name: str
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ packet = _P3_PACKETS_BY_RUN[run_name]
+ bindings = _P3_REPLAY_BINDINGS[run_name]
+ values = {key: value for key, (_selector, value) in bindings.items()}
+ ctx = _p3_definition_ctx()
+ _enable_imposition(ctx)
+ draft = _p3_draft_yaml(packet, bindings)
+ for _ in range(2):
+ rejected = await _update_workflow({"workflow_yaml": draft}, ctx)
+ assert rejected["ok"] is False
+ assert rejected["data"]["reason_code"] == "definition_contract_unsatisfied"
+ for summary in packet["reject_summaries"]:
+ assert ("Failed: " + rejected["error"]).startswith(
+ _recorded_summary_prefix(summary["recorded_summary"])
+ )
+ assert arm_recorded_outcome_grounding_requirement(ctx) is not None
+ ctx.scout_trajectory = _p3_scout_trajectory(packet)
+ ctx.composition_page_evidence = _p3_composition_evidence(packet, bindings)
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
+
+ result = await _update_workflow(
+ {"workflow_yaml": draft, "parameters": values},
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert result["ok"] is True
+ parsed = parse_workflow_yaml(ctx.workflow_yaml)
+ block = _single_code_block(parsed)
+ assert block["parameter_keys"] == sorted(bindings)
+ code = str(block["code"])
+ terminal_selector = _p3_recorded_clicks(packet)[-1]["selector"]
+ terminal_call = f'page.locator("{terminal_selector}").click()'
+ for key, (selector, _value) in bindings.items():
+ fill = f'page.locator("{selector}").fill(str({key}))'
+ assert code.count(fill) == 1
+ assert code.index(fill) < code.index(terminal_call)
+ for interaction in _p3_recorded_clicks(packet):
+ assert f'page.locator("{interaction["selector"]}")' in code
+ authored = authored_selector_parameter_bindings(code, set(bindings))
+ assert authored is not None
+ for key, (selector, _value) in bindings.items():
+ assert key in authored.get(selector, set())
+ assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is None
+
+ @pytest.mark.asyncio
+ async def test_run1_recorded_packet_ambiguous_mapping_arms_value_free_directive_then_consumes(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ packet = _P3_PACKETS_BY_RUN["run1"]
+ bindings = _P3_REPLAY_BINDINGS["run1"]
+ values = {key: value for key, (_selector, value) in bindings.items()}
+ ctx = _p3_definition_ctx()
+ _enable_imposition(ctx)
+ monkeypatch.setattr(tools_module, "_request_policy_allows_update_and_skip_run", lambda *_args: False)
+ monkeypatch.setattr(tools_module, "_authority_tool_error", lambda *_args, **_kwargs: None)
+ draft = _p3_draft_yaml(packet, bindings)
+ ctx.scout_trajectory = _p3_scout_trajectory(packet)
+ ctx.composition_page_evidence = _p3_composition_evidence(
+ packet,
+ bindings,
+ extra_fields=[{"selector": "#scopeSearch", "value": values["account_number"]}],
+ )
+
+ first_result = json.loads(
+ await tools_module.update_and_run_blocks_tool.on_invoke_tool(
+ SimpleNamespace(context=ctx, tool_name="update_and_run_blocks"),
+ json.dumps(
+ {
+ "workflow_yaml": draft,
+ "block_labels": [packet["block_labels"][0]],
+ "parameters": values,
+ }
+ ),
+ )
+ )
+
+ assert first_result["ok"] is False
+ repair_context = ctx.last_code_authoring_repair_context
+ assert repair_context is not None
+ directive = repair_context.parameter_binding_directive
+ assert isinstance(directive, AuthoringParameterBindingDirective)
+ candidate_pairs = {(candidate.declared_key, candidate.field_selector) for candidate in directive.candidates}
+ assert candidate_pairs >= {
+ ("account_number", "#accountNumberFilter"),
+ ("account_number", "#scopeSearch"),
+ }
+ for value in values.values():
+ assert value not in str(directive)
+
+ fills = "".join(
+ f'await page.locator("{selector}").fill(str({key}))\n' for key, (selector, _value) in bindings.items()
+ )
+ clicks = "".join(
+ f'await page.locator("{interaction["selector"]}").click()\n' for interaction in _p3_recorded_clicks(packet)
+ )
+ authored_parsed = parse_workflow_yaml(draft)
+ authored_block = _single_code_block(authored_parsed)
+ authored_block["code"] = fills + clicks
+ authored_block["parameter_keys"] = sorted(bindings)
+ authored_yaml = yaml.safe_dump(authored_parsed, sort_keys=False)
+
+ with capture_logs() as logs:
+ second_result = await _update_workflow(
+ {"workflow_yaml": authored_yaml, "parameters": values},
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert second_result["ok"] is True
+ assert any(log["event"] == "copilot authoring parameter binding directive consumed" for log in logs)
+ final_block = _single_code_block(parse_workflow_yaml(ctx.workflow_yaml))
+ assert final_block["parameter_keys"] == sorted(bindings)
+ final_code = str(final_block["code"])
+ for key, (selector, _value) in bindings.items():
+ assert final_code.count(f'page.locator("{selector}").fill(str({key}))') == 1
+ assert workflow_update_module._definition_plane_preflight_reject(ctx, ctx.workflow_yaml) is None
+
+ @pytest.mark.asyncio
+ async def test_run1_recorded_halt_packet_negative_stays_byte_identical_without_targeting_fill(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _stub_successful_update(monkeypatch)
+ packet = _P3_PACKETS_BY_RUN["run1"]
+ bindings = _P3_REPLAY_BINDINGS["run1"]
+ values = {key: value for key, (_selector, value) in bindings.items()}
+ ctx = _p3_definition_ctx()
+ _enable_imposition(ctx)
+ draft = _p3_draft_yaml(packet, bindings)
+ for _ in range(2):
+ assert (await _update_workflow({"workflow_yaml": draft}, ctx))["ok"] is False
+ assert arm_recorded_outcome_grounding_requirement(ctx) is not None
+ ctx.blocker_signal = ctx.turn_halt = ctx.turn_ownership = None
+ ctx.scout_trajectory = _p3_scout_trajectory(packet)
+ ctx.composition_page_evidence = {
+ "source_tool": "inspect_page_for_composition",
+ "current_url": _p3_recorded_clicks(packet)[0]["source_url"],
+ "forms": [],
+ }
+ assert maybe_satisfy_recorded_outcome_grounding_requirement(ctx) is True
+
+ result = await _update_workflow(
+ {"workflow_yaml": draft, "parameters": values},
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert result["ok"] is False
+ halt_packet = packet["turn_halts"][0]
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.extra == {
+ "unresolved_parameter_keys": halt_packet["unresolved_parameter_keys"],
+ "grounding_unresolved": halt_packet["grounding_unresolved"],
+ }
+ assert ctx.blocker_signal.user_facing_reason == (
+ "I kept the workflow draft, but I could not safely connect the current page fields to these reusable "
+ "inputs: `account_number`, `billing_end_date`, `billing_start_date`. No workflow run was started."
+ )
+ assert ctx.turn_halt is not None
+ assert ctx.turn_halt.kind.value == "definition_contract_unsatisfied"
+
+ def test_definition_contract_blocker_signal_outputs_stay_byte_identical(self) -> None:
+ packet = _P3_PACKETS_BY_RUN["run1"]
+ recorded_keys = packet["turn_halts"][0]["unresolved_parameter_keys"]
+ shuffled_keys = list(reversed(recorded_keys))
+
+ grounding = build_definition_contract_unsatisfied_blocker_signal(
+ unresolved_parameter_keys=shuffled_keys,
+ grounding_unresolved=True,
+ )
+ assert grounding.user_facing_reason == (
+ "I kept the workflow draft, but I could not safely connect the current page fields to these reusable "
+ "inputs: `account_number`, `billing_end_date`, `billing_start_date`. No workflow run was started."
+ )
+ assert grounding.agent_steering_text == (
+ "The exact candidate failed its definition contract before execution. Preserve the draft, stop this "
+ "turn, and explain the unresolved reusable inputs without dispatching the candidate."
+ )
+ assert grounding.extra == {"unresolved_parameter_keys": recorded_keys, "grounding_unresolved": True}
+
+ unreferenced = build_definition_contract_unsatisfied_blocker_signal(
+ unresolved_parameter_keys=shuffled_keys,
+ )
+ assert unreferenced.user_facing_reason == (
+ "I kept the workflow draft, but it cannot run because these reusable inputs are not used: "
+ "`account_number`, `billing_end_date`, `billing_start_date`. Connect each input to the workflow "
+ "before trying again."
+ )
+ assert unreferenced.extra == {"unresolved_parameter_keys": recorded_keys, "grounding_unresolved": False}
+
+ keyless = build_definition_contract_unsatisfied_blocker_signal(unresolved_parameter_keys=[])
+ assert keyless.user_facing_reason == (
+ "I kept the workflow draft, but it does not yet satisfy the required workflow definition. "
+ "Complete the missing definition requirements before trying again."
+ )
diff --git a/tests/unit/test_copilot_code_block_synthesis.py b/tests/unit/test_copilot_code_block_synthesis.py
index a433243d0..981911220 100644
--- a/tests/unit/test_copilot_code_block_synthesis.py
+++ b/tests/unit/test_copilot_code_block_synthesis.py
@@ -17,6 +17,14 @@ from typing import Any
import pytest
+from skyvern.forge.sdk.copilot.authoring_parameter_binding import (
+ AuthoringParameterBindingCandidate,
+ AuthoringParameterFieldBinding,
+ AuthoringParameterTerminalBinding,
+ authoring_parameter_binding_directive_consumed,
+ build_authoring_parameter_binding_directive,
+ build_authoring_parameter_binding_snapshot,
+)
from skyvern.forge.sdk.copilot.code_block_preflight import preflight_code_block
from skyvern.forge.sdk.copilot.code_block_security import author_time_code_security_errors
from skyvern.forge.sdk.copilot.code_block_synthesis import (
@@ -201,6 +209,150 @@ def test_grounded_submit_rung_binding_fails_closed_on_invalid_bundle(mutation: s
assert synthesize_code_block(trajectory, strict_selectors=True) is None
+def test_authoring_parameter_snapshot_rebinds_captured_fill_without_duplicate() -> None:
+ trajectory = [
+ _interaction("type_text", selector="#location", source_url="https://example.com/form", trajectory_index=7),
+ _interaction("click", selector="#submit", source_url="https://example.com/form", trajectory_index=9),
+ ]
+ snapshot = build_authoring_parameter_binding_snapshot(
+ structural_key="definition-reject",
+ source_origin="https://example.com",
+ field_bindings=[
+ AuthoringParameterFieldBinding(
+ declared_key="search_location",
+ field_selector="#location",
+ field_trajectory_index=7,
+ match_basis="unique_ephemeral_value",
+ )
+ ],
+ terminal=AuthoringParameterTerminalBinding(
+ tool_name="click",
+ trajectory_index=9,
+ selector="#submit",
+ ),
+ )
+
+ result = synthesize_code_block(trajectory, strict_selectors=True, parameter_binding_snapshot=snapshot)
+
+ assert result is not None
+ fill = 'page.locator("#location").fill(str(search_location))'
+ assert result.code.count(fill) == 1
+ assert result.code.index(fill) < result.code.index('page.locator("#submit").click()')
+ assert result.parameters == [{"key": "search_location"}]
+ assert result.diagnostics.grounded_submit_binding_fingerprints == [snapshot.fingerprint]
+
+
+def test_authoring_parameter_snapshot_recovers_missing_fill_before_enter() -> None:
+ trajectory = [
+ _interaction(
+ "press_key",
+ selector="#location",
+ key="Enter",
+ source_url="https://example.com/form",
+ trajectory_index=0,
+ )
+ ]
+ snapshot = build_authoring_parameter_binding_snapshot(
+ structural_key="definition-reject",
+ source_origin="https://example.com",
+ field_bindings=[
+ AuthoringParameterFieldBinding(
+ declared_key="search_location",
+ field_selector="#location",
+ match_basis="unique_ephemeral_value",
+ )
+ ],
+ terminal=AuthoringParameterTerminalBinding(
+ tool_name="press_key",
+ trajectory_index=0,
+ selector="#location",
+ key="Enter",
+ ),
+ )
+
+ result = synthesize_code_block(trajectory, strict_selectors=True, parameter_binding_snapshot=snapshot)
+
+ assert result is not None
+ fill = 'page.locator("#location").fill(str(search_location))'
+ press = 'page.locator("#location").press("Enter")'
+ assert result.code.count(fill) == 1
+ assert result.code.index(fill) < result.code.index(press)
+ assert result.parameters == [{"key": "search_location"}]
+
+
+def test_authoring_parameter_directive_consumption_requires_structural_and_final_code_evidence() -> None:
+ snapshot = build_authoring_parameter_binding_snapshot(
+ structural_key="definition-reject",
+ source_origin="https://example.com",
+ field_bindings=[
+ AuthoringParameterFieldBinding(
+ declared_key="search_location",
+ field_selector="#location",
+ field_trajectory_index=0,
+ match_basis="exact_authored_selector",
+ )
+ ],
+ terminal=AuthoringParameterTerminalBinding(
+ tool_name="click",
+ trajectory_index=1,
+ selector="#submit",
+ ),
+ )
+ directive = build_authoring_parameter_binding_directive(
+ structural_key="definition-reject",
+ source_origin="https://example.com",
+ candidates=[
+ AuthoringParameterBindingCandidate(
+ declared_key="search_location",
+ field_selector="#location",
+ )
+ ],
+ )
+ code = 'await page.locator("#location").fill(str(search_location))'
+
+ assert authoring_parameter_binding_directive_consumed(
+ directive,
+ snapshot,
+ code=code,
+ parameter_keys=["search_location"],
+ )
+ assert not authoring_parameter_binding_directive_consumed(
+ directive.model_copy(update={"structural_key": "stale"}),
+ snapshot,
+ code=code,
+ parameter_keys=["search_location"],
+ )
+ assert not authoring_parameter_binding_directive_consumed(
+ directive,
+ snapshot,
+ code='await page.locator("#other").fill(str(search_location))',
+ parameter_keys=["search_location"],
+ )
+
+
+def test_authoring_parameter_snapshot_fails_closed_when_terminal_identity_changes() -> None:
+ trajectory = [_interaction("press_key", selector="#location", key="Tab", source_url="https://example.com/form")]
+ snapshot = build_authoring_parameter_binding_snapshot(
+ structural_key="definition-reject",
+ source_origin="https://example.com",
+ field_bindings=[
+ AuthoringParameterFieldBinding(
+ declared_key="search_location",
+ field_selector="#location",
+ match_basis="unique_ephemeral_value",
+ )
+ ],
+ terminal=AuthoringParameterTerminalBinding(
+ tool_name="press_key",
+ trajectory_index=0,
+ selector="#location",
+ key="Enter",
+ ),
+ )
+
+ assert synthesize_code_block(trajectory, strict_selectors=True, parameter_binding_snapshot=snapshot) is None
+
+
def _extraction_plan() -> RequestedOutputExtractionPlan:
return RequestedOutputExtractionPlan(
requested_output_paths=(
diff --git a/tests/unit/test_copilot_output_contract_actuation.py b/tests/unit/test_copilot_output_contract_actuation.py
index 884cb9a60..ed419fd9b 100644
--- a/tests/unit/test_copilot_output_contract_actuation.py
+++ b/tests/unit/test_copilot_output_contract_actuation.py
@@ -1165,6 +1165,44 @@ def test_steer_only_never_terminals_click_only_and_skips_declick() -> None:
assert second.reason_code != OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODE
+def test_value_bearing_reject_uses_steer_only_structure_directive() -> None:
+ signature = "sig_value_bearing_steer"
+ evaluation = _make_evaluation(
+ signature,
+ block_label="collect",
+ shape_violations=["value_bearing_output_required"],
+ )
+ non_steer_ctx = _ladder_ctx()
+
+ inert = wu._adjudicate_output_contract_ladder_after_reject(
+ non_steer_ctx,
+ evaluation,
+ workflow_yaml=_PAGE_READ_YAML,
+ current_fingerprint="value-bearing:fp",
+ )
+
+ assert inert is None
+ assert non_steer_ctx.output_contract_armed_directive_fingerprint_by_signature == {}
+
+ ctx = _ladder_ctx()
+ actuation = wu._adjudicate_output_contract_ladder_after_reject(
+ ctx,
+ evaluation,
+ workflow_yaml=_PAGE_READ_YAML,
+ current_fingerprint="value-bearing:fp",
+ steer_only=True,
+ )
+
+ assert actuation is not None
+ assert actuation.kind == OutputContractActuationKind.STRUCTURE_DIRECTIVE
+ assert ctx.output_contract_armed_directive_fingerprint_by_signature[signature] == "value-bearing:fp"
+ assert ctx.output_contract_actuation_by_signature == {}
+ assert ctx.output_contract_pending_run_evidence == {}
+ assert ctx.output_contract_actuation_count_by_signature == {}
+ assert ctx.output_contract_declick_attempted_by_signature == {}
+ assert ctx.turn_halt is None
+
+
def test_observed_required_values_exact_and_lineage_match() -> None:
ctx = SimpleNamespace(scouted_output_covered_paths={"output.order.id"}, composition_page_evidence=None)
assert wu._observed_required_output_values(ctx, {"output.order.id"}) is True
@@ -1783,6 +1821,25 @@ def test_contingent_antecedent_alone_forms_declaration_only_contract() -> None:
assert contract.union == {"output.blocker"}
+def test_blocker_family_path_is_declaration_only_for_authoring() -> None:
+ ctx = _antecedent_ctx(
+ CompletionCriterion(
+ id="c_blocker",
+ outcome="A blocker is reported when the site blocks submission.",
+ output_path="output.blocker",
+ antecedent_family="blocker",
+ ),
+ )
+
+ contract = wu._output_contract_required_paths_source(ctx)
+
+ assert contract.observation_paths == set()
+ assert contract.declaration_paths == {"output.blocker"}
+ assert contract.union == {"output.blocker"}
+ assert contract.liveness is wu._OutputContractLiveness.ABSENT
+ assert wu._value_bearing_directive_paths(contract) == {"output"}
+
+
def test_antecedent_overlapping_requested_output_stays_observation() -> None:
ctx = _antecedent_ctx(
CompletionCriterion(
@@ -2070,7 +2127,9 @@ def test_mint_degraded_output_path_leaves_observation_lane() -> None:
)
assert wu._requested_output_child_paths(ctx) == set()
- assert wu._output_contract_required_paths_source(ctx).union == set()
+ contract = wu._output_contract_required_paths_source(ctx)
+ assert contract.union == set()
+ assert contract.degraded_request_slots == ()
def test_face_c_degraded_mint_preserves_satisfiable_value_bearing_authoring_path() -> None: