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): compare a run against a prior skill version (#387)

Christopher Kevinb61b1ef749d2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1bece060..edff1e18 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,10 @@ All notable changes to SkillEvaluator are documented in this file.
- Tier 3 datasets can declare deterministic behavior checks for script invocation and success, workspace files, and final-response text.
+- Tier 3 `evaluate --compare-to RUN` and read-only `compare-versions` compare
+ compatible retained skill versions, report paired per-agent deltas and
+ regressions, and keep version comparisons separate from no-skill Skill Lift.
+
- Read-only Tier 3 `history` lists retained Skill Lift runs chronologically,
separates incompatible configurations into segments, preserves unavailable
lift as missing, and exports JSON, CSV, or Markdown summaries.
diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdx
index e0e0bbee..744d0c71 100644
--- a/docs/cli-reference.mdx
+++ b/docs/cli-reference.mdx
@@ -32,6 +32,7 @@ commands referenced below.
| [similarity-check](#similarity-check) | Detect duplicate content across a collection | Embeddings provider key |
| [tier3 evaluate](#tier3-evaluate) | Run Tier 3 live agent evaluation | Provider key plus a credential the selected agents can use (one `NVIDIA_API_KEY` covers both on NVIDIA Build), backend (Docker by default) |
| [tier3 select-decoys](#tier3-select-decoys) | Save a reproducible set of neighboring skills for group evaluation | Local description-embedding catalog, skill collection, embeddings provider key |
+| [tier3 compare-versions](#tier3-compare-versions) | Compare current and prior retained with-skill scores without writes | Two compatible retained runs |
| [create-eval-dataset](#create-eval-dataset) | Generate synthetic eval datasets | LLM provider key (none with `--no-llm`) |
| [init-custom-grader](#init-custom-grader) | Scaffold a bring-your-own-grader starter | Nothing |
| [init-harbor-task](#init-harbor-task) | Scaffold a bring-your-own-task Harbor starter | Nothing |
@@ -520,6 +521,23 @@ without contacting the embedding provider. See
[Select a reproducible decoy set](agents-and-sandboxes.mdx#select-a-reproducible-decoy-set)
for a complete example and the limits of similarity-based selection.
+## tier3 compare-versions
+
+```bash
+skillevaluator tier3 compare-versions ./my-skill --current CURRENT --prior PRIOR --results-dir ./results --json
+```
+
+Read-only comparison of two retained runs; no agent execution, credentials,
+or artifact writes. Without `--json`, prints the prior/current score table.
+Unavailable comparisons print reasons and exit nonzero.
+
+| Flag | Default | Effect |
+| --- | --- | --- |
+| `--current RUN` | required | Current retained run id, or `latest` completed run. |
+| `--prior RUN` | required | Prior retained run id, or `latest` eligible different skill revision. |
+| `--results-dir DIRECTORY` | normal results-root resolution | External results root containing the per-skill directory. |
+| `--json` | off | Print the complete comparison block as JSON. |
+
## tier3 evaluate
Run Tier 3 live agent evaluation: real agents attempt your eval cases with and without the skill, and the difference becomes Skill Lift. Requires the `tier3` extra, a provider key for grading, a credential the selected agents can use — with NVIDIA Build in `--env-mode docker`, `kata`, or `local`, the one `NVIDIA_API_KEY` covers both roles — and a running backend (Docker by default). The full walkthrough is [Tier 3: Live Evaluation](tier3-live-evaluation.mdx).
@@ -541,6 +559,7 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing
| `--skip-baseline` | off | Skip the without-skill baseline (no lift analysis, faster). |
| `--skip-with-skill` | off | Run only the without-skill baseline, for example to calibrate a task set or measure a model change before running the skill. The report is marked baseline-only: the overall score is the baseline score, with-skill and lift are unavailable (shown as `skipped` or N/A, never 0.0), and no skill verdict is given. Mutually exclusive with `--skip-baseline`. Not available on `validate`. |
| `--reuse-baseline RUN` | off | Reuse a compatible fresh without-skill baseline from a retained run id in the same results root, or `latest`. An incompatible explicit id fails before execution; `latest` falls back to a fresh baseline. Mutually exclusive with `--skip-baseline` and `--skip-with-skill`. |
+| `--compare-to RUN` | off | Compare with-skill scores to a compatible retained run. `latest` selects the newest eligible different skill revision, or records an unavailable comparison and continues. An incompatible explicit id fails before execution. Mutually exclusive with `--skip-with-skill`. Independent of no-skill Skill Lift. |
| `--n-attempts INTEGER` | unset | Attempts per eval case (pass@k). |
| `--pass-threshold FLOAT` | unset | Score threshold (0.0–1.0) for a case to count as passed. |
| `--max-agent-tokens INTEGER` | unset | Maximum measured agent-model tokens. |
diff --git a/docs/reports.mdx b/docs/reports.mdx
index a2e64eb9..c84af0d4 100644
--- a/docs/reports.mdx
+++ b/docs/reports.mdx
@@ -755,6 +755,25 @@ only one arm, `tier3 compare` drops it from both arms for the Overall lift, as
`lift.json` does, so its lift can differ from the difference between the two
arm overall scores.
+### Prior-version comparison
+
+When requested, `result.json` contains `prior_version_comparison` with `status`
+(`available` or `unavailable`), reasons, source run id and timestamp,
+`source_skill_identity`, `current_skill_identity`, and an `identical_skill`
+flag. Skill identities preserve evaluated-source revision and publication
+target digest when recorded. `latest` also records bounded rejected candidates.
+The report configuration retains this block for later rendering.
+
+Available comparisons contain per-agent `current_overall`, `prior_overall`,
+`delta`, `metrics` (current/prior/delta), optional custom metric deltas, and
+`regression` when delta is negative. The top-level regression flag is true
+when any available agent comparison regresses. Incompatible or missing scored
+evidence for any selected agent makes the whole comparison unavailable, with
+no regression flag. Reports show this
+comparison next to, never folded into, no-skill Skill Lift. The read-only
+`tier3 compare-versions` command recomputes the same comparison from retained
+rows without changing either run.
+
### Lift history and retention
Use `skillevaluator tier3 history ./my-skill` to list retained runs oldest
diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdx
index 2f8aeb9f..190326a4 100644
--- a/docs/tier3-live-evaluation.mdx
+++ b/docs/tier3-live-evaluation.mdx
@@ -779,6 +779,36 @@ The new run retains its own baseline rows. Fresh execution counts and reused
trial counts are separate; reused evidence is not another independent attempt.
Cost savings depend on the run, including agent, judge, and environment usage.
+### Compare skill versions
+
+Add `--compare-to RUN` to compare the current with-skill arm with a retained
+run's with-skill arm. This is separate from Skill Lift, which still compares
+with-skill against no-skill. It can be combined with `--reuse-baseline latest`:
+
+```bash
+skillevaluator tier3 evaluate ./my-skill --compare-to RUN --reuse-baseline latest
+skillevaluator tier3 compare-versions ./my-skill --current CURRENT --prior PRIOR
+skillevaluator tier3 compare-versions ./my-skill --current CURRENT --prior PRIOR --json
+```
+
+Both runs must have compatible datasets/cases, agents and resolved models,
+environment, judge/scoring policy, attempts, evaluator version, and workspace
+configuration. The prior with-skill arm must have complete successful scored
+evidence; it may itself have reused a no-skill baseline. An incompatible
+explicit id is refused before agent execution. `--compare-to latest` searches
+newest first for an eligible different skill revision, records bounded rejected
+candidates, and continues without a version comparison if none is available.
+An explicitly selected identical skill identity is allowed but flagged as
+not a version change.
+
+Version deltas use the same per-case pairing and score policy as Skill Lift.
+A negative available delta is marked as a regression; missing or unscored
+evidence is unavailable, never zero or a regression. Reports show the source
+run/revision and prior-to-current score transition. `compare-versions` is
+read-only, needs no provider credentials, and uses the same results-root
+resolution via `--results-dir`. It exits nonzero when comparison is unavailable.
+The static semver option `--previous-version` is unrelated and unchanged.
+
### Baseline-only runs
`--skip-with-skill` is the counterpart of `--skip-baseline`: it stages and runs
diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.py
index ed045d37..f24b1bf4 100644
--- a/src/skillevaluator/cli.py
+++ b/src/skillevaluator/cli.py
@@ -3300,6 +3300,12 @@ def _tier2_workflow(
@click.option(
"--reuse-baseline", metavar="RUN", default=None, help="Reuse a compatible retained baseline run id or latest."
)
+ "--compare-to",
+ metavar="RUN",
+ default=None,
+ help="Compare with-skill scores to a retained skill version or latest.",
+)
@click.option(
"--skip-with-skill",
is_flag=True,
@@ -3417,6 +3423,7 @@ def evaluate(
skip_baseline: bool,
skip_with_skill: bool,
reuse_baseline: str | None,
+ compare_to: str | None,
n_attempts: int | None,
max_agent_tokens: int | None,
max_judge_calls: int | None,
@@ -3458,6 +3465,8 @@ def evaluate(
raise click.UsageError("--skip-baseline and --skip-with-skill are mutually exclusive (no arm would run)")
if reuse_baseline and (skip_baseline or skip_with_skill):
raise click.UsageError("--reuse-baseline is mutually exclusive with --skip-baseline and --skip-with-skill")
+ if compare_to and skip_with_skill:
+ raise click.UsageError("--compare-to is mutually exclusive with --skip-with-skill")
from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_config
try:
@@ -3502,6 +3511,7 @@ def evaluate(
skip_baseline=skip_baseline,
skip_with_skill=skip_with_skill,
reuse_baseline=reuse_baseline,
+ compare_to=compare_to,
n_attempts=n_attempts,
max_agent_tokens=max_agent_tokens,
max_judge_calls=max_judge_calls,
@@ -3996,6 +4006,43 @@ def tier3_validate(skill_path: Path, as_json: bool, strict: bool, harbor_contrac
raise SystemExit(tier3_validate_evals(skill_path, as_json=as_json, strict=strict, harbor_contract=harbor_contract))
[email protected]("compare-versions")
+@_skill_argument
[email protected]("--current", required=True, metavar="RUN", help="Current retained run id or latest.")
[email protected]("--prior", required=True, metavar="RUN", help="Prior retained run id or latest different revision.")
[email protected]("--results-dir", type=click.Path(file_okay=False, path_type=Path), default=None)
[email protected]("--json", "as_json", is_flag=True, help="Print the comparison as JSON.")
+def compare_versions_command(
+ skill_path: Path, current: str, prior: str, results_dir: Path | None, as_json: bool
+) -> None:
+ """Compare two retained skill versions without execution or writes."""
+ from skillevaluator.tier3.results_location import resolve_results_root
+ from skillevaluator.tier3.version_comparison import compare_retained_runs, version_comparison_lines
+
+ comparison = compare_retained_runs(resolve_results_root(skill_path, results_dir), current, prior)
+ if as_json:
+ click.echo(json.dumps(comparison, indent=2))
+ else:
+ from rich.table import Table
+ from rich.text import Text
+
+ for line in version_comparison_lines(comparison):
+ console.print(Text(line))
+ if comparison.get("status") == "available":
+ table = Table("Agent", "Prior", "Current", "Delta", "Regression")
+ for agent, values in comparison["agents"].items():
+ table.add_row(
+ Text(agent),
+ f"{values['prior_overall']:.4f}",
+ f"{values['current_overall']:.4f}",
+ f"{values['delta']:+.4f}",
+ str(values["regression"]),
+ )
+ console.print(table)
+ if comparison.get("status") != "available":
+ raise click.exceptions.Exit(1)
+
+
@tier3.command("history")
@_skill_argument
@click.option("--results-dir", type=click.Path(file_okay=False, path_type=Path), default=None)
diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.py
index 7dbb184d..8f2c0298 100644
--- a/src/skillevaluator/evaluation/options.py
+++ b/src/skillevaluator/evaluation/options.py
@@ -58,6 +58,7 @@ class EvaluationOptions:
# Appended so legacy positional construction keeps its field order.
max_cases: int | None = None
reuse_baseline: str | None = None
+ compare_to: str | None = None
max_agent_tokens: int | None = None
max_judge_calls: int | None = None
max_attempts_total: int | None = None
diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.py
index 2fe324a7..536a2374 100644
--- a/src/skillevaluator/evaluation/tier3_report.py
+++ b/src/skillevaluator/evaluation/tier3_report.py
@@ -1042,6 +1042,7 @@ def build_agent_eval_payload(
payload = {
"schema_version": _SCHEMA_VERSION,
"baseline": (run_config or {}).get("baseline", {}),
+ "prior_version_comparison": (run_config or {}).get("prior_version_comparison", {}),
"summary": summary,
"skill_name": skill_name,
"mode": mode,
diff --git a/src/skillevaluator/reporting/benchmark.py b/src/skillevaluator/reporting/benchmark.py
index b75b2f7e..0e28c280 100644
--- a/src/skillevaluator/reporting/benchmark.py
+++ b/src/skillevaluator/reporting/benchmark.py
@@ -57,6 +57,7 @@ from skillevaluator.source_identity import evaluated_source_revision, recorded_e
from skillevaluator.tier3.baseline_store import baseline_description
from skillevaluator.tier3.dataset_provenance import dataset_provenance_display
from skillevaluator.tier3.evidence_volume import format_evidence_volume
+from skillevaluator.tier3.version_comparison import version_comparison_lines
from skillevaluator.tier3_environments import HARBOR_ENV_MODES
if TYPE_CHECKING:
@@ -434,6 +435,8 @@ class BenchmarkReporter(ReporterBase):
)
if baseline := _mapping((ae or {}).get("baseline")):
lines.append(f"- {_publication_safe_inline(baseline_description(baseline))}")
+ if comparison := _mapping((ae or {}).get("prior_version_comparison")):
+ lines.extend(f"- {_publication_safe_inline(line)}" for line in version_comparison_lines(comparison))
policy = _mapping((ae or {}).get("attempt_policy"))
attempts = _nonnegative_int(policy.get("max_attempts"))
diff --git a/src/skillevaluator/reporting/cli.py b/src/skillevaluator/reporting/cli.py
index ee1907df..dd0912fe 100644
--- a/src/skillevaluator/reporting/cli.py
+++ b/src/skillevaluator/reporting/cli.py
@@ -58,6 +58,7 @@ from skillevaluator.reporting.terminal_styles import AMBER, FAINT, GREEN, RED, T
from skillevaluator.tier3.baseline_store import baseline_description
from skillevaluator.tier3.dataset_provenance import dataset_provenance_display
from skillevaluator.tier3.evidence_volume import format_evidence_volume
+from skillevaluator.tier3.version_comparison import version_comparison_lines
from skillevaluator.utils.rich_markup import escape_markup
if TYPE_CHECKING:
@@ -873,6 +874,12 @@ class CLIReporter(ReporterBase):
console.print(table)
+ for result in results:
+ agent_eval = result.metadata.get("agent_eval")
+ if isinstance(agent_eval, dict) and (comparison := agent_eval.get("prior_version_comparison")):
+ for line in version_comparison_lines(comparison):
+ console.print(escape_markup(line))
+
@staticmethod
def _static_test_evidence_message(result: ValidationResult) -> str | None:
"""Return the static test limitation from direct or folder-aggregated results."""
diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.py
index 31e9a7ef..a2095d66 100644
--- a/src/skillevaluator/reporting/html.py
+++ b/src/skillevaluator/reporting/html.py
@@ -104,6 +104,7 @@ from skillevaluator.source_identity import recorded_evaluated_source
from skillevaluator.tier3.baseline_store import baseline_description
from skillevaluator.tier3.dataset_provenance import dataset_provenance_display
from skillevaluator.tier3.evidence_volume import format_evidence_volume
+from skillevaluator.tier3.version_comparison import version_comparison_lines
if TYPE_CHECKING:
from skillevaluator.models import ValidationResult
@@ -1290,6 +1291,8 @@ def _sanitize_tier3_display_payload(value: dict[str, Any]) -> dict[str, Any]:
baseline = payload.get("baseline")
if isinstance(baseline, dict) and baseline:
payload["baseline_description"] = baseline_description(baseline)
+ if comparison := payload.get("prior_version_comparison"):
+ payload["prior_version_lines"] = version_comparison_lines(comparison)
payload["summary"]["runtime_seconds"] = (
_finite_number(payload["summary"].get("runtime_seconds"), minimum=0.0) or 0.0
)
diff --git a/src/skillevaluator/reporting/markdown.py b/src/skillevaluator/reporting/markdown.py
index 2e44ef5f..b07e0528 100644
--- a/src/skillevaluator/reporting/markdown.py
+++ b/src/skillevaluator/reporting/markdown.py
@@ -45,6 +45,7 @@ from skillevaluator.reporting.run_status import Status, resolve_run_status, resu
from skillevaluator.reporting.summary_copy import SKILL_LIFT_DEFINITION, pass_at_k_summary
from skillevaluator.tier3.baseline_store import baseline_description
from skillevaluator.tier3.dataset_provenance import dataset_provenance_display
+from skillevaluator.tier3.version_comparison import version_comparison_lines
if TYPE_CHECKING:
from skillevaluator.models import Finding, ValidationResult
@@ -359,6 +360,9 @@ class MarkdownReporter(ReporterBase):
if ae.get("baseline"):
lines.append(baseline_description(ae["baseline"]))
lines.append("")
+ if comparison := ae.get("prior_version_comparison"):
+ lines.extend(html.escape(line) for line in version_comparison_lines(comparison))
+ lines.append("")
composite_text = _format_report_number(composite, signed=True)
lines.append(f"**Verdict:** {verdict} (Skill Lift = {composite_text})")
if _finite_report_number(composite) is not None:
diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2
index c80ba182..fbe90330 100644
--- a/src/skillevaluator/reporting/templates/report.html.j2
+++ b/src/skillevaluator/reporting/templates/report.html.j2
@@ -2162,6 +2162,7 @@
{# Helpers / locals used across the Tier 3 sub-tabs #}
{% set t3_summary = tier3.summary or {} %}
{% if tier3.baseline_description %}<p>{{ tier3.baseline_description }}</p>{% endif %}
+ {% for line in tier3.prior_version_lines | default([]) %}<p>{{ line }}</p>{% endfor %}
{% set t3_agents = tier3.agents or {} %}
{% macro tier3_chart(id, title, description, reference, reference_label, height) %}
<h3>{{ title }}</h3>
diff --git a/src/skillevaluator/tier3/baseline_store.py b/src/skillevaluator/tier3/baseline_store.py
index 51f2c344..11587b83 100644
--- a/src/skillevaluator/tier3/baseline_store.py
+++ b/src/skillevaluator/tier3/baseline_store.py
@@ -26,6 +26,8 @@ _NON_COMPARISON_FIELDS = frozenset(
"private_comparisons",
"baseline",
"reuse_baseline",
+ "compare_to",
+ "prior_version_comparison",
"budget",
}
)
@@ -197,10 +199,17 @@ def comparison_mismatches(current: dict[str, Any], source: dict[str, Any]) -> li
def load_baseline_rows(run_dir: Path, agent: str) -> list[dict[str, Any]]:
+ """Load the retained without-skill arm."""
+ return load_condition_rows(run_dir, agent, "without_skill")
+
+
+def load_condition_rows(run_dir: Path, agent: str, arm: str) -> list[dict[str, Any]]:
"""Restore collector-owned annotations from their public persistence envelope."""
- paths = sorted((run_dir / agent / "without-skill" / "trials").glob("*/reward.json"))
+ if arm not in {"with_skill", "without_skill"}:
+ raise ValueError("Unknown retained condition")
+ paths = sorted((run_dir / agent / arm.replace("_", "-") / "trials").glob("*/reward.json"))
if not paths:
- raise ValueError(f"{agent}: missing without-skill reward rows")
+ raise ValueError(f"{agent}: missing {arm.replace('_', '-')} reward rows")
rows = []
for path in paths:
try:
@@ -228,28 +237,54 @@ def load_baseline_rows(run_dir: Path, agent: str) -> list[dict[str, Any]]:
def baseline_eligibility(
run_dir: Path, agents: list[str], identity: dict[str, Any]
) -> tuple[list[str], dict[str, Any]]:
- """Require completed current results and complete, scoreable baseline rows."""
+ """Require a fresh, complete baseline under the current result contract."""
+ return condition_eligibility(run_dir, agents, identity, "without_skill", require_fresh=True)
+
+
+def condition_eligibility(
+ run_dir: Path,
+ agents: list[str],
+ identity: dict[str, Any],
+ arm: str,
+ *,
+ require_fresh: bool = False,
+ collected_result: dict[str, Any] | None = None,
+) -> tuple[list[str], dict[str, Any]]:
+ """Validate a retained arm, or the runner's not-yet-published collection."""
from skillevaluator.tier3.harbor.collector import _condition_execution_summary, _partition_scoreable_rewards
reasons: list[str] = []
try:
- config = json.loads((run_dir / "run_config.json").read_text(encoding="utf-8"))
- result = json.loads((run_dir / "result.json").read_text(encoding="utf-8"))
+ result = (
+ collected_result
+ if collected_result is not None
+ else json.loads((run_dir / "result.json").read_text(encoding="utf-8"))
+ )
+ if not isinstance(result, dict):
+ raise ValueError("invalid result")
+ config = (
+ result.get("run_config")
+ if collected_result is not None
+ else json.loads((run_dir / "run_config.json").read_text(encoding="utf-8"))
+ )
if not isinstance(config, dict) or not isinstance(result, dict):
raise ValueError("invalid result/config")
except (OSError, ValueError):
return ["missing or corrupt result/config"], {}
- if run_directory_sort_key(run_dir, require_completed_result=True) is None:
+ if collected_result is None and run_directory_sort_key(run_dir, require_completed_result=True) is None:
return ["run is not completed under the current result contract"], result
baseline = result.get("baseline", config.get("baseline", {}))
- if not isinstance(baseline, dict) or baseline.get("mode") == "reused":
- reasons.append("source run reused a baseline; select the original fresh run")
- elif baseline.get("mode") == "skipped":
- reasons.append("source run skipped its baseline")
- elif "baseline" not in result and "baseline" not in config:
- reasons.append("source run predates baseline provenance")
- elif baseline.get("mode") != "fresh":
- reasons.append("source run has an unsupported baseline mode")
+ if require_fresh:
+ if not isinstance(baseline, dict):
+ reasons.append("source run has invalid baseline provenance")
+ elif baseline.get("mode") == "reused":
+ reasons.append("source run reused a baseline; select the original fresh run")
+ elif baseline.get("mode") == "skipped":
+ reasons.append("source run skipped its baseline")
+ elif "baseline" not in result and "baseline" not in config:
+ reasons.append("source run predates baseline provenance")
+ elif baseline.get("mode") != "fresh":
+ reasons.append("source run has an unsupported baseline mode")
source_identity = result.get("comparison_identity")
if not isinstance(source_identity, dict):
reasons.append("run lacks a persisted comparison identity")
@@ -281,28 +316,29 @@ def baseline_eligibility(
reasons.append("source comparison identity disagrees with attempt policy evidence")
for agent in agents:
payload = result.get("agents", {}).get(agent, {})
- condition = payload.get("conditions", {}).get("without_skill", {})
+ condition = payload.get("conditions", {}).get(arm, {})
+ arm_label = "baseline" if arm == "without_skill" else "with-skill"
if condition.get("execution_status") != "succeeded":
- reasons.append(f"{agent}: without-skill condition did not succeed")
+ reasons.append(f"{agent}: {arm.replace('_', '-')} condition did not succeed")
if (
- payload.get("job_failures", {}).get("without_skill")
- or payload.get("trial_failures", {}).get("without_skill")
- or payload.get("agent_runtime_failures", {}).get("without_skill")
- or payload.get("historical_job_failures", {}).get("without_skill")
- or payload.get("recovered_trial_failures", {}).get("without_skill")
+ payload.get("job_failures", {}).get(arm)
+ or payload.get("trial_failures", {}).get(arm)
+ or payload.get("agent_runtime_failures", {}).get(arm)
+ or payload.get("historical_job_failures", {}).get(arm)
+ or payload.get("recovered_trial_failures", {}).get(arm)
):
- reasons.append(f"{agent}: baseline has job, trial or runtime failures")
+ reasons.append(f"{agent}: {arm_label} has job, trial or runtime failures")
try:
- summary = json.loads((run_dir / agent / "without-skill" / "summary.json").read_text(encoding="utf-8"))
+ summary = json.loads((run_dir / agent / arm.replace("_", "-") / "summary.json").read_text(encoding="utf-8"))
if not isinstance(summary, dict):
- raise ValueError("invalid baseline summary")
+ raise ValueError(f"invalid {arm_label} summary")
if (
summary.get("execution_status") != "succeeded"
or summary.get("job_failure")
or summary.get("trial_failures")
):
- reasons.append(f"{agent}: baseline summary is incomplete or failed")
- rows = load_baseline_rows(run_dir, agent)
+ reasons.append(f"{agent}: {arm_label} summary is incomplete or failed")
+ rows = load_condition_rows(run_dir, agent, arm)
scored, failures = _partition_scoreable_rewards(rows)
policy = identity["attempt_policy"]
execution = _condition_execution_summary(
@@ -316,9 +352,9 @@ def baseline_eligibility(
reward_failures=failures,
)
if failures or execution["execution_status"] != "succeeded":
- reasons.append(f"{agent}: baseline reward coverage is incomplete or unscoreable")
+ reasons.append(f"{agent}: {arm_label} reward coverage is incomplete or unscoreable")
except (OSError, ValueError, TypeError, KeyError) as exc:
- reasons.append(f"{agent}: missing or corrupt baseline evidence: {exc}")
+ reasons.append(f"{agent}: missing or corrupt {arm_label} evidence: {exc}")
return reasons, result
diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.py
index 13bdce06..f0cd0b12 100644
--- a/src/skillevaluator/tier3/commands.py
+++ b/src/skillevaluator/tier3/commands.py
@@ -669,6 +669,7 @@ def evaluate(
skip_baseline: bool,
skip_with_skill: bool = False,
reuse_baseline: str | None = None,
+ compare_to: str | None = None,
n_attempts: int | None,
max_agent_tokens: int | None = None,
max_judge_calls: int | None = None,
@@ -734,6 +735,8 @@ def evaluate(
raise ValueError("--skip-baseline and --skip-with-skill are mutually exclusive (no arm would run)")
if reuse_baseline and (skip_baseline or skip_with_skill):
raise ValueError("--reuse-baseline is mutually exclusive with --skip-baseline and --skip-with-skill")
+ if compare_to and skip_with_skill:
+ raise ValueError("--compare-to is mutually exclusive with --skip-with-skill")
unknown = validate_agents(agent_list)
if unknown:
supported = ", ".join(sorted(HARBOR_AGENTS_SUPPORTED))
@@ -764,6 +767,7 @@ def evaluate(
skip_baseline=skip_baseline,
skip_with_skill=skip_with_skill,
reuse_baseline=reuse_baseline,
+ compare_to=compare_to,
n_attempts=n_attempts,
max_agent_tokens=max_agent_tokens,
max_judge_calls=max_judge_calls,
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index 73225aec..eac20d8e 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -172,6 +172,7 @@ from skillevaluator.tier3.output_provenance import (
write_output_file_atomically,
)
from skillevaluator.tier3.results_location import publish_latest_results
+from skillevaluator.tier3.version_comparison import compare_versions, select_prior_version
from skillevaluator.tier3_environments import (
DEFAULT_ENV_MODE,
ENV_MODE_LOCAL,
@@ -5321,6 +5322,7 @@ def _run_harbor_eval_impl(
skip_baseline: bool = False,
skip_with_skill: bool = False,
reuse_baseline: str | None = None,
+ compare_to: str | None = None,
n_attempts: int | None = None,
max_agent_tokens: int | None = None,
max_judge_calls: int | None = None,
@@ -5378,6 +5380,10 @@ def _run_harbor_eval_impl(
detail = "--reuse-baseline is mutually exclusive with --skip-baseline and --skip-with-skill"
reporter.emit(ProgressEvent(stage="configuration", state="failed", detail=detail))
return {"error": [detail]}
+ if compare_to and skip_with_skill:
+ detail = "--compare-to is mutually exclusive with --skip-with-skill"
+ reporter.emit(ProgressEvent(stage="configuration", state="failed", detail=detail))
+ return {"error": [detail]}
if env_mode == ENV_MODE_LOCAL:
from skillevaluator.tier3.harbor import local_sandbox
@@ -6321,6 +6327,12 @@ def _run_harbor_eval_impl(
},
)
baseline = {"mode": "skipped" if skip_baseline else "fresh"}
+ prior_version = None
+ if compare_to:
+ try:
+ prior_version = select_prior_version(run_dir.parent, compare_to, identity, current_run_dir=run_dir)
+ except ValueError as exc:
+ return _persist_pre_execution_failure([str(exc)])
reused_baseline_dir = None
if reuse_baseline:
try:
@@ -6776,6 +6788,15 @@ def _run_harbor_eval_impl(
)
if errors:
_merge_launch_execution_errors(results, errors)
+ if prior_version is not None:
+ comparison = (
+ compare_versions(run_dir, Path(prior_version["source_run_dir"]), collected_result=results)
+ if prior_version["status"] == "available"
+ else prior_version
+ )
+ comparison["rejected_candidates"] = prior_version.get("rejected_candidates", [])
+ results["prior_version_comparison"] = comparison
+ run_config["prior_version_comparison"] = comparison
reporter.emit(ProgressEvent(stage="report", state="running"))
try:
(run_dir / "run_config.json").write_text(json.dumps(run_config, indent=2), encoding="utf-8")
diff --git a/src/skillevaluator/tier3/result_display.py b/src/skillevaluator/tier3/result_display.py
index 97a510b8..9abae801 100644
--- a/src/skillevaluator/tier3/result_display.py
+++ b/src/skillevaluator/tier3/result_display.py
@@ -40,6 +40,7 @@ from skillevaluator.tier3.harbor.metrics import (
)
from skillevaluator.tier3.harbor.progress import redact_progress_detail, secret_values_from_environment
from skillevaluator.tier3.harbor.runner import format_harbor_view_command
+from skillevaluator.tier3.version_comparison import version_comparison_lines
def _number(value: object, *, signed: bool = False) -> str:
@@ -1012,6 +1013,9 @@ def render_evaluation_result(
provenance_line, provenance_is_template = dataset_provenance_display(result.get("dataset_provenance"))
if provenance_line:
console.print(Text(provenance_line, style="yellow" if provenance_is_template else "dim"))
+ if comparison := result.get("prior_version_comparison"):
+ for line in version_comparison_lines(comparison):
+ console.print(Text(safe(line)))
agents = result.get("agents")
incomplete = status in {"failed", "incomplete"} and not any(
diff --git a/src/skillevaluator/tier3/version_comparison.py b/src/skillevaluator/tier3/version_comparison.py
new file mode 100644
index 00000000..628c26b9
--- /dev/null
+++ b/src/skillevaluator/tier3/version_comparison.py
@@ -0,0 +1,274 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Read-only comparisons of retained with-skill evidence."""
+
+from __future__ import annotations
+
+import copy
+import json
+import math
+from pathlib import Path
+from typing import Any
+
+from skillevaluator.source_identity import evaluated_source_revision
+from skillevaluator.tier3.baseline_store import comparison_identity, condition_eligibility, load_condition_rows
+from skillevaluator.tier3.results_location import ordered_run_directories, run_directory_sort_key
+
+
+def retained_run(root: Path, requested: str) -> Path:
+ """Resolve one retained run without following run-directory aliases."""
+ if requested == "latest":
+ candidates = ordered_run_directories(root, completed_only=True)
+ if not candidates:
+ raise ValueError("No completed retained runs found")
+ return candidates[0]
+ if Path(requested).name != requested or requested in {".", ".."}:
+ raise ValueError("Run must be a retained run id under the results root")
+ candidate = root / requested
+ if candidate.is_symlink() or candidate.resolve().parent != root.resolve():
+ raise ValueError("Linked run directories are not comparison sources")
+ return candidate
+
+
+def _read_result(run_dir: Path) -> dict[str, Any]:
+ result = json.loads((run_dir / "result.json").read_text(encoding="utf-8"))
+ if not isinstance(result, dict):
+ raise ValueError("Invalid retained result")
+ return result
+
+
+def _skill_revision(skill: dict[str, Any]) -> tuple[Any, Any]:
+ source = skill.get("evaluated_source") if isinstance(skill.get("evaluated_source"), dict) else {}
+ target = skill.get("publication_target") if isinstance(skill.get("publication_target"), dict) else {}
+ return evaluated_source_revision(source), target.get("skill_digest")
+
+
+def _same_skill_revision(current: dict[str, Any], prior: dict[str, Any]) -> bool:
+ current_revision, current_digest = _skill_revision(current)
+ prior_revision, prior_digest = _skill_revision(prior)
+ if current_digest and prior_digest:
+ return current_digest == prior_digest
+ return current_revision == prior_revision
+
+
+def _eligible(
+ run_dir: Path,
+ identity: dict[str, Any],
+ *,
+ collected_result: dict[str, Any] | None = None,
+) -> tuple[list[str], dict[str, Any]]:
+ try:
+ agents = list(identity["config"]["agents"])
+ reasons, result = condition_eligibility(
+ run_dir, agents, identity, "with_skill", collected_result=collected_result
+ )
+ recorded = result.get("comparison_identity", {})
+ if set(recorded.get("config", {}).get("agents", {})) != set(agents):
+ reasons.append("agent selection changed")
+ config = (
+ collected_result["run_config"]
+ if collected_result is not None
+ else json.loads((run_dir / "run_config.json").read_text(encoding="utf-8"))
+ )
+ if recorded.get("skill") != comparison_identity(config, result)["skill"]:
+ reasons.append("recorded skill identity disagrees with source evidence")
+ return reasons, result
+ except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc:
+ return [f"Missing or corrupt with-skill comparison evidence: {str(exc)[:512]}"], {}
+
+
+def _provenance(current_identity: dict[str, Any], source: dict[str, Any], source_dir: Path) -> dict[str, Any]:
+ current_skill = copy.deepcopy(current_identity.get("skill", {}))
+ prior_skill = copy.deepcopy(source.get("comparison_identity", {}).get("skill", {}))
+ current_skill = current_skill if isinstance(current_skill, dict) else {}
+ prior_skill = prior_skill if isinstance(prior_skill, dict) else {}
+ identical = _same_skill_revision(current_skill, prior_skill)
+ return {
+ "source_run_id": source_dir.name,
+ "source_evaluated_at": source.get("evaluated_at"),
+ "source_run_dir": str(source_dir),
+ "source_skill_identity": prior_skill,
+ "current_skill_identity": current_skill,
+ "identical_skill": identical,
+ }
+
+
+def select_prior_version(
+ root: Path, requested: str, identity: dict[str, Any], *, current_run_dir: Path
+) -> dict[str, Any]:
+ """Check a source before execution; latest excludes the current skill revision."""
+ candidates = (
+ ordered_run_directories(root, completed_only=True) if requested == "latest" else [retained_run(root, requested)]
+ )
+ if requested == "latest" and (
+ current_key := run_directory_sort_key(current_run_dir, require_completed_result=True)
+ ):
+ candidates = [
+ candidate
+ for candidate in candidates
+ if (candidate_key := run_directory_sort_key(candidate, require_completed_result=True))
+ and candidate_key < current_key
+ ]
+ rejected = []
+ for candidate in candidates:
+ if candidate.resolve() == current_run_dir.resolve():
+ continue
+ reasons, result = _eligible(candidate, identity)
+ provenance = _provenance(identity, result, candidate)
+ if requested == "latest" and (
+ provenance["identical_skill"] or not any(_skill_revision(identity.get("skill", {})))
+ ):
+ reasons.append("skill identity is unchanged or unrecorded; not a different skill revision")
+ if reasons:
+ if requested != "latest":
+ raise ValueError(f"Cannot compare to {requested}: " + "; ".join(reasons))
+ if len(rejected) < 16:
+ rejected.append({"run_id": candidate.name, "reasons": [reason[:1024] for reason in reasons[:16]]})
+ continue
+ return {"status": "available", "reasons": [], "rejected_candidates": rejected, **provenance}
+ return {
+ "status": "unavailable",
+ "reasons": ["No compatible completed run of a different skill revision"],
+ "current_skill_identity": copy.deepcopy(identity.get("skill", {})),
+ "rejected_candidates": rejected,
+ }
+
+
+def compare_versions(
+ current_dir: Path, prior_dir: Path, *, collected_result: dict[str, Any] | None = None
+) -> dict[str, Any]:
+ """Compute paired version deltas without changing either retained run."""
+ from skillevaluator.tier3.harbor.collector import (
+ _compute_custom_lift,
+ _compute_lift,
+ _logical_attempt_rewards,
+ _score_policy_for_rewards,
+ average_custom_metrics,
+ average_metrics,
+ )
+
+ unavailable: dict[str, Any] = {"status": "unavailable", "reasons": [], "agents": {}}
+ try:
+ current = collected_result if collected_result is not None else _read_result(current_dir)
+ identity = current["comparison_identity"]
+ current_reasons, _ = _eligible(current_dir, identity, collected_result=collected_result)
+ prior_reasons, source = _eligible(prior_dir, identity)
+ unavailable.update(_provenance(identity, source, prior_dir))
+ reasons = [
+ *(f"current: {reason}" for reason in current_reasons),
+ *(f"prior: {reason}" for reason in prior_reasons),
+ ]
+ if reasons:
+ return {**unavailable, "reasons": reasons}
+ agents = {}
+ for agent in identity["config"]["agents"]:
+ current_rows = _logical_attempt_rewards(load_condition_rows(current_dir, agent, "with_skill"))
+ prior_rows = _logical_attempt_rewards(load_condition_rows(prior_dir, agent, "with_skill"))
+ current_scores, _, current_metrics = average_metrics(current_rows)
+ prior_scores, _, prior_metrics = average_metrics(prior_rows)
+ if current_metrics != prior_metrics:
+ raise ValueError(f"{agent}: scored metric set changed")
+ current_policy, _ = _score_policy_for_rewards(current_rows, current_metrics)
+ prior_policy, _ = _score_policy_for_rewards(prior_rows, prior_metrics)
+ if current_policy != prior_policy or current_policy != identity["score_policy"]:
+ raise ValueError(f"{agent}: conflicting observed score policies")
+ lift = _compute_lift(
+ current_scores,
+ prior_scores,
+ current_rows,
+ prior_rows,
+ identity["expected_case_ids"],
+ score_policy=current_policy,
+ )
+ custom_lift = _compute_custom_lift(
+ average_custom_metrics(current_rows),
+ average_custom_metrics(prior_rows),
+ current_rows,
+ prior_rows,
+ include_overall=not current_metrics and not prior_metrics,
+ )
+ overall = lift.get("overall") or custom_lift.get("overall")
+ if overall is None:
+ raise ValueError(f"{agent}: no comparable paired overall score")
+
+ def deltas(values):
+ return {
+ key: {"current": value["with_skill"], "prior": value["without_skill"], "delta": value["delta"]}
+ for key, value in values.items()
+ if key != "overall" and isinstance(value, dict) and "delta" in value
+ }
+
+ agents[agent] = {
+ "current_overall": overall["with_skill"],
+ "prior_overall": overall["without_skill"],
+ "delta": overall["delta"],
+ "regression": overall["delta"] < 0,
+ "metrics": deltas(lift),
+ "custom_metrics": deltas(custom_lift),
+ "pairing": lift.get("basis", {}).get("pairing"),
+ }
+ if not agents:
+ raise ValueError("No selected agents with comparable scores")
+ return {
+ **unavailable,
+ "status": "available",
+ "agents": agents,
+ "reasons": ["Skill identity is unchanged; comparison is not a version change"]
+ if unavailable["identical_skill"]
+ else [],
+ "regression": any(agent["regression"] for agent in agents.values()),
+ }
+ except (OSError, ValueError, TypeError, KeyError, AttributeError) as exc:
+ return {**unavailable, "reasons": [f"Version comparison unavailable: {str(exc)[:1024]}"]}
+
+
+def compare_retained_runs(root: Path, current: str, prior: str) -> dict[str, Any]:
+ """Resolve read-only command selectors and use the live comparison path."""
+ try:
+ current_dir = retained_run(root, current)
+ current_result = _read_result(current_dir)
+ if prior == "latest":
+ selection = select_prior_version(
+ root, prior, current_result["comparison_identity"], current_run_dir=current_dir
+ )
+ if selection["status"] != "available":
+ return selection
+ prior_dir = Path(selection["source_run_dir"])
+ else:
+ prior_dir = retained_run(root, prior)
+ return compare_versions(current_dir, prior_dir)
+ except (OSError, ValueError, TypeError, KeyError) as exc:
+ return {"status": "unavailable", "reasons": [str(exc)], "agents": {}}
+
+
+def version_comparison_lines(comparison: dict[str, Any]) -> list[str]:
+ """Small shared report section, independent of no-skill lift."""
+ if not isinstance(comparison, dict):
+ return ["Versus prior version: unavailable (invalid comparison)"]
+ if comparison.get("status") != "available":
+ reasons = "; ".join(str(reason) for reason in comparison.get("reasons", []))
+ return [f"Versus prior version: unavailable ({reasons})"]
+ agents = comparison.get("agents")
+ if (
+ not isinstance(agents, dict)
+ or not agents
+ or any(
+ not isinstance(values, dict)
+ or any(
+ type(values.get(key)) not in (int, float) or not math.isfinite(values[key])
+ for key in ("prior_overall", "current_overall", "delta")
+ )
+ for values in agents.values()
+ )
+ ):
+ return ["Versus prior version: unavailable (invalid scores)"]
+ skill = comparison.get("source_skill_identity")
+ revision, digest = _skill_revision(skill if isinstance(skill, dict) else {})
+ prefix = f"Versus prior version (run {comparison.get('source_run_id')}, rev {revision or digest or 'unrecorded'})"
+ flag = "; identical skill, not a version change" if comparison.get("identical_skill") else ""
+ return [
+ f"{prefix} · {agent}: overall {values['prior_overall']:.2f} → {values['current_overall']:.2f} "
+ f"({values['delta']:+.2f}{', regression' if values['delta'] < 0 else ''}{flag})"
+ for agent, values in agents.items()
+ ]
diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json
index 6cc97f9b..ac8098fb 100644
--- a/tests/golden/cli_surface.json
+++ b/tests/golden/cli_surface.json
@@ -821,6 +821,14 @@
"param_type": "option",
"type": "text"
},
+ {
+ "name": "compare_to",
+ "opts": [
+ "--compare-to"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
{
"default": "False",
"is_flag": true,
@@ -2691,6 +2699,55 @@
}
]
},
+ "compare-versions": {
+ "params": [
+ {
+ "name": "skill_path",
+ "opts": [
+ "skill_path"
+ ],
+ "param_type": "argument",
+ "required": true,
+ "type": "path"
+ },
+ {
+ "name": "current",
+ "opts": [
+ "--current"
+ ],
+ "param_type": "option",
+ "required": true,
+ "type": "text"
+ },
+ {
+ "name": "prior",
+ "opts": [
+ "--prior"
+ ],
+ "param_type": "option",
+ "required": true,
+ "type": "text"
+ },
+ {
+ "name": "results_dir",
+ "opts": [
+ "--results-dir"
+ ],
+ "param_type": "option",
+ "type": "directory"
+ },
+ {
+ "default": "False",
+ "is_flag": true,
+ "name": "as_json",
+ "opts": [
+ "--json"
+ ],
+ "param_type": "option",
+ "type": "boolean"
+ }
+ ]
+ },
"create-eval-dataset": {
"params": [
{
@@ -2965,6 +3022,14 @@
"param_type": "option",
"type": "text"
},
+ {
+ "name": "compare_to",
+ "opts": [
+ "--compare-to"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
{
"default": "False",
"is_flag": true,
@@ -3908,6 +3973,14 @@
"param_type": "option",
"type": "text"
},
+ {
+ "name": "compare_to",
+ "opts": [
+ "--compare-to"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
{
"default": "False",
"is_flag": true,
diff --git a/tests/test_baseline_store.py b/tests/test_baseline_store.py
index 52d83a19..464655c9 100644
--- a/tests/test_baseline_store.py
+++ b/tests/test_baseline_store.py
@@ -224,9 +224,16 @@ def test_baseline_eligibility_explains_source_mode(tmp_path: Path, monkeypatch,
assert any(message in reason for reason in reasons), (mode, reasons)
[email protected]("skip", ["--skip-baseline", "--skip-with-skill"])
-def test_cli_mutual_exclusion(tmp_path: Path, skip: str) -> None:
- result = CliRunner().invoke(cli, ["tier3", "evaluate", str(tmp_path), "--reuse-baseline", "latest", skip])
+ ("reference_flag", "skip"),
+ [
+ ("--reuse-baseline", "--skip-baseline"),
+ ("--reuse-baseline", "--skip-with-skill"),
+ ("--compare-to", "--skip-with-skill"),
+ ],
+)
+def test_cli_mutual_exclusion(tmp_path: Path, reference_flag: str, skip: str) -> None:
+ result = CliRunner().invoke(cli, ["tier3", "evaluate", str(tmp_path), reference_flag, "latest", skip])
assert result.exit_code == 2
assert "mutually exclusive" in result.output
@@ -362,14 +369,20 @@ def test_active_failed_trials_count_as_started_and_make_usage_unavailable(monkey
assert agent["measured_usage"]["fresh"]["with_skill"] is None
[email protected]("skip", ["skip_baseline", "skip_with_skill"])
-def test_runner_mutual_exclusion_emits_configuration_failure(tmp_path: Path, skip: str) -> None:
+ ("reference_option", "skip"),
+ [
+ ("reuse_baseline", "skip_baseline"),
+ ("reuse_baseline", "skip_with_skill"),
+ ("compare_to", "skip_with_skill"),
+ ],
+)
+def test_runner_mutual_exclusion_emits_configuration_failure(tmp_path: Path, reference_option: str, skip: str) -> None:
events = []
result = runner._run_harbor_eval_impl(
tmp_path,
["opencode"],
- reuse_baseline="latest",
- **{skip: True},
+ **{reference_option: "latest", skip: True},
progress_reporter=SimpleNamespace(emit=events.append),
)
assert result["error"]
diff --git a/tests/test_version_comparison.py b/tests/test_version_comparison.py
new file mode 100644
index 00000000..da7cc5a8
--- /dev/null
+++ b/tests/test_version_comparison.py
@@ -0,0 +1,312 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+from __future__ import annotations
+
+import copy
+import hashlib
+import io
+import json
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+from rich.console import Console
+
+from skillevaluator.cli import cli
+from skillevaluator.evaluation.tier3_report import agent_eval_result_from_directory
+from skillevaluator.provider_config import ProviderConfig
+from skillevaluator.reporting.benchmark import BenchmarkReporter
+from skillevaluator.reporting.cli import CLIReporter
+from skillevaluator.reporting.html import HTMLReporter
+from skillevaluator.reporting.markdown import MarkdownReporter
+from skillevaluator.tier3.baseline_store import condition_eligibility
+from skillevaluator.tier3.harbor import runner, runtime_preflight
+from skillevaluator.tier3.result_display import render_evaluation_result
+from skillevaluator.tier3.version_comparison import compare_versions, select_prior_version, version_comparison_lines
+from test_baseline_store import _job, _write
+
+
+def evaluation(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
+ skill = tmp_path / "demo"
+ _write(skill / "evals/evals.json", [])
+ provider = ProviderConfig(
+ provider="openai",
+ model="test-model",
+ api_key="test-key",
+ base_url="https://provider.example/v1",
+ litellm_model="openai/test-model",
+ )
+ monkeypatch.setattr(runner, "resolve_llm_provider", lambda: provider)
+ monkeypatch.setattr(runner, "load_evals_config", lambda _path: ({"harbor": {"task_source": "evals_json"}}, None))
+ monkeypatch.setattr(runner, "find_evals_file", lambda _path: skill / "evals/evals.json")
+ monkeypatch.setattr(runner, "_check_prerequisites", lambda **_kwargs: [])
+ monkeypatch.setattr(
+ runtime_preflight,
+ "probe_model",
+ lambda selected: runtime_preflight.ModelProbeResult(True, selected.provider, selected.model, "available"),
+ )
+ monkeypatch.setattr(runner, "render_agent_eval_html_report", lambda *_args, **_kwargs: tmp_path / "report.html")
+
+ def emit(_skill, target, **_kwargs):
+ task = target / "case-001"
+ task.mkdir(parents=True)
+ (task / "task.toml").write_text(
+ 'schema_version = "1.3"\n[task]\nname = "case-001"\n[metadata]\nentry_id = "case-001"\n'
+ )
+ return [task]
+
+ monkeypatch.setattr(runner, "generate_harbor_tasks", emit)
+ active = {}
+ launches = []
+
+ def launch(**kwargs):
+ launches.append(kwargs)
+ for condition, suffix, score in (("with_skill", "with", active["score"]), ("baseline", "without", 0.5)):
+ if kwargs[condition] is not None:
+ _job(kwargs["jobs_dir"] / f"demo-opencode-{suffix}", score, grading_mode=active["grading"])
+ return []
+
+ monkeypatch.setattr(runner, "_run_agent_pair", launch)
+
+ def evaluate(version="a", score=0.8, **options):
+ active.update(score=score, grading=options.get("grading_mode", "default"))
+ (skill / "SKILL.md").write_text(f"---\nname: demo\ndescription: Arithmetic note\n---\nVersion {version}\n")
+ return runner.run_harbor_eval(
+ skill,
+ ["opencode"],
+ output_dir=tmp_path / "results/demo",
+ env_mode="docker",
+ agent_runtime_preflight=False,
+ agent_models={"opencode": "openai/test-model"},
+ evaluated_source={"repository": "example/skill", "commit": version * 40},
+ **options,
+ )
+
+ evaluate.skill = skill
+ evaluate.launches = launches
+ return evaluate
+
+
[email protected]("grading_mode", ["default", "custom_only"])
+def test_live_and_readback_share_regression_math(evaluation, grading_mode):
+ prior = evaluation(grading_mode=grading_mode)
+ assert "error" not in prior, prior
+ current = evaluation("b", 0.2, grading_mode=grading_mode, compare_to=prior["run_id"], reuse_baseline="latest")
+ assert "error" not in current, current
+ comparison = current["prior_version_comparison"]
+ assert comparison["status"] == "available", comparison
+ assert comparison["regression"] is True
+ assert comparison["agents"]["opencode"]["delta"] == -0.6
+ assert comparison["agents"]["opencode"]["current_overall"] == 0.2
+ assert comparison["agents"]["opencode"]["prior_overall"] == 0.8
+ if grading_mode == "default":
+ assert current["agents"]["opencode"]["lift"]["overall"]["delta"] == -0.3
+ assert comparison["agents"]["opencode"]["metrics"]["accuracy"]["delta"] == -0.6
+ assert current["baseline"]["mode"] == "reused"
+ assert evaluation.launches[-1]["baseline"] is None
+ readback = compare_versions(Path(current["run_dir"]), Path(prior["run_dir"]))
+ assert readback == {key: value for key, value in comparison.items() if key != "rejected_candidates"}
+
+
+def test_explicit_incompatible_refuses_before_execution(evaluation):
+ prior = evaluation()
+ current = evaluation("b", 0.2, compare_to=prior["run_id"], n_attempts=2)
+ assert "attempt policy changed" in str(current["error"])
+ assert len(evaluation.launches) == 1
+
+
+def test_latest_requires_different_skill_and_can_be_unavailable(evaluation):
+ prior = evaluation()
+ same = evaluation(compare_to="latest")
+ unavailable = same["prior_version_comparison"]
+ assert unavailable["status"] == "unavailable"
+ assert "unchanged" in str(unavailable["rejected_candidates"])
+ assert "regression" not in unavailable
+ different = evaluation("b", 0.2, compare_to="latest")
+ assert different["prior_version_comparison"]["status"] == "available"
+ assert different["prior_version_comparison"]["source_run_id"] in {same["run_id"], prior["run_id"]}
+
+
+def test_identical_explicit_source_is_flagged(evaluation):
+ prior = evaluation()
+ same = evaluation(compare_to=prior["run_id"])
+ comparison = same["prior_version_comparison"]
+ assert comparison["status"] == "available"
+ assert comparison["identical_skill"] is True
+ assert comparison["regression"] is False
+ assert "not a version change" in " ".join(version_comparison_lines(comparison))
+
+
+def test_revision_fallback_is_used_when_publication_digest_is_missing(evaluation):
+ prior = evaluation("a", 0.8)
+ current = evaluation("b", 0.2)
+ for run in (prior, current):
+ result_path = Path(run["run_dir"]) / "result.json"
+ result = json.loads(result_path.read_text())
+ result["publication_target"]["skill_digest"] = None
+ result["comparison_identity"]["skill"]["publication_target"]["skill_digest"] = None
+ _write(result_path, result)
+
+ comparison = compare_versions(Path(current["run_dir"]), Path(prior["run_dir"]))
+
+ assert comparison["status"] == "available"
+ assert comparison["identical_skill"] is False
+ assert f"rev {'a' * 40}" in version_comparison_lines(comparison)[0]
+
+
[email protected]("arm", ["prior", "current"])
[email protected]("damage", ["missing", "corrupt", "unscored", "old", "partial", "failed"])
+def test_missing_or_unscored_is_not_a_regression(evaluation, damage, arm):
+ prior, current = evaluation(), evaluation("b", 0.2)
+ damaged = prior if arm == "prior" else current
+ reward = next((Path(damaged["run_dir"]) / "opencode/with-skill/trials").glob("*/reward.json"))
+ row = json.loads(reward.read_text())
+ if damage == "missing":
+ reward.unlink()
+ elif damage == "corrupt":
+ reward.write_text("{")
+ elif damage == "failed":
+ damaged["agents"]["opencode"]["conditions"]["with_skill"]["execution_status"] = "failed"
+ _write(Path(damaged["run_dir"]) / "result.json", damaged)
+ else:
+ if damage == "unscored":
+ row["evaluation_status"] = "failed"
+ elif damage == "old":
+ row.pop("baseline_evidence")
+ else:
+ row["entry_id"] = "another-case"
+ _write(reward, row)
+ comparison = compare_versions(Path(current["run_dir"]), Path(prior["run_dir"]))
+ assert comparison["status"] == "unavailable"
+ assert comparison["reasons"]
+ assert comparison["agents"] == {}
+ assert "regression" not in comparison
+
+
+def test_reused_no_skill_run_can_supply_prior_with_skill(evaluation):
+ original = evaluation()
+ prior = evaluation("b", 0.7, reuse_baseline=original["run_id"])
+ current = evaluation("c", 0.2, compare_to=prior["run_id"])
+ assert current["prior_version_comparison"]["status"] == "available"
+
+
+def test_posthoc_is_read_only_and_prints_table_or_json(evaluation):
+ prior, current = evaluation(), evaluation("b", 0.2)
+ root = Path(current["run_dir"]).parent
+
+ def snapshot():
+ return {p: hashlib.sha256(p.read_bytes()).hexdigest() for p in root.rglob("*") if p.is_file()}
+
+ before = snapshot()
+ args = [
+ "tier3",
+ "compare-versions",
+ str(evaluation.skill),
+ "--current",
+ current["run_id"],
+ "--prior",
+ prior["run_id"],
+ "--results-dir",
+ str(root.parent),
+ ]
+ result = CliRunner().invoke(cli, [*args, "--json"])
+ assert result.exit_code == 0, result.output
+ assert json.loads(result.output)["regression"] is True
+ table = CliRunner().invoke(cli, args)
+ assert table.exit_code == 0, table.output
+ assert "Regression" in table.output and "-0.6000" in table.output
+ invalid_args = list(args)
+ invalid_args[6] = "../outside"
+ invalid = CliRunner().invoke(cli, [*invalid_args, "--json"])
+ assert invalid.exit_code != 0
+ assert snapshot() == before
+ assert len(evaluation.launches) == 2
+
+
+def test_all_report_formats_keep_version_delta_separate(evaluation):
+ prior = evaluation()
+ current = evaluation("b", 0.2, compare_to=prior["run_id"])
+ result = agent_eval_result_from_directory(
+ evaluation.skill, Path(current["run_dir"]), engine_result=current, use_llm_judge=False
+ )
+ assert result is not None
+ for reporter in (
+ BenchmarkReporter(skill_name="demo", report_scope="tier3"),
+ MarkdownReporter(),
+ HTMLReporter(),
+ CLIReporter(),
+ ):
+ rendered = reporter.render_all([result])
+ assert "Versus prior version" in rendered
+ assert "regression" in rendered
+ stream = io.StringIO()
+ render_evaluation_result(current, console=Console(file=stream, width=200), verbose=False)
+ assert "Versus prior version" in stream.getvalue() and "regression" in stream.getvalue()
+
+
[email protected]("changed", ["model", "environment", "judge", "cases", "agents"])
+def test_version_compatibility_uses_shared_identity(evaluation, changed):
+ prior = evaluation()
+ identity = copy.deepcopy(prior["comparison_identity"])
+ if changed == "model":
+ identity["config"]["agents"]["opencode"]["model"] = "another-model"
+ elif changed == "environment":
+ identity["config"]["harbor"]["environment"] = "local"
+ elif changed == "judge":
+ identity["config"]["judge"]["model"] = "another-judge"
+ elif changed == "cases":
+ identity["expected_case_ids"] = ["another-case"]
+ else:
+ identity["config"]["agents"] = {}
+ with pytest.raises(ValueError, match="Cannot compare to"):
+ select_prior_version(
+ Path(prior["run_dir"]).parent,
+ prior["run_id"],
+ identity,
+ current_run_dir=Path(prior["run_dir"]).parent / "new",
+ )
+
+
+def test_latest_rejects_incompatible_candidates(evaluation):
+ prior = evaluation()
+ identity = dict(prior["comparison_identity"])
+ identity["evaluator_version"] = "another-version"
+ selection = select_prior_version(
+ Path(prior["run_dir"]).parent, "latest", identity, current_run_dir=Path(prior["run_dir"]).parent / "new"
+ )
+ assert selection["status"] == "unavailable"
+ assert "evaluator version changed" in str(selection["rejected_candidates"])
+
+
+def test_latest_never_selects_a_run_newer_than_the_current_run(evaluation):
+ current = evaluation("a", 0.8)
+ evaluation("b", 0.2)
+
+ selection = select_prior_version(
+ Path(current["run_dir"]).parent,
+ "latest",
+ current["comparison_identity"],
+ current_run_dir=Path(current["run_dir"]),
+ )
+
+ assert selection["status"] == "unavailable"
+ assert selection["reasons"] == ["No compatible completed run of a different skill revision"]
+
+
+def test_with_skill_eligibility_reasons_name_the_with_skill_arm(evaluation):
+ run = evaluation()
+ summary_path = Path(run["run_dir"]) / "opencode/with-skill/summary.json"
+ summary = json.loads(summary_path.read_text())
+ summary["execution_status"] = "failed"
+ _write(summary_path, summary)
+
+ reasons, _ = condition_eligibility(Path(run["run_dir"]), ["opencode"], run["comparison_identity"], "with_skill")
+
+ assert "opencode: with-skill summary is incomplete or failed" in reasons
+ assert not any("baseline" in reason for reason in reasons)
+
+
+def test_malformed_display_scores_are_unavailable():
+ assert "unavailable" in version_comparison_lines({"status": "available", "agents": {"agent": {}}})[0]