Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(tier3): reuse a compatible retained no-skill baseline (#384)
Christopher Kevin01b1e63116c2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8b684208..0e6f1b57 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 --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.+- Tier 3 evaluations support token, judge-call, attempt, and priced-cost budgets.- Tier 3 reports list up to three run-level **Next steps** under the per-casediff --git a/docs/cli-reference.mdx b/docs/cli-reference.mdxindex edf7d4e4..57c623b1 100644--- a/docs/cli-reference.mdx+++ b/docs/cli-reference.mdx@@ -502,6 +502,7 @@ Use `skillevaluator tier3 PATH` for the complete workflow with automatic missing| `--autopilot` | off | Create one eval case when no dataset/task source exists, then evaluate. The case is LLM-generated with the configured provider, with a deterministic keyless template fallback; an existing source is never overwritten. || `--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`. || `--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.mdxindex 2992acf4..384613bd 100644--- a/docs/reports.mdx+++ b/docs/reports.mdx@@ -503,6 +503,16 @@ completed run directly:relative path, byte size, and SHA-256 digest. The in-process return valueremains complete; readers rebuilding a report from disk follow thoseartifact references.+- **Baseline provenance** — `result.json` and `run_config.json` include a+ `baseline` block with mode `fresh`, `reused`, or `skipped`. Reused baselines+ record `source_run_id`, `source_evaluated_at`, `source_run_dir`, and+ `source_identity`. A `latest` fallback records bounded `rejected_candidates`+ and a `reuse_reason`. `comparison_identity` separates baseline configuration+ from skill revision. Each agent's `execution_counts` and `measured_usage`+ distinguish fresh execution from reused evidence (not new spend). Missing+ token/cost measurements stay unavailable rather than becoming zero. Reused+ baseline rows remain in the new run; its without-skill summary is marked+ `reused`.- **`run_config.json`** / **`attempt_policy.json`** — exactly how the run wasconfigured: environment, attempts, concurrency, grading mode, pass threshold.- **`report.html`** — the human-readable report, generated automatically atdiff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex 16bb04e2..09c2e786 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -726,6 +726,7 @@ The high-signal flags, with defaults:| `--max-agents` | selected-agent count | Maximum agents run in parallel || `--max-cases` | every case | Run only the first N eval cases; a run that skips cases is not publication evidence || `--skip-baseline` | off | Skip the without-skill arm; faster, but no Skill Lift |+| `--reuse-baseline RUN` | off | Reuse a compatible fresh baseline from a retained run id, or `latest` || `--skip-with-skill` | off | Run only the without-skill arm, for example to calibrate a task set; the report shows baseline scores with no Skill Lift or skill verdict || `--stop-on-pass` | off | Stop a case's remaining attempts once one passes || `--agent-runtime-preflight` | off | Add one agent-only execution of the first staged task per agent before the full A/B matrix; `--no-agent-runtime-preflight` overrides a config value that enables it |@@ -754,6 +755,30 @@ While iterating on a dataset, `--skip-baseline` roughly halves the runtime.Re-enable the baseline arm for any run whose Skill Lift you intend to trust.</Tip>+### Reuse a baseline++Use `skillevaluator tier3 evaluate ./my-skill --reuse-baseline latest` to run+the with-skill arm against an existing without-skill baseline in the same+results root. An explicit retained run id can replace `latest`. This option+cannot be combined with `--skip-baseline` or `--skip-with-skill`.++Reuse requires matching datasets and case coverage, selected agents and resolved+models (including model sources), environment configuration, judge/scorer,+attempt policy, evaluator version, and workspace/repository-context settings.+Skill content and evaluated revision are separate from baseline compatibility.+The source must have a successful, complete, freshly executed without-skill arm+with readable persisted case/attempt evidence. Older runs without that evidence,+failed or partial baselines, and runs which themselves reused a baseline are+not sources. Keep the original fresh run if you want to reuse it again.++An incompatible explicit id fails before agent jobs launch and lists the+rejection reasons. `latest` searches completed runs newest first; if none is+compatible, evaluation runs a fresh baseline and records bounded rejection+diagnostics. Reports identify the source and timestamp when reuse succeeds.+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.+### Baseline-only runs`--skip-with-skill` is the counterpart of `--skip-baseline`: it stages and runsdiff --git a/src/skillevaluator/cli.py b/src/skillevaluator/cli.pyindex f01a24d1..d73d73c0 100644--- a/src/skillevaluator/cli.py+++ b/src/skillevaluator/cli.py@@ -3240,6 +3240,9 @@ def _tier2_workflow(help="Create one eval case when no dataset/task source exists, then evaluate.",)@click.option("--skip-baseline", is_flag=True, help="Skip without-skill baseline.")+ "--reuse-baseline", metavar="RUN", default=None, help="Reuse a compatible retained baseline run id or latest."+)@click.option("--skip-with-skill",is_flag=True,@@ -3356,6 +3359,7 @@ def evaluate(autopilot: bool,skip_baseline: bool,skip_with_skill: bool,+ reuse_baseline: str | None,n_attempts: int | None,max_agent_tokens: int | None,max_judge_calls: int | None,@@ -3395,6 +3399,8 @@ def evaluate(if skip_baseline and skip_with_skill:# Reject before --autopilot can spend a generation call on a run that cannot start.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")from skillevaluator.tier3.evals_config import EvalsConfigError, load_evals_configtry:@@ -3438,6 +3444,7 @@ def evaluate(environment_kwarg=environment_kwarg,skip_baseline=skip_baseline,skip_with_skill=skip_with_skill,+ reuse_baseline=reuse_baseline,n_attempts=n_attempts,max_agent_tokens=max_agent_tokens,max_judge_calls=max_judge_calls,diff --git a/src/skillevaluator/evaluation/options.py b/src/skillevaluator/evaluation/options.pyindex 904322c9..7dbb184d 100644--- a/src/skillevaluator/evaluation/options.py+++ b/src/skillevaluator/evaluation/options.py@@ -57,6 +57,7 @@ class EvaluationOptions:environment_kwargs: dict[str, str] = field(default_factory=dict)# Appended so legacy positional construction keeps its field order.max_cases: int | None = None+ reuse_baseline: str | None = Nonemax_agent_tokens: int | None = Nonemax_judge_calls: int | None = Nonemax_attempts_total: int | None = Nonediff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.pyindex 8b2972e0..2fe324a7 100644--- a/src/skillevaluator/evaluation/tier3_report.py+++ b/src/skillevaluator/evaluation/tier3_report.py@@ -1041,6 +1041,7 @@ def build_agent_eval_payload(payload = {"schema_version": _SCHEMA_VERSION,+ "baseline": (run_config or {}).get("baseline", {}),"summary": summary,"skill_name": skill_name,"mode": mode,diff --git a/src/skillevaluator/reporting/benchmark.py b/src/skillevaluator/reporting/benchmark.pyindex d794de2a..b75b2f7e 100644--- a/src/skillevaluator/reporting/benchmark.py+++ b/src/skillevaluator/reporting/benchmark.py@@ -54,6 +54,7 @@ from skillevaluator.reporting.run_status import resolve_run_statusfrom skillevaluator.reporting.summary_copy import SKILL_LIFT_DEFINITION, pass_at_k_summaryfrom skillevaluator.reporting.tier3_scope import completed_agent_result, validate_report_scopefrom skillevaluator.source_identity import evaluated_source_revision, recorded_evaluated_source+from skillevaluator.tier3.baseline_store import baseline_descriptionfrom skillevaluator.tier3.dataset_provenance import dataset_provenance_displayfrom skillevaluator.tier3.evidence_volume import format_evidence_volumefrom skillevaluator.tier3_environments import HARBOR_ENV_MODES@@ -431,6 +432,8 @@ class BenchmarkReporter(ReporterBase):if tier3_run_idelse "- Tier 3 run ID: not recorded (Tier 3 did not complete)")+ if baseline := _mapping((ae or {}).get("baseline")):+ lines.append(f"- {_publication_safe_inline(baseline_description(baseline))}")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.pyindex 6029be91..ee1907df 100644--- a/src/skillevaluator/reporting/cli.py+++ b/src/skillevaluator/reporting/cli.py@@ -55,6 +55,7 @@ from skillevaluator.reporting.presentation import FinalRenderContext, build_finafrom skillevaluator.reporting.run_status import Status, result_statusfrom skillevaluator.reporting.summary_copy import SKILL_LIFT_DEFINITION, pass_at_k_summaryfrom skillevaluator.reporting.terminal_styles import AMBER, FAINT, GREEN, RED, TEXT, grade_style, lift_style+from skillevaluator.tier3.baseline_store import baseline_descriptionfrom skillevaluator.tier3.dataset_provenance import dataset_provenance_displayfrom skillevaluator.tier3.evidence_volume import format_evidence_volumefrom skillevaluator.utils.rich_markup import escape_markup@@ -419,6 +420,8 @@ class CLIReporter(ReporterBase):@staticmethoddef _print_agent_eval_tables(agent_eval: dict, console: Console) -> None:"""Print Tier 3 agent evaluation results."""+ if agent_eval.get("baseline"):+ console.print(escape_markup(baseline_description(agent_eval["baseline"])))verdict = agent_eval.get("verdict", "unknown")best_agent = agent_eval.get("best_agent")multiple_agents = isinstance(agent_eval.get("agents_run"), list) and len(agent_eval["agents_run"]) > 1diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.pyindex e87d2aea..31e9a7ef 100644--- a/src/skillevaluator/reporting/html.py+++ b/src/skillevaluator/reporting/html.py@@ -101,6 +101,7 @@ from skillevaluator.reporting.tier3_scope import completed_agent_result, validatfrom skillevaluator.reporting.trial_charts import steps_by_case_chartfrom skillevaluator.skillspector_provenance import skillspector_provenance_recordsfrom skillevaluator.source_identity import recorded_evaluated_source+from skillevaluator.tier3.baseline_store import baseline_descriptionfrom skillevaluator.tier3.dataset_provenance import dataset_provenance_displayfrom skillevaluator.tier3.evidence_volume import format_evidence_volume@@ -1286,6 +1287,9 @@ def _sanitize_tier3_display_payload(value: dict[str, Any]) -> dict[str, Any]:maximum=1.0,)payload["runtime_seconds"] = _finite_number(payload.get("runtime_seconds"), minimum=0.0) or 0.0+ baseline = payload.get("baseline")+ if isinstance(baseline, dict) and baseline:+ payload["baseline_description"] = baseline_description(baseline)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.pyindex cb6b46e0..2e44ef5f 100644--- a/src/skillevaluator/reporting/markdown.py+++ b/src/skillevaluator/reporting/markdown.py@@ -43,6 +43,7 @@ from skillevaluator.reporting.harbor_viewer import ()from skillevaluator.reporting.run_status import Status, resolve_run_status, result_statusfrom skillevaluator.reporting.summary_copy import SKILL_LIFT_DEFINITION, pass_at_k_summary+from skillevaluator.tier3.baseline_store import baseline_descriptionfrom skillevaluator.tier3.dataset_provenance import dataset_provenance_displayif TYPE_CHECKING:@@ -355,6 +356,9 @@ class MarkdownReporter(ReporterBase):lines.append("## Tier 3: Agent Evaluation")lines.append("")+ if ae.get("baseline"):+ lines.append(baseline_description(ae["baseline"]))+ 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.j2index 37cb7e27..c80ba182 100644--- a/src/skillevaluator/reporting/templates/report.html.j2+++ b/src/skillevaluator/reporting/templates/report.html.j2@@ -2161,6 +2161,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 %}{% 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.pynew file mode 100644index 00000000..51f2c344--- /dev/null+++ b/src/skillevaluator/tier3/baseline_store.py@@ -0,0 +1,355 @@+# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++"""Comparison identities and validated, retained baseline evidence."""++from __future__ import annotations++import copy+import hashlib+import json+import math+import re+from collections.abc import Sequence+from pathlib import Path+from typing import Any++from skillevaluator.tier3.results_location import ordered_run_directories, run_directory_sort_key++_NON_COMPARISON_FIELDS = frozenset(+ {+ "n_concurrent",+ "jobs_retained",+ "credential_validation",+ "evaluated_source",+ "config_file",+ "private_comparisons",+ "baseline",+ "reuse_baseline",+ "budget",+ }+)+_ARM_TASK_NAME_SUFFIX = re.compile(r"(?m)^(\s*name\s*=\s*['\"][^'\"\r\n]*)-(?:with|without)-skill(['\"]\s*(?:#.*)?)$")+_ARM_TASK_DIR_SUFFIX = re.compile(r"-(?:with|without)-skill$")+_ARM_NEUTRAL_ENTRY_FIELDS = frozenset({"has_skill", "evaluated_skill", "workspace_skill_names"})+BASELINE_ANNOTATION_KEYS = (+ "_trial_name",+ "_trial_root_name",+ "_step_name",+ "_started_at",+ "_attempt_ordinal",+ "_trusted_task_selector",+ "_arm_suffix",+ "_authoritative_entry_id",+ "_result_entry_id",+ "_trusted_case_identity_unresolved",+ "_judge_models",+ "_trajectory_summary",+)+++def measured_condition_usage(condition_dir: Path) -> dict[str, float | None]:+ """Sum observed trajectory counters; missing measurements remain unavailable."""+ fields = ("total_prompt_tokens", "total_completion_tokens", "total_cached_tokens", "total_cost_usd")+ values: dict[str, list[float]] = {field: [] for field in fields}+ seen = set()+ complete = True+ for reward_path in sorted((condition_dir / "trials").glob("*/reward.json")):+ try:+ reward = json.loads(reward_path.read_text(encoding="utf-8"))+ trial_id = reward["trial_id"]+ if trial_id in seen:+ complete = False+ continue+ seen.add(trial_id)+ trajectory = json.loads(reward_path.with_name("trajectory.json").read_text(encoding="utf-8"))+ metrics = trajectory["final_metrics"]+ for field in fields:+ value = metrics.get(field)+ if type(value) in (int, float) and math.isfinite(value) and value >= 0:+ values[field].append(value)+ except (OSError, ValueError, TypeError, KeyError, OverflowError):+ complete = False+ return {+ field: sum(counters) if complete and counters and len(counters) == len(seen) else None+ for field, counters in values.items()+ }+++def identity_dataset_digest(task_dirs: Sequence[Path]) -> str:+ """Hash staged baseline entries without fields that identify one comparison arm."""+ entries = []+ for task_dir in sorted(task_dirs, key=lambda path: path.name):+ task_name = _ARM_TASK_DIR_SUFFIX.sub("", task_dir.name)+ entry_path = task_dir / "tests" / "entry.json"+ if entry_path.is_file():+ entry = json.loads(entry_path.read_text(encoding="utf-8"))+ if not isinstance(entry, dict):+ raise ValueError(f"Invalid staged entry: {entry_path}")+ else:+ entry = None+ entries.append(+ {+ "task": task_name,+ "entry": (+ {key: value for key, value in entry.items() if key not in _ARM_NEUTRAL_ENTRY_FIELDS}+ if isinstance(entry, dict)+ else None+ ),+ }+ )+ encoded = json.dumps(entries, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")+ return "sha256:" + hashlib.sha256(encoded).hexdigest()+++def baseline_task_tree_digest(task_dirs_by_agent: dict[str, Sequence[Path]]) -> str:+ """Hash the staged without-skill task trees, normalizing arm-specific task names."""+ digest = hashlib.sha256()+ for agent, task_dirs in sorted(task_dirs_by_agent.items()):+ for task_dir in sorted(task_dirs, key=lambda path: path.name):+ task_name = _ARM_TASK_DIR_SUFFIX.sub("", task_dir.name)+ header = f"{agent}/{task_name}".encode()+ digest.update(len(header).to_bytes(8, "big"))+ digest.update(header)+ for path in sorted(task_dir.rglob("*")):+ if path.name == "repo-context.json":+ continue+ relative = path.relative_to(task_dir).as_posix()+ if path.is_symlink():+ content = b"symlink\0" + path.readlink().as_posix().encode("utf-8")+ elif path.is_file():+ content = path.read_bytes()+ if relative == "task.toml":+ content = _ARM_TASK_NAME_SUFFIX.sub(r"\1\2", content.decode("utf-8"), count=1).encode("utf-8")+ else:+ continue+ file_header = relative.encode("utf-8")+ digest.update(len(file_header).to_bytes(8, "big"))+ digest.update(file_header)+ digest.update(len(content).to_bytes(8, "big"))+ digest.update(content)+ return "sha256:" + digest.hexdigest()+++def comparison_identity(run_config: dict[str, Any], result: dict[str, Any]) -> dict[str, Any]:+ """Keep unknown configuration relevant by default, separating skill identity."""++ def relevant(value: Any) -> Any:+ if isinstance(value, dict):+ return {key: relevant(item) for key, item in value.items() if key not in _NON_COMPARISON_FIELDS}+ if isinstance(value, list):+ return [relevant(item) for item in value]+ return value++ config = relevant(run_config)+ workspace = config.get("skill_workspace", {})+ skill = {+ "evaluated_source": copy.deepcopy(run_config.get("evaluated_source")),+ "publication_target": copy.deepcopy(result.get("publication_target")),+ }+ if isinstance(workspace, dict) and "decoy_manifest" in workspace:+ skill["workspace_content"] = workspace.pop("decoy_manifest")+ return {+ "config": config,+ "dataset_digest": result.get("dataset_digest"),+ "identity_dataset_digest": result.get("identity_dataset_digest", result.get("dataset_digest")),+ "baseline_task_tree_digest": result.get("baseline_task_tree_digest"),+ "expected_case_ids": sorted(result.get("expected_case_ids", [])),+ "attempt_policy": copy.deepcopy(result.get("attempt_policy")),+ "score_policy": result.get("score_policy"),+ "evaluator_version": result.get("evaluator_version"),+ "skill": skill,+ }+++def comparison_mismatches(current: dict[str, Any], source: dict[str, Any]) -> list[str]:+ """Explain all baseline-relevant differences, ignoring skill revisions."""+ reasons: list[str] = []+ current_config, source_config = current["config"], source["config"]+ for agent, model in current_config.get("agents", {}).items():+ old = source_config.get("agents", {}).get(agent)+ if old != model:+ reasons.append(f"model changed for {agent}: {old} -> {model}")+ added = sorted(set(current.get("expected_case_ids", [])) - set(source.get("expected_case_ids", [])))+ removed = sorted(set(source.get("expected_case_ids", [])) - set(current.get("expected_case_ids", [])))+ current_dataset = current.get("identity_dataset_digest", current.get("dataset_digest"))+ source_dataset = source.get("identity_dataset_digest", source.get("dataset_digest"))+ if current_dataset != source_dataset or added or removed:+ reasons.append(f"dataset changed (cases added: {added[:16]}; removed: {removed[:16]})")+ if current.get("baseline_task_tree_digest") != source.get("baseline_task_tree_digest"):+ reasons.append("staged baseline task tree changed")+ for field in ("attempt_policy", "score_policy", "evaluator_version"):+ if field == "score_policy" and current.get(field) is None:+ continue+ if current.get(field) != source.get(field):+ reasons.append(f"{field.replace('_', ' ')} changed: {source.get(field)} -> {current.get(field)}")+ for field in sorted(set(current_config) | set(source_config)):+ if field == "agents":+ continue+ if current_config.get(field) != source_config.get(field):+ label = {+ "harbor": "environment/attempt policy",+ "judge": "judge/scorer",+ "provider": "judge provider/model",+ }.get(field, field)+ reasons.append(f"{label} changed: {source_config.get(field)} -> {current_config.get(field)}")+ return reasons+++def load_baseline_rows(run_dir: Path, agent: 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 not paths:+ raise ValueError(f"{agent}: missing without-skill reward rows")+ rows = []+ for path in paths:+ try:+ if path.is_symlink() or path.parent.is_symlink() or not path.resolve().is_relative_to(run_dir.resolve()):+ raise ValueError("linked baseline evidence")+ if path.stat().st_size > 2 * 1024 * 1024:+ raise ValueError("oversized baseline evidence")+ row = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError) as exc:+ raise ValueError(f"{agent}: corrupt reward.json ({path.parent.name})") from exc+ if not isinstance(row, dict) or not isinstance(row.get("baseline_evidence"), dict):+ raise ValueError(f"{agent}: reward.json lacks reusable case/attempt evidence")+ evidence = row.pop("baseline_evidence")+ if evidence.get("version") != 1 or not isinstance(evidence.get("annotations"), dict):+ raise ValueError(f"{agent}: unsupported baseline evidence")+ annotations = evidence["annotations"]+ if set(annotations) - set(BASELINE_ANNOTATION_KEYS) or not annotations.get("_trial_root_name"):+ raise ValueError(f"{agent}: invalid baseline case/attempt annotations")+ row.update(annotations)+ row["_authoritative_entry_id"] = True+ rows.append(row)+ return rows+++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."""+ 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"))+ 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:+ 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")+ source_identity = result.get("comparison_identity")+ if not isinstance(source_identity, dict):+ reasons.append("run lacks a persisted comparison identity")+ else:+ recorded = comparison_identity(config, {})["config"]+ cases = source_identity.get("expected_case_ids")+ if (+ source_identity.get("config") != recorded+ or not isinstance(cases, list)+ or not all(isinstance(case, str) for case in cases)+ ):+ reasons.append("source comparison identity disagrees with run configuration")+ else:+ reasons.extend(comparison_mismatches(identity, source_identity))+ if (+ source_identity.get("dataset_digest") != result.get("dataset_digest")+ or source_identity.get("identity_dataset_digest", source_identity.get("dataset_digest"))+ != result.get("identity_dataset_digest", result.get("dataset_digest"))+ or source_identity.get("baseline_task_tree_digest") != result.get("baseline_task_tree_digest")+ or source_identity.get("evaluator_version") != result.get("evaluator_version")+ ):+ reasons.append("source comparison identity disagrees with dataset/evaluator evidence")+ if source_identity.get("score_policy") != result.get("score_policy"):+ reasons.append("source comparison identity disagrees with score policy evidence")+ policy = result.get("attempt_policy", {})+ if source_identity.get("attempt_policy") != {+ key: policy.get(key) for key in ("max_attempts", "pass_threshold", "stop_on_pass")+ }:+ 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", {})+ if condition.get("execution_status") != "succeeded":+ reasons.append(f"{agent}: without-skill 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")+ ):+ reasons.append(f"{agent}: baseline has job, trial or runtime failures")+ try:+ summary = json.loads((run_dir / agent / "without-skill" / "summary.json").read_text(encoding="utf-8"))+ if not isinstance(summary, dict):+ raise ValueError("invalid baseline 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)+ scored, failures = _partition_scoreable_rewards(rows)+ policy = identity["attempt_policy"]+ execution = _condition_execution_summary(+ scored,+ expected_case_ids=identity["expected_case_ids"],+ expected_cases=len(identity["expected_case_ids"]),+ n_attempts=policy["max_attempts"],+ job_failure="",+ stop_on_pass=policy["stop_on_pass"],+ pass_threshold=policy["pass_threshold"],+ reward_failures=failures,+ )+ if failures or execution["execution_status"] != "succeeded":+ reasons.append(f"{agent}: baseline reward coverage is incomplete or unscoreable")+ except (OSError, ValueError, TypeError, KeyError) as exc:+ reasons.append(f"{agent}: missing or corrupt baseline evidence: {exc}")+ return reasons, result+++def select_baseline(root: Path, requested: str, agents: list[str], identity: dict[str, Any]) -> dict[str, Any]:+ """Select fresh evidence, or return bounded rejection diagnostics for latest."""+ if requested != "latest" and (Path(requested).name != requested or requested in {".", ".."}):+ raise ValueError("Baseline run must be a run id under the results root")+ candidates = ordered_run_directories(root, completed_only=True) if requested == "latest" else [root / requested]+ rejected = []+ for candidate in candidates:+ reasons, result = baseline_eligibility(candidate, agents, identity)+ if reasons:+ if requested != "latest":+ raise ValueError(f"Cannot reuse baseline {requested}: " + "; ".join(reasons))+ if len(rejected) < 16:+ rejected.append({"run_id": candidate.name, "reasons": [reason[:1024] for reason in reasons[:16]]})+ continue+ return {+ "mode": "reused",+ "source_run_id": candidate.name,+ "source_evaluated_at": result.get("evaluated_at"),+ "source_run_dir": str(candidate),+ "source_identity": copy.deepcopy(result["comparison_identity"]),+ }+ return {"mode": "fresh", "rejected_candidates": rejected, "reuse_reason": "no compatible completed fresh baseline"}+++def baseline_description(baseline: dict[str, Any]) -> str:+ """Render a compact provenance line shared by reports."""+ if baseline.get("mode") == "reused":+ return f"Baseline: reused from run {baseline.get('source_run_id')} ({baseline.get('source_evaluated_at')})"+ if baseline.get("mode") == "fresh" and baseline.get("reuse_reason"):+ return f"Baseline: fresh (reuse not possible: {baseline['reuse_reason']})"+ return f"Baseline: {baseline.get('mode', 'fresh')}"diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex a15f5b88..13bdce06 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -668,6 +668,7 @@ def evaluate(environment_kwarg: tuple[str, ...] = (),skip_baseline: bool,skip_with_skill: bool = False,+ reuse_baseline: str | None = None,n_attempts: int | None,max_agent_tokens: int | None = None,max_judge_calls: int | None = None,@@ -731,6 +732,8 @@ def evaluate(reporter.emit(ProgressEvent(stage="configuration", state="running"))if skip_baseline and skip_with_skill: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")unknown = validate_agents(agent_list)if unknown:supported = ", ".join(sorted(HARBOR_AGENTS_SUPPORTED))@@ -760,6 +763,7 @@ def evaluate(agents=agent_list,skip_baseline=skip_baseline,skip_with_skill=skip_with_skill,+ reuse_baseline=reuse_baseline,n_attempts=n_attempts,max_agent_tokens=max_agent_tokens,max_judge_calls=max_judge_calls,diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.pyindex 32a46a7f..a2951f63 100644--- a/src/skillevaluator/tier3/harbor/collector.py+++ b/src/skillevaluator/tier3/harbor/collector.py@@ -29,6 +29,7 @@ from pathlib import Path, PurePosixPath, PureWindowsPathfrom typing import Anyfrom skillevaluator.tier3.attempt_verdict import attempt_verdict, scored_goal_accuracy+from skillevaluator.tier3.baseline_store import BASELINE_ANNOTATION_KEYS, load_baseline_rows, measured_condition_usagefrom skillevaluator.tier3.eval_core.atif_helpers import extract_tool_calls_as_dicts, get_skill_tool_callsfrom skillevaluator.tier3.eval_core.checks import check_negative_casefrom skillevaluator.tier3.eval_core.codex_tool_call_normalizer import atif_content_text@@ -6403,6 +6404,10 @@ def _save_trials(reward["_trajectory_summary"] = _summarize_trajectory(materialized_traj)clean_reward = {k: v for k, v in reward.items() if not k.startswith("_")}+ clean_reward["baseline_evidence"] = {+ "version": 1,+ "annotations": {key: reward[key] for key in BASELINE_ANNOTATION_KEYS if key in reward},+ }if safe_materialized_traj is None and trajectory_reason not in {None,"missing_single_step_trajectory",@@ -7048,6 +7053,7 @@ def collect_harbor_results(*,skip_baseline: bool = False,skip_with_skill: bool = False,+ reused_baseline_dir: Path | None = None,n_attempts: int = 1,pass_threshold: float = 0.50,stop_on_pass: bool = False,@@ -7381,6 +7387,7 @@ def collect_harbor_results(without_scores: dict[str, float] = {}without_custom_scores: dict[str, float] = {}without_pass: dict[str, Any] = {}+ without_collected_rewards: list[dict[str, Any]] = []without_runtime_failures: list[dict[str, str]] = []without_trial_failures: list[dict[str, str]] = []without_job_failure = ""@@ -7396,51 +7403,60 @@ def collect_harbor_results(without_job_dir: Path | None = Noneif not skip_baseline:without_job_name = f"{skill_name}-{agent}-without"- without_job_dir = _find_job_dir(jobs_dir, without_job_name)+ without_job_dir = (+ reused_baseline_dir / agent / "without-skill"+ if reused_baseline_dir is not None+ else _find_job_dir(jobs_dir, without_job_name)+ )if without_job_dir:- without_job_ok, without_job_failure = validate_harbor_job_result(- without_job_dir / "result.json",- expected_trials=without_expected_trials,- )- without_job_failure = _published_job_failure(without_job_failure)- without_runtime_failures = _extract_agent_runtime_failures(without_job_dir)- without_trial_failures = _extract_trial_failures(without_job_dir)- preserve_partial = _can_preserve_partial_rewards(without_job_dir, without_trial_failures)- # The runner stages unsuffixed task names when only one arm runs.- without_arm_suffix = "-without-skill" if not skip_with_skill else ""- without_task_entry_ids = (- _staged_task_entry_id_map(output_dir, agent, "without", arm_suffix=without_arm_suffix)- if case_id_by_task_selector is None- else None- )- without_collected_rewards = (- _extract_rewards(+ if reused_baseline_dir is not None:+ without_job_ok, without_job_failure = True, ""+ without_collected_rewards = load_baseline_rows(reused_baseline_dir, agent)+ without_rewards, invalid_score_failures = _partition_scoreable_rewards(without_collected_rewards)+ else:+ without_job_ok, without_job_failure = validate_harbor_job_result(+ without_job_dir / "result.json",+ expected_trials=without_expected_trials,+ )+ without_job_failure = _published_job_failure(without_job_failure)+ without_runtime_failures = _extract_agent_runtime_failures(without_job_dir)+ without_trial_failures = _extract_trial_failures(without_job_dir)+ preserve_partial = _can_preserve_partial_rewards(without_job_dir, without_trial_failures)+ # The runner stages unsuffixed task names when only one arm runs.+ without_arm_suffix = "-without-skill" if not skip_with_skill else ""+ without_task_entry_ids = (+ _staged_task_entry_id_map(output_dir, agent, "without", arm_suffix=without_arm_suffix)+ if case_id_by_task_selector is None+ else None+ )+ without_collected_rewards = (+ _extract_rewards(+ without_job_dir,+ case_id_by_task_selector,+ arm_suffix=without_arm_suffix,+ task_entry_id_map=without_task_entry_ids,+ )+ if without_job_ok or preserve_partial+ else []+ )+ without_rewards, invalid_score_failures = _partition_scoreable_rewards(without_collected_rewards)+ _observe_private_trials(+ agent,+ "without_skill",without_job_dir,+ without_collected_rewards,+ without_rewards,case_id_by_task_selector,- arm_suffix=without_arm_suffix,- task_entry_id_map=without_task_entry_ids,)- if without_job_ok or preserve_partial- else []- )- without_rewards, invalid_score_failures = _partition_scoreable_rewards(without_collected_rewards)- _observe_private_trials(- agent,- "without_skill",- without_job_dir,- without_collected_rewards,- without_rewards,- case_id_by_task_selector,- )- without_recovered = (- _recovered_timeout_attempts(without_job_dir, without_rewards, n_attempts=n_attempts)- if stop_on_pass- else []- )- without_job_recovered = _recovered_job_failure(- without_job_dir, without_trial_failures, without_recovered- )+ without_recovered = (+ _recovered_timeout_attempts(without_job_dir, without_rewards, n_attempts=n_attempts)+ if stop_on_pass+ else []+ )+ without_job_recovered = _recovered_job_failure(+ without_job_dir, without_trial_failures, without_recovered+ )without_logical_rewards = _logical_attempt_rewards(without_rewards)without_mixed_metric_contracts = rewards_have_mixed_metric_contracts(without_rewards)without_trial_failures.extend(invalid_score_failures)@@ -7503,18 +7519,29 @@ def collect_harbor_results(if without_execution["execution_status"] == "succeeded"else None)- _save_trials(- without_collected_rewards,- agent_dir / "without-skill" / "trials",- without_job_dir,- skill_name=skill_name,- agent=agent,- variant="without_skill",- agent_model=agent_model,- agent_model_source=agent_model_source,- expected_case_ids=expected_case_ids,- )+ if reused_baseline_dir is not None:+ for source_reward in (without_job_dir / "trials").glob("*/reward.json"):+ target = agent_dir / "without-skill" / "trials" / source_reward.parent.name+ target.mkdir(parents=True, exist_ok=True)+ shutil.copyfile(source_reward, target / "reward.json")+ for artifact in ("trajectory.json", "result.json"):+ source = source_reward.with_name(artifact)+ if source.is_file() and not source.is_symlink():+ shutil.copyfile(source, target / artifact)+ else:+ _save_trials(+ without_collected_rewards,+ agent_dir / "without-skill" / "trials",+ without_job_dir,+ skill_name=skill_name,+ agent=agent,+ variant="without_skill",+ agent_model=agent_model,+ agent_model_source=agent_model_source,+ expected_case_ids=expected_case_ids,+ )without_summary = {+ "reused": reused_baseline_dir is not None,"agent": agent,"model": agent_model,"model_source": agent_model_source,@@ -7765,6 +7792,27 @@ def collect_harbor_results(without_active_trial_failures, without_recovered_trial_failures = _split_recovered_failures(without_trial_failures, without_recovered)+ with_reward_trials = {+ str(reward.get("_trial_root_name") or reward.get("_trial_name") or "") for reward in with_collected_rewards+ }+ without_reward_trials = {+ str(reward.get("_trial_root_name") or reward.get("_trial_name") or "")+ for reward in without_collected_rewards+ }+ with_unrepresented_failures = {+ str(failure.get("trial") or "")+ for failure in with_active_trial_failures+ if failure.get("trial") and str(failure["trial"]) not in with_reward_trials+ }+ without_unrepresented_failures = {+ str(failure.get("trial") or "")+ for failure in without_active_trial_failures+ if failure.get("trial") and str(failure["trial"]) not in without_reward_trials+ }+ with_execution_count = len(_logical_attempt_rewards(with_collected_rewards)) + len(with_unrepresented_failures)+ without_execution_count = len(_logical_attempt_rewards(without_collected_rewards)) + len(+ without_unrepresented_failures+ )all_results["agents"][agent] = {"model": agent_model,"model_source": agent_model_source,@@ -7827,6 +7875,28 @@ def collect_harbor_results(**agent_execution,"num_trials_with": len(with_logical_rewards),"num_trials_without": len(without_logical_rewards) if not skip_baseline else 0,+ "execution_counts": {+ "fresh": {+ "with_skill": with_execution_count,+ "without_skill": 0 if reused_baseline_dir else without_execution_count,+ },+ "reused": {"without_skill": len(without_logical_rewards) if reused_baseline_dir else 0},+ },+ "measured_usage": {+ "fresh": {+ "with_skill": None+ if with_active_trial_failures+ else measured_condition_usage(agent_dir / "with-skill"),+ "without_skill": None+ if reused_baseline_dir or without_active_trial_failures+ else measured_condition_usage(agent_dir / "without-skill"),+ },+ "reused": {+ "without_skill": measured_condition_usage(agent_dir / "without-skill")+ if reused_baseline_dir+ else None,+ },+ },"output_dir": str(agent_dir.resolve()),}diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex deb69a7c..73225aec 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -68,6 +68,13 @@ from skillevaluator.publication_identity import (publication_target_from_path,)from skillevaluator.source_identity import normalized_evaluated_source+from skillevaluator.tier3.baseline_store import (+ baseline_description,+ baseline_task_tree_digest,+ comparison_identity,+ identity_dataset_digest,+ select_baseline,+)from skillevaluator.tier3.case_ids import validate_case_idsfrom skillevaluator.tier3.eval_core.llm_judge import JUDGE_REASONING_EFFORTfrom skillevaluator.tier3.evals_config import (@@ -5313,6 +5320,7 @@ def _run_harbor_eval_impl(*,skip_baseline: bool = False,skip_with_skill: bool = False,+ reuse_baseline: str | None = None,n_attempts: int | None = None,max_agent_tokens: int | None = None,max_judge_calls: int | None = None,@@ -5366,6 +5374,10 @@ def _run_harbor_eval_impl(detail = "skip_baseline and skip_with_skill are mutually exclusive (no arm would run)"reporter.emit(ProgressEvent(stage="configuration", state="failed", detail=detail))return {"error": [detail]}+ if reuse_baseline and (skip_baseline or skip_with_skill):+ 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 env_mode == ENV_MODE_LOCAL:from skillevaluator.tier3.harbor import local_sandbox@@ -5815,6 +5827,23 @@ def _run_harbor_eval_impl(detail="credentials and selected models verified",))+ effective_resources = harbor_config.get("resources", {})+ effective_resources = dict(effective_resources) if isinstance(effective_resources, Mapping) else {}+ for resource, override in (+ ("cpus", override_cpus),+ ("memory_mb", override_memory_mb),+ ("storage_mb", override_storage_mb),+ ):+ if override is not None:+ effective_resources[resource] = override+ environment_kwargs_digest = hashlib.sha256(+ json.dumps(effective_environment_kwargs, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode(+ "utf-8"+ )+ ).hexdigest()+ runtime_env_digest = hashlib.sha256(+ json.dumps(configured_runtime_env, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")+ ).hexdigest()run_config = {"config_file": str(config_path.relative_to(evaluator_skill_path)) if config_path else "none","harbor": {@@ -5822,12 +5851,21 @@ def _run_harbor_eval_impl("environment_kwargs": {"keys": sorted(effective_environment_kwargs),"sources": environment_kwarg_sources,+ "values_sha256": environment_kwargs_digest,},"n_attempts": n_attempts,"stop_on_pass": bool(stop_on_pass),"n_concurrent": n_concurrent,"timeout_multiplier": timeout_multiplier,"base_image_mode": base_image_mode,+ "resources": {+ "cpus": effective_resources.get("cpus"),+ "memory_mb": effective_resources.get("memory_mb"),+ "storage_mb": effective_resources.get("storage_mb"),+ },+ "agent_workdir": harbor_config.get("agent_workdir"),+ "custom_dockerfile_mode": dockerfile_mode,+ "runtime_env": {"keys": sorted(configured_runtime_env), "values_sha256": runtime_env_digest},"jobs_retained": keep_harbor_jobs,},"provider": {"name": provider.provider, "model": provider.model},@@ -5838,6 +5876,9 @@ def _run_harbor_eval_impl(},"task_source": task_source,"grading": {"mode": grading_mode},+ "skill_workspace": {"mode": workspace_mode},+ "copy_repo": copy_repo,+ "repo_context_exclude_paths": [str(path) for path in repo_context_exclude_paths],"agents": model_resolution,# Persisted so a card rendered later from this run directory records the# source tree that was evaluated, not the evaluator build that ran it.@@ -6250,6 +6291,48 @@ def _run_harbor_eval_impl(task_selectors = expected_task_selectors or []case_id_by_task_selector = expected_case_id_by_task_selector or {}case_ids = [case_id_by_task_selector[selector] for selector in task_selectors]+ baseline_task_dirs = {agent: tuple(emitted_tasks[agent].get("without_skill", ())) for agent in agents}+ try:+ identity_digest = identity_dataset_digest(next(iter(baseline_task_dirs.values()), ()))+ task_tree_digest = baseline_task_tree_digest(baseline_task_dirs)+ except (OSError, UnicodeError, ValueError) as exc:+ return _persist_pre_execution_failure([f"could not record baseline task identity: {exc}"])+ run_config["baseline_task_tree_digest"] = task_tree_digest+ try:+ dataset_truth = _persist_dataset_truth(run_dir, fallback_task_ids=case_ids)+ except DatasetSnapshotContractError as exc:+ return _persist_pre_execution_failure([str(exc)])+ expected_trials = len(task_selectors) * n_attempts+ identity = comparison_identity(+ run_config,+ {+ "dataset_digest": dataset_truth["dataset_digest"],+ "identity_dataset_digest": identity_digest,+ "baseline_task_tree_digest": task_tree_digest,+ "expected_case_ids": case_ids,+ "evaluator_version": dataset_truth["evaluator_version"],+ "publication_target": publication_target,+ "attempt_policy": {+ "max_attempts": n_attempts,+ "pass_threshold": float(pass_threshold),+ "stop_on_pass": bool(stop_on_pass),+ },+ "score_policy": None,+ },+ )+ baseline = {"mode": "skipped" if skip_baseline else "fresh"}+ reused_baseline_dir = None+ if reuse_baseline:+ try:+ baseline = select_baseline(run_dir.parent, reuse_baseline, agents, identity)+ except ValueError as exc:+ return _persist_pre_execution_failure([str(exc)])+ if baseline["mode"] == "reused":+ reused_baseline_dir = Path(baseline["source_run_dir"])+ skip_baseline = True+ run_config["baseline"] = baseline+ if reuse_baseline:+ reporter.emit(ProgressEvent(stage="baseline", state="complete", detail=baseline_description(baseline)))from skillevaluator.tier3.harbor.run_budget import (BudgetConfigurationError,BudgetController,@@ -6300,11 +6383,6 @@ def _run_harbor_eval_impl())run_config["budget"] = budget.metadata()- try:- dataset_truth = _persist_dataset_truth(run_dir, fallback_task_ids=case_ids)- except DatasetSnapshotContractError as exc:- return _persist_pre_execution_failure([str(exc)])- expected_trials = len(task_selectors) * n_attemptsvariants = 2 - int(skip_baseline) - int(skip_with_skill)matrix_trials = expected_trials * sum(variants + len(additional_arms.get(agent, ())) for agent in agents)try:@@ -6427,7 +6505,7 @@ def _run_harbor_eval_impl(model=model_resolution[agent]["model"],env_mode=env_mode,with_skill=agent_task_dirs[agent][0],- baseline=agent_task_dirs[agent][1],+ baseline=None if reused_baseline_dir is not None else agent_task_dirs[agent][1],jobs_dir=jobs_dir,run_env={**runtime_plans[agent].subprocess_env, **job_judge_subprocess_env},n_attempts=n_attempts,@@ -6560,8 +6638,9 @@ def _run_harbor_eval_impl(agents=agents,output_dir=run_dir,jobs_dir=jobs_dir,- skip_baseline=skip_baseline,+ skip_baseline=skip_baseline and reused_baseline_dir is None,skip_with_skill=skip_with_skill,+ reused_baseline_dir=reused_baseline_dir,n_attempts=n_attempts,pass_threshold=float(pass_threshold),stop_on_pass=bool(stop_on_pass),@@ -6582,8 +6661,12 @@ def _run_harbor_eval_impl(_emit_run_finished("failed", "result collection failed")raisereporter.emit(ProgressEvent(stage="collection", state="complete", detail="Harbor results collected"))+ identity["score_policy"] = results.get("score_policy", identity["score_policy"])results.update({+ "baseline": baseline,+ "comparison_identity": identity,+ "expected_case_ids": case_ids,"skill_name": skill_path.name,"run_id": run_id,**_run_owned_publication_fields(),@@ -6598,13 +6681,14 @@ def _run_harbor_eval_impl("dataset_summary": dataset_truth["dataset_summary"],"dataset_digest": dataset_truth["dataset_digest"],"dataset_digest_algorithm": dataset_truth["dataset_digest_algorithm"],+ "identity_dataset_digest": identity_digest,+ "baseline_task_tree_digest": task_tree_digest,"budget": budget.metadata(),"dataset_provenance": dataset_provenance,"run_config": run_config,"partial": bool(budget.not_run),})- run_config["budget"] = budget.metadata()from skillevaluator.evaluation.tier3_report import (_agent_score_policy,_build_agent,diff --git a/src/skillevaluator/tier3/result_display.py b/src/skillevaluator/tier3/result_display.pyindex d82997a5..97a510b8 100644--- a/src/skillevaluator/tier3/result_display.py+++ b/src/skillevaluator/tier3/result_display.py@@ -997,6 +997,11 @@ def render_evaluation_result(duration = result.get("duration_seconds")if _finite_number(duration) is not None:console.print(f"Time: {float(duration):.1f}s")+ baseline = result.get("baseline")+ if isinstance(baseline, Mapping) and (baseline.get("mode") == "reused" or baseline.get("reuse_reason")):+ from skillevaluator.tier3.baseline_store import baseline_description++ console.print(safe(baseline_description(dict(baseline))))budget = result.get("budget")if isinstance(budget, Mapping) and (budget.get("status") == "exhausted" or any(value is not None for value in (budget.get("limits") or {}).values())diff --git a/src/skillevaluator/tier3/workflow.py b/src/skillevaluator/tier3/workflow.pyindex c35bd8c6..4e1296ef 100644--- a/src/skillevaluator/tier3/workflow.py+++ b/src/skillevaluator/tier3/workflow.py@@ -121,6 +121,8 @@ def _preflight_options(skill_path: Path, params: dict[str, Any]) -> dict[str, Anif params.get("skip_baseline") and params.get("skip_with_skill"):raise ValueError("--skip-baseline and --skip-with-skill are mutually exclusive (no arm would run)")+ if params.get("reuse_baseline") and (params.get("skip_baseline") or params.get("skip_with_skill")):+ raise ValueError("--reuse-baseline is mutually exclusive with --skip-baseline and --skip-with-skill")provider = resolve_llm_provider()config, config_path = load_evals_config(skill_path)effective = deepcopy(config)diff --git a/tests/golden/cli_surface.json b/tests/golden/cli_surface.jsonindex 61bff829..4fb12b31 100644--- a/tests/golden/cli_surface.json+++ b/tests/golden/cli_surface.json@@ -813,6 +813,14 @@"param_type": "option","type": "boolean"},+ {+ "name": "reuse_baseline",+ "opts": [+ "--reuse-baseline"+ ],+ "param_type": "option",+ "type": "text"+ },{"default": "False","is_flag": true,@@ -2907,6 +2915,14 @@"param_type": "option","type": "boolean"},+ {+ "name": "reuse_baseline",+ "opts": [+ "--reuse-baseline"+ ],+ "param_type": "option",+ "type": "text"+ },{"default": "False","is_flag": true,@@ -3629,6 +3645,14 @@"param_type": "option","type": "boolean"},+ {+ "name": "reuse_baseline",+ "opts": [+ "--reuse-baseline"+ ],+ "param_type": "option",+ "type": "text"+ },{"default": "False","is_flag": true,diff --git a/tests/test_baseline_store.py b/tests/test_baseline_store.pynew file mode 100644index 00000000..52d83a19--- /dev/null+++ b/tests/test_baseline_store.py@@ -0,0 +1,531 @@+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.+# SPDX-License-Identifier: Apache-2.0++from __future__ import annotations++import copy+import json+from pathlib import Path+from types import SimpleNamespace++import pytest+from click.testing import CliRunner++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.tier3 import baseline_store+from skillevaluator.tier3.harbor import collector, runner, runtime_preflight+from skillevaluator.tier3.harbor.metrics import CUSTOM_ONLY_METRIC_SET, CUSTOM_SCORE_POLICY, DEFAULT_METRICS+++def _write(path: Path, value: object) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(value), encoding="utf-8")+++def _job(path: Path, score: float, *, grading_mode: str = "default") -> None:+ trial = "case-001__attempt"+ _write(+ path / "result.json",+ {+ "n_total_trials": 1,+ "stats": {+ "n_completed_trials": 1,+ "n_errored_trials": 0,+ "n_running_trials": 0,+ "n_pending_trials": 0,+ "n_cancelled_trials": 0,+ "n_retries": 0,+ "evals": {"eval": {"n_trials": 1, "n_errors": 0, "reward_stats": {"reward": {str(score): [trial]}}}},+ },+ },+ )+ _write(path / trial / "result.json", {"trial_name": trial, "task_id": {"path": str(path / "tasks/case-001")}})+ reward = {"entry_id": "case-001", **dict.fromkeys(DEFAULT_METRICS, score)}+ if grading_mode == "custom_only":+ reward = {+ "entry_id": "case-001",+ "metric_set": CUSTOM_ONLY_METRIC_SET,+ "score_policy": CUSTOM_SCORE_POLICY,+ "overall": score,+ }+ _write(path / trial / "verifier" / "reward.json", reward)+++def _identity() -> dict:+ return baseline_store.comparison_identity(+ {+ "agents": {"codex": {"model": "model-a", "source": "explicit"}},+ "harbor": {"environment": "docker"},+ "judge": {"model": "judge-a"},+ },+ {+ "dataset_digest": "sha256:one",+ "expected_case_ids": ["case-001"],+ "evaluator_version": "1",+ "attempt_policy": {"max_attempts": 1, "stop_on_pass": False, "pass_threshold": 0.5},+ },+ )+++ ("field", "value", "reason"),+ [+ ("expected_case_ids", ["case-002"], "dataset changed"),+ ("attempt_policy", {"max_attempts": 3}, "attempt policy changed"),+ ("score_policy", "custom", "score policy changed"),+ ("evaluator_version", "2", "evaluator version changed"),+ ],+)+def test_identity_reasons(field: str, value: object, reason: str) -> None:+ old = _identity()+ current = copy.deepcopy(old)+ current[field] = value+ assert any(reason in item for item in baseline_store.comparison_mismatches(current, old))+++ ("field", "value", "reason"),+ [+ ("agents", {"codex": {"model": "model-b", "source": "explicit"}}, "model changed for codex"),+ ("harbor", {"environment": "local"}, "environment"),+ ("judge", {"model": "judge-b"}, "judge/scorer"),+ ("new_setting", True, "new_setting changed"),+ ],+)+def test_config_identity_reasons(field: str, value: object, reason: str) -> None:+ old = _identity()+ current = copy.deepcopy(old)+ current["config"][field] = value+ assert any(reason in item for item in baseline_store.comparison_mismatches(current, old))+++def test_identity_separates_skill_and_ignores_only_operational_settings() -> None:+ config = {+ "harbor": {"n_concurrent": 1},+ "evaluated_source": {"revision": "one"},+ "budget": {"max_attempts_total": 1},+ }+ old = baseline_store.comparison_identity(config, {})+ config["harbor"]["n_concurrent"] = 8+ config["evaluated_source"]["revision"] = "two"+ config["budget"]["max_attempts_total"] = 8+ current = baseline_store.comparison_identity(config, {})+ assert current["skill"] != old["skill"]+ assert baseline_store.comparison_mismatches(current, old) == []+++def test_identity_tracks_effective_runtime_settings_without_raw_environment_values() -> None:+ config = {+ "harbor": {+ "resources": {"cpus": 4, "memory_mb": 8192},+ "agent_workdir": "/workspace/project",+ "custom_dockerfile_mode": "rebase",+ "runtime_env": {"keys": ["MODEL_TOKEN"], "values_sha256": "a" * 64},+ "environment_kwargs": {"keys": ["credential"], "values_sha256": "b" * 64},+ }+ }+ old = baseline_store.comparison_identity(config, {})+ changed = copy.deepcopy(config)+ changed["harbor"]["runtime_env"]["values_sha256"] = "c" * 64+ current = baseline_store.comparison_identity(changed, {})+ assert baseline_store.comparison_mismatches(current, old)+ assert "MODEL_TOKEN" in str(old["config"])+ assert "credential-value" not in str(old["config"])+++def test_identity_uses_arm_neutral_dataset_digest_without_replacing_snapshot_digest() -> None:+ old = baseline_store.comparison_identity(+ {},+ {+ "dataset_digest": "sha256:arm-specific",+ "identity_dataset_digest": "sha256:neutral",+ "baseline_task_tree_digest": "sha256:tree",+ },+ )+ current = baseline_store.comparison_identity(+ {},+ {+ "dataset_digest": "sha256:other-arm-specific",+ "identity_dataset_digest": "sha256:neutral",+ "baseline_task_tree_digest": "sha256:tree",+ },+ )+ assert old["dataset_digest"] == "sha256:arm-specific"+ assert baseline_store.comparison_mismatches(current, old) == []+ current["identity_dataset_digest"] = "sha256:changed"+ assert any("dataset changed" in item for item in baseline_store.comparison_mismatches(current, old))+++def test_arm_neutral_dataset_and_staged_task_digests(tmp_path: Path) -> None:+ paired = tmp_path / "paired" / "case-001-without-skill"+ baseline = tmp_path / "baseline" / "case-001"+ with_skill = tmp_path / "with" / "case-001-with-skill"+ for task, has_skill, suffix in (+ (paired, False, "-without-skill"),+ (baseline, False, ""),+ (with_skill, True, "-with-skill"),+ ):+ _write(task / "tests/entry.json", {"id": "case-001", "has_skill": has_skill, "evaluated_skill": "demo"})+ (task / "task.toml").parent.mkdir(parents=True, exist_ok=True)+ (task / "task.toml").write_text(+ f'[task]\nname = "nvidia/skillevaluator-case-001{suffix}"\n',+ encoding="utf-8",+ )+ _write(task / "environment/repo-context.json", {"metadata": task.parent.name})+ (task / "environment/Dockerfile").write_text("FROM python:3.12\n", encoding="utf-8")+ (task / "repo/tools/helper.py").parent.mkdir(parents=True, exist_ok=True)+ (task / "repo/tools/helper.py").write_text("VALUE = 1\n", encoding="utf-8")+ assert baseline_store.identity_dataset_digest([paired]) == baseline_store.identity_dataset_digest([with_skill])+ first_tree = baseline_store.baseline_task_tree_digest({"codex": [paired]})+ assert first_tree == baseline_store.baseline_task_tree_digest({"codex": [baseline]})+ (baseline / "repo/tools/helper.py").write_text("VALUE = 2\n", encoding="utf-8")+ assert first_tree != baseline_store.baseline_task_tree_digest({"codex": [baseline]})+++ ("mode", "baseline", "message"),+ [+ ("reused", {"mode": "reused"}, "source run reused a baseline"),+ ("skipped", {"mode": "skipped"}, "source run skipped its baseline"),+ ("missing", None, "source run predates baseline provenance"),+ ],+)+def test_baseline_eligibility_explains_source_mode(tmp_path: Path, monkeypatch, mode, baseline, message) -> None:+ monkeypatch.setattr(baseline_store, "run_directory_sort_key", lambda *_args, **_kwargs: "complete")+ run_dir = tmp_path / "run"+ run_dir.mkdir()+ identity = baseline_store.comparison_identity(+ {},+ {+ "dataset_digest": "sha256:one",+ "expected_case_ids": [],+ "evaluator_version": "1",+ "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},+ "score_policy": "policy",+ },+ )+ result = {+ "dataset_digest": "sha256:one",+ "evaluator_version": "1",+ "attempt_policy": {"max_attempts": 1, "pass_threshold": 0.5, "stop_on_pass": False},+ "score_policy": "policy",+ "comparison_identity": identity,+ }+ config = {}+ if baseline is not None:+ result["baseline"] = baseline+ config["baseline"] = baseline+ _write(run_dir / "result.json", result)+ _write(run_dir / "run_config.json", config)+ reasons, _ = baseline_store.baseline_eligibility(run_dir, [], identity)+ 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])+ assert result.exit_code == 2+ assert "mutually exclusive" in result.output+++def test_collector_reuses_same_rows_and_lift(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:+ jobs = tmp_path / "jobs"+ _job(jobs / "demo-codex-with", 0.75)+ _job(jobs / "demo-codex-without", 0.25)+ fresh = collector.collect_harbor_results(+ "demo", ["codex"], tmp_path / "fresh", jobs, expected_case_ids=["case-001"]+ )++ def guard(name):+ original = getattr(collector, name)++ def checked(*args, **kwargs):+ assert "without" not in str(args), name+ return original(*args, **kwargs)++ monkeypatch.setattr(collector, name, checked)++ for name in (+ "_staged_task_entry_id_map",+ "_extract_rewards",+ "_can_preserve_partial_rewards",+ "_extract_agent_runtime_failures",+ "_extract_trial_failures",+ "_observe_private_trials",+ "_recovered_timeout_attempts",+ "_recovered_job_failure",+ ):+ guard(name)+ reused = collector.collect_harbor_results(+ "demo",+ ["codex"],+ tmp_path / "reuse",+ jobs,+ expected_case_ids=["case-001"],+ reused_baseline_dir=tmp_path / "fresh",+ )+ for key in ("without_skill", "lift", "custom_lift", "pass_at_k", "security_attribution", "conditions"):+ assert reused["agents"]["codex"][key] == fresh["agents"]["codex"][key]+ assert reused["agents"]["codex"]["execution_counts"] == {+ "fresh": {"with_skill": 1, "without_skill": 0},+ "reused": {"without_skill": 1},+ }+ summary = json.loads((tmp_path / "reuse/codex/without-skill/summary.json").read_text())+ assert summary["reused"] is True+ assert baseline_store.load_baseline_rows(tmp_path / "reuse", "codex")+++ "baseline", [{"mode": "fresh"}, {"mode": "reused", "source_run_id": "source", "source_evaluated_at": "time"}]+)+def test_generated_benchmark_reports_baseline(tmp_path: Path, baseline: dict) -> None:+ jobs, output = tmp_path / "jobs", tmp_path / "output"+ _job(jobs / "demo-codex-with", 0.75)+ _job(jobs / "demo-codex-without", 0.25)+ result = collector.collect_harbor_results("demo", ["codex"], output, jobs, expected_case_ids=["case-001"])+ _write(output / "run_config.json", {"baseline": baseline})+ report_result = agent_eval_result_from_directory(+ tmp_path / "demo", output, engine_result=result, use_llm_judge=False+ )+ assert report_result is not None+ report = BenchmarkReporter(skill_name="demo", report_scope="tier3").render(report_result)+ assert baseline_store.baseline_description(baseline) in report+++def test_reused_rows_with_conflicting_policy_fail_collection(tmp_path: Path) -> None:+ jobs = tmp_path / "jobs"+ _job(jobs / "demo-codex-without", 0.25, grading_mode="custom_only")+ collector.collect_harbor_results(+ "demo",+ ["codex"],+ tmp_path / "source",+ jobs,+ skip_with_skill=True,+ expected_case_ids=["case-001"],+ grading_mode="custom_only",+ )+ _job(jobs / "demo-codex-with", 0.75)+ result = collector.collect_harbor_results(+ "demo",+ ["codex"],+ tmp_path / "reuse",+ jobs,+ expected_case_ids=["case-001"],+ reused_baseline_dir=tmp_path / "source",+ )+ agent = result["agents"]["codex"]+ assert agent["execution_status"] == "failed"+ assert "Conflicting score policies across conditions" in str(agent["execution_errors"])+ assert not agent["lift"]+++def test_unobserved_policy_defers_to_collection() -> None:+ current, source = _identity(), _identity()+ source["score_policy"] = CUSTOM_SCORE_POLICY+ assert baseline_store.comparison_mismatches(current, source) == []+++def test_execution_counts_include_unscoreable_trials(tmp_path: Path) -> None:+ jobs = tmp_path / "jobs"+ _job(jobs / "demo-codex-with", 0.75)+ _job(jobs / "demo-codex-without", 0.25)+ reward = jobs / "demo-codex-with/case-001__attempt/verifier/reward.json"+ _write(reward, {"entry_id": "case-001", "evaluation_status": "failed", "error": "judge unavailable"})+ result = collector.collect_harbor_results(+ "demo", ["codex"], tmp_path / "output", jobs, expected_case_ids=["case-001"]+ )+ agent = result["agents"]["codex"]+ assert agent["execution_status"] == "failed"+ assert agent["execution_counts"]["fresh"] == {"with_skill": 1, "without_skill": 1}+++def test_active_failed_trials_count_as_started_and_make_usage_unavailable(monkeypatch, tmp_path: Path) -> None:+ jobs = tmp_path / "jobs"+ _job(jobs / "demo-codex-with", 0.75)+ _job(jobs / "demo-codex-without", 0.25)+ extract = collector._extract_trial_failures++ def extract_with_crash(job_dir: Path):+ if job_dir.name == "demo-codex-with":+ return [{"trial": "case-002__attempt", "reason": "RuntimeError"}]+ return extract(job_dir)++ monkeypatch.setattr(collector, "_extract_trial_failures", extract_with_crash)+ result = collector.collect_harbor_results(+ "demo", ["codex"], tmp_path / "output", jobs, expected_case_ids=["case-001", "case-002"]+ )+ agent = result["agents"]["codex"]+ assert agent["execution_counts"]["fresh"] == {"with_skill": 2, "without_skill": 1}+ 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:+ events = []+ result = runner._run_harbor_eval_impl(+ tmp_path,+ ["opencode"],+ reuse_baseline="latest",+ **{skip: True},+ progress_reporter=SimpleNamespace(emit=events.append),+ )+ assert result["error"]+ assert [(event.stage, event.state) for event in events] == [("configuration", "failed")]+++def test_latest_empty_falls_back_and_explicit_missing_rejects(tmp_path: Path) -> None:+ result = baseline_store.select_baseline(tmp_path, "latest", ["codex"], _identity())+ assert result["mode"] == "fresh"+ assert result["rejected_candidates"] == []+ with pytest.raises(ValueError, match="missing or corrupt"):+ baseline_store.select_baseline(tmp_path, "missing", ["codex"], _identity())+ with pytest.raises(ValueError, match="run id"):+ baseline_store.select_baseline(tmp_path, "../outside", ["codex"], _identity())++[email protected]("grading_mode", ["default", "custom_only"])+def test_runner_fresh_reused_and_incompatible(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, grading_mode: str+) -> None:+ 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]++ launched = []++ def launch(**kwargs):+ launched.append(kwargs["baseline"] is not None)+ for condition, suffix, score in (("with_skill", "with", 0.75), ("baseline", "without", 0.25)):+ if kwargs[condition] is not None:+ _job(kwargs["jobs_dir"] / f"demo-opencode-{suffix}", score, grading_mode=grading_mode)+ return []++ monkeypatch.setattr(runner, "generate_harbor_tasks", emit)+ monkeypatch.setattr(runner, "_run_agent_pair", launch)+ kwargs = {+ "output_dir": tmp_path / "results",+ "env_mode": "docker",+ "agent_runtime_preflight": False,+ "agent_models": {"opencode": "openai/test-model"},+ "grading_mode": grading_mode,+ }+ fresh = runner.run_harbor_eval(skill, ["opencode"], **kwargs)+ assert "error" not in fresh, fresh+ reused = runner.run_harbor_eval(+ skill,+ ["opencode"],+ reuse_baseline=fresh["run_id"],+ max_attempts_total=1,+ **kwargs,+ )+ assert "error" not in reused, reused+ assert launched == [True, False]+ assert reused["baseline"]["mode"] == "reused"+ assert reused["budget"]["planned_attempts"] == 1+ assert fresh["comparison_identity"]["score_policy"] == reused["comparison_identity"]["score_policy"]+ assert fresh["agents"]["opencode"]["lift"] == reused["agents"]["opencode"]["lift"]+ assert (+ baseline_store.select_baseline(tmp_path / "results", "latest", ["opencode"], fresh["comparison_identity"])[+ "source_run_id"+ ]+ == fresh["run_id"]+ )+ incompatible = runner.run_harbor_eval(skill, ["opencode"], reuse_baseline=fresh["run_id"], n_attempts=3, **kwargs)+ assert incompatible["error"]+ assert "attempt" in str(incompatible["error"])+ assert launched == [True, False]++ source = Path(fresh["run_dir"])+ identity = fresh["comparison_identity"]+ result_path = source / "result.json"+ original_result = result_path.read_text()+ changed = json.loads(original_result)+ changed["baseline"] = {"mode": "reused"}+ result_path.write_text(json.dumps(changed))+ assert any("reused" in reason for reason in baseline_store.baseline_eligibility(source, ["opencode"], identity)[0])+ result_path.write_text(original_result)+ assert baseline_store.baseline_eligibility(source, ["missing-agent"], identity)[0]+ reward = next((source / "opencode/without-skill/trials").glob("*/reward.json"))+ original_reward = reward.read_text()+ for invalid in ("{", "{}"):+ reward.write_text(invalid)+ assert baseline_store.baseline_eligibility(source, ["opencode"], identity)[0]+ partial = json.loads(original_reward)+ partial["entry_id"] = "unexpected-case"+ reward.write_text(json.dumps(partial))+ assert any(+ "coverage" in reason for reason in baseline_store.baseline_eligibility(source, ["opencode"], identity)[0]+ )+ reward.write_text(original_reward)+ summary = source / "opencode/without-skill/summary.json"+ summary.write_text(json.dumps({"execution_status": "failed"}))+ assert any("failed" in reason for reason in baseline_store.baseline_eligibility(source, ["opencode"], identity)[0])+ fallback = baseline_store.select_baseline(tmp_path / "results", "latest", ["opencode"], identity)+ assert fallback["mode"] == "fresh"+ assert {candidate["run_id"] for candidate in fallback["rejected_candidates"]} == {fresh["run_id"], reused["run_id"]}+ reward.unlink()+ assert baseline_store.baseline_eligibility(source, ["opencode"], identity)[0]+++def test_usage_separates_missing_and_measured_counters(tmp_path: Path) -> None:+ assert all(value is None for value in baseline_store.measured_condition_usage(tmp_path).values())+ trial = tmp_path / "trials/one"+ _write(trial / "reward.json", {"trial_id": "one"})+ _write(+ trial / "trajectory.json",+ {"final_metrics": {"total_prompt_tokens": 10, "total_completion_tokens": 4, "total_cost_usd": 0.05}},+ )+ usage = baseline_store.measured_condition_usage(tmp_path)+ assert usage["total_prompt_tokens"] == 10+ assert usage["total_completion_tokens"] == 4+ assert usage["total_cost_usd"] == 0.05+ assert usage["total_cached_tokens"] is None+++def test_usage_is_unavailable_when_trial_has_multiple_step_rewards(tmp_path: Path) -> None:+ for step, prompt, cost in (("finish", 300, 0.3), ("prepare", 100, 0.1)):+ trial = tmp_path / "trials" / f"case-001__{step}"+ _write(trial / "reward.json", {"trial_id": "case-001"})+ _write(+ trial / "trajectory.json",+ {"final_metrics": {"total_prompt_tokens": prompt, "total_cost_usd": cost}},+ )+ assert all(value is None for value in baseline_store.measured_condition_usage(tmp_path).values())+++def test_provenance_description() -> None:+ assert (+ baseline_store.baseline_description({"mode": "reused", "source_run_id": "run", "source_evaluated_at": "time"})+ == "Baseline: reused from run run (time)"+ )+ assert (+ baseline_store.baseline_description({"mode": "fresh", "reuse_reason": "no match"})+ == "Baseline: fresh (reuse not possible: no match)"+ )diff --git a/tests/test_commands.py b/tests/test_commands.pyindex bd51258f..9846142f 100644--- a/tests/test_commands.py+++ b/tests/test_commands.py@@ -504,9 +504,7 @@ def test_validate_default_reports_do_not_write_into_authored_sibling_skill(encoding="utf-8",)initial_files = {- path.relative_to(authored_sibling): path.read_bytes()- for path in authored_sibling.rglob("*")- if path.is_file()+ path.relative_to(authored_sibling): path.read_bytes() for path in authored_sibling.rglob("*") if path.is_file()}private_state = tmp_path / "private-state"private_state.mkdir(mode=0o700)@@ -523,9 +521,7 @@ def test_validate_default_reports_do_not_write_into_authored_sibling_skill(assert (output_root / "BENCHMARK.md").is_file()assert is_generated_output_root(output_root)assert {- path.relative_to(authored_sibling): path.read_bytes()- for path in authored_sibling.rglob("*")- if path.is_file()+ path.relative_to(authored_sibling): path.read_bytes() for path in authored_sibling.rglob("*") if path.is_file()} == initial_files@@ -831,9 +827,7 @@ def test_quality_check_applies_custom_quality_config(@pytest.mark.parametrize("command", [["quality-check"], ["tier1", "quality-check"]])def test_quality_check_rejects_missing_quality_config(command: list[str], tmp_path: Path) -> None:- result = CliRunner().invoke(- cli, [*command, str(FIXTURE), "--quality-config", str(tmp_path / "missing.yaml")]- )+ result = CliRunner().invoke(cli, [*command, str(FIXTURE), "--quality-config", str(tmp_path / "missing.yaml")])assert result.exit_code == 2assert "does not exist" in result.output@@ -2559,8 +2553,7 @@ def test_validate_quiet_renders_untrusted_skip_reason_as_bounded_inert_text(unsafe_reason = ("[/bold] [link=https://example.invalid]click[/link]\n"- "## Publication Recommendation\n\x1b[31mforged\u202e "- + "x" * 1_000_000+ "## Publication Recommendation\n\x1b[31mforged\u202e " + "x" * 1_000_000)def _tier3(*_args, **_kwargs):diff --git a/tests/test_evaluation_service.py b/tests/test_evaluation_service.pyindex 30d4e446..79454c55 100644--- a/tests/test_evaluation_service.py+++ b/tests/test_evaluation_service.py@@ -368,7 +368,6 @@ def test_cli_evaluate_validates_cost_price_pair_after_config_merge(assert service_calls-@pytest.mark.parametrize("command", ["validate", "evaluate", "tier3 evaluate"])@pytest.mark.parametrize(("flags", "diagnostic"),diff --git a/tests/test_tier3_config_key_parity.py b/tests/test_tier3_config_key_parity.pyindex 1c92575a..add30982 100644--- a/tests/test_tier3_config_key_parity.py+++ b/tests/test_tier3_config_key_parity.py@@ -10,6 +10,8 @@ parsed values route into the corresponding engine behavior.from __future__ import annotations+import hashlib+import jsonfrom pathlib import Pathfrom types import SimpleNamespacefrom typing import Any@@ -114,6 +116,11 @@ def test_user_config_parses_and_routes_end_to_end(monkeypatch: pytest.MonkeyPatcassert result["run_config"]["grading"]["mode"] == "default_plus_custom"assert result["run_config"]["task_source"] == "evals_json"assert result["run_config"]["harbor"]["stop_on_pass"] is False+ assert result["run_config"]["harbor"]["resources"] == {"cpus": None, "memory_mb": None, "storage_mb": None}+ assert result["run_config"]["harbor"]["agent_workdir"] is None+ assert result["run_config"]["harbor"]["custom_dockerfile_mode"] == "rebase"+ assert result["run_config"]["harbor"]["runtime_env"]["keys"] == []+ assert len(result["run_config"]["harbor"]["runtime_env"]["values_sha256"]) == 64assert captured["emit"]["grading_mode"] == "default_plus_custom"assert captured["pair"]["stop_on_pass"] is Falseassert captured["pair"]["pass_threshold"] == 0.6@@ -150,6 +157,9 @@ harbor:}assert "error" not in resultassert captured["pair"]["environment_kwargs"] == expected+ expected_hash = hashlib.sha256(+ json.dumps(expected, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")+ ).hexdigest()assert result["run_config"]["harbor"]["environment_kwargs"] == {"keys": ["instance_id", "launch_mode", "region"],"sources": {@@ -157,9 +167,47 @@ harbor:"launch_mode": "CLI","region": "CLI",},+ "values_sha256": expected_hash,}+def test_baseline_identity_records_runtime_environment_and_effective_resources(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ runtime_value = "private-runtime-value"+ config = """\+schema_version: 1+harbor:+ task_source: evals_json+ resources:+ cpus: 2+ memory_mb: 4096+ storage_mb: 8192+ agent_workdir: /workspace/project+ custom_dockerfile_mode: rebase+ runtime_env:+ SE_BASELINE_IDENTITY: private-runtime-value+"""+ result, _captured = _run_engine(monkeypatch, tmp_path, config, override_cpus=4)++ assert "error" not in result+ harbor = result["run_config"]["harbor"]+ runtime_hash = hashlib.sha256(+ json.dumps(+ {"SE_BASELINE_IDENTITY": runtime_value},+ sort_keys=True,+ separators=(",", ":"),+ ensure_ascii=False,+ ).encode("utf-8")+ ).hexdigest()+ assert harbor["resources"] == {"cpus": 4, "memory_mb": 4096, "storage_mb": 8192}+ assert harbor["agent_workdir"] == "/workspace/project"+ assert harbor["custom_dockerfile_mode"] == "rebase"+ assert harbor["runtime_env"] == {"keys": ["SE_BASELINE_IDENTITY"], "values_sha256": runtime_hash}+ assert runtime_value not in json.dumps(result["run_config"])++def test_stop_on_pass_config_key_routes_sequential_attempt_policy(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/test_tier3_result_display.py b/tests/test_tier3_result_display.pyindex 3aaaff5d..f8b7b279 100644--- a/tests/test_tier3_result_display.py+++ b/tests/test_tier3_result_display.py@@ -312,6 +312,34 @@ def test_case_first_display_keeps_case_matrix_columns_and_ids_at_width_80() -> Nassert "FAIL: goal not met (goal accuracy 0.00)" in rendered+ ("baseline", "expected"),+ [+ (+ {"mode": "reused", "source_run_id": "source", "source_evaluated_at": "time"},+ "Baseline: reused from run source (time)",+ ),+ ({"mode": "fresh", "reuse_reason": "no compatible completed baseline"}, "Baseline: fresh (reuse not possible"),+ ],+)+def test_evaluation_summary_reports_reused_or_fallback_baseline(baseline, expected: str) -> None:+ stream = io.StringIO()+ render_evaluation_result(+ {"execution_status": "succeeded", "baseline": baseline, "agents": {}},+ console=Console(file=stream, force_terminal=False, width=180),+ )+ assert expected in stream.getvalue()+++def test_evaluation_summary_omits_unremarkable_fresh_baseline() -> None:+ stream = io.StringIO()+ render_evaluation_result(+ {"execution_status": "succeeded", "baseline": {"mode": "fresh"}, "agents": {}},+ console=Console(file=stream, force_terminal=False, width=180),+ )+ assert "Baseline:" not in stream.getvalue()++@pytest.mark.parametrize("change",[diff --git a/tests/tier3/test_workflow.py b/tests/tier3/test_workflow.pyindex 02ec15a4..35dbcb66 100644--- a/tests/tier3/test_workflow.py+++ b/tests/tier3/test_workflow.py@@ -229,6 +229,21 @@ def test_invalid_options_error_before_generating(skill, configured, monkeypatch,assert not configured[email protected]("skip", ["--skip-baseline", "--skip-with-skill"])+def test_reuse_baseline_conflicts_before_autopilot_generation(skill, configured, monkeypatch, skip):+ monkeypatch.setattr(+ EvaluationService, "create_autopilot_dataset", lambda *_args, **_kwargs: pytest.fail("must preflight")+ )+ result = CliRunner().invoke(+ _command(),+ [str(skill), "--reuse-baseline", "latest", skip, "--progress", "off"],+ )+ assert result.exit_code != 0+ assert "--reuse-baseline is mutually exclusive" in result.output+ assert not (skill / "evals").exists()+ assert not configured++def test_invalid_configuration_does_not_generate(skill, configured, monkeypatch):(skill / "evals").mkdir()config = skill / "evals" / "config.yml"