Skip to content

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.

feat(tier3): case-first CLI summary and case-based report findings (#255)

Christopher Kevinff1ff7db7f8d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9b12c0b2..b84dcc93 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,11 +6,34 @@ All notable changes to SkillEvaluator are documented in this file.
### Added
-- Reusable GitHub Actions onboarding for complete Tier 1 checks, with
- pinned runtime/workflow consumer templates, affected-skill PR selection,
- optional hosted reports and updated PR feedback. The new guide separates
- basic scanning from publisher setup; public image publication and generated
- release files require a reviewed manual release before consumer use.
+- `tier3 evaluate` now leads with a case-first summary: a verdict line and one
+ row per `evals.json` case. With one agent, each row shows, for with and
+ without the skill, the pass count, per-attempt marks (`✓` pass, `✗` fail,
+ `⊘` did not run, `·` skipped after a pass) and mean score, plus an effect
+ column (`helps`, `hurts`, `both fail`, `better score`, `worse score`,
+ `no change`, `inconclusive`). With several agents, each agent gets a column
+ showing without-skill → with-skill marks and the pass-rate change. Success
+ rate, quality score, and dimensions follow. A "How to improve" list follows,
+ ranked by attempts lost and capped at three; each item names the case,
+ agent, issue type (`skill`, `skill not used`, `skill hurts`, `environment`,
+ `run error`, `eval case`, `missing input`, `goal not met`), one action, and an evidence
+ path, and is also written to `what_to_fix.json` in the run directory. When
+ nothing needs fixing it prints a one-line "nothing to fix" instead. The
+ verdict is `inconclusive` when attempts did not run. The per-evaluator and
+ per-dimension tables and metric findings moved behind the new `--verbose`
+ flag and remain in `report.html`.
+- `goal not met` flags with-skill attempts that pass on the aggregate score
+ while the judge scored goal accuracy 0.00 (for example, the agent only asked
+ for details).
+- `report.html` leads with the same case-based findings: "Verdict at a glance"
+ adds the per-case result, the highest-scoring agent versus the biggest skill
+ lift, and the goal-not-met count; "Conclusion & Next Steps" and the Insights
+ recommendations list the `what_to_fix.json` fixes (or "Nothing to fix").
+ Data fixes elsewhere: Pass@K shows attempts passed, a regressed passing
+ dimension reads "PASS · regressed" with its weakest signal, resource totals
+ are formatted with units and percent change, Attempt Details groups each
+ case's with/without rows and marks passes that missed the goal, and Error
+ Recovery lists only trials with faults, retries or warnings.
- `--quality-config PATH` on `validate`, `quality-check`, and `tier1` loads the
deterministic quality check's expected Markdown headings from a YAML file
instead of the built-in list. Each `expected_headers` entry sets a `heading`
diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdx
index b90ce2ff..3b558022 100644
--- a/docs/cli-reference.mdx
+++ b/docs/cli-reference.mdx
@@ -445,6 +445,7 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing
| `--grading-mode [default\|default_plus_custom\|custom_only]` | unset | Reward/grading mode — see [Custom Graders & Tasks](custom-graders.mdx). The legacy aliases `aces_default` (→ `default`) and `aces_plus_custom` (→ `default_plus_custom`) are still accepted. |
| `--results-dir DIRECTORY` | unset | Directory for live-eval results (precedence rules in [Reports & Results](reports.mdx)). |
| `--harbor-keep-jobs` | off | Retain Harbor job dirs and artifacts for inspection with [harbor-view](#harbor-view). |
+| `--verbose` | off | Also print the per-evaluator and per-dimension tables and the metric findings after the case summary. |
| `--agent-runtime-preflight / --no-agent-runtime-preflight` | disabled | Opt into an extra agent-only execution of the first staged task before the full A/B evaluation matrix. |
| `--timeout-multiplier FLOAT` | unset | Scale Harbor's agent, verifier, and environment-build timeouts (built-in default `1.0`). Must be a finite number greater than 0. |
| `--override-cpus INTEGER` | unset | Override eval-environment CPU allocation (passed through to Harbor). |
diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.py
index 38d8ec08..a7999dd5 100644
--- a/src/skillevaluator/cli.py
+++ b/src/skillevaluator/cli.py
@@ -2868,6 +2868,11 @@ def _tier2_workflow(
show_default=True,
help="Tier 3 progress presentation (auto uses Rich on a TTY and plain lines otherwise).",
)
+ "--verbose",
+ is_flag=True,
+ help="Also print per-evaluator and per-dimension tables and the metric findings report.",
+)
def evaluate(
skill_path: Path,
agents: str | None,
@@ -2898,6 +2903,7 @@ def evaluate(
evaluated_source_revision: str | None,
evaluator_container_revision: str | None,
progress: str,
+ verbose: bool,
) -> None:
"""Run Tier 3 live agent evaluation."""
from skillevaluator.evaluation import EvaluationOptions, EvaluationService
@@ -3002,7 +3008,7 @@ def evaluate(
if isinstance(display_result, dict):
from skillevaluator.tier3.result_display import render_evaluation_result
- render_evaluation_result(display_result, console=console)
+ render_evaluation_result(display_result, console=console, verbose=verbose, skill_path=skill_path)
if failure:
raise click.exceptions.Exit(1)
except (click.ClickException, click.exceptions.Exit):
diff --git a/src/skillevaluator/evaluation/dimension_judge.py b/src/skillevaluator/evaluation/dimension_judge.py
index 40824537..53c6fd7d 100644
--- a/src/skillevaluator/evaluation/dimension_judge.py
+++ b/src/skillevaluator/evaluation/dimension_judge.py
@@ -379,31 +379,29 @@ def _human_reasoning_bullets(
bullets = [bullet_score, bullet_lift]
- strongest = _strongest_signal(parts)
- if strongest:
- bullets.append(f"Strongest signal: {strongest}.")
+ regressed = lift is not None and baseline is not None and lift <= LIFT_EXPLANATION_FAIL_THRESHOLD
+ signal = _strongest_signal(parts, weakest=regressed)
+ if signal:
+ bullets.append(f"{'Weakest' if regressed else 'Strongest'} signal: {signal}.")
return bullets
-def _strongest_signal(parts: list[str]) -> str | None:
- """Return the highest-scoring ``name=value`` part for the strongest-signal bullet."""
- if not parts:
- return None
- best_part: str | None = None
- best_value = float("-inf")
+def _strongest_signal(parts: list[str], *, weakest: bool = False) -> str | None:
+ """Return the highest- (or lowest-) scoring ``name=value`` part for the signal bullet."""
+ scored: list[tuple[float, str]] = []
for entry in parts:
- if "=" not in entry:
+ name, sep, raw = entry.partition("=")
+ if not sep:
continue
- name, raw = entry.split("=", 1)
try:
- value = float(raw)
+ scored.append((float(raw), name))
except ValueError:
continue
- if value > best_value:
- best_value = value
- best_part = f"{name} {value:.2f}"
- return best_part
+ if not scored:
+ return None
+ value, name = (min if weakest else max)(scored, key=lambda item: item[0])
+ return f"{name} {value:.2f}"
def compute_dimensions(
diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.py
index 43b1c2ab..0665675d 100644
--- a/src/skillevaluator/evaluation/tier3_report.py
+++ b/src/skillevaluator/evaluation/tier3_report.py
@@ -19,6 +19,7 @@ from __future__ import annotations
import contextlib
import json
+import logging
import math
from dataclasses import dataclass, field
from itertools import islice
@@ -42,6 +43,8 @@ from skillevaluator.evidence import evidence_ref_identity
from skillevaluator.models.result import Finding, Severity, ValidationResult
from skillevaluator.source_identity import resolve_evaluated_source
+logger = logging.getLogger(__name__)
+
# Verdict labels mirror SkillEvaluator's AGENT_EVAL_VERDICT_* values so the ported
# reporters classify the overall outcome identically.
VERDICT_PASS = "pass"
@@ -598,6 +601,8 @@ def render_agent_eval_html_report(
raise ValueError(f"No agent results found in {run_dir}")
canonical_payload = result.metadata.get("agent_eval")
+ if isinstance(canonical_payload, dict):
+ _apply_case_findings(canonical_payload, engine_result, run_dir, skill_path, use_llm=use_llm_judge)
if engine_result is not None and isinstance(canonical_payload, dict):
# Persist only the compact feedback contract needed by the CLI. The
# complete canonical payload remains in the HTML report and can be much
@@ -3028,6 +3033,72 @@ def _recommendation_category_from(text: str) -> str:
return _RECO_CATEGORY_HINTS.get(first, "Action")
+def _apply_case_findings(
+ payload: dict[str, Any],
+ engine_result: dict[str, Any] | None,
+ run_dir: Path,
+ skill_path: Path,
+ *,
+ use_llm: bool,
+) -> None:
+ """Lead the report with the case-based verdict and fixes; also saves them as what_to_fix.json for the CLI."""
+ from skillevaluator.tier3.case_summary import verdict as case_verdict
+ from skillevaluator.tier3.case_summary import what_to_fix
+
+ source = engine_result
+ if not isinstance(source, dict):
+ with contextlib.suppress(OSError, ValueError):
+ source = json.loads((run_dir / "result.json").read_text(encoding="utf-8"))
+ if not isinstance(source, dict) or not isinstance(source.get("agents"), dict):
+ return
+ try:
+ fixes = what_to_fix(source, run_dir=run_dir, skill_path=skill_path, use_llm=use_llm)
+ (run_dir / "what_to_fix.json").write_text(json.dumps(fixes, indent=2), encoding="utf-8")
+ except Exception: # advisory: the report keeps its metric-based insights
+ logger.debug("Case findings skipped", exc_info=True)
+ return
+ label, detail = case_verdict(source["agents"])
+ if not label:
+ return
+ message = f"per-case result: {label} ({detail})."
+ agents = payload.get("agents") if isinstance(payload.get("agents"), dict) else {}
+ scores = {
+ n: v for n, a in agents.items() if isinstance(a, dict) and (v := _finite_float(a.get("with_skill"))) is not None
+ }
+ lifts = {n: v for n, a in agents.items() if isinstance(a, dict) and (v := _finite_float(a.get("lift"))) is not None}
+ if len(scores) > 1 and lifts:
+ top, lifted = max(scores, key=scores.__getitem__), max(lifts, key=lifts.__getitem__)
+ message += f" Highest score: {top} {scores[top]:.2f}"
+ message += (
+ f" · biggest skill lift: {lifted} {lifts[lifted]:+.2f}." if lifted != top else " with the biggest lift."
+ )
+ if missed := sum(f["attempts_lost"] for f in fixes if f["kind"] == "goal not met"):
+ message += f" {missed} passing with-skill attempt(s) did not meet the goal (goal accuracy 0.00)."
+ severity = "pass" if label == "skill helps" and not fixes else "fail" if label == "skill hurts" else "warn"
+ effect = {"severity": severity, "title": "Skill effect", "message": message, "source": "deterministic"}
+ payload["conclusions"] = [effect, *(payload.get("conclusions") or [])]
+ # Evidence stays plain text: report links are limited to validated Harbor viewer URLs.
+ payload["recommendations"] = [
+ {
+ "title": f"{fix['case']} · {fix['scope']}",
+ "category": fix["kind"],
+ "message": " ".join(
+ part
+ for part in (
+ f"{fix['what'].rstrip('.')}.",
+ f"Fix: {fix['action']}" if fix.get("action") else "",
+ f"Evidence: {fix['evidence']}" if fix.get("evidence") else "",
+ )
+ if part
+ ),
+ "severity": "fail" if fix["kind"] == "skill hurts" else "warn",
+ "source": "deterministic",
+ }
+ for fix in fixes
+ ]
+ payload["suggestions"] = [fix["action"] for fix in fixes if fix.get("action")]
+
+
def _recommendation_title_from(text: str) -> str:
"""Short title for a deterministic recommendation (first sentence, truncated)."""
if not isinstance(text, str):
@@ -3050,14 +3121,18 @@ def _build_conclusions(
best = agents[best_name]
best_score = _finite_float(best.get("with_skill")) or 0.0
lift = _finite_float(best.get("lift"))
+ message = f"{best_name} leads with overall score {best_score:.2f}" + (
+ f" and lift {lift:+.2f}." if lift is not None else "."
+ )
+ lifts = {name: value for name, a in agents.items() if (value := _finite_float(a.get("lift"))) is not None}
+ top_lift = max(lifts, key=lifts.__getitem__) if lifts else None
+ if top_lift and top_lift != best_name and lift is not None and lifts[top_lift] > lift:
+ message += f" Biggest skill lift: {top_lift} {lifts[top_lift]:+.2f}."
conclusions.append(
{
"severity": "pass" if best_score >= pass_threshold else "warn",
"title": "Best performing agent",
- "message": (
- f"{best_name} leads with overall score {best_score:.2f}"
- + (f" and lift {lift:+.2f}." if lift is not None else ".")
- ),
+ "message": message,
}
)
diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2
index 9ab3f5de..35181ba9 100644
--- a/src/skillevaluator/reporting/templates/report.html.j2
+++ b/src/skillevaluator/reporting/templates/report.html.j2
@@ -2384,6 +2384,7 @@
{# ---------- Overview ---------- #}
<section class="t3-page active" id="tier3-page-overview">
+ {% set t3_effect = (tier3.conclusions or []) | selectattr('title', 'equalto', 'Skill effect') | first %}
<div class="t3-overview-lead">
{% if tier3_is_skipped %}
<strong>Live evaluation skipped:</strong> {{ tier3_skip_message }}
@@ -2393,11 +2394,12 @@
Scores are diagnostic only; no lift verdict was computed. Check skill loading and agent support, then rerun the evaluation.
{% else %}
<strong>Verdict at a glance:</strong>
- {{ tier3_verdict | upper }} with an overall score of
+ {{ tier3_verdict | upper }}{% if t3_effect %} · {{ t3_effect.message }}{% else %} with an overall score of
{{ "%.2f" | format(tier3.overall_score) if tier3.overall_score is not none else "N/A" }}.
{% if t3_best_name %}Best performing agent is <strong>{{ t3_best_name }}</strong>{% else %}No successfully scored agent is available{% endif %}
{% if tier3.get('overall_lift') is not none %} with {{ "%+.2f" | format(tier3.get('overall_lift')) }} skill lift{% endif %}.
{% endif %}
+ {% endif %}
</div>
{% if t3_harbor_job_url or t3_harbor_analysis_url %}
<div class="t3-harbor-panel">
@@ -2442,6 +2444,24 @@
<h3>Conclusion &amp; Next Steps</h3>
<button class="t3-link-btn" type="button" onclick="showTier3SubTab('suggestions', document.querySelector('.t3-subtab[data-tier3-tab=&quot;suggestions&quot;]'))">Open Full Insights</button>
</div>
+ {% if t3_effect %}
+ {% set t3_fix_count = t3_preview_recommendations | length %}
+ <p class="t3-next-steps-conclusion">
+ {% if t3_fix_count %}{{ t3_fix_count }} issue{{ 's' if t3_fix_count != 1 else '' }} to fix, most attempts lost first:{% else %}Nothing to fix: every with-skill attempt passed and met its goal, and the skill didn't hurt any case.{% endif %}
+ </p>
+ {% if t3_fix_count %}
+ <ol class="t3-next-steps-list">
+ {% for reco in t3_preview_recommendations[:3] %}
+ <li>
+ <strong>{{ reco.title }}</strong> [{{ reco.category }}]: {{ reco.message }}
+ {% if reco.evidence and reco.evidence.url %}
+ <a class="t3-evidence-link" href="{{ reco.evidence.url }}" target="_blank" rel="noopener">View {{ reco.evidence.label or 'evidence' }}</a>
+ {% endif %}
+ </li>
+ {% endfor %}
+ </ol>
+ {% endif %}
+ {% else %}
{% if t3_preview_conclusion %}
<p class="t3-next-steps-conclusion">
{{ t3_preview_conclusion.message if t3_preview_conclusion.message is defined and t3_preview_conclusion.message else t3_preview_conclusion }}
@@ -2467,6 +2487,7 @@
{% else %}
<p class="t3-next-steps-conclusion">No recommendations were generated for this evaluation.</p>
{% endif %}
+ {% endif %}
</div>
{% if tier3.dimensions %}
@@ -2502,7 +2523,8 @@
<td style="color:{{ 'var(--success-color)' if dim.lift is not none and dim.lift >= tier3_lift_pass_threshold else ('var(--danger-color)' if dim.lift is not none and dim.lift <= tier3_lift_fail_threshold else 'var(--text-secondary)') }};font-weight:600;">
{{ "%+.2f" | format(dim.lift) if dim.lift is not none else "N/A" }}
</td>
- <td><span class="t3-pill {{ 'ok' if dim.verdict == 'PASS' else ('critical' if dim.verdict == 'FAIL' else 'warning') }}">{{ dim.verdict }}</span></td>
+ {% set dim_regressed = dim.verdict == 'PASS' and dim.lift is not none and dim.lift <= tier3_lift_fail_threshold %}
+ <td><span class="t3-pill {{ 'warning' if dim_regressed else ('ok' if dim.verdict == 'PASS' else ('critical' if dim.verdict == 'FAIL' else 'warning')) }}">{{ dim.verdict }}{{ ' · regressed' if dim_regressed else '' }}</span></td>
<td>
{% for metric_id in dim.evaluators or [] %}
<span class="metadata-tag">{{ t3_metric_labels.get(metric_id, metric_id | replace("_", " ") | title) }}</span>
@@ -2681,9 +2703,10 @@
Higher rates and a positive lift show better observed repeatability on these evaluated cases.
</p>
<div class="table-scroll" tabindex="0" role="region" aria-label="Pass at K summary table">
+ {% macro t3_attempts_passed(branch) %}{% if branch.case_details_truncated %}{{ branch.attempts_used or 0 }} of {{ branch.max_attempts_possible or 0 }} scored{% else %}{% set ns = namespace(n=0) %}{% for case in (branch.cases or {}).values() %}{% for att in case.attempts or [] %}{% if att.passed %}{% set ns.n = ns.n + 1 %}{% endif %}{% endfor %}{% endfor %}{{ ns.n }} of {{ branch.attempts_used or 0 }}{% endif %}{% endmacro %}
<table class="summary-table pass-at-k-table" style="width:100%;">
<thead><tr>
- <th>Agent</th><th>Condition</th><th>Pass Rate</th><th>95% Interval</th><th>Cases Passed</th><th>Scored Attempts</th><th>Lift</th>
+ <th>Agent</th><th>Condition</th><th>Pass Rate</th><th>95% Interval</th><th>Cases Passed</th><th>Attempts Passed</th><th>Lift</th>
</tr></thead>
<tbody>
{% for name, agent in t3_agents.items() %}
@@ -2701,7 +2724,7 @@
<td>{{ "%.0f%%" | format((wp.rate or 0.0) * 100) }}</td>
<td>{% if wi %}{{ wi | adaptive_interval_percent }}{% else %}—{% endif %}</td>
<td>{{ wp.passed_cases or 0 }} of {{ wp.total_cases or 0 }}</td>
- <td>{{ wp.attempts_used or 0 }} of {{ wp.max_attempts_possible or 0 }}</td>
+ <td>{{ t3_attempts_passed(wp) }}</td>
<td style="color:{{ 'var(--success-color)' if (lf.delta or 0) >= tier3_lift_pass_threshold else ('var(--danger-color)' if (lf.delta or 0) <= tier3_lift_fail_threshold else 'var(--text-secondary)') }};font-weight:600;">
{% if lf.delta is defined %}{{ "%+.0f%%" | format((lf.delta or 0.0) * 100) }}{% else %}—{% endif %}
</td>
@@ -2714,7 +2737,7 @@
<td>{{ "%.0f%%" | format((bp.rate or 0.0) * 100) }}</td>
<td>{% if bi %}{{ bi | adaptive_interval_percent }}{% else %}—{% endif %}</td>
<td>{{ bp.passed_cases or 0 }} of {{ bp.total_cases or 0 }}</td>
- <td>{{ bp.attempts_used or 0 }} of {{ bp.max_attempts_possible or 0 }}</td>
+ <td>{{ t3_attempts_passed(bp) }}</td>
<td>baseline</td>
</tr>
{% endif %}
@@ -2771,9 +2794,10 @@
{% for field, label in [('tokens', 'Prompt + completion tokens (cache included)'), ('agent_seconds', 'Agent execution seconds')] %}
{% set measured = agent.resources[field] %}
<tr><td>{{ name }}</td><td>{{ label }}</td>
- <td>{{ '%.2f' | format(measured.with_skill.total) if measured.with_skill.total is not none else 'N/A' }}</td>
- <td>{{ '%.2f' | format(measured.baseline.total) if measured.baseline.total is not none else 'N/A' }}</td>
- <td>{{ '%+.2f' | format(measured.delta) if measured.delta is not none else 'N/A' }}</td>
+ {% set unit_fmt = '{:,.1f} s' if field == 'agent_seconds' else '{:,.0f}' %}
+ <td>{{ unit_fmt.format(measured.with_skill.total) if measured.with_skill.total is not none else 'N/A' }}</td>
+ <td>{{ unit_fmt.format(measured.baseline.total) if measured.baseline.total is not none else 'N/A' }}</td>
+ <td>{% if measured.delta is not none %}{{ ('+' if measured.delta >= 0 else '') ~ unit_fmt.format(measured.delta) }}{% if measured.baseline.total %} ({{ '%+.0f' | format(measured.delta / measured.baseline.total * 100) }}%){% endif %}{% else %}N/A{% endif %}</td>
<td>{{ measured.with_skill.measured_trials }}/{{ measured.with_skill.trials }} / {{ measured.baseline.measured_trials }}/{{ measured.baseline.trials }}</td>
</tr>
{% endfor %}
@@ -2815,16 +2839,20 @@
{% if t3_agents %}
{% for agent_name, agent in t3_agents.items() %}
{% set pak = agent.pass_at_k or {} %}
- {% for cond_label, branch in [('With skill', pak.with_skill), ('Without skill', pak.without_skill)] %}
- {% if branch is mapping and branch.get('cases') %}
- {% for case_id, case_data in branch.cases.items() %}
- {% set _ = t3_attempt_rows.append({'agent': agent_name, 'condition': cond_label, 'case_id': case_id, 'case': case_data}) %}
- {% endfor %}
- {% endif %}
+ {% set t3_branches = [('With skill', pak.with_skill), ('Without skill', pak.without_skill)] | selectattr('1', 'mapping') | selectattr('1.cases') | list %}
+ {% set t3_case_ids = [] %}
+ {% for cond_label, branch in t3_branches %}{% for case_id in branch.cases %}{% if case_id not in t3_case_ids %}{% set _ = t3_case_ids.append(case_id) %}{% endif %}{% endfor %}{% endfor %}
+ {# Agent -> case -> condition, so each case's with/without rows sit together. #}
+ {% for case_id in t3_case_ids | sort %}
+ {% for cond_label, branch in t3_branches if case_id in branch.cases %}
+ {% set _ = t3_attempt_rows.append({'agent': agent_name, 'condition': cond_label, 'case_id': case_id, 'case': branch.cases[case_id]}) %}
+ {% endfor %}
{% endfor %}
{% endfor %}
{% endif %}
+ {% set t3_goal_by_trial = {} %}
+ {% for trial in tier3.trials or [] %}{% if trial.scores and trial.scores.goal_accuracy is defined %}{% set _ = t3_goal_by_trial.update({trial.trial_id: trial.scores.goal_accuracy}) %}{% endif %}{% endfor %}
{% if t3_attempt_rows %}
<details class="t3-details" id="tier3-attempt-details" open>
<summary>Attempt Details</summary>
@@ -2896,7 +2924,11 @@
{% endif %}
</td>
<td>
- {% if passed and first_pass_attempt is not none %}
+ {% set goal = namespace(missed=0) %}
+ {% if row.condition == 'With skill' %}{% for att in attempts %}{% if att.get('passed') and t3_goal_by_trial.get(att.get('trial')) == 0 %}{% set goal.missed = goal.missed + 1 %}{% endif %}{% endfor %}{% endif %}
+ {% if passed and goal.missed %}
+ <span class="t3-pill warning" title="{{ goal.missed }} passing attempt(s) scored goal accuracy 0.00">passed{% if first_pass_attempt is not none %} on scored attempt {{ first_pass_attempt | int }}{% endif %} · goal not met (0.00)</span>
+ {% elif passed and first_pass_attempt is not none %}
<span class="t3-pill ok">passed on scored attempt {{ first_pass_attempt | int }}</span>
{% elif passed %}
<span class="t3-pill ok">passed</span>
@@ -3025,7 +3057,12 @@
<table class="summary-table">
<thead><tr><th>Agent</th><th>Case</th><th>First Attempt</th><th>Faults</th><th>Details</th></tr></thead>
<tbody>
- {% for trial in t3_recovery_trials %}
+ {% set t3_fault_trials = [] %}
+ {% for trial in t3_recovery_trials %}{% set recovery = trial.error_recovery or {} %}{% if recovery.skill_faults or recovery.agent_faults or recovery.first_attempt == 'retries needed' or recovery.details or trial.warnings %}{% set _ = t3_fault_trials.append(trial) %}{% endif %}{% endfor %}
+ {% if not t3_fault_trials %}
+ <tr><td colspan="5" style="color:var(--text-secondary);">No faults, retries or warnings recorded in {{ t3_recovery_trials | length }} trial{{ 's' if t3_recovery_trials | length != 1 else '' }}.</td></tr>
+ {% endif %}
+ {% for trial in t3_fault_trials %}
{% set recovery = trial.error_recovery or {} %}
<tr>
<td><strong>{{ trial.agent or '(default)' }}</strong></td>
diff --git a/src/skillevaluator/tier3/case_summary.py b/src/skillevaluator/tier3/case_summary.py
new file mode 100644
index 00000000..8b0a0ea2
--- /dev/null
+++ b/src/skillevaluator/tier3/case_summary.py
@@ -0,0 +1,878 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Case-first Tier 3 summary: per-case attempt grid, verdict, and a short "How to improve" list."""
+
+from __future__ import annotations
+
+import json
+import logging
+import re
+from collections import Counter
+from collections.abc import Mapping
+from difflib import SequenceMatcher
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+from rich.box import SIMPLE
+from rich.table import Table
+from rich.text import Text
+
+if TYPE_CHECKING:
+ from rich.console import Console
+
+logger = logging.getLogger(__name__)
+
+PASS, FAIL, ERROR, SKIPPED = "✓", "✗", "⊘", "·"
+_VARIANTS = (("with_skill", "with-skill"), ("without_skill", "without-skill"))
+_CLEAR_EFFECT_PP = 10
+_CLEAR_SCORE_DELTA = 0.1
+_MAX_FIXES = 3
+_ROOT_ERROR = re.compile(r"(?m)^\s*(?:error|Error|\w+Error):\s*(.+)$")
+_MAX_REASON_CHARS = 220
+_MAX_SKILL_MD_CHARS = 6000
+_MAX_TRIAL_JSON_BYTES = 8 * 1024 * 1024
+_MAX_LOG_TAIL_BYTES = 64 * 1024
+_STDOUT = re.compile(r"\bstdout:\s*(.+?)\s*(?:\bstderr:|$)", re.DOTALL)
+_RESTATED_CHARS = 60
+_ASKS_FOR_INPUT = re.compile(
+ r"(?i)(workspace (?:is|appears to be|looks|seems)[^.\n]{0,20}empty|"
+ r"(?:there's|there is) no [^.\n]{0,60}(?:here|in (?:the|your|it|this))|doesn't (?:have|contain) any|"
+ r"(?:could|can) you (?:share|provide|upload)|please (?:share|provide|upload)|"
+ r"what's the file path|I(?:'ll| will)? need (?:a few (?:quick )?(?:things|details)|a bit more|more (?:context|information))|"
+ r"send me (?:these|the following|a few|the details))"
+)
+_STOPPED_FOR_INPUT = re.compile(
+ r"(?i)\b(?:asked|requested) (?:the user|for|additional|more|further|clarification)|\bclarifying questions?\b|"
+ r"\b(?:does|did) not exist in the workspace|\bnot found in the workspace|\bno [^.]{0,40} in the workspace"
+)
+_SAFE_TRIAL = re.compile(r"^[A-Za-z0-9._-]+$")
+_ENV_ERROR = re.compile(
+ r"(ModuleNotFoundError: No module named '?[\w.]+'?|No module named '?[\w.]+'?|"
+ r"[\w./-]+: command not found|command not found: [\w.-]+|"
+ r"(?:is not installed|not installed in)[^\n\"]{0,60}|"
+ r"No such file or directory: '[^']+'|Could not find a version that satisfies[^\n\"]{0,80})"
+)
+_JUDGED_METRICS = ("goal_accuracy", "accuracy", "behavior_check")
+
+
+# ---------------------------------------------------------------- per-case data
+
+
+def _cases(agent: Mapping[str, Any], key: str) -> Mapping[str, Any]:
+ pass_at_k = agent.get("pass_at_k")
+ variant = pass_at_k.get(key) if isinstance(pass_at_k, Mapping) else None
+ cases = variant.get("cases") if isinstance(variant, Mapping) else None
+ if isinstance(cases, Mapping) and cases:
+ return cases
+ # A failed condition persists no pass@k cases; rebuild them from its trial rewards and errors.
+ failures = agent.get("trial_failures")
+ failed = failures.get(key) if isinstance(failures, Mapping) else None
+ errored = Counter(
+ str(f["trial"]).split("__", 1)[0] for f in failed or [] if isinstance(f, Mapping) and f.get("trial")
+ )
+ rebuilt = _scored_trials(agent, key)
+ for case_id, n in errored.items():
+ rebuilt.setdefault(case_id, {"attempts": []})["attempts_missing"] = n
+ return rebuilt
+
+
+def _scored_trials(agent: Mapping[str, Any], key: str) -> dict[str, dict[str, Any]]:
+ output_dir = agent.get("output_dir")
+ trials = Path(str(output_dir)) / dict(_VARIANTS)[key] / "trials" if output_dir else None
+ if trials is None or not trials.is_dir():
+ return {}
+ pass_at_k = agent.get("pass_at_k") if isinstance(agent.get("pass_at_k"), Mapping) else {}
+ threshold = next(
+ (
+ float(v["pass_threshold"])
+ for v in pass_at_k.values()
+ if isinstance(v, Mapping) and isinstance(v.get("pass_threshold"), int | float)
+ ),
+ 0.5,
+ )
+ cases: dict[str, dict[str, Any]] = {}
+ for trial in sorted(trials.iterdir()):
+ reward = _load_json(trial / "reward.json")
+ score = reward.get("overall") if isinstance(reward, Mapping) else None
+ if isinstance(score, int | float) and not isinstance(score, bool):
+ attempts = cases.setdefault(trial.name.split("__", 1)[0], {"attempts": []})["attempts"]
+ attempts.append(
+ {"attempt": len(attempts) + 1, "trial": trial.name, "score": score, "passed": score >= threshold}
+ )
+ return cases
+
+
+def _marks(case: Mapping[str, Any] | None) -> list[str]:
+ if not isinstance(case, Mapping):
+ return []
+ attempts = case.get("attempts") if isinstance(case.get("attempts"), list) else []
+ marks = [PASS if a.get("passed") is True else FAIL for a in attempts if isinstance(a, Mapping)]
+ marks += [ERROR] * int(case.get("attempts_missing") or 0)
+ marks += [SKIPPED] * int(case.get("attempts_skipped") or 0)
+ return marks
+
+
+def _attempt_rate(marks: list[str]) -> tuple[int, int]:
+ scored = [m for m in marks if m in (PASS, FAIL)]
+ return scored.count(PASS), len(scored)
+
+
+def _case_ids(agents: Mapping[str, Any]) -> list[str]:
+ ids: dict[str, None] = {}
+ for agent in agents.values():
+ if isinstance(agent, Mapping):
+ for key, _ in _VARIANTS:
+ ids.update(dict.fromkeys(str(case_id) for case_id in _cases(agent, key)))
+ return sorted(ids)
+
+
+def _agent_rates(agent: Mapping[str, Any]) -> dict[str, tuple[int, int]]:
+ rates = {}
+ for key, _ in _VARIANTS:
+ passed = total = 0
+ for case in _cases(agent, key).values():
+ p, n = _attempt_rate(_marks(case))
+ passed, total = passed + p, total + n
+ rates[key] = (passed, total)
+ return rates
+
+
+def _pct(passed: int, total: int) -> float | None:
+ return 100.0 * passed / total if total else None
+
+
+def verdict(agents: Mapping[str, Any]) -> tuple[str, str]:
+ """Return (label, per-agent detail) using the raw per-attempt success rate."""
+ deltas: dict[str, float] = {}
+ not_run: dict[str, int] = {}
+ for name, agent in agents.items():
+ if not isinstance(agent, Mapping):
+ continue
+ missing = sum(_marks(case).count(ERROR) for key, _ in _VARIANTS for case in _cases(agent, key).values())
+ if missing:
+ # Rates over different subsets of attempts are not comparable.
+ not_run[str(name)] = missing
+ continue
+ rates = _agent_rates(agent)
+ with_pct, without_pct = _pct(*rates["with_skill"]), _pct(*rates["without_skill"])
+ if with_pct is not None and without_pct is not None:
+ deltas[str(name)] = with_pct - without_pct
+ detail = " · ".join(
+ [f"{name} {delta:+.0f} pp" for name, delta in deltas.items()]
+ + [f"{name}: {n} attempt(s) did not run" for name, n in not_run.items()]
+ )
+ if not deltas:
+ return ("inconclusive", detail) if not_run else ("", "")
+ if all(delta >= _CLEAR_EFFECT_PP for delta in deltas.values()):
+ label = "skill helps"
+ elif all(delta <= -_CLEAR_EFFECT_PP for delta in deltas.values()):
+ label = "skill hurts"
+ elif any(delta <= -_CLEAR_EFFECT_PP for delta in deltas.values()):
+ label = "mixed: skill hurts on some agents"
+ elif any(delta >= _CLEAR_EFFECT_PP for delta in deltas.values()):
+ label = "mixed: skill helps on some agents"
+ else:
+ label = "no clear effect"
+ return label, detail
+
+
+# ---------------------------------------------------------------- rendering
+
+
+def _marks_text(marks: list[str]) -> Text:
+ text = Text()
+ style = {PASS: "green", FAIL: "red", ERROR: "yellow", SKIPPED: "dim"}
+ for mark in marks:
+ text.append(mark, style=style[mark])
+ return text if marks else Text("-", style="dim")
+
+
+def _mean_score(case: Mapping[str, Any] | None) -> float | None:
+ attempts = case.get("attempts") if isinstance(case, Mapping) and isinstance(case.get("attempts"), list) else []
+ scores = [s for a in attempts if isinstance(a, Mapping) and (s := _score(a.get("score"))) is not None]
+ return sum(scores) / len(scores) if scores else None
+
+
+def _condition_cell(case: Mapping[str, Any] | None) -> Text:
+ marks = _marks(case)
+ p, n = _attempt_rate(marks)
+ cell = Text(f"{p}/{n} " if n else "", style="bold")
+ cell.append_text(_marks_text(marks))
+ if (mean := _mean_score(case)) is not None:
+ cell.append(f" ({mean:.2f})", style="dim")
+ return cell
+
+
+def _effect(with_case: Mapping[str, Any] | None, without_case: Mapping[str, Any] | None) -> Text:
+ """One word per case on what the skill changed: pass rate first, then mean score."""
+ with_marks, without_marks = _marks(with_case), _marks(without_case)
+ (wp, wn), (op, on) = _attempt_rate(with_marks), _attempt_rate(without_marks)
+ if not wn or not on or ERROR in with_marks + without_marks:
+ return Text("inconclusive", style="yellow")
+ if wp * on != op * wn:
+ return Text("helps", style="green") if wp * on > op * wn else Text("hurts", style="bold red")
+ if not wp:
+ return Text("both fail", style="red")
+ delta = (_mean_score(with_case) or 0.0) - (_mean_score(without_case) or 0.0)
+ if delta >= _CLEAR_SCORE_DELTA:
+ return Text(f"better score ({delta:+.2f})", style="green")
+ if delta <= -_CLEAR_SCORE_DELTA:
+ return Text(f"worse score ({delta:+.2f})", style="yellow")
+ return Text("no change", style="dim")
+
+
+def _summary_cells(
+ with_value: float | None, without_value: float | None, fmt: str, delta_fmt: str, weak: float | None = None
+) -> list[Text]:
+ def one(value: float | None) -> Text:
+ if value is None:
+ return Text("-", style="dim")
+ return Text(fmt.format(value), style="yellow" if weak is not None and value < weak else "")
+
+ delta = (
+ Text(delta_fmt.format(with_value - without_value), style="dim")
+ if with_value is not None and without_value is not None
+ else Text("")
+ )
+ return [one(with_value), one(without_value), delta]
+
+
+def _score(value: object) -> float | None:
+ return float(value) if isinstance(value, int | float) and not isinstance(value, bool) else None
+
+
+def _dimension_score(agent: Mapping[str, Any], key: str, name: str) -> float | None:
+ dims = agent.get(f"dimensions_{key}")
+ entry = dims.get(name) if isinstance(dims, Mapping) else None
+ return _score(entry.get("score") if isinstance(entry, Mapping) else entry)
+
+
+def _quality(agent: Mapping[str, Any], key: str) -> float | None:
+ overall = agent.get("lift", {}).get("overall") if isinstance(agent.get("lift"), Mapping) else None
+ if isinstance(overall, Mapping) and _score(overall.get(key)) is not None:
+ return _score(overall.get(key))
+ return _score(agent.get(f"overall_{key}"))
+
+
+def _table(*headers: str | Text) -> Table:
+ table = Table(box=SIMPLE, show_edge=False, pad_edge=False)
+ table.add_column(headers[0], overflow="fold")
+ for header in headers[1:-1]:
+ table.add_column(header, no_wrap=True)
+ table.add_column(headers[-1])
+ return table
+
+
+def _condition_grid(agents: Mapping[str, Any], case_ids: list[str], dims: list[str], title: str) -> Table:
+ """One agent: a row per case with both conditions side by side and the effect."""
+ [agent] = agents.values()
+ table = _table(title, "with skill", "without skill", "effect")
+ for case_id in case_ids:
+ with_case, without_case = _cases(agent, "with_skill").get(case_id), _cases(agent, "without_skill").get(case_id)
+ table.add_row(
+ case_id, _condition_cell(with_case), _condition_cell(without_case), _effect(with_case, without_case)
+ )
+ table.add_section()
+ rates = _agent_rates(agent)
+ table.add_row(
+ Text("success rate", style="bold"),
+ *_summary_cells(_pct(*rates["with_skill"]), _pct(*rates["without_skill"]), "{:.0f}%", "{:+.0f} pp"),
+ )
+ table.add_row(
+ Text("quality score (0-1)", style="bold"),
+ *_summary_cells(_quality(agent, "with_skill"), _quality(agent, "without_skill"), "{:.2f}", "{:+.2f}"),
+ )
+ if dims:
+ table.add_section()
+ for dim in dims:
+ table.add_row(
+ Text(f" {dim}", style="dim"),
+ *_summary_cells(
+ _dimension_score(agent, "with_skill", dim),
+ _dimension_score(agent, "without_skill", dim),
+ "{:.2f}",
+ "{:+.2f}",
+ weak=0.6,
+ ),
+ )
+ return table
+
+
+def _change(text: str, value: float | None) -> Text:
+ if value is None:
+ return Text("")
+ return Text(f" {text}", style="green" if value > 0 else "red" if value < 0 else "dim")
+
+
+def _agent_cell(with_case: Mapping[str, Any] | None, without_case: Mapping[str, Any] | None) -> Text:
+ with_marks, without_marks = _marks(with_case), _marks(without_case)
+ cell = _marks_text(without_marks)
+ cell.append(" → ", style="dim")
+ cell.append_text(_marks_text(with_marks))
+ (wp, wn), (op, on) = _attempt_rate(with_marks), _attempt_rate(without_marks)
+ if not wn or not on or ERROR in with_marks + without_marks:
+ return cell.append(" ?", style="yellow")
+ delta = 100.0 * (wp / wn - op / on)
+ return cell.append_text(_change(f"{delta:+.0f}" if delta else "·", delta))
+
+
+def _arrow_cell(with_value: float | None, without_value: float | None, fmt: str, delta_fmt: str) -> Text:
+ cell = Text(" → ".join(fmt.format(v) if v is not None else "-" for v in (without_value, with_value)))
+ if with_value is None or without_value is None:
+ return cell
+ return cell.append_text(_change(delta_fmt.format(with_value - without_value), with_value - without_value))
+
+
+def _agent_grid(agents: Mapping[str, Any], case_ids: list[str], dims: list[str], title: str) -> Table:
+ """Several agents: a row per case, a column per agent, each cell without skill → with skill."""
+ table = _table(title, *(Text.assemble(f"{name}\n", ("(without → with skill)", "dim")) for name in agents))
+ for case_id in case_ids:
+ table.add_row(
+ case_id,
+ *(
+ _agent_cell(_cases(a, "with_skill").get(case_id), _cases(a, "without_skill").get(case_id))
+ for a in agents.values()
+ ),
+ )
+ table.add_section()
+ rates = []
+ for a in agents.values():
+ r = _agent_rates(a)
+ cell = _arrow_cell(_pct(*r["with_skill"]), _pct(*r["without_skill"]), "{:.0f}%", "{:+.0f} pp")
+ complete = all(ERROR not in _marks(c) for key, _ in _VARIANTS for c in _cases(a, key).values())
+ rates.append(cell if complete else Text(cell.plain.split(" ")[0]).append(" ?", style="yellow"))
+ table.add_row(Text("success rate", style="bold"), *rates)
+ table.add_row(
+ Text("quality score (0-1)", style="bold"),
+ *(
+ _arrow_cell(_quality(a, "with_skill"), _quality(a, "without_skill"), "{:.2f}", "{:+.2f}")
+ for a in agents.values()
+ ),
+ )
+ if dims:
+ table.add_section()
+ table.add_row(Text("dimensions", style="dim"))
+ for dim in dims:
+ table.add_row(
+ Text(f" {dim}", style="dim"),
+ *(
+ _arrow_cell(
+ _dimension_score(a, "with_skill", dim),
+ _dimension_score(a, "without_skill", dim),
+ "{:.2f}",
+ "{:+.2f}",
+ )
+ for a in agents.values()
+ ),
+ )
+ return table
+
+
+def render_case_summary(result: Mapping[str, Any], *, console: Console, fixes: list[dict[str, Any]] | None) -> bool:
+ """Print the case grid and fixes; False when the result has no per-case rows to show."""
+ agents = {k: v for k, v in (result.get("agents") or {}).items() if isinstance(v, Mapping)}
+ case_ids = _case_ids(agents)
+ if not case_ids:
+ return False
+ label, detail = verdict(agents)
+ if label:
+ style = "bold green" if label == "skill helps" else "bold red" if label == "skill hurts" else "bold yellow"
+ line = Text(f"{'✔' if label == 'skill helps' else '✖' if label == 'skill hurts' else '•'} {label}", style=style)
+ line.append(f" {detail}", style="dim")
+ console.print(line)
+
+ k = next(
+ (
+ v["k"]
+ for a in agents.values()
+ if isinstance(p := a.get("pass_at_k"), Mapping)
+ for v in p.values()
+ if isinstance(v, Mapping) and v.get("k")
+ ),
+ None,
+ )
+ names = sorted(
+ {
+ d
+ for a in agents.values()
+ for d in (a.get("dimensions_with_skill") or {})
+ if isinstance(a.get("dimensions_with_skill"), Mapping)
+ },
+ key=lambda d: (
+ min((s for a in agents.values() if (s := _dimension_score(a, "with_skill", d)) is not None), default=1.0),
+ d,
+ ),
+ )
+ grid = _agent_grid if len(agents) > 1 else _condition_grid
+ table = grid(agents, case_ids, names, f"test case (k={k})" if k else "test case")
+ console.print(table)
+ legend = f"{PASS} pass {FAIL} fail {ERROR} did not run {SKIPPED} skipped after a pass"
+ if len(agents) > 1:
+ legend += " ? incomplete\n+50 = change in pass rate, in percentage points"
+ else:
+ legend += " (0.82) mean score 0-1"
+ console.print(Text(legend, style="dim"))
+ if fixes:
+ console.print()
+ heading = Text("How to improve", style="bold")
+ heading.append(" (consider these fixes)", style="dim")
+ console.print(heading)
+ for i, fix in enumerate(fixes, 1):
+ head = Text(f" {i}. ", style="bold")
+ head.append(safe(fix["case"]), style="bold cyan")
+ n = fix["attempts_lost"]
+ lost = (
+ (f" · {n} attempt(s) missed the goal" if fix["kind"] == "goal not met" else f" · lost {n} attempt(s)")
+ if n
+ else ""
+ )
+ head.append(f" [{safe(fix['kind'])}] · {safe(fix['scope'])}{lost}", style="dim")
+ console.print(head)
+ console.print(Text(f" what happened: {fix['what']}"))
+ if fix.get("action"):
+ console.print(Text(f" fix: {fix['action']}", style="green"))
+ if fix.get("evidence"):
+ console.print(Text(f" evidence: {fix['evidence']}", style="dim"))
+ elif fixes is not None:
+ console.print()
+ line = Text("How to improve: ", style="bold")
+ line.append(
+ "nothing to fix. Every with-skill attempt passed and met its goal, and the skill didn't hurt any case.",
+ style="green",
+ )
+ console.print(line)
+ console.print()
+ return True
+
+
+def _load_json(path: Path) -> Any:
+ try:
+ if not path.is_file() or path.stat().st_size > _MAX_TRIAL_JSON_BYTES:
+ return None
+ return json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+
+
+def _trial_dir(run_dir: Path, agent: str, variant_dir: str, trial: object) -> Path | None:
+ if not isinstance(trial, str) or not _SAFE_TRIAL.match(trial) or not _SAFE_TRIAL.match(agent):
+ return None
+ path = run_dir / agent / variant_dir / "trials" / trial
+ return path if path.is_dir() else None
+
+
+def _short(text: object, limit: int = _MAX_REASON_CHARS) -> str:
+ value = " ".join(str(text or "").split())
+ return value if len(value) <= limit else value[: limit - 1].rstrip() + "…"
+
+
+def _activated(reward: Mapping[str, Any]) -> bool | None:
+ details = reward.get("details")
+ execution = details.get("skill_execution") if isinstance(details, Mapping) else None
+ activation = execution.get("activation") if isinstance(execution, Mapping) else None
+ passed = activation.get("passed") if isinstance(activation, Mapping) else None
+ return passed if isinstance(passed, bool) else None
+
+
+def _failed_reasons(reward: Mapping[str, Any]) -> list[str]:
+ details = reward.get("details") if isinstance(reward.get("details"), Mapping) else {}
+ reasons: list[str] = []
+ behavior = details.get("behavior_check")
+ for step in behavior.get("results", []) if isinstance(behavior, Mapping) else []:
+ if isinstance(step, Mapping) and step.get("passed") is False and step.get("reason"):
+ reasons.append(_short(step["reason"]))
+ scored = [
+ (score, metric)
+ for metric in _JUDGED_METRICS
+ if (score := _score(reward.get(metric))) is not None and isinstance(details.get(metric), Mapping)
+ ]
+ for score, metric in sorted(scored):
+ if score < 0.8 and details[metric].get("reason"):
+ reasons.append(_short(details[metric]["reason"]))
+ return reasons
+
+
+def _env_errors(trial_dir: Path) -> list[str]:
+ trajectory = _load_json(trial_dir / "trajectory.json")
+ steps = trajectory.get("steps") if isinstance(trajectory, Mapping) else None
+ found: list[str] = []
+ for step in steps if isinstance(steps, list) else []:
+ if isinstance(step, Mapping) and step.get("source") != "user":
+ found += [m.group(0) for m in _ENV_ERROR.finditer(json.dumps(step.get("observation") or "")[:200_000])]
+ return [_short(e, 120) for e in dict.fromkeys(found)]
+
+
+def _final_message(trial_dir: Path) -> str:
+ trajectory = _load_json(trial_dir / "trajectory.json")
+ steps = trajectory.get("steps") if isinstance(trajectory, Mapping) else None
+ for step in reversed(steps if isinstance(steps, list) else []):
+ if isinstance(step, Mapping) and step.get("source") == "agent" and str(step.get("message") or "").strip():
+ return _short(step["message"], 600)
+ return ""
+
+
+def _root_error_in_logs(trial_dir: Path) -> re.Match[str] | None:
+ """Find the agent CLI's own error line in its log (failure.json truncates long messages)."""
+ for log in sorted(trial_dir.glob("*.txt")):
+ try:
+ with log.open("rb") as handle:
+ handle.seek(max(0, log.stat().st_size - _MAX_LOG_TAIL_BYTES))
+ text = handle.read().decode("utf-8", "replace")
+ except OSError:
+ continue
+ plain = "\n".join(line for line in text.splitlines() if not line.lstrip().startswith("{"))
+ if match := _ROOT_ERROR.search(plain):
+ return match
+ return None
+
+
+def _run_error(trial_dir: Path) -> str:
+ failure = _load_json(trial_dir / "failure.json")
+ error = failure.get("error") if isinstance(failure, Mapping) else None
+ if not isinstance(error, Mapping):
+ return ""
+ message = str(error.get("message") or "")
+ # Agent exit errors embed the whole command line; the root cause is the CLI's own error line.
+ root = _root_error_in_logs(trial_dir) or _ROOT_ERROR.search(message)
+ detail = root.group(1) if root else message.split("\nstdout:", 1)[0]
+ # Setup-command failures embed the script; its stdout carries the actual cause (e.g. a curl error).
+ if detail.startswith("Command failed") and (stdout := _STDOUT.search(message)):
+ detail = stdout.group(1)
+ return _short(f"{error.get('type', 'error')}: {detail}", 160)
+
+
+def _diagnose_agent_case(
+ run_dir: Path, agent_name: str, agent: Mapping[str, Any], case_id: str
+) -> list[dict[str, Any]]:
+ with_case = _cases(agent, "with_skill").get(case_id)
+ with_marks, without_marks = _marks(with_case), _marks(_cases(agent, "without_skill").get(case_id))
+ wp, wn = _attempt_rate(with_marks)
+ bp, bn = _attempt_rate(without_marks)
+ errors = with_marks.count(ERROR)
+ failed_trials = []
+ for attempt in with_case.get("attempts", []) if isinstance(with_case, Mapping) else []:
+ if isinstance(attempt, Mapping) and attempt.get("passed") is not True:
+ trial_dir = _trial_dir(run_dir, agent_name, "with-skill", attempt.get("trial"))
+ if trial_dir is not None:
+ failed_trials.append((attempt.get("score"), trial_dir))
+ errored_trials = []
+ with_trials = run_dir / agent_name / "with-skill" / "trials"
+ if errors and with_trials.is_dir() and _SAFE_TRIAL.match(agent_name):
+ errored_trials = [
+ d
+ for d in sorted(with_trials.iterdir())
+ if d.name.split("__", 1)[0] == case_id and (d / "failure.json").is_file()
+ ]
+
+ lost = (wn - wp) + errors
+ hurts = (
+ _case_comparable(agent, with_case, _cases(agent, "without_skill").get(case_id))
+ and bn
+ and wn
+ and bp / bn > wp / wn
+ )
+ goal = _goal_not_met(run_dir, agent_name, case_id, with_case)
+ if not lost and not hurts and not not_used:
+ return [goal] if goal else []
+ rewards = [
+ (r, d) for _, d in failed_trials if isinstance(r := _load_json(d / "reward.json", root=run_dir), Mapping)
+ ]
+ reasons = Counter(reason for reward, _ in rewards for reason in _failed_reasons(reward))
+ env = list(dict.fromkeys(e for _, d in failed_trials for e in _env_errors(d)))
+ activations = [_activated(reward) for reward, _ in rewards]
+ finals = [_final_message(d) for _, d in failed_trials]
+ evidence_dir = (failed_trials or [(None, d) for d in errored_trials] or [(None, None)])[0][1]
+
+ if hurts and wp < wn:
+ kind, what = "skill hurts", f"passes {bp}/{bn} without the skill but {wp}/{wn} with it"
+ if reasons:
+ what += f"; {reasons.most_common(1)[0][0]}"
+ lost = max(lost, round(bp / bn * wn) - wp)
+ elif errors and not failed_trials:
+ detail = next((e for d in errored_trials if (e := _run_error(d))), "")
+ kind, what = "run error", f"{errors} attempt(s) never produced a score" + (f": {detail}" if detail else "")
+ elif finals and all(_ASKS_FOR_INPUT.search(f) for f in finals):
+ kind = "missing input"
+ what = f'the agent stopped to ask for input the case does not provide: "{_short(finals[0], 140)}"'
+ elif activations and all(a is False for a in activations):
+ kind, what = "skill not used", "the agent never loaded the skill in the failed attempts"
+ if reasons:
+ what += f"; {reasons.most_common(1)[0][0]}"
+ elif env:
+ kind, what = "environment", f"tool/dependency errors in the sandbox: {'; '.join(env[:2])}"
+ else:
+ kind = "skill"
+ what = "; ".join(r for r, _ in reasons.most_common(2)) or "attempts scored below the pass threshold"
+ failure = {
+ "case": case_id,
+ "agent": agent_name,
+ "kind": kind,
+ "what": _short(what, 320),
+ "attempts_lost": lost,
+ "reasons": [r for r, _ in reasons.most_common(6)],
+ "env_errors": env[:4],
+ "final_message": _final_message(failed_trials[0][1]) if failed_trials else "",
+ "evidence": _evidence(run_dir, evidence_dir, run_error=kind == "run error"),
+ }
+ return [failure, goal] if goal else [failure]
+
+
+def _goal_not_met(
+ run_dir: Path, agent_name: str, case_id: str, with_case: Mapping[str, Any] | None
+) -> dict[str, Any] | None:
+ """Passing attempts whose judge scored goal accuracy 0: other metrics carried the score, the task wasn't done."""
+ attempts = with_case.get("attempts") if isinstance(with_case, Mapping) else None
+ passed = [a for a in attempts or [] if isinstance(a, Mapping) and a.get("passed") is True]
+ misses = []
+ for attempt in passed:
+ trial_dir = _trial_dir(run_dir, agent_name, "with-skill", attempt.get("trial"))
+ reward = _load_json(trial_dir / "reward.json") if trial_dir else None
+ if isinstance(reward, Mapping) and _score(reward.get("goal_accuracy")) == 0:
+ misses.append((reward, trial_dir))
+ if not misses:
+ return None
+ details = misses[0][0].get("details")
+ goal = details.get("goal_accuracy") if isinstance(details, Mapping) else None
+ goal = goal if isinstance(goal, Mapping) else {}
+ outcome = goal.get("end_state") or goal.get("reason") or ""
+ finals = [_final_message(d) for _, d in misses]
+ what = "passed on the other metrics but scored goal accuracy 0.00"
+ return {
+ "case": case_id,
+ "agent": agent_name,
+ "kind": "goal not met",
+ "what": _short(what + (f": {outcome}" if outcome else ""), 320),
+ "attempts_lost": len(misses),
+ "reasons": [_short(goal["reason"])] if goal.get("reason") else [],
+ "env_errors": [],
+ "final_message": finals[0],
+ "asks_for_input": all(_ASKS_FOR_INPUT.search(f) for f in finals) or bool(_STOPPED_FOR_INPUT.search(outcome)),
+ "evidence": _evidence(run_dir, misses[0][1], run_error=False),
+ }
+
+
+def _evidence(run_dir: Path, trial_dir: Path | None, *, run_error: bool) -> str:
+ if trial_dir is None:
+ return ""
+ names = ("exception.txt", "failure.json") if run_error else ("trajectory.json",)
+ name = next((n for n in names if (trial_dir / n).is_file()), names[-1])
+ return (trial_dir.relative_to(run_dir) / name).as_posix()
+
+
+def _fallback_action(issue: Mapping[str, Any]) -> str:
+ kind = issue["kind"]
+ if kind == "skill not used":
+ request = f' such as "{_short(issue["prompt"], 120)}"' if issue.get("prompt") else ""
+ return (
+ f"Widen the SKILL.md frontmatter description to cover requests{request}; "
+ "the agent decides from the description alone whether to load the skill."
+ )
+ if kind == "environment":
+ return "Install the missing tool or package in evals/environment/Dockerfile, or document the install step in SKILL.md."
+ if kind == "run error":
+ return "Not a skill problem: re-run this case; if it repeats, check the agent/gateway logs."
+ if kind == "missing input":
+ return (
+ "Not a skill problem: add the files or app the prompt refers to (evals/files or "
+ "evals/environment/Dockerfile), or make the prompt self-contained."
+ )
+ if kind == "eval case":
+ return (
+ "Not a skill problem: rewrite this prompt in evals/evals.json as a concrete user request "
+ "(the input and the output wanted), so the case actually exercises the skill."
+ )
+ if kind == "goal not met" and issue.get("asks_for_input"):
+ return (
+ "The agent stopped to ask for input instead of producing the output: add the files the prompt refers to "
+ "(evals/files) or put the needed details in the prompt, or have SKILL.md proceed with marked placeholders."
+ )
+ if kind == "skill hurts":
+ return "Check whether SKILL.md steers the agent away from an approach that already works for this request."
+ return f"Address in SKILL.md: {issue['reasons'][0]}" if issue.get("reasons") else ""
+
+
+def _llm_actions(
+ issues: list[dict[str, Any]], skill_path: Path | None, dataset: Mapping[str, Mapping[str, Any]]
+) -> list[str] | None:
+ skill_md = ""
+ files: list[str] = []
+ if skill_path and (skill_path / "SKILL.md").is_file():
+ skill_md = (skill_path / "SKILL.md").read_text(encoding="utf-8", errors="replace")[:_MAX_SKILL_MD_CHARS]
+ files = sorted(
+ str(p.relative_to(skill_path)) for p in skill_path.rglob("*") if p.is_file() and ".git" not in p.parts
+ )[:80]
+ blocks = []
+ for i, issue in enumerate(issues, 1):
+ entry = dataset.get(issue["case"], {})
+ expected = entry.get("expected_behavior") or entry.get("assertions") or []
+ blocks.append(
+ f"ISSUE {i} [{issue['kind']}] case {issue['case']} ({issue['scope']})\n"
+ f"prompt: {_short(entry.get('question') or entry.get('prompt'), 500)}\n"
+ f"expected: {_short(entry.get('ground_truth') or entry.get('expected_output'), 400)}\n"
+ f"expected steps: {_short('; '.join(map(str, expected)), 500)}\n"
+ f"judge reasons for failure: {' | '.join(issue['reasons'][:5]) or '(none)'}\n"
+ f"sandbox errors: {' | '.join(issue['env_errors']) or '(none)'}\n"
+ f"agent final answer: {issue['final_message'] or '(none)'}"
+ )
+ prompt = (
+ "You help a skill author fix an agent skill after a live evaluation. For each issue give ONE concrete fix, "
+ "at most 35 words, naming the file and what to change (SKILL.md section, a script, "
+ "evals/environment/Dockerfile, or the eval case in evals/evals.json if the case expects something the skill "
+ "does not provide). For [skill not used] issues the fix belongs in the SKILL.md frontmatter description, "
+ "which is all the agent sees when deciding whether to load the skill. "
+ "Write fixes that cover the whole class of requests; do not copy names or details from this one case. "
+ "Base it only on the evidence; do not invent features.\n\n"
+ f"SKILL FILES: {', '.join(files) or '(unknown)'}\n\nSKILL.md:\n{skill_md or '(unavailable)'}\n\n"
+ + "\n\n".join(blocks)
+ + "\n\nRespond with ONLY a JSON array of strings, one fix per issue, in order."
+ )
+ try:
+ from skillevaluator.tier3.eval_core.llm_judge import _extract_json, call_public_llm
+
+ content, error = call_public_llm(prompt, max_tokens=4096, timeout=120)
+ parsed = _extract_json(content) if content and not error else None
+ except Exception: # advisory: fall back to rule-based actions
+ logger.debug("What-to-fix generation failed", exc_info=True)
+ return None
+ if isinstance(parsed, list) and len(parsed) == len(issues) and all(isinstance(p, str) for p in parsed):
+ return [_short(p, 400) for p in parsed]
+ return None
+
+
+def _dataset_entries(run_dir: Path) -> dict[str, Mapping[str, Any]]:
+ snapshot = _load_json(run_dir / "dataset_snapshot.json")
+ entries = snapshot.get("dataset") if isinstance(snapshot, Mapping) else None
+ return {str(e["id"]): e for e in entries or [] if isinstance(e, Mapping) and e.get("id") is not None}
+
+
+_MERGED_KINDS = ("run error", "skill not used", "eval case", "missing input", "goal not met")
+
+
+def _merge_across_cases(issues: list[dict[str, Any]], n_cases: int) -> list[dict[str, Any]]:
+ """Collapse one cause repeated across cases (same error type, or same kind and scope) into one item."""
+ merged: dict[tuple[str, str], dict[str, Any]] = {}
+ rest = []
+ for issue in issues:
+ if issue["kind"] not in _MERGED_KINDS:
+ rest.append(issue)
+ continue
+ cause = issue["what"].split(": ", 1)[-1]
+ key = (issue["kind"], cause.split(":", 1)[0] if issue["kind"] == "run error" else issue["scope"])
+ if (seen := merged.get(key)) is None:
+ merged[key] = dict(issue, cases=[issue["case"]], reasons=list(issue["reasons"]))
+ else:
+ seen["cases"].append(issue["case"])
+ seen["attempts_lost"] += issue["attempts_lost"]
+ seen["asks_for_input"] = bool(seen.get("asks_for_input") and issue.get("asks_for_input"))
+ seen["reasons"] += [r for r in issue["reasons"] if r not in seen["reasons"]]
+ for issue in merged.values():
+ if len(issue["cases"]) > 1:
+ issue["case"] = f"all {n_cases} cases" if len(set(issue["cases"])) == n_cases else ", ".join(issue["cases"])
+ if issue["kind"] == "run error":
+ cause = issue["what"].split(": ", 1)[-1]
+ issue["what"] = f"{issue['attempts_lost']} attempt(s) never produced a score: {cause}"
+ return rest + list(merged.values())
+
+
+def _skill_description(skill_path: Path | None) -> str:
+ skill_md = skill_path / "SKILL.md" if skill_path else None
+ if skill_md is None or not skill_md.is_file():
+ return ""
+ match = re.match(r"---\s*\n(.*?)\n---", skill_md.read_text(encoding="utf-8", errors="replace"), re.DOTALL)
+ try:
+ import yaml
+
+ meta = yaml.safe_load(match.group(1)) if match else None
+ except Exception: # malformed frontmatter: Tier 1 reports it
+ return ""
+ return str(meta.get("description") or "") if isinstance(meta, Mapping) else ""
+
+
+def _restates(prompt: str, description: str) -> bool:
+ """True when the eval prompt pastes in a long run of the skill description instead of posing a task."""
+ a, b = prompt.lower(), description.lower()
+ if len(a) < _RESTATED_CHARS or len(b) < _RESTATED_CHARS:
+ return False
+ return SequenceMatcher(None, a, b, autojunk=False).find_longest_match(0, len(a), 0, len(b)).size >= _RESTATED_CHARS
+
+
+def what_to_fix(
+ result: Mapping[str, Any], *, run_dir: Path, skill_path: Path | None = None, use_llm: bool = True
+) -> list[dict[str, Any]]:
+ """Rank failed test cases across agents by attempts lost and attach one fix each."""
+ agents = {str(k): v for k, v in (result.get("agents") or {}).items() if isinstance(v, Mapping)}
+ grouped: dict[tuple[str, str], list[dict[str, Any]]] = {}
+ for case_id in _case_ids(agents):
+ for name, agent in agents.items():
+ for issue in _diagnose_agent_case(run_dir, name, agent, case_id):
+ grouped.setdefault((case_id, issue["kind"]), []).append(issue)
+ issues = []
+ for items in grouped.values():
+ names = [item["agent"] for item in items]
+ merged = dict(items[0])
+ merged["asks_for_input"] = all(item.get("asks_for_input") for item in items)
+ merged.update(
+ scope=names[0] + " only"
+ if len(agents) > 1 and len(names) == 1
+ else "all agents"
+ if len(agents) > 1
+ else names[0],
+ attempts_lost=sum(item["attempts_lost"] for item in items),
+ reasons=list(dict.fromkeys(r for item in items for r in item["reasons"])),
+ env_errors=list(dict.fromkeys(e for item in items for e in item["env_errors"])),
+ )
+ issues.append(merged)
+ dataset = _dataset_entries(run_dir)
+ description = _skill_description(skill_path)
+ for issue in issues:
+ entry = dataset.get(issue["case"], {})
+ prompt = str(entry.get("question") or entry.get("prompt") or "")
+ issue["prompt"] = prompt
+ if issue["kind"] != "run error" and _restates(prompt, description):
+ issue["kind"] = "eval case"
+ issue["what"] = "the test prompt repeats the skill description instead of asking for a concrete task"
+ issues = _merge_across_cases(issues, len(_case_ids(agents)))
+ if saturated := _baseline_saturated(agents):
+ issues.append(saturated)
+ issues.sort(key=lambda issue: (issue["kind"] == "run error", -issue["attempts_lost"], issue["case"]))
+ issues = issues[:_MAX_FIXES]
+ # These kinds have a fixed remedy; the LLM only writes fixes that depend on the skill's content.
+ actionable = [
+ issue
+ for issue in issues
+ if issue["kind"] not in ("run error", "eval case", "missing input", "skill not used")
+ and not issue.get("asks_for_input")
+ ]
+ actions = _llm_actions(actionable, skill_path, dataset) if use_llm and actionable else None
+ by_id = dict(zip((id(i) for i in actionable), actions or [], strict=False))
+ for issue in issues:
+ issue["action"] = issue.get("action") or by_id.get(id(issue)) or _fallback_action(issue)
+ return issues
+
+
+def _baseline_saturated(agents: Mapping[str, Mapping[str, Any]]) -> dict[str, Any] | None:
+ """Flag agents that pass every case without the skill: the eval cannot show what the skill adds."""
+ names = []
+ for name, agent in agents.items():
+ cases = _cases(agent, "without_skill").values()
+ passed, total = _agent_rates(agent)["without_skill"]
+ if total and passed == total and not any(ERROR in _marks(case) for case in cases):
+ names.append(name)
+ if not names:
+ return None
+ return {
+ "case": "all cases",
+ "agent": names[0],
+ "kind": "eval case",
+ "scope": "all agents" if len(agents) > 1 and len(names) == len(agents) else ", ".join(names),
+ "attempts_lost": 0,
+ "what": "every case also passes without the skill, so this eval cannot show what the skill adds",
+ "reasons": [],
+ "env_errors": [],
+ "evidence": "",
+ "action": (
+ "Add cases the agent fails without the skill (tasks that need the skill's scripts, "
+ "conventions or domain rules) so the eval measures the skill's value."
+ ),
+ }
diff --git a/src/skillevaluator/tier3/result_display.py b/src/skillevaluator/tier3/result_display.py
index abe288be..09b3d4e2 100644
--- a/src/skillevaluator/tier3/result_display.py
+++ b/src/skillevaluator/tier3/result_display.py
@@ -6,6 +6,7 @@
from __future__ import annotations
import io
+import json
import logging
import math
import os
@@ -745,8 +746,37 @@ def _render_feedback_and_suggestions(
)
-def render_evaluation_result(result: Mapping[str, Any], *, console: Console) -> None:
- """Render persisted engine truth, aggregating only canonical score components."""
+def _case_first_summary(result: Mapping[str, Any], *, console: Console, skill_path: Path | None) -> bool:
+ from skillevaluator.tier3.case_summary import render_case_summary, what_to_fix
+
+ run_dir = result.get("run_dir") or result.get("output_dir")
+ fixes = None
+ if run_dir and Path(str(run_dir)).is_dir():
+ saved = Path(str(run_dir)) / "what_to_fix.json"
+ try:
+ # The HTML report render writes this first; reuse it so CLI and report show the same fixes.
+ fixes = json.loads(saved.read_text(encoding="utf-8")) if saved.is_file() else None
+ if not isinstance(fixes, list):
+ fixes = what_to_fix(result, run_dir=Path(str(run_dir)), skill_path=skill_path)
+ saved.write_text(json.dumps(fixes, indent=2), encoding="utf-8")
+ except Exception: # advisory panel: never break the run summary
+ logging.getLogger(__name__).debug("What-to-fix skipped", exc_info=True)
+ return render_case_summary(result, console=console, fixes=fixes)
+
+
+def render_evaluation_result(
+ result: Mapping[str, Any],
+ *,
+ console: Console,
+ verbose: bool = True,
+ skill_path: Path | None = None,
+) -> None:
+ """Render persisted engine truth, aggregating only canonical score components.
+
+ The case-first summary always leads; ``verbose`` adds the per-evaluator and
+ per-dimension tables and the metric findings report, which are also shown
+ when the result has no per-case rows.
+ """
secret_values = secret_values_from_environment(os.environ)
def safe(value: object) -> str:
@@ -769,7 +799,11 @@ def render_evaluation_result(result: Mapping[str, Any], *, console: Console) ->
)
if incomplete:
rendered_feedback_messages = _render_incomplete_execution(result=result, console=console, safe=safe)
+ has_cases = False
if isinstance(agents, Mapping) and agents and not incomplete:
+ has_cases = _case_first_summary(result, console=console, skill_path=skill_path)
+ detailed = verbose or not has_cases
+ if isinstance(agents, Mapping) and agents and not incomplete and detailed:
metrics = _display_metrics(result, agents)
for agent, raw in agents.items():
data = raw if isinstance(raw, Mapping) else {}
@@ -821,32 +855,39 @@ def render_evaluation_result(result: Mapping[str, Any], *, console: Console) ->
if not incomplete and (rendered_errors or warnings):
status_style = "bold red" if rendered_errors else "bold yellow"
console.print(Text(f"Tier 3 Evaluation: {display_status.upper()}", style=status_style))
- findings = Text()
- if rendered_errors:
- findings.append("Failures\n", style="bold red")
- for error in dict.fromkeys(rendered_errors):
- findings.append(f" - {safe(error)}\n")
- if warnings:
- findings.append("Warnings\n", style="bold yellow")
+ if not detailed:
for warning in warnings:
- findings.append(f" - {safe(warning)}\n")
- console.print(
- Panel(
- findings,
- title="[bold]Findings[/bold]",
- border_style="red" if rendered_errors else "yellow",
- padding=(1, 1),
+ console.print(Text(f" warning: {safe(warning)}", style="yellow"))
+ if rendered_errors:
+ console.print(f" {len(dict.fromkeys(rendered_errors))} failure detail(s): --verbose or report.html")
+ else:
+ findings = Text()
+ if rendered_errors:
+ findings.append("Failures\n", style="bold red")
+ for error in dict.fromkeys(rendered_errors):
+ findings.append(f" - {safe(error)}\n")
+ if warnings:
+ findings.append("Warnings\n", style="bold yellow")
+ for warning in warnings:
+ findings.append(f" - {safe(warning)}\n")
+ console.print(
+ Panel(
+ findings,
+ title="[bold]Findings[/bold]",
+ border_style="red" if rendered_errors else "yellow",
+ padding=(1, 1),
+ )
)
- )
# Keep payload-only insights while filtering exact items already printed by
# the detailed per-evaluator report.
- _render_feedback_and_suggestions(
- console=console,
- result=result,
- safe=safe,
- excluded_messages=rendered_feedback_messages,
- )
+ if detailed or incomplete:
+ _render_feedback_and_suggestions(
+ console=console,
+ result=result,
+ safe=safe,
+ excluded_messages=rendered_feedback_messages,
+ )
artifact_rows: list[tuple[str, str]] = []
report_path = result.get("report_path")
diff --git a/tests/evaluation/test_judges.py b/tests/evaluation/test_judges.py
index 859b74bf..d142b0a8 100644
--- a/tests/evaluation/test_judges.py
+++ b/tests/evaluation/test_judges.py
@@ -838,3 +838,14 @@ class TestInsightsJudgeNegativeControls:
assert parsed[0]["claim_type"] == "general"
assert parsed[0]["evidence_case_ids"] == ["positive-002", "positive-001"]
+
+
+def test_regressed_dimension_reasoning_names_the_weakest_signal() -> None:
+ from skillevaluator.evaluation.dimension_judge import _human_reasoning_bullets
+
+ parts = ["goal_accuracy=0.25", "behavior_check=0.81"]
+ regressed = _human_reasoning_bullets(with_skill=0.53, baseline=0.66, lift=-0.13, parts=parts)
+ improved = _human_reasoning_bullets(with_skill=0.8, baseline=0.4, lift=0.4, parts=parts)
+
+ assert regressed[-1] == "Weakest signal: goal_accuracy 0.25."
+ assert improved[-1] == "Strongest signal: behavior_check 0.81."
diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json
index 3d65650b..760d91c1 100644
--- a/tests/golden/cli_surface.json
+++ b/tests/golden/cli_surface.json
@@ -647,6 +647,16 @@
"--progress"
],
"param_type": "option"
+ },
+ {
+ "default": "False",
+ "is_flag": true,
+ "name": "verbose",
+ "opts": [
+ "--verbose"
+ ],
+ "param_type": "option",
+ "type": "boolean"
}
]
},
@@ -2541,6 +2551,16 @@
"--progress"
],
"param_type": "option"
+ },
+ {
+ "default": "False",
+ "is_flag": true,
+ "name": "verbose",
+ "opts": [
+ "--verbose"
+ ],
+ "param_type": "option",
+ "type": "boolean"
}
]
},
@@ -3047,6 +3067,16 @@
"--progress"
],
"param_type": "option"
+ },
+ {
+ "default": "False",
+ "is_flag": true,
+ "name": "verbose",
+ "opts": [
+ "--verbose"
+ ],
+ "param_type": "option",
+ "type": "boolean"
}
]
}
diff --git a/tests/reporting/test_case_findings_report.py b/tests/reporting/test_case_findings_report.py
new file mode 100644
index 00000000..1d727263
--- /dev/null
+++ b/tests/reporting/test_case_findings_report.py
@@ -0,0 +1,63 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""report.html leads with the case-based verdict and fixes shared with the CLI."""
+
+import json
+
+from tests.reporting.test_resource_comparison import write_arm
+
+from skillevaluator.evaluation.tier3_report import render_agent_eval_html_report
+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS
+
+
+def _run(tmp_path, *, goal_accuracy: float):
+ run = tmp_path / "run"
+ trial = write_arm(run, "with-skill", 10, 3)
+ write_arm(run, "without-skill", 20, 5)
+ reward = {
+ "entry_id": "case",
+ "trial_id": "case__1",
+ **dict.fromkeys(DEFAULT_METRICS, 1.0),
+ "goal_accuracy": goal_accuracy,
+ }
+ reward["details"] = {"goal_accuracy": {"reason": "no report", "end_state": "asked for the data"}}
+ (trial / "reward.json").write_text(json.dumps(reward))
+
+ def condition(passed):
+ attempt = {"attempt": 1, "trial": "case__1", "score": 0.9 if passed else 0.2, "passed": passed}
+ return {"k": 1, "cases": {"case": {"passed": passed, "attempts": [attempt]}}}
+
+ agent = {"pass_at_k": {"with_skill": condition(True), "without_skill": condition(False)}}
+ for arm, passed in (("with-skill", True), ("without-skill", False)):
+ summary = json.loads((run / "opencode" / arm / "summary.json").read_text())
+ (run / "opencode" / arm / "summary.json").write_text(json.dumps({**summary, "pass_at_k": condition(passed)}))
+ (run / "result.json").write_text(json.dumps({"agents": {"opencode": agent}}))
+ return run
+
+
+def test_report_leads_with_skill_effect_and_goal_not_met_fix(tmp_path) -> None:
+ run = _run(tmp_path, goal_accuracy=0.0)
+
+ html = render_agent_eval_html_report(tmp_path, run, use_llm_judge=False).read_text(encoding="utf-8")
+
+ [fix] = json.loads((run / "what_to_fix.json").read_text())
+ assert fix["kind"] == "goal not met"
+ assert (
+ "· per-case result: skill helps (opencode +100 pp). 1 passing with-skill attempt(s) did not meet the goal"
+ in html
+ )
+ assert "1 issue to fix, most attempts lost first:" in html
+ assert "[goal not met]: passed on the other metrics but scored goal accuracy 0.00: asked for the data." in html
+ assert "Evidence: opencode/with-skill/trials/case__1/trajectory.json" in html
+ assert "goal not met (0.00)</span>" in html
+
+
+def test_report_says_nothing_to_fix_when_every_case_passes_and_meets_its_goal(tmp_path) -> None:
+ run = _run(tmp_path, goal_accuracy=1.0)
+
+ html = render_agent_eval_html_report(tmp_path, run, use_llm_judge=False).read_text(encoding="utf-8")
+
+ assert json.loads((run / "what_to_fix.json").read_text()) == []
+ assert "Nothing to fix: every with-skill attempt passed and met its goal" in html
+ assert "goal not met (0.00)" not in html
diff --git a/tests/reporting/test_resource_comparison.py b/tests/reporting/test_resource_comparison.py
index 5442a7d2..d08fe012 100644
--- a/tests/reporting/test_resource_comparison.py
+++ b/tests/reporting/test_resource_comparison.py
@@ -64,7 +64,7 @@ def test_resources_flow_from_harbor_artifacts_to_json_and_html(tmp_path, missing
html = HTMLReporter(target_path=str(tmp_path)).render_all([result])
assert "Measured Agent Resources" in html
assert "Agent execution seconds" in html
- assert "-2.00" in html
- assert "N/A" in html if missing_tokens else "-10.00" in html
+ assert "-2.0 s (-" in html
+ assert "N/A" in html if missing_tokens else "-10 (-" in html
output = json.loads(JSONReporter().render_all([result]))
assert "resources" in json.dumps(output)
diff --git a/tests/test_tier3_case_summary.py b/tests/test_tier3_case_summary.py
new file mode 100644
index 00000000..4b7fdc75
--- /dev/null
+++ b/tests/test_tier3_case_summary.py
@@ -0,0 +1,632 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Case-first Tier 3 summary and How-to-improve ranking."""
+
+import json
+from pathlib import Path
+
+from rich.console import Console
+
+from skillevaluator.tier3.case_summary import render_case_summary, verdict, what_to_fix
+from skillevaluator.tier3.result_display import render_result
+
+
+def _case(*passed: bool, missing: int = 0, prefix: str = "t") -> dict:
+ return {
+ "attempts": [
+ {"attempt": i + 1, "trial": f"{prefix}{i}", "score": 0.9 if p else 0.2, "passed": p}
+ for i, p in enumerate(passed)
+ ],
+ "attempts_missing": missing,
+ }
+
+
+def _agent(with_cases: dict, without_cases: dict) -> dict:
+ return {
+ "execution_status": "succeeded",
+ "pass_at_k": {"with_skill": {"k": 2, "cases": with_cases}, "without_skill": {"k": 2, "cases": without_cases}},
+ "lift": {"overall": {"with_skill": 0.7, "without_skill": 0.4, "delta": 0.3}},
+ "dimensions_with_skill": {"effectiveness": {"score": 0.5}, "security": {"score": 1.0}},
+ "dimensions_without_skill": {"effectiveness": {"score": 0.3}, "security": {"score": 1.0}},
+ }
+
+
+def _trial(run_dir: Path, agent: str, name: str, reward: dict, observation: str = "") -> None:
+ trial = run_dir / agent / "with-skill" / "trials" / name
+ trial.mkdir(parents=True)
+ (trial / "reward.json").write_text(json.dumps(reward))
+ steps = [{"source": "user", "message": "q"}, {"source": "agent", "message": "done", "observation": observation}]
+ (trial / "trajectory.json").write_text(json.dumps({"steps": steps}))
+
+
+def _reward(activated: bool, reason: str) -> dict:
+ return {
+ "goal_accuracy": 0.2,
+ "details": {
+ "skill_execution": {"activation": {"passed": activated}},
+ "goal_accuracy": {"reason": reason},
+ "behavior_check": {"results": [{"passed": False, "reason": reason}]},
+ },
+ }
+
+
+def test_grid_shows_one_row_per_case_with_attempt_marks_per_agent() -> None:
+ result = {
+ "execution_status": "succeeded",
+ "agents": {
+ "claude-code": _agent({"c1": _case(True, True), "c2": _case(False, True)}, {"c1": _case(False, False)}),
+ "codex": _agent({"c1": _case(True, False), "c2": _case(False, missing=1)}, {"c2": _case(True, True)}),
+ },
+ }
+ output = render_result(result)
+ rows = {line.split()[0]: line for line in output.splitlines() if line.startswith("c")}
+ lines = output.splitlines()
+ header = lines[next(i for i, line in enumerate(lines) if line.startswith("test case")) - 1]
+ assert header.split() == ["claude-code", "codex"]
+ assert "✗✗ → ✓✓ +100" in rows["c1"] and "- → ✓✗ ?" in rows["c1"]
+ assert "- → ✗✓ ?" in rows["c2"] and "✓✓ → ✗⊘ ?" in rows["c2"]
+ rates = next(line for line in output.splitlines() if line.startswith("success rate"))
+ assert "0% → 75% +75 pp" in rates and rates.rstrip().endswith("?")
+ assert output.index("effectiveness") < output.index("security")
+ assert output.count("(without → with skill)") == 2 and "change in pass rate" in output
+ assert "skill helps claude-code +75 pp · codex: 1 attempt(s) did not run" in output
+
+
+def test_verdict_thresholds() -> None:
+ helps = {"a": _agent({"c": _case(True, True)}, {"c": _case(False, False)})}
+ flat = {"a": _agent({"c": _case(True, False)}, {"c": _case(False, True)})}
+ hurts = {"a": _agent({"c": _case(False, False)}, {"c": _case(True, True)})}
+ assert verdict(helps) == ("skill helps", "a +100 pp")
+ assert verdict(flat)[0] == "no clear effect"
+ assert verdict(hurts)[0] == "skill hurts"
+ partial = {"a": _agent({"c": _case(True, missing=1)}, {"c": _case(False, False)})}
+ assert verdict(partial) == ("inconclusive", "a: 1 attempt(s) did not run")
+
+
+def test_what_to_fix_classifies_and_ranks_by_attempts_lost(tmp_path: Path) -> None:
+ agents = {
+ "opencode": _agent(
+ {
+ "unused": _case(False, False, prefix="u"),
+ "env": _case(False, True, prefix="e"),
+ "hurts": _case(True, False, prefix="h"),
+ "broken": _case(missing=2),
+ "fine": _case(True, True, prefix="f"),
+ },
+ {"hurts": _case(True, True), "unused": _case(False, False)},
+ )
+ }
+ for name in ("u0", "u1"):
+ _trial(tmp_path, "opencode", name, _reward(False, "never read SKILL.md"))
+ _trial(tmp_path, "opencode", "e0", _reward(True, "no output"), "ModuleNotFoundError: No module named 'pypdf'")
+ _trial(tmp_path, "opencode", "h1", _reward(True, "followed the wrong script"))
+ for name in ("broken__a", "broken__b"):
+ (tmp_path / "opencode" / "with-skill" / "trials" / name).mkdir(parents=True)
+ (tmp_path / "opencode" / "with-skill" / "trials" / name / "failure.json").write_text(
+ json.dumps({"error": {"type": "NonZeroAgentExitCodeError", "message": "EPIPE"}})
+ )
+
+ fixes = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert [(f["case"], f["kind"], f["attempts_lost"]) for f in fixes] == [
+ ("unused", "skill not used", 2),
+ ("env", "environment", 1),
+ ("hurts", "skill hurts", 1),
+ ]
+ assert "No module named 'pypdf'" in fixes[1]["what"]
+ assert fixes[0]["evidence"] == "opencode/with-skill/trials/u0/trajectory.json"
+ assert all(f["action"] for f in fixes)
+
+
+def test_run_errors_rank_after_skill_issues_and_are_not_blamed_on_the_skill(tmp_path: Path) -> None:
+ agents = {"opencode": _agent({"broken": _case(missing=2)}, {})}
+ trial = tmp_path / "opencode" / "with-skill" / "trials" / "broken__a"
+ trial.mkdir(parents=True)
+ (trial / "failure.json").write_text(json.dumps({"error": {"type": "AgentTimeoutError", "message": "900s"}}))
+
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert fix["kind"] == "run error"
+ assert "AgentTimeoutError" in fix["what"]
+ assert fix["action"].startswith("Not a skill problem")
+ assert fix["evidence"] == "opencode/with-skill/trials/broken__a/failure.json"
+
+
+def test_multi_agent_issue_scope_names_the_failing_agent(tmp_path: Path) -> None:
+ agents = {
+ "claude-code": _agent({"c": _case(True, True)}, {}),
+ "codex": _agent({"c": _case(False, False, prefix="x")}, {}),
+ }
+ for name in ("x0", "x1"):
+ _trial(tmp_path, "codex", name, _reward(True, "skipped validation step"))
+
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert (fix["scope"], fix["kind"]) == ("codex only", "skill")
+ assert "skipped validation step" in fix["what"]
+
+
+def test_trial_names_cannot_escape_the_run_directory(tmp_path: Path) -> None:
+ agents = {"opencode": _agent({"c": {"attempts": [{"trial": "../../etc", "passed": False}]}}, {})}
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+ assert fix["evidence"] == ""
+
+
+def test_eval_prompt_that_restates_the_description_is_flagged_as_an_eval_problem(tmp_path: Path) -> None:
+ description = "Use this skill whenever the user wants to create, read, edit, or manipulate Word documents."
+ skill = tmp_path / "skill"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text(f"---\nname: docx\ndescription: {description}\n---\n# Docx\n")
+ run = tmp_path / "run"
+ cases = {f"c{i}": _case(False, prefix=f"c{i}_") for i in (1, 2)}
+ entries = [{"id": f"c{i}", "question": f"I need help: {description.lower()}"} for i in (1, 2)]
+ run.mkdir()
+ (run / "dataset_snapshot.json").write_text(json.dumps({"dataset": entries}))
+ for i in (1, 2):
+ _trial(run, "claude-code", f"c{i}_0", _reward(False, "asked what to do"))
+
+ [fix] = what_to_fix({"agents": {"claude-code": _agent(cases, {})}}, run_dir=run, skill_path=skill, use_llm=False)
+
+ assert (fix["case"], fix["kind"], fix["attempts_lost"]) == ("all 2 cases", "eval case", 2)
+ assert fix["action"].startswith("Not a skill problem: rewrite this prompt")
+
+
+def test_setup_command_failure_reports_its_stdout_and_merges_by_error_type(tmp_path: Path) -> None:
+ agents = {"claude-code": _agent({"a": _case(missing=1), "b": _case(missing=1)}, {})}
+ for case, code in (("a", 35), ("b", 56)):
+ trial = tmp_path / "claude-code" / "with-skill" / "trials" / f"{case}__x"
+ trial.mkdir(parents=True)
+ message = f"Command failed (exit 1): set -euo pipefail; curl -fsSL https://x | bash stdout: curl: ({code}) Recv failure stderr: None"
+ (trial / "failure.json").write_text(
+ json.dumps({"error": {"type": "NetworkConnectionError", "message": message}})
+ )
+
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert fix["case"] == "all 2 cases"
+ assert fix["what"] == "2 attempt(s) never produced a score: NetworkConnectionError: curl: (35) Recv failure"
+
+
+def test_failed_condition_rebuilds_case_rows_from_trial_rewards(tmp_path: Path) -> None:
+ trials = tmp_path / "claude-code" / "with-skill" / "trials"
+ for name, overall in (("ok__1", 0.9), ("low__1", 0.3)):
+ (trials / name).mkdir(parents=True)
+ (trials / name / "reward.json").write_text(json.dumps({"overall": overall}))
+ (trials / "gone__1").mkdir()
+ agent = _agent({}, {"ok": _case(False)})
+ agent["pass_at_k"]["without_skill"]["pass_threshold"] = 0.5
+ agent.update(output_dir=str(tmp_path / "claude-code"), trial_failures={"with_skill": [{"trial": "gone__1"}]})
+
+ output = render_result({"execution_status": "failed", "agents": {"claude-code": agent}})
+
+ assert "1/1 ✓ (0.90)" in output and "0/1 ✗ (0.30)" in output and "⊘" in output
+
+
+def test_agent_asking_for_files_the_case_lacks_is_flagged_as_missing_input(tmp_path: Path) -> None:
+ agents = {"claude-code": _agent({"app": _case(False, False, prefix="m")}, {})}
+ for name in ("m0", "m1"):
+ trial = tmp_path / "claude-code" / "with-skill" / "trials" / name
+ _trial(tmp_path, "claude-code", name, _reward(True, "did not run Playwright"))
+ steps = [{"source": "agent", "message": "The workspace appears to be empty. Could you share your app?"}]
+ (trial / "trajectory.json").write_text(json.dumps({"steps": steps}))
+
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert (fix["kind"], fix["attempts_lost"]) == ("missing input", 2)
+ assert "workspace appears to be empty" in fix["what"]
+ assert fix["action"].startswith("Not a skill problem: add the files")
+
+
+def test_baseline_passing_every_case_is_flagged_as_unable_to_show_lift(tmp_path: Path) -> None:
+ agents = {"claude-code": _agent({"a": _case(True, True)}, {"a": _case(True, True)})}
+
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert (fix["case"], fix["kind"], fix["attempts_lost"]) == ("all cases", "eval case", 0)
+ assert fix["action"].startswith("Add cases the agent fails without the skill")
+ console = Console(record=True, width=160)
+ render_case_summary({"agents": agents}, console=console, fixes=[fix])
+ assert "all cases [eval case] · claude-code\n" in console.export_text()
+
+
+def _scored(*scores: float) -> dict:
+ return {"attempts": [{"attempt": i + 1, "score": s, "passed": s >= 0.5} for i, s in enumerate(scores)]}
+
+
+def test_effect_column_names_what_the_skill_changed_per_case() -> None:
+ with_cases = {
+ "helps": _scored(0.8, 0.8),
+ "hurts": _scored(0.3, 0.2),
+ "both-fail": _scored(0.4, 0.3),
+ "better": _scored(0.9, 0.9),
+ "worse": _scored(0.6, 0.6),
+ "same": _scored(0.9, 0.85),
+ "partial": {**_scored(0.9), "attempts_missing": 1},
+ }
+ without_cases = {
+ "helps": _scored(0.3, 0.6),
+ "hurts": _scored(0.9, 0.9),
+ "both-fail": _scored(0.2, 0.1),
+ "better": _scored(0.6, 0.6),
+ "worse": _scored(0.9, 0.8),
+ "same": _scored(0.9, 0.9),
+ "partial": _scored(0.9, 0.9),
+ }
+ output = render_result({"execution_status": "succeeded", "agents": {"a": _agent(with_cases, without_cases)}})
+ effect = {
+ line.split()[0]: line.rstrip().split(" ")[-1].strip() for line in output.splitlines() if line[:1].isalpha()
+ }
+
+ assert effect["helps"] == "helps"
+ assert effect["hurts"] == "hurts"
+ assert effect["both-fail"] == "both fail"
+ assert effect["better"] == "better score (+0.30)"
+ assert effect["worse"] == "worse score (-0.25)"
+ assert effect["same"] == "no change"
+ assert effect["partial"] == "inconclusive"
+ assert "1/1 ✓⊘ (0.90)" in output and "(0.82) mean score 0-1" in output
+
+
+def test_multi_agent_grid_wraps_instead_of_truncating_on_an_80_column_terminal() -> None:
+ cases = {f"internal-comms-with-a-long-case-name-00{i}": _scored(0.81, 0.81) for i in (1, 2)}
+ baseline = {f"internal-comms-with-a-long-case-name-00{i}": _scored(0.53, 0.2) for i in (1, 2)}
+ console = Console(record=True, width=80)
+ render_case_summary(
+ {"agents": {"claude-code": _agent(cases, baseline), "codex": _agent(cases, baseline)}},
+ console=console,
+ fixes=[],
+ )
+ output = console.export_text()
+ assert "…" not in output
+ assert output.count("✓✗ → ✓✓ +50") == 4 and "codex" in output
+ assert max(map(len, output.splitlines())) <= 80
+
+
+def test_multi_agent_dimensions_read_without_then_with_skill() -> None:
+ agent = _agent({"c1": _case(True, True)}, {"c1": _case(False, False)})
+ console = Console(record=True, width=120)
+ render_case_summary({"agents": {"a": agent, "b": agent}}, console=console, fixes=[])
+ rows = {line.split()[0]: line for line in console.export_text().splitlines() if line.strip()}
+ assert rows["effectiveness"].count("0.30 → 0.50 +0.20") == 2
+ assert rows["security"].count("1.00 → 1.00 +0.00") == 2
+
+
+def test_how_to_improve_says_nothing_to_fix_only_when_the_list_was_computed_and_empty() -> None:
+ result = {"agents": {"a": _agent({"c1": _case(True, True)}, {"c1": _case(False, False)})}}
+ for fixes, expected in (([], True), (None, False)):
+ console = Console(record=True, width=120)
+ render_case_summary(result, console=console, fixes=fixes)
+ assert ("How to improve: nothing to fix." in console.export_text()) is expected
+
+
+def test_passing_attempts_that_miss_the_goal_are_reported_with_a_prompt_fix(tmp_path: Path) -> None:
+ agents = {
+ name: _agent({"c1": _case(True, True, prefix=f"{name}1-"), "c2": _case(True, prefix=f"{name}2-")}, {})
+ for name in ("a", "b")
+ }
+ asked = "I need a few quick details: team name, dates, progress."
+ for name in ("a", "b"):
+ for trial in (f"{name}1-0", f"{name}1-1", f"{name}2-0"):
+ reward = {"goal_accuracy": 0.0, "details": {"goal_accuracy": {"reason": "no update", "end_state": "asked"}}}
+ _trial(tmp_path, name, trial, reward)
+ steps = [{"source": "user", "message": "q"}, {"source": "agent", "message": asked}]
+ (tmp_path / name / "with-skill" / "trials" / trial / "trajectory.json").write_text(
+ json.dumps({"steps": steps})
+ )
+ _trial(tmp_path, "a", "unused", {"goal_accuracy": 1.0})
+
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert (fix["case"], fix["kind"], fix["scope"], fix["attempts_lost"]) == (
+ "all 2 cases",
+ "goal not met",
+ "all agents",
+ 6,
+ )
+ assert fix["what"].endswith("goal accuracy 0.00: asked")
+ assert fix["action"].startswith("The agent stopped to ask for input")
+
+
+def test_goal_met_or_unscored_passes_are_not_flagged(tmp_path: Path) -> None:
+ agents = {"a": _agent({"c1": _case(True, True)}, {})}
+ _trial(tmp_path, "a", "t0", {"goal_accuracy": 0.6})
+ _trial(tmp_path, "a", "t1", {})
+
+ assert what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False) == []
+
+
+def test_never_activated_scores_do_not_claim_a_skill_effect(tmp_path: Path) -> None:
+ agent = _agent({"c": _case(False)}, {"c": _case(True)})
+ agent["skill_activation"] = {"status": "never_activated"}
+ _trial(tmp_path, "a", "t0", _reward(False, "the skill was not loaded"))
+ assert verdict({"a": agent})[0] == "inconclusive"
+ fixes = what_to_fix({"agents": {"a": agent}}, run_dir=tmp_path, use_llm=False)
+ assert all(fix["kind"] != "skill hurts" for fix in fixes)
+ output = render_result({"execution_status": "succeeded", "agents": {"a": agent}})
+ assert "skill hurts" not in output
+ assert "inconclusive" in output
+
+
+def test_truncated_attempts_cannot_produce_a_complete_effect_or_clean_bill(tmp_path: Path) -> None:
+ case = {**_case(True), "attempt_details_total": 2, "attempt_details_truncated": True}
+ agent = _agent({"c": case}, {"c": _case(False, False)})
+ assert verdict({"a": agent})[0] == "inconclusive"
+ console = Console(record=True, width=160)
+ render_case_summary({"agents": {"a": agent}}, console=console, fixes=[])
+ output = console.export_text()
+ assert "inconclusive" in output and "nothing to fix" not in output
+
+
+def test_truncated_case_sample_does_not_claim_baseline_saturation(tmp_path: Path) -> None:
+ agent = _agent({"c": _case(True)}, {"c": _case(True)})
+ agent["pass_at_k"]["without_skill"].update(case_details_truncated=True, total_cases=100)
+ assert verdict({"a": agent})[0] == "inconclusive"
+ assert what_to_fix({"agents": {"a": agent}}, run_dir=tmp_path, use_llm=False) == []
+
+
+def test_new_summary_redacts_known_credentials_and_keeps_case_names_literal(tmp_path: Path, monkeypatch) -> None:
+ secret = "review-fake-environment-credential-7135"
+ monkeypatch.setenv("OPENAI_API_KEY", secret)
+ case_id = f"[bold]case[/bold]-{secret}"
+ agent = _agent({case_id: _case(False)}, {case_id: _case(False)})
+ (tmp_path / "what_to_fix.json").write_text(
+ json.dumps(
+ [
+ {
+ "case": case_id,
+ "scope": secret,
+ "kind": "skill",
+ "what": secret,
+ "action": secret,
+ "evidence": secret,
+ "attempts_lost": 1,
+ }
+ ]
+ )
+ )
+ output = render_result({"execution_status": "succeeded", "run_dir": str(tmp_path), "agents": {secret: agent}})
+ assert secret not in output
+ assert "[bold]case[/bold]" in output
+
+
+def test_trial_artifact_symlinks_cannot_supply_advice(tmp_path: Path) -> None:
+ outside = tmp_path / "outside"
+ outside.mkdir()
+ (outside / "reward.json").write_text(json.dumps(_reward(True, "outside-private-reason")))
+ (outside / "trajectory.json").write_text(
+ json.dumps({"steps": [{"source": "agent", "message": "outside-private-answer"}]})
+ )
+ run = tmp_path / "run"
+ trials = run / "a" / "with-skill" / "trials"
+ trials.mkdir(parents=True)
+ (trials / "t0").symlink_to(outside, target_is_directory=True)
+ [fix] = what_to_fix({"agents": {"a": _agent({"c": _case(False)}, {})}}, run_dir=run, use_llm=False)
+ assert "outside-private" not in json.dumps(fix)
+ assert fix["evidence"] == ""
+
+
+def test_symlinked_reward_file_cannot_supply_advice(tmp_path: Path) -> None:
+ outside = tmp_path / "outside.json"
+ outside.write_text(json.dumps(_reward(True, "outside-private-reason")))
+ trial = tmp_path / "run" / "a" / "with-skill" / "trials" / "t0"
+ trial.mkdir(parents=True)
+ (trial / "reward.json").symlink_to(outside)
+ [fix] = what_to_fix({"agents": {"a": _agent({"c": _case(False)}, {})}}, run_dir=tmp_path / "run", use_llm=False)
+ assert "outside-private-reason" not in json.dumps(fix)
+
+
+def test_parent_agent_component_cannot_escape_run_directory(tmp_path: Path) -> None:
+ run = tmp_path / "run"
+ run.mkdir()
+ trial = tmp_path / "with-skill" / "trials" / "t0"
+ trial.mkdir(parents=True)
+ (trial / "reward.json").write_text(json.dumps(_reward(True, "outside-private-reason")))
+ [fix] = what_to_fix({"agents": {"..": _agent({"c": _case(False)}, {})}}, run_dir=run, use_llm=False)
+ assert "outside-private-reason" not in json.dumps(fix)
+ assert fix["evidence"] == ""
+
+
+def test_advice_is_redacted_before_it_is_saved(tmp_path: Path, monkeypatch) -> None:
+ secret = "review-fake-credential-in-judge-reason-8745"
+ monkeypatch.setenv("OPENAI_API_KEY", secret)
+ _trial(tmp_path, "a", "t0", _reward(True, secret))
+ fixes = what_to_fix({"agents": {"a": _agent({"c": _case(False)}, {})}}, run_dir=tmp_path, use_llm=False)
+ assert secret not in json.dumps(fixes)
+ assert "<redacted>" in json.dumps(fixes)
+
+
+def test_issue_scope_names_a_subset_of_more_than_two_agents(tmp_path: Path) -> None:
+ agents = {name: _agent({"c": _case(name == "c")}, {}) for name in ("a", "b", "c")}
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+ assert fix["scope"] == "a, b only"
+
+
+def test_missing_attempts_suppress_the_single_agent_summary_delta() -> None:
+ agent = _agent({"c": _case(True, missing=1)}, {"c": _case(False)})
+ output = render_result({"execution_status": "succeeded", "agents": {"a": agent}})
+ row = next(line for line in output.splitlines() if line.startswith("success rate"))
+ assert "+100" not in row
+
+
+def test_advisory_prompt_redacts_credentials_before_the_model_call(tmp_path: Path, monkeypatch) -> None:
+ from skillevaluator.tier3.eval_core import llm_judge
+
+ secret = "review-fake-advisory-prompt-secret-9375"
+ monkeypatch.setenv("OPENAI_API_KEY", secret)
+ _trial(tmp_path, "a", "t0", _reward(True, secret))
+ skill = tmp_path / "skill"
+ skill.mkdir()
+ (skill / "SKILL.md").write_text(f"# Skill\n\nPrivate setup: {secret}")
+ prompts = []
+
+ def call(prompt, **kwargs):
+ prompts.append(prompt)
+ return '["Improve the skill instructions."]', None
+
+ monkeypatch.setattr(llm_judge, "call_public_llm", call)
+ what_to_fix({"agents": {"a": _agent({"c": _case(False)}, {})}}, run_dir=tmp_path, skill_path=skill)
+ assert len(prompts) == 1 and secret not in prompts[0]
+ assert "\n\nSKILL.md:\n# Skill\n" in prompts[0]
+
+
+def test_long_error_logs_keep_the_root_error_from_the_bounded_tail(tmp_path: Path) -> None:
+ trial = tmp_path / "a" / "with-skill" / "trials" / "c__1"
+ trial.mkdir(parents=True)
+ (trial / "failure.json").write_text(json.dumps({"error": {"type": "AgentExitError", "message": "wrapper failed"}}))
+ (trial / "agent.txt").write_text("irrelevant log output\n" * 10000 + "Error: specific-tail-cause\n")
+ [fix] = what_to_fix({"agents": {"a": _agent({"c": _case(missing=1)}, {})}}, run_dir=tmp_path, use_llm=False)
+ assert "specific-tail-cause" in fix["what"]
+
+
+def test_failed_condition_rebuild_does_not_follow_a_symlinked_trials_directory(tmp_path: Path) -> None:
+ outside = tmp_path / "outside" / "c__1"
+ outside.mkdir(parents=True)
+ (outside / "reward.json").write_text(json.dumps({"overall": 0.9}))
+ agent_dir = tmp_path / "run" / "a"
+ (agent_dir / "with-skill").mkdir(parents=True)
+ (agent_dir / "with-skill" / "trials").symlink_to(outside.parent, target_is_directory=True)
+ agent = _agent({}, {})
+ agent["output_dir"] = str(agent_dir)
+ console = Console(record=True, width=160)
+ assert not render_case_summary({"agents": {"a": agent}}, console=console, fixes=None)
+
+
+def test_different_condition_score_contracts_do_not_claim_a_causal_skill_effect(tmp_path: Path) -> None:
+ for fields in (
+ {"metrics_with_skill": ["security"], "metrics_without_skill": ["accuracy"]},
+ {"score_policy_with_skill": "dimension-mean/v1", "score_policy_without_skill": "legacy-flat/v1"},
+ ):
+ agent = {**_agent({"c": _case(False)}, {"c": _case(True)}), **fields}
+ assert verdict({"a": agent})[0] == "inconclusive"
+ fixes = what_to_fix({"agents": {"a": agent}}, run_dir=tmp_path, use_llm=False)
+ assert all(fix["kind"] != "skill hurts" for fix in fixes)
+ output = render_result({"execution_status": "succeeded", "agents": {"a": agent}})
+ assert "skill hurts" not in output
+ rates = next(line for line in output.splitlines() if line.startswith("success rate"))
+ assert "-100" not in rates
+
+
+def test_disjoint_case_coverage_does_not_produce_an_overall_effect() -> None:
+ agent = _agent(
+ {"shared": _case(True), "with-only": _case(True)}, {"shared": _case(False), "baseline-only": _case(False)}
+ )
+ assert verdict({"a": agent})[0] == "inconclusive"
+
+
+def test_logical_multistep_goal_counts_average_steps_once(tmp_path: Path) -> None:
+ from skillevaluator.tier3.case_summary import goal_not_met_count
+
+ for label, goals, expected in (("missed", [0.0, 0.0], 1), ("mixed", [0.0, 1.0], 0)):
+ run = tmp_path / label
+ trial_id = "case__attempt1"
+ for i, goal in enumerate(goals, 1):
+ _trial(run, "a", f"{trial_id}__step-{i}", {"trial_id": trial_id, "goal_accuracy": goal})
+ case = {"attempts": [{"trial": trial_id, "passed": True, "score": 0.9}]}
+ source = {"agents": {"a": _agent({"case": case}, {"case": _case(False)})}}
+ assert goal_not_met_count(source, run_dir=run) == expected
+ fixes = what_to_fix(source, run_dir=run, use_llm=False)
+ assert sum(f["attempts_lost"] for f in fixes if f["kind"] == "goal not met") == expected
+
+
+def test_failed_conditions_keep_rebuilt_scores_diagnostic(tmp_path: Path) -> None:
+ agent = _agent({"c": _case(True)}, {"c": _case(False)})
+ agent["conditions"] = {
+ "with_skill": {"execution_status": "failed"},
+ "without_skill": {"execution_status": "succeeded"},
+ }
+ assert verdict({"a": agent})[0] == "inconclusive"
+ output = render_result({"execution_status": "failed", "agents": {"a": agent}})
+ assert "skill helps" not in output
+
+
+def test_saved_fixes_do_not_follow_a_symlink(tmp_path: Path) -> None:
+ outside = tmp_path / "outside.json"
+ content = json.dumps(
+ [
+ {
+ "case": "private-external-case",
+ "scope": "private",
+ "kind": "skill",
+ "what": "private",
+ "action": "private",
+ "evidence": "private",
+ "attempts_lost": 1,
+ }
+ ]
+ )
+ outside.write_text(content)
+ run = tmp_path / "run"
+ run.mkdir()
+ (run / "what_to_fix.json").symlink_to(outside)
+ agent = _agent({"c": _case(True)}, {"c": _case(False)})
+ output = render_result({"execution_status": "succeeded", "run_dir": str(run), "agents": {"a": agent}})
+ assert "private-external-case" not in output
+ assert outside.read_text() == content
+
+
+def _goal_miss(run_dir: Path, agent: str, trial: str, end_state: str) -> None:
+ _trial(run_dir, agent, trial, {"goal_accuracy": 0.0, "details": {"goal_accuracy": {"end_state": end_state}}})
+
+
+def test_goal_not_met_uses_the_canned_fix_only_when_the_agent_stopped_for_input(tmp_path: Path) -> None:
+ outcomes = {
+ "The agent made HTTP requests to the API and returned the wrong totals.": False,
+ "The agent fixed an import that was not found and wrote the report.": False,
+ "The agent asked the user for the report file.": True,
+ "report.pdf does not exist in the workspace, so nothing was extracted.": True,
+ }
+ for index, (outcome, stopped) in enumerate(outcomes.items()):
+ run_dir = tmp_path / str(index)
+ _goal_miss(run_dir, "a", "x0", outcome)
+
+ [fix] = what_to_fix(
+ {"agents": {"a": _agent({"c1": _case(True, prefix="x")}, {})}}, run_dir=run_dir, use_llm=False
+ )
+
+ assert fix["asks_for_input"] is stopped, outcome
+ assert fix["action"].startswith("The agent stopped to ask for input") is stopped, outcome
+
+
+def test_merged_goal_issue_keeps_the_canned_fix_only_if_every_agent_stopped_for_input(tmp_path: Path) -> None:
+ agents = {name: _agent({"c1": _case(True, prefix=name)}, {}) for name in ("a", "b")}
+ _goal_miss(tmp_path, "a", "a0", "The agent asked for the sprint details.")
+ _goal_miss(tmp_path, "b", "b0", "The agent wrote the wrong section headings.")
+
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert (fix["scope"], fix["asks_for_input"]) == ("all agents", False)
+
+
+def test_case_with_a_failure_also_reports_passes_that_missed_the_goal(tmp_path: Path) -> None:
+ agents = {"a": _agent({"c1": _case(True, False, prefix="m")}, {})}
+ _goal_miss(tmp_path, "a", "m0", "The agent asked for the data.")
+ _trial(tmp_path, "a", "m1", _reward(True, "wrong totals"))
+
+ kinds = {f["kind"] for f in what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)}
+
+ assert kinds == {"skill", "goal not met"}
+
+
+def test_fixes_redact_environment_secrets(tmp_path: Path, monkeypatch) -> None:
+ secret = "review-fake-goal-credential-5521"
+ monkeypatch.setenv("SKILL_EVAL_LLM_API_KEY", secret)
+ agents = {"a": _agent({"c1": _case(True, prefix="s")}, {})}
+ _goal_miss(tmp_path, "a", "s0", f"The agent printed {secret} and asked for the file.")
+
+ [fix] = what_to_fix({"agents": agents}, run_dir=tmp_path, use_llm=False)
+
+ assert secret not in json.dumps(fix)
+ assert "<redacted>" in fix["what"]
+
+
+def test_goal_not_met_heading_counts_attempts_that_missed_the_goal() -> None:
+ result = {"agents": {"a": _agent({"c1": _case(True)}, {"c1": _case(False)})}}
+ fix = {"case": "c1", "kind": "goal not met", "scope": "a", "attempts_lost": 2, "what": "w", "action": "f"}
+ console = Console(record=True, width=120)
+
+ render_case_summary(result, console=console, fixes=[fix])
+
+ text = console.export_text()
+ assert "2 attempt(s) missed the goal" in text
+ assert "lost 2" not in text