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): add a lift history view over retained runs (#388)

Christopher Kevin98d12798d865
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5e438b84..eee51e90 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.
+- 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.
+
- Tier 3 `evaluate --reuse-baseline RUN` reuses compatible retained fresh
without-skill evidence, preserving lift calculations and baseline provenance.
`latest` searches completed runs and falls back to a fresh baseline when needed.
diff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdx
index 2d1d9806..b1d6cd90 100644
--- a/docs/cli-reference.mdx
+++ b/docs/cli-reference.mdx
@@ -37,6 +37,7 @@ commands referenced below.
| [init-harbor-task](#init-harbor-task) | Scaffold a bring-your-own-task Harbor starter | Nothing |
| [view](#view) | Open the latest HTML live-evaluation report | A previous `tier3 evaluate` run |
| [compare](#compare) | Compare live-evaluation results across agents | A previous `tier3 evaluate` run |
+| [tier3 history](#tier3-history) | Inspect retained Skill Lift over skill revisions, grouped by compatible configuration | Retained Tier 3 summaries |
| [tier3 feedback](#tier3-feedback) | Chat about one completed live-evaluation run and possible skill changes | A completed `tier3 evaluate` run, LLM provider key |
| [dashboard](#dashboard) | Filter quantitative tables and paired usage differences | Saved JSON reports or retained runs; dashboard extra |
| [harbor-view](#harbor-view) | Browse retained Harbor job artifacts | A run made with `--harbor-keep-jobs` |
@@ -630,6 +631,31 @@ skillevaluator view ./my-skill
| --- | --- | --- |
| `--results-dir DIRECTORY` | unset | Results directory to read from (default resolution in [Reports & Results](reports.mdx)). |
+## tier3 history
+
+```bash
+skillevaluator tier3 history ./my-skill
+skillevaluator tier3 history ./my-skill --results-dir ./saved-runs --agent opencode --json
+skillevaluator tier3 history ./my-skill --output ./lift-history.md
+```
+
+List every retained run chronologically, with one row per run and agent,
+including failed, incomplete, and corrupt runs. An unavailable lift is JSON
+`null` with `lift_status` and reasons, never an inferred zero. Segments and
+visible break markers separate model, dataset, attempt, scoring-policy, and
+other configuration changes; the change column never crosses a segment boundary.
+Skill revisions alone do not break baseline compatibility.
+
+| Flag | Default | Effect |
+| --- | --- | --- |
+| `--results-dir DIRECTORY` | normal results-root resolution | External root containing the per-skill directory; honors the configured location and legacy fallback like `compare`. |
+| `--agent TEXT` | all | Include only this agent's rows. |
+| `--json` | off | Print the complete history as JSON instead of a table. |
+| `--output FILE` | none | Write exactly this `.json`, `.csv`, or `.md` export. The file must be outside all candidate results roots; no directories are created. Stdout still follows `--json`. |
+
+The command reads summaries only: no agents, provider credentials, or raw
+trajectories are needed. See [Lift history and retention](reports.mdx#lift-history-and-retention).
+
## compare
Compare live-evaluation results across agents from previous runs.
diff --git a/docs/reports.mdx b/docs/reports.mdx
index 384613bd..a2e64eb9 100644
--- a/docs/reports.mdx
+++ b/docs/reports.mdx
@@ -755,6 +755,59 @@ 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.
+### Lift history and retention
+
+Use `skillevaluator tier3 history ./my-skill` to list retained runs oldest
+first, with one row per run and agent. The reader uses the same results-root
+precedence and legacy fallback as `compare`: explicit `--results-dir`, then
+`SKILLEVALUATOR_RESULTS_DIR`, then `<skill>/evals/results/`. It reads the first
+populated candidate root, not a merged history from different roots.
+
+```bash
+skillevaluator tier3 history ./my-skill --agent opencode
+skillevaluator tier3 history ./my-skill --results-dir ./saved-runs --json
+skillevaluator tier3 history ./my-skill --output ./lift-history.csv
+skillevaluator tier3 history ./my-skill --output ./lift-history.md
+```
+
+Rows show run id and evaluation time, skill revision/content identity, model,
+dataset digest and case count, with/without scores, paired Skill Lift, scored
+and expected case coverage for both arms, baseline mode, and status. JSON
+keeps the full identities; the table abbreviates long content and dataset
+digests. Failed, incomplete, corrupt, skipped-baseline, baseline-only, or
+unscored rows retain a null `lift_delta`, `lift_status="unavailable"`, and
+reasons. A recorded lift of zero remains a real zero. Older summaries expose
+whatever identity and score fields they recorded; missing facts stay unknown.
+
+Each agent has its own chronological segments. The P0 baseline comparison
+identity excludes skill revisions but includes model, dataset/cases,
+environment, judge/scorer, attempts, score policy, and evaluator version.
+Configuration changes start a numbered segment, set `config_changed`, and
+list mismatch reasons; Markdown exports insert a break line. Known changes
+in unavailable rows also break the segment. `lift_change` compares only
+available rows with known compatible identities within the same segment;
+unknown identities never establish a cross-run trend. Do not interpret
+across-segment differences as skill improvement or regression.
+
+History is a summary reader, not an evidence-eligibility check. Unlike the
+completed-run views above, it also lists timestamped reservations with missing
+or corrupt completion artifacts. This does not make them eligible baseline
+sources. The command never launches evaluation or writes into the results
+root. `--output` writes only the requested JSON, CSV, or Markdown file outside
+the candidate results roots.
+
+New evaluations reserve a unique run directory; they do not prune older run
+directories. The default `<skill>/evals/results/` is inside the skill
+repository, but a separate skill repository does not automatically ignore that
+path. Add it to that repository's `.gitignore` before force-adding selected
+summaries. Keep the full local tree if you need trial evidence or reusable
+baselines. To retain a compact history with the repository, review
+privacy-sensitive metadata and force-add **only** each chosen run's
+`result.json` and `run_config.json` summaries (or copy them into a separately
+tracked archive). Do not commit raw trajectories, logs, credentials, or the
+entire generated results tree. Summary archives preserve history, not the
+per-row evidence required for baseline reuse or publication validation.
+
### Skill Lift
Skill Lift compares Overall on the metrics and cases both arms scored, so it
diff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.py
index 58596957..cba97bac 100644
--- a/src/skillevaluator/cli.py
+++ b/src/skillevaluator/cli.py
@@ -3939,6 +3939,44 @@ 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))
+@_skill_argument
[email protected]("--results-dir", type=click.Path(file_okay=False, path_type=Path), default=None)
[email protected]("--agent", default=None, help="Include only this agent's history.")
[email protected]("--json", "as_json", is_flag=True, help="Print history as JSON.")
+ "--output",
+ type=click.Path(dir_okay=False, path_type=Path),
+ default=None,
+ help="Export to .json, .csv or .md outside the results root.",
+)
+def tier3_history(
+ skill_path: Path, results_dir: Path | None, agent: str | None, as_json: bool, output: Path | None
+) -> None:
+ """List retained Skill Lift runs chronologically without execution."""
+ from skillevaluator.tier3.history import collect_history, export_history, print_history
+ from skillevaluator.tier3.results_location import iter_candidate_results_roots
+
+ try:
+ if output is not None:
+ if output.suffix.lower() not in {".json", ".csv", ".md"}:
+ raise click.UsageError("--output must end in .json, .csv or .md")
+ if any(
+ output.resolve().is_relative_to(root.resolve())
+ for root in iter_candidate_results_roots(skill_path, results_dir)
+ ):
+ raise click.UsageError("--output must be outside the results roots (history is read-only)")
+ history = collect_history(skill_path, results_dir, agent)
+ if output is not None:
+ output.write_text(export_history(history, output.suffix.lower()), encoding="utf-8", newline="")
+ if as_json:
+ click.echo(export_history(history, ".json"), nl=False)
+ else:
+ print_history(history, console)
+ except (OSError, ValueError) as exc:
+ raise click.ClickException(str(exc)) from exc
+
+
@tier3.command("feedback")
@click.argument("run_dir", type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path))
@click.option(
diff --git a/src/skillevaluator/tier3/history.py b/src/skillevaluator/tier3/history.py
new file mode 100644
index 00000000..e8d9f396
--- /dev/null
+++ b/src/skillevaluator/tier3/history.py
@@ -0,0 +1,512 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Summary-only, read-only Skill Lift history and exports."""
+
+from __future__ import annotations
+
+import csv
+import html
+import io
+import json
+import math
+import stat
+from contextlib import suppress
+from pathlib import Path
+from typing import Any
+
+from rich.box import SIMPLE
+from rich.console import Console
+from rich.table import Table
+from rich.text import Text
+
+from skillevaluator.source_identity import evaluated_source_revision
+from skillevaluator.tier3.baseline_store import comparison_identity, comparison_mismatches
+from skillevaluator.tier3.results_location import (
+ _CURRENT_RUN_SUFFIX,
+ _run_timestamp_parts,
+ is_legacy_completed_run_dir,
+ iter_candidate_results_roots,
+ ordered_run_directories,
+)
+from skillevaluator.utils.rich_markup import strip_terminal_controls
+from skillevaluator.utils.secure_fs import SecurePathError, SecureRoot
+
+
+def history_directories(root: Path) -> list[Path]:
+ """Keep shared ordering, including reservations without completion artifacts."""
+ directories = ordered_run_directories(root, completed_only=False)
+ try:
+ for candidate in root.iterdir():
+ parsed = _run_timestamp_parts(candidate.name)
+ if parsed is None or (parsed[1] and not _CURRENT_RUN_SUFFIX.fullmatch(parsed[1])):
+ continue
+ if candidate not in directories and stat.S_ISDIR(candidate.lstat().st_mode) and not candidate.is_symlink():
+ directories.append(candidate)
+ except OSError:
+ pass
+
+ def key(path: Path):
+ parsed = _run_timestamp_parts(path.name)
+ try:
+ mtime = (path / "result.json").lstat().st_mtime_ns
+ except OSError:
+ mtime = 0
+ return (parsed[0].isoformat() if parsed else "", mtime, path.name)
+
+ return sorted(directories, key=key)
+
+
+def _mapping(value: Any) -> dict[str, Any]:
+ return value if isinstance(value, dict) else {}
+
+
+def _invalid_constant(value: str) -> None:
+ raise ValueError(f"Non-finite JSON value: {value}")
+
+
+def _read(root: SecureRoot, path: str) -> tuple[dict[str, Any], str | None]:
+ try:
+ data, _ = root.read_bytes(Path(path), 32 * 1024 * 1024)
+ result = json.loads(data, parse_constant=_invalid_constant)
+ if not isinstance(result, dict):
+ raise ValueError("expected an object")
+ return result, None
+ except (OSError, ValueError, SecurePathError) as exc:
+ return {}, f"missing or corrupt {path}: {str(exc)[:160]}"
+
+
+def _number(value: Any, minimum: float = 0, maximum: float = 1) -> float | None:
+ if type(value) not in (int, float):
+ return None
+ try:
+ return float(value) if math.isfinite(value) and minimum <= value <= maximum else None
+ except OverflowError:
+ return None
+
+
+def _count(value: Any) -> int | None:
+ return value if type(value) is int and value >= 0 else None
+
+
+def _identity(config: dict, result: dict) -> dict:
+ recorded = _mapping(result.get("comparison_identity"))
+ facts = {**recorded, **result}
+ policy = _mapping(facts.get("attempt_policy"))
+ facts["attempt_policy"] = {
+ key: value for key, value in policy.items() if key not in {"score_policy", "score_definition"}
+ }
+ cases = facts.get("expected_case_ids")
+ facts["expected_case_ids"] = (
+ cases if isinstance(cases, list) and all(isinstance(case, str) for case in cases) else []
+ )
+ identity = comparison_identity(_mapping(recorded.get("config")) or config, facts)
+ skill = _mapping(recorded.get("skill"))
+ for key in ("evaluated_source", "publication_target"):
+ if identity["skill"].get(key) is None:
+ identity["skill"][key] = skill.get(key, result.get(key))
+ return identity
+
+
+def _known_identity(identity: dict, agent: str | None) -> bool:
+ model = _mapping(_mapping(identity["config"].get("agents")).get(agent)).get("model")
+ return bool(
+ isinstance(model, str)
+ and model
+ and isinstance(identity.get("dataset_digest"), str)
+ and identity["dataset_digest"]
+ and identity.get("expected_case_ids")
+ and identity.get("attempt_policy")
+ and isinstance(identity.get("score_policy"), str)
+ and identity["score_policy"]
+ and isinstance(identity.get("evaluator_version"), str)
+ and identity["evaluator_version"]
+ )
+
+
+def _known_mismatches(current: dict, previous: dict, agent: str | None) -> list[str]:
+ if not current.get("config") or not previous.get("config"):
+ return []
+ current, previous = dict(current), dict(previous)
+ for field in (
+ "dataset_digest",
+ "identity_dataset_digest",
+ "expected_case_ids",
+ "attempt_policy",
+ "score_policy",
+ "evaluator_version",
+ ):
+ if not current.get(field) or not previous.get(field):
+ current[field] = previous[field] = [] if field == "expected_case_ids" else None
+ for identity in (current, previous):
+ config = dict(_mapping(identity.get("config")))
+ agents = _mapping(config.get("agents"))
+ config["agents"] = {agent: agents.get(agent)}
+ identity["config"] = config
+ return comparison_mismatches(current, previous)
+
+
+def _run_rows(run_dir: Path, selected_agent: str | None) -> list[tuple[dict, dict]]:
+ with SecureRoot(run_dir) as root:
+ config, config_error = _read(root, "run_config.json")
+ result, result_error = _read(root, "result.json")
+ config = config or _mapping(result.get("run_config"))
+ identity = _identity(config, result)
+ agents = set(_mapping(config.get("agents"))) | set(_mapping(result.get("agents")))
+ agents.update(_mapping(identity["config"].get("agents")))
+ with suppress(OSError):
+ agents.update(
+ p.name
+ for p in run_dir.iterdir()
+ if p.is_dir()
+ and not p.is_symlink()
+ and any(
+ (p / name).exists()
+ for name in ("summary.json", "with-skill/summary.json", "without-skill/summary.json")
+ )
+ )
+ names = sorted(
+ name for name in agents if isinstance(name, str) and Path(name).name == name and name not in {".", ".."}
+ )
+ if selected_agent is not None:
+ names = [name for name in names if name == selected_agent]
+ elif not names:
+ names = [None]
+ rows = []
+ for agent in names:
+ payload = _mapping(_mapping(result.get("agents")).get(agent))
+ conditions = _mapping(payload.get("conditions"))
+ summaries = {}
+ for arm in ("with_skill", "without_skill"):
+ summaries[arm], _ = (
+ _read(root, f"{agent}/{arm.replace('_', '-')}/summary.json") if agent else ({}, None)
+ )
+ if agent and not summaries["with_skill"]:
+ summaries["with_skill"], _ = _read(root, f"{agent}/summary.json")
+ with_condition = {**summaries["with_skill"], **_mapping(conditions.get("with_skill"))}
+ without_condition = {**summaries["without_skill"], **_mapping(conditions.get("without_skill"))}
+ coverage = {
+ arm: {
+ "scored_cases": _count(condition.get("scored_cases")),
+ "expected_cases": _count(condition.get("expected_cases")),
+ }
+ for arm, condition in (("with_skill", with_condition), ("without_skill", without_condition))
+ }
+ baseline = _mapping(result.get("baseline", config.get("baseline")))
+ result_path = run_dir / "result.json"
+ legacy_completed = not result_path.exists() and is_legacy_completed_run_dir(run_dir)
+ status = (
+ "legacy"
+ if legacy_completed
+ else result.get("execution_status")
+ or ("corrupt" if result_error and result_path.exists() else "incomplete")
+ )
+ reasons = [error for error in (config_error, result_error) if error]
+ if legacy_completed:
+ reasons = [error for error in reasons if error != result_error]
+ reasons.append("legacy run: no run-level result.json; case coverage not recorded")
+ if not isinstance(status, str):
+ status = "corrupt"
+ reasons.append("invalid run execution status")
+ if result.get("run_id", run_dir.name) != run_dir.name:
+ reasons.append("result run id disagrees with directory")
+ status = "corrupt"
+ agent_status = payload.get("execution_status") or result.get("execution_status")
+ if agent_status is not None and agent_status != "succeeded":
+ reasons.append(f"agent status is {agent_status}")
+ if baseline.get("mode") == "skipped" or without_condition.get("execution_status") == "skipped":
+ reasons.append("without-skill baseline was skipped")
+ if with_condition.get("execution_status") == "skipped":
+ reasons.append("with-skill arm was skipped (baseline-only run)")
+ for arm, condition in (("with_skill", with_condition), ("without_skill", without_condition)):
+ scored, expected = coverage[arm]["scored_cases"], coverage[arm]["expected_cases"]
+ if condition.get("execution_status") != "succeeded":
+ reasons.append(f"{arm}: condition did not succeed")
+ if expected is None or expected == 0 or scored != expected:
+ reasons.append(f"{arm}: incomplete or unknown case coverage")
+ attempts, expected_attempts = (
+ _count(condition.get("scored_attempts")),
+ _count(condition.get("expected_attempts")),
+ )
+ if (
+ expected_attempts is not None
+ and (attempts is None or attempts < expected_attempts)
+ and not _mapping(identity.get("attempt_policy")).get("stop_on_pass")
+ ):
+ reasons.append(f"{arm}: incomplete attempt coverage")
+ with_policy = payload.get("score_policy_with_skill", with_condition.get("score_policy"))
+ without_policy = payload.get("score_policy_without_skill", without_condition.get("score_policy"))
+ row_identity = {**identity, "score_policy": with_policy or identity.get("score_policy")}
+ if with_policy and without_policy and with_policy != without_policy:
+ reasons.append("score policy differs between arms")
+ lift = _mapping(_mapping(payload.get("lift")).get("overall")) or _mapping(
+ _mapping(payload.get("custom_lift")).get("overall")
+ )
+ if not lift and agent:
+ retained_lift, _ = _read(root, f"{agent}/lift.json")
+ lift = _mapping(retained_lift.get("overall"))
+ delta = _number(lift.get("delta"), -1, 1)
+ lift_with_score = _number(lift.get("with_skill"))
+ lift_without_score = _number(lift.get("without_skill"))
+ arm_with_score = _number(payload.get("overall_with_skill", summaries["with_skill"].get("overall_score")))
+ arm_without_score = _number(
+ payload.get("overall_without_skill", summaries["without_skill"].get("overall_score"))
+ )
+ if lift_with_score is not None and lift_without_score is not None:
+ with_score, without_score = lift_with_score, lift_without_score
+ else:
+ with_score, without_score = arm_with_score, arm_without_score
+ if arm_with_score is None or arm_without_score is None:
+ reasons.append("one or both condition overall scores are unscored or unknown")
+ if delta is None:
+ reasons.append("paired overall lift was not recorded")
+ elif (
+ any(_number(lift.get(key)) is None for key in ("with_skill", "without_skill"))
+ or abs(lift["with_skill"] - lift["without_skill"] - delta) > 0.0002
+ ):
+ reasons.append("paired overall lift is corrupt")
+ skill = identity["skill"]
+ revision = evaluated_source_revision(_mapping(skill.get("evaluated_source"))) or None
+ digest = _mapping(skill.get("publication_target")).get("skill_digest")
+ model = (
+ payload.get("model")
+ or _mapping(_mapping(config.get("agents")).get(agent)).get("model")
+ or summaries["with_skill"].get("model")
+ )
+ row = {
+ "run_id": run_dir.name,
+ "evaluated_at": result.get("evaluated_at"),
+ "agent": agent,
+ "skill_identity": skill,
+ "skill_revision": revision,
+ "skill_digest": digest,
+ "model": model,
+ "dataset_digest": identity.get("dataset_digest"),
+ "case_count": len(identity["expected_case_ids"])
+ if identity["expected_case_ids"]
+ else coverage["with_skill"]["expected_cases"],
+ "with_skill_score": with_score,
+ "without_skill_score": without_score,
+ "lift_delta": None if reasons else delta,
+ "lift_status": "unavailable" if reasons else "available",
+ "lift_reasons": reasons,
+ "coverage": coverage,
+ "baseline_mode": baseline.get("mode"),
+ "status": status,
+ "score_policy": row_identity.get("score_policy"),
+ }
+ rows.append((row, row_identity))
+ return rows
+
+
+def collect_history(skill_path: Path, results_dir: Path | None = None, agent: str | None = None) -> dict:
+ """Read the first populated results root, with the usual legacy fallback."""
+ candidates = iter_candidate_results_roots(skill_path, results_dir)
+ root, directories = candidates[0], []
+ for candidate in candidates:
+ if found := history_directories(candidate):
+ root, directories = candidate, found
+ break
+ rows, states = [], {}
+ for directory in directories:
+ try:
+ observed = _run_rows(directory, agent)
+ except (OSError, ValueError, SecurePathError) as exc:
+ observed = [
+ (
+ {
+ "run_id": directory.name,
+ "agent": agent,
+ "status": "corrupt",
+ "lift_delta": None,
+ "lift_status": "unavailable",
+ "lift_reasons": [str(exc)],
+ },
+ {},
+ )
+ ]
+ for row, identity in observed:
+ previous = states.get(row["agent"])
+ known = bool(identity) and _known_identity(identity, row["agent"])
+ mismatches = []
+ if previous and identity and previous["identity"]:
+ mismatches = _known_mismatches(identity, previous["identity"], row["agent"])
+ segment = (previous["segment"] + bool(mismatches)) if previous else 1
+ prior_lift = previous["lift"] if previous and not mismatches else None
+ row.update(
+ segment=segment,
+ config_changed=bool(mismatches),
+ identity_status="known" if known else "unknown",
+ comparison_mismatches=mismatches,
+ lift_change=round(row["lift_delta"] - prior_lift, 4)
+ if known and row["lift_delta"] is not None and prior_lift is not None
+ else None,
+ )
+ states[row["agent"]] = {
+ "segment": segment,
+ "identity": identity if known or mismatches or not previous else previous["identity"],
+ "lift": row["lift_delta"]
+ if row["lift_status"] == "available" and known
+ else (prior_lift if not mismatches else None),
+ }
+ rows.append({key: row.get(key) for key in _ROW_FIELDS})
+ return {"schema_version": "1.0", "results_root": str(root), "rows": rows}
+
+
+def _coverage(row: dict) -> str:
+ def arm(name):
+ value = _mapping(_mapping(row.get("coverage")).get(name))
+ return f"{value.get('scored_cases') if value.get('scored_cases') is not None else '?'}/{value.get('expected_cases') if value.get('expected_cases') is not None else '?'}"
+
+ return f"{arm('with_skill')} / {arm('without_skill')}"
+
+
+def _display(value: Any) -> str:
+ return "unknown" if value is None else str(value)
+
+
+def _cells(row: dict) -> list[str]:
+ return [
+ str(row["segment"]) + (" * BREAK" if row["config_changed"] else ""),
+ row["run_id"],
+ _display(row.get("evaluated_at")),
+ _display(row.get("agent")),
+ _display(row.get("skill_revision") or row.get("skill_digest")),
+ _display(row.get("model")),
+ f"{_display(row.get('dataset_digest'))} ({_display(row.get('case_count'))})",
+ *[
+ "unavailable"
+ if key == "lift_delta" and row.get(key) is None
+ else f"{row[key]:+.4f}"
+ if key == "lift_change" and row.get(key) is not None
+ else _display(row.get(key))
+ for key in ("with_skill_score", "without_skill_score", "lift_delta", "lift_change")
+ ],
+ _coverage(row),
+ _display(row.get("baseline_mode")),
+ _display(row.get("status")),
+ "; ".join(row.get("lift_reasons", [])),
+ ]
+
+
+_HEADERS = (
+ "Segment",
+ "Run",
+ "Evaluated at",
+ "Agent",
+ "Revision / content",
+ "Model",
+ "Dataset (cases)",
+ "With",
+ "Without",
+ "Lift",
+ "Change",
+ "Cases W / WO",
+ "Baseline",
+ "Status",
+ "Lift reason",
+)
+
+_ROW_FIELDS = (
+ "run_id",
+ "evaluated_at",
+ "agent",
+ "skill_identity",
+ "skill_revision",
+ "skill_digest",
+ "model",
+ "dataset_digest",
+ "case_count",
+ "with_skill_score",
+ "without_skill_score",
+ "lift_delta",
+ "lift_status",
+ "lift_reasons",
+ "coverage",
+ "baseline_mode",
+ "status",
+ "score_policy",
+ "segment",
+ "config_changed",
+ "comparison_mismatches",
+ "identity_status",
+ "lift_change",
+)
+
+
+def print_history(history: dict, console: Console) -> None:
+ headers = (_HEADERS[0], "Run / evaluated at", *_HEADERS[3:-1])
+ table = Table(*headers, box=SIMPLE, min_width=220)
+ for row in history["rows"]:
+ if row["config_changed"]:
+ table.add_section()
+ cells = _cells(row)
+ cells[4] = cells[4][:22]
+ cells[6] = f"{_display(row.get('dataset_digest'))[:22]} ({_display(row.get('case_count'))})"
+ if row["lift_delta"] is None:
+ cells[9] = "unavailable"
+ safe_cells = [strip_terminal_controls(cell) for cell in cells]
+ table.add_row(
+ *(Text(cell) for cell in [safe_cells[0], safe_cells[1] + "\n" + safe_cells[2], *safe_cells[3:-1]])
+ )
+ wide_console = Console(
+ file=console.file,
+ width=max(console.width, 240),
+ color_system=console.color_system,
+ force_terminal=console.is_terminal,
+ )
+ wide_console.print(table)
+ if not history["rows"]:
+ console.print("No retained runs match this history request.")
+ for row in history["rows"]:
+ if row.get("lift_reasons"):
+ console.print(
+ Text(
+ strip_terminal_controls(f"{row['run_id']} ({row.get('agent')}): " + "; ".join(row["lift_reasons"]))
+ )
+ )
+ if row["config_changed"]:
+ console.print(
+ Text(
+ strip_terminal_controls(
+ f"BREAK: segment {row['segment']} ({row.get('agent')}): "
+ + "; ".join(row["comparison_mismatches"])
+ )
+ )
+ )
+
+
+def export_history(history: dict, suffix: str) -> str:
+ if suffix == ".json":
+ return json.dumps(history, indent=2, allow_nan=False) + "\n"
+ if suffix == ".csv":
+ output = io.StringIO(newline="")
+ writer = csv.DictWriter(output, fieldnames=_ROW_FIELDS)
+ writer.writeheader()
+ for row in history["rows"]:
+ writer.writerow(
+ {key: json.dumps(value) if isinstance(value, dict | list) else value for key, value in row.items()}
+ )
+ return output.getvalue()
+ if suffix != ".md":
+ raise ValueError("History output must end in .json, .csv or .md")
+
+ def safe(value):
+ return html.escape(str(value)).replace("|", "\\|").replace("\n", " ").replace("\r", " ")
+
+ header = "| " + " | ".join(_HEADERS) + " |"
+ divider = "| " + " | ".join("---" for _ in _HEADERS) + " |"
+ lines = ["# Skill Lift history", "", header, divider]
+ for row in history["rows"]:
+ if row["config_changed"]:
+ lines.extend(
+ [
+ "",
+ f"**Segment {row['segment']} break ({safe(row.get('agent'))}): {safe('; '.join(row['comparison_mismatches']))}**",
+ "",
+ header,
+ divider,
+ ]
+ )
+ lines.append("| " + " | ".join(safe(cell) for cell in _cells(row)) + " |")
+ return "\n".join(lines) + "\n"
diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.json
index 34d12ea4..ff4b9f02 100644
--- a/tests/golden/cli_surface.json
+++ b/tests/golden/cli_surface.json
@@ -3249,6 +3249,53 @@
}
]
},
+ "history": {
+ "params": [
+ {
+ "name": "skill_path",
+ "opts": [
+ "skill_path"
+ ],
+ "param_type": "argument",
+ "required": true,
+ "type": "path"
+ },
+ {
+ "name": "results_dir",
+ "opts": [
+ "--results-dir"
+ ],
+ "param_type": "option",
+ "type": "directory"
+ },
+ {
+ "name": "agent",
+ "opts": [
+ "--agent"
+ ],
+ "param_type": "option",
+ "type": "text"
+ },
+ {
+ "default": "False",
+ "is_flag": true,
+ "name": "as_json",
+ "opts": [
+ "--json"
+ ],
+ "param_type": "option",
+ "type": "boolean"
+ },
+ {
+ "name": "output",
+ "opts": [
+ "--output"
+ ],
+ "param_type": "option",
+ "type": "file"
+ }
+ ]
+ },
"import-metrics": {
"params": [
{
diff --git a/tests/test_tier3_history.py b/tests/test_tier3_history.py
new file mode 100644
index 00000000..f8bb8858
--- /dev/null
+++ b/tests/test_tier3_history.py
@@ -0,0 +1,452 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+from __future__ import annotations
+
+import copy
+import csv
+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.tier3.baseline_store import comparison_identity
+from skillevaluator.tier3.harbor.runner import _reserve_run_dir
+from skillevaluator.tier3.history import collect_history, print_history
+
+
+def _write(path, value):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(value))
+
+
+def _run(
+ root: Path,
+ hour: int,
+ *,
+ score=0.8,
+ model="model-a",
+ policy="policy-a",
+ revision="a",
+ status="succeeded",
+ baseline="fresh",
+):
+ name = f"20260101_{hour:02d}0000"
+ directory = root / name
+ config = {
+ "agents": {"opencode": {"model": model, "source": "explicit"}},
+ "harbor": {"environment": "local"},
+ "judge": {"model": "judge-a"},
+ "evaluated_source": {"commit": revision * 40},
+ }
+ condition = {
+ "execution_status": "succeeded",
+ "scored_cases": 1,
+ "expected_cases": 1,
+ "scored_attempts": 1,
+ "expected_attempts": 1,
+ }
+ result = {
+ "run_id": name,
+ "evaluated_at": f"2026-01-01T{hour:02d}:00:00+00:00",
+ "execution_status": status,
+ "dataset_digest": "sha256:cases",
+ "expected_case_ids": ["case-001"],
+ "evaluator_version": "1",
+ "attempt_policy": {"max_attempts": 1, "stop_on_pass": False, "pass_threshold": 0.5},
+ "score_policy": policy,
+ "baseline": {"mode": baseline},
+ "publication_target": {"skill_digest": f"sha256:{revision}"},
+ "agents": {
+ "opencode": {
+ "model": model,
+ "overall_with_skill": score,
+ "overall_without_skill": 0.5,
+ "score_policy_with_skill": policy,
+ "score_policy_without_skill": policy,
+ "conditions": {"with_skill": copy.deepcopy(condition), "without_skill": copy.deepcopy(condition)},
+ "lift": {"overall": {"with_skill": score, "without_skill": 0.5, "delta": round(score - 0.5, 4)}},
+ }
+ },
+ }
+ result["comparison_identity"] = comparison_identity(config, result)
+ _write(directory / "run_config.json", config)
+ _write(directory / "result.json", result)
+ return directory
+
+
+def _update(directory, update):
+ path = directory / "result.json"
+ result = json.loads(path.read_text())
+ update(result)
+ _write(path, result)
+
+
+def test_chronology_revision_changes_and_lift_trend(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ _run(root, 3, score=0.9, revision="c", baseline="reused")
+ _run(root, 1)
+ _run(root, 2, score=0.5, revision="b")
+ rows = collect_history(skill)["rows"]
+ assert [r["run_id"] for r in rows] == ["20260101_010000", "20260101_020000", "20260101_030000"]
+ assert [r["lift_delta"] for r in rows] == [0.3, 0.0, 0.4]
+ assert [r["lift_change"] for r in rows] == [None, -0.3, 0.4]
+ assert all(r["segment"] == 1 and not r["config_changed"] for r in rows)
+ assert rows[-1]["baseline_mode"] == "reused"
+ assert rows[-1]["coverage"]["with_skill"] == {"scored_cases": 1, "expected_cases": 1}
+
+
[email protected]("change", ["model", "policy"])
+def test_segment_break_stops_trend_across_configuration_change(tmp_path, change):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ _run(root, 1)
+ _run(root, 2, **({"model": "model-b"} if change == "model" else {"policy": "policy-b"}))
+ rows = collect_history(skill)["rows"]
+ assert rows[1]["segment"] == 2 and rows[1]["config_changed"] is True
+ assert rows[1]["lift_change"] is None
+ assert ("model changed" if change == "model" else "score policy changed") in str(rows[1]["comparison_mismatches"])
+
+
+ "failure",
+ ["failed", "incomplete", "corrupt", "missing", "skipped", "baseline_only", "coverage", "unscored", "invalid_delta"],
+)
+def test_unavailable_lift_is_never_zero(tmp_path, failure):
+ skill = tmp_path / "demo"
+ d = _run(skill / "evals/results", 1, score=0.5)
+ if failure == "corrupt":
+ (d / "result.json").write_text("{")
+ elif failure == "missing":
+ (d / "result.json").unlink()
+ else:
+
+ def update(r):
+ a = r["agents"]["opencode"]
+ if failure in {"failed", "incomplete"}:
+ r["execution_status"] = failure
+ elif failure == "skipped":
+ r["baseline"]["mode"] = "skipped"
+ a["conditions"]["without_skill"]["execution_status"] = "skipped"
+ elif failure == "baseline_only":
+ a["conditions"]["with_skill"]["execution_status"] = "skipped"
+ elif failure == "coverage":
+ a["conditions"]["with_skill"]["scored_cases"] = 0
+ elif failure == "unscored":
+ a["overall_with_skill"] = None
+ else:
+ a["lift"]["overall"]["delta"] = True
+
+ _update(d, update)
+ row = collect_history(skill)["rows"][0]
+ assert row["lift_delta"] is None
+ assert row["lift_status"] == "unavailable" and row["lift_reasons"]
+
+
+def test_unknown_old_identity_does_not_create_a_trend(tmp_path):
+ skill = tmp_path / "demo"
+ first = _run(skill / "evals/results", 1)
+ second = _run(skill / "evals/results", 2)
+ for d in (first, second):
+
+ def update(r):
+ r.pop("comparison_identity")
+ r.pop("evaluator_version")
+ r.pop("baseline")
+
+ _update(d, update)
+ rows = collect_history(skill)["rows"]
+ assert rows[0]["skill_revision"] == "a" * 40
+ assert rows[0]["baseline_mode"] is None
+ assert rows[1]["lift_change"] is None
+ assert rows[1]["identity_status"] == "unknown"
+ assert rows[1]["config_changed"] is False
+
+
+def test_external_root_configured_root_and_legacy_fallback(monkeypatch, tmp_path):
+ skill = tmp_path / "demo"
+ _run(skill / "evals/results", 1)
+ _run(tmp_path / "external/demo", 2)
+ monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(tmp_path / "external"))
+ assert collect_history(skill)["rows"][0]["run_id"] == "20260101_020000"
+ _run(tmp_path / "explicit/demo", 3)
+ assert collect_history(skill, tmp_path / "explicit")["rows"][0]["run_id"] == "20260101_030000"
+ monkeypatch.delenv("SKILLEVALUATOR_RESULTS_DIR")
+ assert collect_history(skill, tmp_path / "empty")["rows"][0]["run_id"] == "20260101_010000"
+
+
[email protected]("suffix", ["json", "csv", "md"])
+def test_cli_exports_and_read_only_results(tmp_path, suffix):
+ skill = tmp_path / "demo"
+ root = tmp_path / "external/demo"
+ _run(root, 1)
+ _run(root, 2, model="model-b")
+ skill.mkdir()
+
+ def snapshot():
+ return {p: (p.read_bytes(), p.stat().st_mtime_ns) for p in root.rglob("*") if p.is_file()}
+
+ before = snapshot()
+ output = tmp_path / f"history.{suffix}"
+ args = ["tier3", "history", str(skill), "--results-dir", str(root.parent)]
+ result = CliRunner().invoke(cli, [*args, "--json", "--output", str(output)])
+ assert result.exit_code == 0, result.output
+ assert len(json.loads(result.output)["rows"]) == 2
+ if suffix == "json":
+ assert json.loads(output.read_text())["rows"][1]["segment"] == 2
+ elif suffix == "csv":
+ assert list(csv.DictReader(io.StringIO(output.read_text())))[1]["config_changed"] == "True"
+ else:
+ assert "**Segment 2 break" in output.read_text()
+ assert snapshot() == before
+ table = CliRunner().invoke(cli, args)
+ assert table.exit_code == 0, table.output
+ assert "BREAK" in table.output and "model changed" in table.output
+ assert json.loads(CliRunner().invoke(cli, [*args, "--agent", "absent", "--json"]).output)["rows"] == []
+ refused = CliRunner().invoke(cli, [*args, "--output", str(root / "overwrite.md")])
+ assert refused.exit_code != 0 and "outside" in refused.output
+ assert snapshot() == before
+
+
+def test_agent_segments_are_independent(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ for hour in (1, 2):
+ directory = _run(root, hour)
+
+ def update(r):
+ r["agents"]["codex"] = copy.deepcopy(r["agents"]["opencode"])
+
+ _update(directory, update)
+ rows = collect_history(skill)["rows"]
+ assert [r["agent"] for r in rows] == ["codex", "opencode", "codex", "opencode"]
+ opencode = collect_history(skill, agent="opencode")["rows"]
+ assert opencode[1]["lift_change"] == 0.0
+
+
+def _set_codex(directory: Path, model: str | None, *, status: str = "succeeded") -> None:
+ config_path = directory / "run_config.json"
+ result_path = directory / "result.json"
+ config = json.loads(config_path.read_text())
+ result = json.loads(result_path.read_text())
+ if model is None:
+ config["agents"].pop("codex", None)
+ result["agents"].pop("codex", None)
+ else:
+ config["agents"]["codex"] = {"model": model, "source": "explicit"}
+ codex = copy.deepcopy(result["agents"]["opencode"])
+ codex["model"] = model
+ codex["execution_status"] = status
+ result["agents"]["codex"] = codex
+ result["agents"]["opencode"]["execution_status"] = "succeeded"
+ result["comparison_identity"] = comparison_identity(config, result)
+ _write(config_path, config)
+ _write(result_path, result)
+
+
+def test_agent_lift_status_is_independent_of_run_status(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ succeeded = _run(root, 1)
+ failed = _run(root, 2, status="failed")
+ _set_codex(succeeded, "codex-a")
+ _set_codex(failed, "codex-a", status="failed")
+
+ opencode = collect_history(skill, agent="opencode")["rows"]
+ codex = collect_history(skill, agent="codex")["rows"]
+
+ assert opencode[1]["status"] == "failed"
+ assert opencode[1]["lift_delta"] == 0.3
+ assert codex[1]["lift_delta"] is None
+ assert "agent status is failed" in codex[1]["lift_reasons"]
+
+
+def test_agent_segments_ignore_other_agents_changes(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ first, second, third = (_run(root, hour) for hour in (1, 2, 3))
+ _set_codex(first, "codex-a")
+ _set_codex(second, "codex-b")
+ _set_codex(third, None)
+
+ rows = collect_history(skill, agent="opencode")["rows"]
+
+ assert [row["segment"] for row in rows] == [1, 1, 1]
+ assert not any(row["config_changed"] for row in rows)
+ assert rows[-1]["lift_change"] == 0.0
+
+
+def test_with_and_without_columns_use_recorded_lift_operands(tmp_path):
+ skill = tmp_path / "demo"
+ run = _run(skill / "evals/results", 1, score=0.6)
+ result = json.loads((run / "result.json").read_text())
+ result["agents"]["opencode"]["lift"]["overall"] = {
+ "with_skill": 0.6667,
+ "without_skill": 0.5667,
+ "delta": 0.1,
+ }
+ _write(run / "result.json", result)
+
+ row = collect_history(skill)["rows"][0]
+
+ assert row["with_skill_score"] == 0.6667
+ assert row["without_skill_score"] == 0.5667
+
+
+def test_csv_export_disables_newline_translation(monkeypatch, tmp_path):
+ skill = tmp_path / "demo"
+ _run(skill / "evals/results", 1)
+ output = tmp_path / "history.csv"
+ original_write_text = Path.write_text
+ observed = {}
+
+ def write_text(path, data, encoding=None, errors=None, newline=None):
+ if path == output:
+ observed["newline"] = newline
+ return original_write_text(path, data, encoding=encoding, errors=errors, newline=newline)
+
+ monkeypatch.setattr(Path, "write_text", write_text)
+ result = CliRunner().invoke(
+ cli,
+ ["tier3", "history", str(skill), "--output", str(output)],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert observed["newline"] == ""
+
+
+def test_history_sanitizes_terminal_controls_in_cells_and_reasons(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ _run(root, 1)
+ _run(root, 2, model="model\x1b]8;;https://example.invalid\x1b\\")
+ output = io.StringIO()
+
+ print_history(collect_history(skill), Console(file=output, width=300))
+
+ assert "\x1b" not in output.getvalue()
+ assert "BREAK: segment" in output.getvalue()
+
+
+def test_legacy_completed_run_has_legacy_status_not_missing_result_error(tmp_path):
+ from test_results_location_legacy_compatibility import (
+ _write_legacy_run_config,
+ _write_successful_summary,
+ )
+
+ skill = tmp_path / "demo"
+ legacy = skill / "evals/results/20260709_120000"
+ legacy.mkdir(parents=True)
+ _write_legacy_run_config(legacy, "opencode")
+ _write_successful_summary(legacy)
+
+ row = collect_history(skill)["rows"][0]
+
+ assert row["status"] == "legacy"
+ assert "legacy run: no run-level result.json; case coverage not recorded" in row["lift_reasons"]
+ assert not any("No such file or directory" in reason for reason in row["lift_reasons"])
+
+
+def test_new_run_reservation_keeps_previous_runs(tmp_path):
+ original = _run(tmp_path, 1)
+ before = (original / "result.json").read_bytes()
+ new = _reserve_run_dir(tmp_path, "20260101_020000")
+ assert new.is_dir() and original.is_dir()
+ assert (original / "result.json").read_bytes() == before
+
+
+def test_available_trend_skips_unavailable_rows_in_same_segment(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ _run(root, 1)
+ _run(root, 2, status="failed")
+ _run(root, 3, score=0.9)
+ rows = collect_history(skill)["rows"]
+ assert rows[1]["lift_delta"] is None
+ assert rows[2]["lift_change"] == 0.1
+ assert all(row["segment"] == 1 for row in rows)
+
+
+def test_partial_failed_run_still_exposes_known_configuration_change(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ _run(root, 1)
+ failed = _run(root, 2, status="failed")
+ result = json.loads((failed / "result.json").read_text())
+ for key in ("comparison_identity", "dataset_digest", "expected_case_ids", "attempt_policy", "score_policy"):
+ result.pop(key)
+ result["agents"] = {}
+ _write(failed / "result.json", result)
+ config = json.loads((failed / "run_config.json").read_text())
+ config["harbor"]["n_attempts"] = 2
+ _write(failed / "run_config.json", config)
+ rows = collect_history(skill)["rows"]
+ assert rows[1]["config_changed"] and rows[1]["segment"] == 2
+ assert "n_attempts" in str(rows[1]["comparison_mismatches"])
+ assert "dataset changed" not in str(rows[1]["comparison_mismatches"])
+ assert rows[1]["lift_delta"] is None
+
+
+def test_per_agent_policy_is_recovered_when_global_policy_is_unknown(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ for hour, policy in ((1, "policy-a"), (2, "policy-b")):
+ directory = _run(root, hour, policy=policy)
+
+ def update(r):
+ r["score_policy"] = None
+ r["comparison_identity"]["score_policy"] = None
+
+ _update(directory, update)
+ rows = collect_history(skill)["rows"]
+ assert rows[1]["config_changed"] and rows[1]["score_policy"] == "policy-b"
+ assert "score policy changed" in str(rows[1]["comparison_mismatches"])
+
+
+def test_persisted_comparison_config_remains_authoritative(tmp_path):
+ skill = tmp_path / "demo"
+ root = skill / "evals/results"
+ _run(root, 1)
+ later = _run(root, 2)
+ config = json.loads((later / "run_config.json").read_text())
+ config["report_metadata"] = {"source_run_id": "another-run"}
+ _write(later / "run_config.json", config)
+ rows = collect_history(skill)["rows"]
+ assert rows[1]["config_changed"] is False
+ assert rows[1]["lift_change"] == 0.0
+
+
+def test_table_keeps_full_model_and_dataset_case_count(tmp_path):
+ skill = tmp_path / "demo"
+ model = "provider/long-model-name-with-distinct-version"
+ _run(skill / "evals/results", 1, model=model)
+ output = io.StringIO()
+ print_history(collect_history(skill), Console(file=output, width=300))
+ assert model in output.getvalue()
+ assert "sha256:cases (1)" in output.getvalue()
+
+
+def test_empty_history_and_invalid_export(tmp_path):
+ skill = tmp_path / "demo"
+ skill.mkdir()
+ result = CliRunner().invoke(cli, ["tier3", "history", str(skill), "--json"])
+ assert result.exit_code == 0 and json.loads(result.output)["rows"] == []
+ invalid = CliRunner().invoke(cli, ["tier3", "history", str(skill), "--output", str(tmp_path / "bad.txt")])
+ assert invalid.exit_code != 0 and "must end in" in invalid.output
+
+
+def test_corrupt_config_and_linked_artifacts_do_not_escape(tmp_path):
+ skill = tmp_path / "demo"
+ d = _run(skill / "evals/results", 1)
+ (d / "run_config.json").unlink()
+ try:
+ (d / "run_config.json").symlink_to(d / "result.json")
+ except OSError:
+ pytest.skip("symlinks unavailable")
+ row = collect_history(skill)["rows"][0]
+ assert row["lift_delta"] is None and "run_config.json" in str(row["lift_reasons"])