Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(reporting): add per-case expectation diagnostics (#382)
Christopher Kevind7f8db1bc707
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 49b08522..7858a472 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,13 @@ All notable changes to SkillEvaluator are documented in this file.### Added+- Tier 3 reports show per-case expectation inventories with explicit met,+ unmet, unchecked, unscored and inapplicable judgments, evidence and next+ diagnostic steps for executed conditions. Behavior judges can abstain when+ evidence is missing; partial results preserve every original requirement+ without presenting missing judgments as verified skill defects. Unexpected+ judge errors retain that inventory; intentionally skipped arms add no attempts.+- Run SkillEvaluator's own `skills/` through the pinned three-tier GitHubcallers, retaining Tier 1 as required and Tier 2/3 as advisory. A separateconsumer feedback listener preserves the reusable publisher's public path;diff --git a/docs/reports.mdx b/docs/reports.mdxindex 13f1cdcf..9416db99 100644--- a/docs/reports.mdx+++ b/docs/reports.mdx@@ -803,6 +803,52 @@ from every trial, not only the rows the preview keeps, for up to 200 evalcases; a note says how many more cases the JSON download holds. A case withmissing or partial step telemetry is a gap, not a zero.+### Per-case expectation diagnostics++The HTML **Dataset** tab expands each case into its authored requirements and+recorded judgments, separately for each agent, attempt and condition. The JSON+payload's `case_diagnostics` carries the same inventory. Requirements retain+their original text (with credentials redacted); behavior IDs use the source+field and zero-based position, while judge `step` numbers remain one-based.+Routing and script checks use their named sub-checks, not the aggregate score.+Expected output is checked separately for goal achievement and accuracy; an+excluded accuracy criterion is listed as inapplicable, never as unmet.++Each judgment has one of five statuses:++| Status | Meaning | Next diagnostic step |+| --- | --- | --- |+| Met | An explicit verdict supports the requirement | No correction indicated by this check |+| Unmet | An explicit verdict reports a violation | Compare the requirement with the observed evidence; inspect execution if it is valid, or correct the test if it is inappropriate |+| Not checked | No unique usable verdict: missing/truncated output, judge or execution error, ambiguous identity, or explicit judge abstention | Inspect the retained execution/judge artifacts and rerun before diagnosing a skill defect |+| Unscored | The grader did not score this requirement's metric | Inspect grader configuration and score output |+| Not applicable | The grader explicitly excluded this check for this condition | Confirm that exclusion is intended; do not count it as a failure |++Reasons and short evidence excerpts accompany the verdicts when recorded.+Excerpts are metric-level context, not proof automatically attributed to every+requirement. A low score alone never assigns ownership to the skill or test.+Negative controls may correctly avoid the skill while completing an unrelated+task; being unrelated is not a reason to remove the case. The no-skill baseline+can mark skill checks inapplicable while still judging the task outcome.+Intentionally skipped conditions do not create diagnostic attempts. Failed or+unknown conditions remain visible even when no trial result was retained.++Behavior judges may return `passed: null` with an explanation when evidence+does not permit a check. The rich behavior result's `expectations` retains all+original behaviors, including those missing from a salvaged response. Existing+conservative scoring is preserved: only explicit passes earn credit, and the+denominator remains the full expected behavior count. Unchecked entries can+therefore lower the score without establishing a verified defect.++Inventories are bounded to 512 cases, 128 requirements per case, 512 attempts+across the report and 8,192 judgments. Any omissions are recorded under+`report_truncation.omitted`. Oversized HTML previews omit whole diagnostic+inventories rather than truncating identity or status fields; JSON Downloads+retain them unless the canonical 2 MiB limit also requires dropping them.+Dropping an oversized diagnostic inventory preserves built failure reasons+whenever those reasons still fit within the canonical limit.+Retained run artifacts remain the source for details omitted by either limit.+### pass@kpass@k is the reliability signal, reported separately from the dimensiondiff --git a/src/skillevaluator/evaluation/tier3_expectations.py b/src/skillevaluator/evaluation/tier3_expectations.pynew file mode 100644index 00000000..3359b648--- /dev/null+++ b/src/skillevaluator/evaluation/tier3_expectations.py@@ -0,0 +1,243 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Join authored requirements to recorded verdicts, never to aggregate scores."""++from __future__ import annotations++from collections import Counter+from typing import Any++from skillevaluator.evaluation.tier3_findings import sanitize_grader_text++_MAX_CASES = 512+_MAX_ATTEMPTS = 512+_MAX_EXPECTATIONS = 128+_MAX_JUDGMENTS = 8192+_NEXT_STEPS = {+ "met": "No correction indicated by this check.",+ "unmet": (+ "Compare the recorded evidence with this requirement. If the requirement is valid, inspect the skill or "+ "agent execution; if it is inappropriate for this prompt, correct the test. Ownership is not established by the score."+ ),+ "not_checked": "Inspect execution and judge artifacts, then rerun this check before diagnosing a skill defect.",+ "unscored": "Inspect the grader configuration and score output; no scored verdict supports a skill defect.",+ "not_applicable": "Confirm this check is intentionally inapplicable to this condition; do not count it as a failure.",+}+++def _mapping(value: Any) -> dict[str, Any]:+ return value if isinstance(value, dict) else {}+++def _requirement_text(value: Any) -> str:+ # Keep authored whitespace, unlike compact grader reasons.+ from skillevaluator.tier3.eval_core.llm_judge import _redact_configured_credentials+ from skillevaluator.tier3.eval_core.secret_redaction import redact_secrets_in_log_line+ from skillevaluator.utils.redaction import redact_sensitive_text++ return redact_sensitive_text(redact_secrets_in_log_line(_redact_configured_credentials(str(value))))+++def _requirements(case: dict[str, Any]) -> list[dict[str, Any]]:+ requirements = []+ for field, fallback, metric in (+ ("expected_output", "ground_truth", "goal_accuracy"),+ ("assertions", "expected_behavior", "behavior_check"),+ ("expected_skill", "expected_skill", "skill_execution"),+ ("expected_script", "expected_script", "skill_execution"),+ ):+ source = field if field in case else fallback+ value = case.get(source)+ if field == "expected_skill" and source in case:+ text = str(value) if value is not None else "Do not activate the evaluated skill (expected_skill: null)"+ requirements.append({"expectation_id": source, "requirement": _requirement_text(text), "metric": metric})+ elif field == "assertions" and isinstance(value, list):+ for index, text in enumerate(value):+ requirements.append(+ {+ "expectation_id": f"{source}/{index}",+ "requirement": str(text),+ "metric": metric,+ "step": index + 1,+ "source_conflict": fallback in case and case[fallback] != value,+ }+ )+ elif value is not None and str(value).strip():+ requirements.append(+ {+ "expectation_id": source,+ "requirement": str(value),+ "metric": metric,+ "source_conflict": fallback in case and case[fallback] != value,+ }+ )+ if metric == "goal_accuracy":+ requirements.append(+ {+ "expectation_id": f"{source}/accuracy",+ "requirement": str(value),+ "metric": "accuracy",+ "source_conflict": fallback in case and case[fallback] != value,+ }+ )+ return requirements+++def _judgment(+ requirement: dict[str, Any], reward: dict[str, Any], *, ambiguous: bool = False, missing: bool = False+) -> dict[str, Any]:+ from skillevaluator.tier3.harbor.metrics import metric_set_for_reward, metric_value++ metric = requirement["metric"]+ detail = _mapping(_mapping(reward.get("details")).get(metric))+ check = detail+ if metric == "behavior_check":+ results = detail.get("results")+ matches = (+ [+ item+ for item in results+ if isinstance(item, dict) and type(item.get("step")) is int and item["step"] == requirement.get("step")+ ]+ if isinstance(results, list)+ else []+ )+ check = matches[0] if len(matches) == 1 else {}+ elif metric == "skill_execution":+ key = (+ "script_execution"+ if requirement["expectation_id"] == "expected_script"+ else ("negative_check" if detail.get("should_trigger") is False else "activation")+ )+ check = _mapping(detail.get(key))++ reason = sanitize_grader_text(check.get("reason") or detail.get("reason") or detail.get("message"), 512)+ criteria = _mapping(detail.get("criteria")) if metric == "accuracy" else {}+ excluded = detail.get("excluded_criteria")+ excluded = excluded if isinstance(excluded, list) else []+ applicable_criteria = {key: value for key, value in criteria.items() if key not in excluded}+ metric_error = _mapping(reward.get("evaluation_errors")).get(metric)+ score = metric_value(reward, metric)+ if requirement.get("source_conflict"):+ status, reason = (+ "not_checked",+ "The dataset's current and legacy requirement fields disagree; verify the test input",+ )+ elif missing:+ status, reason = "not_checked", "No retained trial result could be matched to this case"+ elif ambiguous:+ status, reason = "not_checked", "Multiple reward rows cannot be matched to this requirement unambiguously"+ elif reward.get("error"):+ status, reason = "not_checked", sanitize_grader_text(reward["error"], 512)+ elif detail.get("status") == "error" or metric_error:+ status = "not_checked"+ reason = sanitize_grader_text(metric_error, 512) or reason or "Judge failed"+ elif detail.get("status") == "not_applicable" and score is None:+ status = "not_applicable"+ elif metric not in metric_set_for_reward(reward)[1] or score is None:+ status = "unscored"+ reason = reason or "This grader did not record a score for the requirement's metric"+ else:+ passed = check.get("achieved") if metric == "goal_accuracy" else check.get("passed")+ if metric == "accuracy" and applicable_criteria and all(type(v) is bool for v in applicable_criteria.values()):+ passed = all(applicable_criteria.values())+ if type(passed) is bool:+ status = "met" if passed else "unmet"+ else:+ status = "not_checked"+ reason = reason or "No unique explicit verdict was recorded for this expectation"++ evidence = []+ refs = detail.get("evidence_refs")+ if isinstance(refs, list) and status in {"met", "unmet"}:+ for ref in refs[:4]:+ if not isinstance(ref, dict) or ref.get("kind") in {"expected_behavior", "ground_truth"}:+ continue+ text = sanitize_grader_text(ref.get("excerpt"), 300)+ if text:+ evidence.append(text)+ return {+ "expectation_id": requirement["expectation_id"],+ "status": status,+ "reason": reason or "No reason recorded",+ "evidence": evidence,+ "unmet_checks": [sanitize_grader_text(key, 128) for key, value in applicable_criteria.items() if value is False]+ if status == "unmet"+ else [],+ "inapplicable_checks": [sanitize_grader_text(key, 128) for key in excluded[:16]],+ "next_step": _NEXT_STEPS[status],+ }+++def build_case_diagnostics(+ dataset: list[dict[str, Any]], agents: dict[str, dict[str, Any]], *, evaluation_mode: str = "both"+) -> tuple[list[dict[str, Any]], dict[str, int]]:+ from skillevaluator.tier3.harbor.report_data import logical_trial_reward_groups++ condition_trials = []+ for agent, info in agents.items():+ for condition, key in (("with_skill", "rewards"), ("without_skill", "rewards_baseline")):+ if evaluation_mode == "baseline_only" and condition == "with_skill":+ continue+ if evaluation_mode == "with_skill_only" and condition == "without_skill":+ continue+ conditions = _mapping(info.get("conditions"))+ if _mapping(conditions.get(condition)).get("execution_status") == "skipped":+ continue+ if not info.get(key) and condition not in conditions:+ continue+ rows = info.get(key)+ groups_by_case: dict[str, list[list[dict[str, Any]]]] = {}+ groups = (+ logical_trial_reward_groups([row for row in rows if isinstance(row, dict)])+ if isinstance(rows, list)+ else []+ )+ for group in groups:+ for entry_id in {row["entry_id"] for row in group if isinstance(row.get("entry_id"), str)}:+ groups_by_case.setdefault(entry_id, []).append(group)+ errors = _mapping(conditions.get(condition)).get("execution_errors")+ condition_trials.append((agent, condition, groups_by_case, errors))++ omitted: Counter[str] = Counter()+ cases = []+ attempts_left, judgments_left = _MAX_ATTEMPTS, _MAX_JUDGMENTS+ for case in dataset[:_MAX_CASES]:+ entry_id = case.get("id")+ if not isinstance(entry_id, str) or not entry_id:+ continue+ requirements = _requirements(case)+ omitted["expectations"] += max(0, len(requirements) - _MAX_EXPECTATIONS)+ requirements = requirements[:_MAX_EXPECTATIONS]+ for requirement in requirements:+ requirement["requirement"] = _requirement_text(requirement["requirement"])+ attempts = []+ for agent, condition, groups_by_case, errors in condition_trials:+ for group in groups_by_case.get(entry_id) or [[]]:+ if attempts_left <= 0 or judgments_left < len(requirements):+ omitted["expectation_attempts"] += 1+ continue+ attempts_left -= 1+ judgments_left -= len(requirements)+ reward = group[0] if group else {}+ attempts.append(+ {+ "agent": agent,+ "condition": condition,+ "trial_id": reward.get("trial_id"),+ "errors": [sanitize_grader_text(error, 512) for error in errors[:4]]+ if not group and isinstance(errors, list)+ else [],+ "judge_note": sanitize_grader_text(+ _mapping(_mapping(reward.get("details")).get("behavior_check")).get("reason"), 512+ ),+ "judgments": [+ _judgment(requirement, reward, ambiguous=len(group) > 1, missing=not group)+ for requirement in requirements+ ],+ }+ )+ cases.append({"entry_id": entry_id, "requirements": requirements, "attempts": attempts})+ omitted["expectation_cases"] += max(0, len(dataset) - _MAX_CASES)+ return cases, {key: value for key, value in omitted.items() if value}diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.pyindex 031a0c61..68b5301d 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -43,6 +43,7 @@ from skillevaluator.evaluation.tier3_findings import (TRIAL_PASS_THRESHOLD,failure_excerpt,failure_reason,+ failure_reason_text_slots,sanitize_grader_text,strip_failure_reason_text,)@@ -851,6 +852,11 @@ def build_agent_eval_payload(for trial in agent.get("trials", []):trial.pop("score_reasons", None)public_dataset = deduplicate_dataset_entries([entry for entry in (dataset or []) if isinstance(entry, dict)])+ from skillevaluator.evaluation.tier3_expectations import build_case_diagnostics++ case_diagnostics, expectation_omissions = build_case_diagnostics(public_dataset, agents, evaluation_mode=mode)+ for section, count in expectation_omissions.items():+ report_budget.omit(section, count)computed_dataset_truth = (build_dataset_snapshot(public_dataset, evaluator_version=evaluator_version or "") if public_dataset else None)@@ -1014,6 +1020,7 @@ def build_agent_eval_payload("metric_labels": metric_labels,"attempt_policy": policy,"dataset": public_dataset,+ "case_diagnostics": case_diagnostics,"provenance": _build_provenance(agent_payloads,agents,@@ -1366,7 +1373,19 @@ def _enforce_report_payload_budget(# Built failure reasons and excerpts only explain scores the payload already# carries, so they go before any recorded evidence.- report_budget.omit("failure_reasons", strip_failure_reason_text(payload))+ deferred_reasons = [(container, key, container[key]) for container, key in failure_reason_text_slots(payload)]+ omitted_reasons = strip_failure_reason_text(payload)+ if _serialized_payload_size(payload) > _MAX_EMBEDDED_REPORT_BYTES:+ report_budget.omit("case_diagnostics", len(payload.pop("case_diagnostics", [])))+ for container, key, value in deferred_reasons:+ container[key] = value+ refresh_signal()+ omitted_reasons = (+ strip_failure_reason_text(payload)+ if _serialized_payload_size(payload) > _MAX_EMBEDDED_REPORT_BYTES+ else 0+ )+ report_budget.omit("failure_reasons", omitted_reasons)refresh_signal()if _serialized_payload_size(payload) <= _MAX_EMBEDDED_REPORT_BYTES:returndiff --git a/src/skillevaluator/reporting/dashboard_data.py b/src/skillevaluator/reporting/dashboard_data.pyindex 1018eef1..d5294bd4 100644--- a/src/skillevaluator/reporting/dashboard_data.py+++ b/src/skillevaluator/reporting/dashboard_data.py@@ -140,6 +140,10 @@ def _trial_coverage_truncated(marker: dict[str, Any]) -> bool:"custom_metric_discovery_trials","non_best_agent_details","failure_reasons",+ "case_diagnostics",+ "expectation_cases",+ "expectations",+ "expectation_attempts",}if not omitted:return not loading # an unexplained truncation still fails closeddiff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.pyindex 1af5b49c..946b5082 100644--- a/src/skillevaluator/reporting/html.py+++ b/src/skillevaluator/reporting/html.py@@ -985,6 +985,22 @@ def _sanitize_tier3_dataset_case(value: dict[str, Any]) -> dict[str, Any]:return case+def _sanitize_tier3_case_diagnostics(value: object) -> list[dict[str, Any]]:+ cases = _dict_list(value)+ for case in cases:+ case["entry_id"] = _tier3_display_identifier(case.get("entry_id"))+ case["requirements"] = _dict_list(case.get("requirements"))+ case["attempts"] = _dict_list(case.get("attempts"))+ for attempt in case["attempts"]:+ attempt["errors"] = _string_list(attempt.get("errors"))+ attempt["judgments"] = _dict_list(attempt.get("judgments"))+ for judgment in attempt["judgments"]:+ judgment["evidence"] = _string_list(judgment.get("evidence"))+ judgment["unmet_checks"] = _string_list(judgment.get("unmet_checks"))+ judgment["inapplicable_checks"] = _string_list(judgment.get("inapplicable_checks"))+ return cases++def _sanitize_tier3_display_payload(value: dict[str, Any]) -> dict[str, Any]:"""Normalize template-facing types after merging canonical and fallback data."""payload = _json_safe_tier3_payload(value)@@ -1092,6 +1108,7 @@ def _sanitize_tier3_display_payload(value: dict[str, Any]) -> dict[str, Any]:for key in ("conclusions", "recommendations", "suggestions_v2"):payload[key] = _sanitize_tier3_insight_items(payload.get(key))payload["dataset"] = [_sanitize_tier3_dataset_case(item) for item in _dict_list(payload.get("dataset"))]+ payload["case_diagnostics"] = _sanitize_tier3_case_diagnostics(payload.get("case_diagnostics"))payload["trials"] = [_sanitize_tier3_trial(item) for item in _dict_list(payload.get("trials"))]timing: list[dict[str, Any]] = []for item in _dict_list(payload.get("timing")):@@ -1274,9 +1291,20 @@ def _bounded_tier3_preview(payload: dict[str, Any] | None) -> tuple[dict[str, An# reasons are dropped without being restored or counted as left out.strip_failure_reason_text(slim)slim_size = len(_compact_json(slim).encode("utf-8"))+ omitted_diagnostics = 0+ if slim_size > _TIER3_HTML_PREVIEW_TRIGGER_BYTES:+ omitted_diagnostics = len(slim.pop("case_diagnostics", []))+ slim_size = len(_compact_json(slim).encode("utf-8"))if slim_size <= _TIER3_HTML_PREVIEW_TRIGGER_BYTES:omitted_reasons = _restore_failure_reason_text(deferred, _TIER3_HTML_PREVIEW_TRIGGER_BYTES - slim_size)- return slim, {"failure_reasons": omitted_reasons} if omitted_reasons else {}+ return slim, {+ key: count+ for key, count in {+ "failure_reasons": omitted_reasons,+ "case_diagnostics": omitted_diagnostics,+ }.items()+ if count+ }budget = _Tier3PreviewBudget()preview = _bounded_tier3_preview_value(slim, budget)@@ -1287,6 +1315,7 @@ def _bounded_tier3_preview(payload: dict[str, Any] | None) -> tuple[dict[str, An"items": budget.omitted_items,"trial_rows": _capped_tier3_trial_rows(slim),"failure_reasons": len(deferred),+ "case_diagnostics": omitted_diagnostics,}.items()if value > 0}diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2index af9a697b..fa6b4565 100644--- a/src/skillevaluator/reporting/templates/report.html.j2+++ b/src/skillevaluator/reporting/templates/report.html.j2@@ -2247,6 +2247,9 @@.t3-ds-behaviors { counter-reset:behavior; list-style:none; margin:0.45rem 0 0; padding:0; display:grid; gap:0.35rem; }.t3-ds-behaviors li { counter-increment:behavior; display:grid; grid-template-columns:1.7rem 1fr; gap:0.5rem; align-items:start; color:var(--dark-text); font-size:0.87rem; line-height:1.45; }.t3-ds-behaviors li::before { content:counter(behavior); display:inline-flex; align-items:center; justify-content:center; width:1.35rem; height:1.35rem; border-radius:999px; background:var(--bg-secondary); color:var(--secondary-color); font-weight:800; font-size:0.72rem; border:1px solid var(--border-color); }+ .t3-ds-diagnostics { list-style:none; margin:0.45rem 0 0; padding:0; }+ .t3-ds-diagnostics > li { margin-top:0.65rem; padding:0.65rem; border:1px solid var(--border-color); border-radius:0.4rem; overflow-wrap:anywhere; color:var(--dark-text); font-size:0.87rem; line-height:1.45; }+ .t3-ds-diagnostics > li > div { margin-top:0.25rem; }.t3-conclusion { border-left:4px solid var(--warning-color); }.t3-conclusion.pass { border-left-color:var(--success-color); }.t3-conclusion.fail { border-left-color:var(--danger-color); }@@ -2471,6 +2474,9 @@{% if tier3_preview_notice.failure_reasons %}HTML preview left out {{ tier3_preview_notice.failure_reasons }} failure reason{{ 's' if tier3_preview_notice.failure_reasons != 1 else '' }} or excerpt{{ 's' if tier3_preview_notice.failure_reasons != 1 else '' }} to keep the overview complete.{% endif %}+ {% if tier3_preview_notice.case_diagnostics %}+ Expectation diagnostics for {{ tier3_preview_notice.case_diagnostics }} case(s) were omitted from the HTML preview; use JSON Downloads for the retained inventory.+ {% endif %}JSON Downloads preserve the complete bounded canonical payload.</span>{% endif %}@@ -3595,6 +3601,41 @@<ol class="t3-ds-behaviors">{% for b in case_assertions %}<li>{{ b }}</li>{% endfor %}</ol></div>{% endif %}+ {% for diagnostic in tier3.case_diagnostics or [] if diagnostic.entry_id == case.id %}+ <div class="t3-ds-field">+ <span class="t3-ds-label">Expectation diagnostics</span>+ <p>Recorded verdicts, not inferred skill defects. Evidence excerpts are metric-level context; inspect the trial for attribution.</p>+ {% for attempt in diagnostic.attempts %}+ <details class="t3-details" open>+ <summary>{{ attempt.agent }} · {{ 'With skill' if attempt.condition == 'with_skill' else 'Without skill' }} · {{ attempt.trial_id or 'No matched trial' }}</summary>+ <div class="t3-details-body">+ {% for error in attempt.errors %}<p>{{ error }}</p>{% endfor %}+ {% if attempt.judge_note %}<p>{{ attempt.judge_note }}</p>{% endif %}+ {% for status in ['unmet', 'not_checked', 'unscored', 'not_applicable', 'met'] %}+ {% set judgments = attempt.judgments | selectattr('status', 'equalto', status) | list %}+ {% if judgments %}+ <h4>{{ status | replace('_', ' ') | title }} ({{ judgments | length }})</h4>+ <ul class="t3-ds-diagnostics">+ {% for judgment in judgments %}+ <li>+ {% for requirement in diagnostic.requirements if requirement.expectation_id == judgment.expectation_id %}+ <div><b>{{ requirement.expectation_id }}</b>: <span style="white-space:pre-wrap;">{{ requirement.requirement }}</span></div>+ {% endfor %}+ <div>{{ judgment.reason }}</div>+ {% if judgment.unmet_checks %}<div>Unmet rubric checks: {{ judgment.unmet_checks | join(', ') }}</div>{% endif %}+ {% if judgment.inapplicable_checks %}<div>Inapplicable rubric checks: {{ judgment.inapplicable_checks | join(', ') }}</div>{% endif %}+ {% for excerpt in judgment.evidence %}<div><code>{{ excerpt }}</code></div>{% endfor %}+ {% if status != 'met' %}<div>Next diagnostic step: {{ judgment.next_step }}</div>{% endif %}+ </li>+ {% endfor %}+ </ul>+ {% endif %}+ {% endfor %}+ </div>+ </details>+ {% endfor %}+ </div>+ {% endfor %}</div></details>{% endfor %}diff --git a/src/skillevaluator/tier3/eval_core/llm_judge.py b/src/skillevaluator/tier3/eval_core/llm_judge.pyindex 9004cc81..594e177d 100644--- a/src/skillevaluator/tier3/eval_core/llm_judge.py+++ b/src/skillevaluator/tier3/eval_core/llm_judge.py@@ -667,7 +667,7 @@ BEHAVIOR_CHECK_JSON_SCHEMA: dict[str, Any] = {"type": "object","properties": {"step": {"type": "integer"},- "passed": {"type": "boolean"},+ "passed": {"type": ["boolean", "null"]},"reason": {"type": "string"},},"required": ["step", "passed", "reason"],@@ -880,7 +880,12 @@ EXPECTED BEHAVIORS:Respond with ONLY one JSON object. "results" must hold exactly {expected_count} entries, one per \expected behavior: "step" is the behavior's number (each number from 1 to {expected_count} exactly \-once), "passed" is true (observed) or false (not observed), and "reason" is under 15 words. Add a \+once), "passed" is true (observed), false (evidence supports a violation or absence), or null \+when missing or incomplete evidence prevents checking the behavior. Missing artifact contents, \+unavailable tool output, or a truncated trace require null, NOT false, for checks that depend on \+that evidence. A missing observation alone is not proof the behavior failed. Explain that evidence gap \+in "reason" (under 15 words). An unrelated task \+can be a valid negative control: evaluate its stated behavior without requiring skill use. Add a \one-sentence "summary". Do not include a score: it is computed from the results.Example of the shape for this task's {expected_count} behaviors (the values are only an illustration):{example}"""@@ -983,8 +988,14 @@ def _behavior_prompt_example(expected_count: int) -> str:"results": [{"step": step,- "passed": step % 2 == 1,- "reason": "Seen in the transcript." if step % 2 == 1 else "Not seen in the transcript.",+ "passed": None if step % 3 == 0 else step % 3 == 1,+ "reason": (+ "Required tool output was not captured."+ if step % 3 == 0+ else "Seen in the transcript."+ if step % 3 == 1+ else "Observed output violates the requirement."+ ),}for step in range(1, expected_count + 1)],@@ -1028,32 +1039,55 @@ def judge_behavior_check(return Nonereturn candidate- parsed, error, _provenance = _call_validated_json_judge(- prompt,- lambda payload: _behavior_payload_error(payload, expected_count),- call_public_llm,- _extract_json,- salvage=salvage,- **kwargs,- )+ try:+ parsed, error, _provenance = _call_validated_json_judge(+ prompt,+ lambda payload: _behavior_payload_error(payload, expected_count),+ call_public_llm,+ _extract_json,+ salvage=salvage,+ **kwargs,+ )+ except Exception as exc:+ error = f"Required behavior_check judge raised {type(exc).__name__}: {exc}"if error:- return _judge_error(error, results=[])+ return _judge_error(error, results=[], expectations=_behavior_expectations(expected_behaviors, [], error))- # A salvaged reply leaves the behaviors after the cut unjudged; they count as not observed.+ # Keep the conservative score denominator without calling missing verdicts failures.results = sorted(parsed["results"], key=lambda result: result["step"])score = sum(1 for result in results if result["passed"]) / expected_countreturn {"score": round(score, 4),"reason": parsed.get("summary", ""),"results": results,+ "expectations": _behavior_expectations(expected_behaviors, results),}+def _behavior_expectations(+ expected_behaviors: list[str], results: list[dict[str, Any]], error: str = ""+) -> list[dict[str, Any]]:+ by_step = {result["step"]: result for result in results}+ return [+ {+ "step": step,+ "requirement": requirement,+ "status": ("met" if by_step[step]["passed"] else "unmet")+ if step in by_step and type(by_step[step]["passed"]) is bool+ else "not_checked",+ "reason": by_step[step].get("reason", "")+ if step in by_step+ else _redact_configured_credentials(error) or "No judgment returned for this expectation",+ }+ for step, requirement in enumerate(expected_behaviors, 1)+ ]++def _behavior_payload_error(parsed: Any, expected_count: int, *, allow_partial: bool = False) -> str | None:"""Describe what is wrong with a behavior reply, or return ``None`` when it is usable.Each expected behavior is judged exactly once, identified by its 1-based- ``step`` number, with a boolean ``passed``. *allow_partial* accepts a+ ``step`` number, with a boolean ``passed`` or an explicit null abstention. *allow_partial* accepts asalvaged prefix that judges each of its steps once. The score is computedfrom the verdicts, so a ``score`` field in the reply is ignored."""@@ -1069,8 +1103,16 @@ def _behavior_payload_error(parsed: Any, expected_count: int, *, allow_partial:return f'"results" has {len(results)} entries; it needs exactly {expected_count}, one per behavior'if any(not isinstance(result, dict) for result in results):return 'every "results" entry must be an object'- if any(not isinstance(result.get("passed"), bool) for result in results):- return 'every "results" entry needs "passed" set to true or false'+ if any(+ "passed" not in result or (result["passed"] is not None and type(result["passed"]) is not bool)+ for result in results+ ):+ return 'every "results" entry needs "passed" set to true, false, or null'+ if any(+ result["passed"] is None and (not isinstance(result.get("reason"), str) or not result["reason"].strip())+ for result in results+ ):+ return 'unchecked entries need a nonempty "reason" explaining the missing evidence'steps = [result.get("step") for result in results]if any(isinstance(step, bool) or not isinstance(step, int) for step in steps):return 'every "results" entry needs an integer "step" number'diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.pyindex d0189bca..a264aeb8 100644--- a/src/skillevaluator/tier3/harbor/templates/eval.py+++ b/src/skillevaluator/tier3/harbor/templates/eval.py@@ -3082,7 +3082,7 @@ BEHAVIOR_CHECK_JSON_SCHEMA = {"type": "object","properties": {"step": {"type": "integer"},- "passed": {"type": "boolean"},+ "passed": {"type": ["boolean", "null"]},"reason": {"type": "string"},},"required": ["step", "passed", "reason"],@@ -3378,8 +3378,14 @@ def _behavior_prompt_example(expected_count):"results": [{"step": step,- "passed": step % 2 == 1,- "reason": "Seen in the transcript." if step % 2 == 1 else "Not seen in the transcript.",+ "passed": None if step % 3 == 0 else step % 3 == 1,+ "reason": (+ "Required tool output was not captured."+ if step % 3 == 0+ else "Seen in the transcript."+ if step % 3 == 1+ else "Observed output violates the requirement."+ ),}for step in range(1, expected_count + 1)],@@ -3407,7 +3413,12 @@ EXPECTED BEHAVIORS:Respond with ONLY one JSON object. "results" must hold exactly {expected_count} entries, one per \expected behavior: "step" is the behavior's number (each number from 1 to {expected_count} exactly \-once), "passed" is true (observed) or false (not observed), and "reason" is under 15 words. Add a \+once), "passed" is true (observed), false (evidence supports a violation or absence), or null \+when missing or incomplete evidence prevents checking the behavior. Missing artifact contents, \+unavailable tool output, or a truncated trace require null, NOT false, for checks that depend on \+that evidence. A missing observation alone is not proof the behavior failed. Explain that evidence gap \+in "reason" (under 15 words). An unrelated task \+can be a valid negative control: evaluate its stated behavior without requiring skill use. Add a \one-sentence "summary". Do not include a score: it is computed from the results.Example of the shape for this task's {expected_count} behaviors (the values are only an illustration):{_behavior_prompt_example(expected_count)}"""@@ -3425,35 +3436,56 @@ Example of the shape for this task's {expected_count} behaviors (the values arereturn Nonereturn candidate- parsed, error, _provenance = _call_validated_json_judge(- prompt,- lambda payload: _behavior_payload_error(payload, expected_count),- call_public_llm,- extract_json,- metric="behavior_check",- salvage=salvage,- max_tokens=BEHAVIOR_JUDGE_MAX_TOKENS,- response_schema=BEHAVIOR_CHECK_JSON_SCHEMA,- schema_name="behavior_check_judgment",- )+ try:+ parsed, error, _provenance = _call_validated_json_judge(+ prompt,+ lambda payload: _behavior_payload_error(payload, expected_count),+ call_public_llm,+ extract_json,+ metric="behavior_check",+ salvage=salvage,+ max_tokens=BEHAVIOR_JUDGE_MAX_TOKENS,+ response_schema=BEHAVIOR_CHECK_JSON_SCHEMA,+ schema_name="behavior_check_judgment",+ )+ except Exception as exc:+ error = f"Required behavior_check judge raised {type(exc).__name__}: {exc}"if error:- return _judge_error(error, results=[])+ return _judge_error(error, results=[], expectations=_behavior_expectations(expected_behaviors, [], error))- # A salvaged reply leaves the behaviors after the cut unjudged; they count as not observed.+ # Keep the conservative score denominator without calling missing verdicts failures.results = sorted(parsed["results"], key=lambda result: result["step"])score = sum(1 for result in results if result["passed"]) / expected_countreturn {"score": round(score, 4),"reason": parsed.get("summary", ""),"results": results,+ "expectations": _behavior_expectations(expected_behaviors, results),}+def _behavior_expectations(expected_behaviors, results, error=""):+ by_step = {result["step"]: result for result in results}+ return [+ {+ "step": step,+ "requirement": requirement,+ "status": ("met" if by_step[step]["passed"] else "unmet")+ if step in by_step and type(by_step[step]["passed"]) is bool+ else "not_checked",+ "reason": by_step[step].get("reason", "")+ if step in by_step+ else _redact_configured_credentials(error) or "No judgment returned for this expectation",+ }+ for step, requirement in enumerate(expected_behaviors, 1)+ ]++def _behavior_payload_error(parsed, expected_count, *, allow_partial=False):"""Describe what is wrong with a behavior reply, or return ``None`` when it is usable.Each expected behavior is judged exactly once, identified by its 1-based- ``step`` number, with a boolean ``passed``. *allow_partial* accepts a+ ``step`` number, with a boolean ``passed`` or an explicit null abstention. *allow_partial* accepts asalvaged prefix that judges each of its steps once. The score is computedfrom the verdicts, so a ``score`` field in the reply is ignored."""@@ -3469,8 +3501,16 @@ def _behavior_payload_error(parsed, expected_count, *, allow_partial=False):return f'"results" has {len(results)} entries; it needs exactly {expected_count}, one per behavior'if any(not isinstance(result, dict) for result in results):return 'every "results" entry must be an object'- if any(not isinstance(result.get("passed"), bool) for result in results):- return 'every "results" entry needs "passed" set to true or false'+ if any(+ "passed" not in result or (result["passed"] is not None and type(result["passed"]) is not bool)+ for result in results+ ):+ return 'every "results" entry needs "passed" set to true, false, or null'+ if any(+ result["passed"] is None and (not isinstance(result.get("reason"), str) or not result["reason"].strip())+ for result in results+ ):+ return 'unchecked entries need a nonempty "reason" explaining the missing evidence'steps = [result.get("step") for result in results]if any(isinstance(step, bool) or not isinstance(step, int) for step in steps):return 'every "results" entry needs an integer "step" number'@@ -3580,7 +3620,15 @@ def _call_required_judge(metric, judge, *args, allow_not_applicable=False, **kwafinally:signal.signal(signal.SIGALRM, previous_alarm_handler)except Exception as exc:- result = _judge_error(f"Required {metric} judge raised {type(exc).__name__}: {exc}")+ error = f"Required {metric} judge raised {type(exc).__name__}: {exc}"+ metadata = {}+ if metric == "behavior_check":+ expected_behaviors = kwargs.get("expected_behaviors", args[1] if len(args) > 1 else [])+ metadata = {+ "results": [],+ "expectations": _behavior_expectations(expected_behaviors or [], [], error),+ }+ result = _judge_error(error, **metadata)finally:_ACTIVE_JUDGE_DEADLINE.reset(token)_ACTIVE_JUDGE_CALLS.reset(calls_token)diff --git a/tests/reporting/test_tier3_expectations.py b/tests/reporting/test_tier3_expectations.pynew file mode 100644index 00000000..8a7ee7c4--- /dev/null+++ b/tests/reporting/test_tier3_expectations.py@@ -0,0 +1,396 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++from __future__ import annotations++import json+import re++import pytest++from skillevaluator.evaluation import tier3_expectations, tier3_report+from skillevaluator.evaluation.tier3_expectations import build_case_diagnostics+from skillevaluator.models import ValidationResult+from skillevaluator.reporting import HTMLReporter+from skillevaluator.reporting.html import _bounded_tier3_preview+from skillevaluator.tier3.eval_core import llm_judge+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS+from skillevaluator.tier3.harbor.report_data import load_agent_data+++def _reward(**overrides):+ return {+ "entry_id": "case-1",+ "trial_id": "trial-1",+ **dict.fromkeys(DEFAULT_METRICS, 1.0),+ "details": {},+ **overrides,+ }+++def _diagnostic(case, reward, baseline=None):+ agents = {"codex": {"rewards": [reward]}}+ if baseline is not None:+ agents["codex"]["rewards_baseline"] = [baseline]+ cases, omitted = build_case_diagnostics([{"id": "case-1", **case}], agents)+ assert not omitted+ return cases[0]+++def _statuses(diagnostic, attempt=0):+ return {item["expectation_id"]: item["status"] for item in diagnostic["attempts"][attempt]["judgments"]}+++def test_full_and_partial_judge_results_reach_case_report(monkeypatch):+ requirements = ["Read the input\nwithout changing it.", "Write <output.txt>", "Verify the result"]+ response = json.dumps(+ {+ "results": [+ {"step": 3, "passed": True, "reason": "result checked"},+ {"step": 1, "passed": True, "reason": "input read"},+ {"step": 2, "passed": False, "reason": "output file absent"},+ ]+ }+ )+ monkeypatch.setattr(llm_judge, "call_public_llm", lambda *_a, **_kw: (response, None))+ full = llm_judge.judge_behavior_check("Agent read the input and checked, but did not write output.", requirements)+ truncated = '{"results":[{"step":2,"passed":false,"reason":"output file absent"},{"step":3'+ monkeypatch.setattr(llm_judge, "call_public_llm", lambda *_a, **_kw: (truncated, None))+ partial = llm_judge.judge_behavior_check("same trace", requirements)++ full["evidence_refs"] = [{"kind": "tool_observation", "excerpt": "ls: output.txt: No such file"}]+ rewards = [+ _reward(behavior_check=full["score"], details={"behavior_check": full}),+ _reward(trial_id="trial-2", behavior_check=partial["score"], details={"behavior_check": partial}),+ ]+ payload = tier3_report.build_agent_eval_payload(+ "demo",+ {+ "codex": {+ "execution_status": "succeeded",+ "execution_errors": [],+ "expected_attempts": 2,+ "scored_attempts": 2,+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.5),+ "rewards": rewards,+ }+ },+ dataset=[{"id": "case-1", "expected_behavior": requirements}],+ use_llm_judge=False,+ )+ diagnostic = payload["case_diagnostics"][0]+ assert [item["requirement"] for item in diagnostic["requirements"]] == requirements+ assert list(_statuses(diagnostic).values()) == ["met", "unmet", "met"]+ assert list(_statuses(diagnostic, 1).values()) == ["not_checked", "unmet", "not_checked"]+ assert "Salvaged 1/3" in diagnostic["attempts"][1]["judge_note"]++ result = ValidationResult(validator_name="AGENT_EVAL", validator_description="Live evaluation")+ result.metadata["agent_eval"] = payload+ html = HTMLReporter(include_timestamp=False).render_all([result])+ dataset_html = html.split('id="tier3-page-dataset"')[1].split('id="tier3-page-suggestions"')[0]+ for expected in ("Unmet (1)", "Not Checked (2)", "ls: output.txt: No such file", "Next diagnostic step:"):+ assert expected in dataset_html+ assert "Write <output.txt>" in dataset_html+ assert "Ownership is not established by the score" in dataset_html+ assert "trial-1" in dataset_html and "trial-2" in dataset_html+ assert '<ul class="t3-ds-diagnostics">' in dataset_html+ assert '<ul class="t3-ds-behaviors">' not in dataset_html+ assert "<div><b>expected_behavior/1</b>:" in dataset_html+ diagnostic_styles = re.findall(r"\.t3-ds-diagnostics[^{}]*\{([^{}]*)\}", html)+ assert diagnostic_styles+ assert not any("grid" in style or "counter" in style for style in diagnostic_styles)+++ "detail,score,status",+ [+ (+ {"status": "error", "reason": "judge timed out", "results": [{"step": 1, "passed": False}]},+ None,+ "not_checked",+ ),+ ({"status": "not_applicable", "reason": "excluded by grader"}, None, "not_applicable"),+ ({"results": []}, None, "unscored"),+ ({"results": []}, 0.0, "not_checked"),+ ({"results": [{"step": 1, "passed": False}, {"step": 1, "passed": True}]}, 0.5, "not_checked"),+ ({"results": [{"step": True, "passed": False}]}, 0.0, "not_checked"),+ ({"results": [{"step": 1, "passed": "false"}]}, 0.0, "not_checked"),+ ({"results": [{"step": 1, "passed": None, "reason": "missing artifact"}]}, 0.0, "not_checked"),+ ],+)+def test_missing_or_invalid_verdicts_are_never_skill_defects(detail, score, status):+ diagnostic = _diagnostic(+ {"assertions": ["write a file"]}, _reward(behavior_check=score, details={"behavior_check": detail})+ )+ assert _statuses(diagnostic) == {"assertions/0": status}+++def test_execution_error_overrides_nominal_scores_and_verdicts():+ diagnostic = _diagnostic(+ {"expected_behavior": ["write a file"]},+ _reward(error="No trajectory", details={"behavior_check": {"results": [{"step": 1, "passed": False}]}}),+ )+ judgment = diagnostic["attempts"][0]["judgments"][0]+ assert judgment["status"] == "not_checked"+ assert judgment["reason"] == "No trajectory"+++def test_negative_control_routes_correctly_while_task_outcome_fails():+ reward = _reward(+ goal_accuracy=0.0,+ details={+ "skill_execution": {"should_trigger": False, "negative_check": {"passed": True, "reason": "skill avoided"}},+ "goal_accuracy": {"achieved": False, "reason": "wrong answer"},+ "accuracy": {+ "criteria": {"TASK_ADDRESSED": False, "SKILL_IDENTIFIED": False},+ "excluded_criteria": ["SKILL_IDENTIFIED"],+ },+ },+ )+ baseline = _reward(+ skill_execution=None,+ details={+ "skill_execution": {"status": "not_applicable", "reason": "skill not installed"},+ "goal_accuracy": {"achieved": True, "reason": "right answer"},+ },+ )+ diagnostic = _diagnostic({"expected_skill": None, "expected_output": "42"}, reward, baseline)+ assert _statuses(diagnostic) == {+ "expected_output": "unmet",+ "expected_output/accuracy": "unmet",+ "expected_skill": "met",+ }+ assert _statuses(diagnostic, 1)["expected_skill"] == "not_applicable"+ assert _statuses(diagnostic, 1)["expected_output"] == "met"+ accuracy = diagnostic["attempts"][0]["judgments"][1]+ assert accuracy["unmet_checks"] == ["TASK_ADDRESSED"]+ assert accuracy["inapplicable_checks"] == ["SKILL_IDENTIFIED"]+ assert "remove" not in json.dumps(diagnostic).lower()+++def test_successful_positive_routing_does_not_hide_unmet_script_requirement():+ diagnostic = _diagnostic(+ {"expected_skill": "demo", "expected_script": "run.py"},+ _reward(+ details={+ "skill_execution": {+ "activation": {"passed": True},+ "script_execution": {"passed": False, "reason": "not invoked"},+ },+ }+ ),+ )+ assert _statuses(diagnostic) == {"expected_skill": "met", "expected_script": "unmet"}+++def test_custom_grader_does_not_impersonate_standard_judgments():+ diagnostic = _diagnostic(+ {"assertions": ["write the file"]},+ _reward(+ metric_set="custom-only",+ details={+ "behavior_check": {"results": [{"step": 1, "passed": False}]},+ },+ ),+ )+ assert _statuses(diagnostic) == {"assertions/0": "unscored"}+++def test_case_identity_and_condition_are_not_matched_by_position():+ cases, _ = build_case_diagnostics(+ [{"id": "case-1", "assertions": ["first"]}, {"id": "case-2", "assertions": ["second"]}],+ {+ "codex": {+ "rewards": [+ _reward(entry_id="case-2", details={"behavior_check": {"results": [{"step": 1, "passed": False}]}})+ ],+ "conditions": {"with_skill": {"execution_errors": ["first trial crashed"]}},+ }+ },+ )+ assert _statuses(cases[0]) == {"assertions/0": "not_checked"}+ assert cases[0]["attempts"][0]["errors"] == ["first trial crashed"]+ assert _statuses(cases[1]) == {"assertions/0": "unmet"}+++def test_conflicting_aliases_and_multirow_trials_fail_closed():+ diagnostic = _diagnostic({"assertions": ["current"], "expected_behavior": ["older"]}, _reward())+ assert _statuses(diagnostic) == {"assertions/0": "not_checked"}+ assert diagnostic["requirements"][0]["requirement"] == "current"+ cases, _ = build_case_diagnostics(+ [{"id": "case-1", "assertions": ["first"]}], {"codex": {"rewards": [_reward(), _reward()]}}+ )+ assert len(cases[0]["attempts"]) == 1+ assert _statuses(cases[0]) == {"assertions/0": "not_checked"}+++def test_diagnostics_redact_credentials_and_bound_cardinality(monkeypatch):+ monkeypatch.setenv("OPENAI_API_KEY", "private-test-credential")+ diagnostic = _diagnostic(+ {"assertions": ["Do not echo private-test-credential"]},+ _reward(+ details={+ "behavior_check": {+ "results": [{"step": 1, "passed": False, "reason": "echoed private-test-credential"}],+ "evidence_refs": [{"kind": "tool_observation", "excerpt": "private-test-credential"}],+ },+ }+ ),+ )+ assert "private-test-credential" not in json.dumps(diagnostic)+ monkeypatch.setattr(tier3_expectations, "_MAX_EXPECTATIONS", 1)+ monkeypatch.setattr(tier3_expectations, "_MAX_ATTEMPTS", 1)+ _, omitted = build_case_diagnostics(+ [{"id": "case-1", "assertions": ["a", "b"]}],+ {+ "codex": {"rewards": [_reward(), _reward(trial_id="trial-2")]},+ },+ )+ assert omitted == {"expectations": 1, "expectation_attempts": 1}+++def test_baseline_only_omits_unrun_with_skill_condition():+ cases, _ = build_case_diagnostics(+ [{"id": "case-1", "assertions": ["first"]}],+ {+ "codex": {"rewards": [], "rewards_baseline": [_reward()]},+ },+ evaluation_mode="baseline_only",+ )+ assert [attempt["condition"] for attempt in cases[0]["attempts"]] == ["without_skill"]++[email protected]("baseline_status", [None, "skipped"])+def test_loaded_with_skill_only_report_has_no_phantom_baseline(tmp_path, monkeypatch, baseline_status):+ monkeypatch.setattr(tier3_expectations, "_MAX_ATTEMPTS", 2)+ active = tmp_path / "codex" / "with-skill"+ active.mkdir(parents=True)+ (active / "summary.json").write_text(+ json.dumps(+ {+ "scores": dict.fromkeys(DEFAULT_METRICS, 1.0),+ "metrics": list(DEFAULT_METRICS),+ "execution_status": "succeeded",+ "num_trials": 2,+ "expected_attempts": 2,+ "scored_attempts": 2,+ }+ )+ )+ for entry_id in ("case-1", "case-2"):+ trial = active / "trials" / entry_id+ trial.mkdir(parents=True)+ (trial / "reward.json").write_text(json.dumps(_reward(entry_id=entry_id, trial_id=f"trial-{entry_id}")))+ if baseline_status:+ baseline = tmp_path / "codex" / "without-skill"+ baseline.mkdir()+ (baseline / "summary.json").write_text(json.dumps({"scores": {}, "execution_status": baseline_status}))+ agents = load_agent_data(tmp_path)+ assert agents["codex"]["rewards_baseline"] == []+ payload = tier3_report.build_agent_eval_payload(+ "demo",+ agents,+ dataset=[{"id": entry_id, "assertions": ["first"]} for entry_id in ("case-1", "case-2")],+ use_llm_judge=False,+ )+ assert payload["mode"] == "with_skill_only"+ assert len(payload["case_diagnostics"]) == 2+ for case in payload["case_diagnostics"]:+ assert [(attempt["condition"], attempt["trial_id"]) for attempt in case["attempts"]] == [+ ("with_skill", f"trial-{case['entry_id']}")+ ]+ assert "expectation_attempts" not in payload.get("report_truncation", {}).get("omitted", {})+++def test_skipped_conditions_and_absent_empty_arms_do_not_consume_attempt_budget(monkeypatch):+ monkeypatch.setattr(tier3_expectations, "_MAX_ATTEMPTS", 3)+ cases, omitted = build_case_diagnostics(+ [{"id": "case-1", "assertions": ["first"]}],+ {+ "codex": {+ "rewards": [_reward()],+ "rewards_baseline": [],+ "conditions": {"without_skill": {"execution_status": "skipped"}},+ },+ "other": {"rewards": [_reward()], "rewards_baseline": [_reward()]},+ "absent": {"rewards": [], "rewards_baseline": []},+ },+ )+ assert not omitted+ assert [(a["agent"], a["condition"]) for a in cases[0]["attempts"]] == [+ ("codex", "with_skill"),+ ("other", "with_skill"),+ ("other", "without_skill"),+ ]++[email protected]("status", ["failed", "unknown"])+def test_unscored_failed_or_unknown_arm_remains_visible(status):+ cases, omitted = build_case_diagnostics(+ [{"id": "case-1", "assertions": ["first"]}],+ {+ "codex": {+ "rewards": [_reward()],+ "rewards_baseline": [],+ "conditions": {"without_skill": {"execution_status": status, "execution_errors": ["No result"]}},+ }+ },+ )+ assert not omitted+ assert [attempt["condition"] for attempt in cases[0]["attempts"]] == ["with_skill", "without_skill"]+ assert _statuses(cases[0], 1) == {"assertions/0": "not_checked"}+ assert cases[0]["attempts"][1]["errors"] == ["No result"]+++def test_large_preview_omits_whole_diagnostics_without_corrupting_identities():+ payload = {+ "summary": {"overall_score": 0.8},+ "case_diagnostics": [+ {"entry_id": "case-1", "requirements": [{"requirement": "x" * 300_000}]},+ ],+ }+ preview, notice = _bounded_tier3_preview(payload)+ assert "case_diagnostics" not in preview+ assert notice["case_diagnostics"] == 1+ assert preview["summary"] == payload["summary"]+ assert payload["case_diagnostics"][0]["entry_id"] == "case-1"+++def test_canonical_budget_records_dropped_diagnostics(monkeypatch):+ monkeypatch.setattr(tier3_report, "_MAX_EMBEDDED_REPORT_BYTES", 1000)+ payload = {"summary": {"overall_score": 0.8}, "case_diagnostics": [{"entry_id": "case-1", "large": "x" * 2000}]}+ budget = tier3_report._ReportBudget()+ tier3_report._enforce_report_payload_budget(payload, budget)+ assert "case_diagnostics" not in payload+ assert payload["report_truncation"]["omitted"]["case_diagnostics"] == 1+ assert payload["summary"]["overall_score"] == 0.8++[email protected]("oversized_reasons", [False, True])+def test_canonical_budget_restores_reasons_after_dropping_diagnostics(monkeypatch, oversized_reasons):+ monkeypatch.setattr(tier3_report, "_MAX_EMBEDDED_REPORT_BYTES", 1500)+ reason = "x" * (2000 if oversized_reasons else 100)+ evidence = {"reason": reason, "excerpt": "observed result"}+ cards = [{"evidence": [evidence]}]+ payload = {+ "summary": {"overall_score": 0.2},+ "agents": {"codex": {"evaluator_cards": cards, "trials_baseline": [{"score_reasons": {"accuracy": reason}}]}},+ "evaluator_cards": cards,+ "trials": [{"agent": "codex", "score_reasons": {"accuracy": reason}}],+ "case_diagnostics": [{"entry_id": "case-1", "large": "x" * 2000}],+ }+ budget = tier3_report._ReportBudget()+ tier3_report._enforce_report_payload_budget(payload, budget)+ assert "case_diagnostics" not in payload+ assert budget.omitted.get("case_diagnostics") == 1+ assert tier3_report._serialized_payload_size(payload) <= 1500+ if oversized_reasons:+ assert budget.omitted["failure_reasons"] == 4+ assert "reason" not in evidence and "excerpt" not in evidence+ assert "score_reasons" not in payload["trials"][0]+ assert "score_reasons" not in payload["agents"]["codex"]["trials_baseline"][0]+ else:+ assert "failure_reasons" not in budget.omitted+ assert evidence == {"reason": reason, "excerpt": "observed result"}+ assert payload["trials"][0]["score_reasons"] == {"accuracy": reason}+ assert payload["agents"]["codex"]["trials_baseline"][0]["score_reasons"] == {"accuracy": reason}diff --git a/tests/tier3/test_judge_result_semantics.py b/tests/tier3/test_judge_result_semantics.pyindex 715f28be..3fb995ad 100644--- a/tests/tier3/test_judge_result_semantics.py+++ b/tests/tier3/test_judge_result_semantics.py@@ -51,6 +51,89 @@ def _load_template_module() -> ModuleType:eval_template = _load_template_module()[email protected]("module", [llm_judge, eval_template])+def test_behavior_inventory_preserves_original_requirements_and_missing_verdicts(module, monkeypatch):+ truncated = '{"results":[{"step":2,"passed":false,"reason":"file absent"},{"step":3'+ monkeypatch.setattr(module, "call_public_llm", _pair_script([(truncated, None)], []))+ result = module.judge_behavior_check("conversation", ["read the input", "write the file", "check the file"])++ assert result["score"] == 0.0+ assert result["results"] == [{"step": 2, "passed": False, "reason": "file absent"}]+ assert [item["requirement"] for item in result["expectations"]] == [+ "read the input",+ "write the file",+ "check the file",+ ]+ assert [item["status"] for item in result["expectations"]] == ["not_checked", "unmet", "not_checked"]+ assert all(item["reason"] for item in result["expectations"])++[email protected]("module", [llm_judge, eval_template])+def test_behavior_inventory_keeps_all_expectations_after_judge_error(module, monkeypatch):+ monkeypatch.setattr(module, "call_public_llm", _pair_script([("", "judge unavailable")], []))+ result = module.judge_behavior_check("conversation", ["first", "second"])++ assert result["score"] is None+ assert result["status"] == "error"+ assert [item["requirement"] for item in result["expectations"]] == ["first", "second"]+ assert all(item["status"] == "not_checked" for item in result["expectations"])+ assert all(item["reason"] for item in result["expectations"])++[email protected]("module", [llm_judge, eval_template])[email protected]("exception", [TimeoutError, RuntimeError])+def test_behavior_inventory_survives_unexpected_provider_exceptions(module, exception, monkeypatch):+ def raise_error(*_args, **_kwargs):+ raise exception("provider failed")++ monkeypatch.setattr(module, "call_public_llm", raise_error)+ result = module.judge_behavior_check("conversation", ["first", "second"])+ assert result["score"] is None and result["status"] == "error"+ assert result["results"] == []+ assert [item["requirement"] for item in result["expectations"]] == ["first", "second"]+ assert all(item["status"] == "not_checked" for item in result["expectations"])+ assert all(exception.__name__ in item["reason"] for item in result["expectations"])++[email protected]("keyword_arguments", [False, True])+def test_required_behavior_judge_wrapper_keeps_inventory_on_unexpected_exception(keyword_arguments):+ def raise_timeout(*_args, **_kwargs):+ raise TimeoutError("judge deadline")++ args = () if keyword_arguments else ("conversation", ["first", "second"])+ kwargs = {"conversation_text": "conversation", "expected_behaviors": ["first", "second"]} if keyword_arguments else {}+ result = eval_template._call_required_judge("behavior_check", raise_timeout, *args, **kwargs)+ assert result["score"] is None and result["status"] == "error"+ assert result["results"] == []+ assert [item["requirement"] for item in result["expectations"]] == ["first", "second"]+ assert all(item["status"] == "not_checked" for item in result["expectations"])+ assert all("TimeoutError" in item["reason"] for item in result["expectations"])++[email protected]("module", [llm_judge, eval_template])+def test_behavior_judge_can_abstain_without_calling_missing_evidence_a_violation(module, monkeypatch):+ response = json.dumps(+ {+ "results": [+ {"step": 1, "passed": True, "reason": "input read"},+ {"step": 2, "passed": None, "reason": "artifact contents not captured"},+ ]+ }+ )+ monkeypatch.setattr(module, "call_public_llm", _pair_script([(response, None)], []))+ result = module.judge_behavior_check("partial trace", ["read input", "verify contents"])+ assert result["score"] == 0.5+ assert [item["status"] for item in result["expectations"]] == ["met", "not_checked"]+ assert result["expectations"][1]["reason"] == "artifact contents not captured"++[email protected]("module", [llm_judge, eval_template])[email protected]("reason", [None, "", " ", []])+def test_behavior_abstention_requires_a_reason(module, reason):+ payload = {"results": [{"step": 1, "passed": None, "reason": reason}]}+ assert module._behavior_payload_error(payload, 1) is not None++@pytest.mark.parametrize("module", [llm_judge, eval_template])def test_accuracy_grades_the_outcome_not_skill_use(module, monkeypatch):# A correct no-skill or negative-case answer can reach 1.0: skill use is