Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-12000 Copilot: give each turn a single decision-owner so conflicting checks can't drop work (#7318)
Andrew Neilson0550b7959af1
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex 03f99e7b6..6dbc30bb1 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -177,6 +177,7 @@ from skyvern.forge.sdk.copilot.turn_halt import (CopilotTurnHalt,TurnHalt,TurnHaltKind,+ expire_output_contract_ladder_at_turn_end,raise_if_turn_halt,turn_halt_to_trace_data,)@@ -197,6 +198,7 @@ from skyvern.forge.sdk.copilot.turn_outcome import (derive_response_kind,with_copilot_code_mode_diagnostics,)+from skyvern.forge.sdk.copilot.turn_ownership import blocker_signal_render_allowedfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcomefrom skyvern.forge.sdk.schemas.persistent_browser_sessions import is_final_statusfrom skyvern.forge.sdk.schemas.workflow_copilot import (@@ -2120,6 +2122,7 @@ def _build_turn_halt_exit_result(# reframed reason must live there, not just in the local reply.if isinstance(ctx.blocker_signal, CopilotToolBlockerSignal):ctx.blocker_signal = ctx.blocker_signal.model_copy(update={"user_facing_reason": user_response})+ ctx.blocker_signal_claimant = Noneelif isinstance(signal, CopilotToolBlockerSignal):user_response = signal.user_facing_reasonelse:@@ -2524,6 +2527,8 @@ def _finalize_result_with_blocker_override(return resultif not local_signal.renders_final_reply:return result+ if not blocker_signal_render_allowed(ctx, local_signal):+ return resultif local_signal.internal_reason_code in _INVOLUNTARY_BLOCKER_REASON_CODES and outcome_fully_verified(ctx):preserved = _verified_terminal_preserve_result(ctx, result, exit_site=exit_site)if preserved is not None:@@ -3213,7 +3218,11 @@ async def _translate_to_agent_result(# Bind the signal to a local so the proposal-cascade gating below can't# desync from the inline override if ctx mutates mid-translate.local_blocker_signal = ctx.blocker_signal if isinstance(ctx.blocker_signal, CopilotToolBlockerSignal) else None- render_blocker_reply = local_blocker_signal is not None and local_blocker_signal.renders_final_reply+ render_blocker_reply = (+ local_blocker_signal is not None+ and local_blocker_signal.renders_final_reply+ and blocker_signal_render_allowed(ctx, local_blocker_signal)+ )blocker_active = render_blocker_replyif local_blocker_signal is not None and render_blocker_reply:# Override only user-visible text + resp_type so REPLACE_WORKFLOW and ASK_QUESTION gating skip the model's side-effect path; the shim is the sole renderer.@@ -4151,7 +4160,11 @@ def _build_output_policy_blocked_result(# steering-only blockers should still flow through normal output-policy# salvage so internal tool text is scrubbed and saved drafts can surface.local_blocker_signal = ctx.blocker_signal if isinstance(ctx.blocker_signal, CopilotToolBlockerSignal) else None- blocker_active = local_blocker_signal is not None and local_blocker_signal.renders_final_reply+ blocker_active = (+ local_blocker_signal is not None+ and local_blocker_signal.renders_final_reply+ and blocker_signal_render_allowed(ctx, local_blocker_signal)+ )preserved_workflow = (ctx.last_workflow if ctx.last_workflow is not None and ctx.last_workflow_yaml and not blocker_active else None)@@ -4321,6 +4334,31 @@ def _build_output_policy_blocked_result()+def _result_carries_terminal_outcome(result: AgentResult) -> bool:+ if result.cancelled or result.response_type == "ASK_QUESTION":+ return True+ return result.turn_outcome is not None and bool(result.turn_outcome.terminal_reason)+++def _reconcile_turn_end_ownership(+ ctx: CopilotContext | None, result: AgentResult, *, preserve_result: bool = False+) -> AgentResult:+ """Turn-end obligation: a GRANTED advisory signature always expires here, and only a silent+ non-terminal reply is replaced by the stalled terminal; its own try keeps a reconcile failure+ from masking the turn's real result."""+ if ctx is None:+ return result+ try:+ rewrite = not (preserve_result or _result_carries_terminal_outcome(result) or outcome_fully_verified(ctx))+ halt = expire_output_contract_ladder_at_turn_end(ctx, emit_stalled_terminal=rewrite)+ if halt is None:+ return result+ return _build_turn_halt_exit_result(ctx, result.global_llm_context, halt)+ except Exception:+ LOG.warning("copilot_turn_end_ownership_reconcile_failed", exc_info=True)+ return result++async def run_copilot_agent(stream: EventSourceStream,organization_id: str,@@ -4345,12 +4383,12 @@ async def run_copilot_agent(if turn_id is None:turn_id = uuid.uuid4().hexnormalized_turn_index = turn_index if turn_index is not None else 0+ ctx_sink: list[CopilotContext] = []try:# Initialize tracing before opening the turn span so Logfire's OTel provider# is installed; otherwise the very first turn lands the parent span on# OTel's no-op ProxyTracer when running locally with COPILOT_TRACING_ENABLED.ensure_tracing_initialized()- ctx_sink: list[CopilotContext] = []with _copilot_turn_span(chat_request=chat_request,chat_history=chat_history,@@ -4358,7 +4396,7 @@ async def run_copilot_agent(turn_id=turn_id,) as turn_span:try:- return await _run_copilot_turn_impl(+ result = await _run_copilot_turn_impl(stream=stream,organization_id=organization_id,chat_request=chat_request,@@ -4377,6 +4415,7 @@ async def run_copilot_agent(stored_completion_criteria=stored_completion_criteria,prior_turn_outcome=prior_turn_outcome,)+ return _reconcile_turn_end_ownership(ctx_sink[0] if ctx_sink else None, result)except Exception as exc:LOG.error("Copilot turn unhandled error",@@ -4399,7 +4438,10 @@ async def run_copilot_agent(turn_id=turn_id,turn_index=normalized_turn_index,)- return _build_unexpected_error_exit_result(ctx, global_llm_context, error=exc, span=turn_span)+ error_result = _build_unexpected_error_exit_result(ctx, global_llm_context, error=exc, span=turn_span)+ return _reconcile_turn_end_ownership(+ ctx_sink[0] if ctx_sink else None, error_result, preserve_result=True+ )finally:finalize_outcome_verification_trace(ctx_sink[0] if ctx_sink else None, turn_span)except Exception as exc:@@ -4423,7 +4465,8 @@ async def run_copilot_agent(turn_id=turn_id,turn_index=normalized_turn_index,)- return _build_unexpected_error_exit_result(ctx, global_llm_context, error=exc)+ error_result = _build_unexpected_error_exit_result(ctx, global_llm_context, error=exc)+ return _reconcile_turn_end_ownership(ctx_sink[0] if ctx_sink else None, error_result, preserve_result=True)async def _run_copilot_turn_impl(diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.pyindex f82e620b7..0fea9622e 100644--- a/skyvern/forge/sdk/copilot/blocker_signal.py+++ b/skyvern/forge/sdk/copilot/blocker_signal.py@@ -6,7 +6,7 @@ import refrom collections.abc import Iterable, Mappingfrom dataclasses import dataclassfrom types import MappingProxyType-from typing import Any, Literal, Protocol+from typing import TYPE_CHECKING, Any, Literal, Protocolimport structlogfrom pydantic import BaseModel, ConfigDict, Field, field_serializer, model_validator@@ -17,7 +17,10 @@ from skyvern.forge.sdk.copilot.output_contracts import (OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODE,)from skyvern.forge.sdk.copilot.result_evidence import LoadedResultCompositionEvidence-from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome+from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODE, RecordedRunOutcome++if TYPE_CHECKING:+ from skyvern.forge.sdk.copilot.turn_ownership import TurnClaimantBlockerKind = Literal["authority_denied",@@ -240,6 +243,9 @@ class _LoopEvidenceCtx(Protocol):class _BlockerSignalCtx(_LoopEvidenceCtx, Protocol):blocker_signal: CopilotToolBlockerSignal | None+ # Owned here at the stash choke-point: cleared whenever the held signal changes identity,+ # re-assigned only by an owned precedence claim in turn_ownership.+ blocker_signal_claimant: TurnClaimant | Nonelatest_tool_blocker_signal: CopilotToolBlockerSignal | Nonetool_blocker_signals: list[CopilotToolBlockerSignal]@@ -337,11 +343,34 @@ _ACTIVE_TERMINAL_REPLACEABLE_REASON_CODES = frozenset({"tool_error_per_tool_budg_TERMINAL_CHALLENGE_REPLACEABLE_REASON_CODES = frozenset({"tool_error_post_budget_challenge_result_evidence"})SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE = "tool_error_synthesized_block_persistence_required"UNCOVERED_OUTPUT_RESCOUT_STEER_REASON_CODE = "tool_error_uncovered_output_rescout_steer"-_RECORDED_OUTCOME_GROUNDING_REASON_CODE = "recorded_outcome_grounding_required"+RECORDED_OUTCOME_GROUNDING_REASON_CODE = "recorded_outcome_grounding_required"+SCHEMA_INCOMPATIBILITY_REASON_CODE = "schema_incompatibility"_OUTPUT_CONTRACT_TERMINAL_REASON_CODES = frozenset({OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODE, OUTPUT_CONTRACT_ACTUATION_EXHAUSTED_REASON_CODE})+# A held blocker whose reason code is in this set must win both the rendered reply and the typed+# halt kind over a later non-terminal trip (e.g. the code-authoring churn backstop).+GENUINELY_TERMINAL_BLOCKER_REASON_CODES: frozenset[str] = frozenset(+ {+ ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE,+ TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,+ "tool_error_run_output_terminal_blocker",+ "tool_error_post_budget_challenge_blocker",+ "tool_error_challenge_gated_submit_disabled",+ "probable_site_block_stop",+ SCHEMA_INCOMPATIBILITY_REASON_CODE,+ OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODE,+ OUTPUT_CONTRACT_ACTUATION_EXHAUSTED_REASON_CODE,+ "advisory_dispatch_stalled",+ "repair_ceiling_reached",+ }+)+++def blocker_signal_is_genuinely_terminal(signal: CopilotToolBlockerSignal | None) -> bool:+ return signal is not None and signal.internal_reason_code in GENUINELY_TERMINAL_BLOCKER_REASON_CODES+def _should_stash_over_existing(existing: CopilotToolBlockerSignal | None,@@ -365,13 +394,13 @@ def _should_stash_over_existing():return Trueif (- incoming.internal_reason_code == _RECORDED_OUTCOME_GROUNDING_REASON_CODE+ incoming.internal_reason_code == RECORDED_OUTCOME_GROUNDING_REASON_CODEand existing.blocker_kind == "tool_error"and not existing.renders_final_reply):return Trueif (- existing.internal_reason_code == _RECORDED_OUTCOME_GROUNDING_REASON_CODE+ existing.internal_reason_code == RECORDED_OUTCOME_GROUNDING_REASON_CODEand not existing.renders_final_replyand incoming.renders_final_reply):@@ -399,12 +428,14 @@ def maybe_clear_blocker_signal_on_tool_success(ctx: _BlockerSignalCtx, succeededsignal = getattr(ctx, "blocker_signal", None)if isinstance(signal, CopilotToolBlockerSignal) and _tool_success_clears_signal(signal, succeeded_tool_name):ctx.blocker_signal = None+ ctx.blocker_signal_claimant = Nonedef clear_blocker_signal_for_reason_codes(ctx: _BlockerSignalCtx, internal_reason_codes: frozenset[str]) -> None:signal = getattr(ctx, "blocker_signal", None)if isinstance(signal, CopilotToolBlockerSignal) and signal.internal_reason_code in internal_reason_codes:ctx.blocker_signal = None+ ctx.blocker_signal_claimant = Nonedef clear_tool_blocker_signals_for_reason_codes(ctx: _BlockerSignalCtx, internal_reason_codes: frozenset[str]) -> None:@@ -439,6 +470,7 @@ def stash_blocker_signal(ctx: _BlockerSignalCtx, signal: CopilotToolBlockerSignastashed = _should_stash_over_existing(existing, signal)if stashed:ctx.blocker_signal = signal+ ctx.blocker_signal_claimant = Noneextra: dict[str, Any] = {"stashed": stashed}if not stashed and isinstance(existing, CopilotToolBlockerSignal):extra["existing_reason_code"] = existing.internal_reason_code@@ -697,4 +729,5 @@ def refresh_held_loop_blocker_evidence(ctx: _BlockerSignalCtx) -> None:except ValueError:returnctx.blocker_signal = refreshed+ ctx.blocker_signal_claimant = NoneLOG.info("copilot loop blocker signal evidence refreshed", **to_trace_data(refreshed))diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.pyindex e84fc4184..69b8ee796 100644--- a/skyvern/forge/sdk/copilot/enforcement.py+++ b/skyvern/forge/sdk/copilot/enforcement.py@@ -128,7 +128,6 @@ from skyvern.forge.sdk.copilot.run_outcome import (from skyvern.forge.sdk.copilot.runtime import (AgentContext,AuthorTimeGateAblationPayload,- output_contract_ladder_unresolved,record_author_time_gate_ablation_event,)from skyvern.forge.sdk.copilot.screenshot_utils import ScreenshotEntry@@ -145,6 +144,13 @@ from skyvern.forge.sdk.copilot.turn_halt import (stash_turn_halt_from_blocker_signal,)from skyvern.forge.sdk.copilot.turn_intent import RequiredContextKey, TurnIntent, TurnIntentMode+from skyvern.forge.sdk.copilot.turn_ownership import (+ ClaimOutcome,+ TurnClaimant,+ claim_and_stash_blocker_signal,+ claim_turn,+ emit_blocker_signal_payload,+)from skyvern.utils.token_counter import count_tokensif TYPE_CHECKING:@@ -578,7 +584,8 @@ def _record_code_authoring_guardrail_reject(# halt kind, so the churn stop defers to it rather than overriding.if blocker_signal_is_genuinely_terminal(ctx.blocker_signal):return- if output_contract_ladder_unresolved(ctx):+ claimant = TurnClaimant.CREDENTIAL_PRIORITY_CHURN if defer_churn_stop else TurnClaimant.CODE_AUTHORING_CHURN+ if claim_and_stash_blocker_signal(ctx, claimant, signal, force_stash=True) is None:returntry:unresolved_obligation = _scouted_spine_open_obligation(ctx)@@ -587,8 +594,6 @@ def _record_code_authoring_guardrail_reject(unresolved_obligation = []if unresolved_obligation:_log_scouted_spine_unresolved(unresolved_obligation, site="churn_stop")- stash_blocker_signal(ctx, signal)- ctx.blocker_signal = signaldef no_forward_progress_interaction_stop_signal(ctx: Any) -> CopilotToolBlockerSignal:@@ -635,8 +640,7 @@ def register_no_progress_interaction_click(ctx: Any, *, outcome: str) -> None:if blocker_signal_is_genuinely_terminal(ctx.blocker_signal):returnsignal = no_forward_progress_interaction_stop_signal(ctx)- stash_blocker_signal(ctx, signal)- ctx.blocker_signal = signal+ claim_and_stash_blocker_signal(ctx, TurnClaimant.LOOP_DETECTED, signal, force_stash=True)def _needs_code_authoring_churn_halt(ctx: Any) -> bool:@@ -1717,12 +1721,12 @@ def _check_enforcement(if not getattr(ctx, "last_test_non_retriable_nav_error", None):churn_signal = _churn_signal_if_halting(ctx)if churn_signal is not None:- stash_blocker_signal(ctx, churn_signal)+ emit_blocker_signal_payload(ctx, churn_signal)stash_turn_halt_from_blocker_signal(ctx, churn_signal, source="enforcement_backstop")raise_if_turn_halt(ctx)if _needs_no_progress_interaction_halt(ctx):no_progress_signal = no_forward_progress_interaction_stop_signal(ctx)- stash_blocker_signal(ctx, no_progress_signal)+ emit_blocker_signal_payload(ctx, no_progress_signal)stash_turn_halt_from_blocker_signal(ctx, no_progress_signal, source="enforcement_backstop")raise_if_turn_halt(ctx)@@ -2837,6 +2841,9 @@ def uncovered_output_reject_scout_steer_signal(ctx: AgentContext, tool_name: strpayload=payload,):return None+ # Commit-after-claim: a yielded steer must not burn the one-shot rescout key.+ if claim_turn(ctx, TurnClaimant.UNCOVERED_OUTPUT_RESCOUT_STEER) is ClaimOutcome.YIELDED:+ return Nonectx.uncovered_output_rescout_steer_key = keynamed_paths = ", ".join(sorted(active))return CopilotToolBlockerSignal(@@ -2900,8 +2907,10 @@ def synthesized_block_persistence_signal(ctx: Any, tool_name: str) -> CopilotTooif _uncovered_output_reject_admits_evaluate(ctx, tool_name):return Noneif _credential_scout_reopen_admits_evaluate(ctx, tool_name):+ claim_turn(ctx, TurnClaimant.CREDENTIAL_SCOUT_REOPEN)return Noneif _actuation_obligation_admits_required_fill_tool(ctx, tool_name):+ claim_turn(ctx, TurnClaimant.ACTUATION_OBLIGATION_FILL)return Noneif (ambiguous_selector_rescout_state != "block"@@ -3014,6 +3023,10 @@ async def run_with_enforcement():force_synthesized_block_persistence = _should_force_synthesized_block_persistence(ctx)force_advisory_run_dispatch = _should_force_advisory_run_dispatch(ctx)+ # The advisory-dispatch force claims the actuation ladder itself (same-claimant), so the+ # grant-consumption path can never self-deadlock.+ if force_advisory_run_dispatch:+ claim_turn(ctx, TurnClaimant.OUTPUT_CONTRACT_ACTUATION)force_run_dispatch = force_synthesized_block_persistence or force_advisory_run_dispatchcurrent_runner_kwargs = (_runner_kwargs_with_forced_tool_choice(runner_kwargs, SYNTHESIZED_BLOCK_PERSISTENCE_TOOL)diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.pyindex 26129174c..f67b3f381 100644--- a/skyvern/forge/sdk/copilot/mcp_adapter.py+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py@@ -48,6 +48,7 @@ from skyvern.forge.sdk.copilot.runtime import (from skyvern.forge.sdk.copilot.screenshot_utils import enqueue_screenshot_from_resultfrom skyvern.forge.sdk.copilot.secret_scrub import scrub_secrets_from_structurefrom skyvern.forge.sdk.copilot.turn_halt import stash_turn_halt_from_blocker_signal+from skyvern.forge.sdk.copilot.turn_ownership import emit_blocker_signal_payloadPreHook = Callable[[dict[str, Any], AgentContext], Awaitable[dict[str, Any] | None]]PostHook = Callable[[dict[str, Any], dict[str, Any], AgentContext], Awaitable[dict[str, Any]]]@@ -139,7 +140,7 @@ _CURRENT_PAGE_TERMINAL_CHALLENGE_MCP_TOOLS = frozenset(def _stash_and_emit_loop_blocker(ctx: Any, loop_message: str, tool_name: str) -> str:signal = build_loop_blocker_signal(loop_message, tool_name=tool_name, evidence=loop_blocker_evidence_from_ctx(ctx))- payload = stash_blocker_signal(ctx, signal)+ payload = emit_blocker_signal_payload(ctx, signal)stash_turn_halt_from_blocker_signal(ctx, signal, source="mcp_loop_blocker")return payload@@ -152,7 +153,7 @@ def _stash_and_emit_current_page_terminal_challenge_blocker(ctx: Any, tool_name:)if signal is None:return None- payload = stash_blocker_signal(ctx, signal)+ payload = emit_blocker_signal_payload(ctx, signal)stash_turn_halt_from_blocker_signal(ctx, signal, source="mcp_current_page_terminal_challenge")return payload@@ -335,7 +336,7 @@ class SkyvernOverlayMCPServer(MCPServer):None,),)- payload = stash_blocker_signal(copilot_ctx, persistence_signal)+ payload = emit_blocker_signal_payload(copilot_ctx, persistence_signal)result = {"ok": False, "error": payload}record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, result)return _copilot_to_call_tool_result(result)diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 0d89e4583..183d17fc0 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -61,6 +61,7 @@ if TYPE_CHECKING:from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcomefrom skyvern.forge.sdk.copilot.schema_incompatibility import SchemaIncompatibilityfrom skyvern.forge.sdk.copilot.turn_halt import TurnHalt+ from skyvern.forge.sdk.copilot.turn_ownership import GatePrecedenceConflictEvent, TurnClaimant, TurnOwnershipfrom skyvern.forge.sdk.routes.event_source_stream import EventSourceStreamfrom skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession@@ -490,6 +491,13 @@ class AgentContext:# Surfaced into the persisted TurnOutcome so a later turn can report it.latest_schema_incompatibility: SchemaIncompatibility | None = Noneauthor_time_gate_ablation_events: list[AuthorTimeGateAblationEvent] = field(default_factory=list)+ # Single-owner turn-precedence contract. One mechanism owns a turn's steering+ # at a time; a contradicting weaker claim is recorded here and yields.+ turn_ownership: TurnOwnership | None = None+ gate_precedence_conflict_events: list[GatePrecedenceConflictEvent] = field(default_factory=list)+ # Claimant whose owned claim stashed the current blocker_signal; the stash choke-point clears+ # it whenever the held signal changes identity, so a plain stash can never alias a stale owner.+ blocker_signal_claimant: TurnClaimant | None = Nonedef copilot_author_time_gate_log_only_enabled() -> bool:diff --git a/skyvern/forge/sdk/copilot/schema_incompatibility.py b/skyvern/forge/sdk/copilot/schema_incompatibility.pyindex aaa8143ba..ff70d9eab 100644--- a/skyvern/forge/sdk/copilot/schema_incompatibility.py+++ b/skyvern/forge/sdk/copilot/schema_incompatibility.py@@ -16,12 +16,14 @@ from typing import Anyfrom pydantic import BaseModel, ConfigDict, Field+from skyvern.forge.sdk.copilot.blocker_signal import (+ SCHEMA_INCOMPATIBILITY_REASON_CODE as SCHEMA_INCOMPATIBILITY_REASON_CODE,+)from skyvern.forge.sdk.copilot.blocker_signal import (CopilotToolBlockerSignal,assert_clean_user_facing_text,)-SCHEMA_INCOMPATIBILITY_REASON_CODE = "schema_incompatibility"SCHEMA_INCOMPATIBILITY_FAILURE_TYPE = "schema_incompatibility"SCHEMA_INCOMPATIBILITY_BLOCKED_TOOL = "update_and_run_blocks"diff --git a/skyvern/forge/sdk/copilot/tools/_shared.py b/skyvern/forge/sdk/copilot/tools/_shared.pyindex ecd754ef9..2b16ce82c 100644--- a/skyvern/forge/sdk/copilot/tools/_shared.py+++ b/skyvern/forge/sdk/copilot/tools/_shared.py@@ -11,7 +11,7 @@ import structlogimport yamlfrom skyvern.forge import app-from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, stash_blocker_signal+from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.composition_browser_expressions import (COMPOSITION_STRIPPED_HTML_EXPRESSION as _COMPOSITION_STRIPPED_HTML_EXPRESSION,)@@ -30,6 +30,7 @@ from skyvern.forge.sdk.copilot.enforcement import TOTAL_TIMEOUT_SECONDSfrom skyvern.forge.sdk.copilot.runtime import AgentContextfrom skyvern.forge.sdk.copilot.tracing_setup import copilot_spanfrom skyvern.forge.sdk.copilot.turn_halt import stash_turn_halt_from_blocker_signal+from skyvern.forge.sdk.copilot.turn_ownership import emit_blocker_signal_payloadfrom skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidencefrom skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, Block, TaskV2Blockfrom skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus@@ -320,7 +321,7 @@ def _same_page_ignoring_fragment(left: str | None, right: str | None) -> bool:def _emit_tool_blocker_signal(ctx: AgentContext, signal: CopilotToolBlockerSignal) -> str:- payload = stash_blocker_signal(ctx, signal)+ payload = emit_blocker_signal_payload(ctx, signal)stash_turn_halt_from_blocker_signal(ctx, signal, source="tool_blocker_signal")return payloaddiff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex 803a5fcac..0ea892c53 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -158,6 +158,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_ownership import TurnClaimant, claim_turn, current_turn_ownerfrom skyvern.forge.sdk.copilot.workflow_credential_utils import (credential_param_ids,parse_workflow_yaml,@@ -3455,6 +3456,7 @@ def _grant_output_contract_advisory_run(ctx: AgentContext, signature: str) -> Noif _output_contract_advisory_state(ctx, signature) == OutputContractAdvisoryState.GRANTED:returnctx.output_contract_actuation_by_signature[signature] = OutputContractAdvisoryState.GRANTED+ claim_turn(ctx, TurnClaimant.OUTPUT_CONTRACT_ACTUATION)LOG.info("copilot_output_contract_advisory_run_granted",canonical_output_contract_signature=signature,@@ -4084,6 +4086,30 @@ def _impose_output_contract_envelope_after_steering(return workflow_yaml, scaffolded_metadata, applied or declaration_stamped+def _has_granted_output_contract_advisory_run(ctx: AgentContext) -> bool:+ return any(+ state == OutputContractAdvisoryState.GRANTED for state in ctx.output_contract_actuation_by_signature.values()+ )+++def _metadata_preflight_reject_yields_to_ladder(ctx: AgentContext) -> bool:+ """Register the preflight reject's claim and report whether it must yield to a live GRANTED advisory run.++ The reject always registers its (transient) claim. It yields only when a GRANTED advisory — the ladder's+ decision to dispatch despite deficiencies — owns the turn: yielding lets the forced dispatch consume the grant+ instead of re-blocking it. An ordinary reject cycle (a landed actuation without a grant) is the ladder's own+ mechanism, not a contradiction, so the reject still fires; and it does not yield to a genuinely-terminal owner+ (e.g. a just-committed early terminal), which legitimately ends the turn rather than dispatching a run behind it.+ """+ owner = current_turn_owner(ctx)+ claim_turn(ctx, TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT)+ return (+ _has_granted_output_contract_advisory_run(ctx)+ and owner is not None+ and owner.claimant is TurnClaimant.OUTPUT_CONTRACT_ACTUATION+ )++def _metadata_contract_run_preflight_reject(ctx: AgentContext,workflow_yaml: str,@@ -4119,6 +4145,8 @@ def _metadata_contract_run_preflight_reject()if convergence_reject.commit_early_terminal:_commit_recorded_outcome_early_terminal(ctx)+ if _metadata_preflight_reject_yields_to_ladder(ctx):+ return Nonereturn {"ok": False,"error": (@@ -4167,6 +4195,8 @@ def _metadata_contract_run_preflight_reject(payload["reason_code"] = _METADATA_CONTRACT_REQUIRED_BEFORE_RUN_REASON_CODEpayload["reject_reason"] = _METADATA_CONTRACT_REQUIRED_BEFORE_RUN_REASON_CODEblock_label = evaluation.block_label or "the target output block"+ if _metadata_preflight_reject_yields_to_ladder(ctx):+ return Nonereturn {"ok": False,"error": (@@ -5039,6 +5069,7 @@ def _signal_is_churn(signal: CopilotToolBlockerSignal | None) -> bool:def _clear_held_churn_signals(ctx: AgentContext) -> None:if _signal_is_churn(ctx.blocker_signal):ctx.blocker_signal = None+ ctx.blocker_signal_claimant = Noneif _signal_is_churn(ctx.latest_tool_blocker_signal):ctx.latest_tool_blocker_signal = Nonediff --git a/skyvern/forge/sdk/copilot/turn_halt.py b/skyvern/forge/sdk/copilot/turn_halt.pyindex aca046fd8..3076247dd 100644--- a/skyvern/forge/sdk/copilot/turn_halt.py+++ b/skyvern/forge/sdk/copilot/turn_halt.py@@ -8,11 +8,14 @@ from typing import TYPE_CHECKING, Anyimport structlog+from skyvern.forge.sdk.copilot.blocker_signal import (+ GENUINELY_TERMINAL_BLOCKER_REASON_CODES as GENUINELY_TERMINAL_BLOCKER_REASON_CODES,+)from skyvern.forge.sdk.copilot.blocker_signal import (CopilotToolBlockerSignal,+ blocker_signal_is_genuinely_terminal,build_output_source_unobservable_blocker_signal,clear_tool_blocker_signals_for_reason_codes,- stash_blocker_signal,)from skyvern.forge.sdk.copilot.blocker_signal import to_trace_data as blocker_signal_to_trace_datafrom skyvern.forge.sdk.copilot.failure_tracking import ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE@@ -24,6 +27,18 @@ from skyvern.forge.sdk.copilot.output_contracts import (from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODEfrom skyvern.forge.sdk.copilot.runtime import output_contract_ladder_unresolvedfrom skyvern.forge.sdk.copilot.schema_incompatibility import SCHEMA_INCOMPATIBILITY_REASON_CODE+from skyvern.forge.sdk.copilot.turn_ownership import (+ TURN_HALT_RETIRED_LOG_EVENT,+ TurnClaimant,+ claim_and_stash_blocker_signal,+ claim_turn,+ claimant_outranks,+ current_turn_owner,+ effective_signal_claimant,+ record_gate_precedence_conflict,+ release_turn_claim,+ turn_halt_is_genuinely_terminal,+)LOG = structlog.get_logger()@@ -80,22 +95,6 @@ _OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODES = frozenset(})-# A held blocker whose reason code is in this set must win both the rendered-# reply and the typed halt kind over a later non-terminal trip (e.g. the-# code-authoring churn backstop), which defers entirely when one is present.-GENUINELY_TERMINAL_BLOCKER_REASON_CODES = (- _ACTIVE_TERMINAL_CHALLENGE_REASON_CODES- | _PROBABLE_SITE_BLOCK_REASON_CODES- | _SCHEMA_INCOMPATIBILITY_REASON_CODES- | _OUTPUT_SOURCE_UNOBSERVABLE_REASON_CODES- | frozenset({"repair_ceiling_reached"})-)---def blocker_signal_is_genuinely_terminal(signal: CopilotToolBlockerSignal | None) -> bool:- return signal is not None and signal.internal_reason_code in GENUINELY_TERMINAL_BLOCKER_REASON_CODES--# Halts the agent did not choose: a verified outcome may suppress these.# ACTIVE_TERMINAL_CHALLENGE is voluntary and is deliberately excluded so a# future terminal kind defaults to raising rather than being suppressed.@@ -187,38 +186,72 @@ def _output_contract_defer_progress_token(ctx: Any) -> tuple[int, int, int, int])-def _expire_stalled_output_contract_ladder(ctx: Any) -> None:- if getattr(ctx, "turn_halt", None) is not None:- return+def _expire_unresolved_output_contract_signatures(ctx: AgentContext, *, include_granted: bool) -> list[str]:states = ctx.output_contract_actuation_by_signature- # A GRANTED grant is awaiting its forced run dispatch, not stalled: the dispatch lane consumes it- # next iteration, so expiring it here would false-fire arm-D on a source-producible shape and re-arm- # the loop guards before the granted run runs. Only a directive ladder with no live grant expires here.- if any(state == OutputContractAdvisoryState.GRANTED for state in states.values()):- return- counts = getattr(ctx, "output_contract_actuation_count_by_signature", {}) or {}+ counts = ctx.output_contract_actuation_count_by_signatureresolved = {OutputContractAdvisoryState.CONSUMED, OutputContractAdvisoryState.EXPIRED}expired: list[str] = []+ if include_granted:+ for signature, state in states.items():+ if state == OutputContractAdvisoryState.GRANTED:+ states[signature] = OutputContractAdvisoryState.EXPIRED+ expired.append(signature)for signature in set(states) | set(counts):- state = states.get(signature)- if int(counts.get(signature, 0) or 0) >= 1 and state not in resolved:+ if int(counts.get(signature, 0) or 0) >= 1 and states.get(signature) not in resolved:states[signature] = OutputContractAdvisoryState.EXPIREDexpired.append(signature)- if not expired:- return- required_paths = sorted(- {path for paths in getattr(ctx, "output_contract_pending_run_evidence", {}).values() for path in paths}- )+ return expired+++def _emit_advisory_dispatch_stalled_terminal(ctx: AgentContext, expired: list[str], *, source: str) -> TurnHalt | None:+ required_paths = sorted({path for paths in ctx.output_contract_pending_run_evidence.values() for path in paths})signal = build_output_source_unobservable_blocker_signal(reason_code=ADVISORY_DISPATCH_STALLED_REASON_CODE,required_paths=required_paths,block_label="",)- stash_blocker_signal(ctx, signal)- halt = turn_halt_from_blocker_signal(signal, source="turn_halt_defer_expiry")- if halt is not None:- ctx.turn_halt = halt- LOG.info("copilot_output_contract_advisory_dispatch_stalled", canonical_output_contract_signatures=expired)+ claim_and_stash_blocker_signal(ctx, TurnClaimant.GENUINELY_TERMINAL, signal)+ halt = turn_halt_from_blocker_signal(signal, source=source)+ if halt is None:+ return None+ ctx.turn_halt = halt+ LOG.info("copilot_output_contract_advisory_dispatch_stalled", canonical_output_contract_signatures=expired)+ return halt+++def _expire_stalled_output_contract_ladder(ctx: AgentContext) -> None:+ if ctx.turn_halt is not None:+ return+ states = ctx.output_contract_actuation_by_signature+ # A GRANTED grant is awaiting its forced run dispatch, not stalled: the dispatch lane consumes it+ # next iteration, so expiring it here would false-fire arm-D on a source-producible shape and re-arm+ # the loop guards before the granted run runs. Only a directive ladder with no live grant expires here.+ if any(state == OutputContractAdvisoryState.GRANTED for state in states.values()):+ return+ expired = _expire_unresolved_output_contract_signatures(ctx, include_granted=False)+ if not expired:+ return+ _emit_advisory_dispatch_stalled_terminal(ctx, expired, source="turn_halt_defer_expiry")+++def expire_output_contract_ladder_at_turn_end(+ ctx: AgentContext, *, emit_stalled_terminal: bool = True+) -> TurnHalt | None:+ """Turn-end obligation: every GRANTED advisory signature expires here, and when no other halt+ ended the turn the existing advisory-dispatch-stalled terminal is emitted for the silent grant."""+ states = ctx.output_contract_actuation_by_signature+ if not any(state == OutputContractAdvisoryState.GRANTED for state in states.values()):+ return None+ expired = _expire_unresolved_output_contract_signatures(ctx, include_granted=True)+ existing = ctx.turn_halt+ if existing is not None or not emit_stalled_terminal:+ LOG.info(+ "copilot_output_contract_advisory_turn_end_reconcile_noop",+ canonical_output_contract_signatures=expired,+ existing_turn_halt_kind=existing.kind.value if existing is not None else None,+ )+ return None+ return _emit_advisory_dispatch_stalled_terminal(ctx, expired, source="turn_end_ownership_reconcile")def _defer_loop_detected_while_output_contract_ladder_unresolved(ctx: Any, signal: object) -> bool:@@ -258,6 +291,8 @@ def stash_turn_halt_from_blocker_signal(ctx: Any, signal: object, *, source: strif halt is None:return Nonectx.turn_halt = halt+ if blocker_signal_is_genuinely_terminal(halt.blocker_signal):+ claim_turn(ctx, TurnClaimant.GENUINELY_TERMINAL, renders_final_reply=True)LOG.info("copilot turn halt stashed", **turn_halt_to_trace_data(halt))return halt@@ -281,6 +316,7 @@ def stash_repair_ceiling_turn_halt(},)ctx.turn_halt = halt+ claim_turn(ctx, TurnClaimant.GENUINELY_TERMINAL, renders_final_reply=True)LOG.info("copilot turn halt stashed", **turn_halt_to_trace_data(halt))return halt@@ -296,10 +332,52 @@ def stash_delivered_unverified_turn_halt(ctx: AgentContext, *, workflow_run_id:extra={"source": "run_execution"},)ctx.turn_halt = halt+ claim_turn(ctx, TurnClaimant.GENUINELY_TERMINAL, renders_final_reply=True)LOG.info("copilot turn halt stashed", **turn_halt_to_trace_data(halt))return halt+def _restored_owner_halt(ctx: AgentContext, owner_claimant: TurnClaimant) -> TurnHalt | None:+ held = ctx.blocker_signal+ if held is None or effective_signal_claimant(ctx, held) is not owner_claimant:+ return None+ return turn_halt_from_blocker_signal(held, source="precedence_owner_restored")+++def retire_outranked_turn_halt(ctx: AgentContext) -> bool:+ """Storage follows ownership at the halt's consumption points: a non-terminal halt outranked by+ the live owner is retired (conflict recorded) and the owner's halt is restored by re-emission+ from the held signal, never resurrected from the retired object."""+ halt = ctx.turn_halt+ if halt is None or turn_halt_is_genuinely_terminal(halt):+ return False+ owner = current_turn_owner(ctx)+ if owner is None:+ return False+ signal = halt.blocker_signal+ halt_claimant = effective_signal_claimant(ctx, signal) if signal is not None else None+ if halt_claimant is None or halt_claimant is owner.claimant or not claimant_outranks(owner.claimant, halt_claimant):+ return False+ record_gate_precedence_conflict(+ ctx,+ owner=owner.claimant.value,+ yielded=halt_claimant.value,+ owner_renders_final_reply=owner.renders_final_reply,+ yielded_renders_final_reply=bool(signal is not None and signal.renders_final_reply),+ site="turn_halt",+ )+ restored = _restored_owner_halt(ctx, owner.claimant)+ ctx.turn_halt = restored+ LOG.info(+ TURN_HALT_RETIRED_LOG_EVENT,+ owner=owner.claimant.value,+ retired=halt_claimant.value,+ retired_reason_code=signal.internal_reason_code if signal is not None else None,+ restored_turn_halt_kind=restored.kind.value if restored is not None else None,+ )+ return True++def raise_if_turn_halt(ctx: Any, *, verified: bool = False) -> None:"""Raise the stashed turn halt unless a verified outcome suppresses it.@@ -311,6 +389,10 @@ def raise_if_turn_halt(ctx: Any, *, verified: bool = False) -> None:halt = getattr(ctx, "turn_halt", None)if not isinstance(halt, TurnHalt):return+ if retire_outranked_turn_halt(ctx):+ halt = getattr(ctx, "turn_halt", None)+ if not isinstance(halt, TurnHalt):+ returnsuppressible_reason_codes = _INVOLUNTARY_BLOCKER_REASON_CODESif (halt.kind == TurnHaltKind.ACTIVE_TERMINAL_CHALLENGE@@ -326,6 +408,7 @@ def raise_if_turn_halt(ctx: Any, *, verified: bool = False) -> None:if verified and suppressible_reason_codes:ctx.turn_halt = Noneclear_tool_blocker_signals_for_reason_codes(ctx, suppressible_reason_codes)+ release_turn_claim(ctx, TurnClaimant.GENUINELY_TERMINAL)LOG.info("copilot turn halt suppressed by verified outcome",**turn_halt_to_trace_data(halt),diff --git a/skyvern/forge/sdk/copilot/turn_ownership.py b/skyvern/forge/sdk/copilot/turn_ownership.pynew file mode 100644index 000000000..fa93cc8f3--- /dev/null+++ b/skyvern/forge/sdk/copilot/turn_ownership.py@@ -0,0 +1,361 @@+"""Single-owner turn-precedence contract: one mechanism owns a Copilot turn's steering at a time,+computed as the strongest live claim; weaker claims yield and are recorded as gate-precedence+conflicts, and storage (held blocker signal and turn halt) follows ownership."""++from __future__ import annotations++from dataclasses import dataclass, field, replace+from enum import StrEnum+from typing import TYPE_CHECKING++import structlog++from skyvern.forge.sdk.copilot.blocker_signal import (+ GENUINELY_TERMINAL_BLOCKER_REASON_CODES,+ RECORDED_OUTCOME_GROUNDING_REASON_CODE,+ SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE,+ UNCOVERED_OUTPUT_RESCOUT_STEER_REASON_CODE,+ CopilotToolBlockerSignal,+ blocker_signal_is_genuinely_terminal,+ build_llm_tool_error_payload,+ stash_blocker_signal,+)+from skyvern.forge.sdk.copilot.runtime import AgentContext, output_contract_ladder_unresolved++if TYPE_CHECKING:+ from skyvern.forge.sdk.copilot.turn_halt import TurnHalt++LOG = structlog.get_logger()++GATE_PRECEDENCE_CONFLICT_LOG_EVENT = "copilot_gate_precedence_conflict"+TURN_HALT_RETIRED_LOG_EVENT = "copilot_turn_halt_retired_by_precedence_owner"+BLOCKER_SIGNAL_REPLACED_LOG_EVENT = "copilot_blocker_signal_replaced_by_precedence_owner"++_MAX_CONFLICT_EVENTS = 20+++class TurnClaimant(StrEnum):+ GENUINELY_TERMINAL = "genuinely_terminal"+ OUTPUT_CONTRACT_ACTUATION = "output_contract_actuation"+ CREDENTIAL_PRIORITY_CHURN = "credential_priority_authoring_churn"+ METADATA_RUN_PREFLIGHT_REJECT = "metadata_run_preflight_reject"+ ACTUATION_OBLIGATION_FILL = "actuation_obligation_fill"+ CREDENTIAL_SCOUT_REOPEN = "credential_scout_reopen"+ UNCOVERED_OUTPUT_RESCOUT_STEER = "uncovered_output_rescout_steer"+ RECORDED_OUTCOME_GROUNDING = "recorded_outcome_grounding"+ SYNTHESIZED_BLOCK_PERSISTENCE_FORCE = "synthesized_block_persistence_force"+ CODE_AUTHORING_CHURN = "code_authoring_guardrail_churn"+ LOOP_DETECTED = "loop_detected"+++class ClaimOutcome(StrEnum):+ OWNED = "owned"+ YIELDED = "yielded"+++# Strongest first. Each row's position derives from an observed cascade order, a ratified+# carve-out, or the ladder defer; pairs that never co-occur at a seam are newly defined.+_PRECEDENCE_ORDER: tuple[TurnClaimant, ...] = (+ # Genuinely-terminal blockers keep both the rendered reply and the halt kind: the loop-defer+ # choke-point excludes them and the churn floor defers to a held terminal signal.+ TurnClaimant.GENUINELY_TERMINAL,+ # Ladder-over-loop defer at the turn-halt choke-point; ladder-over-rescout; the inline churn+ # defer keyed on output_contract_ladder_unresolved.+ TurnClaimant.OUTPUT_CONTRACT_ACTUATION,+ # Bound-8 credential-priority churn defers only to terminal evidence and the actuation ladder,+ # preserving the credential-scout reply.+ TurnClaimant.CREDENTIAL_PRIORITY_CHURN,+ # Author-time preflight reject steers before any churn or loop floor accumulates.+ TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT,+ # Actuation-obligation fill carve-out admits the required fill tool through the persistence+ # gate; predicate-gated at its call site, never an unconditional rank flip.+ TurnClaimant.ACTUATION_OBLIGATION_FILL,+ # One-shot credential-scout reopen admits evaluate through the persistence gate;+ # predicate-gated at its call site.+ TurnClaimant.CREDENTIAL_SCOUT_REOPEN,+ # First-match cascade order: the uncovered-output rescout steer is evaluated before the+ # persistence force and the grounding gate.+ TurnClaimant.UNCOVERED_OUTPUT_RESCOUT_STEER,+ # Grounding-over-persistence nested exception: a live grounding requirement is emitted instead+ # of the persistence force when both hold.+ TurnClaimant.RECORDED_OUTCOME_GROUNDING,+ # Cascade position after the rescout steer and below the grounding exception.+ TurnClaimant.SYNTHESIZED_BLOCK_PERSISTENCE_FORCE,+ # The churn convergence floor fires before the no-progress floor in the enforcement backstop.+ TurnClaimant.CODE_AUTHORING_CHURN,+ # Loop detectors defer to every steering gate above them.+ TurnClaimant.LOOP_DETECTED,+)+_PRECEDENCE_RANK: dict[TurnClaimant, int] = {claimant: index for index, claimant in enumerate(_PRECEDENCE_ORDER)}++# The one shared claimant table: every cascade (tool-side and MCP) resolves a+# signal's claimant here so the two paths cannot diverge.+CLAIMANT_REASON_CODE_FAMILIES: dict[TurnClaimant, frozenset[str]] = {+ TurnClaimant.GENUINELY_TERMINAL: GENUINELY_TERMINAL_BLOCKER_REASON_CODES,+ TurnClaimant.OUTPUT_CONTRACT_ACTUATION: frozenset(),+ TurnClaimant.CREDENTIAL_PRIORITY_CHURN: frozenset({"credential_priority_authoring_churn"}),+ TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT: frozenset(),+ TurnClaimant.ACTUATION_OBLIGATION_FILL: frozenset(),+ TurnClaimant.CREDENTIAL_SCOUT_REOPEN: frozenset(),+ TurnClaimant.UNCOVERED_OUTPUT_RESCOUT_STEER: frozenset({UNCOVERED_OUTPUT_RESCOUT_STEER_REASON_CODE}),+ TurnClaimant.RECORDED_OUTCOME_GROUNDING: frozenset({RECORDED_OUTCOME_GROUNDING_REASON_CODE}),+ TurnClaimant.SYNTHESIZED_BLOCK_PERSISTENCE_FORCE: frozenset({SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE}),+ TurnClaimant.CODE_AUTHORING_CHURN: frozenset({"code_authoring_guardrail_churn"}),+ TurnClaimant.LOOP_DETECTED: frozenset(+ {+ "loop_detected_credential_or_parameter_misconfig",+ "loop_detected_repeated_failed_step",+ "loop_detected_consecutive_same_tool",+ "loop_detected_generic",+ "loop_detected_no_forward_progress_interaction",+ }+ ),+}++_CLAIMANT_BY_REASON_CODE: dict[str, TurnClaimant] = {+ reason_code: claimant+ for claimant, reason_codes in CLAIMANT_REASON_CODE_FAMILIES.items()+ for reason_code in reason_codes+}++# Claimants whose ownership lasts only for the duration of the claiming call: the claim records+# reachability and conflicts, but never suppresses a later gate or render on the same turn.+_TRANSIENT_CLAIMANTS = frozenset(+ {+ TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT,+ TurnClaimant.ACTUATION_OBLIGATION_FILL,+ TurnClaimant.CREDENTIAL_SCOUT_REOPEN,+ }+)++_SIGNALLESS_TERMINAL_TURN_HALT_KIND_VALUES = frozenset({"repair_ceiling_reached", "delivered_unverified"})+++def claimant_outranks(candidate: TurnClaimant, incumbent: TurnClaimant) -> bool:+ return _PRECEDENCE_RANK[candidate] < _PRECEDENCE_RANK[incumbent]+++def claimant_for_blocker_signal(signal: CopilotToolBlockerSignal) -> TurnClaimant | None:+ if not signal.internal_reason_code:+ return None+ return _CLAIMANT_BY_REASON_CODE.get(signal.internal_reason_code)+++@dataclass(frozen=True)+class PrecedenceClaim:+ claimant: TurnClaimant+ renders_final_reply: bool = False+++@dataclass(frozen=True)+class GatePrecedenceConflictEvent:+ owner: str+ yielded: str+ owner_renders_final_reply: bool+ yielded_renders_final_reply: bool+ site: str = "claim"++ @property+ def fingerprint(self) -> str:+ return f"{self.owner}>{self.yielded}"+++@dataclass+class TurnOwnership:+ claims: dict[TurnClaimant, PrecedenceClaim] = field(default_factory=dict)+++_LADDER_CLAIM = PrecedenceClaim(claimant=TurnClaimant.OUTPUT_CONTRACT_ACTUATION)+++def _ownership_registry(ctx: AgentContext) -> TurnOwnership:+ if ctx.turn_ownership is None:+ ctx.turn_ownership = TurnOwnership()+ return ctx.turn_ownership+++def record_gate_precedence_conflict(+ ctx: AgentContext,+ *,+ owner: str,+ yielded: str,+ owner_renders_final_reply: bool,+ yielded_renders_final_reply: bool,+ site: str,+) -> GatePrecedenceConflictEvent:+ event = GatePrecedenceConflictEvent(+ owner=owner,+ yielded=yielded,+ owner_renders_final_reply=owner_renders_final_reply,+ yielded_renders_final_reply=yielded_renders_final_reply,+ site=site,+ )+ events = ctx.gate_precedence_conflict_events+ events.append(event)+ if len(events) > _MAX_CONFLICT_EVENTS:+ del events[:-_MAX_CONFLICT_EVENTS]+ LOG.info(+ GATE_PRECEDENCE_CONFLICT_LOG_EVENT,+ owner=event.owner,+ yielded=event.yielded,+ fingerprint=event.fingerprint,+ owner_renders_final_reply=event.owner_renders_final_reply,+ yielded_renders_final_reply=event.yielded_renders_final_reply,+ site=event.site,+ )+ return event+++def turn_halt_is_genuinely_terminal(halt: TurnHalt | None) -> bool:+ if halt is None:+ return False+ if halt.blocker_signal is not None:+ return blocker_signal_is_genuinely_terminal(halt.blocker_signal)+ return halt.kind.value in _SIGNALLESS_TERMINAL_TURN_HALT_KIND_VALUES+++def _held_signal_claimant(ctx: AgentContext) -> TurnClaimant | None:+ held = ctx.blocker_signal+ if held is None:+ return None+ if ctx.blocker_signal_claimant is not None:+ return ctx.blocker_signal_claimant+ return claimant_for_blocker_signal(held)+++def effective_signal_claimant(ctx: AgentContext, signal: CopilotToolBlockerSignal) -> TurnClaimant | None:+ if ctx.blocker_signal is signal and ctx.blocker_signal_claimant is not None:+ return ctx.blocker_signal_claimant+ return claimant_for_blocker_signal(signal)+++def _claim_is_live(ctx: AgentContext, claim: PrecedenceClaim) -> bool:+ if claim.claimant in _TRANSIENT_CLAIMANTS:+ return False+ if claim.claimant is TurnClaimant.OUTPUT_CONTRACT_ACTUATION:+ return output_contract_ladder_unresolved(ctx)+ if claim.claimant is TurnClaimant.GENUINELY_TERMINAL and turn_halt_is_genuinely_terminal(ctx.turn_halt):+ return True+ return _held_signal_claimant(ctx) is claim.claimant+++def current_turn_owner(ctx: AgentContext) -> PrecedenceClaim | None:+ claims = dict(ctx.turn_ownership.claims) if ctx.turn_ownership is not None else {}+ # The actuation ladder's ownership is state-backed: a live ladder owns the+ # turn even when no explicit claim was registered before it went live.+ if TurnClaimant.OUTPUT_CONTRACT_ACTUATION not in claims and output_contract_ladder_unresolved(ctx):+ claims[TurnClaimant.OUTPUT_CONTRACT_ACTUATION] = _LADDER_CLAIM+ live = [claim for claim in claims.values() if _claim_is_live(ctx, claim)]+ if not live:+ return None+ return min(live, key=lambda claim: _PRECEDENCE_RANK[claim.claimant])+++def claim_turn(+ ctx: AgentContext,+ claimant: TurnClaimant,+ *,+ renders_final_reply: bool = False,+) -> ClaimOutcome:+ owner = current_turn_owner(ctx)+ if owner is not None and owner.claimant is not claimant and not claimant_outranks(claimant, owner.claimant):+ record_gate_precedence_conflict(+ ctx,+ owner=owner.claimant.value,+ yielded=claimant.value,+ owner_renders_final_reply=owner.renders_final_reply,+ yielded_renders_final_reply=renders_final_reply,+ site="claim",+ )+ return ClaimOutcome.YIELDED+ registry = _ownership_registry(ctx)+ existing = registry.claims.get(claimant)+ if existing is None:+ claim = PrecedenceClaim(claimant=claimant, renders_final_reply=renders_final_reply)+ else:+ # Same-claimant re-claims are first-wins: the original instance stays live; only the metadata widens.+ claim = replace(existing, renders_final_reply=existing.renders_final_reply or renders_final_reply)+ registry.claims[claimant] = claim+ if owner is not None and owner.claimant is not claimant:+ record_gate_precedence_conflict(+ ctx,+ owner=claim.claimant.value,+ yielded=owner.claimant.value,+ owner_renders_final_reply=claim.renders_final_reply,+ yielded_renders_final_reply=owner.renders_final_reply,+ site="claim",+ )+ return ClaimOutcome.OWNED+++def release_turn_claim(ctx: AgentContext, claimant: TurnClaimant) -> None:+ if ctx.turn_ownership is not None:+ ctx.turn_ownership.claims.pop(claimant, None)+++def _owned_claim_replaces_held(ctx: AgentContext, claimant: TurnClaimant, held: CopilotToolBlockerSignal) -> bool:+ held_claimant = effective_signal_claimant(ctx, held)+ return held_claimant is not None and claimant_outranks(claimant, held_claimant)+++def claim_and_stash_blocker_signal(+ ctx: AgentContext,+ claimant: TurnClaimant,+ signal: CopilotToolBlockerSignal,+ *,+ force_stash: bool = False,+) -> str | None:+ """Atomic claim-then-stash: a yielded claim stashes nothing and returns None; an owned claim+ stashes with storage-follows-ownership replacement and takes over the held-signal association."""+ if claim_turn(ctx, claimant, renders_final_reply=signal.renders_final_reply) is ClaimOutcome.YIELDED:+ return None+ payload = stash_blocker_signal(ctx, signal)+ held = ctx.blocker_signal+ if (+ held is not None+ and held is not signal+ and not blocker_signal_is_genuinely_terminal(held)+ and (force_stash or _owned_claim_replaces_held(ctx, claimant, held))+ ):+ ctx.blocker_signal = signal+ LOG.info(+ BLOCKER_SIGNAL_REPLACED_LOG_EVENT,+ owner=claimant.value,+ replaced_reason_code=held.internal_reason_code,+ stashed_reason_code=signal.internal_reason_code,+ )+ if ctx.blocker_signal is signal:+ ctx.blocker_signal_claimant = claimant+ return payload+++def emit_blocker_signal_payload(ctx: AgentContext, signal: CopilotToolBlockerSignal) -> str:+ """Claim-gated stash that always returns the tool-block payload: a yielded claim suppresses the+ stash (reply/halt ownership), never the tool block itself."""+ claimant = claimant_for_blocker_signal(signal)+ if claimant is None:+ return stash_blocker_signal(ctx, signal)+ payload = claim_and_stash_blocker_signal(ctx, claimant, signal)+ if payload is not None:+ return payload+ return build_llm_tool_error_payload(signal)+++def blocker_signal_render_allowed(ctx: AgentContext, signal: CopilotToolBlockerSignal) -> bool:+ """A held signal mapped to a claimant outranked by the live owner is denied the final-reply+ render and the denial is recorded as a gate-precedence conflict; unclaimed signals fail open."""+ owner = current_turn_owner(ctx)+ if owner is None:+ return True+ claimant = effective_signal_claimant(ctx, signal)+ if claimant is None or claimant is owner.claimant or not claimant_outranks(owner.claimant, claimant):+ return True+ record_gate_precedence_conflict(+ ctx,+ owner=owner.claimant.value,+ yielded=claimant.value,+ owner_renders_final_reply=owner.renders_final_reply,+ yielded_renders_final_reply=signal.renders_final_reply,+ site="final_reply_render",+ )+ return Falsediff --git a/tests/unit/test_copilot_agent_blocker_renderer.py b/tests/unit/test_copilot_agent_blocker_renderer.pyindex fc306f105..fc426d7f6 100644--- a/tests/unit/test_copilot_agent_blocker_renderer.py+++ b/tests/unit/test_copilot_agent_blocker_renderer.py@@ -27,6 +27,7 @@ from skyvern.forge.sdk.copilot.blocker_signal import ()from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdictfrom skyvern.forge.sdk.copilot.context import AgentResult, CopilotContext+from skyvern.forge.sdk.copilot.output_contracts import OutputContractAdvisoryStatefrom skyvern.forge.sdk.copilot.output_policy import (ACTUATION_OBLIGATION_STEER_REASON_CODE,CopilotOutputKind,@@ -36,6 +37,8 @@ from skyvern.forge.sdk.copilot.output_policy import (from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicyfrom skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODE, RecordedRunOutcomefrom skyvern.forge.sdk.copilot.turn_halt import TurnHalt, TurnHaltKind+from skyvern.forge.sdk.copilot.turn_ownership import TurnClaimant, claim_and_stash_blocker_signal+from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequestfrom tests.unit.conftest import make_copilot_context as _ctx# Source-of-truth deny list lives in blocker_signal.py. Re-importing here@@ -875,3 +878,211 @@ def test_verified_outcome_does_not_suppress_voluntary_terminal_challenge() -> Noassert overridden.user_response == challenge_textassert overridden.user_response != _VERIFIED_WORKFLOW_SUCCESS_REPLYassert overridden.proposal_disposition != "review_tested"+++def _churn_render_signal() -> CopilotToolBlockerSignal:+ return _signal(+ kind="loop_detected",+ user_facing="I kept rewriting the generated code, but the safety checks rejected each version.",+ internal_reason_code="code_authoring_guardrail_churn",+ )+++def test_shim_denies_churn_render_while_ladder_owns_and_records_conflict() -> None:+ ctx = _ctx()+ signal = _churn_render_signal()+ claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, signal)+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ original = _agent_result("Model reply describing progress.")++ result = _finalize_result_with_blocker_override(ctx, original)++ assert result is original+ assert any(+ event.site == "final_reply_render"+ and event.fingerprint == "output_contract_actuation>code_authoring_guardrail_churn"+ for event in ctx.gate_precedence_conflict_events+ )+++def test_shim_renders_churn_after_ladder_resolves() -> None:+ ctx = _ctx()+ signal = _churn_render_signal()+ claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, signal)+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.CONSUMED+ original = _agent_result("Model reply describing progress.")++ result = _finalize_result_with_blocker_override(ctx, original)++ assert result is not original+ assert signal.user_facing_reason in result.user_response+++def test_credential_priority_churn_still_renders_when_no_ladder_owns() -> None:+ ctx = _ctx()+ signal = _signal(+ kind="loop_detected",+ user_facing=CREDENTIAL_SCOUT_VERIFY_REPLY,+ internal_reason_code="credential_priority_authoring_churn",+ )+ claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, signal)++ result = _finalize_result_with_blocker_override(ctx, _agent_result())++ assert CREDENTIAL_SCOUT_VERIFY_REPLY in result.user_response+++def test_output_policy_blocked_result_surfaces_draft_when_blocker_render_denied() -> None:+ ctx = _ctx()+ fake_workflow: Any = object()+ ctx.last_workflow = fake_workflow+ ctx.last_workflow_yaml = "title: X\nworkflow_definition:\n blocks: []\n"+ claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, _churn_render_signal())+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED++ result = _blocked_result(ctx, OutputPolicyReason.UNAPPROVED_CREDENTIAL_REFERENCE)++ assert result.updated_workflow is fake_workflow+ assert any(event.site == "final_reply_render" for event in ctx.gate_precedence_conflict_events)+++def test_reconcile_turn_end_replaces_result_with_stalled_terminal() -> None:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ ctx.output_contract_pending_run_evidence["sig_a"] = ["output.confirmation_number"]+ original = _agent_result("Model reply describing progress.")++ result = agent_module._reconcile_turn_end_ownership(ctx, original)++ assert result is not original+ assert ctx.turn_halt is not None+ assert ctx.turn_halt.kind is TurnHaltKind.OUTPUT_SOURCE_UNOBSERVABLE+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.EXPIRED+ assert "I couldn't shape this workflow" in result.user_response+++def test_reconcile_turn_end_noop_without_live_grant() -> None:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.CONSUMED+ original = _agent_result()++ assert agent_module._reconcile_turn_end_ownership(ctx, original) is original+++def test_reconcile_turn_end_failure_never_masks_original_result(monkeypatch: pytest.MonkeyPatch) -> None:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED++ def _boom(_: Any) -> None:+ raise RuntimeError("reconcile failure")++ monkeypatch.setattr(agent_module, "expire_output_contract_ladder_at_turn_end", _boom)+ original = _agent_result()++ assert agent_module._reconcile_turn_end_ownership(ctx, original) is original+++def _stalled_chat_request() -> WorkflowCopilotChatRequest:+ return WorkflowCopilotChatRequest(+ workflow_permanent_id="wpid_xyz",+ workflow_id="w_001",+ workflow_copilot_chat_id="chat_abc",+ message="build the workflow",+ workflow_yaml="",+ )+++async def test_turn_end_obligation_transforms_returned_result_on_normal_exit(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: list[CopilotContext] = []++ async def stub_impl(*, ctx_sink: list[CopilotContext], **_: Any) -> AgentResult:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ ctx_sink.append(ctx)+ captured.append(ctx)+ return _agent_result("Model reply describing progress.")++ monkeypatch.setattr(agent_module, "_run_copilot_turn_impl", stub_impl)++ result = await agent_module.run_copilot_agent(+ stream=object(),+ organization_id="o_test",+ chat_request=_stalled_chat_request(),+ chat_history=[],+ global_llm_context=None,+ debug_run_info_text="",+ llm_api_handler=None,+ )++ ctx = captured[0]+ assert ctx.turn_halt is not None+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.EXPIRED+ assert "I couldn't shape this workflow" in result.user_response+++async def test_turn_end_obligation_preserves_error_terminal_and_expires_grant(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: list[CopilotContext] = []++ async def stub_impl(*, ctx_sink: list[CopilotContext], **_: Any) -> AgentResult:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ ctx_sink.append(ctx)+ captured.append(ctx)+ raise RuntimeError("mid-turn failure")++ monkeypatch.setattr(agent_module, "_run_copilot_turn_impl", stub_impl)++ result = await agent_module.run_copilot_agent(+ stream=object(),+ organization_id="o_test",+ chat_request=_stalled_chat_request(),+ chat_history=[],+ global_llm_context=None,+ debug_run_info_text="",+ llm_api_handler=None,+ )++ ctx = captured[0]+ assert ctx.turn_halt is None+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.EXPIRED+ assert "I couldn't shape this workflow" not in result.user_response+++def test_reconcile_turn_end_keeps_ask_question_result_and_expires_grant() -> None:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ original = AgentResult(+ user_response="Which site should this run against?",+ updated_workflow=None,+ global_llm_context=None,+ response_type="ASK_QUESTION",+ )++ result = agent_module._reconcile_turn_end_ownership(ctx, original)++ assert result is original+ assert ctx.turn_halt is None+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.EXPIRED+++def test_reconcile_turn_end_keeps_cancelled_result_and_expires_grant() -> None:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ original = AgentResult(+ user_response="Cancelled by user.",+ updated_workflow=None,+ global_llm_context=None,+ cancelled=True,+ )++ result = agent_module._reconcile_turn_end_ownership(ctx, original)++ assert result is original+ assert ctx.turn_halt is None+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.EXPIREDdiff --git a/tests/unit/test_copilot_blocker_lifecycle.py b/tests/unit/test_copilot_blocker_lifecycle.pyindex 38a2cbdeb..9a1857b10 100644--- a/tests/unit/test_copilot_blocker_lifecycle.py+++ b/tests/unit/test_copilot_blocker_lifecycle.py@@ -1,7 +1,21 @@from __future__ import annotations+import pytest+from skyvern.forge.sdk.copilot.blocker_signal import BlockerKind, CopilotToolBlockerSignal+from skyvern.forge.sdk.copilot.enforcement import (+ MAX_CODE_AUTHORING_GUARDRAIL_REJECTS,+ _record_code_authoring_guardrail_reject,+)from skyvern.forge.sdk.copilot.loop_detection import record_tool_step_result_for_ctx+from skyvern.forge.sdk.copilot.mcp_adapter import _stash_and_emit_loop_blocker+from skyvern.forge.sdk.copilot.output_contracts import OutputContractAdvisoryState+from skyvern.forge.sdk.copilot.tools import workflow_update as workflow_update_module+from skyvern.forge.sdk.copilot.turn_ownership import (+ TurnClaimant,+ blocker_signal_render_allowed,+ current_turn_owner,+)from tests.unit.conftest import make_copilot_context as _ctx@@ -268,3 +282,57 @@ def test_reconciliation_requires_input_does_not_clear_after_metadata_only_succesassert ctx.pending_reconciliation_run_id == "wr_pending"assert ctx.blocker_signal is not Noneassert ctx.blocker_signal.internal_reason_code == "tool_error_pending_reconciliation_requires_input"+++def test_preflight_reject_leaves_churn_floor_armed_for_rest_of_turn(monkeypatch: pytest.MonkeyPatch) -> None:+ ctx = _ctx()+ monkeypatch.setattr(+ workflow_update_module,+ "_recorded_outcome_convergence_reject",+ lambda *_args, **_kwargs: workflow_update_module._ConvergenceReject(+ "sig", "identical_authored_structure", False+ ),+ )++ reject = workflow_update_module._metadata_contract_run_preflight_reject(ctx, "title: X", [])+ assert reject is not None+ assert ctx.turn_ownership is not None+ assert TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT in ctx.turn_ownership.claims+ assert current_turn_owner(ctx) is None++ ctx.code_authoring_guardrail_reject_count = MAX_CODE_AUTHORING_GUARDRAIL_REJECTS - 1+ _record_code_authoring_guardrail_reject(ctx)++ signal = ctx.blocker_signal+ assert signal is not None+ assert signal.internal_reason_code == "code_authoring_guardrail_churn"+ assert blocker_signal_render_allowed(ctx, signal) is True+++def test_mcp_loop_blocker_yield_still_blocks_the_tool() -> None:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED++ payload = _stash_and_emit_loop_blocker(ctx, "update_workflow has been called 4 times in a row", "update_workflow")++ assert isinstance(payload, str) and payload+ assert ctx.blocker_signal is None+ assert ctx.turn_halt is None+ assert any(+ event.fingerprint == "output_contract_actuation>loop_detected" for event in ctx.gate_precedence_conflict_events+ )+++def test_mcp_loop_blocker_re_emits_after_ladder_resolves() -> None:+ ctx = _ctx()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ _stash_and_emit_loop_blocker(ctx, "update_workflow has been called 4 times in a row", "update_workflow")+ assert ctx.blocker_signal is None++ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.CONSUMED+ payload = _stash_and_emit_loop_blocker(ctx, "update_workflow has been called 4 times in a row", "update_workflow")++ assert payload is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "loop_detected_consecutive_same_tool"+ assert ctx.turn_halt is not Nonediff --git a/tests/unit/test_copilot_enforcement_hardening.py b/tests/unit/test_copilot_enforcement_hardening.pyindex 697ca7839..3fbee5520 100644--- a/tests/unit/test_copilot_enforcement_hardening.py+++ b/tests/unit/test_copilot_enforcement_hardening.py@@ -54,14 +54,21 @@ from skyvern.forge.sdk.copilot.enforcement import (_maybe_raise_non_retriable_nav,_needs_inspect_before_repair_nudge,_prune_input_list,+ _record_code_authoring_guardrail_reject,_recover_from_context_overflow,_strip_input_images,register_no_progress_interaction_click,reset_no_progress_interaction_count,)+from skyvern.forge.sdk.copilot.output_contracts import OutputContractAdvisoryStatefrom skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODEfrom skyvern.forge.sdk.copilot.streaming_adapter import _update_enforcement_from_tool-from skyvern.forge.sdk.copilot.turn_halt import CopilotTurnHalt, TurnHaltKind+from skyvern.forge.sdk.copilot.turn_halt import (+ ADVISORY_DISPATCH_STALLED_REASON_CODE,+ CopilotTurnHalt,+ TurnHaltKind,+ expire_output_contract_ladder_at_turn_end,+)from tests.unit.conftest import make_copilot_context as _fresh_context# ---------------------------------------------------------------------------@@ -728,3 +735,97 @@ def test_no_progress_held_blocker_survives_progress_tool_success(recovery_tool:maybe_clear_blocker_signal_on_tool_success(ctx, recovery_tool)assert ctx.blocker_signal is held+++def _grant_output_contract_ladder(ctx: CopilotContext) -> None:+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+++def test_inline_churn_reject_yields_to_live_ladder_and_keeps_count() -> None:+ ctx = _fresh_context()+ ctx.code_authoring_guardrail_reject_count = MAX_CODE_AUTHORING_GUARDRAIL_REJECTS - 1+ _grant_output_contract_ladder(ctx)++ _record_code_authoring_guardrail_reject(ctx)++ assert ctx.code_authoring_guardrail_reject_count == MAX_CODE_AUTHORING_GUARDRAIL_REJECTS+ assert ctx.blocker_signal is None+ assert ctx.turn_halt is None+ assert any(+ event.fingerprint == "output_contract_actuation>code_authoring_guardrail_churn"+ for event in ctx.gate_precedence_conflict_events+ )+++def test_inline_churn_reject_stashes_when_no_owner_is_live() -> None:+ ctx = _fresh_context()+ ctx.code_authoring_guardrail_reject_count = MAX_CODE_AUTHORING_GUARDRAIL_REJECTS - 1++ _record_code_authoring_guardrail_reject(ctx)++ signal = ctx.blocker_signal+ assert isinstance(signal, CopilotToolBlockerSignal)+ assert signal.internal_reason_code == "code_authoring_guardrail_churn"+ assert signal.renders_final_reply is True+++def test_churn_backstop_yields_to_live_ladder_without_halt_or_stash() -> None:+ ctx = _fresh_context()+ ctx.code_authoring_guardrail_reject_count = MAX_CODE_AUTHORING_GUARDRAIL_REJECTS+ _grant_output_contract_ladder(ctx)++ assert _check_enforcement(ctx) is None++ assert ctx.blocker_signal is None+ assert ctx.turn_halt is None+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.GRANTED+ assert any(+ event.fingerprint == "output_contract_actuation>code_authoring_guardrail_churn"+ for event in ctx.gate_precedence_conflict_events+ )+++def test_no_progress_backstop_yields_to_live_ladder() -> None:+ ctx = _fresh_context()+ ctx.consecutive_no_progress_interaction_count = MAX_NO_PROGRESS_INTERACTION_ATTEMPTS+ _grant_output_contract_ladder(ctx)++ assert _check_enforcement(ctx) is None++ assert ctx.blocker_signal is None+ assert ctx.turn_halt is None+ assert any(+ event.fingerprint == "output_contract_actuation>loop_detected" for event in ctx.gate_precedence_conflict_events+ )+++def test_register_no_progress_click_yields_to_live_ladder() -> None:+ ctx = _fresh_context()+ ctx.consecutive_no_progress_interaction_count = MAX_NO_PROGRESS_INTERACTION_ATTEMPTS - 1+ _grant_output_contract_ladder(ctx)++ register_no_progress_interaction_click(ctx, outcome="failed")++ assert ctx.consecutive_no_progress_interaction_count == MAX_NO_PROGRESS_INTERACTION_ATTEMPTS+ assert ctx.blocker_signal is None+++def test_grant_plus_ceiling_reject_in_one_call_reaches_stalled_terminal_not_churn_reply() -> None:+ ctx = _fresh_context()+ ctx.code_authoring_guardrail_reject_count = MAX_CODE_AUTHORING_GUARDRAIL_REJECTS - 1+ _grant_output_contract_ladder(ctx)+ ctx.output_contract_pending_run_evidence["sig_a"] = ["output.confirmation_number"]++ _record_code_authoring_guardrail_reject(ctx)+ assert _check_enforcement(ctx) is None+ assert ctx.blocker_signal is None+ assert ctx.turn_halt is None++ halt = expire_output_contract_ladder_at_turn_end(ctx)++ assert halt is not None+ assert ctx.turn_halt is halt+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.EXPIRED+ signal = ctx.blocker_signal+ assert isinstance(signal, CopilotToolBlockerSignal)+ assert signal.internal_reason_code == ADVISORY_DISPATCH_STALLED_REASON_CODEdiff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.pyindex 3511e7137..db616681d 100644--- a/tests/unit/test_copilot_enforcement_pruning.py+++ b/tests/unit/test_copilot_enforcement_pruning.py@@ -88,6 +88,7 @@ from skyvern.forge.sdk.copilot.tools.scouting import ()from skyvern.forge.sdk.copilot.turn_halt import stash_turn_halt_from_blocker_signalfrom skyvern.forge.sdk.copilot.turn_intent import RequiredContextKey, TurnIntent, TurnIntentAuthority, TurnIntentMode+from skyvern.forge.sdk.copilot.turn_ownership import TurnClaimant, current_turn_ownerfrom skyvern.forge.sdk.copilot.verification_evidence import WorkflowVerificationEvidencefrom tests.unit.conftest import make_copilot_context@@ -149,6 +150,13 @@ class _Ctx:self.reached_download_target: ReachedDownloadTarget | None = Noneself.author_time_gate_ablation_events = []self.request_policy = None+ self.blocker_signal = None+ self.blocker_signal_claimant = None+ self.turn_halt = None+ self.turn_ownership = None+ self.gate_precedence_conflict_events: list[object] = []+ self.output_contract_actuation_by_signature: dict[str, object] = {}+ self.output_contract_actuation_count_by_signature: dict[str, int] = {}class TestSynthesizedOfferPersistenceGate:@@ -388,6 +396,34 @@ class TestSynthesizedOfferPersistenceGate:assert isinstance(click_signal, CopilotToolBlockerSignal)assert click_signal.internal_reason_code == SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE+ def test_actuation_obligation_fill_admission_registers_precedence_claim(self) -> None:+ ctx = _Ctx()+ ctx.turn_intent = TurnIntent(+ mode=TurnIntentMode.BUILD,+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),+ required_context={RequiredContextKey.BROWSER_STATE},+ )+ ctx.request_policy = RequestPolicy(+ completion_criteria=[+ CompletionCriterion(+ id="form-submit",+ outcome="form fields are filled",+ kind="terminal_action",+ terminal_action_family="form",+ )+ ],+ )+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER+ ctx.synthesized_block_offered = True+ ctx.synthesized_block_offered_trajectory_len = 1+ ctx.scout_trajectory = [{"tool_name": "click", "selector": "button.start", "accessible_name": "Start"}]++ assert synthesized_block_persistence_signal(ctx, "type_text") is None++ assert ctx.turn_ownership is not None+ assert TurnClaimant.ACTUATION_OBLIGATION_FILL in ctx.turn_ownership.claims+ assert current_turn_owner(ctx) is None+def test_actuation_obligation_admits_required_fill_tool_for_method_mandated_run_contract(self) -> None:ctx = _Ctx()ctx.turn_intent = TurnIntent(@@ -2599,6 +2635,22 @@ class TestScoutOutputCoverageGate:)assert event.log_only is True+ def test_steer_yields_to_live_ladder_and_one_shot_key_survives(self) -> None:+ ctx = self._authoring_ctx(_criterion("output.document_name", "the order status document name is captured"))+ ctx.update_workflow_called = True+ ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("output.document_name")+ consume_uncovered_output_reopen_event(ctx)+ ctx.output_contract_actuation_by_signature = {"sig_a": OutputContractAdvisoryState.GRANTED}+ ctx.output_contract_actuation_count_by_signature = {}++ assert uncovered_output_reject_scout_steer_signal(ctx, "update_and_run_blocks") is None+ assert ctx.uncovered_output_rescout_steer_key is None++ ctx.output_contract_actuation_by_signature = {"sig_a": OutputContractAdvisoryState.CONSUMED}+ steer = uncovered_output_reject_scout_steer_signal(ctx, "update_and_run_blocks")+ assert isinstance(steer, CopilotToolBlockerSignal)+ assert ctx.uncovered_output_rescout_steer_key is not None+def test_steer_inert_without_reopen_latch(self) -> None:ctx = self._authoring_ctx(_criterion("output.document_name", "the order status document name is captured"))ctx.latest_recorded_build_test_outcome = _author_time_reject_outcome("output.document_name")@@ -3055,6 +3107,16 @@ class TestCredentialScoutReopen:ctx.synthesized_block_reopened_for_credential_scout = Trueassert synthesized_block_persistence_signal(ctx, "evaluate") is None+ def test_reopen_admission_registers_precedence_claim(self) -> None:+ ctx = self._offered_complete_ctx()+ ctx.synthesized_block_reopened_for_credential_scout = True++ assert synthesized_block_persistence_signal(ctx, "evaluate") is None++ assert ctx.turn_ownership is not None+ assert TurnClaimant.CREDENTIAL_SCOUT_REOPEN in ctx.turn_ownership.claims+ assert current_turn_owner(ctx) is None+def test_reopen_reopens_offer_refresh_window(self) -> None:ctx = self._offered_complete_ctx()ctx.update_workflow_called = Truediff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.pyindex 014be0dd5..b46062361 100644--- a/tests/unit/test_copilot_hooks.py+++ b/tests/unit/test_copilot_hooks.py@@ -31,6 +31,11 @@ class _FakeContext:total_tokens_used: int | None = Nonelast_artifact_health_blocker_reason: str | None = Nonecompletion_verification_result: Any = None+ turn_ownership: Any = None+ blocker_signal_claimant: Any = None+ gate_precedence_conflict_events: list[Any] = field(default_factory=list)+ output_contract_actuation_by_signature: dict[str, Any] = field(default_factory=dict)+ output_contract_actuation_count_by_signature: dict[str, Any] = field(default_factory=dict)# `on_tool_end(context, agent, tool, result)` only reads `tool` and `result`;@@ -497,6 +502,9 @@ class TestMCPFailedStepLoopDetection:ctx = MagicMock()ctx.consecutive_tool_tracker = []ctx.failed_tool_step_tracker = {}+ ctx.turn_ownership = None+ ctx.blocker_signal_claimant = None+ ctx.gate_precedence_conflict_events = []server = SkyvernOverlayMCPServer(transport=MagicMock(),overlays={"click": SchemaOverlay(post_hook=raising_post_hook)},@@ -557,6 +565,9 @@ class TestMCPFailedStepLoopDetection:ctx = MagicMock()ctx.consecutive_tool_tracker = []ctx.failed_tool_step_tracker = {}+ ctx.turn_ownership = None+ ctx.blocker_signal_claimant = None+ ctx.gate_precedence_conflict_events = []server = SkyvernOverlayMCPServer(transport=MagicMock(),overlays={"get_browser_screenshot": SchemaOverlay(requires_browser=True)},@@ -725,6 +736,9 @@ class TestMCPFailedStepLoopDetection:ctx = MagicMock()ctx.consecutive_tool_tracker = []ctx.failed_tool_step_tracker = {}+ ctx.turn_ownership = None+ ctx.blocker_signal_claimant = None+ ctx.gate_precedence_conflict_events = []client = FakeClient()server = SkyvernOverlayMCPServer(transport=MagicMock(),diff --git a/tests/unit/test_copilot_output_contract_actuation.py b/tests/unit/test_copilot_output_contract_actuation.pyindex b1c0743cd..96754e65b 100644--- a/tests/unit/test_copilot_output_contract_actuation.py+++ b/tests/unit/test_copilot_output_contract_actuation.py@@ -16,6 +16,7 @@ import pytestfrom skyvern.config import settingsfrom skyvern.forge.sdk.copilot import enforcementfrom skyvern.forge.sdk.copilot.blocker_signal import (+ CopilotToolBlockerSignal,assert_clean_user_facing_text,build_output_source_unobservable_blocker_signal,)@@ -40,6 +41,11 @@ from skyvern.forge.sdk.copilot.runtime import ()from skyvern.forge.sdk.copilot.tools import workflow_update as wufrom skyvern.forge.sdk.copilot.turn_halt import TurnHaltKind, turn_halt_from_blocker_signal+from skyvern.forge.sdk.copilot.turn_ownership import (+ TurnClaimant,+ claim_and_stash_blocker_signal,+ current_turn_owner,+)from tests.unit.copilot_test_helpers import make_copilot_ctx_ALL_SPLIT_BLOCKERS = [@@ -519,6 +525,9 @@ _FINGERPRINT = "fp_stage_topology"def _advisory_ctx() -> SimpleNamespace:return SimpleNamespace(+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],output_contract_reject_count_by_signature={},output_contract_imposed_since_last_reject_by_signature={},output_contract_armed_directive_fingerprint_by_signature={},@@ -736,6 +745,95 @@ def test_log_only_metadata_preflight_skips_run_attemptable_without_advisory(assert ctx.output_contract_reject_count_by_signature == {}+def _genuine_terminal_signal() -> CopilotToolBlockerSignal:+ return CopilotToolBlockerSignal(+ blocker_kind="tool_error",+ agent_steering_text="stop",+ user_facing_reason="I can't get past this page, so I'll stop here.",+ recovery_hint="report_blocker_to_user",+ cleared_by_tools=frozenset(),+ renders_final_reply=True,+ internal_reason_code="probable_site_block_stop",+ blocked_tool="update_workflow",+ )+++def test_metadata_preflight_yields_to_live_ladder_and_records_conflict() -> None:+ ctx = make_copilot_ctx()+ ctx.output_contract_actuation_by_signature["sig_live"] = OutputContractAdvisoryState.GRANTED++ assert wu._metadata_preflight_reject_yields_to_ladder(ctx) is True+ assert any(+ event.owner == "output_contract_actuation" and event.yielded == "metadata_run_preflight_reject"+ for event in ctx.gate_precedence_conflict_events+ )+++def test_metadata_preflight_does_not_yield_without_a_live_grant() -> None:+ ctx = make_copilot_ctx()++ assert wu._metadata_preflight_reject_yields_to_ladder(ctx) is False+ assert ctx.gate_precedence_conflict_events == []+++def test_metadata_preflight_does_not_yield_during_ordinary_reject_without_a_grant() -> None:+ ctx = make_copilot_ctx()+ ctx.output_contract_actuation_count_by_signature["sig_landed"] = 1+ assert output_contract_ladder_unresolved(ctx) is True++ assert wu._metadata_preflight_reject_yields_to_ladder(ctx) is False+++def test_metadata_preflight_does_not_yield_to_a_genuine_terminal_owner() -> None:+ ctx = make_copilot_ctx()+ ctx.output_contract_actuation_by_signature["sig_live"] = OutputContractAdvisoryState.GRANTED+ terminal = _genuine_terminal_signal()+ claim_and_stash_blocker_signal(ctx, TurnClaimant.GENUINELY_TERMINAL, terminal)+ ctx.turn_halt = turn_halt_from_blocker_signal(terminal, source="test")+ assert current_turn_owner(ctx).claimant is TurnClaimant.GENUINELY_TERMINAL++ assert wu._metadata_preflight_reject_yields_to_ladder(ctx) is False+++def test_metadata_preflight_reject_returns_none_at_call_site_while_ladder_owns(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = make_copilot_ctx()+ ctx.output_contract_actuation_by_signature["sig_live"] = OutputContractAdvisoryState.GRANTED+ monkeypatch.setattr(+ wu,+ "_recorded_outcome_convergence_reject",+ lambda *args, **kwargs: wu._ConvergenceReject("sig_target", "frontier_unchanged", False),+ )+ monkeypatch.setattr(wu, "_workflow_yaml_code_blocks_by_label", lambda *args: {})+ monkeypatch.setattr(wu, "_record_author_time_reject_outcome", lambda *args, **kwargs: None)+ monkeypatch.setattr(wu, "_record_code_authoring_guardrail_reject", lambda *args, **kwargs: None)++ result = wu._metadata_contract_run_preflight_reject(ctx, "workflow: yaml", {})++ assert result is None+ assert any(event.yielded == "metadata_run_preflight_reject" for event in ctx.gate_precedence_conflict_events)+++def test_metadata_preflight_reject_still_rejects_without_a_live_ladder(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = make_copilot_ctx()+ monkeypatch.setattr(+ wu,+ "_recorded_outcome_convergence_reject",+ lambda *args, **kwargs: wu._ConvergenceReject("sig_target", "frontier_unchanged", False),+ )+ monkeypatch.setattr(wu, "_workflow_yaml_code_blocks_by_label", lambda *args: {})+ monkeypatch.setattr(wu, "_record_author_time_reject_outcome", lambda *args, **kwargs: None)+ monkeypatch.setattr(wu, "_record_code_authoring_guardrail_reject", lambda *args, **kwargs: None)++ result = wu._metadata_contract_run_preflight_reject(ctx, "workflow: yaml", {})++ assert result is not None+ assert result["ok"] is False++def test_credential_scout_submit_gate_still_blocks_with_author_time_log_only(monkeypatch: pytest.MonkeyPatch,) -> None:diff --git a/tests/unit/test_copilot_recorded_outcome_grounding.py b/tests/unit/test_copilot_recorded_outcome_grounding.pyindex 13f7b81f0..7b344a8f4 100644--- a/tests/unit/test_copilot_recorded_outcome_grounding.py+++ b/tests/unit/test_copilot_recorded_outcome_grounding.py@@ -767,6 +767,11 @@ def test_convergence_reject_uncrossable_frontier_commits_early_terminal() -> Nonblocker_signal=None,turn_halt=None,consecutive_non_converging_repair_count=2,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ output_contract_actuation_by_signature={},+ output_contract_actuation_count_by_signature={},)decision = _recorded_outcome_convergence_reject(@@ -920,6 +925,11 @@ def test_early_terminal_renders_typed_final_reply_and_preserves_draft() -> None:blocker_signal=None,turn_halt=None,consecutive_non_converging_repair_count=3,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ output_contract_actuation_by_signature={},+ output_contract_actuation_count_by_signature={},)_commit_recorded_outcome_early_terminal(ctx)diff --git a/tests/unit/test_copilot_streaming_adapter.py b/tests/unit/test_copilot_streaming_adapter.pyindex a8c6f2dfd..b470bf4be 100644--- a/tests/unit/test_copilot_streaming_adapter.py+++ b/tests/unit/test_copilot_streaming_adapter.py@@ -214,7 +214,13 @@ async def test_stream_to_sse_keeps_running_after_client_disconnect() -> None:stream.is_disconnected = AsyncMock(return_value=True)stream.send = AsyncMock(return_value=True)- ctx = SimpleNamespace(last_artifact_health_blocker_reason=None, completion_verification_result=None)+ ctx = SimpleNamespace(+ last_artifact_health_blocker_reason=None,+ completion_verification_result=None,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ )await stream_to_sse(result, stream, ctx)@@ -246,7 +252,13 @@ async def test_tool_call_sse_uses_product_safe_activity_label() -> None:stream = MagicMock()stream.is_disconnected = AsyncMock(return_value=False)stream.send = _send- ctx = SimpleNamespace(last_artifact_health_blocker_reason=None, completion_verification_result=None)+ ctx = SimpleNamespace(+ last_artifact_health_blocker_reason=None,+ completion_verification_result=None,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ )await stream_to_sse(result, stream, ctx)@@ -284,7 +296,13 @@ async def test_stream_to_sse_propagates_cancelled_error() -> None:stream.is_disconnected = AsyncMock(return_value=False)stream.send = AsyncMock(return_value=True)- ctx = SimpleNamespace(last_artifact_health_blocker_reason=None, completion_verification_result=None)+ ctx = SimpleNamespace(+ last_artifact_health_blocker_reason=None,+ completion_verification_result=None,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ )with pytest.raises(asyncio.CancelledError):await stream_to_sse(result, stream, ctx)@@ -422,7 +440,13 @@ async def test_tool_result_sse_summary_translates_loop_detected_failure() -> Nonstream.is_disconnected = AsyncMock(return_value=False)stream.send = _send- ctx = SimpleNamespace(last_artifact_health_blocker_reason=None, completion_verification_result=None)+ ctx = SimpleNamespace(+ last_artifact_health_blocker_reason=None,+ completion_verification_result=None,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ )await stream_to_sse(result, stream, ctx)@@ -485,6 +509,11 @@ async def test_tool_result_sse_uses_latest_blocker_signal_for_activity_surface()tool_blocker_signals=[signal],last_artifact_health_blocker_reason=None,completion_verification_result=None,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ output_contract_actuation_by_signature={},+ output_contract_actuation_count_by_signature={},)await stream_to_sse(result, stream, ctx)@@ -552,6 +581,11 @@ async def test_stream_to_sse_cancels_and_stops_on_terminal_turn_halt() -> None:tool_blocker_signals=[signal],last_artifact_health_blocker_reason=None,completion_verification_result=None,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ output_contract_actuation_by_signature={},+ output_contract_actuation_count_by_signature={},)with pytest.raises(CopilotTurnHalt):@@ -587,7 +621,13 @@ async def test_stream_to_sse_raises_and_cancels_on_repeated_unrecoverable_tool_estream = MagicMock()stream.is_disconnected = AsyncMock(return_value=False)stream.send = AsyncMock(return_value=True)- ctx = SimpleNamespace(last_artifact_health_blocker_reason=None, completion_verification_result=None)+ ctx = SimpleNamespace(+ last_artifact_health_blocker_reason=None,+ completion_verification_result=None,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ )with pytest.raises(CopilotUnrecoverableToolError):await stream_to_sse(result, stream, ctx)@@ -631,7 +671,13 @@ async def test_tool_result_sse_summary_drops_click_selector_on_success() -> Nonestream.is_disconnected = AsyncMock(return_value=False)stream.send = _send- ctx = SimpleNamespace(last_artifact_health_blocker_reason=None, completion_verification_result=None)+ ctx = SimpleNamespace(+ last_artifact_health_blocker_reason=None,+ completion_verification_result=None,+ turn_ownership=None,+ blocker_signal_claimant=None,+ gate_precedence_conflict_events=[],+ )await stream_to_sse(result, stream, ctx)diff --git a/tests/unit/test_copilot_tool_loop_error_block_running.py b/tests/unit/test_copilot_tool_loop_error_block_running.pyindex f7e149bf2..a592fba8c 100644--- a/tests/unit/test_copilot_tool_loop_error_block_running.py+++ b/tests/unit/test_copilot_tool_loop_error_block_running.py@@ -49,6 +49,9 @@ def _ctx(**overrides: Any) -> Any:"output_contract_actuation_count_by_signature": {},"output_contract_armed_directive_fingerprint_by_signature": {},"output_contract_dispatch_reopened_by_signature": {},+ "turn_ownership": None,+ "blocker_signal_claimant": None,+ "gate_precedence_conflict_events": [],}base.update(overrides)return SimpleNamespace(**base)diff --git a/tests/unit/test_copilot_turn_halt.py b/tests/unit/test_copilot_turn_halt.pyindex 696071842..4b98633b8 100644--- a/tests/unit/test_copilot_turn_halt.py+++ b/tests/unit/test_copilot_turn_halt.py@@ -19,13 +19,17 @@ from skyvern.forge.sdk.copilot.run_outcome import (RecordedRunOutcome,)from skyvern.forge.sdk.copilot.turn_halt import (+ ADVISORY_DISPATCH_STALLED_REASON_CODE,CopilotTurnHalt,TurnHaltKind,+ expire_output_contract_ladder_at_turn_end,raise_if_turn_halt,stash_repair_ceiling_turn_halt,stash_turn_halt_from_blocker_signal,turn_halt_from_blocker_signal,)+from skyvern.forge.sdk.copilot.turn_ownership import TurnClaimant, claim_and_stash_blocker_signal+from tests.unit.conftest import make_copilot_contextdef _signal(@@ -83,8 +87,25 @@ def test_terminal_blockers_map_to_halts(signal: CopilotToolBlockerSignal, expectassert halt.blocker_signal is signal+def _halt_ctx(**overrides: object) -> SimpleNamespace:+ fields: dict[str, object] = {+ "turn_halt": None,+ "blocker_signal": None,+ "blocker_signal_claimant": None,+ "turn_ownership": None,+ "gate_precedence_conflict_events": [],+ "latest_tool_blocker_signal": None,+ "tool_blocker_signals": [],+ "output_contract_actuation_by_signature": {},+ "output_contract_actuation_count_by_signature": {},+ "output_contract_pending_run_evidence": {},+ }+ fields.update(overrides)+ return SimpleNamespace(**fields)++def test_stash_and_raise_turn_halt_sets_context_once() -> None:- ctx = SimpleNamespace(turn_halt=None)+ ctx = _halt_ctx()signal = _signal(blocker_kind="loop_detected", internal_reason_code="loop_detected_repeated_failed_step")halt = stash_turn_halt_from_blocker_signal(ctx, signal, source="stream")@@ -97,10 +118,7 @@ def test_stash_and_raise_turn_halt_sets_context_once() -> None:def test_enforcement_backstop_converts_existing_terminal_blocker_signal() -> None:- ctx = SimpleNamespace(- turn_halt=None,- latest_tool_blocker_signal=None,- blocker_signal=None,+ ctx = _halt_ctx(last_artifact_health_blocker_reason=None,completion_verification_result=None,)@@ -115,7 +133,7 @@ def test_enforcement_backstop_converts_existing_terminal_blocker_signal() -> Nondef test_terminal_challenge_halt_preserves_signal_extra() -> None:- ctx = SimpleNamespace(turn_halt=None)+ ctx = _halt_ctx()signal = _signal(internal_reason_code=TERMINAL_CHALLENGE_BLOCKER_REASON_CODE,extra={@@ -329,7 +347,7 @@ def _consume_ctx(latest_tool_blocker_signal: CopilotToolBlockerSignal | None = None,tool_blocker_signals: list[CopilotToolBlockerSignal] | None = None,) -> SimpleNamespace:- return SimpleNamespace(+ return _halt_ctx(turn_halt=turn_halt,blocker_signal=blocker_signal,latest_tool_blocker_signal=latest_tool_blocker_signal,@@ -339,7 +357,7 @@ def _consume_ctx(def test_verified_outcome_suppresses_and_consumes_involuntary_halt() -> None:signal = _involuntary_repair_ceiling_signal()- halt = stash_repair_ceiling_turn_halt(SimpleNamespace(turn_halt=None), signal, consecutive_identical_repair_count=3)+ halt = stash_repair_ceiling_turn_halt(_halt_ctx(), signal, consecutive_identical_repair_count=3)ctx = _consume_ctx(turn_halt=halt,blocker_signal=signal,@@ -381,7 +399,7 @@ def test_verified_outcome_does_not_suppress_voluntary_terminal_challenge() -> Nodef test_verified_outcome_does_not_clear_voluntary_blocker_when_involuntary_absent() -> None:challenge_signal = _signal(internal_reason_code=ACTIVE_RUN_TERMINAL_EVIDENCE_REASON_CODE)loop_halt = stash_turn_halt_from_blocker_signal(- SimpleNamespace(turn_halt=None),+ _halt_ctx(),_signal(blocker_kind="loop_detected", internal_reason_code="loop_detected_repeated_failed_step"),source="hook",)@@ -455,11 +473,7 @@ def test_default_verified_argument_is_fail_safe_and_raises() -> None:def _output_contract_ctx(*, granted: bool) -> SimpleNamespace:states = {"sig_a": OutputContractAdvisoryState.GRANTED} if granted else {}- return SimpleNamespace(- turn_halt=None,- output_contract_actuation_by_signature=states,- output_contract_actuation_count_by_signature={},- )+ return _halt_ctx(output_contract_actuation_by_signature=states)def test_loop_detected_deferred_while_output_contract_ladder_unresolved() -> None:@@ -503,13 +517,8 @@ def test_active_terminal_challenge_promotes_while_ladder_unresolved() -> None:def _defer_ledger_ctx() -> SimpleNamespace:- return SimpleNamespace(- turn_halt=None,- blocker_signal=None,- latest_tool_blocker_signal=None,- tool_blocker_signals=[],+ return _halt_ctx(output_contract_actuation_by_signature={"sig_a": OutputContractAdvisoryState.GRANTED},- output_contract_actuation_count_by_signature={},output_contract_run_output_observed_by_signature={},output_contract_page_extraction_imposed_by_signature={},output_contract_pending_run_evidence={"sig_a": ["output.confirmation_number"]},@@ -517,11 +526,7 @@ def _defer_ledger_ctx() -> SimpleNamespace:def _defer_count_ledger_ctx() -> SimpleNamespace:- return SimpleNamespace(- turn_halt=None,- blocker_signal=None,- latest_tool_blocker_signal=None,- tool_blocker_signals=[],+ return _halt_ctx(output_contract_actuation_by_signature={"sig_a": OutputContractAdvisoryState.UNUSED},output_contract_actuation_count_by_signature={"sig_a": 1},output_contract_run_output_observed_by_signature={},@@ -574,3 +579,94 @@ def test_defer_countonly_ladder_reaches_a_terminal_within_two_stalled_signals()if ctx.turn_halt is not None:breakassert ctx.turn_halt is not None+++def test_turn_end_expiry_transitions_granted_and_emits_stalled_terminal() -> None:+ ctx = make_copilot_context()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ ctx.output_contract_pending_run_evidence["sig_a"] = ["output.confirmation_number"]++ halt = expire_output_contract_ladder_at_turn_end(ctx)++ assert halt is not None+ assert halt.kind == TurnHaltKind.OUTPUT_SOURCE_UNOBSERVABLE+ assert ctx.turn_halt is halt+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.EXPIRED+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == ADVISORY_DISPATCH_STALLED_REASON_CODE+ assert ctx.blocker_signal.renders_final_reply is True+++def test_turn_end_expiry_noop_without_live_grant() -> None:+ ctx = make_copilot_context()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.CONSUMED++ assert expire_output_contract_ladder_at_turn_end(ctx) is None+ assert ctx.turn_halt is None+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.CONSUMED+++def test_turn_end_expiry_keeps_existing_halt_but_expires_grant() -> None:+ ctx = make_copilot_context()+ terminal_signal = _signal(internal_reason_code="probable_site_block_stop")+ existing = stash_turn_halt_from_blocker_signal(ctx, terminal_signal, source="test")+ assert existing is not None+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED++ assert expire_output_contract_ladder_at_turn_end(ctx) is None+ assert ctx.turn_halt is existing+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.EXPIRED+++def test_mid_turn_expiry_keeps_granted_early_return() -> None:+ ctx = make_copilot_context()+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+ stash_turn_halt_from_blocker_signal(ctx, _loop_signal(), source="enforcement_backstop")+ stash_turn_halt_from_blocker_signal(ctx, _loop_signal(), source="enforcement_backstop")++ assert ctx.turn_halt is None+ assert ctx.output_contract_actuation_by_signature["sig_a"] == OutputContractAdvisoryState.GRANTED+++def test_terminal_stash_choke_point_claims_genuinely_terminal() -> None:+ ctx = make_copilot_context()+ signal = _signal(internal_reason_code="probable_site_block_stop")++ stash_turn_halt_from_blocker_signal(ctx, signal, source="test")++ assert ctx.turn_ownership is not None+ assert TurnClaimant.GENUINELY_TERMINAL in ctx.turn_ownership.claims+++def test_repair_ceiling_stash_choke_point_claims_genuinely_terminal() -> None:+ ctx = make_copilot_context()+ signal = _involuntary_repair_ceiling_signal()++ stash_repair_ceiling_turn_halt(ctx, signal, consecutive_identical_repair_count=3)++ assert ctx.turn_ownership is not None+ assert TurnClaimant.GENUINELY_TERMINAL in ctx.turn_ownership.claims+++def test_raise_if_turn_halt_retires_halt_outranked_by_live_ladder() -> None:+ ctx = make_copilot_context()+ loop_signal = _signal(blocker_kind="loop_detected", internal_reason_code="loop_detected_generic")+ claim_and_stash_blocker_signal(ctx, TurnClaimant.LOOP_DETECTED, loop_signal)+ stash_turn_halt_from_blocker_signal(ctx, loop_signal, source="test")+ assert ctx.turn_halt is not None+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED++ raise_if_turn_halt(ctx)++ assert ctx.turn_halt is None+ assert any(event.site == "turn_halt" for event in ctx.gate_precedence_conflict_events)+++def test_raise_if_turn_halt_still_raises_genuinely_terminal_over_live_ladder() -> None:+ ctx = make_copilot_context()+ terminal_signal = _signal(internal_reason_code="probable_site_block_stop")+ stash_turn_halt_from_blocker_signal(ctx, terminal_signal, source="test")+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED++ with pytest.raises(CopilotTurnHalt):+ raise_if_turn_halt(ctx)diff --git a/tests/unit/test_copilot_turn_ownership.py b/tests/unit/test_copilot_turn_ownership.pynew file mode 100644index 000000000..5f800c65a--- /dev/null+++ b/tests/unit/test_copilot_turn_ownership.py@@ -0,0 +1,418 @@+from __future__ import annotations++from skyvern.forge.sdk.copilot.blocker_signal import (+ GENUINELY_TERMINAL_BLOCKER_REASON_CODES,+ SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE,+ CopilotToolBlockerSignal,+ stash_blocker_signal,+)+from skyvern.forge.sdk.copilot.context import CopilotContext+from skyvern.forge.sdk.copilot.output_contracts import OutputContractAdvisoryState+from skyvern.forge.sdk.copilot.turn_halt import (+ retire_outranked_turn_halt,+ stash_turn_halt_from_blocker_signal,+)+from skyvern.forge.sdk.copilot.turn_ownership import (+ _PRECEDENCE_ORDER,+ CLAIMANT_REASON_CODE_FAMILIES,+ ClaimOutcome,+ TurnClaimant,+ blocker_signal_render_allowed,+ claim_and_stash_blocker_signal,+ claim_turn,+ claimant_for_blocker_signal,+ current_turn_owner,+ emit_blocker_signal_payload,+ release_turn_claim,+)+from tests.unit.conftest import make_copilot_context+++def _signal(+ reason: str,+ *,+ blocker_kind: str = "loop_detected",+ renders_final_reply: bool = True,+) -> CopilotToolBlockerSignal:+ return CopilotToolBlockerSignal(+ blocker_kind=blocker_kind, # type: ignore[arg-type]+ agent_steering_text="steering",+ user_facing_reason="I could not continue this step.",+ recovery_hint="report_blocker_to_user",+ cleared_by_tools=frozenset(),+ renders_final_reply=renders_final_reply,+ internal_reason_code=reason,+ blocked_tool="update_workflow",+ )+++def _churn_signal() -> CopilotToolBlockerSignal:+ return _signal("code_authoring_guardrail_churn")+++def _grant_ladder(ctx: CopilotContext) -> None:+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.GRANTED+++def _resolve_ladder(ctx: CopilotContext) -> None:+ ctx.output_contract_actuation_by_signature["sig_a"] = OutputContractAdvisoryState.CONSUMED+ ctx.output_contract_actuation_count_by_signature.clear()+++def _conflict_fingerprints(ctx: CopilotContext) -> list[str]:+ return [event.fingerprint for event in ctx.gate_precedence_conflict_events]+++def test_two_claimants_one_owner_loser_recorded() -> None:+ ctx = make_copilot_context()+ signal = _churn_signal()+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, signal) is not None+ assert ctx.blocker_signal is signal++ loop_signal = _signal("loop_detected_generic")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.LOOP_DETECTED, loop_signal) is None++ owner = current_turn_owner(ctx)+ assert owner is not None+ assert owner.claimant is TurnClaimant.CODE_AUTHORING_CHURN+ assert ctx.blocker_signal is signal+ assert _conflict_fingerprints(ctx) == ["code_authoring_guardrail_churn>loop_detected"]+++def test_r31_three_way_contradiction_yields_single_owner() -> None:+ ctx = make_copilot_context()+ _grant_ladder(ctx)+ claim_turn(ctx, TurnClaimant.OUTPUT_CONTRACT_ACTUATION)++ rescout = claim_turn(ctx, TurnClaimant.UNCOVERED_OUTPUT_RESCOUT_STEER)+ persistence_payload = claim_and_stash_blocker_signal(+ ctx,+ TurnClaimant.SYNTHESIZED_BLOCK_PERSISTENCE_FORCE,+ _signal(SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE, blocker_kind="tool_error", renders_final_reply=False),+ )++ assert rescout is ClaimOutcome.YIELDED+ assert persistence_payload is None+ assert ctx.blocker_signal is None+ owner = current_turn_owner(ctx)+ assert owner is not None+ assert owner.claimant is TurnClaimant.OUTPUT_CONTRACT_ACTUATION+ assert sorted(_conflict_fingerprints(ctx)) == [+ "output_contract_actuation>synthesized_block_persistence_force",+ "output_contract_actuation>uncovered_output_rescout_steer",+ ]+++def test_precedence_order_covers_every_claimant_once() -> None:+ assert len(set(_PRECEDENCE_ORDER)) == len(_PRECEDENCE_ORDER)+ assert set(_PRECEDENCE_ORDER) == set(TurnClaimant)+ assert set(CLAIMANT_REASON_CODE_FAMILIES) == set(TurnClaimant)+++def test_rescout_outranks_grounding_and_persistence_per_cascade_order() -> None:+ ctx = make_copilot_context()+ assert claim_turn(ctx, TurnClaimant.RECORDED_OUTCOME_GROUNDING) is ClaimOutcome.OWNED+ assert claim_turn(ctx, TurnClaimant.UNCOVERED_OUTPUT_RESCOUT_STEER) is ClaimOutcome.OWNED++ ctx2 = make_copilot_context()+ assert claim_and_stash_blocker_signal(+ ctx2,+ TurnClaimant.SYNTHESIZED_BLOCK_PERSISTENCE_FORCE,+ _signal(SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE, blocker_kind="tool_error", renders_final_reply=False),+ )+ assert claim_turn(ctx2, TurnClaimant.UNCOVERED_OUTPUT_RESCOUT_STEER) is ClaimOutcome.OWNED+++def test_grounding_outranks_persistence_per_nested_exception() -> None:+ ctx = make_copilot_context()+ persisted = claim_and_stash_blocker_signal(+ ctx,+ TurnClaimant.SYNTHESIZED_BLOCK_PERSISTENCE_FORCE,+ _signal(SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE, blocker_kind="tool_error", renders_final_reply=False),+ )+ assert persisted is not None+ grounding = claim_and_stash_blocker_signal(+ ctx,+ TurnClaimant.RECORDED_OUTCOME_GROUNDING,+ _signal(+ "recorded_outcome_grounding_required", blocker_kind="missing_required_context", renders_final_reply=False+ ),+ )+ assert grounding is not None+ assert ctx.blocker_signal is not None+ assert ctx.blocker_signal.internal_reason_code == "recorded_outcome_grounding_required"+ assert "recorded_outcome_grounding>synthesized_block_persistence_force" in _conflict_fingerprints(ctx)+++def test_genuinely_terminal_family_is_the_shared_blocker_signal_set() -> None:+ assert CLAIMANT_REASON_CODE_FAMILIES[TurnClaimant.GENUINELY_TERMINAL] is GENUINELY_TERMINAL_BLOCKER_REASON_CODES+++def test_claimant_table_resolves_signals_for_both_cascades() -> None:+ assert claimant_for_blocker_signal(_churn_signal()) is TurnClaimant.CODE_AUTHORING_CHURN+ assert (+ claimant_for_blocker_signal(_signal("credential_priority_authoring_churn"))+ is TurnClaimant.CREDENTIAL_PRIORITY_CHURN+ )+ assert claimant_for_blocker_signal(_signal("loop_detected_generic")) is TurnClaimant.LOOP_DETECTED+ assert (+ claimant_for_blocker_signal(_signal("probable_site_block_stop", blocker_kind="tool_error"))+ is TurnClaimant.GENUINELY_TERMINAL+ )+ assert claimant_for_blocker_signal(_signal("tool_error_repeated_action_abort", blocker_kind="tool_error")) is None+++def test_same_claimant_reclaim_is_first_wins_and_widens_metadata() -> None:+ ctx = make_copilot_context()+ assert claim_turn(ctx, TurnClaimant.CODE_AUTHORING_CHURN) is ClaimOutcome.OWNED+ assert claim_turn(ctx, TurnClaimant.CODE_AUTHORING_CHURN, renders_final_reply=True) is ClaimOutcome.OWNED+ assert ctx.turn_ownership is not None+ claim = ctx.turn_ownership.claims[TurnClaimant.CODE_AUTHORING_CHURN]+ assert claim.renders_final_reply is True+ assert ctx.gate_precedence_conflict_events == []+++def test_stale_owner_releases_when_ladder_resolves() -> None:+ ctx = make_copilot_context()+ _grant_ladder(ctx)+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, _churn_signal()) is None++ _resolve_ladder(ctx)+ assert current_turn_owner(ctx) is None+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, _churn_signal()) is not None+ owner = current_turn_owner(ctx)+ assert owner is not None+ assert owner.claimant is TurnClaimant.CODE_AUTHORING_CHURN+++def test_stronger_owned_claim_replaces_held_signal() -> None:+ ctx = make_copilot_context()+ loop_signal = _signal("loop_detected_generic")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.LOOP_DETECTED, loop_signal) is not None+ assert ctx.blocker_signal is loop_signal++ terminal_signal = _signal("probable_site_block_stop", blocker_kind="tool_error")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.GENUINELY_TERMINAL, terminal_signal) is not None+ assert ctx.blocker_signal is terminal_signal+++def test_genuinely_terminal_held_signal_is_never_replaced() -> None:+ ctx = make_copilot_context()+ terminal_signal = _signal("probable_site_block_stop", blocker_kind="tool_error")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.GENUINELY_TERMINAL, terminal_signal) is not None++ churn_payload = claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, _churn_signal())+ assert churn_payload is None+ assert ctx.blocker_signal is terminal_signal+++def test_plain_stash_replacement_clears_stale_association() -> None:+ ctx = make_copilot_context()+ loop_signal = _signal("loop_detected_generic")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.LOOP_DETECTED, loop_signal) is not None+ assert ctx.blocker_signal_claimant is TurnClaimant.LOOP_DETECTED++ terminal_signal = _signal("output_source_unobservable", blocker_kind="tool_error")+ stash_blocker_signal(ctx, terminal_signal)++ assert ctx.blocker_signal is terminal_signal+ assert ctx.blocker_signal_claimant is None+ assert current_turn_owner(ctx) is None+ assert blocker_signal_render_allowed(ctx, terminal_signal) is True+++def test_signal_only_stronger_claim_retires_outranked_halt_on_consult() -> None:+ ctx = make_copilot_context()+ loop_signal = _signal("loop_detected_generic")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.LOOP_DETECTED, loop_signal) is not None+ stash_turn_halt_from_blocker_signal(ctx, loop_signal, source="test")+ assert ctx.turn_halt is not None++ _grant_ladder(ctx)+ assert claim_turn(ctx, TurnClaimant.OUTPUT_CONTRACT_ACTUATION) is ClaimOutcome.OWNED+ assert retire_outranked_turn_halt(ctx) is True++ assert ctx.turn_halt is None+ assert ctx.blocker_signal is loop_signal+ assert any(+ event.site == "turn_halt" and event.fingerprint == "output_contract_actuation>loop_detected"+ for event in ctx.gate_precedence_conflict_events+ )+++def test_retirement_restores_owner_halt_by_re_emission() -> None:+ ctx = make_copilot_context()+ terminal_signal = _signal("probable_site_block_stop", blocker_kind="tool_error")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.GENUINELY_TERMINAL, terminal_signal) is not None++ loop_signal = _signal("loop_detected_generic")+ loop_halt = stash_turn_halt_from_blocker_signal(ctx, loop_signal, source="test")+ assert loop_halt is not None+ assert ctx.turn_halt is loop_halt++ assert retire_outranked_turn_halt(ctx) is True+ restored = ctx.turn_halt+ assert restored is not None+ assert restored is not loop_halt+ assert restored.blocker_signal is terminal_signal+++def test_genuinely_terminal_halt_is_never_retired() -> None:+ ctx = make_copilot_context()+ terminal_signal = _signal("probable_site_block_stop", blocker_kind="tool_error")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.GENUINELY_TERMINAL, terminal_signal) is not None+ stash_turn_halt_from_blocker_signal(ctx, terminal_signal, source="test")+ halt = ctx.turn_halt+ assert halt is not None++ _grant_ladder(ctx)+ claim_turn(ctx, TurnClaimant.OUTPUT_CONTRACT_ACTUATION)+ assert retire_outranked_turn_halt(ctx) is False+ assert ctx.turn_halt is halt+++def test_render_denied_while_ladder_owns_and_restores_on_resolution() -> None:+ ctx = make_copilot_context()+ churn = _churn_signal()+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, churn) is not None+ assert blocker_signal_render_allowed(ctx, churn) is True++ _grant_ladder(ctx)+ assert blocker_signal_render_allowed(ctx, churn) is False+ assert any(+ event.site == "final_reply_render"+ and event.fingerprint == "output_contract_actuation>code_authoring_guardrail_churn"+ for event in ctx.gate_precedence_conflict_events+ )++ _resolve_ladder(ctx)+ assert blocker_signal_render_allowed(ctx, churn) is True+++def test_association_survives_held_signal_refresh() -> None:+ ctx = make_copilot_context()+ churn = _churn_signal()+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, churn) is not None++ refreshed = churn.model_copy(update={"user_facing_reason": "I stopped rewriting the generated code."})+ ctx.blocker_signal = refreshed++ owner = current_turn_owner(ctx)+ assert owner is not None+ assert owner.claimant is TurnClaimant.CODE_AUTHORING_CHURN+ assert blocker_signal_render_allowed(ctx, refreshed) is True+++def test_unclaimed_signal_with_no_live_owner_still_renders() -> None:+ ctx = make_copilot_context()+ signal = _signal("tool_error_repeated_action_abort", blocker_kind="tool_error")+ ctx.blocker_signal = signal+ assert blocker_signal_render_allowed(ctx, signal) is True+++def test_unclaimed_signal_fails_open_to_render_while_owner_live() -> None:+ ctx = make_copilot_context()+ signal = _signal("tool_error_repeated_action_abort", blocker_kind="tool_error")+ ctx.blocker_signal = signal+ _grant_ladder(ctx)++ assert blocker_signal_render_allowed(ctx, signal) is True+ assert ctx.gate_precedence_conflict_events == []+++def test_preflight_claim_never_outlives_the_rejecting_call() -> None:+ ctx = make_copilot_context()+ assert claim_turn(ctx, TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT) is ClaimOutcome.OWNED+ assert current_turn_owner(ctx) is None++ churn = _churn_signal()+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.CODE_AUTHORING_CHURN, churn) is not None+ assert blocker_signal_render_allowed(ctx, churn) is True+++def test_preflight_claim_yields_to_live_ladder_and_records_conflict() -> None:+ ctx = make_copilot_context()+ _grant_ladder(ctx)+ assert claim_turn(ctx, TurnClaimant.METADATA_RUN_PREFLIGHT_REJECT) is ClaimOutcome.YIELDED+ assert _conflict_fingerprints(ctx) == ["output_contract_actuation>metadata_run_preflight_reject"]+++def test_carve_out_claimants_are_transient() -> None:+ ctx = make_copilot_context()+ assert claim_turn(ctx, TurnClaimant.ACTUATION_OBLIGATION_FILL) is ClaimOutcome.OWNED+ assert claim_turn(ctx, TurnClaimant.CREDENTIAL_SCOUT_REOPEN) is ClaimOutcome.OWNED+ assert current_turn_owner(ctx) is None+++def test_credential_priority_churn_yields_only_to_ladder_and_terminal() -> None:+ ctx = make_copilot_context()+ _grant_ladder(ctx)+ signal = _signal("credential_priority_authoring_churn")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.CREDENTIAL_PRIORITY_CHURN, signal) is None++ ctx2 = make_copilot_context()+ assert claim_and_stash_blocker_signal(+ ctx2,+ TurnClaimant.SYNTHESIZED_BLOCK_PERSISTENCE_FORCE,+ _signal(SYNTHESIZED_BLOCK_PERSISTENCE_REASON_CODE, blocker_kind="tool_error", renders_final_reply=False),+ )+ credential_signal = _signal("credential_priority_authoring_churn")+ assert claim_and_stash_blocker_signal(ctx2, TurnClaimant.CREDENTIAL_PRIORITY_CHURN, credential_signal) is not None+ assert ctx2.blocker_signal is credential_signal+ assert blocker_signal_render_allowed(ctx2, credential_signal) is True+++def test_emit_blocker_signal_payload_returns_payload_even_on_yield() -> None:+ ctx = make_copilot_context()+ _grant_ladder(ctx)+ loop_signal = _signal("loop_detected_generic")++ payload = emit_blocker_signal_payload(ctx, loop_signal)++ assert payload == loop_signal.agent_steering_text+ assert ctx.blocker_signal is None+ assert any(+ event.fingerprint == "output_contract_actuation>loop_detected" for event in ctx.gate_precedence_conflict_events+ )+++def test_dispatch_force_reclaim_of_live_ladder_is_owned() -> None:+ ctx = make_copilot_context()+ _grant_ladder(ctx)+ claim_turn(ctx, TurnClaimant.OUTPUT_CONTRACT_ACTUATION)+ assert claim_turn(ctx, TurnClaimant.OUTPUT_CONTRACT_ACTUATION) is ClaimOutcome.OWNED+ assert ctx.gate_precedence_conflict_events == []+++def test_state_backed_ladder_owns_without_explicit_claim_and_query_does_not_register() -> None:+ ctx = make_copilot_context()+ _grant_ladder(ctx)+ owner = current_turn_owner(ctx)+ assert owner is not None+ assert owner.claimant is TurnClaimant.OUTPUT_CONTRACT_ACTUATION+ assert ctx.turn_ownership is None+++def test_release_turn_claim_removes_registered_claim() -> None:+ ctx = make_copilot_context()+ terminal_signal = _signal("probable_site_block_stop", blocker_kind="tool_error")+ assert claim_and_stash_blocker_signal(ctx, TurnClaimant.GENUINELY_TERMINAL, terminal_signal) is not None+ assert ctx.turn_ownership is not None+ assert TurnClaimant.GENUINELY_TERMINAL in ctx.turn_ownership.claims++ release_turn_claim(ctx, TurnClaimant.GENUINELY_TERMINAL)+ assert TurnClaimant.GENUINELY_TERMINAL not in ctx.turn_ownership.claims+++def test_conflict_events_are_capped() -> None:+ ctx = make_copilot_context()+ _grant_ladder(ctx)+ for _ in range(30):+ claim_turn(ctx, TurnClaimant.LOOP_DETECTED)+ assert len(ctx.gate_precedence_conflict_events) == 20+++def test_fresh_context_has_no_owner() -> None:+ ctx = make_copilot_context()+ assert current_turn_owner(ctx) is None+ assert ctx.gate_precedence_conflict_events == []