Skip to content

Automate browser based workflows with AI

SKY-10931: persist copilot completion criteria per goal epoch with tri-state adjudication (#6562)

Andrew Neilson4480b811206d
diff --git a/alembic/versions/2026_06_14_2221-218048b68412_add_workflow_copilot_completion_criteria_sets_table.py b/alembic/versions/2026_06_14_2221-218048b68412_add_workflow_copilot_completion_criteria_sets_table.py
new file mode 100644
index 000000000..0f44122f9
--- /dev/null
+++ b/alembic/versions/2026_06_14_2221-218048b68412_add_workflow_copilot_completion_criteria_sets_table.py
@@ -0,0 +1,65 @@
+"""add workflow_copilot_completion_criteria_sets table
+
+Revision ID: 218048b68412
+Revises: a8c4e2f9d6b1
+Create Date: 2026-06-14T22:21:36.243898+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "218048b68412"
+down_revision: Union[str, None] = "a8c4e2f9d6b1"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+_TABLE = "workflow_copilot_completion_criteria_sets"
+
+
+def upgrade() -> None:
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if inspector.has_table(_TABLE):
+ return
+
+ if conn.dialect.name == "postgresql":
+ op.execute(sa.text("SET lock_timeout = '2s'"))
+
+ op.create_table(
+ _TABLE,
+ sa.Column("completion_criteria_set_id", sa.String(), nullable=False),
+ sa.Column("organization_id", sa.String(), nullable=False),
+ sa.Column("workflow_copilot_chat_id", sa.String(), nullable=False),
+ sa.Column("goal_epoch", sa.Integer(), nullable=False),
+ sa.Column("status", sa.String(), nullable=False),
+ sa.Column("criteria", sa.JSON(), nullable=False),
+ sa.Column("source_turn_id", sa.String(), nullable=True),
+ sa.Column("source_goal_text", sa.UnicodeText(), nullable=True),
+ sa.Column("consecutive_all_no_evidence", sa.Integer(), nullable=False),
+ sa.Column("tripwire_fired", sa.Boolean(), nullable=False),
+ sa.Column("last_fully_satisfied_workflow_yaml", sa.UnicodeText(), nullable=True),
+ sa.Column("superseded_by_set_id", sa.String(), nullable=True),
+ sa.Column("superseded_at", sa.DateTime(), nullable=True),
+ sa.Column("supersede_reason", sa.String(), nullable=True),
+ sa.Column("created_at", sa.DateTime(), nullable=False),
+ sa.Column("modified_at", sa.DateTime(), nullable=False),
+ sa.PrimaryKeyConstraint("completion_criteria_set_id"),
+ )
+ op.create_index("wcccs_org_chat_index", _TABLE, ["organization_id", "workflow_copilot_chat_id"])
+
+ if conn.dialect.name == "postgresql":
+ op.execute(sa.text("SET lock_timeout = '0'"))
+
+
+def downgrade() -> None:
+ conn = op.get_bind()
+ inspector = sa.inspect(conn)
+ if not inspector.has_table(_TABLE):
+ return
+ op.drop_index("wcccs_org_chat_index", table_name=_TABLE)
+ op.drop_table(_TABLE)
diff --git a/skyvern/config.py b/skyvern/config.py
index e411c949e..a79a76448 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -152,6 +152,10 @@ class Settings(BaseSettings):
# Off restores schema-less interaction packets plus standalone page inspects.
COPILOT_SCOUT_ACT_OBSERVE_ENABLED: bool = True
COPILOT_SCOUT_ACT_OBSERVE_TIMEOUT_SECONDS: float = 4.0
+ # Persist copilot completion criteria per goal epoch with tri-state verdicts
+ # and definition-plane grading. Off restores per-turn re-derivation, the legacy
+ # run-status success claim, and unknown-verdicts-as-unsatisfied consumer behavior.
+ COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED: bool = True
# Dispatch flag for the workflow copilot v2 (openai-agents-SDK rewrite).
# Off = existing direct-LLM copilot at workflow_copilot_chat_post.
# On = new agent-SDK path under skyvern.forge.sdk.copilot.
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
index 0ff725238..c6b081e3d 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
@@ -25,11 +25,15 @@ completion_contract:
- Set to null when the user does not provide an explicit completion condition.
{% if outcome_verification_enabled %}completion_criteria:
-- An array of the END-STATE OUTCOMES that must be true for the user's goal to be done. Each item is {outcome, implicit, method_mandated}.
+- An array of the END-STATE OUTCOMES that must be true for the user's goal to be done. Each item is {outcome, implicit, method_mandated, level}.
- outcome: a short statement of an end state the workflow must achieve (an END, not a step). Extract the goal as outcomes the user wants to be true, not the recipe they describe.
- Capture ALL distinct outcomes the goal requires, including implicit constraints the user did not state as a step (for example "added exactly once / not duplicated", "the item is present in the cart"). Mark such items implicit=true.
- A prescribed HOW step is NOT a criterion. "search for X", "open the result lightbox", "click add to cart", "go to the cart page" are methods/navigation, not outcomes — do not list them. A different or shorter path that reaches the same end state must still satisfy the goal.
+- Telling/showing/reporting results to the user is NOT a criterion. "tell me what it extracted", "show me the data", "confirm to me it worked" describe the chat reply, which no workflow definition or run can evidence — capture only the underlying workflow outcome (the data is extracted into the run output, the form is submitted) and list nothing for the reporting itself.
- method_mandated=true ONLY when the user explicitly makes a specific method the point of the request (for example "verify it works by submitting the real form", "specifically use the search bar"). Otherwise method_mandated=false.
+- level=definition when the outcome is a property of the workflow definition itself, checkable without running it (for example "the workflow accepts first name, last name, and NPI as reusable inputs", "X is a configurable parameter"). level=run when the outcome is an end state only a run can show (data extracted, item in cart, form submitted). Default to run when unsure.
+- Do not emit a criterion that restates or negates another criterion in the list (for example a "values are not hardcoded" duplicate of a reusable-inputs criterion); one outcome, one criterion. State a definition-level outcome as the positive checkable property of the named inputs, never as a negation.
+- When ACTIVE COMPLETION CRITERIA are provided below, they are the canonical phrasing of the chat's current goal. If the latest request keeps that goal — including repeat, retest, fix, and follow-up turns — emit each still-required outcome COPIED VERBATIM from that list, character for character, punctuation included; never rephrase or reword a covered outcome. Write new phrasing only for an outcome the list does not cover, and drop an item only when the latest request abandons or replaces it.
- Set to [] when the user gives no goal with a checkable outcome (for example a pure draft-only or sketch request).
{% endif %}
@@ -81,4 +85,6 @@ Retained recent history:
```{{ retained_history }}```
Current workflow YAML:
```{{ workflow_yaml }}```
-Global context: ```{{ global_llm_context }}```
+{% if outcome_verification_enabled and active_completion_criteria %}ACTIVE COMPLETION CRITERIA (canonical phrasing for the current goal):
+```{{ active_completion_criteria }}```
+{% endif %}Global context: ```{{ global_llm_context }}```
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index e33256d13..2f2a8c13c 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -30,6 +30,7 @@ import yaml
from litellm.exceptions import NotFoundError as LiteLLMNotFoundError
from pydantic import ValidationError
+from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.copilot.blocker_signal import (
@@ -40,6 +41,11 @@ from skyvern.forge.sdk.copilot.blocker_signal import (
from skyvern.forge.sdk.copilot.blocker_signal import to_trace_data as blocker_signal_to_trace_data
from skyvern.forge.sdk.copilot.build_phase import initial_build_phase
from skyvern.forge.sdk.copilot.code_block_synthesis import render_synthesized_offer_text, synthesize_code_block
+from skyvern.forge.sdk.copilot.completion_criteria_store import (
+ StoredCriteriaSnapshot,
+ build_turn_state,
+ reconcile_completion_criteria,
+)
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig, normalize_block_authoring_policy
from skyvern.forge.sdk.copilot.context import (
COPILOT_RESPONSE_TYPES,
@@ -48,15 +54,20 @@ from skyvern.forge.sdk.copilot.context import (
NarrativeActivityEntry,
NarrativeBlock,
NarrativeDraft,
+ NarrativeOutcomeAdjudication,
ResponseType,
StructuredContext,
TurnNarrativePayload,
finalize_discovery_counter_in_global_llm_context,
)
-from skyvern.forge.sdk.copilot.enforcement import outcome_fully_verified, verified_goal_satisfied_context
+from skyvern.forge.sdk.copilot.enforcement import (
+ outcome_fully_verified,
+ verified_goal_claim_authorized,
+)
from skyvern.forge.sdk.copilot.failure_tracking import PER_TOOL_BUDGET_FAILURE_CATEGORY
from skyvern.forge.sdk.copilot.outcome_verification_trace import (
finalize_outcome_verification_trace,
+ record_criteria_lifecycle,
record_gate_decision,
)
from skyvern.forge.sdk.copilot.output_policy import (
@@ -87,6 +98,7 @@ from skyvern.forge.sdk.copilot.recoverable_failure import (
)
from skyvern.forge.sdk.copilot.request_policy import (
RAW_SECRET_REFUSAL_SENTINEL,
+ CompletionCriterion,
RequestPolicy,
build_request_policy,
redact_raw_secrets_for_prompt,
@@ -95,6 +107,7 @@ from skyvern.forge.sdk.copilot.runtime import _browser_context_is_attachable
from skyvern.forge.sdk.copilot.streaming_adapter import (
emit_turn_start,
emit_workflow_draft,
+ flush_goal_satisfied_tool_result,
maybe_emit_design_end,
)
from skyvern.forge.sdk.copilot.tracing_setup import _copilot_model_name, ensure_tracing_initialized, is_tracing_enabled
@@ -215,6 +228,7 @@ class RequestPolicyGuardrailInputs:
workflow_permanent_id: str | None = None
workflow_run_id: str | None = None
browser_session_id: str | None = None
+ stored_completion_criteria: StoredCriteriaSnapshot | None = None
class CopilotRequestPolicyMissingError(Exception):
@@ -343,6 +357,39 @@ def _request_policy_agent_inputs(
return user_message, chat_history_text
+def _stored_active_completion_criteria(
+ policy_inputs: RequestPolicyGuardrailInputs,
+) -> list[CompletionCriterion] | None:
+ if not (settings.COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED and settings.COPILOT_OUTCOME_VERIFICATION_ENABLED):
+ return None
+ snapshot = policy_inputs.stored_completion_criteria
+ if snapshot is None or snapshot.active is None:
+ return None
+ return list(snapshot.active.criteria)
+
+
+def _reconcile_completion_criteria_on_context(
+ ctx: CopilotContext,
+ policy: RequestPolicy,
+ policy_inputs: RequestPolicyGuardrailInputs,
+) -> None:
+ if not (settings.COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED and settings.COPILOT_OUTCOME_VERIFICATION_ENABLED):
+ return
+ snapshot = policy_inputs.stored_completion_criteria
+ if snapshot is None:
+ return
+ decision = reconcile_completion_criteria(
+ snapshot,
+ list(policy.completion_criteria),
+ actionable=policy.user_response_policy != "ask_clarification",
+ )
+ if decision.action == "adopt_stored":
+ policy.completion_criteria = list(decision.criteria)
+ ctx.completion_criteria_turn_state = build_turn_state(snapshot, decision)
+ record_criteria_lifecycle(ctx, decision.to_trace_data())
+ LOG.info("copilot completion criteria reconciled", **decision.to_trace_data())
+
+
def _store_request_policy_on_context(
ctx: CopilotContext,
policy: RequestPolicy,
@@ -355,6 +402,7 @@ def _store_request_policy_on_context(
chat_history_text=policy_inputs.chat_history_text,
previous_user_message=policy_inputs.previous_user_message,
)
+ _reconcile_completion_criteria_on_context(ctx, policy, policy_inputs)
ctx.request_policy = policy
ctx.allow_untested_workflow_draft = policy.testing_intent == "skip_test"
ctx.user_message = agent_user_message
@@ -890,10 +938,34 @@ def _make_agent_result(
if turn_outcome is not None and "responseKind" not in narrative_payload:
payload_updates["responseKind"] = turn_outcome.response_kind.value
if ctx is not None and "verifiedSuccess" not in narrative_payload:
- payload_updates["verifiedSuccess"] = bool(verified_goal_satisfied_context(ctx))
+ payload_updates["verifiedSuccess"] = bool(verified_goal_claim_authorized(ctx))
+ if ctx is not None and "outcomeAdjudication" not in narrative_payload:
+ adjudication = _build_outcome_adjudication_payload(ctx)
+ if adjudication is not None:
+ payload_updates["outcomeAdjudication"] = adjudication
if payload_updates:
kwargs["narrative_payload"] = {**narrative_payload, **payload_updates}
- return AgentResult(global_llm_context=final_context, turn_outcome=turn_outcome, **kwargs)
+ result = AgentResult(global_llm_context=final_context, turn_outcome=turn_outcome, **kwargs)
+ if ctx is not None and result.completion_criteria_turn_state is None:
+ result.completion_criteria_turn_state = getattr(ctx, "completion_criteria_turn_state", None)
+ return result
+
+
+def _build_outcome_adjudication_payload(ctx: CopilotContext) -> NarrativeOutcomeAdjudication | None:
+ turn_state = getattr(ctx, "completion_criteria_turn_state", None)
+ if turn_state is None:
+ return None
+ counts = turn_state.last_verdict_state_counts or {}
+ payload: NarrativeOutcomeAdjudication = {
+ "satisfiedCount": int(counts.get("satisfied", 0)),
+ "unsatisfiedCount": int(counts.get("unsatisfied", 0)),
+ "unknownCount": int(counts.get("unknown", 0)),
+ "claimTier": "verified_goal_satisfied" if verified_goal_claim_authorized(ctx) else "built_unverified",
+ }
+ if turn_state.decision is not None:
+ payload["criteriaEpoch"] = turn_state.decision.epoch
+ payload["criteriaLifecycleReason"] = turn_state.decision.reason
+ return payload
_BLOCK_STATUS_TO_UI_STATE: dict[str, str] = {
@@ -1070,11 +1142,22 @@ def _build_exit_result(
)
-def _build_goal_satisfied_exit_result(ctx: CopilotContext, global_llm_context: str | None) -> AgentResult:
+async def _build_goal_satisfied_exit_result(ctx: CopilotContext, global_llm_context: str | None) -> AgentResult:
# Bypass one extra LLM turn after a full workflow test already satisfies
# the diagnosis contract.
+ if ctx.stream is not None:
+ try:
+ await flush_goal_satisfied_tool_result(ctx.stream, ctx)
+ except Exception as flush_err:
+ LOG.warning("copilot_goal_satisfied_tool_result_flush_failed", error=str(flush_err))
verified_workflow, verified_yaml = _verified_workflow_or_none(ctx)
- user_response = "I created and tested the workflow successfully."
+ if verified_goal_claim_authorized(ctx):
+ user_response = "I created and tested the workflow successfully."
+ else:
+ user_response = (
+ "I built the workflow and the test run completed, but the goal outcome was not "
+ "independently verified. Review the draft to confirm it does what you need."
+ )
final_text, outcome = apply_repeated_reply_guard(
final_text=user_response,
attempted_kind=derive_response_kind(ctx.turn_intent),
@@ -2538,6 +2621,7 @@ def _build_copilot_input_guardrails(
global_llm_context=policy_inputs.global_llm_context,
organization_id=policy_inputs.organization_id,
handler=policy_inputs.handler,
+ active_criteria=_stored_active_completion_criteria(policy_inputs),
)
if isinstance(ctx, CopilotContext):
turn_intent_classification = None
@@ -2765,6 +2849,7 @@ async def run_copilot_agent(
turn_id: str | None = None,
prior_copilot_workflow_yaml: str | None = None,
prior_block_count: int | None = None,
+ stored_completion_criteria: StoredCriteriaSnapshot | None = None,
) -> AgentResult:
# One id per turn — passed to every downstream AgentResult and
# CopilotContext so the envelope and terminal frames correlate. The
@@ -2801,6 +2886,7 @@ async def run_copilot_agent(
prior_copilot_workflow_yaml=prior_copilot_workflow_yaml,
prior_block_count=prior_block_count,
ctx_sink=ctx_sink,
+ stored_completion_criteria=stored_completion_criteria,
)
except Exception as exc:
LOG.error(
@@ -2868,6 +2954,7 @@ async def _run_copilot_turn_impl(
prior_copilot_workflow_yaml: str | None = None,
prior_block_count: int | None = None,
ctx_sink: list[CopilotContext] | None = None,
+ stored_completion_criteria: StoredCriteriaSnapshot | None = None,
) -> AgentResult:
copilot_config = config or CopilotConfig(security_rules=security_rules)
chat_history_text = _format_chat_history(chat_history)
@@ -2955,6 +3042,7 @@ async def _run_copilot_turn_impl(
workflow_permanent_id=chat_request.workflow_permanent_id,
workflow_run_id=getattr(chat_request, "workflow_run_id", None),
browser_session_id=getattr(chat_request, "browser_session_id", None),
+ stored_completion_criteria=stored_completion_criteria,
)
request_policy_guardrails = _build_copilot_input_guardrails(
InputGuardrail,
@@ -3273,7 +3361,7 @@ async def _run_copilot_turn_impl(
workflow_permanent_id=chat_request.workflow_permanent_id,
workflow_run_id=ctx.last_successful_run_blocks_workflow_run_id,
)
- return _build_goal_satisfied_exit_result(ctx, global_llm_context)
+ return await _build_goal_satisfied_exit_result(ctx, global_llm_context)
except CopilotTurnHalt as exc:
LOG.info(
"Copilot run stopped after typed turn halt",
@@ -3366,6 +3454,6 @@ async def _run_copilot_turn_impl(
workflow_run_id=ctx.last_successful_run_blocks_workflow_run_id,
error_type=type(e).__name__,
)
- return _build_goal_satisfied_exit_result(ctx, global_llm_context)
+ return await _build_goal_satisfied_exit_result(ctx, global_llm_context)
LOG.error("Copilot agent error", error=str(e), exc_info=True)
return _build_unexpected_error_exit_result(ctx, global_llm_context, error=e)
diff --git a/skyvern/forge/sdk/copilot/completion_criteria_store.py b/skyvern/forge/sdk/copilot/completion_criteria_store.py
new file mode 100644
index 000000000..08f507f4a
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/completion_criteria_store.py
@@ -0,0 +1,268 @@
+"""Pure lifecycle logic for persisted completion-criteria sets (SKY-10931).
+
+A criteria set belongs to exactly one goal epoch of one chat. Sets are immutable
+once written and superseded wholesale — never edited per criterion. Staleness
+always degrades to regeneration, never to a sticky block (GOTCHAS §9). DB IO
+stays at the route/repository seam; everything here is side-effect free.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Literal
+
+from skyvern.forge.sdk.copilot.completion_verification import (
+ CompletionVerificationResult,
+ run_plane_all_no_evidence,
+)
+from skyvern.forge.sdk.copilot.request_policy import (
+ CompletionCriterion,
+ normalized_criterion_outcome_key,
+)
+
+ReconcileAction = Literal["create", "adopt_stored", "none"]
+ReconcileReason = Literal["first", "not_subset", "kept", "empty_fresh", "no_criteria", "not_actionable"]
+SupersedeReason = Literal["not_subset", "tripwire"]
+
+CRITERIA_SET_STATUS_ACTIVE = "active"
+CRITERIA_SET_STATUS_SUPERSEDED = "superseded"
+TRIPWIRE_CONSECUTIVE_ALL_NO_EVIDENCE = 2
+_CRITERION_LEVELS = ("definition", "run")
+
+
+@dataclass(frozen=True)
+class StoredCriteriaSet:
+ set_id: str
+ goal_epoch: int
+ criteria: tuple[CompletionCriterion, ...]
+ consecutive_all_no_evidence: int = 0
+ tripwire_fired: bool = False
+ last_fully_satisfied_workflow_yaml: str | None = None
+
+
+@dataclass(frozen=True)
+class StoredCriteriaSnapshot:
+ """What the route loads before the turn: the active set (if any) and the next
+ free epoch (max persisted epoch + 1, so epochs stay monotonic across supersedes)."""
+
+ active: StoredCriteriaSet | None = None
+ next_epoch: int = 1
+
+
+@dataclass(frozen=True)
+class ReconcileDecision:
+ action: ReconcileAction
+ reason: ReconcileReason
+ epoch: int
+ criteria: tuple[CompletionCriterion, ...]
+ superseded_set_id: str | None = None
+
+ def to_trace_data(self) -> dict[str, Any]:
+ return {
+ "criteria_lifecycle_action": self.action,
+ "criteria_lifecycle_reason": self.reason,
+ "criteria_lifecycle_epoch": self.epoch,
+ "criteria_lifecycle_count": len(self.criteria),
+ }
+
+
+@dataclass
+class CompletionCriteriaTurnState:
+ """Mutable per-turn record connecting the reconcile decision to post-turn
+ persistence: adjudication events accumulate as run/observation verifications
+ land, and the route folds them into the stored row after the turn."""
+
+ decision: ReconcileDecision | None = None
+ active_set_id: str | None = None
+ prior_consecutive_all_no_evidence: int = 0
+ prior_tripwire_fired: bool = False
+ known_good_yaml_available: bool = False
+ adjudication_all_no_evidence_events: list[bool] = field(default_factory=list)
+ fully_satisfied_workflow_yaml: str | None = None
+ last_verdict_state_counts: dict[str, int] = field(default_factory=dict)
+
+
+@dataclass(frozen=True)
+class PersistencePlan:
+ """What the route must write after the turn. ``counter_*`` applies to the row
+ named by ``counter_set_id`` — the adopted stored row, or the row created this
+ turn (``counter_set_id is None`` then; the route uses the new row's id)."""
+
+ create_epoch: int | None = None
+ create_criteria: tuple[CompletionCriterion, ...] = ()
+ create_reason: ReconcileReason | None = None
+ supersede_set_id: str | None = None
+ supersede_reason: SupersedeReason | None = None
+ counter_set_id: str | None = None
+ counter_value: int = 0
+ tripwire_fired: bool = False
+ fully_satisfied_workflow_yaml: str | None = None
+
+ @property
+ def creates_set(self) -> bool:
+ return self.create_epoch is not None
+
+
+def criteria_to_json(criteria: tuple[CompletionCriterion, ...] | list[CompletionCriterion]) -> list[dict[str, Any]]:
+ return [
+ {
+ "id": criterion.id,
+ "outcome": criterion.outcome,
+ "implicit": criterion.implicit,
+ "method_mandated": criterion.method_mandated,
+ "level": criterion.level,
+ }
+ for criterion in criteria
+ ]
+
+
+def criteria_from_json(raw: Any) -> tuple[CompletionCriterion, ...]:
+ if not isinstance(raw, list):
+ return ()
+ criteria: list[CompletionCriterion] = []
+ for item in raw:
+ if not isinstance(item, dict):
+ continue
+ criterion_id = item.get("id")
+ outcome = item.get("outcome")
+ if not isinstance(criterion_id, str) or not isinstance(outcome, str) or not outcome.strip():
+ continue
+ level = item.get("level")
+ criteria.append(
+ CompletionCriterion(
+ id=criterion_id,
+ outcome=outcome,
+ implicit=bool(item.get("implicit")),
+ method_mandated=bool(item.get("method_mandated")),
+ level=level if isinstance(level, str) and level in _CRITERION_LEVELS else "run", # type: ignore[arg-type]
+ )
+ )
+ return tuple(criteria)
+
+
+def _outcome_key_set(criteria: tuple[CompletionCriterion, ...] | list[CompletionCriterion]) -> set[str]:
+ return {normalized_criterion_outcome_key(criterion.outcome) for criterion in criteria}
+
+
+def reconcile_completion_criteria(
+ snapshot: StoredCriteriaSnapshot | None,
+ fresh: list[CompletionCriterion],
+ *,
+ actionable: bool,
+) -> ReconcileDecision:
+ """Decide once per turn whether the stored set survives or a new epoch begins.
+
+ An empty fresh derivation never supersedes (repair/run follow-up turns commonly
+ derive nothing); a fresh key set that subsets the stored keys keeps the stored
+ set; anything else supersedes wholesale. Non-actionable (clarification) turns
+ never create or supersede.
+ """
+ stored = snapshot.active if snapshot is not None else None
+ next_epoch = snapshot.next_epoch if snapshot is not None else 1
+ if stored is None:
+ if not fresh:
+ return ReconcileDecision(action="none", reason="no_criteria", epoch=0, criteria=())
+ if not actionable:
+ return ReconcileDecision(action="none", reason="not_actionable", epoch=0, criteria=tuple(fresh))
+ return ReconcileDecision(action="create", reason="first", epoch=next_epoch, criteria=tuple(fresh))
+ if not fresh:
+ return ReconcileDecision(
+ action="adopt_stored", reason="empty_fresh", epoch=stored.goal_epoch, criteria=stored.criteria
+ )
+ if _outcome_key_set(fresh) <= _outcome_key_set(stored.criteria):
+ return ReconcileDecision(
+ action="adopt_stored", reason="kept", epoch=stored.goal_epoch, criteria=stored.criteria
+ )
+ if not actionable:
+ return ReconcileDecision(
+ action="adopt_stored", reason="not_actionable", epoch=stored.goal_epoch, criteria=stored.criteria
+ )
+ return ReconcileDecision(
+ action="create",
+ reason="not_subset",
+ epoch=next_epoch,
+ criteria=tuple(fresh),
+ superseded_set_id=stored.set_id,
+ )
+
+
+def build_turn_state(
+ snapshot: StoredCriteriaSnapshot | None, decision: ReconcileDecision
+) -> CompletionCriteriaTurnState:
+ stored = snapshot.active if snapshot is not None else None
+ if decision.action != "adopt_stored" or stored is None:
+ return CompletionCriteriaTurnState(decision=decision)
+ return CompletionCriteriaTurnState(
+ decision=decision,
+ active_set_id=stored.set_id,
+ prior_consecutive_all_no_evidence=stored.consecutive_all_no_evidence,
+ prior_tripwire_fired=stored.tripwire_fired,
+ known_good_yaml_available=bool(stored.last_fully_satisfied_workflow_yaml),
+ )
+
+
+def note_adjudication_on_turn_state(
+ turn_state: CompletionCriteriaTurnState | None,
+ verification: CompletionVerificationResult,
+ *,
+ fully_satisfied_workflow_yaml: str | None = None,
+) -> None:
+ if turn_state is None or verification.status != "evaluated":
+ return
+ turn_state.adjudication_all_no_evidence_events.append(run_plane_all_no_evidence(verification))
+ turn_state.last_verdict_state_counts = verification.verdict_state_counts()
+ if verification.is_fully_satisfied() and fully_satisfied_workflow_yaml:
+ turn_state.fully_satisfied_workflow_yaml = fully_satisfied_workflow_yaml
+
+
+def plan_persistence(turn_state: CompletionCriteriaTurnState | None) -> PersistencePlan | None:
+ """Fold the turn's reconcile decision and adjudication events into the writes
+ the route must make. The tripwire fires at most once per epoch: when the
+ consecutive all-no_evidence counter reaches the threshold on a set that has
+ not fired yet, the set is superseded so the next derivation starts a new epoch."""
+ if turn_state is None or turn_state.decision is None:
+ return None
+ decision = turn_state.decision
+ if decision.action == "none":
+ return None
+
+ if decision.action == "create":
+ # A set created this turn folds its counter but can never fire: the
+ # tripwire detects persisted staleness, which needs at least one
+ # adopted turn to exist. Early all-no_evidence runs while the workflow
+ # is still being built must not churn fresh epochs.
+ counter = 0
+ for all_no_evidence in turn_state.adjudication_all_no_evidence_events:
+ counter = counter + 1 if all_no_evidence else 0
+ return PersistencePlan(
+ create_epoch=decision.epoch,
+ create_criteria=decision.criteria,
+ create_reason=decision.reason,
+ supersede_set_id=decision.superseded_set_id,
+ supersede_reason="not_subset" if decision.superseded_set_id else None,
+ counter_set_id=None,
+ counter_value=counter,
+ tripwire_fired=False,
+ fully_satisfied_workflow_yaml=turn_state.fully_satisfied_workflow_yaml,
+ )
+
+ if not turn_state.adjudication_all_no_evidence_events and turn_state.fully_satisfied_workflow_yaml is None:
+ return None
+
+ counter = turn_state.prior_consecutive_all_no_evidence
+ fired = turn_state.prior_tripwire_fired
+ fired_now = False
+ for all_no_evidence in turn_state.adjudication_all_no_evidence_events:
+ counter = counter + 1 if all_no_evidence else 0
+ if counter >= TRIPWIRE_CONSECUTIVE_ALL_NO_EVIDENCE and not fired:
+ fired = True
+ fired_now = True
+
+ return PersistencePlan(
+ supersede_set_id=turn_state.active_set_id if fired_now else None,
+ supersede_reason="tripwire" if fired_now else None,
+ counter_set_id=turn_state.active_set_id,
+ counter_value=counter,
+ tripwire_fired=fired,
+ fully_satisfied_workflow_yaml=turn_state.fully_satisfied_workflow_yaml,
+ )
diff --git a/skyvern/forge/sdk/copilot/completion_verification.py b/skyvern/forge/sdk/copilot/completion_verification.py
index 6b0574d71..4a1f32e15 100644
--- a/skyvern/forge/sdk/copilot/completion_verification.py
+++ b/skyvern/forge/sdk/copilot/completion_verification.py
@@ -12,10 +12,12 @@ from __future__ import annotations
import asyncio
import json
+import re
from dataclasses import dataclass, field
from typing import Any, Literal
import structlog
+import yaml
from skyvern.config import settings
from skyvern.forge.prompts import prompt_engine
@@ -48,15 +50,28 @@ _PAGE_EVIDENCE_KEYS = (
)
VerificationStatus = Literal["evaluated", "unavailable"]
+CriterionState = Literal["satisfied", "unsatisfied", "unknown"]
+
+
+def resolve_unknown(state: CriterionState) -> CriterionState:
+ """Effective verdict state for consumers: with persisted-criteria off, ``unknown``
+ collapses to ``unsatisfied`` (the pre-tri-state equivalent of a missing verdict)."""
+ if state == "unknown" and not settings.COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED:
+ return "unsatisfied"
+ return state
@dataclass(frozen=True)
class CriterionVerdict:
criterion_id: str
- satisfied: bool
+ state: CriterionState
reason_code: str
evidence_ref: str | None = None
+ @property
+ def satisfied(self) -> bool:
+ return self.state == "satisfied"
+
@dataclass(frozen=True)
class CompletionVerificationResult:
@@ -74,11 +89,20 @@ class CompletionVerificationResult:
return {
"status": self.status,
"criterion_count": len(self.criterion_ids),
- "satisfied_count": sum(1 for verdict in self.verdicts if verdict.satisfied),
+ "satisfied_count": sum(1 for verdict in self.verdicts if verdict.state == "satisfied"),
+ "unsatisfied_count": sum(1 for verdict in self.verdicts if verdict.state == "unsatisfied"),
+ "unknown_count": sum(1 for verdict in self.verdicts if verdict.state == "unknown"),
"fully_satisfied": self.is_fully_satisfied(),
"reason_codes": [verdict.reason_code for verdict in self.verdicts],
}
+ def verdict_state_counts(self) -> dict[str, int]:
+ return {
+ "satisfied": sum(1 for verdict in self.verdicts if verdict.state == "satisfied"),
+ "unsatisfied": sum(1 for verdict in self.verdicts if verdict.state == "unsatisfied"),
+ "unknown": sum(1 for verdict in self.verdicts if verdict.state == "unknown"),
+ }
+
@dataclass(frozen=True)
class RunEvidenceSnapshot:
@@ -169,26 +193,202 @@ def _coerce_result(raw: Any, criterion_ids: list[str]) -> CompletionVerification
reason = item.get("reason_code")
reason_code = reason if reason in _REASON_CODES else "unknown"
# A criterion counts as satisfied only when the judge cites confirming
- # evidence; an "unknown"/"no_evidence"/"contradicts" verdict never passes.
- satisfied = bool(item.get("satisfied")) and reason_code == "evidence_confirms"
+ # evidence; "no_evidence"/"contradicts" are affirmative negatives, while an
+ # incoherent or "unknown" verdict stays unknown — it never passes and never fails.
+ if bool(item.get("satisfied")) and reason_code == "evidence_confirms":
+ state: CriterionState = "satisfied"
+ elif reason_code in ("no_evidence", "evidence_contradicts"):
+ state = "unsatisfied"
+ else:
+ state = "unknown"
evidence_ref_raw = item.get("evidence_ref")
evidence_ref = (
evidence_ref_raw.strip() if isinstance(evidence_ref_raw, str) and evidence_ref_raw.strip() else None
)
by_id[criterion_id] = CriterionVerdict(
criterion_id=criterion_id,
- satisfied=satisfied,
+ state=state,
reason_code=reason_code,
evidence_ref=evidence_ref,
)
+ # A criterion the judge never returned a verdict for was not evaluated —
+ # that is absent signal (unknown), not affirmative no_evidence.
verdicts = [
- by_id.get(criterion_id, CriterionVerdict(criterion_id=criterion_id, satisfied=False, reason_code="no_evidence"))
+ by_id.get(criterion_id, CriterionVerdict(criterion_id=criterion_id, state="unknown", reason_code="unknown"))
for criterion_id in criterion_ids
]
return CompletionVerificationResult(status="evaluated", criterion_ids=list(criterion_ids), verdicts=verdicts)
+_DEFINITION_PARAMETER_HINT_RE = re.compile(r"\b(?:inputs?|parameters?|params?|reusable|configurable)\b", re.I)
+_DEFINITION_INPUT_LIST_RE = re.compile(
+ r"(?:accepts?|takes?|uses?|with|defines?)\s+(?P<items>[^.;:]{3,160}?)\s+as\s+(?:the\s+)?"
+ r"(?:reusable|configurable|run[ -]?time)?\s*(?:workflow\s+)?(?:inputs?|parameters?)\b"
+ r"|(?P<items_are>[^.;:]{3,160}?)\s+(?:are|is|should\s+be|will\s+be)\s+(?:the\s+)?"
+ r"(?:reusable|configurable|run[ -]?time)\s+(?:workflow\s+)?(?:inputs?|parameters?)\b",
+ re.I,
+)
+_DEFINITION_INPUT_SPLIT_RE = re.compile(r",|\band\b|&|/", re.I)
+_DEFINITION_INPUT_STOPWORDS = frozenset({"the", "a", "an", "my", "their", "all", "of", "workflow", "number", "value"})
+
+
+def _normalize_input_phrase(text: str) -> str:
+ return " ".join(re.sub(r"[^a-z0-9]+", " ", text.lower()).split())
+
+
+def _named_definition_inputs(outcome: str) -> list[str]:
+ match = _DEFINITION_INPUT_LIST_RE.search(outcome)
+ if match is None:
+ return []
+ items_text = match.group("items") or match.group("items_are") or ""
+ candidates: list[str] = []
+ for segment in _DEFINITION_INPUT_SPLIT_RE.split(items_text):
+ phrase = _normalize_input_phrase(segment)
+ words = [word for word in phrase.split() if word not in _DEFINITION_INPUT_STOPWORDS]
+ if 0 < len(words) <= 4:
+ candidates.append(" ".join(words))
+ return candidates
+
+
+def _input_matches_any_key(candidate: str, normalized_keys: list[str]) -> bool:
+ return any(candidate == key or candidate in key or key in candidate for key in normalized_keys)
+
+
+def _moustache_reference_pattern(key: str) -> re.Pattern[str]:
+ return re.compile(r"\{\{[^{}]*\b" + re.escape(key) + r"\b[^{}]*\}\}")
+
+
+def _value_references_key(value: Any, key: str, pattern: re.Pattern[str], depth: int = 0) -> bool:
+ if depth > 8:
+ return False
+ if isinstance(value, str):
+ return bool(pattern.search(value))
+ if isinstance(value, dict):
+ parameter_keys = value.get("parameter_keys")
+ if isinstance(parameter_keys, list) and key in parameter_keys:
+ return True
+ return any(_value_references_key(item, key, pattern, depth + 1) for item in value.values())
+ if isinstance(value, list):
+ return any(_value_references_key(item, key, pattern, depth + 1) for item in value)
+ return False
+
+
+def _workflow_parameter_reference_state(workflow_yaml: str | None) -> tuple[list[str], list[str]] | None:
+ """(defined workflow-parameter keys, the subset referenced by blocks); None when unparseable."""
+ if not isinstance(workflow_yaml, str) or not workflow_yaml.strip():
+ return [], []
+ try:
+ parsed = yaml.safe_load(workflow_yaml)
+ except yaml.YAMLError:
+ return None
+ if not isinstance(parsed, dict):
+ return None
+ definition = parsed.get("workflow_definition")
+ definition = definition if isinstance(definition, dict) else {}
+ raw_parameters = definition.get("parameters")
+ raw_parameters = raw_parameters if isinstance(raw_parameters, list) else []
+ keys = [
+ item["key"]
+ for item in raw_parameters
+ if isinstance(item, dict)
+ and isinstance(item.get("key"), str)
+ and item["key"].strip()
+ and item.get("parameter_type") in (None, "workflow")
+ ]
+ blocks = definition.get("blocks")
+ blocks = blocks if isinstance(blocks, list) else []
+ referenced = [key for key in keys if _value_references_key(blocks, key, _moustache_reference_pattern(key))]
+ return keys, referenced
+
+
+def grade_definition_criteria(criteria: list[CompletionCriterion], workflow_yaml: str | None) -> list[CriterionVerdict]:
+ """Grade definition-level criteria against the workflow YAML, never the run snapshot.
+
+ Deterministic check for the reusable-inputs class only; anything else is ``unknown``
+ (never ``no_evidence`` — runs cannot evidence the definition plane).
+ """
+ reference_state = _workflow_parameter_reference_state(workflow_yaml)
+ verdicts: list[CriterionVerdict] = []
+ for criterion in criteria:
+ if not _DEFINITION_PARAMETER_HINT_RE.search(criterion.outcome) or reference_state is None:
+ verdicts.append(
+ CriterionVerdict(criterion_id=criterion.id, state="unknown", reason_code="definition_unknown")
+ )
+ continue
+ defined, referenced = reference_state
+ if defined and referenced:
+ # When the criterion names specific inputs, each must match a defined
+ # parameter key; one stray parameter must not satisfy a multi-input ask.
+ # An unmatchable name degrades to unknown, not unsatisfied — extraction
+ # is heuristic and a false negative would drive repair of correct YAML.
+ named = _named_definition_inputs(criterion.outcome)
+ normalized_keys = [_normalize_input_phrase(key) for key in defined]
+ if named and not all(_input_matches_any_key(candidate, normalized_keys) for candidate in named):
+ verdicts.append(
+ CriterionVerdict(
+ criterion_id=criterion.id, state="unknown", reason_code="definition_parameters_unmatched"
+ )
+ )
+ continue
+ verdicts.append(
+ CriterionVerdict(
+ criterion_id=criterion.id,
+ state="satisfied",
+ reason_code="definition_parameters_referenced",
+ evidence_ref="workflow_yaml:" + ",".join(referenced[:8]),
+ )
+ )
+ elif defined:
+ verdicts.append(
+ CriterionVerdict(
+ criterion_id=criterion.id, state="unsatisfied", reason_code="definition_parameters_unreferenced"
+ )
+ )
+ else:
+ verdicts.append(
+ CriterionVerdict(
+ criterion_id=criterion.id, state="unsatisfied", reason_code="definition_parameters_missing"
+ )
+ )
+ return verdicts
+
+
+_DEFINITION_REASON_PREFIX = "definition_"
+
+
+def run_plane_all_no_evidence(result: CompletionVerificationResult) -> bool:
+ """Whether every run-plane verdict in an evaluated result is ``no_evidence``.
+
+ Definition-plane verdicts are excluded: they can never be ``no_evidence`` by
+ construction, so including them would permanently disarm the staleness tripwire
+ for mixed sets.
+ """
+ if result.status != "evaluated":
+ return False
+ run_verdicts = [v for v in result.verdicts if not v.reason_code.startswith(_DEFINITION_REASON_PREFIX)]
+ return bool(run_verdicts) and all(v.reason_code == "no_evidence" for v in run_verdicts)
+
+
+def combine_verification_results(
+ criterion_ids: list[str],
+ run_result: CompletionVerificationResult | None,
+ definition_verdicts: list[CriterionVerdict],
+) -> CompletionVerificationResult:
+ """One result spanning both evidence planes; a judge that could not evaluate
+ keeps the whole result unavailable so fail-closed messaging is preserved."""
+ if run_result is not None and run_result.status != "evaluated":
+ return run_result
+ verdict_by_id = {verdict.criterion_id: verdict for verdict in definition_verdicts}
+ if run_result is not None:
+ verdict_by_id.update({verdict.criterion_id: verdict for verdict in run_result.verdicts})
+ verdicts = [
+ verdict_by_id.get(cid, CriterionVerdict(criterion_id=cid, state="unknown", reason_code="unknown"))
+ for cid in criterion_ids
+ ]
+ return CompletionVerificationResult(status="evaluated", criterion_ids=list(criterion_ids), verdicts=verdicts)
+
+
async def evaluate_completion_criteria(
criteria: list[CompletionCriterion],
snapshot: RunEvidenceSnapshot,
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 6f15d34fa..7dfaccad0 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -51,6 +51,16 @@ class NarrativeBlock(TypedDict):
outcomeReason: NotRequired[str]
+class NarrativeOutcomeAdjudication(TypedDict):
+ satisfiedCount: int
+ unsatisfiedCount: int
+ unknownCount: int
+ # "verified_goal_satisfied" | "built_unverified".
+ claimTier: str
+ criteriaEpoch: NotRequired[int]
+ criteriaLifecycleReason: NotRequired[str]
+
+
# Mirror of the FE TurnNarrativeState; camelCase keys match the wire shape.
class TurnNarrativePayload(TypedDict):
turnId: str | None
@@ -61,9 +71,11 @@ class TurnNarrativePayload(TypedDict):
proposalDisposition: NotRequired[ProposalDisposition]
# TurnOutcome.response_kind value: "build" | "clarify" | "diagnose" | "refuse" | "recover".
responseKind: NotRequired[str]
- # The ADR-0005 terminal adjudication (enforcement.verified_goal_satisfied_context):
+ # The ADR-0005 terminal adjudication (enforcement.verified_goal_claim_authorized):
# True only when outcome evidence authorizes a tested-success claim.
verifiedSuccess: NotRequired[bool]
+ # Verdict-state summary from the turn's latest evaluated adjudication.
+ outcomeAdjudication: NotRequired[NarrativeOutcomeAdjudication]
designStarted: bool
designEnded: bool
draft: NarrativeDraft | None
@@ -79,6 +91,7 @@ class TurnNarrativePayload(TypedDict):
if TYPE_CHECKING:
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
+ from skyvern.forge.sdk.copilot.completion_criteria_store import CompletionCriteriaTurnState
from skyvern.forge.sdk.copilot.diagnosis_repair_contract import DiagnosisRepairContract
from skyvern.forge.sdk.copilot.narration import NarratorState
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
@@ -308,6 +321,16 @@ class AgentResult:
# Set when ``_update_workflow`` wrote canonical mid-turn (param / top-level
# settings changes); terminal handlers roll back on non-auto-accept.
canonical_was_persisted_due_to_param_change: bool = False
+ # Criteria lifecycle decision + adjudication counters the route persists
+ # after the turn; None when persisted criteria are disabled.
+ completion_criteria_turn_state: CompletionCriteriaTurnState | None = None
+
+
+@dataclass(frozen=True)
+class InFlightStreamToolCall:
+ call_id: str
+ tool_name: str
+ iteration: int
@dataclass
@@ -355,6 +378,12 @@ class CopilotContext(AgentContext):
# Tool tracking
consecutive_tool_tracker: list[str] = field(default_factory=list)
tool_activity: list[dict[str, Any]] = field(default_factory=list)
+ # A goal-satisfied stop raised from on_tool_end ends the SDK stream before
+ # the satisfying tool's tool_output event flushes; these carry what the
+ # exit path needs to emit the missing TOOL_RESULT frame.
+ in_flight_stream_tool_call: InFlightStreamToolCall | None = None
+ goal_satisfied_tool_name: str | None = None
+ goal_satisfied_tool_output: dict[str, Any] | None = None
latest_tool_blocker_signal: CopilotToolBlockerSignal | None = None
tool_blocker_signals: list[CopilotToolBlockerSignal] = field(default_factory=list)
turn_halt: TurnHalt | None = None
@@ -518,6 +547,7 @@ class CopilotContext(AgentContext):
# Set when ``_update_workflow`` wrote canonical mid-turn (param / top-level
# settings changes); terminal handlers roll back on non-auto-accept.
canonical_was_persisted_due_to_param_change: bool = False
+ completion_criteria_turn_state: CompletionCriteriaTurnState | None = None
prior_block_count: int | None = None
block_state_map: dict[str, str] = field(default_factory=dict)
block_started_at_map: dict[str, str] = field(default_factory=dict)
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index 9dc4cdcc9..4b8a6e856 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -305,6 +305,18 @@ def verified_goal_satisfied_context(ctx: CopilotContext) -> bool:
return not _verified_goal_likely_needs_more_work(ctx)
+def verified_goal_claim_authorized(ctx: CopilotContext) -> bool:
+ """Whether the terminal may CLAIM a tested success. Turn completion keeps
+ flowing through ``verified_goal_satisfied_context``; with persisted criteria
+ enabled, the claim tier additionally requires judge-confirmed outcome evidence —
+ criteria-less or judge-less terminals end the turn but render built-but-unverified.
+ With either flag off the judge cannot be authoritative, so the claim falls back
+ to the legacy gate."""
+ if not (settings.COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED and settings.COPILOT_OUTCOME_VERIFICATION_ENABLED):
+ return verified_goal_satisfied_context(ctx)
+ return outcome_fully_verified(ctx)
+
+
def gate_decision_trace_fields(ctx: CopilotContext) -> dict[str, bool]:
"""The terminal-gate decision plus the conjuncts that explain it.
@@ -315,6 +327,7 @@ def gate_decision_trace_fields(ctx: CopilotContext) -> dict[str, bool]:
"""
return {
"gate_satisfied": verified_goal_satisfied_context(ctx),
+ "gate_claim_authorized": verified_goal_claim_authorized(ctx),
"gate_last_test_ok": ctx.last_test_ok is True,
"gate_last_full_workflow_test_ok": ctx.last_full_workflow_test_ok is True,
"gate_diagnosis_contract_satisfies_goal": latest_diagnosis_contract_satisfies_goal(ctx),
diff --git a/skyvern/forge/sdk/copilot/hooks.py b/skyvern/forge/sdk/copilot/hooks.py
index 3637c5274..19441d913 100644
--- a/skyvern/forge/sdk/copilot/hooks.py
+++ b/skyvern/forge/sdk/copilot/hooks.py
@@ -143,4 +143,6 @@ class CopilotRunHooks(RunHooksBase):
if isinstance(parsed.get("data"), dict)
else None,
)
+ self._ctx.goal_satisfied_tool_name = tool_name
+ self._ctx.goal_satisfied_tool_output = dict(parsed)
raise CopilotGoalSatisfied()
diff --git a/skyvern/forge/sdk/copilot/outcome_verification_trace.py b/skyvern/forge/sdk/copilot/outcome_verification_trace.py
index e3bf6da32..8801eb177 100644
--- a/skyvern/forge/sdk/copilot/outcome_verification_trace.py
+++ b/skyvern/forge/sdk/copilot/outcome_verification_trace.py
@@ -45,6 +45,17 @@ def record_gate_decision(ctx: Any, fields: dict[str, Any]) -> None:
LOG.warning("failed to record copilot gate decision telemetry", exc_info=True)
+def record_criteria_lifecycle(ctx: Any, fields: dict[str, Any]) -> None:
+ """Attach criteria-lifecycle fields (epoch, decision reason, tripwire counters,
+ claim tier) to the per-turn snapshot so they ride the copilot.turn span."""
+ try:
+ snapshot = _snapshot(ctx)
+ if snapshot is not None:
+ snapshot.update(fields)
+ except Exception:
+ LOG.warning("failed to record copilot criteria lifecycle telemetry", exc_info=True)
+
+
def record_code_artifact_violations(ctx: Any, violations: list[str], offending_labels: list[str]) -> None:
"""Persist the code-artifact-metadata violation batch onto the turn snapshot.
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index a10741450..bdae25793 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import json
import re
from dataclasses import dataclass, field
from typing import Any, Literal, cast, get_args
@@ -127,6 +128,9 @@ _INVALID_CONDITIONAL_CONTAINER_MARKERS = (
_MAX_COMPLETION_CRITERIA = 8
_COMPLETION_CRITERION_OUTCOME_MAX_CHARS = 200
+CriterionLevel = Literal["definition", "run"]
+_CRITERION_LEVELS: frozenset[str] = frozenset({"definition", "run"})
+
@dataclass(frozen=True)
class CompletionCriterion:
@@ -134,6 +138,9 @@ class CompletionCriterion:
outcome: str
implicit: bool = False
method_mandated: bool = False
+ # "definition": a property of the workflow definition itself, graded against the
+ # YAML; "run": an end state only a run can evidence. Invalid input coerces to "run".
+ level: CriterionLevel = "run"
@dataclass
@@ -533,16 +540,20 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
outcome = " ".join(outcome_raw.split())[:_COMPLETION_CRITERION_OUTCOME_MAX_CHARS].strip()
if not outcome:
continue
- key = outcome.lower()
+ key = normalized_criterion_outcome_key(outcome)
if key in seen:
continue
seen.add(key)
+ level_raw = item.get("level")
criteria.append(
CompletionCriterion(
id=f"c{len(criteria)}",
outcome=outcome,
implicit=bool(item.get("implicit")),
method_mandated=bool(item.get("method_mandated")),
+ level=cast(CriterionLevel, level_raw)
+ if isinstance(level_raw, str) and level_raw in _CRITERION_LEVELS
+ else "run",
)
)
if len(criteria) >= _MAX_COMPLETION_CRITERIA:
@@ -550,6 +561,27 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
return criteria
+def normalized_criterion_outcome_key(outcome: str) -> str:
+ collapsed = " ".join((outcome or "").split())[:_COMPLETION_CRITERION_OUTCOME_MAX_CHARS]
+ return collapsed.strip().lower().rstrip(".!?;:,").strip()
+
+
+def _render_active_criteria_for_prompt(criteria: list[CompletionCriterion] | None) -> str:
+ if not criteria:
+ return ""
+ return json.dumps(
+ [
+ {
+ "outcome": criterion.outcome,
+ "implicit": criterion.implicit,
+ "method_mandated": criterion.method_mandated,
+ "level": criterion.level,
+ }
+ for criterion in criteria
+ ]
+ )
+
+
def _classifier_fallback_policy(ids: list[str], *, raw_secret_present: bool) -> RequestPolicy:
if raw_secret_present:
return RequestPolicy(
@@ -568,6 +600,8 @@ async def _classify_request(
chat_history: list[WorkflowCopilotChatHistoryMessage],
global_llm_context: str,
handler: Any,
+ *,
+ active_criteria: list[CompletionCriterion] | None = None,
) -> RequestPolicy:
ids = _credential_ids(user_message)
raw_secret_present = _raw_secret_detected(user_message)
@@ -600,6 +634,7 @@ async def _classify_request(
latest_assistant_turn=transcript.latest_assistant_turn,
retained_history=transcript.retained_history,
global_llm_context=escape_code_fences(redact_raw_secrets_for_prompt(global_llm_context)[:2048]),
+ active_completion_criteria=escape_code_fences(_render_active_criteria_for_prompt(active_criteria)),
)
try:
raw = await asyncio.wait_for(
@@ -1078,8 +1113,16 @@ async def build_request_policy(
global_llm_context: str,
organization_id: str,
handler: Any,
+ active_criteria: list[CompletionCriterion] | None = None,
) -> RequestPolicy:
- policy = await _classify_request(user_message, workflow_yaml, chat_history, global_llm_context, handler)
+ policy = await _classify_request(
+ user_message,
+ workflow_yaml,
+ chat_history,
+ global_llm_context,
+ handler,
+ active_criteria=active_criteria,
+ )
policy.raw_secret_detected = policy.raw_secret_detected or policy.credential_input_kind == "raw_secret"
policy.existing_workflow_credential_ids = sorted(workflow_credential_ids(workflow_yaml))
policy.existing_workflow_credential_origins = {
diff --git a/skyvern/forge/sdk/copilot/streaming_adapter.py b/skyvern/forge/sdk/copilot/streaming_adapter.py
index dd0a3a4c5..946857adf 100644
--- a/skyvern/forge/sdk/copilot/streaming_adapter.py
+++ b/skyvern/forge/sdk/copilot/streaming_adapter.py
@@ -12,6 +12,7 @@ import structlog
# Reuse the HTTP-logging redactor so SSE tool inputs and request-body logs
# share one exact-match sensitive-key policy.
from skyvern.forge.request_logging import redact_sensitive_fields
+from skyvern.forge.sdk.copilot.context import InFlightStreamToolCall
from skyvern.forge.sdk.copilot.narration import (
NarratorState,
TransitionKind,
@@ -141,6 +142,9 @@ async def stream_to_sse(
call_id = _get_raw_field(raw, "call_id") or _get_raw_field(raw, "id") or ""
tool_name = _get_raw_field(raw, "name") or "unknown"
call_id_to_name[call_id] = tool_name
+ ctx.in_flight_stream_tool_call = InFlightStreamToolCall(
+ call_id=call_id, tool_name=tool_name, iteration=iteration
+ )
narrator_state.record_activity(build_tool_call_activity(tool_name, iteration, call_id))
if not client_gone:
@@ -177,6 +181,7 @@ async def stream_to_sse(
raw = event.item.raw_item
call_id = _get_raw_field(raw, "call_id") or _get_raw_field(raw, "id") or ""
tool_name = call_id_to_name.get(call_id, "unknown")
+ ctx.in_flight_stream_tool_call = None
# Clear pending_tool_name so post-tool transitions describe
# what the agent just finished, not what it's still doing.
narrator_state.pending_tool_name = None
@@ -257,6 +262,44 @@ async def stream_to_sse(
await cancel_in_flight(narrator_state)
+async def flush_goal_satisfied_tool_result(stream: EventSourceStream, ctx: CopilotContext) -> None:
+ """Emit the TOOL_RESULT frame for the goal-satisfying tool.
+
+ The goal-satisfied stop is raised from ``on_tool_end`` before the SDK
+ yields the matching ``tool_output`` event, so the frame the loop above
+ would have sent never streams; the exit path calls this instead.
+ """
+ pending = ctx.in_flight_stream_tool_call
+ parsed = ctx.goal_satisfied_tool_output
+ tool_name = ctx.goal_satisfied_tool_name
+ ctx.in_flight_stream_tool_call = None
+ ctx.goal_satisfied_tool_output = None
+ ctx.goal_satisfied_tool_name = None
+ if pending is None or parsed is None or tool_name != pending.tool_name:
+ return
+ blocker_signals = _tool_blocker_signal_candidates(ctx)
+ summary = format_tool_result_for_user(pending.tool_name, parsed, blocker_signal=blocker_signals)
+ success = parsed.get("ok", True)
+ narrator_state = ctx.narrator_state
+ if narrator_state is not None:
+ narrator_state.record_activity(
+ build_tool_result_activity(pending.tool_name, summary, success, pending.iteration, pending.call_id)
+ )
+ if await stream.is_disconnected():
+ return
+ await stream.send(
+ WorkflowCopilotToolResultUpdate(
+ type=WorkflowCopilotStreamMessageType.TOOL_RESULT,
+ tool_name=pending.tool_name,
+ success=success,
+ summary=summary,
+ iteration=pending.iteration,
+ tool_call_id=pending.call_id,
+ detail=summarize_tool_result_detail(parsed, tool_name=pending.tool_name, blocker_signal=blocker_signals),
+ )
+ )
+
+
def _get_raw_field(raw: Any, key: str) -> Any:
if isinstance(raw, dict):
return raw.get(key)
diff --git a/skyvern/forge/sdk/copilot/tools/blockers.py b/skyvern/forge/sdk/copilot/tools/blockers.py
index 6eb2fc5c7..81728b921 100644
--- a/skyvern/forge/sdk/copilot/tools/blockers.py
+++ b/skyvern/forge/sdk/copilot/tools/blockers.py
@@ -863,16 +863,25 @@ def _looks_like_anti_bot_blocker(text: str) -> bool:
return any(term in lowered for term in _ANTI_BOT_BLOCKER_TERMS)
-def _structured_blocker_message(value: object, *, depth: int = 0, include_flag_keys: bool = False) -> str | None:
+def _structured_blocker_message(
+ value: object,
+ *,
+ depth: int = 0,
+ include_flag_keys: bool = False,
+ key_terms: frozenset[str] = _STRUCTURED_BLOCKER_KEY_TERMS,
+ declared_keys: frozenset[str] = frozenset(),
+) -> str | None:
if depth > 5:
return None
if isinstance(value, dict):
for key, item in value.items():
normalized_key = _normalize_structured_key(key)
+ if normalized_key in declared_keys:
+ continue
if not isinstance(item, str) or not item.strip():
continue
has_blocker_key = normalized_key in _STRUCTURED_BLOCKER_MESSAGE_KEYS or any(
- term in normalized_key for term in _STRUCTURED_BLOCKER_KEY_TERMS
+ term in normalized_key for term in key_terms
)
if has_blocker_key or (
normalized_key in {"message", "error", "failure_reason", "reason"}
@@ -884,12 +893,24 @@ def _structured_blocker_message(value: object, *, depth: int = 0, include_flag_k
if flagged:
return flagged
for item in value.values():
- nested = _structured_blocker_message(item, depth=depth + 1, include_flag_keys=include_flag_keys)
+ nested = _structured_blocker_message(
+ item,
+ depth=depth + 1,
+ include_flag_keys=include_flag_keys,
+ key_terms=key_terms,
+ declared_keys=declared_keys,
+ )
if nested:
return nested
elif isinstance(value, list):
for item in value:
- nested = _structured_blocker_message(item, depth=depth + 1, include_flag_keys=include_flag_keys)
+ nested = _structured_blocker_message(
+ item,
+ depth=depth + 1,
+ include_flag_keys=include_flag_keys,
+ key_terms=key_terms,
+ declared_keys=declared_keys,
+ )
if nested:
return nested
return None
@@ -917,7 +938,31 @@ def _blocker_flag_or_status_message(value: dict[str, Any]) -> str | None:
return None
-def _run_blocks_structured_blocker_message(result: dict[str, Any]) -> str | None:
+def _declared_code_output_keys(copilot_ctx: Any, block_label: object) -> frozenset[str]:
+ """Output keys the block's code-artifact metadata declares as goal content
+ (claimed-outcome ids, entities, required tokens) — the #12034 typed source.
+ A declared key is never string-matched into a blocker signal."""
+ metadata = getattr(copilot_ctx, "code_artifact_metadata", None) if copilot_ctx is not None else None
+ if not isinstance(metadata, dict) or not isinstance(block_label, str):
+ return frozenset()
+ entry = metadata.get(block_label)
+ if not isinstance(entry, dict):
+ return frozenset()
+ declared: set[str] = set()
+ claims = entry.get("claimed_outcomes")
+ for claim in claims if isinstance(claims, list) else []:
+ if not isinstance(claim, dict):
+ continue
+ for field_name in ("id", "entities", "required_tokens"):
+ value = claim.get(field_name)
+ values = value if isinstance(value, list) else [value]
+ declared.update(
+ _normalize_structured_key(item) for item in values if isinstance(item, str) and item.strip()
+ )
+ return frozenset(declared)
+
+
+def _run_blocks_structured_blocker_message(result: dict[str, Any], copilot_ctx: Any = None) -> str | None:
data = result.get("data")
if not isinstance(data, dict):
return None
@@ -934,7 +979,15 @@ def _run_blocks_structured_blocker_message(result: dict[str, Any]) -> str | None
if block.get("status") != "completed":
continue
if _is_code_block_type(block_type):
- blocker = _structured_blocker_message(block.get("extracted_data"), include_flag_keys=True)
+ # Code-block outputs are arbitrary JSON the model authored: key matching
+ # uses the strict term set (broad terms like ``verification`` belong to
+ # the page-text arms) and metadata-declared goal keys are exempt.
+ blocker = _structured_blocker_message(
+ block.get("extracted_data"),
+ include_flag_keys=True,
+ key_terms=_STRICT_BLOCKER_FLAG_TERMS,
+ declared_keys=_declared_code_output_keys(copilot_ctx, block.get("label")),
+ )
elif block_type in _DATA_PRODUCING_BLOCK_TYPES:
payload = _block_data_payload(block.get("extracted_data"), block_type)
blocker = _structured_blocker_message(payload)
@@ -945,26 +998,30 @@ def _run_blocks_structured_blocker_message(result: dict[str, Any]) -> str | None
return None
-def _is_blocker_term_key(key: object) -> bool:
+def _is_blocker_term_key(key: object, declared_keys: frozenset[str] = frozenset()) -> bool:
normalized_key = _normalize_structured_key(key)
- return any(term in normalized_key for term in _STRUCTURED_BLOCKER_KEY_TERMS)
+ if normalized_key in declared_keys:
+ return False
+ return any(term in normalized_key for term in _STRICT_BLOCKER_FLAG_TERMS)
-def _code_output_contains_collection(value: Any, *, depth: int = 0) -> bool:
+def _code_output_contains_collection(
+ value: Any, *, depth: int = 0, declared_keys: frozenset[str] = frozenset()
+) -> bool:
if depth > 5:
return False
if isinstance(value, (list, tuple)):
return True
if isinstance(value, dict):
return any(
- _code_output_contains_collection(item, depth=depth + 1)
+ _code_output_contains_collection(item, depth=depth + 1, declared_keys=declared_keys)
for key, item in value.items()
- if not _is_blocker_term_key(key)
+ if not _is_blocker_term_key(key, declared_keys)
)
return False
-def _code_output_has_goal_content(value: Any, *, depth: int = 0) -> bool:
+def _code_output_has_goal_content(value: Any, *, depth: int = 0, declared_keys: frozenset[str] = frozenset()) -> bool:
"""Goal content in a code block's output: a non-empty string, truthy number, or
non-empty collection surviving after blocker-term, status, and boolean entries
are stripped (status/state values are machine shape, not goal data)."""
@@ -980,9 +1037,10 @@ def _code_output_has_goal_content(value: Any, *, depth: int = 0) -> bool:
return len(value) > 0
if isinstance(value, dict):
return any(
- _code_output_has_goal_content(item, depth=depth + 1)
+ _code_output_has_goal_content(item, depth=depth + 1, declared_keys=declared_keys)
for key, item in value.items()
- if not _is_blocker_term_key(key) and _normalize_structured_key(key) not in _BLOCKER_STATUS_KEYS
+ if not _is_blocker_term_key(key, declared_keys)
+ and _normalize_structured_key(key) not in _BLOCKER_STATUS_KEYS
)
return False
@@ -1487,7 +1545,13 @@ def _analyze_run_blocks(
extracted = block.get("extracted_data")
if extracted is None:
continue
- structured_blocker = _structured_blocker_message(extracted, include_flag_keys=True)
+ declared_keys = _declared_code_output_keys(copilot_ctx, block.get("label"))
+ structured_blocker = _structured_blocker_message(
+ extracted,
+ include_flag_keys=True,
+ key_terms=_STRICT_BLOCKER_FLAG_TERMS,
+ declared_keys=declared_keys,
+ )
if structured_blocker:
texts_to_scan.append(structured_blocker)
goal_value_paths = _goal_value_paths_for_code_block(copilot_ctx, block.get("label"))
@@ -1505,9 +1569,9 @@ def _analyze_run_blocks(
continue
# A code output joins the emptiness denominator only when it declares a
# collection shape; action-only outputs are exempt.
- if _code_output_contains_collection(extracted):
+ if _code_output_contains_collection(extracted, declared_keys=declared_keys):
has_data_blocks = True
- if _code_output_has_goal_content(extracted):
+ if _code_output_has_goal_content(extracted, declared_keys=declared_keys):
any_data_output = True
combined = "\n".join(texts_to_scan)
diff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.py
index ce64a9474..e3278181b 100644
--- a/skyvern/forge/sdk/copilot/tools/completion.py
+++ b/skyvern/forge/sdk/copilot/tools/completion.py
@@ -4,16 +4,21 @@ from typing import Any
import structlog
from skyvern.config import settings
+from skyvern.forge.sdk.copilot.completion_criteria_store import note_adjudication_on_turn_state
from skyvern.forge.sdk.copilot.completion_verification import (
CompletionVerificationResult,
CriterionVerdict,
RunEvidenceSnapshot,
+ combine_verification_results,
evaluate_completion_criteria,
+ grade_definition_criteria,
+ resolve_unknown,
summarize_unsatisfied_outcomes,
)
from skyvern.forge.sdk.copilot.enforcement import _goal_likely_needs_more_blocks
from skyvern.forge.sdk.copilot.llm_config import resolve_main_copilot_handler
from skyvern.forge.sdk.copilot.outcome_verification_trace import record_completion_verification
+from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
from ._shared import (
@@ -40,6 +45,34 @@ def _completion_verification_criteria(copilot_ctx: Any) -> list[Any]:
return [c for c in (policy.completion_criteria if policy is not None else []) if not c.method_mandated]
+def _split_criteria_by_plane(criteria: list[Any]) -> tuple[list[CompletionCriterion], list[CompletionCriterion]]:
+ if not settings.COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED:
+ return list(criteria), []
+ run_criteria = [c for c in criteria if getattr(c, "level", "run") != "definition"]
+ definition_criteria = [c for c in criteria if getattr(c, "level", "run") == "definition"]
+ return run_criteria, definition_criteria
+
+
+def _definition_plane_workflow_yaml(copilot_ctx: Any) -> str | None:
+ last_yaml = getattr(copilot_ctx, "last_workflow_yaml", None)
+ if isinstance(last_yaml, str) and last_yaml.strip():
+ return last_yaml
+ initial_yaml = getattr(copilot_ctx, "workflow_yaml", None)
+ return initial_yaml if isinstance(initial_yaml, str) else None
+
+
+def _record_adjudication_on_turn_state(copilot_ctx: Any, verification: CompletionVerificationResult | None) -> None:
+ if verification is None or verification.status != "evaluated":
+ return
+ note_adjudication_on_turn_state(
+ getattr(copilot_ctx, "completion_criteria_turn_state", None),
+ verification,
+ fully_satisfied_workflow_yaml=_definition_plane_workflow_yaml(copilot_ctx)
+ if verification.is_fully_satisfied()
+ else None,
+ )
+
+
def _verified_context_block_labels_for_snapshot(
copilot_ctx: Any, current_labels: list[str], executed_labels: list[str]
) -> list[str]:
@@ -96,34 +129,45 @@ async def _maybe_run_completion_verification_from_page_observation(
criteria = _completion_verification_criteria(copilot_ctx)
if not criteria:
return None
- handler = await _completion_verification_handler(copilot_ctx)
- if handler is None:
- return None
- remaining = _copilot_seconds_remaining(copilot_ctx)
- if (
- remaining is not None
- and remaining
- <= settings.COPILOT_FEASIBILITY_GATE_TIMEOUT_SECONDS + _COMPLETION_VERIFICATION_BUDGET_MARGIN_SECONDS
- ):
- verification = CompletionVerificationResult(status="unavailable")
+ run_criteria, definition_criteria = _split_criteria_by_plane(criteria)
+ criterion_ids = [criterion.id for criterion in criteria]
+ definition_verdicts = (
+ grade_definition_criteria(definition_criteria, _definition_plane_workflow_yaml(copilot_ctx))
+ if definition_criteria
+ else []
+ )
+ if not run_criteria:
+ verification = combine_verification_results(criterion_ids, None, definition_verdicts)
else:
- snapshot = _build_page_observation_evidence_snapshot(
- copilot_ctx,
- url=url,
- title=title,
- observed_data=observed_data,
- )
- if not snapshot.has_evidence():
- verification = CompletionVerificationResult(
- status="evaluated",
- criterion_ids=[criterion.id for criterion in criteria],
- verdicts=[
- CriterionVerdict(criterion_id=criterion.id, satisfied=False, reason_code="no_evidence")
- for criterion in criteria
- ],
- )
+ handler = await _completion_verification_handler(copilot_ctx)
+ if handler is None:
+ return None
+ remaining = _copilot_seconds_remaining(copilot_ctx)
+ if (
+ remaining is not None
+ and remaining
+ <= settings.COPILOT_FEASIBILITY_GATE_TIMEOUT_SECONDS + _COMPLETION_VERIFICATION_BUDGET_MARGIN_SECONDS
+ ):
+ verification = CompletionVerificationResult(status="unavailable")
else:
- verification = await evaluate_completion_criteria(criteria, snapshot, handler)
+ snapshot = _build_page_observation_evidence_snapshot(
+ copilot_ctx,
+ url=url,
+ title=title,
+ observed_data=observed_data,
+ )
+ if not snapshot.has_evidence():
+ run_result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=[criterion.id for criterion in run_criteria],
+ verdicts=[
+ CriterionVerdict(criterion_id=criterion.id, state="unsatisfied", reason_code="no_evidence")
+ for criterion in run_criteria
+ ],
+ )
+ else:
+ run_result = await evaluate_completion_criteria(run_criteria, snapshot, handler)
+ verification = combine_verification_results(criterion_ids, run_result, definition_verdicts)
if (
isinstance(existing, CompletionVerificationResult)
@@ -134,6 +178,7 @@ async def _maybe_run_completion_verification_from_page_observation(
copilot_ctx.completion_verification_result = verification
record_completion_verification(copilot_ctx, verification)
+ _record_adjudication_on_turn_state(copilot_ctx, verification)
if verification.status == "evaluated":
_emit_completion_verification_trace(copilot_ctx, verification)
return verification
@@ -161,7 +206,7 @@ def _is_outcome_evidence_candidate(copilot_ctx: Any, result: dict[str, Any]) ->
"""
if not bool(result.get("ok", False)):
return False
- if _run_blocks_structured_blocker_message(result):
+ if _run_blocks_structured_blocker_message(result, copilot_ctx):
return False
_anti_bot, empty_data_blocks, _categories = _analyze_run_blocks(result, copilot_ctx)
return not empty_data_blocks
@@ -177,7 +222,7 @@ def _is_unfinished_run_verification_candidate(copilot_ctx: Any, result: dict[str
return False
if _active_run_terminal_evidence_detected(result):
return False
- if _run_blocks_structured_blocker_message(result):
+ if _run_blocks_structured_blocker_message(result, copilot_ctx):
return False
data = result.get("data")
if not isinstance(data, dict):
@@ -236,6 +281,15 @@ async def _maybe_run_completion_verification(
or _is_unfinished_run_verification_candidate(copilot_ctx, result)
):
return None
+ run_criteria, definition_criteria = _split_criteria_by_plane(criteria)
+ criterion_ids = [criterion.id for criterion in criteria]
+ definition_verdicts = (
+ grade_definition_criteria(definition_criteria, _definition_plane_workflow_yaml(copilot_ctx))
+ if definition_criteria
+ else []
+ )
+ if not run_criteria:
+ return combine_verification_results(criterion_ids, None, definition_verdicts)
# A missing judge handler is an infra/config state, not a transient failure:
# fall back to the prior gate rather than fail closed on every run.
handler = await _completion_verification_handler(copilot_ctx)
@@ -248,15 +302,17 @@ async def _maybe_run_completion_verification(
return CompletionVerificationResult(status="unavailable")
snapshot = _build_run_evidence_snapshot(copilot_ctx, result)
if not snapshot.has_evidence():
- return CompletionVerificationResult(
+ run_result = CompletionVerificationResult(
status="evaluated",
- criterion_ids=[criterion.id for criterion in criteria],
+ criterion_ids=[criterion.id for criterion in run_criteria],
verdicts=[
- CriterionVerdict(criterion_id=criterion.id, satisfied=False, reason_code="no_evidence")
- for criterion in criteria
+ CriterionVerdict(criterion_id=criterion.id, state="unsatisfied", reason_code="no_evidence")
+ for criterion in run_criteria
],
)
- return await evaluate_completion_criteria(criteria, snapshot, handler)
+ else:
+ run_result = await evaluate_completion_criteria(run_criteria, snapshot, handler)
+ return combine_verification_results(criterion_ids, run_result, definition_verdicts)
def _outcome_unverified_reason(
@@ -271,9 +327,17 @@ def _outcome_unverified_reason(
criteria = list(policy.completion_criteria) if policy is not None else []
unmet = summarize_unsatisfied_outcomes(completion_verification, criteria)
detail = f": {unmet}" if unmet else ""
+ turn_state = getattr(copilot_ctx, "completion_criteria_turn_state", None)
+ known_good = (
+ " A previously tested revision of this workflow satisfied every criterion; if repairs regress "
+ "working blocks, prefer restoring that revision over rewriting them."
+ if turn_state is not None and getattr(turn_state, "known_good_yaml_available", False)
+ else ""
+ )
return (
f"The run completed but did not demonstrate the goal outcome(s){detail}. "
- "Add an end-state confirmation (an extraction or validation block) that observes the outcome, then re-run."
+ "Add an end-state confirmation (an extraction or validation block) that observes the outcome, "
+ f"then re-run.{known_good}"
)
# An 'unavailable' result reaches here only when verification was required;
# fail closed and ask for a re-run rather than claim an unverified success.
@@ -299,6 +363,12 @@ def _outcome_failure_warrants_repair(
return False
if any(verdict.reason_code == "evidence_contradicts" for verdict in completion_verification.verdicts):
return True
+ # Repair needs at least one affirmatively unsatisfied criterion; unknown alone
+ # (absent judge signal, unmappable definition checks) never warrants repair.
+ if settings.COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED and not any(
+ resolve_unknown(verdict.state) == "unsatisfied" for verdict in completion_verification.verdicts
+ ):
+ return False
return _current_workflow_has_evidence_block(copilot_ctx)
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 91ef6520f..9afc7145c 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -89,6 +89,7 @@ from .completion import (
_maybe_run_completion_verification,
_outcome_failure_warrants_repair,
_outcome_unverified_reason,
+ _record_adjudication_on_turn_state,
)
from .composition_capture import (
ActiveRunTerminalEvidenceSample,
@@ -1417,6 +1418,7 @@ def _record_run_blocks_result(
run_id = data.get("workflow_run_id") if isinstance(data, dict) else None
copilot_ctx.completion_verification_result = completion_verification
record_completion_verification(copilot_ctx, completion_verification)
+ _record_adjudication_on_turn_state(copilot_ctx, completion_verification)
if completion_verification is not None and completion_verification.status == "evaluated":
_emit_completion_verification_trace(copilot_ctx, completion_verification)
copilot_ctx.last_run_blocks_workflow_run_id = run_id if isinstance(run_id, str) else None
@@ -1445,7 +1447,7 @@ def _record_run_blocks_result(
copilot_ctx.post_run_page_observation_after_failed_test = False
copilot_ctx.post_run_current_page_inspection_workflow_run_id = None
- structured_blocker = _run_blocks_structured_blocker_message(result)
+ structured_blocker = _run_blocks_structured_blocker_message(result, copilot_ctx)
anti_bot_match, empty_data_blocks, failure_categories = _analyze_run_blocks(result, copilot_ctx)
record_gate_decision(
copilot_ctx,
diff --git a/skyvern/forge/sdk/db/id.py b/skyvern/forge/sdk/db/id.py
index c1a4d4c5b..b1156cce2 100644
--- a/skyvern/forge/sdk/db/id.py
+++ b/skyvern/forge/sdk/db/id.py
@@ -74,6 +74,7 @@ WORKFLOW_TEMPLATE_PREFIX = "wt"
ORGANIZATION_BILLING_PREFIX = "ob"
WORKFLOW_COPILOT_CHAT_PREFIX = "wcc"
WORKFLOW_COPILOT_CHAT_MESSAGE_PREFIX = "wccm"
+WORKFLOW_COPILOT_COMPLETION_CRITERIA_SET_PREFIX = "wccs"
SCRIPT_FALLBACK_EPISODE_PREFIX = "sfe"
WORKFLOW_SCHEDULE_PREFIX = "wfs"
TAG_EVENT_PREFIX = "tge"
@@ -310,6 +311,11 @@ def generate_workflow_copilot_chat_message_id() -> str:
return f"{WORKFLOW_COPILOT_CHAT_MESSAGE_PREFIX}_{int_id}"
+def generate_workflow_copilot_completion_criteria_set_id() -> str:
+ int_id = generate_id()
+ return f"{WORKFLOW_COPILOT_COMPLETION_CRITERIA_SET_PREFIX}_{int_id}"
+
+
def generate_script_fallback_episode_id() -> str:
int_id = generate_id()
return f"{SCRIPT_FALLBACK_EPISODE_PREFIX}_{int_id}"
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index 225ee713e..be16e0963 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -62,6 +62,7 @@ from skyvern.forge.sdk.db.id import (
generate_totp_code_id,
generate_workflow_copilot_chat_id,
generate_workflow_copilot_chat_message_id,
+ generate_workflow_copilot_completion_criteria_set_id,
generate_workflow_id,
generate_workflow_parameter_id,
generate_workflow_permanent_id,
@@ -1502,6 +1503,36 @@ class WorkflowCopilotChatMessageModel(Base):
)
+class WorkflowCopilotCompletionCriteriaSetModel(Base):
+ __tablename__ = "workflow_copilot_completion_criteria_sets"
+ __table_args__ = (Index("wcccs_org_chat_index", "organization_id", "workflow_copilot_chat_id"),)
+
+ completion_criteria_set_id = Column(
+ String, primary_key=True, default=generate_workflow_copilot_completion_criteria_set_id
+ )
+ organization_id = Column(String, nullable=False)
+ workflow_copilot_chat_id = Column(String, nullable=False)
+ goal_epoch = Column(Integer, nullable=False)
+ status = Column(String, nullable=False, default="active")
+ criteria = Column(JSON, nullable=False)
+ source_turn_id = Column(String, nullable=True)
+ source_goal_text = Column(UnicodeText, nullable=True)
+ consecutive_all_no_evidence = Column(Integer, nullable=False, default=0)
+ tripwire_fired = Column(Boolean, nullable=False, default=False)
+ last_fully_satisfied_workflow_yaml = Column(UnicodeText, nullable=True)
+ superseded_by_set_id = Column(String, nullable=True)
+ superseded_at = Column(DateTime, nullable=True)
+ supersede_reason = Column(String, nullable=True)
+
+ created_at = Column(DateTime, default=datetime.datetime.utcnow, nullable=False)
+ modified_at = Column(
+ DateTime,
+ default=datetime.datetime.utcnow,
+ onupdate=datetime.datetime.utcnow,
+ nullable=False,
+ )
+
+
class ScriptFallbackEpisodeModel(Base):
__tablename__ = "script_fallback_episodes"
__table_args__ = (
diff --git a/skyvern/forge/sdk/db/repositories/workflow_parameters.py b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
index 23c6f0996..53eb9ef72 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_parameters.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_parameters.py
@@ -29,6 +29,7 @@ from skyvern.forge.sdk.db.models import (
TaskModel,
WorkflowCopilotChatMessageModel,
WorkflowCopilotChatModel,
+ WorkflowCopilotCompletionCriteriaSetModel,
WorkflowParameterModel,
)
from skyvern.forge.sdk.db.utils import (
@@ -46,6 +47,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (
WorkflowCopilotChat,
WorkflowCopilotChatMessage,
WorkflowCopilotChatSender,
+ WorkflowCopilotCompletionCriteriaSet,
)
from skyvern.forge.sdk.workflow.models.parameter import (
PARAMETER_TYPE,
@@ -593,6 +595,114 @@ class WorkflowParametersRepository(BaseRepository):
return None
return WorkflowCopilotChat.model_validate(chat)
+ @db_operation("get_latest_workflow_copilot_completion_criteria_set")
+ async def get_latest_workflow_copilot_completion_criteria_set(
+ self,
+ organization_id: str,
+ workflow_copilot_chat_id: str,
+ ) -> WorkflowCopilotCompletionCriteriaSet | None:
+ async with self.Session() as session:
+ query = (
+ select(WorkflowCopilotCompletionCriteriaSetModel)
+ .filter(WorkflowCopilotCompletionCriteriaSetModel.organization_id == organization_id)
+ .filter(WorkflowCopilotCompletionCriteriaSetModel.workflow_copilot_chat_id == workflow_copilot_chat_id)
+ .order_by(WorkflowCopilotCompletionCriteriaSetModel.goal_epoch.desc())
+ .limit(1)
+ )
+ row = (await session.scalars(query)).first()
+ if not row:
+ return None
+ return WorkflowCopilotCompletionCriteriaSet.model_validate(row)
+
+ @db_operation("create_workflow_copilot_completion_criteria_set")
+ async def create_workflow_copilot_completion_criteria_set(
+ self,
+ organization_id: str,
+ workflow_copilot_chat_id: str,
+ goal_epoch: int,
+ criteria: list[dict],
+ source_turn_id: str | None = None,
+ source_goal_text: str | None = None,
+ consecutive_all_no_evidence: int = 0,
+ last_fully_satisfied_workflow_yaml: str | None = None,
+ ) -> WorkflowCopilotCompletionCriteriaSet:
+ async with self.Session() as session:
+ new_set = WorkflowCopilotCompletionCriteriaSetModel(
+ organization_id=organization_id,
+ workflow_copilot_chat_id=workflow_copilot_chat_id,
+ goal_epoch=goal_epoch,
+ status="active",
+ criteria=criteria,
+ source_turn_id=source_turn_id,
+ source_goal_text=source_goal_text,
+ consecutive_all_no_evidence=consecutive_all_no_evidence,
+ tripwire_fired=False,
+ last_fully_satisfied_workflow_yaml=last_fully_satisfied_workflow_yaml,
+ )
+ session.add(new_set)
+ await session.commit()
+ await session.refresh(new_set)
+ return WorkflowCopilotCompletionCriteriaSet.model_validate(new_set)
+
+ @db_operation("supersede_workflow_copilot_completion_criteria_set")
+ async def supersede_workflow_copilot_completion_criteria_set(
+ self,
+ organization_id: str,
+ completion_criteria_set_id: str,
+ supersede_reason: str,
+ superseded_by_set_id: str | None = None,
+ ) -> None:
+ async with self.Session() as session:
+ row = (
+ await session.scalars(
+ select(WorkflowCopilotCompletionCriteriaSetModel)
+ .where(WorkflowCopilotCompletionCriteriaSetModel.organization_id == organization_id)
+ .where(
+ WorkflowCopilotCompletionCriteriaSetModel.completion_criteria_set_id
+ == completion_criteria_set_id
+ )
+ )
+ ).first()
+ if not row:
+ return
+ row.status = "superseded"
+ row.supersede_reason = supersede_reason
+ row.superseded_by_set_id = superseded_by_set_id
+ row.superseded_at = datetime.now(timezone.utc).replace(tzinfo=None)
+ if supersede_reason == "tripwire":
+ row.tripwire_fired = True
+ await session.commit()
+
+ @db_operation("update_workflow_copilot_completion_criteria_set_state")
+ async def update_workflow_copilot_completion_criteria_set_state(
+ self,
+ organization_id: str,
+ completion_criteria_set_id: str,
+ consecutive_all_no_evidence: int | None = None,
+ tripwire_fired: bool | None = None,
+ last_fully_satisfied_workflow_yaml: str | None = None,
+ ) -> None:
+ async with self.Session() as session:
+ row = (
+ await session.scalars(
+ select(WorkflowCopilotCompletionCriteriaSetModel)
+ .where(WorkflowCopilotCompletionCriteriaSetModel.organization_id == organization_id)
+ .where(
+ WorkflowCopilotCompletionCriteriaSetModel.completion_criteria_set_id
+ == completion_criteria_set_id
+ )
+ )
+ ).first()
+ if not row:
+ return
+ if consecutive_all_no_evidence is not None:
+ row.consecutive_all_no_evidence = consecutive_all_no_evidence
+ if tripwire_fired is not None:
+ row.tripwire_fired = tripwire_fired
+ if last_fully_satisfied_workflow_yaml is not None:
+ row.last_fully_satisfied_workflow_yaml = last_fully_satisfied_workflow_yaml
+ await session.commit()
+
@db_operation("get_task_generation_by_prompt_hash")
async def get_task_generation_by_prompt_hash(
self,
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index 5f228047d..19f555329 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -26,6 +26,14 @@ from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType, LogEntityT
from skyvern.forge.sdk.copilot.agent import run_copilot_agent
from skyvern.forge.sdk.copilot.attribution import is_copilot_born_initial_write, resolve_copilot_created_by_stamp
from skyvern.forge.sdk.copilot.block_type_aliases import normalize_copilot_block_type_alias
+from skyvern.forge.sdk.copilot.completion_criteria_store import (
+ CRITERIA_SET_STATUS_ACTIVE,
+ StoredCriteriaSet,
+ StoredCriteriaSnapshot,
+ criteria_from_json,
+ criteria_to_json,
+ plan_persistence,
+)
from skyvern.forge.sdk.copilot.config import CopilotConfig
from skyvern.forge.sdk.copilot.context import AgentResult, ProposalDisposition, TurnNarrativePayload
from skyvern.forge.sdk.copilot.llm_config import resolve_main_copilot_handler
@@ -385,6 +393,87 @@ async def _clear_proposed_workflow(chat: Any) -> None:
)
+async def _load_completion_criteria_snapshot(chat: Any) -> StoredCriteriaSnapshot | None:
+ """None disables the lifecycle for this turn (flag off, or load failure —
+ which degrades to today's per-turn regeneration rather than risking a
+ duplicate-epoch write)."""
+ if not (settings.COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED and settings.COPILOT_OUTCOME_VERIFICATION_ENABLED):
+ return None
+ try:
+ latest = await app.DATABASE.workflow_params.get_latest_workflow_copilot_completion_criteria_set(
+ organization_id=chat.organization_id,
+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,
+ )
+ except Exception:
+ LOG.warning("copilot completion criteria snapshot load failed", exc_info=True)
+ return None
+ if latest is None:
+ return StoredCriteriaSnapshot()
+ active = None
+ if latest.status == CRITERIA_SET_STATUS_ACTIVE:
+ active = StoredCriteriaSet(
+ set_id=latest.completion_criteria_set_id,
+ goal_epoch=latest.goal_epoch,
+ criteria=criteria_from_json(latest.criteria),
+ consecutive_all_no_evidence=latest.consecutive_all_no_evidence,
+ tripwire_fired=latest.tripwire_fired,
+ last_fully_satisfied_workflow_yaml=latest.last_fully_satisfied_workflow_yaml,
+ )
+ return StoredCriteriaSnapshot(active=active, next_epoch=latest.goal_epoch + 1)
+
+
+async def _persist_completion_criteria_state(chat: Any, agent_result: AgentResult, user_message: str) -> None:
+ plan = plan_persistence(getattr(agent_result, "completion_criteria_turn_state", None))
+ if plan is None:
+ return
+ try:
+ if plan.creates_set:
+ new_set = await app.DATABASE.workflow_params.create_workflow_copilot_completion_criteria_set(
+ organization_id=chat.organization_id,
+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,
+ goal_epoch=plan.create_epoch or 1,
+ criteria=criteria_to_json(plan.create_criteria),
+ source_turn_id=agent_result.turn_id,
+ source_goal_text=user_message[:2000] if user_message else None,
+ consecutive_all_no_evidence=plan.counter_value,
+ last_fully_satisfied_workflow_yaml=plan.fully_satisfied_workflow_yaml,
+ )
+ if plan.supersede_set_id:
+ await app.DATABASE.workflow_params.supersede_workflow_copilot_completion_criteria_set(
+ organization_id=chat.organization_id,
+ completion_criteria_set_id=plan.supersede_set_id,
+ supersede_reason=plan.supersede_reason or "not_subset",
+ superseded_by_set_id=new_set.completion_criteria_set_id,
+ )
+ else:
+ if plan.counter_set_id:
+ await app.DATABASE.workflow_params.update_workflow_copilot_completion_criteria_set_state(
+ organization_id=chat.organization_id,
+ completion_criteria_set_id=plan.counter_set_id,
+ consecutive_all_no_evidence=plan.counter_value,
+ tripwire_fired=plan.tripwire_fired,
+ last_fully_satisfied_workflow_yaml=plan.fully_satisfied_workflow_yaml,
+ )
+ if plan.supersede_set_id:
+ await app.DATABASE.workflow_params.supersede_workflow_copilot_completion_criteria_set(
+ organization_id=chat.organization_id,
+ completion_criteria_set_id=plan.supersede_set_id,
+ supersede_reason=plan.supersede_reason or "tripwire",
+ )
+ LOG.info(
+ "copilot completion criteria persisted",
+ criteria_set_created=plan.creates_set,
+ criteria_epoch=plan.create_epoch,
+ criteria_superseded_set_id=plan.supersede_set_id,
+ criteria_supersede_reason=plan.supersede_reason,
+ criteria_consecutive_all_no_evidence=plan.counter_value,
+ criteria_tripwire_fired=plan.tripwire_fired,
+ )
+ except Exception:
+ # A failed persist degrades to per-turn regeneration on the next turn.
+ LOG.warning("copilot completion criteria persist failed", exc_info=True)
+
+
def _build_proposed_workflow_data(updated_workflow: Workflow, agent_result: AgentResult) -> dict[str, Any]:
proposed_data = dict(updated_workflow.model_dump(mode="json"))
if agent_result.workflow_yaml:
@@ -593,6 +682,7 @@ async def _finalise_normal_turn(
raise
await _persist_proposed_workflow_state(chat, agent_result, restored)
+ await _persist_completion_criteria_state(chat, agent_result, chat_request.message)
proposal_disposition = _proposal_disposition(agent_result)
narrative_payload = _with_terminal_narrative_metadata(
agent_result.narrative_payload,
@@ -1677,6 +1767,8 @@ async def _new_copilot_chat_post(
elif original_workflow is not None and original_workflow.workflow_definition is not None:
prior_block_count = len(original_workflow.workflow_definition.blocks or [])
+ stored_completion_criteria = await _load_completion_criteria_snapshot(chat)
+
with bind_copilot_session_id(chat.workflow_copilot_chat_id):
agent_result = await run_copilot_agent(
stream=stream,
@@ -1692,6 +1784,7 @@ async def _new_copilot_chat_post(
turn_id=turn_id,
prior_copilot_workflow_yaml=prior_copilot_workflow_yaml,
prior_block_count=prior_block_count,
+ stored_completion_criteria=stored_completion_criteria,
)
if getattr(agent_result, "cancelled", False):
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 1da867c38..1934b3897 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -21,6 +21,27 @@ class WorkflowCopilotChat(BaseModel):
modified_at: datetime = Field(..., description="When the chat was last modified")
+class WorkflowCopilotCompletionCriteriaSet(BaseModel):
+ model_config = ConfigDict(from_attributes=True)
+
+ completion_criteria_set_id: str
+ organization_id: str
+ workflow_copilot_chat_id: str
+ goal_epoch: int
+ status: str
+ criteria: list[dict]
+ source_turn_id: str | None = None
+ source_goal_text: str | None = None
+ consecutive_all_no_evidence: int = 0
+ tripwire_fired: bool = False
+ last_fully_satisfied_workflow_yaml: str | None = None
+ superseded_by_set_id: str | None = None
+ superseded_at: datetime | None = None
+ supersede_reason: str | None = None
+ created_at: datetime
+ modified_at: datetime
+
+
class WorkflowCopilotChatSender(StrEnum):
USER = "user"
AI = "ai"
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 72f93a4d5..df7247283 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -559,6 +559,10 @@ class TestVerifiedGoalSatisfiedStop:
result=result,
)
+ assert ctx.goal_satisfied_tool_name == "update_and_run_blocks"
+ assert ctx.goal_satisfied_tool_output is not None
+ assert ctx.goal_satisfied_tool_output["ok"] is True
+
assert ctx.tool_activity[-1]["tool"] == "update_and_run_blocks"
def test_wrapped_goal_satisfied_error_context_is_recognized(self) -> None:
@@ -599,7 +603,8 @@ class TestVerifiedGoalSatisfiedStop:
assert not verified_goal_satisfied_context(ctx)
- def test_goal_satisfied_exit_result_surfaces_tested_workflow(self) -> None:
+ @pytest.mark.asyncio
+ async def test_goal_satisfied_exit_result_surfaces_tested_workflow(self) -> None:
from skyvern.forge.sdk.copilot.agent import _build_goal_satisfied_exit_result
workflow = object()
@@ -611,12 +616,62 @@ class TestVerifiedGoalSatisfiedStop:
tool_activity=[{"tool": "update_and_run_blocks", "summary": "OK"}],
)
- result = _build_goal_satisfied_exit_result(ctx, global_llm_context=None)
+ result = await _build_goal_satisfied_exit_result(ctx, global_llm_context=None)
assert result.updated_workflow is workflow
assert result.workflow_yaml == "workflow_definition:\n blocks: []\n"
assert result.proposal_disposition == "auto_applicable"
- assert "tested" in result.user_response.lower()
+ # No adjudicated outcome evidence: the turn ends but the claim renders
+ # built-but-unverified instead of a tested-success claim.
+ assert "not independently verified" in result.user_response.lower()
+ assert result.narrative_payload is not None
+ assert result.narrative_payload["terminal"] == "response"
+ assert result.narrative_payload["verifiedSuccess"] is False
+
+ from skyvern.forge.sdk.copilot.completion_verification import (
+ CompletionVerificationResult,
+ CriterionVerdict,
+ )
+
+ ctx.completion_verification_result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0"],
+ verdicts=[CriterionVerdict(criterion_id="c0", state="satisfied", reason_code="evidence_confirms")],
+ )
+ verified = await _build_goal_satisfied_exit_result(ctx, global_llm_context=None)
+ assert "tested" in verified.user_response.lower()
+ assert verified.narrative_payload is not None
+ assert verified.narrative_payload["verifiedSuccess"] is True
+
+ @pytest.mark.asyncio
+ async def test_goal_satisfied_exit_result_carries_outcome_adjudication(self) -> None:
+ from skyvern.forge.sdk.copilot.agent import _build_goal_satisfied_exit_result
+ from skyvern.forge.sdk.copilot.completion_criteria_store import (
+ CompletionCriteriaTurnState,
+ ReconcileDecision,
+ )
+
+ ctx = _ctx(
+ last_workflow=object(),
+ last_workflow_yaml="workflow_definition:\n blocks: []\n",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ latest_diagnosis_repair_contract=_verified_goal_contract(),
+ tool_activity=[{"tool": "update_and_run_blocks", "summary": "OK"}],
+ )
+ ctx.completion_criteria_turn_state = CompletionCriteriaTurnState(
+ decision=ReconcileDecision(action="create", reason="not_subset", epoch=2, criteria=()),
+ last_verdict_state_counts={"satisfied": 2, "unsatisfied": 0, "unknown": 0},
+ )
+
+ result = await _build_goal_satisfied_exit_result(ctx, global_llm_context=None)
+
+ payload = result.narrative_payload
+ assert payload is not None
+ adjudication = payload["outcomeAdjudication"]
+ assert adjudication["criteriaEpoch"] == 2
+ assert adjudication["criteriaLifecycleReason"] == "not_subset"
+ assert adjudication["satisfiedCount"] == 2
class TestSupersededAgentIntentGates:
@@ -676,8 +731,44 @@ class TestRequestPolicyInputGuardrail:
global_llm_context="",
organization_id="org-1",
handler=policy_inputs.handler,
+ active_criteria=None,
)
+ @pytest.mark.asyncio
+ async def test_sdk_input_guardrail_forwards_stored_active_criteria(self, monkeypatch) -> None:
+ from agents import GuardrailFunctionOutput, InputGuardrail
+ from agents.run_context import RunContextWrapper
+
+ from skyvern.forge.sdk.copilot.completion_criteria_store import StoredCriteriaSet, StoredCriteriaSnapshot
+ from skyvern.forge.sdk.copilot.request_policy import CompletionCriterion, RequestPolicy
+
+ stored = StoredCriteriaSet(
+ set_id="wccs_1",
+ goal_epoch=1,
+ criteria=(CompletionCriterion(id="c0", outcome="The main heading is extracted into the run output"),),
+ )
+ build_request_policy = AsyncMock(return_value=RequestPolicy())
+ monkeypatch.setattr(agent_module, "build_request_policy", build_request_policy)
+ policy_inputs = agent_module.RequestPolicyGuardrailInputs(
+ user_message="run it again",
+ workflow_yaml="",
+ chat_history_text="",
+ chat_history_messages=[],
+ global_llm_context="",
+ organization_id="org-1",
+ handler=object(),
+ stored_completion_criteria=StoredCriteriaSnapshot(active=stored, next_epoch=2),
+ )
+ guardrails = agent_module._build_copilot_input_guardrails(
+ InputGuardrail,
+ GuardrailFunctionOutput,
+ policy_inputs=policy_inputs,
+ )
+ await guardrails[0].run(SimpleNamespace(), "input", RunContextWrapper(context=_ctx()))
+
+ assert build_request_policy.await_args is not None
+ assert build_request_policy.await_args.kwargs["active_criteria"] == list(stored.criteria)
+
@pytest.mark.asyncio
async def test_sdk_input_guardrail_trips_after_computing_blocked_policy(self, monkeypatch) -> None:
from agents import GuardrailFunctionOutput, InputGuardrail
diff --git a/tests/unit/test_copilot_completion_criteria_lifecycle.py b/tests/unit/test_copilot_completion_criteria_lifecycle.py
new file mode 100644
index 000000000..8d95efae5
--- /dev/null
+++ b/tests/unit/test_copilot_completion_criteria_lifecycle.py
@@ -0,0 +1,599 @@
+"""SKY-10931: persisted completion-criteria lifecycle (epoch/supersede/tripwire),
+definition-plane grading, tri-state verdict semantics, and the claim-side closure
+of the judge-unavailable success bypass."""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock
+
+import pytest
+
+from skyvern.config import settings
+from skyvern.forge.sdk.copilot.agent import (
+ RequestPolicyGuardrailInputs,
+ _reconcile_completion_criteria_on_context,
+ _stored_active_completion_criteria,
+)
+from skyvern.forge.sdk.copilot.completion_criteria_store import (
+ CompletionCriteriaTurnState,
+ ReconcileDecision,
+ StoredCriteriaSet,
+ StoredCriteriaSnapshot,
+ build_turn_state,
+ criteria_from_json,
+ criteria_to_json,
+ note_adjudication_on_turn_state,
+ plan_persistence,
+ reconcile_completion_criteria,
+)
+from skyvern.forge.sdk.copilot.completion_verification import (
+ CompletionVerificationResult,
+ CriterionVerdict,
+ _coerce_result,
+ combine_verification_results,
+ grade_definition_criteria,
+ resolve_unknown,
+ run_plane_all_no_evidence,
+)
+from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.copilot.diagnosis_repair_contract import (
+ DiagnosisInput,
+ DiagnosisRepairContract,
+ DiagnosisResult,
+ RepairDecision,
+ RepairNextAction,
+ VerificationResult,
+)
+from skyvern.forge.sdk.copilot.enforcement import (
+ verified_goal_claim_authorized,
+ verified_goal_satisfied_context,
+)
+from skyvern.forge.sdk.copilot.request_policy import (
+ CompletionCriterion,
+ RequestPolicy,
+ _parse_completion_criteria,
+ normalized_criterion_outcome_key,
+)
+from skyvern.forge.sdk.copilot.tools.completion import _outcome_failure_warrants_repair, _split_criteria_by_plane
+
+
+def _criterion(cid: str, outcome: str, *, level: str = "run") -> CompletionCriterion:
+ return CompletionCriterion(id=cid, outcome=outcome, level=level) # type: ignore[arg-type]
+
+
+def _stored(
+ *outcomes: str,
+ set_id: str = "wccs_1",
+ epoch: int = 1,
+ counter: int = 0,
+ fired: bool = False,
+ known_good: str | None = None,
+) -> StoredCriteriaSet:
+ return StoredCriteriaSet(
+ set_id=set_id,
+ goal_epoch=epoch,
+ criteria=tuple(_criterion(f"c{i}", outcome) for i, outcome in enumerate(outcomes)),
+ consecutive_all_no_evidence=counter,
+ tripwire_fired=fired,
+ last_fully_satisfied_workflow_yaml=known_good,
+ )
+
+
+def _verdict(cid: str, state: str, reason: str) -> CriterionVerdict:
+ return CriterionVerdict(criterion_id=cid, state=state, reason_code=reason) # type: ignore[arg-type]
+
+
+def _evaluated(*verdicts: CriterionVerdict) -> CompletionVerificationResult:
+ return CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=[v.criterion_id for v in verdicts],
+ verdicts=list(verdicts),
+ )
+
+
+def _all_no_evidence(*cids: str) -> CompletionVerificationResult:
+ return _evaluated(*[_verdict(cid, "unsatisfied", "no_evidence") for cid in cids])
+
+
+def test_reconcile_first_derivation_creates_epoch_one() -> None:
+ decision = reconcile_completion_criteria(
+ StoredCriteriaSnapshot(), [_criterion("c0", "the item is in the cart")], actionable=True
+ )
+ assert decision.action == "create"
+ assert decision.reason == "first"
+ assert decision.epoch == 1
+
+
+def test_reconcile_subset_keeps_stored_set() -> None:
+ stored = _stored("the item is in the cart", "the order total is extracted")
+ snapshot = StoredCriteriaSnapshot(active=stored, next_epoch=2)
+ decision = reconcile_completion_criteria(snapshot, [_criterion("x0", "The item is in the cart")], actionable=True)
+ assert decision.action == "adopt_stored"
+ assert decision.reason == "kept"
+ assert decision.epoch == 1
+ assert decision.criteria == stored.criteria
+
+
+def test_normalized_outcome_key_ignores_trailing_punctuation() -> None:
+ assert normalized_criterion_outcome_key("The heading is extracted.") == "the heading is extracted"
+ assert normalized_criterion_outcome_key(" The heading is extracted! ") == "the heading is extracted"
+
+
+def test_reconcile_keeps_stored_set_on_trailing_punctuation_and_case_variance() -> None:
+ stored = _stored("The page's main heading is extracted from https://example.com")
+ decision = reconcile_completion_criteria(
+ StoredCriteriaSnapshot(active=stored, next_epoch=2),
+ [_criterion("c0", "the page's main heading is extracted from https://example.com.")],
+ actionable=True,
+ )
+ assert decision.action == "adopt_stored"
+ assert decision.reason == "kept"
+ assert decision.criteria == stored.criteria
+
+
+def test_reconcile_empty_fresh_never_supersedes() -> None:
+ stored = _stored("the item is in the cart")
+ decision = reconcile_completion_criteria(StoredCriteriaSnapshot(active=stored, next_epoch=2), [], actionable=True)
+ assert decision.action == "adopt_stored"
+ assert decision.reason == "empty_fresh"
+ assert decision.criteria == stored.criteria
+
+
+def test_reconcile_non_subset_supersedes_wholesale() -> None:
+ stored = _stored("the item is in the cart", set_id="wccs_old", epoch=3)
+ decision = reconcile_completion_criteria(
+ StoredCriteriaSnapshot(active=stored, next_epoch=4),
+ [_criterion("c0", "the invoice totals are extracted")],
+ actionable=True,
+ )
+ assert decision.action == "create"
+ assert decision.reason == "not_subset"
+ assert decision.epoch == 4
+ assert decision.superseded_set_id == "wccs_old"
+
+
+def test_reconcile_epoch_stays_monotonic_after_supersede_chain() -> None:
+ # A superseded latest row still advances next_epoch, so a new set never
+ # reuses an epoch number.
+ decision = reconcile_completion_criteria(
+ StoredCriteriaSnapshot(active=None, next_epoch=7),
+ [_criterion("c0", "the report is downloaded")],
+ actionable=True,
+ )
+ assert decision.epoch == 7
+
+
+def test_reconcile_clarification_turn_never_creates_or_supersedes() -> None:
+ no_store = reconcile_completion_criteria(
+ StoredCriteriaSnapshot(), [_criterion("c0", "the item is in the cart")], actionable=False
+ )
+ assert no_store.action == "none"
+
+ stored = _stored("the item is in the cart")
+ with_store = reconcile_completion_criteria(
+ StoredCriteriaSnapshot(active=stored, next_epoch=2),
+ [_criterion("c0", "something entirely different")],
+ actionable=False,
+ )
+ assert with_store.action == "adopt_stored"
+ assert with_store.criteria == stored.criteria
+
+
+def test_reconcile_no_criteria_anywhere_is_noop() -> None:
+ decision = reconcile_completion_criteria(StoredCriteriaSnapshot(), [], actionable=True)
+ assert decision.action == "none"
+ assert plan_persistence(build_turn_state(StoredCriteriaSnapshot(), decision)) is None
+
+
+def test_criteria_json_round_trip_preserves_level_and_flags() -> None:
+ criteria = (
+ CompletionCriterion(id="c0", outcome="the item is in the cart", implicit=True),
+ CompletionCriterion(id="c1", outcome="inputs are reusable", method_mandated=True, level="definition"),
+ )
+ assert criteria_from_json(criteria_to_json(criteria)) == criteria
+
+
+def test_criteria_from_json_coerces_invalid_level_to_run() -> None:
+ (criterion,) = criteria_from_json([{"id": "c0", "outcome": "done", "level": "bogus"}])
+ assert criterion.level == "run"
+
+
+def _adopted_turn_state(stored: StoredCriteriaSet) -> CompletionCriteriaTurnState:
+ snapshot = StoredCriteriaSnapshot(active=stored, next_epoch=stored.goal_epoch + 1)
+ decision = reconcile_completion_criteria(snapshot, [], actionable=True)
+ return build_turn_state(snapshot, decision)
+
+
+def test_tripwire_fires_after_two_consecutive_all_no_evidence_adjudications() -> None:
+ stored = _stored("the item is in the cart", counter=1)
+ turn_state = _adopted_turn_state(stored)
+ note_adjudication_on_turn_state(turn_state, _all_no_evidence("c0"))
+ plan = plan_persistence(turn_state)
+ assert plan is not None
+ assert plan.counter_value == 2
+ assert plan.tripwire_fired is True
+ assert plan.supersede_set_id == stored.set_id
+ assert plan.supersede_reason == "tripwire"
+
+
+def test_tripwire_fires_at_most_once_per_epoch() -> None:
+ stored = _stored("the item is in the cart", counter=2, fired=True)
+ turn_state = _adopted_turn_state(stored)
+ note_adjudication_on_turn_state(turn_state, _all_no_evidence("c0"))
+ plan = plan_persistence(turn_state)
+ assert plan is not None
+ assert plan.counter_value == 3
+ assert plan.supersede_set_id is None
+ assert plan.supersede_reason is None
+
+
+def test_tripwire_counter_resets_on_evidence() -> None:
+ stored = _stored("the item is in the cart", counter=1)
+ turn_state = _adopted_turn_state(stored)
+ note_adjudication_on_turn_state(turn_state, _evaluated(_verdict("c0", "satisfied", "evidence_confirms")))
+ plan = plan_persistence(turn_state)
+ assert plan is not None
+ assert plan.counter_value == 0
+ assert plan.supersede_set_id is None
+
+
+def test_tripwire_never_fires_on_a_set_created_this_turn() -> None:
+ snapshot = StoredCriteriaSnapshot()
+ decision = reconcile_completion_criteria(snapshot, [_criterion("c0", "the item is in the cart")], actionable=True)
+ turn_state = build_turn_state(snapshot, decision)
+ note_adjudication_on_turn_state(turn_state, _all_no_evidence("c0"))
+ note_adjudication_on_turn_state(turn_state, _all_no_evidence("c0"))
+ plan = plan_persistence(turn_state)
+ assert plan is not None
+ assert plan.creates_set is True
+ assert plan.counter_value == 2
+ assert plan.tripwire_fired is False
+ assert plan.supersede_reason is None
+
+
+def test_fully_satisfied_adjudication_records_known_good_yaml() -> None:
+ stored = _stored("the item is in the cart")
+ turn_state = _adopted_turn_state(stored)
+ note_adjudication_on_turn_state(
+ turn_state,
+ _evaluated(_verdict("c0", "satisfied", "evidence_confirms")),
+ fully_satisfied_workflow_yaml="title: test workflow",
+ )
+ plan = plan_persistence(turn_state)
+ assert plan is not None
+ assert plan.fully_satisfied_workflow_yaml == "title: test workflow"
+
+
+def test_build_turn_state_exposes_known_good_availability() -> None:
+ stored = _stored("the item is in the cart", known_good="title: known good")
+ assert _adopted_turn_state(stored).known_good_yaml_available is True
+ assert _adopted_turn_state(_stored("the item is in the cart")).known_good_yaml_available is False
+
+
+def test_run_plane_all_no_evidence_ignores_definition_verdicts() -> None:
+ mixed = _evaluated(
+ _verdict("c0", "unsatisfied", "no_evidence"),
+ _verdict("c1", "satisfied", "definition_parameters_referenced"),
+ )
+ assert run_plane_all_no_evidence(mixed) is True
+ only_definition = _evaluated(_verdict("c0", "unknown", "definition_unknown"))
+ assert run_plane_all_no_evidence(only_definition) is False
+ confirmed = _evaluated(_verdict("c0", "satisfied", "evidence_confirms"))
+ assert run_plane_all_no_evidence(confirmed) is False
+
+
+def test_coerce_result_tristate_mapping() -> None:
+ raw = {
+ "verdicts": [
+ {"criterion_id": "c0", "satisfied": True, "reason_code": "evidence_confirms"},
+ {"criterion_id": "c1", "satisfied": False, "reason_code": "no_evidence"},
+ {"criterion_id": "c2", "satisfied": False, "reason_code": "evidence_contradicts"},
+ {"criterion_id": "c3", "satisfied": False, "reason_code": "unknown"},
+ {"criterion_id": "c4", "satisfied": True, "reason_code": "no_evidence"},
+ ]
+ }
+ result = _coerce_result(raw, ["c0", "c1", "c2", "c3", "c4", "c5"])
+ states = {v.criterion_id: v.state for v in result.verdicts}
+ assert states == {
+ "c0": "satisfied",
+ "c1": "unsatisfied",
+ "c2": "unsatisfied",
+ "c3": "unknown",
+ "c4": "unsatisfied",
+ "c5": "unknown",
+ }
+ assert result.is_fully_satisfied() is False
+ assert result.verdict_state_counts() == {"satisfied": 1, "unsatisfied": 3, "unknown": 2}
+
+
+def test_resolve_unknown_collapses_to_unsatisfied_only_when_flag_off(monkeypatch: pytest.MonkeyPatch) -> None:
+ assert resolve_unknown("unknown") == "unknown"
+ monkeypatch.setattr(settings, "COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED", False)
+ assert resolve_unknown("unknown") == "unsatisfied"
+ assert resolve_unknown("satisfied") == "satisfied"
+
+
+_PARAMETERIZED_YAML = """\
+title: provider lookup
+workflow_definition:
+ parameters:
+ - parameter_type: workflow
+ key: first_name
+ - parameter_type: workflow
+ key: npi_number
+ blocks:
+ - block_type: goto_url
+ label: open_portal
+ url: https://registry.example.com/search
+ - block_type: navigation
+ label: fill_search
+ navigation_goal: "Search for {{ first_name }} with NPI {{ npi_number }}"
+"""
+
+_UNREFERENCED_YAML = """\
+title: provider lookup
+workflow_definition:
+ parameters:
+ - parameter_type: workflow
+ key: first_name
+ blocks:
+ - block_type: goto_url
+ label: open_portal
+ url: https://registry.example.com/search
+"""
+
+_NO_PARAMS_YAML = """\
+title: provider lookup
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: goto_url
+ label: open_portal
+ url: https://registry.example.com/search
+"""
+
+
+def test_definition_grading_satisfied_when_parameters_exist_and_are_referenced() -> None:
+ criteria = [_criterion("c0", "the workflow accepts first name and NPI as reusable inputs", level="definition")]
+ (verdict,) = grade_definition_criteria(criteria, _PARAMETERIZED_YAML)
+ assert verdict.state == "satisfied"
+ assert verdict.reason_code == "definition_parameters_referenced"
+
+
+def test_definition_grading_unsatisfied_when_parameters_missing_or_unreferenced() -> None:
+ criteria = [_criterion("c0", "the workflow accepts reusable inputs", level="definition")]
+ (missing,) = grade_definition_criteria(criteria, _NO_PARAMS_YAML)
+ assert missing.state == "unsatisfied"
+ assert missing.reason_code == "definition_parameters_missing"
+ (unreferenced,) = grade_definition_criteria(criteria, _UNREFERENCED_YAML)
+ assert unreferenced.state == "unsatisfied"
+ assert unreferenced.reason_code == "definition_parameters_unreferenced"
+
+
+def test_definition_grading_requires_every_named_input_to_match() -> None:
+ criteria = [
+ _criterion(
+ "c0",
+ "the workflow accepts first name, last name, and NPI number as reusable inputs",
+ level="definition",
+ )
+ ]
+ # _PARAMETERIZED_YAML defines first_name + npi_number but not last_name:
+ # a multi-input ask must not be satisfied by a partial parameter set.
+ (verdict,) = grade_definition_criteria(criteria, _PARAMETERIZED_YAML)
+ assert verdict.state == "unknown"
+ assert verdict.reason_code == "definition_parameters_unmatched"
+
+ full_yaml = _PARAMETERIZED_YAML.replace(
+ " - parameter_type: workflow\n key: npi_number",
+ " - parameter_type: workflow\n key: last_name\n - parameter_type: workflow\n key: npi_number",
+ )
+ (full,) = grade_definition_criteria(criteria, full_yaml)
+ assert full.state == "satisfied"
+
+
+def test_parse_completion_criteria_tolerates_unhashable_level() -> None:
+ parsed = _parse_completion_criteria(
+ [
+ {"outcome": "the item is in the cart", "level": ["definition"]},
+ {"outcome": "the order is placed", "level": {"value": "run"}},
+ ]
+ )
+ assert [c.level for c in parsed] == ["run", "run"]
+
+
+def test_definition_grading_unknown_when_no_deterministic_check_applies() -> None:
+ criteria = [_criterion("c0", "the summary email is well written", level="definition")]
+ (verdict,) = grade_definition_criteria(criteria, _PARAMETERIZED_YAML)
+ assert verdict.state == "unknown"
+ assert verdict.reason_code == "definition_unknown"
+
+
+def test_definition_grading_never_emits_no_evidence() -> None:
+ criteria = [
+ _criterion("c0", "inputs are reusable", level="definition"),
+ _criterion("c1", "something unmappable", level="definition"),
+ ]
+ for yaml_text in (_PARAMETERIZED_YAML, _UNREFERENCED_YAML, _NO_PARAMS_YAML, "not: [valid", ""):
+ for verdict in grade_definition_criteria(criteria, yaml_text):
+ assert verdict.reason_code != "no_evidence"
+
+
+def test_combine_results_keeps_unavailable_run_result_authoritative() -> None:
+ unavailable = CompletionVerificationResult(status="unavailable")
+ combined = combine_verification_results(
+ ["c0", "c1"], unavailable, [_verdict("c1", "satisfied", "definition_parameters_referenced")]
+ )
+ assert combined.status == "unavailable"
+ assert combined.verdicts == []
+
+
+def test_combine_results_merges_planes_and_fills_unknown() -> None:
+ run_result = _evaluated(_verdict("c0", "satisfied", "evidence_confirms"))
+ combined = combine_verification_results(
+ ["c0", "c1", "c2"], run_result, [_verdict("c1", "unknown", "definition_unknown")]
+ )
+ assert combined.status == "evaluated"
+ assert [v.state for v in combined.verdicts] == ["satisfied", "unknown", "unknown"]
+ assert combined.criterion_ids == ["c0", "c1", "c2"]
+
+
+def test_split_criteria_by_plane_respects_flag(monkeypatch: pytest.MonkeyPatch) -> None:
+ criteria = [
+ _criterion("c0", "the item is in the cart"),
+ _criterion("c1", "inputs are reusable", level="definition"),
+ ]
+ run_criteria, definition_criteria = _split_criteria_by_plane(criteria)
+ assert [c.id for c in run_criteria] == ["c0"]
+ assert [c.id for c in definition_criteria] == ["c1"]
+
+ monkeypatch.setattr(settings, "COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED", False)
+ run_criteria, definition_criteria = _split_criteria_by_plane(criteria)
+ assert [c.id for c in run_criteria] == ["c0", "c1"]
+ assert definition_criteria == []
+
+
+def test_parse_completion_criteria_coerces_level() -> None:
+ parsed = _parse_completion_criteria(
+ [
+ {"outcome": "the item is in the cart", "level": "run"},
+ {"outcome": "inputs are reusable", "level": "definition"},
+ {"outcome": "the order is placed", "level": "nonsense"},
+ {"outcome": "the page is reached"},
+ ]
+ )
+ assert [c.level for c in parsed] == ["run", "definition", "run", "run"]
+
+
+def _ctx(**overrides: object) -> CopilotContext:
+ defaults: dict = dict(
+ organization_id="org-1",
+ workflow_id="wf-1",
+ workflow_permanent_id="wfp-1",
+ workflow_yaml="",
+ browser_session_id=None,
+ stream=MagicMock(),
+ )
+ defaults.update(overrides)
+ return CopilotContext(**defaults)
+
+
+def _legacy_verified_ctx() -> CopilotContext:
+ return _ctx(
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ latest_diagnosis_repair_contract=DiagnosisRepairContract(
+ diagnosis_input=DiagnosisInput(source_tool="update_and_run_blocks"),
+ diagnosis_result=DiagnosisResult(),
+ repair_decision=RepairDecision(next_action=RepairNextAction.NO_CHANGE),
+ verification_result=VerificationResult(
+ user_goal_satisfied=True,
+ completion_contract_satisfied=True,
+ ),
+ ),
+ )
+
+
+def test_claim_closure_turn_still_ends_but_claim_downgrades() -> None:
+ ctx = _legacy_verified_ctx()
+ # Turn completion is unchanged: the legacy conjunction still satisfies the gate.
+ assert verified_goal_satisfied_context(ctx) is True
+ # The claim tier is closed: no adjudicated evidence, no tested-success claim.
+ assert verified_goal_claim_authorized(ctx) is False
+
+
+def test_claim_authorized_with_flag_off_matches_legacy_gate(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED", False)
+ ctx = _legacy_verified_ctx()
+ assert verified_goal_claim_authorized(ctx) is True
+
+
+def test_claim_authorized_with_adjudicated_evidence() -> None:
+ ctx = _legacy_verified_ctx()
+ ctx.completion_verification_result = _evaluated(_verdict("c0", "satisfied", "evidence_confirms"))
+ assert verified_goal_claim_authorized(ctx) is True
+
+
+def test_unknown_only_verdicts_never_route_to_repair() -> None:
+ ctx = _ctx(last_workflow_yaml="workflow_definition:\n blocks:\n - block_type: extraction\n label: e\n")
+ all_unknown = _evaluated(_verdict("c0", "unknown", "unknown"))
+ assert _outcome_failure_warrants_repair(ctx, all_unknown) is False
+
+
+def test_unknown_verdicts_route_to_repair_with_flag_off(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(settings, "COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED", False)
+ ctx = _ctx(last_workflow_yaml="workflow_definition:\n blocks:\n - block_type: extraction\n label: e\n")
+ all_unknown = _evaluated(_verdict("c0", "unknown", "unknown"))
+ assert _outcome_failure_warrants_repair(ctx, all_unknown) is True
+
+
+def _policy_inputs(snapshot: StoredCriteriaSnapshot | None) -> RequestPolicyGuardrailInputs:
+ return RequestPolicyGuardrailInputs(
+ user_message="build a workflow",
+ workflow_yaml="",
+ chat_history_text="",
+ chat_history_messages=[],
+ global_llm_context="",
+ organization_id="org-1",
+ handler=None,
+ stored_completion_criteria=snapshot,
+ )
+
+
+def test_reconcile_on_context_adopts_stored_criteria_onto_policy() -> None:
+ stored = _stored("the item is in the cart", "the order total is extracted")
+ policy = RequestPolicy(completion_criteria=[_criterion("x0", "the item is in the cart")])
+ ctx = _ctx()
+ _reconcile_completion_criteria_on_context(
+ ctx, policy, _policy_inputs(StoredCriteriaSnapshot(active=stored, next_epoch=2))
+ )
+ assert [c.outcome for c in policy.completion_criteria] == [c.outcome for c in stored.criteria]
+ assert ctx.completion_criteria_turn_state is not None
+ assert ctx.completion_criteria_turn_state.decision is not None
+ assert ctx.completion_criteria_turn_state.decision.reason == "kept"
+
+
+def test_reconcile_on_context_skips_without_snapshot_or_flag(monkeypatch: pytest.MonkeyPatch) -> None:
+ policy = RequestPolicy(completion_criteria=[_criterion("c0", "the item is in the cart")])
+ ctx = _ctx()
+ _reconcile_completion_criteria_on_context(ctx, policy, _policy_inputs(None))
+ assert ctx.completion_criteria_turn_state is None
+
+ monkeypatch.setattr(settings, "COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED", False)
+ _reconcile_completion_criteria_on_context(ctx, policy, _policy_inputs(StoredCriteriaSnapshot()))
+ assert ctx.completion_criteria_turn_state is None
+
+
+def test_stored_active_criteria_forwarded_only_with_active_set(monkeypatch: pytest.MonkeyPatch) -> None:
+ stored = _stored("the item is in the cart")
+ snapshot = StoredCriteriaSnapshot(active=stored, next_epoch=2)
+ assert _stored_active_completion_criteria(_policy_inputs(snapshot)) == list(stored.criteria)
+ assert _stored_active_completion_criteria(_policy_inputs(StoredCriteriaSnapshot())) is None
+ assert _stored_active_completion_criteria(_policy_inputs(None)) is None
+
+ monkeypatch.setattr(settings, "COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED", False)
+ assert _stored_active_completion_criteria(_policy_inputs(snapshot)) is None
+
+
+def test_plan_persistence_for_supersede_creates_new_epoch_and_points_back() -> None:
+ stored = _stored("the item is in the cart", set_id="wccs_old", epoch=2)
+ snapshot = StoredCriteriaSnapshot(active=stored, next_epoch=3)
+ decision = reconcile_completion_criteria(
+ snapshot, [_criterion("c0", "the invoice totals are extracted")], actionable=True
+ )
+ turn_state = build_turn_state(snapshot, decision)
+ plan = plan_persistence(turn_state)
+ assert plan is not None
+ assert plan.creates_set is True
+ assert plan.create_epoch == 3
+ assert plan.supersede_set_id == "wccs_old"
+ assert plan.supersede_reason == "not_subset"
+
+
+def test_plan_persistence_none_for_none_decision() -> None:
+ assert plan_persistence(None) is None
+ assert plan_persistence(CompletionCriteriaTurnState()) is None
+ none_state = CompletionCriteriaTurnState(
+ decision=ReconcileDecision(action="none", reason="no_criteria", epoch=0, criteria=())
+ )
+ assert plan_persistence(none_state) is None
diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.py
index d49925f2c..4a83308ba 100644
--- a/tests/unit/test_copilot_completion_verification.py
+++ b/tests/unit/test_copilot_completion_verification.py
@@ -66,7 +66,11 @@ def _criterion(cid: str, outcome: str, *, method_mandated: bool = False) -> Comp
def _evaluated(*satisfied_by_id: tuple[str, bool]) -> CompletionVerificationResult:
ids = [cid for cid, _ in satisfied_by_id]
verdicts = [
- CriterionVerdict(criterion_id=cid, satisfied=ok, reason_code="evidence_confirms" if ok else "no_evidence")
+ CriterionVerdict(
+ criterion_id=cid,
+ state="satisfied" if ok else "unsatisfied",
+ reason_code="evidence_confirms" if ok else "no_evidence",
+ )
for cid, ok in satisfied_by_id
]
return CompletionVerificationResult(status="evaluated", criterion_ids=ids, verdicts=verdicts)
@@ -101,9 +105,10 @@ def test_coerce_requires_evidence_confirms_for_satisfied() -> None:
assert result.verdicts[0].satisfied is False
-def test_coerce_missing_criterion_defaults_to_no_evidence() -> None:
+def test_coerce_missing_criterion_defaults_to_unknown() -> None:
result = _coerce_result({"verdicts": []}, ["c0", "c1"])
- assert [v.reason_code for v in result.verdicts] == ["no_evidence", "no_evidence"]
+ assert [v.reason_code for v in result.verdicts] == ["unknown", "unknown"]
+ assert [v.state for v in result.verdicts] == ["unknown", "unknown"]
assert result.is_fully_satisfied() is False
@@ -420,7 +425,7 @@ def _ctx_with_blocks(*block_types: str) -> CopilotContext:
def _contradicted(cid: str) -> CompletionVerificationResult:
- verdict = CriterionVerdict(criterion_id=cid, satisfied=False, reason_code="evidence_contradicts")
+ verdict = CriterionVerdict(criterion_id=cid, state="unsatisfied", reason_code="evidence_contradicts")
return CompletionVerificationResult(status="evaluated", criterion_ids=[cid], verdicts=[verdict])
diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.py
index e9bcc61ff..6c2d41dc8 100644
--- a/tests/unit/test_copilot_diagnosis_repair_contract.py
+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py
@@ -160,7 +160,7 @@ def test_contradictory_completion_auth_evidence_repairs_frontier_block() -> None
verdicts=[
CriterionVerdict(
criterion_id="c0",
- satisfied=False,
+ state="unsatisfied",
reason_code="evidence_contradicts",
evidence_ref="current_url,page_title",
)
diff --git a/tests/unit/test_copilot_make_agent_result_backfill.py b/tests/unit/test_copilot_make_agent_result_backfill.py
index 42350e36b..7081c76c0 100644
--- a/tests/unit/test_copilot_make_agent_result_backfill.py
+++ b/tests/unit/test_copilot_make_agent_result_backfill.py
@@ -89,10 +89,39 @@ def test_backfill_writes_both_fields_together() -> None:
assert result.narrative_payload["verifiedSuccess"] is False
-def test_backfill_verified_success_true_when_gate_passes() -> None:
+def test_backfill_verified_success_requires_adjudicated_evidence() -> None:
+ # The legacy run-status conjunction still ends the turn but no longer backs
+ # a verified-success claim: without judge-confirmed outcome evidence the
+ # claim tier renders built-but-unverified.
result = _result(_verified_goal_ctx(), turn_outcome=_outcome(ResponseKind.BUILD), narrative_payload=_payload())
assert result.narrative_payload is not None
assert result.narrative_payload["responseKind"] == "build"
+ assert result.narrative_payload["verifiedSuccess"] is False
+
+
+def test_backfill_verified_success_true_when_legacy_gate_passes_with_flag_off(monkeypatch) -> None:
+ from skyvern.config import settings
+
+ monkeypatch.setattr(settings, "COPILOT_PERSISTED_COMPLETION_CRITERIA_ENABLED", False)
+ result = _result(_verified_goal_ctx(), turn_outcome=_outcome(ResponseKind.BUILD), narrative_payload=_payload())
+ assert result.narrative_payload is not None
+ assert result.narrative_payload["verifiedSuccess"] is True
+
+
+def test_backfill_verified_success_true_when_outcome_fully_verified() -> None:
+ from skyvern.forge.sdk.copilot.completion_verification import (
+ CompletionVerificationResult,
+ CriterionVerdict,
+ )
+
+ ctx = _verified_goal_ctx()
+ ctx.completion_verification_result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0"],
+ verdicts=[CriterionVerdict(criterion_id="c0", state="satisfied", reason_code="evidence_confirms")],
+ )
+ result = _result(ctx, turn_outcome=_outcome(ResponseKind.BUILD), narrative_payload=_payload())
+ assert result.narrative_payload is not None
assert result.narrative_payload["verifiedSuccess"] is True
diff --git a/tests/unit/test_copilot_outcome_verification_trace.py b/tests/unit/test_copilot_outcome_verification_trace.py
index cb978e014..40cb41c46 100644
--- a/tests/unit/test_copilot_outcome_verification_trace.py
+++ b/tests/unit/test_copilot_outcome_verification_trace.py
@@ -26,8 +26,10 @@ def _evaluated_result() -> CompletionVerificationResult:
status="evaluated",
criterion_ids=["c0", "c1"],
verdicts=[
- CriterionVerdict(criterion_id="c0", satisfied=True, reason_code="evidence_confirms", evidence_ref="cart"),
- CriterionVerdict(criterion_id="c1", satisfied=False, reason_code="no_evidence"),
+ CriterionVerdict(
+ criterion_id="c0", state="satisfied", reason_code="evidence_confirms", evidence_ref="cart"
+ ),
+ CriterionVerdict(criterion_id="c1", state="unsatisfied", reason_code="no_evidence"),
],
)
diff --git a/tests/unit/test_copilot_request_policy_prompt.py b/tests/unit/test_copilot_request_policy_prompt.py
index 1679a2795..93691e5dd 100644
--- a/tests/unit/test_copilot_request_policy_prompt.py
+++ b/tests/unit/test_copilot_request_policy_prompt.py
@@ -9,6 +9,7 @@ from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.copilot.request_policy import (
PROMPT_NAME,
RAW_SECRET_REFUSAL_SENTINEL,
+ CompletionCriterion,
_classify_request,
_credential_ids,
_raw_secret_detected,
@@ -324,3 +325,42 @@ class TestMalformedCredentialIdExtraction:
reason="none",
)
assert policy.credential_input_kind == "credential_id"
+
+
+def _capture_handler(captured: dict[str, str]):
+ async def handler(prompt: str, prompt_name: str) -> dict[str, object]:
+ captured["prompt"] = prompt
+ return {"testing_intent": "unspecified", "credential_input_kind": "none"}
+
+ return handler
+
+
+class TestActiveCriteriaPromptAnchor:
+ @pytest.mark.asyncio
+ async def test_active_criteria_render_verbatim(self) -> None:
+ captured: dict[str, str] = {}
+ await _classify_request(
+ user_message="run it again to make sure it still works",
+ workflow_yaml="",
+ chat_history=[],
+ global_llm_context="",
+ handler=_capture_handler(captured),
+ active_criteria=[
+ CompletionCriterion(id="c0", outcome="The main heading from https://example.com is extracted"),
+ ],
+ )
+ assert "ACTIVE COMPLETION CRITERIA (canonical phrasing for the current goal):" in captured["prompt"]
+ assert "The main heading from https://example.com is extracted" in captured["prompt"]
+ assert "COPIED VERBATIM" in captured["prompt"]
+
+ @pytest.mark.asyncio
+ async def test_no_active_criteria_omits_anchor_section(self) -> None:
+ captured: dict[str, str] = {}
+ await _classify_request(
+ user_message="build a workflow",
+ workflow_yaml="",
+ chat_history=[],
+ global_llm_context="",
+ handler=_capture_handler(captured),
+ )
+ assert "ACTIVE COMPLETION CRITERIA (canonical phrasing for the current goal):" not in captured["prompt"]
diff --git a/tests/unit/test_copilot_run_outcome_event.py b/tests/unit/test_copilot_run_outcome_event.py
index f34fded5f..3dddbee85 100644
--- a/tests/unit/test_copilot_run_outcome_event.py
+++ b/tests/unit/test_copilot_run_outcome_event.py
@@ -105,7 +105,9 @@ def _clean_run_result() -> dict[str, Any]:
def _evaluated(satisfied: bool) -> CompletionVerificationResult:
verdict = CriterionVerdict(
- criterion_id="c0", satisfied=satisfied, reason_code="evidence_confirms" if satisfied else "no_evidence"
+ criterion_id="c0",
+ state="satisfied" if satisfied else "unsatisfied",
+ reason_code="evidence_confirms" if satisfied else "no_evidence",
)
return CompletionVerificationResult(status="evaluated", criterion_ids=["c0"], verdicts=[verdict])
diff --git a/tests/unit/test_copilot_run_output_content_gate.py b/tests/unit/test_copilot_run_output_content_gate.py
index 9359903be..fa0f584fa 100644
--- a/tests/unit/test_copilot_run_output_content_gate.py
+++ b/tests/unit/test_copilot_run_output_content_gate.py
@@ -65,7 +65,7 @@ def _ctx(blocks: list[dict[str, Any]] | None = None) -> CopilotContext:
def _no_evidence(cid: str) -> CompletionVerificationResult:
- verdict = CriterionVerdict(criterion_id=cid, satisfied=False, reason_code="no_evidence")
+ verdict = CriterionVerdict(criterion_id=cid, state="unsatisfied", reason_code="no_evidence")
return CompletionVerificationResult(status="evaluated", criterion_ids=[cid], verdicts=[verdict])
@@ -448,8 +448,45 @@ def test_flag_rule_requires_strict_blocker_terms() -> None:
benign = _run_result([_code_block("notify", {"verification_passed": True})])
assert _run_blocks_structured_blocker_message(benign) is None
- string_rule_parity = _run_result([_code_block("notify", {"verification_code_sent": "yes"})])
- assert _run_blocks_structured_blocker_message(string_rule_parity) == "yes"
+ # SKY-10916: broad terms like ``verification`` no longer key the code-block
+ # string arm; only the strict term set does.
+ broad_term_string = _run_result([_code_block("notify", {"verification_code_sent": "yes"})])
+ assert _run_blocks_structured_blocker_message(broad_term_string) is None
+
+ strict_term_string = _run_result([_code_block("notify", {"human_verification_step": "solve the puzzle"})])
+ assert _run_blocks_structured_blocker_message(strict_term_string) == "solve the puzzle"
+
+
+def test_verification_key_counts_as_goal_content_for_code_outputs() -> None:
+ # SKY-10916: an output key carrying ``verification`` is data, not a blocker —
+ # it must satisfy the emptiness denominator instead of being stripped.
+ result = _run_result(
+ [_code_block("verify_listing", {"verification_results": [{"name": "DOE, JANE", "verified": True}]})]
+ )
+ assert _run_blocks_structured_blocker_message(result) is None
+ _, empty_data_blocks, _ = _analyze_run_blocks(result)
+ assert empty_data_blocks is False
+
+
+class _MetadataCtx:
+ def __init__(self, metadata: dict) -> None:
+ self.code_artifact_metadata = metadata
+
+
+def test_declared_outcome_keys_exempt_from_blocker_term_matching() -> None:
+ # Metadata-declared goal keys (the #12034 typed source) override string
+ # matching even for strict terms.
+ metadata = {
+ "check_challenge": {
+ "claimed_outcomes": [{"id": "captcha_audit_log", "entities": ["challenge_summary"], "required_tokens": []}]
+ }
+ }
+ block = _code_block("check_challenge", {"captcha_audit_log": "3 challenges recorded this month"})
+ result = _run_result([block])
+ assert _run_blocks_structured_blocker_message(result) is not None
+ assert _run_blocks_structured_blocker_message(result, _MetadataCtx(metadata)) is None
+ _, empty_data_blocks, _ = _analyze_run_blocks(result, _MetadataCtx(metadata))
+ assert empty_data_blocks is False
def test_flag_rule_synthesizes_message_and_prefers_sibling_reason() -> None:
diff --git a/tests/unit/test_copilot_streaming_adapter.py b/tests/unit/test_copilot_streaming_adapter.py
index 868068f4e..b5f010d3b 100644
--- a/tests/unit/test_copilot_streaming_adapter.py
+++ b/tests/unit/test_copilot_streaming_adapter.py
@@ -697,3 +697,90 @@ class TestEnforcementStateUpdates:
},
)
assert ctx.update_workflow_called is False
+
+
+class TestFlushGoalSatisfiedToolResult:
+ @staticmethod
+ def _ctx(**overrides: Any) -> SimpleNamespace:
+ from skyvern.forge.sdk.copilot.context import InFlightStreamToolCall
+
+ defaults: dict[str, Any] = dict(
+ in_flight_stream_tool_call=InFlightStreamToolCall(
+ call_id="c9", tool_name="update_and_run_blocks", iteration=3
+ ),
+ goal_satisfied_tool_name="update_and_run_blocks",
+ goal_satisfied_tool_output={"ok": True, "data": {"workflow_run_id": "wr_1"}},
+ narrator_state=None,
+ )
+ defaults.update(overrides)
+ return SimpleNamespace(**defaults)
+
+ @staticmethod
+ def _stream(sent: list[Any], *, disconnected: bool = False) -> MagicMock:
+ async def _send(payload: Any) -> bool:
+ sent.append(payload)
+ return True
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=disconnected)
+ stream.send = _send
+ return stream
+
+ @pytest.mark.asyncio
+ async def test_emits_tool_result_for_goal_satisfying_call(self) -> None:
+ from skyvern.forge.sdk.copilot.streaming_adapter import flush_goal_satisfied_tool_result
+ from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotStreamMessageType
+
+ sent: list[Any] = []
+ ctx = self._ctx()
+
+ await flush_goal_satisfied_tool_result(self._stream(sent), ctx)
+
+ assert len(sent) == 1
+ frame = sent[0]
+ assert frame.type == WorkflowCopilotStreamMessageType.TOOL_RESULT
+ assert frame.tool_call_id == "c9"
+ assert frame.tool_name == "update_and_run_blocks"
+ assert frame.success is True
+ assert frame.iteration == 3
+ assert ctx.in_flight_stream_tool_call is None
+ assert ctx.goal_satisfied_tool_output is None
+ assert ctx.goal_satisfied_tool_name is None
+
+ @pytest.mark.asyncio
+ async def test_noops_when_no_call_is_pending(self) -> None:
+ from skyvern.forge.sdk.copilot.streaming_adapter import flush_goal_satisfied_tool_result
+
+ sent: list[Any] = []
+ ctx = self._ctx(in_flight_stream_tool_call=None)
+
+ await flush_goal_satisfied_tool_result(self._stream(sent), ctx)
+
+ assert sent == []
+
+ @pytest.mark.asyncio
+ async def test_noops_when_pending_call_is_a_different_tool(self) -> None:
+ from skyvern.forge.sdk.copilot.streaming_adapter import flush_goal_satisfied_tool_result
+
+ sent: list[Any] = []
+ ctx = self._ctx(goal_satisfied_tool_name="get_run_results")
+
+ await flush_goal_satisfied_tool_result(self._stream(sent), ctx)
+
+ assert sent == []
+ assert ctx.in_flight_stream_tool_call is None
+
+ @pytest.mark.asyncio
+ async def test_records_narrator_activity_but_skips_send_when_disconnected(self) -> None:
+ from skyvern.forge.sdk.copilot.narration import NarratorState
+ from skyvern.forge.sdk.copilot.streaming_adapter import flush_goal_satisfied_tool_result
+
+ sent: list[Any] = []
+ narrator_state = NarratorState()
+ ctx = self._ctx(narrator_state=narrator_state)
+
+ await flush_goal_satisfied_tool_result(self._stream(sent, disconnected=True), ctx)
+
+ assert sent == []
+ assert narrator_state.design_activity
+ assert narrator_state.design_activity[-1]["kind"] == "tool_result"