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.

fix(tier3): end the rich progress table's line off a terminal, and find a case's trials by its recorded case (#668)

Narendran Raghavanc06b5fa9700f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20ddec9b..dfec0395 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1154,6 +1154,33 @@ All notable changes to SkillEvaluator are documented in this file.
folder, as it already did for a `SKILL.md`. With `--no-dedup`, this also holds
when the file is a symlink to a file with another name.
+- With `--progress rich` when standard error is not a terminal, such as when
+ it is redirected to a file or piped to another program, the Tier 3 progress
+ table now ends its last line. Before, the next output, such as a log line,
+ the shell prompt, or the line saying that progress stopped after a drawing
+ error, was printed on the same line as the table's bottom border. Output to
+ a terminal is unchanged.
+
+- The Tier 3 "How to improve" list now finds the failed attempts of a case
+ whose trial directory names do not start with its case ID: a native or NeMo
+ Gym task whose `[metadata] entry_id` differs from its directory, or a case
+ ID longer than the 32 characters Harbor keeps in a trial name. Before, such a
+ case's run error said only "1 attempt(s) never produced a score", with no
+ cause and no evidence file, and a failed judge got the generic run error
+ advice instead of the judge remedy. Each attempt's case is now the
+ `entry_id` the collector recorded in its `failure.json` or `reward.json`,
+ as for token usage. The case rows rebuilt for a failed arm use the same
+ case instead of the task directory, and the live case grid during a run
+ counts a long-named case's attempts in its own row instead of a second row
+ with the cut name.
+
+- With `--progress rich` and `TTY_INTERACTIVE=1` when standard error is not a
+ terminal, the Tier 3 progress table is now drawn once, when the run ends, as
+ it is without `TTY_INTERACTIVE`. Before, a copy of the table was also
+ printed under each plan line that changed during the run, and the next plan
+ line or table started on the same line as that copy's bottom border. Output
+ to a terminal is unchanged.
+
## 0.9.0 - 2026-11-13
### Fixed
diff --git a/src/skillevaluator/tier3/case_summary.py b/src/skillevaluator/tier3/case_summary.py
index e711d784..cc1bfcde 100644
--- a/src/skillevaluator/tier3/case_summary.py
+++ b/src/skillevaluator/tier3/case_summary.py
@@ -12,6 +12,7 @@ import re
import tempfile
from collections import Counter
from collections.abc import Callable, Mapping
+from contextvars import ContextVar
from difflib import SequenceMatcher
from itertools import islice
from pathlib import Path
@@ -27,6 +28,7 @@ from skillevaluator.reporting.terminal_styles import AMBER
from skillevaluator.tier3.attempt_verdict import attempt_verdict, scored_goal_accuracy
from skillevaluator.tier3.eval_core.checks import resolve_should_trigger
from skillevaluator.tier3.harbor.progress import redact_progress_detail, secret_values_from_environment
+from skillevaluator.tier3.harbor.report_data import _harbor_task_directory, _recorded_case_id
from skillevaluator.utils.redaction import redact_sensitive_text
from skillevaluator.utils.secret_redaction import Redactor
from skillevaluator.utils.secure_fs import SecurePathError, SecureRoot
@@ -167,17 +169,39 @@ def _case_comparable(agent: Mapping[str, Any], with_case: Any, without_case: Any
# ---------------------------------------------------------------- per-case data
+# The rows rebuilt for a failed condition while what_to_fix runs, by agent and condition. Rebuilding
+# reads every trial's files, and what_to_fix asks for an agent's rows several times for each case.
+_REBUILT_CASES: ContextVar[dict[tuple[int, str], tuple[Mapping[str, Any], Mapping[str, Any]]] | None] = ContextVar(
+ "_REBUILT_CASES", default=None
+)
+
+
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
+ rebuilt_cases = _REBUILT_CASES.get()
+ if rebuilt_cases is not None:
+ # The agent itself is kept with its rows, so a later agent that reuses its id gets no stale rows.
+ cached = rebuilt_cases.get((id(agent), key))
+ if cached is not None and cached[0] is agent:
+ return cached[1]
+ rebuilt = _rebuilt_cases(agent, key)
+ if rebuilt_cases is not None:
+ rebuilt_cases[(id(agent), key)] = (agent, rebuilt)
+ return rebuilt
+
+
+def _rebuilt_cases(agent: Mapping[str, Any], key: str) -> dict[str, dict[str, Any]]:
# 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")
+ _failed_trial_case_id(agent, key, str(f["trial"]))
+ 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():
@@ -186,6 +210,53 @@ def _cases(agent: Mapping[str, Any], key: str) -> Mapping[str, Any]:
return rebuilt
+def _trial_case_id(trial: Path, reward: Any) -> str:
+ """Return the case a persisted trial ran.
+
+ Harbor names a trial after the first 32 characters of its task directory.
+ So the name before ``__`` is not the case for a native or NeMo Gym task,
+ whose directory is not named after its case, or for a longer case ID. The
+ collector records the case it resolved from the task each attempt ran:
+ ``entry_id`` in ``failure.json`` for an unscored attempt and in
+ ``reward.json`` for a scored one, unless it rejected that reward's case.
+ The token usage report reads the same record. Without one, or for a run
+ from before that record, the case falls back to the task directory
+ the trial's ``result.json`` or ``config.json`` names, then to the name.
+ The caller has checked that ``trial`` is not reached through a link.
+ """
+ entry_id = reward.get("entry_id") if isinstance(reward, Mapping) and not _identity_rejected(reward) else None
+ return (
+ _recorded_case_id(trial)
+ or (entry_id if isinstance(entry_id, str) and entry_id.strip() else None)
+ or _harbor_task_directory(trial)
+ or trial.name.split("__", 1)[0]
+ )
+
+
+def _identity_rejected(reward: Mapping[str, Any]) -> bool:
+ """Return whether the collector refused this reward's case, so its ``entry_id`` names no case.
+
+ A trial stopped before Harbor wrote its ``result.json`` names no task the
+ collector can map to a case. The collector then fails the reward with this
+ reason and records the placeholder ``entry_id`` "unknown", which must not
+ move the trial away from the case its task directory or name gives.
+ """
+ from skillevaluator.tier3.harbor.collector import UNSAFE_REWARD_IDENTITY_REASON
+
+ errors = reward.get("evaluation_errors")
+ return isinstance(errors, Mapping) and errors.get("collector") == UNSAFE_REWARD_IDENTITY_REASON
+
+
+def _failed_trial_case_id(agent: Mapping[str, Any], key: str, trial: str) -> str:
+ """Return the case of a trial the collector listed as failed, read from the trial's persisted directory."""
+ output_dir = agent.get("output_dir")
+ agent_dir = Path(str(output_dir)) if output_dir else None
+ path = _trial_dir(agent_dir.parent, agent_dir.name, dict(_VARIANTS)[key], trial) if agent_dir else None
+ if path is None:
+ return trial.split("__", 1)[0]
+ return _trial_case_id(path, _load_json(path / "reward.json", root=agent_dir))
+
+
def _evaluation_failed(reward: Any) -> bool:
return isinstance(reward, Mapping) and str(reward.get("evaluation_status") or "").casefold() in {"error", "failed"}
@@ -252,14 +323,15 @@ def _scored_trials(agent: Mapping[str, Any], key: str) -> dict[str, dict[str, An
)
cases: dict[str, dict[str, Any]] = {}
for trial in sorted(trials.iterdir()):
+ # Only a trial whose reward this read returned has its case read, and this read never follows a link.
reward = _load_json(trial / "reward.json", root=Path(str(output_dir)))
if _evaluation_failed(reward):
- case = cases.setdefault(trial.name.split("__", 1)[0], {"attempts": []})
+ case = cases.setdefault(_trial_case_id(trial, reward), {"attempts": []})
case["attempts_missing"] = case.get("attempts_missing", 0) + 1
continue
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 = cases.setdefault(_trial_case_id(trial, reward), {"attempts": []})["attempts"]
verdict = attempt_verdict(
score,
threshold,
@@ -959,6 +1031,19 @@ def _run_error(trial_dir: Path, run_dir: Path) -> str:
return _short(f"{error.get('type', 'error')}: {detail}", 160)
+def _trials_by_case(run_dir: Path, agent: str) -> dict[str, list[Path]]:
+ """Group an agent's with-skill trial directories by the case each one ran."""
+ trials = run_dir / agent / "with-skill" / "trials"
+ by_case: dict[str, list[Path]] = {}
+ if not _SAFE_TRIAL.fullmatch(agent) or not trials.is_dir():
+ return by_case
+ for candidate in sorted(trials.iterdir()):
+ if (trial := _trial_dir(run_dir, agent, "with-skill", candidate.name)) is not None:
+ reward = _load_json(trial / "reward.json", root=run_dir)
+ by_case.setdefault(_trial_case_id(trial, reward), []).append(trial)
+ return by_case
+
+
def _diagnose_agent_case(
run_dir: Path,
agent_name: str,
@@ -966,23 +1051,26 @@ def _diagnose_agent_case(
case_id: str,
*,
entry: Mapping[str, Any] | None = None,
+ trials_by_agent: dict[str, dict[str, list[Path]]] | None = None,
) -> 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)
+ case_trials: list[Path] = []
+ if errors:
+ # A trial's name need not start with its case, so each trial's case is read from its records:
+ # once per agent when the caller shares trials_by_agent across cases.
+ trials_by_agent = {} if trials_by_agent is None else trials_by_agent
+ if agent_name not in trials_by_agent:
+ trials_by_agent[agent_name] = _trials_by_case(run_dir, agent_name)
+ case_trials = trials_by_agent[agent_name].get(case_id, [])
failed_evaluations: dict[str, list[tuple[Path, str]]] = {}
- with_trials = run_dir / agent_name / "with-skill" / "trials"
- if errors and with_trials.is_dir() and _SAFE_TRIAL.fullmatch(agent_name):
- for d in sorted(with_trials.iterdir()):
- if (
- d.name.split("__", 1)[0] == case_id
- and _trial_dir(run_dir, agent_name, "with-skill", d.name) is not None
- and _evaluation_failed(reward := _load_json(d / "reward.json", root=run_dir))
- ):
- cause, reason = _evaluation_failure(reward)
- failed_evaluations.setdefault(cause, []).append((d, reason))
+ for d in case_trials:
+ if _evaluation_failed(reward := _load_json(d / "reward.json", root=run_dir)):
+ cause, reason = _evaluation_failure(reward)
+ failed_evaluations.setdefault(cause, []).append((d, reason))
evaluation_issues = []
for cause, failed in failed_evaluations.items():
lost_unscored = min(errors, len(failed))
@@ -1017,16 +1105,7 @@ def _diagnose_agent_case(
failed_trials.extend(
(attempt.get("score"), d) for d in _trial_dirs(run_dir, agent_name, attempt.get("trial"))
)
- 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 _trial_dir(run_dir, agent_name, "with-skill", d.name) is not None
- and (d / "failure.json").is_file()
- ]
+ errored_trials = [d for d in case_trials if (d / "failure.json").is_file()] if errors else []
lost = (wn - wp) + errors
hurts = (
@@ -1289,6 +1368,17 @@ 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."""
+ # A failed condition's rows are rebuilt from its trials once for this call, not for every case.
+ rebuilt_cases = _REBUILT_CASES.set({})
+ try:
+ return _what_to_fix(result, run_dir=run_dir, skill_path=skill_path, use_llm=use_llm)
+ finally:
+ _REBUILT_CASES.reset(rebuilt_cases)
+
+
+def _what_to_fix(
+ result: Mapping[str, Any], *, run_dir: Path, skill_path: Path | None, use_llm: bool
+) -> list[dict[str, Any]]:
agents = {
str(k): dict(v, attempt_policy=result.get("attempt_policy") or v.get("attempt_policy"))
for k, v in (result.get("agents") or {}).items()
@@ -1296,9 +1386,12 @@ def what_to_fix(
}
dataset = _dataset_entries(run_dir)
grouped: dict[tuple[str, str, str | None], list[dict[str, Any]]] = {}
+ trials_by_agent: dict[str, dict[str, list[Path]]] = {}
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, entry=dataset.get(case_id, {})):
+ for issue in _diagnose_agent_case(
+ run_dir, name, agent, case_id, entry=dataset.get(case_id, {}), trials_by_agent=trials_by_agent
+ ):
grouped.setdefault((case_id, issue["kind"], issue.get("cause")), []).append(issue)
issues = []
for items in grouped.values():
@@ -1526,10 +1619,13 @@ def live_case_marks(
for trial in islice(sorted(job.iterdir()), _MAX_TRIAL_PATHS_SCANNED):
if "__" not in trial.name or not _SAFE_TRIAL.match(trial.name) or trial.is_symlink():
continue
- case_id = trial.name.split("__", 1)[0]
if (agent, key, trial.name) in seen or not trial.is_dir():
continue
seen.add((agent, key, trial.name))
+ # Staged cases are keyed by task directory, but Harbor names a trial after only the
+ # directory's first 32 characters; the config Harbor writes as the trial starts names it whole.
+ task = _harbor_task_directory(trial)
+ case_id = task if task and _SAFE_TRIAL.fullmatch(task) else trial.name.split("__", 1)[0]
mark = _live_mark(trial, run_dir, pass_threshold)
case = marks.setdefault(agent, {}).setdefault(key, {}).setdefault(case_id, [])
if mark is None:
diff --git a/src/skillevaluator/tier3/harbor/progress.py b/src/skillevaluator/tier3/harbor/progress.py
index 3dea4abf..814769fe 100644
--- a/src/skillevaluator/tier3/harbor/progress.py
+++ b/src/skillevaluator/tier3/harbor/progress.py
@@ -438,6 +438,15 @@ class RichProgressReporter(PlainProgressReporter):
from rich.live import Live
self._console = Console(file=self._stream)
+ if not self._console.is_terminal:
+ # TTY_INTERACTIVE=1 makes Rich treat a pipe or a file as
+ # interactive, and Live then draws a whole frame under every line
+ # printed while it runs. Off a terminal Rich drops the cursor moves
+ # that would erase those frames, so they all stay, each with its
+ # last line open, and the next plan line or frame joins its bottom
+ # border. Live then draws only its last frame, as it stops, the same
+ # as on any other stream that is not a terminal.
+ self._console.is_interactive = False
self._live_factory = Live
self._live = None
self._live_plan: Tier3RunPlan | None = None
@@ -503,7 +512,7 @@ class RichProgressReporter(PlainProgressReporter):
# height, so it lists every stage in full.
live.update(self._build_live_table(final=True), refresh=False)
finally:
- live.stop()
+ self._stop_live(live)
elif (
after_failure
and self._live is None
@@ -539,6 +548,24 @@ class RichProgressReporter(PlainProgressReporter):
# notice, belongs to no later run on this reporter.
self._drop_refused_writes()
+ def _stop_live(self, live) -> None:
+ """Stop Live, leaving its last frame on lines of its own."""
+ if self._console.is_terminal or not getattr(live, "is_started", False):
+ # On a terminal Live ends the frame's last line itself when it
+ # stops. Live that never started, or already stopped, writes
+ # nothing here.
+ live.stop()
+ return
+ # Elsewhere, as with --progress rich on a pipe or a file, Live draws
+ # the frame as it stops and leaves the frame's last line open. The
+ # next output, such as a log line, the stop notice or the shell
+ # prompt, would then join the frame's bottom border. The line end
+ # goes out in the same write as the frame, so a stream that keeps a
+ # refused frame keeps its line end too.
+ with self._console:
+ live.stop()
+ self._console.line()
+
def _stop_live_after_failure(self, live) -> None:
"""Stop the live view after a drawing failure and say that the run goes on.
@@ -559,7 +586,7 @@ class RichProgressReporter(PlainProgressReporter):
notice_alone = live is None or bool(getattr(live, "is_started", False))
if live is not None:
try:
- live.stop()
+ self._stop_live(live)
except Exception:
# A terminal that refused the redraw can refuse Live's stop too,
# and with it the write that shows the cursor again.
@@ -630,7 +657,12 @@ class RichProgressReporter(PlainProgressReporter):
try:
if failed_stop.stop_refused:
# Live hides the cursor while it draws and shows it again when
- # it stops, then ends the frame's last line.
+ # it stops, then ends the frame's last line. On a console that
+ # is not a terminal Live drew nothing before that stop, and the
+ # refused stop carried the frame's line end with it, so a
+ # stream that kept the whole stop, or none of it, leaves no
+ # line open. Only a stream buffer already nearly full would
+ # keep part of it.
line_ended = not self._console.is_terminal
self._console.show_cursor(True)
if self._console.is_terminal:
diff --git a/tests/test_tier3_case_summary.py b/tests/test_tier3_case_summary.py
index 230b223b..2150c5a7 100644
--- a/tests/test_tier3_case_summary.py
+++ b/tests/test_tier3_case_summary.py
@@ -1074,6 +1074,209 @@ def test_failed_condition_rebuilds_case_rows_from_trial_rewards(tmp_path: Path)
assert "1/1 ✓ (0.90)" in output and "0/1 ✗ (0.30)" in output and "⊘" in output
+# Harbor names a trial after the first 32 characters of its task directory, so a trial's name need not
+# start with its case: a native task keeps its own directory name, and a longer case ID is cut.
+_LONG_CASE = "convert-quarterly-report-to-markdown-table"
+_TIMEOUT = {"error": {"type": "AgentTimeoutError", "message": "900s"}}
+_JUDGE_FAILED = {
+ "overall": 0.0,
+ "evaluation_status": "failed",
+ "evaluation_errors": {"accuracy": "Judge reply was empty"},
+}
+
+
+def _trial_records(trials: Path, name: str, records: dict[str, dict]) -> Path:
+ trial = trials / name
+ trial.mkdir(parents=True)
+ for file_name, payload in records.items():
+ (trial / file_name).write_text(json.dumps(payload))
+ return trial
+
+
+ ("case_id", "trial_name", "records"),
+ [
+ ("case-alpha", "native-task-a__AbC1234", {"failure.json": {**_TIMEOUT, "entry_id": "case-alpha"}}),
+ (_LONG_CASE, f"{_LONG_CASE[:32]}__AbC1234", {"failure.json": {**_TIMEOUT, "entry_id": _LONG_CASE}}),
+ # A run from before failure.json named the case: the trial's config names the whole task directory.
+ (
+ _LONG_CASE,
+ f"{_LONG_CASE[:32]}__AbC1234",
+ {"failure.json": _TIMEOUT, "config.json": {"task": {"path": f"/run/_harbor-tasks/a/with/{_LONG_CASE}"}}},
+ ),
+ ],
+ ids=["native-task", "long-case-id", "long-case-id-without-recorded-case"],
+)
+def test_run_error_is_found_for_a_trial_whose_name_does_not_start_with_its_case(
+ tmp_path: Path, case_id: str, trial_name: str, records: dict
+) -> None:
+ _trial_records(tmp_path / "a" / "with-skill" / "trials", trial_name, records)
+
+ [fix] = what_to_fix({"agents": {"a": _agent({case_id: _case(missing=1)}, {})}}, run_dir=tmp_path, use_llm=False)
+
+ assert (fix["case"], fix["kind"]) == (case_id, "run error")
+ assert fix["what"] == "1 attempt(s) never produced a score: AgentTimeoutError: 900s"
+ assert fix["evidence"] == f"a/with-skill/trials/{trial_name}/failure.json"
+
+
+def test_judge_failure_of_a_native_task_gets_judge_advice_under_the_case_the_collector_recorded(
+ tmp_path: Path,
+) -> None:
+ # The judge's own entry_id is not authoritative; the collector's record in failure.json is.
+ _trial_records(
+ tmp_path / "a" / "with-skill" / "trials",
+ "native-task-a__AbC1234",
+ {
+ "reward.json": {**_JUDGE_FAILED, "entry_id": "native-task-a"},
+ "failure.json": {"status": "unscored", "evaluation_status": "failed", "entry_id": "case-alpha"},
+ },
+ )
+
+ [fix] = what_to_fix(
+ {"agents": {"a": _agent({"case-alpha": _case(missing=1)}, {})}}, run_dir=tmp_path, use_llm=False
+ )
+
+ assert (fix["case"], fix["kind"], fix.get("cause")) == ("case-alpha", "run error", "judge")
+ assert "Judge reply was empty" in fix["what"]
+ assert "judge model configuration" in fix["action"]
+ assert fix["evidence"] == "a/with-skill/trials/native-task-a__AbC1234/reward.json"
+
+
+def test_failed_condition_rebuilds_native_task_rows_under_the_case_the_collector_recorded(tmp_path: Path) -> None:
+ from skillevaluator.tier3.case_summary import ERROR, PASS, _cases, _marks
+
+ trials = tmp_path / "a" / "with-skill" / "trials"
+ _trial_records(trials, "native-task-a__pass", {"reward.json": {"overall": 0.9, "entry_id": "case-alpha"}})
+ _trial_records(
+ trials,
+ "native-task-a__judge",
+ {"reward.json": _JUDGE_FAILED, "failure.json": {"evaluation_status": "failed", "entry_id": "case-alpha"}},
+ )
+ _trial_records(trials, "native-task-a__timeout", {"failure.json": {**_TIMEOUT, "entry_id": "case-alpha"}})
+ agent = _agent({}, {})
+ agent.update(
+ output_dir=str(tmp_path / "a"),
+ trial_failures={
+ "with_skill": [
+ {"trial": "native-task-a__judge", "reason": "Required judge evaluation failed"},
+ {"trial": "native-task-a__timeout", "reason": "Agent timed out"},
+ ]
+ },
+ )
+
+ assert {case: _marks(row) for case, row in _cases(agent, "with_skill").items()} == {
+ "case-alpha": [PASS, ERROR, ERROR]
+ }
+ fixes = what_to_fix({"agents": {"a": agent}}, run_dir=tmp_path, use_llm=False)
+ assert sorted((f["case"], f["kind"], f.get("cause") or "") for f in fixes) == [
+ ("case-alpha", "run error", ""),
+ ("case-alpha", "run error", "judge"),
+ ]
+
+
+def test_failed_condition_rows_are_rebuilt_once_per_what_to_fix_call(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ from skillevaluator.tier3 import case_summary
+
+ # A failed condition with several cases, each with one scored attempt and one that timed out.
+ trials = tmp_path / "a" / "with-skill" / "trials"
+ failed = []
+ for index in range(4):
+ case_id = f"case-{index}"
+ _trial_records(trials, f"native-{index}__pass", {"reward.json": {"overall": 0.9, "entry_id": case_id}})
+ _trial_records(trials, f"native-{index}__timeout", {"failure.json": {**_TIMEOUT, "entry_id": case_id}})
+ failed.append({"trial": f"native-{index}__timeout", "reason": "Agent timed out"})
+ agent = _agent({}, {})
+ agent.update(output_dir=str(tmp_path / "a"), trial_failures={"with_skill": failed})
+ rebuilds: list[str] = []
+ rebuild = case_summary._rebuilt_cases
+
+ def counted(agent: object, key: str) -> object:
+ rebuilds.append(key)
+ return rebuild(agent, key)
+
+ monkeypatch.setattr(case_summary, "_rebuilt_cases", counted)
+
+ fixes = what_to_fix({"agents": {"a": agent}}, run_dir=tmp_path, use_llm=False)
+
+ # Rebuilding reads every trial's files, so each failed condition is rebuilt once for the whole
+ # call rather than again for each of its cases.
+ assert [fix["case"] for fix in fixes] == ["all 4 cases"]
+ assert sorted(rebuilds) == ["with_skill", "without_skill"]
+ # The next call reads the trials again: they can change between calls.
+ what_to_fix({"agents": {"a": agent}}, run_dir=tmp_path, use_llm=False)
+ assert sorted(rebuilds) == ["with_skill", "with_skill", "without_skill", "without_skill"]
+
+
+ "records",
+ [{}, {"config.json": {"task": {"path": "/run/_harbor-tasks/a/with/plain-case"}}}],
+ ids=["no-harbor-files", "config-written-at-trial-start"],
+)
+def test_trial_whose_reward_identity_the_collector_rejected_keeps_its_own_case(tmp_path: Path, records: dict) -> None:
+ from skillevaluator.tier3.case_summary import _cases
+ from skillevaluator.tier3.harbor.collector import UNSAFE_REWARD_IDENTITY_REASON
+
+ # A trial stopped before Harbor wrote result.json names no task the collector can map to a case, so
+ # the collector rejects its reward and records the placeholder entry_id "unknown", which is no case.
+ rejected = {
+ "overall": 0.9,
+ "evaluation_status": "failed",
+ "evaluation_errors": {"collector": UNSAFE_REWARD_IDENTITY_REASON},
+ "entry_id": "unknown",
+ }
+ trial = "plain-case__Zx81kQa"
+ _trial_records(tmp_path / "a" / "with-skill" / "trials", trial, {"reward.json": rejected, **records})
+ failed_arm = _agent({}, {})
+ failed_arm.update(
+ output_dir=str(tmp_path / "a"),
+ trial_failures={"with_skill": [{"trial": trial, "reason": "Required judge evaluation failed"}]},
+ )
+ scored_arm = _agent({"plain-case": _case(missing=1)}, {})
+
+ assert set(_cases(failed_arm, "with_skill")) == {"plain-case"}
+ for agent in (failed_arm, scored_arm):
+ [fix] = what_to_fix({"agents": {"a": agent}}, run_dir=tmp_path, use_llm=False)
+ assert (fix["case"], fix["kind"], fix.get("cause")) == ("plain-case", "run error", "collector")
+ assert fix["evidence"] == f"a/with-skill/trials/{trial}/reward.json"
+
+
+def test_recorded_case_is_not_read_through_a_link(tmp_path: Path) -> None:
+ from skillevaluator.tier3.case_summary import _cases
+
+ # A link to a trial directory, or to its failure.json, must not move the trial to another case.
+ outside = tmp_path / "outside"
+ _trial_records(outside, "dir", {"failure.json": {**_TIMEOUT, "entry_id": "outside-case"}})
+ (outside / "failure.json").write_text(json.dumps({"entry_id": "outside-case"}))
+ trials = tmp_path / "run" / "a" / "with-skill" / "trials"
+ judged = _trial_records(trials, "t__judge", {"reward.json": _JUDGE_FAILED})
+ (judged / "failure.json").symlink_to(outside / "failure.json")
+ (trials / "t__link").symlink_to(outside / "dir", target_is_directory=True)
+ agent = _agent({}, {})
+ agent.update(output_dir=str(tmp_path / "run" / "a"), trial_failures={"with_skill": [{"trial": "t__link"}]})
+
+ assert set(_cases(agent, "with_skill")) == {"t"}
+
+
+def test_live_marks_key_a_trial_by_its_whole_task_directory(tmp_path: Path) -> None:
+ from skillevaluator.tier3.case_summary import PASS, live_case_marks
+
+ staged = tmp_path / "_harbor-tasks" / "a" / "with" / _LONG_CASE
+ staged.mkdir(parents=True)
+ jobs = tmp_path / "_harbor-jobs" / "job-a-with"
+ done = {"finished_at": "t", "verifier_result": {"rewards": {"overall": 0.9}}}
+ config = {"task": {"path": str(staged)}}
+ _trial_records(jobs, f"{_LONG_CASE[:32]}__AbC1234", {"config.json": config, "result.json": done})
+ # Harbor writes config.json as the trial starts, before any result.
+ _trial_records(jobs, f"{_LONG_CASE[:32]}__DeF5678", {"config.json": config})
+
+ marks, running = live_case_marks(tmp_path, ["a"])
+
+ assert marks == {"a": {"with_skill": {_LONG_CASE: [PASS]}}}
+ assert running == {("a", "with_skill", _LONG_CASE)}
+
+
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"):
diff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.py
index 3782c975..c5c293c7 100644
--- a/tests/test_tier3_progress.py
+++ b/tests/test_tier3_progress.py
@@ -5,6 +5,7 @@
from __future__ import annotations
+import dataclasses
import errno
import importlib
import io
@@ -2082,6 +2083,256 @@ def test_late_notice_starts_a_line_when_the_stream_sent_a_cut_refused_frame(
assert output.endswith(f"\n{_LATE_STOP_NOTICE}\n")
+class _WouldBlockPipe(io.RawIOBase):
+ """A pipe another process made non-blocking, such as standard error piped to a slow reader."""
+
+ def __init__(self) -> None:
+ super().__init__()
+ self.received = bytearray()
+ # While set, the reader is behind and every write would block.
+ self.full = False
+ # Refuses the first write that carries each of these, in order.
+ self.refuse_once: list[bytes] = []
+
+ def writable(self) -> bool:
+ return True
+
+ def isatty(self) -> bool:
+ return False
+
+ def write(self, data: Any) -> int | None:
+ chunk = bytes(data)
+ if self.full:
+ # What a raw write returns for EAGAIN.
+ return None
+ if self.refuse_once and self.refuse_once[0] in chunk:
+ self.refuse_once.pop(0)
+ return None
+ self.received += chunk
+ return len(chunk)
+
+
+def _stderr_shaped(raw: io.RawIOBase) -> io.TextIOWrapper:
+ # Standard error as the CLI passes it: its buffer keeps what the reader
+ # refused and sends it with the next write. The buffer size is that of
+ # Python 3.12 and 3.13, set so that the test does not depend on the
+ # Python version's default.
+ return io.TextIOWrapper(
+ io.BufferedWriter(raw, buffer_size=8192), encoding="utf-8", newline="\n", line_buffering=True
+ )
+
+
+def _bottom_right_corner(console: Any) -> str:
+ # The progress table's box is ROUNDED, but Rich draws it SQUARE on a
+ # legacy Windows console, so its last line ends with "┘" there.
+ from rich import box
+
+ return box.ROUNDED.substitute(console.options).bottom_right
+
+
+ "stream_kind",
+ ["text-stream", "stderr-shaped-pipe", "pipe-full-at-close"],
+ ids=["text-stream", "stderr-shaped-pipe", "pipe-full-when-the-run-ends"],
+)
+def test_forced_rich_progress_on_a_stream_that_is_not_a_terminal_ends_the_final_frame_line(
+ monkeypatch: pytest.MonkeyPatch,
+ stream_kind: str,
+) -> None:
+ progress = _progress_module()
+ # --progress rich with standard error piped to a file or another program.
+ # Nothing in the environment makes Rich treat that stream as a terminal.
+ monkeypatch.delenv("FORCE_COLOR", raising=False)
+ monkeypatch.delenv("TTY_COMPATIBLE", raising=False)
+ pipe = _WouldBlockPipe()
+ stream = io.StringIO() if stream_kind == "text-stream" else _stderr_shaped(pipe)
+ rich_reporter = progress.create_progress_reporter("rich", stream=stream, refresh_interval=60)
+ assert isinstance(rich_reporter, progress.RichProgressReporter)
+ assert rich_reporter._console.is_terminal is False
+ reporter = progress.safe_progress_reporter(rich_reporter)
+ reporter.start(_plan(progress))
+ reporter.emit(progress.ProgressEvent(stage="agent:codex", state="running", detail="evaluating"))
+ reporter.emit(progress.ProgressEvent(stage="agent:codex", state="complete", detail="agent finished"))
+ # The reader can be behind when the run ends. The stream then keeps the
+ # final frame and sends it with the next write.
+ pipe.full = stream_kind == "pipe-full-at-close"
+ reporter.close()
+ pipe.full = False
+ # The caller prints its results after the progress view.
+ stream.write("Result: pass\n")
+ stream.flush()
+ output = stream.getvalue() if isinstance(stream, io.StringIO) else pipe.received.decode("utf-8")
+
+ # Off a terminal, Live draws the frame once, as it stops. Its last line
+ # ends there, once, so the next line is neither joined to the frame's
+ # bottom border nor left after a blank line.
+ corner = _bottom_right_corner(rich_reporter._console)
+ assert output.count(corner) == 1
+ assert output.endswith(f"{corner}\nResult: pass\n")
+
+
+ ("pipe_state", "notice"),
+ [
+ # The pipe refuses the changed plan line, then takes Live's stop and
+ # the notice under the frame.
+ ("plan-line-refused", _STOP_NOTICE),
+ # It also refuses the notice. The stream keeps the notice and sends it
+ # when the run ends, in place of the late one.
+ ("plan-line-and-notice-refused", _STOP_NOTICE),
+ # It is full from the changed plan line until the run ends. The stream
+ # keeps Live's stop, and the late notice follows it.
+ ("full-until-the-run-ends", _LATE_STOP_NOTICE),
+ ],
+ ids=["plan-line-refused", "plan-line-and-notice-refused", "full-until-the-run-ends"],
+)
+def test_forced_rich_stop_notice_on_a_pipe_starts_a_line_below_the_frame(
+ pipe_state: str,
+ notice: str,
+) -> None:
+ from rich.console import Console
+
+ progress = _progress_module()
+ pipe = _WouldBlockPipe()
+ stream = _stderr_shaped(pipe)
+ rich_reporter = progress.RichProgressReporter(stream=stream, refresh_interval=60)
+ rich_reporter._console = Console(
+ file=stream,
+ force_terminal=False,
+ legacy_windows=False,
+ width=120,
+ color_system=None,
+ )
+ reporter = progress.safe_progress_reporter(rich_reporter)
+ reporter.start(_plan(progress))
+ reporter.emit(progress.ProgressEvent(stage="agent:codex", state="running", detail="evaluating"))
+ # Off a terminal, Live draws nothing while the run goes on, so the first
+ # write that can fail is a plan line that changed.
+ if pipe_state == "full-until-the-run-ends":
+ pipe.full = True
+ else:
+ pipe.refuse_once = [b"Run plan: Tasks 3"]
+ if pipe_state == "plan-line-and-notice-refused":
+ pipe.refuse_once.append(_STOP_NOTICE.encode("utf-8"))
+ reporter.start(dataclasses.replace(_plan(progress), task_count=3))
+ assert reporter.is_active is False
+ reporter.close()
+ # The pipe takes whatever the stream still holds once the run is over.
+ pipe.full = False
+ stream.flush()
+ output = pipe.received.decode("utf-8")
+
+ # Live drew its frame once, as it stopped, and one stop notice is a line
+ # of its own under it instead of joining the frame's bottom border.
+ assert output.count("Tier 3 progress display stopped after a drawing error") == 1
+ assert output.endswith(f"╯\n{notice}\n")
+ assert pipe.refuse_once == []
+
+
[email protected]("term", ["xterm-256color", "dumb"], ids=["terminal", "dumb-terminal"])
+def test_rich_progress_on_a_terminal_still_ends_the_final_frame_line_once(
+ monkeypatch: pytest.MonkeyPatch,
+ term: str,
+) -> None:
+ from rich.console import Console
+
+ progress = _progress_module()
+ monkeypatch.setenv("TERM", term)
+ stream = _TTYBuffer()
+ rich_reporter = progress.RichProgressReporter(stream=stream, refresh_interval=60)
+ rich_reporter._console = Console(
+ file=stream,
+ force_terminal=True,
+ legacy_windows=False,
+ width=120,
+ color_system=None,
+ )
+ assert rich_reporter._console.is_dumb_terminal is (term == "dumb")
+ rich_reporter.start(_plan(progress))
+ rich_reporter.emit(progress.ProgressEvent(stage="agent:codex", state="running", detail="evaluating"))
+ rich_reporter.emit(progress.ProgressEvent(stage="agent:codex", state="complete", detail="agent finished"))
+ rich_reporter.close()
+ stream.write("Result: pass\n")
+
+ # On a terminal, a dumb one included, Live ends the frame's last line
+ # itself when it stops, then shows the cursor where the terminal takes
+ # cursor writes. No second line end follows.
+ show_cursor = "" if term == "dumb" else "\x1b[?25h"
+ assert stream.getvalue().endswith(f"╯\n{show_cursor}Result: pass\n")
+
+
+ "stream_kind",
+ ["text-stream", "stderr-shaped-pipe", "plan-line-refused"],
+ ids=["text-stream", "stderr-shaped-pipe", "pipe-refuses-the-changed-plan-line"],
+)
+def test_forced_rich_progress_on_an_interactive_pipe_draws_only_the_final_frame(
+ monkeypatch: pytest.MonkeyPatch,
+ stream_kind: str,
+) -> None:
+ progress = _progress_module()
+ # --progress rich with standard error piped, and TTY_INTERACTIVE=1, which
+ # asks Rich for live updates although the stream is not a terminal.
+ monkeypatch.delenv("FORCE_COLOR", raising=False)
+ monkeypatch.delenv("TTY_COMPATIBLE", raising=False)
+ monkeypatch.setenv("TTY_INTERACTIVE", "1")
+ pipe = _WouldBlockPipe()
+ stream = io.StringIO() if stream_kind == "text-stream" else _stderr_shaped(pipe)
+ rich_reporter = progress.create_progress_reporter("rich", stream=stream, refresh_interval=60)
+ assert isinstance(rich_reporter, progress.RichProgressReporter)
+ assert rich_reporter._console.is_terminal is False
+ reporter = progress.safe_progress_reporter(rich_reporter)
+ reporter.start(_plan(progress))
+ reporter.emit(progress.ProgressEvent(stage="agent:codex", state="running", detail="evaluating"))
+ if stream_kind == "plan-line-refused":
+ pipe.refuse_once = [b"Run plan: Tasks 3"]
+ # A plan line that changes during the run is printed while Live runs.
+ reporter.start(dataclasses.replace(_plan(progress), task_count=3))
+ reporter.emit(progress.ProgressEvent(stage="agent:codex", state="complete", detail="agent finished"))
+ reporter.close()
+ stream.write("Result: pass\n")
+ stream.flush()
+ output = stream.getvalue() if isinstance(stream, io.StringIO) else pipe.received.decode("utf-8")
+
+ # Off a terminal the frames drawn under printed lines could not be erased,
+ # so none is drawn: Live draws its frame once, as it stops. The changed
+ # plan line is a line of its own above it, and the frame's last line ends
+ # once before the next output.
+ corner = _bottom_right_corner(rich_reporter._console)
+ assert output.count(corner) == 1
+ assert "\nRun plan: Tasks 3 · " in output
+ if stream_kind == "plan-line-refused":
+ assert output.count("Tier 3 progress display stopped after a drawing error") == 1
+ assert output.endswith(f"{corner}\n{_STOP_NOTICE}\nResult: pass\n")
+ else:
+ assert output.endswith(f"{corner}\nResult: pass\n")
+
+
+ ("tty_interactive", "interactive"),
+ [(None, True), ("1", True), ("0", False)],
+ ids=["default", "tty-interactive-1", "tty-interactive-0"],
+)
+def test_rich_progress_on_a_terminal_keeps_rich_interactive_setting(
+ monkeypatch: pytest.MonkeyPatch,
+ tty_interactive: str | None,
+ interactive: bool,
+) -> None:
+ progress = _progress_module()
+ monkeypatch.setenv("TERM", "xterm-256color")
+ monkeypatch.delenv("FORCE_COLOR", raising=False)
+ monkeypatch.delenv("TTY_COMPATIBLE", raising=False)
+ if tty_interactive is not None:
+ monkeypatch.setenv("TTY_INTERACTIVE", tty_interactive)
+ rich_reporter = progress.create_progress_reporter("rich", stream=_TTYBuffer(), refresh_interval=60)
+
+ # Only a stream that is not a terminal is kept from redrawing in place. On
+ # a terminal Live still redraws the frame unless TTY_INTERACTIVE=0 says not
+ # to.
+ assert rich_reporter._console.is_terminal is True
+ assert rich_reporter._console.is_interactive is interactive
+
+
def test_changelog_says_a_stream_can_still_send_refused_output_later() -> None:
# close() drops only the view's own copy of what the terminal refused. A
# stream shaped like standard error keeps its copy and sends it with its