Skip to content

Automate browser based workflows with AI

fix(SKY-11496): Add contingent completion criteria (#6859)

Andrew Neilsonb870b60808b8
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-completion-verification.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-completion-verification.j2
index b2f9a6500..dc4a06849 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-completion-verification.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-completion-verification.j2
@@ -8,6 +8,7 @@ Rules:
- If the evidence does not contain anything that shows the outcome, set satisfied=false and reason_code=no_evidence. Do not infer the outcome from the presence of a step or from the criterion text itself.
- If the evidence shows the outcome did NOT happen (e.g. the cart is empty, an error/blocker, a contradicting value), set satisfied=false and reason_code=evidence_contradicts.
- If you cannot tell from the evidence, set satisfied=false and reason_code=unknown.
+- A criterion may include [contingent_on=...] and [contingent_antecedent_output_path=output.<field>]. The server handles whether the antecedent fired from structured run output; you must grade the listed outcome normally against the produced evidence. Use evidence_confirms only when the consequent is shown, no_evidence when the required blocker/report evidence is missing, and evidence_contradicts when the evidence refutes it.
- For an implicit constraint (e.g. "added exactly once"), check the end-state value (e.g. a cart quantity), not whether an add step ran.
- evidence_ref: a short pointer to the specific evidence you used (a block label or the observed URL), or null.
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
index dc37ff00e..314b26e5d 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-request-policy.j2
@@ -25,8 +25,10 @@ completion_contract:
- Set to null when the user does not provide an explicit completion condition.
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, level}.
+- An array of the END-STATE OUTCOMES that must be true for the user's goal to be done. Each item is {outcome, contingent_on, contingent_antecedent_output_path, 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.
+- contingent_on: null for ordinary criteria. Use a short antecedent string only when this criterion should be graded only if that antecedent happens, for example {"contingent_on": "the provider site blocks online submission", "contingent_antecedent_output_path": "output.blocker", "outcome": "the blocker is reported to the user"}. The antecedent goes in contingent_on; the consequent to grade goes in outcome. Do not encode if/then criteria only in prose.
+- contingent_antecedent_output_path: null unless the antecedent is represented by a structured run output field. The only valid form is output.<field> (for example output.blocker). Do not emit transcript paths, selectors, regexes, JSONPath, screenshots, nested paths, or prose conditions here.
- 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.
diff --git a/skyvern/forge/sdk/copilot/completion_criteria_store.py b/skyvern/forge/sdk/copilot/completion_criteria_store.py
index 1a987da0d..cbd579bad 100644
--- a/skyvern/forge/sdk/copilot/completion_criteria_store.py
+++ b/skyvern/forge/sdk/copilot/completion_criteria_store.py
@@ -17,6 +17,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
)
from skyvern.forge.sdk.copilot.request_policy import (
CompletionCriterion,
+ _normalize_contingent_antecedent_output_path,
is_fallback_floor_criterion,
normalized_criterion_outcome_key,
requested_output_path_for_field,
@@ -110,6 +111,8 @@ def criteria_to_json(criteria: tuple[CompletionCriterion, ...] | list[Completion
{
"id": criterion.id,
"outcome": criterion.outcome,
+ "contingent_on": criterion.contingent_on,
+ "contingent_antecedent_output_path": criterion.contingent_antecedent_output_path,
"implicit": criterion.implicit,
"method_mandated": criterion.method_mandated,
"level": criterion.level,
@@ -132,10 +135,18 @@ def criteria_from_json(raw: Any) -> tuple[CompletionCriterion, ...]:
continue
level = item.get("level")
output_path = item.get("output_path")
+ contingent_on = item.get("contingent_on")
+ contingent_antecedent_output_path = _normalize_contingent_antecedent_output_path(
+ item.get("contingent_antecedent_output_path")
+ )
criteria.append(
CompletionCriterion(
id=criterion_id,
outcome=outcome,
+ contingent_on=contingent_on.strip()
+ if isinstance(contingent_on, str) and contingent_on.strip()
+ else None,
+ contingent_antecedent_output_path=contingent_antecedent_output_path,
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]
@@ -146,9 +157,17 @@ def criteria_from_json(raw: Any) -> tuple[CompletionCriterion, ...]:
def _criterion_reconcile_key(criterion: CompletionCriterion) -> str:
+ contingent_key = criterion.contingent_on or ""
+ contingent_path_key = criterion.contingent_antecedent_output_path or ""
if criterion.output_path:
- return f"output_path:{criterion.output_path}"
- return f"outcome:{normalized_criterion_outcome_key(criterion.outcome)}"
+ return (
+ f"contingent:{contingent_key}\x1fantecedent_path:{contingent_path_key}"
+ f"\x1foutput_path:{criterion.output_path}"
+ )
+ return (
+ f"contingent:{contingent_key}\x1fantecedent_path:{contingent_path_key}"
+ f"\x1foutcome:{normalized_criterion_outcome_key(criterion.outcome)}"
+ )
def _outcome_key_set(criteria: tuple[CompletionCriterion, ...] | list[CompletionCriterion]) -> set[str]:
diff --git a/skyvern/forge/sdk/copilot/completion_verification.py b/skyvern/forge/sdk/copilot/completion_verification.py
index 99b13c222..aa1c4377c 100644
--- a/skyvern/forge/sdk/copilot/completion_verification.py
+++ b/skyvern/forge/sdk/copilot/completion_verification.py
@@ -39,6 +39,9 @@ _MISSING_EVIDENCE_MAX_CHARS = 500
_MAX_BLOCK_OUTPUTS = 20
_MAX_TRACE_VERDICTS = 8
_REASON_CODES = frozenset({"evidence_confirms", "no_evidence", "evidence_contradicts", "unknown"})
+_CONTINGENT_ABSTENTION_REASON_CODES = frozenset(
+ {"unknown", "no_evidence", "evidence_contradicts", "missing_exact_field", "unproducible"}
+)
_PAGE_EVIDENCE_KEYS = (
"current_url",
"page_title",
@@ -80,6 +83,10 @@ class CompletionVerificationResult:
criterion_ids: list[str] = field(default_factory=list)
verdicts: list[CriterionVerdict] = field(default_factory=list)
no_gradeable_run_plane: bool = False
+ contingent_criterion_ids: list[str] = field(default_factory=list)
+ contingent_on_by_criterion_id: dict[str, str] = field(default_factory=dict)
+ contingent_antecedent_output_path_by_criterion_id: dict[str, str] = field(default_factory=dict)
+ structural_unfired_criterion_ids: list[str] = field(default_factory=list)
def is_fully_satisfied(self) -> bool:
if self.status != "evaluated" or not self.criterion_ids:
@@ -99,11 +106,28 @@ class CompletionVerificationResult:
# so it must not veto a run whose observable outcome evidence is fully confirmed.
if verdict is not None and _is_definition_plane_abstention(verdict):
continue
+ if verdict is not None and _is_contingent_abstention(
+ verdict,
+ self.contingent_criterion_ids,
+ self.structural_unfired_criterion_ids,
+ ):
+ continue
return False
return satisfied_run_plane_count > 0
+ def is_structural_contingent_abstention(self, verdict: CriterionVerdict) -> bool:
+ return _is_contingent_abstention(
+ verdict,
+ self.contingent_criterion_ids,
+ self.structural_unfired_criterion_ids,
+ )
+
def to_trace_data(self) -> dict[str, Any]:
- unmet = [verdict for verdict in self.verdicts if not verdict.satisfied]
+ unmet = [
+ verdict
+ for verdict in self.verdicts
+ if not verdict.satisfied and not self.is_structural_contingent_abstention(verdict)
+ ]
missing_evidence: list[str] = []
for verdict in unmet:
detail = verdict_missing_evidence(verdict)
@@ -121,15 +145,27 @@ class CompletionVerificationResult:
"unmet_criterion_ids": [verdict.criterion_id for verdict in unmet],
"missing_evidence": missing_evidence,
}
+ if self.contingent_criterion_ids:
+ data["contingent_criterion_ids"] = list(self.contingent_criterion_ids)
+ if self.structural_unfired_criterion_ids:
+ data["structural_unfired_criterion_ids"] = list(self.structural_unfired_criterion_ids)
for index, verdict in enumerate(self.verdicts[:_MAX_TRACE_VERDICTS]):
prefix = f"verdict_{index}"
data[f"{prefix}_criterion_id"] = verdict.criterion_id
+ data[f"{prefix}_state"] = verdict.state
data[f"{prefix}_satisfied"] = verdict.satisfied
data[f"{prefix}_reason_code"] = verdict.reason_code
+ if contingent_on := self.contingent_on_by_criterion_id.get(verdict.criterion_id):
+ data[f"{prefix}_contingent_on"] = contingent_on
+ if contingent_path := self.contingent_antecedent_output_path_by_criterion_id.get(verdict.criterion_id):
+ data[f"{prefix}_contingent_antecedent_output_path"] = contingent_path
+ data[f"{prefix}_structural_unfired"] = verdict.criterion_id in set(
+ self.structural_unfired_criterion_ids
+ )
evidence_ref = _clean_optional_text(verdict.evidence_ref, max_chars=_EVIDENCE_REF_MAX_CHARS)
if evidence_ref:
data[f"{prefix}_evidence_ref"] = evidence_ref
- detail = verdict_missing_evidence(verdict)
+ detail = None if self.is_structural_contingent_abstention(verdict) else verdict_missing_evidence(verdict)
if detail:
data[f"{prefix}_missing_evidence"] = detail
return data
@@ -262,12 +298,86 @@ def _render_criteria(criteria: list[CompletionCriterion]) -> str:
flags += " (implicit)"
if criterion.method_mandated:
flags += " (method_mandated)"
+ contingent_on = f" [contingent_on={criterion.contingent_on}]" if criterion.contingent_on else ""
+ antecedent_output_path = (
+ f" [contingent_antecedent_output_path={criterion.contingent_antecedent_output_path}]"
+ if criterion.contingent_antecedent_output_path
+ else ""
+ )
output_path = f" [required_output_path={criterion.output_path}]" if criterion.output_path else ""
- parts.append(f"- {criterion.id}: {criterion.outcome}{output_path}{flags}")
+ parts.append(
+ f"- {criterion.id}: {criterion.outcome}{contingent_on}{antecedent_output_path}{output_path}{flags}"
+ )
return "\n".join(parts)
-def _coerce_result(raw: Any, criterion_ids: list[str]) -> CompletionVerificationResult:
+def _contingent_metadata_for_criteria(
+ criteria: Iterable[CompletionCriterion],
+) -> tuple[list[str], dict[str, str], dict[str, str]]:
+ contingent_on_by_id = {
+ criterion.id: criterion.contingent_on for criterion in criteria if criterion.contingent_on is not None
+ }
+ contingent_antecedent_output_path_by_id = {
+ criterion.id: criterion.contingent_antecedent_output_path
+ for criterion in criteria
+ if criterion.contingent_antecedent_output_path is not None
+ }
+ contingent_ids = list(dict.fromkeys([*contingent_on_by_id, *contingent_antecedent_output_path_by_id]))
+ return contingent_ids, contingent_on_by_id, contingent_antecedent_output_path_by_id
+
+
+def _output_path_field(path: str) -> str:
+ return path.removeprefix("output.")
+
+
+def _field_aliases_for_output_path(path: str) -> tuple[str, str]:
+ field = _output_path_field(path)
+ return field, f"{field}_output"
+
+
+def _find_structured_field_values(value: Any, field_names: set[str]) -> Iterable[Any]:
+ if isinstance(value, dict):
+ for key, item in value.items():
+ if isinstance(key, str) and key in field_names:
+ yield item
+ yield from _find_structured_field_values(item, field_names)
+ elif isinstance(value, list):
+ for item in value:
+ yield from _find_structured_field_values(item, field_names)
+
+
+def structural_unfired_contingent_criterion_ids(
+ criteria: Iterable[CompletionCriterion],
+ snapshot: RunEvidenceSnapshot,
+) -> list[str]:
+ unfired_ids: list[str] = []
+ for criterion in criteria:
+ path = criterion.contingent_antecedent_output_path
+ if not path:
+ continue
+ field_names = set(_field_aliases_for_output_path(path))
+ values: list[Any] = []
+ for key, value in snapshot.block_outputs.items():
+ if key in field_names:
+ values.append(value)
+ values.extend(_find_structured_field_values(value, field_names))
+ if not values:
+ continue
+ if any(_is_meaningful_contingent_antecedent_value(value) for value in values):
+ continue
+ unfired_ids.append(criterion.id)
+ return unfired_ids
+
+
+def _coerce_result(
+ raw: Any,
+ criterion_ids: list[str],
+ *,
+ contingent_criterion_ids: Iterable[str] = (),
+ contingent_on_by_criterion_id: dict[str, str] | None = None,
+ contingent_antecedent_output_path_by_criterion_id: dict[str, str] | None = None,
+ structural_unfired_criterion_ids: Iterable[str] = (),
+) -> CompletionVerificationResult:
if isinstance(raw, bytes):
raw = raw.decode("utf-8", errors="replace")
if isinstance(raw, str):
@@ -287,7 +397,7 @@ def _coerce_result(raw: Any, criterion_ids: list[str]) -> CompletionVerification
if criterion_id not in allowed or criterion_id in by_id:
continue
reason = item.get("reason_code")
- reason_code = reason if reason in _REASON_CODES else "unknown"
+ reason_code = reason if isinstance(reason, str) and reason in _REASON_CODES else "unknown"
# A criterion counts as satisfied only when the judge cites confirming
# evidence; "no_evidence"/"contradicts" are affirmative negatives, while an
# incoherent or "unknown" verdict stays unknown — it never passes and never fails.
@@ -312,7 +422,15 @@ def _coerce_result(raw: Any, criterion_ids: list[str]) -> CompletionVerification
)
verdicts = [by_id.get(criterion_id, _missing_verdict(criterion_id)) for criterion_id in criterion_ids]
- return CompletionVerificationResult(status="evaluated", criterion_ids=list(criterion_ids), verdicts=verdicts)
+ return CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=list(criterion_ids),
+ verdicts=verdicts,
+ contingent_criterion_ids=list(contingent_criterion_ids),
+ contingent_on_by_criterion_id=dict(contingent_on_by_criterion_id or {}),
+ contingent_antecedent_output_path_by_criterion_id=dict(contingent_antecedent_output_path_by_criterion_id or {}),
+ structural_unfired_criterion_ids=list(structural_unfired_criterion_ids),
+ )
_DEFINITION_PARAMETER_HINT_RE = re.compile(r"\b(?:inputs?|parameters?|params?|reusable|configurable)\b", re.I)
@@ -1159,6 +1277,12 @@ def _is_meaningful_record_value(value: Any) -> bool:
return True
+def _is_meaningful_contingent_antecedent_value(value: Any) -> bool:
+ if isinstance(value, bool):
+ return value
+ return _is_meaningful_record_value(value)
+
+
_DEFINITION_REASON_PREFIX = "definition_"
@@ -1166,6 +1290,19 @@ def _is_definition_plane_abstention(verdict: CriterionVerdict) -> bool:
return verdict.state == "unknown" and verdict.reason_code.startswith(_DEFINITION_REASON_PREFIX)
+def _is_contingent_abstention(
+ verdict: CriterionVerdict,
+ contingent_criterion_ids: Iterable[str],
+ structural_unfired_criterion_ids: Iterable[str],
+) -> bool:
+ return (
+ verdict.criterion_id in set(contingent_criterion_ids)
+ and verdict.criterion_id in set(structural_unfired_criterion_ids)
+ and not verdict.satisfied
+ and verdict.reason_code in _CONTINGENT_ABSTENTION_REASON_CODES
+ )
+
+
def run_plane_all_no_evidence(result: CompletionVerificationResult) -> bool:
"""Whether every run-plane verdict in an evaluated result is ``no_evidence``.
@@ -1183,11 +1320,35 @@ def combine_verification_results(
criterion_ids: list[str],
run_result: CompletionVerificationResult | None,
definition_verdicts: list[CriterionVerdict],
+ *,
+ contingent_criterion_ids: Iterable[str] = (),
+ contingent_on_by_criterion_id: dict[str, str] | None = None,
+ contingent_antecedent_output_path_by_criterion_id: dict[str, str] | None = None,
+ structural_unfired_criterion_ids: Iterable[str] = (),
) -> CompletionVerificationResult:
"""One result spanning both evidence planes; a judge that could not evaluate
keeps the whole result unavailable so fail-closed messaging is preserved."""
+ contingent_ids = list(contingent_criterion_ids)
+ contingent_on_by_id = dict(contingent_on_by_criterion_id or {})
+ contingent_path_by_id = dict(contingent_antecedent_output_path_by_criterion_id or {})
+ structural_unfired_ids = list(structural_unfired_criterion_ids)
+ if run_result is not None:
+ contingent_ids = list(dict.fromkeys([*contingent_ids, *run_result.contingent_criterion_ids]))
+ contingent_on_by_id.update(run_result.contingent_on_by_criterion_id)
+ contingent_path_by_id.update(run_result.contingent_antecedent_output_path_by_criterion_id)
+ structural_unfired_ids = list(
+ dict.fromkeys([*structural_unfired_ids, *run_result.structural_unfired_criterion_ids])
+ )
if run_result is not None and run_result.status != "evaluated":
- return run_result
+ return CompletionVerificationResult(
+ status=run_result.status,
+ criterion_ids=list(criterion_ids),
+ verdicts=list(run_result.verdicts),
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=structural_unfired_ids,
+ )
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})
@@ -1200,6 +1361,10 @@ def combine_verification_results(
criterion_ids=list(criterion_ids),
verdicts=verdicts,
no_gradeable_run_plane=run_result is None,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=structural_unfired_ids,
)
@@ -1209,9 +1374,20 @@ async def evaluate_completion_criteria(
handler: Any,
) -> CompletionVerificationResult:
if handler is None or not criteria:
- return _UNAVAILABLE
+ if not criteria:
+ return _UNAVAILABLE
+ contingent_ids, contingent_on_by_id, contingent_path_by_id = _contingent_metadata_for_criteria(criteria)
+ return CompletionVerificationResult(
+ status="unavailable",
+ criterion_ids=[criterion.id for criterion in criteria],
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ )
criterion_ids = [criterion.id for criterion in criteria]
+ contingent_ids, contingent_on_by_id, contingent_path_by_id = _contingent_metadata_for_criteria(criteria)
+ structural_unfired_ids = structural_unfired_contingent_criterion_ids(criteria, snapshot)
prompt = prompt_engine.load_prompt(
template=PROMPT_TEMPLATE_NAME,
criteria=escape_code_fences(_render_criteria(criteria)),
@@ -1224,9 +1400,30 @@ async def evaluate_completion_criteria(
)
except asyncio.TimeoutError:
LOG.warning("completion-verification judge timed out")
- return _UNAVAILABLE
+ return CompletionVerificationResult(
+ status="unavailable",
+ criterion_ids=criterion_ids,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=structural_unfired_ids,
+ )
except Exception as exc:
LOG.warning("completion-verification judge failed", error=str(exc))
- return _UNAVAILABLE
+ return CompletionVerificationResult(
+ status="unavailable",
+ criterion_ids=criterion_ids,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=structural_unfired_ids,
+ )
- return _coerce_result(raw, criterion_ids)
+ return _coerce_result(
+ raw,
+ criterion_ids,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=structural_unfired_ids,
+ )
diff --git a/skyvern/forge/sdk/copilot/request_policy.py b/skyvern/forge/sdk/copilot/request_policy.py
index 681560276..8c83a700c 100644
--- a/skyvern/forge/sdk/copilot/request_policy.py
+++ b/skyvern/forge/sdk/copilot/request_policy.py
@@ -145,6 +145,8 @@ _CREDENTIAL_CODE_MARKERS = ("saved credential", "login_credentials", ".otp()", "
_MAX_COMPLETION_CRITERIA = 8
_COMPLETION_CRITERION_OUTCOME_MAX_CHARS = 200
+_COMPLETION_CRITERION_CONTINGENT_ON_MAX_CHARS = 200
+_CONTINGENT_ANTECEDENT_OUTPUT_PATH_RE = re.compile(r"^output\.[A-Za-z_][A-Za-z0-9_]*$")
_REQUESTED_OUTPUT_CRITERION_ID_PREFIX = "__copilot_requested_output__"
FALLBACK_FLOOR_CRITERION_ID_PREFIX = "__copilot_fallback_floor__"
@@ -195,6 +197,8 @@ _OUTPUT_OUTCOME_WORDS = frozenset(
class CompletionCriterion:
id: str
outcome: str
+ contingent_on: str | None = None
+ contingent_antecedent_output_path: str | None = None
implicit: bool = False
method_mandated: bool = False
# "definition": a property of the workflow definition itself, graded against the
@@ -555,7 +559,7 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
if not isinstance(raw, list):
return []
criteria: list[CompletionCriterion] = []
- seen: set[str] = set()
+ seen: set[tuple[str, str, str]] = set()
for item in raw:
if not isinstance(item, dict):
continue
@@ -567,7 +571,21 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
continue
output_path_raw = item.get("output_path")
output_path = output_path_raw.strip() if isinstance(output_path_raw, str) and output_path_raw.strip() else None
- key = output_path or normalized_criterion_outcome_key(outcome)
+ contingent_on_raw = item.get("contingent_on")
+ contingent_on = (
+ " ".join(contingent_on_raw.split())[:_COMPLETION_CRITERION_CONTINGENT_ON_MAX_CHARS].strip()
+ if isinstance(contingent_on_raw, str)
+ else None
+ )
+ contingent_on = contingent_on or None
+ contingent_antecedent_output_path = _normalize_contingent_antecedent_output_path(
+ item.get("contingent_antecedent_output_path")
+ )
+ key = (
+ contingent_on or "",
+ contingent_antecedent_output_path or "",
+ output_path or normalized_criterion_outcome_key(outcome),
+ )
if key in seen:
continue
seen.add(key)
@@ -576,6 +594,8 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
CompletionCriterion(
id=f"c{len(criteria)}",
outcome=outcome,
+ contingent_on=contingent_on,
+ contingent_antecedent_output_path=contingent_antecedent_output_path,
implicit=bool(item.get("implicit")),
method_mandated=bool(item.get("method_mandated")),
level=cast(CriterionLevel, level_raw)
@@ -589,6 +609,13 @@ def _parse_completion_criteria(raw: Any) -> list[CompletionCriterion]:
return criteria
+def _normalize_contingent_antecedent_output_path(raw: Any) -> str | None:
+ if not isinstance(raw, str):
+ return None
+ path = raw.strip()
+ return path if _CONTINGENT_ANTECEDENT_OUTPUT_PATH_RE.fullmatch(path) else None
+
+
def normalized_criterion_outcome_key(outcome: str) -> str:
collapsed = " ".join((outcome or "").split())[:_COMPLETION_CRITERION_OUTCOME_MAX_CHARS]
return collapsed.strip().lower().rstrip(".!?;:,").strip()
@@ -870,6 +897,19 @@ def _apply_requested_output_completion_criteria(
if not requested_output_paths:
return
+ contingent_metadata_by_output_path: dict[str, tuple[str | None, str | None]] = {}
+ for criterion in policy.completion_criteria:
+ if criterion.level == "definition" or criterion.method_mandated:
+ continue
+ if not criterion.contingent_on and not criterion.contingent_antecedent_output_path:
+ continue
+ for field_name, output_path, _field_label in requested_specs:
+ if criterion.output_path == output_path or _criterion_text_covers_requested_output(criterion, field_name):
+ contingent_metadata_by_output_path.setdefault(
+ output_path,
+ (criterion.contingent_on, criterion.contingent_antecedent_output_path),
+ )
+
preserved_criteria = [
criterion
for criterion in policy.completion_criteria
@@ -886,6 +926,8 @@ def _apply_requested_output_completion_criteria(
outcome=f"The returned record includes {field_label}.",
level="run",
output_path=output_path,
+ contingent_on=contingent_metadata_by_output_path.get(output_path, (None, None))[0],
+ contingent_antecedent_output_path=contingent_metadata_by_output_path.get(output_path, (None, None))[1],
)
for _field_name, output_path, field_label in requested_specs
]
@@ -906,6 +948,10 @@ def _render_active_criteria_for_prompt(criteria: list[CompletionCriterion] | Non
"method_mandated": criterion.method_mandated,
"level": criterion.level,
}
+ if criterion.contingent_on:
+ item["contingent_on"] = criterion.contingent_on
+ if criterion.contingent_antecedent_output_path:
+ item["contingent_antecedent_output_path"] = criterion.contingent_antecedent_output_path
if criterion.output_path:
item["output_path"] = criterion.output_path
rendered.append(item)
diff --git a/skyvern/forge/sdk/copilot/tools/completion.py b/skyvern/forge/sdk/copilot/tools/completion.py
index 9d2ac2eba..47295e15a 100644
--- a/skyvern/forge/sdk/copilot/tools/completion.py
+++ b/skyvern/forge/sdk/copilot/tools/completion.py
@@ -14,6 +14,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
CompletionVerificationResult,
CriterionVerdict,
RunEvidenceSnapshot,
+ _contingent_metadata_for_criteria,
combine_verification_results,
evaluate_completion_criteria,
grade_definition_criteria,
@@ -22,6 +23,7 @@ from skyvern.forge.sdk.copilot.completion_verification import (
grade_record_semantic_consistency,
grade_structured_record_criteria,
grade_terminal_goal_record_criteria,
+ structural_unfired_contingent_criterion_ids,
summarize_unsatisfied_outcomes,
verdict_missing_evidence,
)
@@ -158,6 +160,10 @@ async def _maybe_run_completion_verification_from_page_observation(
criteria = _completion_verification_criteria(copilot_ctx)
run_criteria, definition_criteria = _split_criteria_by_plane(criteria)
criterion_ids = [criterion.id for criterion in criteria]
+ contingent_ids, contingent_on_by_id, contingent_path_by_id = _contingent_metadata_for_criteria(criteria)
+ run_contingent_ids, run_contingent_on_by_id, run_contingent_path_by_id = _contingent_metadata_for_criteria(
+ run_criteria
+ )
if _classifier_status(copilot_ctx) == "fallback" and not run_criteria:
verification = _no_gradeable_run_plane_result(criterion_ids)
copilot_ctx.completion_verification_result = verification
@@ -173,7 +179,14 @@ async def _maybe_run_completion_verification_from_page_observation(
else []
)
if not run_criteria:
- verification = combine_verification_results(criterion_ids, None, definition_verdicts)
+ verification = combine_verification_results(
+ criterion_ids,
+ None,
+ definition_verdicts,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ )
else:
snapshot = _build_page_observation_evidence_snapshot(
copilot_ctx,
@@ -181,6 +194,7 @@ async def _maybe_run_completion_verification_from_page_observation(
title=title,
observed_data=observed_data,
)
+ run_structural_unfired_ids = structural_unfired_contingent_criterion_ids(run_criteria, snapshot)
requested_output_criteria, judgeable_run_criteria = split_requested_output_criteria(run_criteria)
requested_output_verdicts = (
grade_requested_output_criteria(copilot_ctx, requested_output_criteria, snapshot)
@@ -193,11 +207,29 @@ async def _maybe_run_completion_verification_from_page_observation(
and remaining
<= settings.COPILOT_COMPLETION_JUDGE_TIMEOUT_SECONDS + _COMPLETION_VERIFICATION_BUDGET_MARGIN_SECONDS
):
- run_result = _merge_run_verdicts_if_requested_output_exists(run_criteria, requested_output_verdicts)
+ run_result = _merge_run_verdicts_if_requested_output_exists(
+ run_criteria,
+ requested_output_verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
verification = (
- combine_verification_results(criterion_ids, run_result, definition_verdicts)
+ combine_verification_results(
+ criterion_ids,
+ run_result,
+ definition_verdicts,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ )
if run_result is not None
- else CompletionVerificationResult(status="unavailable")
+ else CompletionVerificationResult(
+ status="unavailable",
+ criterion_ids=criterion_ids,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
)
else:
if not snapshot.has_evidence():
@@ -209,13 +241,25 @@ async def _maybe_run_completion_verification_from_page_observation(
CriterionVerdict(criterion_id=criterion.id, state="unsatisfied", reason_code="no_evidence")
for criterion in judgeable_run_criteria
],
+ contingent_criterion_ids=run_contingent_ids,
+ contingent_on_by_criterion_id=run_contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=run_contingent_path_by_id,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
)
elif not judgeable_run_criteria:
- run_result = _merge_run_verdicts(run_criteria, requested_output_verdicts)
+ run_result = _merge_run_verdicts(
+ run_criteria,
+ requested_output_verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
else:
handler = await _completion_verification_handler(copilot_ctx)
if handler is None:
- run_result = _merge_run_verdicts_if_requested_output_exists(run_criteria, requested_output_verdicts)
+ run_result = _merge_run_verdicts_if_requested_output_exists(
+ run_criteria,
+ requested_output_verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
if run_result is None:
return None
else:
@@ -223,7 +267,11 @@ async def _maybe_run_completion_verification_from_page_observation(
judgeable_result = _apply_present_value_upgrades(judgeable_result, judgeable_run_criteria, snapshot)
if judgeable_result.status != "evaluated":
run_result = (
- _merge_run_verdicts_if_requested_output_exists(run_criteria, requested_output_verdicts)
+ _merge_run_verdicts_if_requested_output_exists(
+ run_criteria,
+ requested_output_verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
or judgeable_result
)
else:
@@ -231,8 +279,16 @@ async def _maybe_run_completion_verification_from_page_observation(
run_criteria,
requested_output_verdicts,
judgeable_result.verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
)
- verification = combine_verification_results(criterion_ids, run_result, definition_verdicts)
+ verification = combine_verification_results(
+ criterion_ids,
+ run_result,
+ definition_verdicts,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ )
if (
isinstance(existing, CompletionVerificationResult)
@@ -438,17 +494,13 @@ def _build_run_evidence_snapshot(copilot_ctx: Any, result: dict[str, Any]) -> Ru
if isinstance(label, str) and label in current_labels and _is_meaningful_extracted_data(evidence_output):
block_outputs[label] = evidence_output
for output_key, output_value in _workflow_output_parameter_payloads(output).items():
- if _is_meaningful_extracted_data(output_value):
- block_outputs[output_key] = output_value
+ block_outputs[output_key] = output_value
for output_key, output_value in _workflow_output_parameter_payloads(data.get("output")).items():
- if _is_meaningful_extracted_data(output_value):
- block_outputs[output_key] = output_value
+ block_outputs[output_key] = output_value
for registered in _registered_output_parameter_payloads(data):
registered_output_key = registered.get("output_parameter_key")
registered_output_value = registered.get("value")
registered_block_label = registered.get("block_label")
- if not _is_meaningful_extracted_data(registered_output_value):
- continue
if isinstance(registered_output_key, str) and registered_output_key:
block_outputs[registered_output_key] = registered_output_value
if isinstance(registered_block_label, str) and registered_block_label in current_labels:
@@ -535,17 +587,32 @@ def _apply_present_value_upgrades(
verdicts = [_merged(verdict) for verdict in run_result.verdicts]
return CompletionVerificationResult(
- status="evaluated", criterion_ids=list(run_result.criterion_ids), verdicts=verdicts
+ status="evaluated",
+ criterion_ids=list(run_result.criterion_ids),
+ verdicts=verdicts,
+ contingent_criterion_ids=list(run_result.contingent_criterion_ids),
+ contingent_on_by_criterion_id=dict(run_result.contingent_on_by_criterion_id),
+ contingent_antecedent_output_path_by_criterion_id=dict(
+ run_result.contingent_antecedent_output_path_by_criterion_id
+ ),
+ structural_unfired_criterion_ids=list(run_result.structural_unfired_criterion_ids),
)
def _merge_run_verdicts(
run_criteria: list[CompletionCriterion],
*verdict_groups: list[CriterionVerdict],
+ contingent_criterion_ids: list[str] | None = None,
+ contingent_on_by_criterion_id: dict[str, str] | None = None,
+ contingent_antecedent_output_path_by_criterion_id: dict[str, str] | None = None,
+ structural_unfired_criterion_ids: list[str] | None = None,
) -> CompletionVerificationResult:
verdict_by_id: dict[str, CriterionVerdict] = {}
for verdicts in verdict_groups:
verdict_by_id.update({verdict.criterion_id: verdict for verdict in verdicts})
+ default_contingent_ids, default_contingent_on_by_id, default_contingent_path_by_id = (
+ _contingent_metadata_for_criteria(run_criteria)
+ )
criterion_ids = [criterion.id for criterion in run_criteria]
return CompletionVerificationResult(
status="evaluated",
@@ -554,6 +621,12 @@ def _merge_run_verdicts(
verdict_by_id.get(criterion_id, CriterionVerdict(criterion_id, "unknown", "unknown"))
for criterion_id in criterion_ids
],
+ contingent_criterion_ids=contingent_criterion_ids or default_contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_criterion_id or default_contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=(
+ contingent_antecedent_output_path_by_criterion_id or default_contingent_path_by_id
+ ),
+ structural_unfired_criterion_ids=structural_unfired_criterion_ids or [],
)
@@ -561,10 +634,16 @@ def _merge_run_verdicts_if_requested_output_exists(
run_criteria: list[CompletionCriterion],
requested_output_verdicts: list[CriterionVerdict],
*verdict_groups: list[CriterionVerdict],
+ structural_unfired_criterion_ids: list[str] | None = None,
) -> CompletionVerificationResult | None:
if not requested_output_verdicts:
return None
- return _merge_run_verdicts(run_criteria, requested_output_verdicts, *verdict_groups)
+ return _merge_run_verdicts(
+ run_criteria,
+ requested_output_verdicts,
+ *verdict_groups,
+ structural_unfired_criterion_ids=structural_unfired_criterion_ids,
+ )
def _run_criteria_for_verdicts(
@@ -587,6 +666,8 @@ def _deterministic_run_verification_result(
remaining criterion stays fail-closed through the normal judge path.
"""
criterion_ids = [criterion.id for criterion in run_criteria]
+ contingent_ids, contingent_on_by_id, contingent_path_by_id = _contingent_metadata_for_criteria(run_criteria)
+ structural_unfired_ids = structural_unfired_contingent_criterion_ids(run_criteria, snapshot)
semantic_verdicts = grade_record_semantic_consistency(run_criteria, snapshot)
if any(not verdict.satisfied for verdict in semantic_verdicts):
return (
@@ -594,6 +675,10 @@ def _deterministic_run_verification_result(
status="evaluated",
criterion_ids=criterion_ids,
verdicts=list(semantic_verdicts),
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=structural_unfired_ids,
),
[],
)
@@ -617,6 +702,10 @@ def _deterministic_run_verification_result(
status="evaluated",
criterion_ids=criterion_ids,
verdicts=[deterministic_by_id[criterion_id] for criterion_id in criterion_ids],
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=structural_unfired_ids,
),
[],
)
@@ -629,6 +718,10 @@ def _deterministic_run_verification_result(
status="evaluated",
criterion_ids=criterion_ids,
verdicts=list(deterministic_by_id.values()),
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=structural_unfired_ids,
),
remaining_criteria,
)
@@ -647,6 +740,10 @@ async def _maybe_run_completion_verification(
criteria = _completion_verification_criteria(copilot_ctx)
run_criteria, definition_criteria = _split_criteria_by_plane(criteria)
criterion_ids = [criterion.id for criterion in criteria]
+ contingent_ids, contingent_on_by_id, contingent_path_by_id = _contingent_metadata_for_criteria(criteria)
+ run_contingent_ids, run_contingent_on_by_id, run_contingent_path_by_id = _contingent_metadata_for_criteria(
+ run_criteria
+ )
if _classifier_status(copilot_ctx) == "fallback" and not run_criteria:
return _no_gradeable_run_plane_result(criterion_ids)
if not criteria:
@@ -657,8 +754,16 @@ async def _maybe_run_completion_verification(
else []
)
if not run_criteria:
- return combine_verification_results(criterion_ids, None, definition_verdicts)
+ return combine_verification_results(
+ criterion_ids,
+ None,
+ definition_verdicts,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ )
snapshot = _build_run_evidence_snapshot(copilot_ctx, result)
+ run_structural_unfired_ids = structural_unfired_contingent_criterion_ids(run_criteria, snapshot)
requested_output_criteria, judgeable_run_criteria = split_requested_output_criteria(run_criteria)
requested_output_verdicts = (
grade_requested_output_criteria(copilot_ctx, requested_output_criteria, snapshot)
@@ -682,13 +787,29 @@ async def _maybe_run_completion_verification(
return combine_verification_results(
[criterion.id for criterion in scoped_run_criteria]
+ [criterion.id for criterion in definition_criteria],
- _merge_run_verdicts(scoped_run_criteria, requested_output_verdicts, contradictions),
+ _merge_run_verdicts(
+ scoped_run_criteria,
+ requested_output_verdicts,
+ contradictions,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ ),
definition_verdicts,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
)
if not definition_verdicts:
return None
+ definition_contingent_ids, definition_contingent_on_by_id, definition_contingent_path_by_id = (
+ _contingent_metadata_for_criteria(definition_criteria)
+ )
return combine_verification_results(
- [criterion.id for criterion in definition_criteria], None, definition_verdicts
+ [criterion.id for criterion in definition_criteria],
+ None,
+ definition_verdicts,
+ contingent_criterion_ids=definition_contingent_ids,
+ contingent_on_by_criterion_id=definition_contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=definition_contingent_path_by_id,
)
if not snapshot.has_evidence():
run_result = _merge_run_verdicts(
@@ -698,24 +819,53 @@ async def _maybe_run_completion_verification(
CriterionVerdict(criterion_id=criterion.id, state="unsatisfied", reason_code="no_evidence")
for criterion in judgeable_run_criteria
],
+ contingent_criterion_ids=run_contingent_ids,
+ contingent_on_by_criterion_id=run_contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=run_contingent_path_by_id,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
)
elif not judgeable_run_criteria:
- run_result = _merge_run_verdicts(run_criteria, requested_output_verdicts)
+ run_result = _merge_run_verdicts(
+ run_criteria,
+ requested_output_verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
else:
deterministic_result, remaining_criteria = _deterministic_run_verification_result(
judgeable_run_criteria, snapshot
)
if deterministic_result is not None and not remaining_criteria:
- run_result = _merge_run_verdicts(run_criteria, requested_output_verdicts, deterministic_result.verdicts)
+ run_result = _merge_run_verdicts(
+ run_criteria,
+ requested_output_verdicts,
+ deterministic_result.verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
else:
handler = await _completion_verification_handler(copilot_ctx)
if handler is None:
requested_output_result = _merge_run_verdicts_if_requested_output_exists(
- run_criteria, requested_output_verdicts
+ run_criteria,
+ requested_output_verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
)
if requested_output_result is not None:
- return combine_verification_results(criterion_ids, requested_output_result, definition_verdicts)
- return CompletionVerificationResult(status="unavailable")
+ return combine_verification_results(
+ criterion_ids,
+ requested_output_result,
+ definition_verdicts,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ )
+ return CompletionVerificationResult(
+ status="unavailable",
+ criterion_ids=criterion_ids,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
# Too little budget to verify a candidate run: fail closed (unavailable)
# rather than let the run-status proxy claim an unverified outcome as success.
remaining = RUN_BLOCKS_SAFETY_CEILING_SECONDS - (time.monotonic() - handler_start)
@@ -724,16 +874,36 @@ async def _maybe_run_completion_verification(
<= settings.COPILOT_COMPLETION_JUDGE_TIMEOUT_SECONDS + _COMPLETION_VERIFICATION_BUDGET_MARGIN_SECONDS
):
requested_output_result = _merge_run_verdicts_if_requested_output_exists(
- run_criteria, requested_output_verdicts
+ run_criteria,
+ requested_output_verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
)
if requested_output_result is not None:
- return combine_verification_results(criterion_ids, requested_output_result, definition_verdicts)
- return CompletionVerificationResult(status="unavailable")
+ return combine_verification_results(
+ criterion_ids,
+ requested_output_result,
+ definition_verdicts,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ )
+ return CompletionVerificationResult(
+ status="unavailable",
+ criterion_ids=criterion_ids,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
judged_result = await evaluate_completion_criteria(remaining_criteria, snapshot, handler)
if judged_result.status != "evaluated":
# Deterministic requested-output verdicts can still ground completion when the judge abstains.
run_result = (
- _merge_run_verdicts_if_requested_output_exists(run_criteria, requested_output_verdicts)
+ _merge_run_verdicts_if_requested_output_exists(
+ run_criteria,
+ requested_output_verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
or judged_result
)
else:
@@ -745,6 +915,10 @@ async def _maybe_run_completion_verification(
status="evaluated",
criterion_ids=[criterion.id for criterion in run_criteria],
verdicts=verdicts,
+ contingent_criterion_ids=run_contingent_ids,
+ contingent_on_by_criterion_id=run_contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=run_contingent_path_by_id,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
)
run_result = _apply_present_value_upgrades(
run_result,
@@ -752,8 +926,20 @@ async def _maybe_run_completion_verification(
snapshot,
include_terminal_goal_records=True,
)
- run_result = _merge_run_verdicts(run_criteria, requested_output_verdicts, run_result.verdicts)
- return combine_verification_results(criterion_ids, run_result, definition_verdicts)
+ run_result = _merge_run_verdicts(
+ run_criteria,
+ requested_output_verdicts,
+ run_result.verdicts,
+ structural_unfired_criterion_ids=run_structural_unfired_ids,
+ )
+ return combine_verification_results(
+ criterion_ids,
+ run_result,
+ definition_verdicts,
+ contingent_criterion_ids=contingent_ids,
+ contingent_on_by_criterion_id=contingent_on_by_id,
+ contingent_antecedent_output_path_by_criterion_id=contingent_path_by_id,
+ )
def _outcome_unverified_reason(
@@ -811,7 +997,7 @@ def _missing_evidence_detail(
outcome_by_id = {criterion.id: criterion.outcome for criterion in criteria}
parts: list[str] = []
for verdict in completion_verification.verdicts:
- if verdict.satisfied:
+ if verdict.satisfied or completion_verification.is_structural_contingent_abstention(verdict):
continue
missing_evidence = verdict_missing_evidence(verdict)
if not missing_evidence:
diff --git a/tests/unit/test_copilot_completion_verification.py b/tests/unit/test_copilot_completion_verification.py
index 3bc8a3c05..74d0bb1cb 100644
--- a/tests/unit/test_copilot_completion_verification.py
+++ b/tests/unit/test_copilot_completion_verification.py
@@ -21,12 +21,14 @@ from skyvern.forge.sdk.copilot.completion_verification import (
RunEvidenceSnapshot,
_coerce_result,
_structured_record_has_identifier,
+ combine_verification_results,
evaluate_completion_criteria,
grade_definition_criteria,
grade_present_value_criteria,
grade_record_semantic_consistency,
grade_structured_record_criteria,
grade_terminal_goal_record_criteria,
+ structural_unfired_contingent_criterion_ids,
structured_record_has_goal_content,
structured_record_has_identity,
summarize_unsatisfied_outcomes,
@@ -75,8 +77,23 @@ from skyvern.forge.sdk.copilot.tools import (
from skyvern.forge.sdk.copilot.tools.completion import _artifact_health_blocker_from_result
-def _criterion(cid: str, outcome: str, *, method_mandated: bool = False) -> CompletionCriterion:
- return CompletionCriterion(id=cid, outcome=outcome, method_mandated=method_mandated)
+def _criterion(
+ cid: str,
+ outcome: str,
+ *,
+ method_mandated: bool = False,
+ output_path: str | None = None,
+ contingent_on: str | None = None,
+ contingent_antecedent_output_path: str | None = None,
+) -> CompletionCriterion:
+ return CompletionCriterion(
+ id=cid,
+ outcome=outcome,
+ method_mandated=method_mandated,
+ output_path=output_path,
+ contingent_on=contingent_on,
+ contingent_antecedent_output_path=contingent_antecedent_output_path,
+ )
_STRUCTURED_RECORD_CRITERIA = (
@@ -239,6 +256,283 @@ def test_definition_plane_unsatisfied_still_blocks() -> None:
assert _mixed(unreferenced, confirmed).is_fully_satisfied() is False
+def test_unfired_contingent_abstention_does_not_sink_evidence_confirmed_run() -> None:
+ contingent_unknown = CriterionVerdict(criterion_id="c0", state="unknown", reason_code="unknown")
+ confirmed = CriterionVerdict(criterion_id="c1", state="satisfied", reason_code="evidence_confirms")
+ result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0", "c1"],
+ contingent_criterion_ids=["c0"],
+ contingent_on_by_criterion_id={"c0": "the provider site blocks online submission"},
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ structural_unfired_criterion_ids=["c0"],
+ verdicts=[contingent_unknown, confirmed],
+ )
+
+ assert result.is_fully_satisfied() is True
+ trace = result.to_trace_data()
+ assert trace["contingent_criterion_ids"] == ["c0"]
+ assert trace["structural_unfired_criterion_ids"] == ["c0"]
+ assert trace["verdict_0_state"] == "unknown"
+ assert trace["verdict_0_contingent_on"] == "the provider site blocks online submission"
+ assert trace["verdict_0_contingent_antecedent_output_path"] == "output.blocker"
+ assert trace["verdict_0_structural_unfired"] is True
+ assert trace["unmet_criterion_ids"] == []
+ assert trace["missing_evidence"] == []
+ assert "verdict_0_missing_evidence" not in trace
+
+
+ "reason_code,state",
+ [("unknown", "unknown"), ("no_evidence", "unsatisfied"), ("evidence_contradicts", "unsatisfied")],
+)
+def test_structural_unfired_contingent_abstention_accepts_non_satisfied_verdicts(reason_code: str, state: str) -> None:
+ result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0", "c1"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ structural_unfired_criterion_ids=["c0"],
+ verdicts=[
+ CriterionVerdict(criterion_id="c0", state=state, reason_code=reason_code), # type: ignore[arg-type]
+ CriterionVerdict(criterion_id="c1", state="satisfied", reason_code="evidence_confirms"),
+ ],
+ )
+
+ assert result.is_fully_satisfied() is True
+
+
+def test_all_contingent_abstentions_do_not_vacuously_satisfy() -> None:
+ result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ structural_unfired_criterion_ids=["c0"],
+ verdicts=[CriterionVerdict(criterion_id="c0", state="unknown", reason_code="unknown")],
+ )
+
+ assert result.is_fully_satisfied() is False
+
+
+def test_contingent_reason_does_not_abstain_for_non_contingent_criterion() -> None:
+ result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0", "c1"],
+ verdicts=[
+ CriterionVerdict(criterion_id="c0", state="unknown", reason_code="unknown"),
+ CriterionVerdict(criterion_id="c1", state="satisfied", reason_code="evidence_confirms"),
+ ],
+ structural_unfired_criterion_ids=["c0"],
+ )
+
+ assert result.is_fully_satisfied() is False
+
+
+def test_judge_contingent_reason_cannot_authorize_structural_abstention() -> None:
+ raw = {
+ "verdicts": [
+ {"criterion_id": "c0", "satisfied": False, "reason_code": "contingent_unfired"},
+ {"criterion_id": "c1", "satisfied": True, "reason_code": "evidence_confirms"},
+ ]
+ }
+
+ result = _coerce_result(
+ raw,
+ ["c0", "c1"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ )
+
+ assert result.verdicts[0].reason_code == "unknown"
+ assert result.verdicts[0].state == "unknown"
+ assert result.is_fully_satisfied() is False
+
+
+def test_fired_contingent_criterion_without_blocker_evidence_fails() -> None:
+ raw = {"verdicts": [{"criterion_id": "c0", "satisfied": False, "reason_code": "no_evidence"}]}
+ criteria = [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ )
+ ]
+ result = _coerce_result(
+ raw,
+ ["c0"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ structural_unfired_criterion_ids=structural_unfired_contingent_criterion_ids(
+ criteria,
+ RunEvidenceSnapshot(block_outputs={"terminal_result": {"blocker": "Provider requires a phone call."}}),
+ ),
+ )
+
+ assert result.verdicts[0].reason_code == "no_evidence"
+ assert result.structural_unfired_criterion_ids == []
+ assert result.is_fully_satisfied() is False
+
+
+def test_fired_contingent_criterion_with_blocker_evidence_can_satisfy() -> None:
+ raw = {
+ "verdicts": [
+ {"criterion_id": "c0", "satisfied": True, "reason_code": "evidence_confirms"},
+ {"criterion_id": "c1", "satisfied": True, "reason_code": "evidence_confirms"},
+ ]
+ }
+ result = _coerce_result(
+ raw,
+ ["c0", "c1"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ )
+
+ assert result.is_fully_satisfied() is True
+
+
+def test_combine_verification_results_preserves_contingent_ids() -> None:
+ run_result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0", "c1"],
+ contingent_criterion_ids=["c1"],
+ contingent_on_by_criterion_id={"c1": "the provider site blocks online submission"},
+ contingent_antecedent_output_path_by_criterion_id={"c1": "output.blocker"},
+ structural_unfired_criterion_ids=["c1"],
+ verdicts=[
+ CriterionVerdict(criterion_id="c0", state="satisfied", reason_code="evidence_confirms"),
+ CriterionVerdict(criterion_id="c1", state="unknown", reason_code="unknown"),
+ ],
+ )
+
+ result = combine_verification_results(["c0", "c1"], run_result, [])
+
+ assert result.contingent_criterion_ids == ["c1"]
+ assert result.contingent_on_by_criterion_id == {"c1": "the provider site blocks online submission"}
+ assert result.contingent_antecedent_output_path_by_criterion_id == {"c1": "output.blocker"}
+ assert result.structural_unfired_criterion_ids == ["c1"]
+ assert result.is_fully_satisfied() is True
+
+
+def test_structural_unfired_ids_derive_from_empty_output_path() -> None:
+ criteria = [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ )
+ ]
+ snapshot = RunEvidenceSnapshot(block_outputs={"blocker_output": None})
+
+ assert structural_unfired_contingent_criterion_ids(criteria, snapshot) == ["c0"]
+
+
[email protected]("reason_code,state", [("evidence_contradicts", "unsatisfied"), ("unknown", "unknown")])
+def test_false_contingent_antecedent_output_abstains(reason_code: str, state: str) -> None:
+ criteria = [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ )
+ ]
+ structural_unfired_ids = structural_unfired_contingent_criterion_ids(
+ criteria,
+ RunEvidenceSnapshot(block_outputs={"terminal_result": {"blocker": False}}),
+ )
+ result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0", "c1"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ structural_unfired_criterion_ids=structural_unfired_ids,
+ verdicts=[
+ CriterionVerdict(criterion_id="c0", state=state, reason_code=reason_code), # type: ignore[arg-type]
+ CriterionVerdict(criterion_id="c1", state="satisfied", reason_code="evidence_confirms"),
+ ],
+ )
+
+ assert structural_unfired_ids == ["c0"]
+ assert result.is_fully_satisfied() is True
+
+
+def test_true_contingent_antecedent_output_fires_and_requires_consequent_evidence() -> None:
+ criteria = [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ )
+ ]
+ structural_unfired_ids = structural_unfired_contingent_criterion_ids(
+ criteria,
+ RunEvidenceSnapshot(block_outputs={"terminal_result": {"blocker": True}}),
+ )
+ result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0", "c1"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ structural_unfired_criterion_ids=structural_unfired_ids,
+ verdicts=[
+ CriterionVerdict(criterion_id="c0", state="unsatisfied", reason_code="evidence_contradicts"),
+ CriterionVerdict(criterion_id="c1", state="satisfied", reason_code="evidence_confirms"),
+ ],
+ )
+
+ assert structural_unfired_ids == []
+ assert result.is_fully_satisfied() is False
+
+
+def test_missing_contingent_antecedent_output_path_fails_closed() -> None:
+ criteria = [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ )
+ ]
+ snapshot = RunEvidenceSnapshot(block_outputs={"confirmation_output": "submitted"})
+ result = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0", "c1"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ structural_unfired_criterion_ids=structural_unfired_contingent_criterion_ids(criteria, snapshot),
+ verdicts=[
+ CriterionVerdict(criterion_id="c0", state="unknown", reason_code="unknown"),
+ CriterionVerdict(criterion_id="c1", state="satisfied", reason_code="evidence_confirms"),
+ ],
+ )
+
+ assert result.structural_unfired_criterion_ids == []
+ assert result.is_fully_satisfied() is False
+
+
+def test_structural_fired_evidence_overrides_empty_output_path() -> None:
+ criteria = [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ )
+ ]
+ snapshot = RunEvidenceSnapshot(
+ block_outputs={
+ "blocker_output": None,
+ "blocker_detector": {"blocker": "Provider site requires a phone call."},
+ }
+ )
+
+ assert structural_unfired_contingent_criterion_ids(criteria, snapshot) == []
+
+
def test_empty_verdicts_with_criteria_is_not_vacuously_satisfied() -> None:
result = CompletionVerificationResult(status="evaluated", criterion_ids=["c0"], verdicts=[])
assert result.is_fully_satisfied() is False
@@ -976,6 +1270,51 @@ def test_outcome_unverified_reason_uses_typed_missing_evidence_not_confirmation_
assert "previously tested revision" in known_good_reason
assert "prefer restoring that revision" in known_good_reason
+
+def test_outcome_unverified_reason_excludes_structurally_abstained_contingent_missing_evidence() -> None:
+ policy = RequestPolicy(
+ completion_criteria=[
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ ),
+ _criterion("c1", "The confirmation number is extracted."),
+ ]
+ )
+ verification = CompletionVerificationResult(
+ status="evaluated",
+ criterion_ids=["c0", "c1", "c2"],
+ contingent_criterion_ids=["c0"],
+ contingent_antecedent_output_path_by_criterion_id={"c0": "output.blocker"},
+ structural_unfired_criterion_ids=["c0"],
+ verdicts=[
+ CriterionVerdict(
+ criterion_id="c0",
+ state="unsatisfied",
+ reason_code="evidence_contradicts",
+ missing_evidence="blocker report",
+ ),
+ CriterionVerdict(
+ criterion_id="c1",
+ state="unsatisfied",
+ reason_code="no_evidence",
+ missing_evidence="confirmation output",
+ ),
+ CriterionVerdict(criterion_id="c2", state="satisfied", reason_code="evidence_confirms"),
+ ],
+ )
+ ctx = SimpleNamespace(request_policy=policy)
+
+ reason = _outcome_unverified_reason(ctx, verification)
+
+ assert reason is not None
+ assert "confirmation output" in reason
+ assert "confirmation number" in reason
+ assert "provider blocker" not in reason
+ assert "blocker report" not in reason
+
missing_metadata = CompletionVerificationResult(
status="evaluated",
criterion_ids=["c_missing"],
@@ -2147,6 +2486,41 @@ async def test_maybe_run_completion_verification_runs_on_unverified_prefix(monke
assert result.is_fully_satisfied() is True
[email protected]("reason_code", ["evidence_contradicts", "no_evidence", "unknown"])
+async def test_mixed_completion_verification_preserves_structural_unfired_contingent_ids(
+ monkeypatch: pytest.MonkeyPatch, reason_code: str
+) -> None:
+ async def handler(**_: object) -> dict:
+ return {"verdicts": [{"criterion_id": "c1", "satisfied": False, "reason_code": reason_code}]}
+
+ _patch_completion_handler(monkeypatch, handler)
+ ctx = _ctx_with_blocks("code")
+ _set_workflow_labels(ctx, "submit_water_request")
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ _criterion("c0", "a commercial water service request is submitted"),
+ _criterion(
+ "c1",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ ),
+ ]
+ )
+
+ result = await _maybe_run_completion_verification(
+ ctx, _terminal_goal_output_result(blocker_output=None), time.monotonic()
+ )
+
+ assert result is not None
+ assert result.contingent_criterion_ids == ["c1"]
+ assert result.contingent_on_by_criterion_id == {"c1": "the provider site blocks online submission"}
+ assert result.contingent_antecedent_output_path_by_criterion_id == {"c1": "output.blocker"}
+ assert result.structural_unfired_criterion_ids == ["c1"]
+ assert result.is_fully_satisfied() is True
+
+
def test_gate_recognizes_clean_run_despite_unverified_prefix() -> None:
ctx = _ctx_unverified_prefix()
# The full-workflow run-status latch is False (incremental run), yet the judge
@@ -2745,6 +3119,86 @@ async def test_requested_output_verdict_survives_unavailable_judge_result(
assert verdicts["c_cart"].state == "unknown"
[email protected]("reason_code", ["missing_exact_field", "unproducible"])
+async def test_unfired_contingent_requested_output_miss_does_not_veto_satisfied_run_criterion(
+ monkeypatch: pytest.MonkeyPatch,
+ reason_code: str,
+) -> None:
+ async def fail_handler(**_: object) -> object:
+ raise AssertionError("deterministic requested-output and present-value criteria should bypass the judge")
+
+ _patch_completion_handler(monkeypatch, fail_handler)
+ ctx = _run_ctx()
+ _set_workflow_labels(ctx, "extract_profile")
+ if reason_code == "missing_exact_field":
+ ctx.code_artifact_metadata = _metadata_for_requested_paths("npi")
+ output = {"status": "DONE", "blocker": False}
+ else:
+ output = {"status": "DONE", "blocker": False, "npi": "1234567890"}
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ _criterion(
+ "c_npi",
+ "The NPI is returned.",
+ output_path="output.npi",
+ contingent_on="the provider lookup is available",
+ contingent_antecedent_output_path="output.blocker",
+ ),
+ _criterion("c_status", 'The output includes "DONE".'),
+ ]
+ )
+
+ verification = await _maybe_run_completion_verification(ctx, _requested_output_result(output), time.monotonic())
+
+ assert verification is not None
+ assert verification.is_fully_satisfied() is True
+ verdicts = {verdict.criterion_id: verdict for verdict in verification.verdicts}
+ assert verdicts["c_npi"].reason_code == reason_code
+ assert verdicts["c_status"].satisfied is True
+ assert verification.structural_unfired_criterion_ids == ["c_npi"]
+
+
[email protected]("reason_code", ["missing_exact_field", "unproducible"])
+async def test_fired_contingent_requested_output_miss_still_vetoes(
+ monkeypatch: pytest.MonkeyPatch,
+ reason_code: str,
+) -> None:
+ async def fail_handler(**_: object) -> object:
+ raise AssertionError("deterministic requested-output and present-value criteria should bypass the judge")
+
+ _patch_completion_handler(monkeypatch, fail_handler)
+ ctx = _run_ctx()
+ _set_workflow_labels(ctx, "extract_profile")
+ if reason_code == "missing_exact_field":
+ ctx.code_artifact_metadata = _metadata_for_requested_paths("npi")
+ output = {"status": "DONE", "blocker": True}
+ else:
+ output = {"status": "DONE", "blocker": True, "npi": "1234567890"}
+ ctx.request_policy = RequestPolicy(
+ completion_criteria=[
+ _criterion(
+ "c_npi",
+ "The NPI is returned.",
+ output_path="output.npi",
+ contingent_on="the provider lookup is available",
+ contingent_antecedent_output_path="output.blocker",
+ ),
+ _criterion("c_status", 'The output includes "DONE".'),
+ ]
+ )
+
+ verification = await _maybe_run_completion_verification(ctx, _requested_output_result(output), time.monotonic())
+
+ assert verification is not None
+ assert verification.is_fully_satisfied() is False
+ verdicts = {verdict.criterion_id: verdict for verdict in verification.verdicts}
+ assert verdicts["c_npi"].reason_code == reason_code
+ assert verdicts["c_status"].satisfied is True
+ assert verification.structural_unfired_criterion_ids == []
+
+
@pytest.mark.asyncio
async def test_maybe_run_completion_verification_treats_fallback_record_as_criteria_less(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_copilot_request_policy_completion_criteria.py b/tests/unit/test_copilot_request_policy_completion_criteria.py
index a1c927302..a0257a8a0 100644
--- a/tests/unit/test_copilot_request_policy_completion_criteria.py
+++ b/tests/unit/test_copilot_request_policy_completion_criteria.py
@@ -9,6 +9,7 @@ import pytest
from skyvern.forge.sdk.copilot.completion_criteria_store import (
StoredCriteriaSet,
StoredCriteriaSnapshot,
+ criteria_from_json,
criteria_to_json,
reconcile_completion_criteria,
)
@@ -18,6 +19,8 @@ from skyvern.forge.sdk.copilot.request_policy import (
RequestPolicy,
_apply_requested_output_completion_criteria,
_classify_request,
+ _parse_completion_criteria,
+ _render_active_criteria_for_prompt,
)
@@ -56,6 +59,8 @@ def _criterion(
level: str = "run",
output_path: str | None = None,
method_mandated: bool = False,
+ contingent_on: str | None = None,
+ contingent_antecedent_output_path: str | None = None,
) -> CompletionCriterion:
return CompletionCriterion(
id=cid,
@@ -63,6 +68,8 @@ def _criterion(
level=level, # type: ignore[arg-type]
output_path=output_path,
method_mandated=method_mandated,
+ contingent_on=contingent_on,
+ contingent_antecedent_output_path=contingent_antecedent_output_path,
)
@@ -325,6 +332,189 @@ def test_stored_complete_requested_output_survives_narrowed_generic_fresh_criter
assert decision.criteria == stored.criteria
+def test_requested_output_canonicalization_preserves_contingent_metadata() -> None:
+ policy = RequestPolicy(
+ completion_criteria=[
+ _criterion(
+ "conditional_npi",
+ "The returned record includes NPI.",
+ output_path="output.npi",
+ contingent_on="the provider site allows online lookup",
+ contingent_antecedent_output_path="output.provider_lookup_available",
+ )
+ ]
+ )
+
+ _apply_requested_output_completion_criteria(policy, "Return a final record with NPI.")
+
+ criteria = _requested_output_subset(policy, {"output.npi"})
+ assert len(criteria) == 1
+ assert criteria[0].outcome == "The returned record includes NPI."
+ assert criteria[0].contingent_on == "the provider site allows online lookup"
+ assert criteria[0].contingent_antecedent_output_path == "output.provider_lookup_available"
+
+
+def test_classifier_parse_preserves_contingent_on_without_inference() -> None:
+ criteria = _parse_completion_criteria(
+ [
+ {
+ "outcome": "A provider blocker is reported to the user.",
+ "contingent_on": "the provider site blocks online submission",
+ },
+ {"outcome": "The request is submitted unless the provider site blocks online submission."},
+ {"outcome": "Ignored empty contingent value.", "contingent_on": " "},
+ ]
+ )
+
+ assert criteria[0].outcome == "A provider blocker is reported to the user."
+ assert criteria[0].contingent_on == "the provider site blocks online submission"
+ assert criteria[1].contingent_on is None
+ assert criteria[2].contingent_on is None
+
+
+def test_classifier_parse_preserves_contingent_antecedent_output_path_without_inference() -> None:
+ criteria = _parse_completion_criteria(
+ [
+ {
+ "outcome": "A provider blocker is reported to the user.",
+ "contingent_on": "the provider site blocks online submission",
+ "contingent_antecedent_output_path": "output.blocker",
+ },
+ {
+ "outcome": "Rejected transcript path.",
+ "contingent_on": "the transcript mentions a blocker",
+ "contingent_antecedent_output_path": "transcript.blocker",
+ },
+ {
+ "outcome": "Rejected nested path.",
+ "contingent_antecedent_output_path": "output.blocker.reason",
+ },
+ {"outcome": "No regex inference when prose mentions output.blocker."},
+ ]
+ )
+
+ assert criteria[0].contingent_antecedent_output_path == "output.blocker"
+ assert criteria[1].contingent_antecedent_output_path is None
+ assert criteria[2].contingent_antecedent_output_path is None
+ assert criteria[3].contingent_antecedent_output_path is None
+
+
+def test_active_criteria_rendering_includes_contingent_on() -> None:
+ rendered = _render_active_criteria_for_prompt(
+ [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ )
+ ]
+ )
+
+ assert json.loads(rendered) == [
+ {
+ "outcome": "A provider blocker is reported to the user.",
+ "implicit": False,
+ "method_mandated": False,
+ "level": "run",
+ "contingent_on": "the provider site blocks online submission",
+ }
+ ]
+
+
+def test_active_criteria_rendering_includes_contingent_antecedent_output_path() -> None:
+ rendered = _render_active_criteria_for_prompt(
+ [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ )
+ ]
+ )
+
+ assert json.loads(rendered) == [
+ {
+ "outcome": "A provider blocker is reported to the user.",
+ "implicit": False,
+ "method_mandated": False,
+ "level": "run",
+ "contingent_on": "the provider site blocks online submission",
+ "contingent_antecedent_output_path": "output.blocker",
+ }
+ ]
+
+
+def test_criteria_json_round_trips_contingent_on() -> None:
+ criteria = (
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ ),
+ )
+
+ restored = criteria_from_json(criteria_to_json(criteria))
+
+ assert restored == criteria
+
+
+def test_criteria_json_round_trips_contingent_antecedent_output_path() -> None:
+ criteria = (
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ ),
+ )
+
+ restored = criteria_from_json(criteria_to_json(criteria))
+
+ assert restored == criteria
+
+
+def test_reconcile_keeps_conditional_and_unconditional_same_outcome_distinct() -> None:
+ stored = _stored(_criterion("s0", "A provider blocker is reported to the user."))
+ fresh = [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ )
+ ]
+
+ decision = reconcile_completion_criteria(
+ StoredCriteriaSnapshot(active=stored, next_epoch=2),
+ fresh,
+ actionable=True,
+ )
+
+ assert decision.action == "create"
+ assert decision.criteria == tuple(fresh)
+
+
+def test_reconcile_keeps_structural_conditional_and_unconditional_same_outcome_distinct() -> None:
+ stored = _stored(_criterion("s0", "A provider blocker is reported to the user."))
+ fresh = [
+ _criterion(
+ "c0",
+ "A provider blocker is reported to the user.",
+ contingent_on="the provider site blocks online submission",
+ contingent_antecedent_output_path="output.blocker",
+ )
+ ]
+
+ decision = reconcile_completion_criteria(
+ StoredCriteriaSnapshot(active=stored, next_epoch=2),
+ fresh,
+ actionable=True,
+ )
+
+ assert decision.action == "create"
+ assert decision.criteria == tuple(fresh)
+
+
@pytest.mark.asyncio
async def test_requested_output_criteria_survive_cap_with_existing_and_generic_criteria() -> None:
criteria = [{"outcome": f"Specific retained outcome {index}."} for index in range(7)]