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
fix(tier3): close final isolation review gaps
Christopher Kevin18b29bca7956
diff --git a/src/skillevaluator/tier3/commands.py b/src/skillevaluator/tier3/commands.pyindex 3205601e..35eeb962 100644--- a/src/skillevaluator/tier3/commands.py+++ b/src/skillevaluator/tier3/commands.py@@ -50,6 +50,7 @@ from skillevaluator.tier3.harbor.runner import (from skillevaluator.tier3.harbor.secure_copy import copytree_securefrom skillevaluator.tier3.results_location import (iter_candidate_results_roots,+ ordered_run_directories,resolve_latest_results,resolve_results_root,)@@ -927,8 +928,7 @@ def harbor_view(jobs_dir: Path) -> int:def compare_results(skill_path: Path, *, results_dir: Path | None = None) -> int:"""Compare latest Harbor result scores across agents."""candidate_roots = iter_candidate_results_roots(skill_path, results_dir)- resolved_results_dir = next((root for root in candidate_roots if root.exists()), candidate_roots[0])- if not resolved_results_dir.exists():+ if not any(root.exists() for root in candidate_roots):searched = ", ".join(str(p) for p in candidate_roots)console.print(f"[red]Error: No results found. Searched: {searched}[/red]")return 1@@ -937,40 +937,51 @@ def compare_results(skill_path: Path, *, results_dir: Path | None = None) -> intagent_without: dict[str, dict[str, float]] = {}agent_meta: dict[str, dict[str, Any]] = {}- for ts_dir in sorted(resolved_results_dir.iterdir(), reverse=True):- if not ts_dir.is_dir() or ts_dir.name.startswith("_") or ts_dir.name == "latest":+ for candidate_root in candidate_roots:+ if not candidate_root.exists():continue- for agent_dir in sorted(ts_dir.iterdir()):- if not agent_dir.is_dir() or agent_dir.name.startswith("_"):- continue- agent_name = agent_dir.name- if agent_name in agent_with:- continue- summary = agent_dir / "with-skill" / "summary.json"- if not summary.exists():- summary = agent_dir / "summary.json"- if not summary.exists():- continue+ root_with: dict[str, dict[str, float]] = {}+ root_without: dict[str, dict[str, float]] = {}+ root_meta: dict[str, dict[str, Any]] = {}+ for ts_dir in ordered_run_directories(candidate_root):try:- data = json.loads(summary.read_text(encoding="utf-8"))- except (ValueError, OSError):+ agent_dirs = sorted(ts_dir.iterdir())+ except OSError:continue- scores = _summary_scores(data)- if scores:- agent_with[agent_name] = scores- agent_meta[agent_name] = {- "timestamp": ts_dir.name,- "path": str(agent_dir),- "num_trials": data.get("num_trials", "?"),- }- wo_summary = agent_dir / "without-skill" / "summary.json"- if wo_summary.exists():- try:- wo_scores = _summary_scores(json.loads(wo_summary.read_text(encoding="utf-8")))- if wo_scores:- agent_without[agent_name] = wo_scores- except (ValueError, OSError):- pass+ for agent_dir in agent_dirs:+ if not agent_dir.is_dir() or agent_dir.name.startswith("_"):+ continue+ agent_name = agent_dir.name+ if agent_name in root_with:+ continue+ summary = agent_dir / "with-skill" / "summary.json"+ if not summary.exists():+ summary = agent_dir / "summary.json"+ if not summary.exists():+ continue+ try:+ data = json.loads(summary.read_text(encoding="utf-8"))+ except (ValueError, OSError):+ continue+ scores = _summary_scores(data)+ if scores:+ root_with[agent_name] = scores+ root_meta[agent_name] = {+ "timestamp": ts_dir.name,+ "path": str(agent_dir),+ "num_trials": data.get("num_trials", "?"),+ }+ wo_summary = agent_dir / "without-skill" / "summary.json"+ if wo_summary.exists():+ try:+ wo_scores = _summary_scores(json.loads(wo_summary.read_text(encoding="utf-8")))+ if wo_scores:+ root_without[agent_name] = wo_scores+ except (ValueError, OSError):+ pass+ if root_with:+ agent_with, agent_without, agent_meta = root_with, root_without, root_meta+ breakif not agent_with:console.print("[red]No agent results found. Run skillevaluator evaluate first.[/red]")@@ -1030,6 +1041,8 @@ def compare_results(skill_path: Path, *, results_dir: Path | None = None) -> intdef _summary_scores(data: dict[str, Any]) -> dict[str, float]:+ if not isinstance(data, dict):+ return {}if data.get("execution_status") != "succeeded":return {}scores: dict[str, float] = {}diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.pyindex 9153b1d7..af82d626 100644--- a/src/skillevaluator/tier3/harbor/adapter.py+++ b/src/skillevaluator/tier3/harbor/adapter.py@@ -914,19 +914,41 @@ def _git_context_files(root: Path) -> list[Path]:return [root / line for line in result.stdout.splitlines() if line.strip()]-def _iter_repo_context_files(root: Path, authenticated_output_roots: set[Path]) -> list[Path]:+def _iter_repo_context_files(+ root: Path,+ authenticated_output_roots: set[Path],+ excluded_roots: Sequence[Path] = (),+) -> list[Path]:+ """Enumerate repository files without inspecting excluded output trees."""git_files = _git_context_files(root)if git_files:return sorted(pathfor path in git_files- if path.is_file() and not _repo_context_ignore_file(path, root, authenticated_output_roots)+ if not _path_is_excluded(path, excluded_roots)+ and path.is_file()+ and not _repo_context_ignore_file(path, root, authenticated_output_roots))- return sorted(- path- for path in root.rglob("*")- if path.is_file() and not _repo_context_ignore_file(path, root, authenticated_output_roots)- )++ files: list[Path] = []+ pending = [root]+ while pending:+ directory = pending.pop()+ with os.scandir(directory) as entries:+ for entry in entries:+ path = Path(entry.path)+ # This lexical-first check must happen before stat/is_file or+ # descent: result trees can contain unsafe or unreadable user+ # artifacts and are explicitly outside the staged context.+ if _path_is_excluded(path, excluded_roots):+ continue+ if _repo_context_ignore_file(path, root, authenticated_output_roots):+ continue+ if entry.is_dir(follow_symlinks=False):+ pending.append(path)+ elif entry.is_file(follow_symlinks=False) or entry.is_symlink():+ files.append(path)+ return sorted(files)def _stage_repo_context(@@ -974,7 +996,11 @@ def _stage_repo_context(staged: list[dict[str, str]] = []if mode == "full":- for src in _iter_repo_context_files(repo_root, authenticated_output_roots):+ for src in _iter_repo_context_files(+ repo_root,+ authenticated_output_roots,+ resolved_excluded_roots,+ ):if _is_excluded_output(src):continueif _repo_context_ignore_file(src, repo_root, authenticated_output_roots):@@ -1002,14 +1028,25 @@ def _stage_repo_context(for raw_target in _discover_skill_link_targets(skill_md):target = _strip_link_target(raw_target)- lexical_target_path = source_skill_path / target if not Path(target).is_absolute() else Path(target)- target_path = lexical_target_path.resolve()- if not target_path.is_file():+ raw_target_path = source_skill_path / target if not Path(target).is_absolute() else Path(target)+ lexical_target_path = Path(os.path.abspath(raw_target_path)) # noqa: PTH100 -- normalize without resolving+ if _path_is_excluded(lexical_target_path, resolved_excluded_roots):+ logger.warning("Skipping SKILL.md link into generated output: %s", raw_target)+ continue+ try:+ target_path = lexical_target_path.resolve(strict=True)+ except (OSError, RuntimeError):+ logger.warning("Skipping unreadable SKILL.md repo link: %s", raw_target)+ continue+ try:+ if not target_path.is_file():+ continue+ except OSError:continueif not _is_relative_to(target_path, repo_root):logger.warning("Skipping SKILL.md link outside repo root: %s", raw_target)continue- if _is_excluded_output(target_path) or _path_is_excluded(lexical_target_path, resolved_excluded_roots):+ if _is_excluded_output(target_path):logger.warning("Skipping SKILL.md link into generated output: %s", raw_target)continueif _repo_context_ignore_file(@@ -1731,7 +1768,7 @@ def _copy_custom_grader(task_dir: Path, skill_path: Path, grading_mode: str) ->if not resolved_evals.is_relative_to(resolved_skill) or not resolved_grader.is_relative_to(resolved_evals):raise ValueError(f"custom grader must be a non-symlinked regular file contained under evals/: {grader}")- shutil.copy2(resolved_grader, destination, follow_symlinks=False)+ copy_file_secure(grader, destination, allowed_root=skill_path / "evals")if destination.suffix == ".sh":destination.chmod(0o755)return True@@ -2874,6 +2911,11 @@ _PROJECT_SKILL_RELATIVE_DIRS = (".opencode/skills",".qwen/skills",)+_RUNTIME_PROJECTION_ROOTS = ("/workspace/input", "/workspace/repo", *_RUNTIME_SKILL_DIRS)+_RUNTIME_PROJECTION_CASE_PATTERNS = (+ *(pattern for root in _RUNTIME_PROJECTION_ROOTS for pattern in (root, f"{root}/*")),+ *(pattern for relative in _PROJECT_SKILL_RELATIVE_DIRS for pattern in (f"*/{relative}", f"*/{relative}/*")),+)_RUNTIME_DISCOVERY_ENV_NAMES = frozenset({"CLAUDE_CODE_DISABLE_POLICY_SKILLS",@@ -2965,16 +3007,7 @@ _DISCOVERY_ENV_SKILL_RESET = ('clear_skill_root "$XDG_CONFIG_HOME/opencode/skills"; fi')_RUNTIME_PROJECTION_OVERLAP_PREFLIGHT = (- 'set -eu; check_path() { value=$1; case "$value" in '- "/workspace/input|/workspace/input/*|/workspace/repo|/workspace/repo/*|"- "/workspace/skills|/workspace/skills/*|"- "*/.agents/skills|*/.agents/skills/*|*/.claude/commands|*/.claude/commands/*|"- "*/.claude/skills|*/.claude/skills/*|*/.cline/skills|*/.cline/skills/*|"- "*/.codex/skills|*/.codex/skills/*|*/.config/goose/skills|*/.config/goose/skills/*|"- "*/.config/opencode/skills|*/.config/opencode/skills/*|"- "*/.cursor/skills|*/.cursor/skills/*|*/.gemini/skills|*/.gemini/skills/*|"- "*/.gemini/extensions|*/.gemini/extensions/*|"- "*/.opencode/skills|*/.opencode/skills/*|*/.qwen/skills|*/.qwen/skills/*) "+ 'set -eu; check_path() { value=$1; case "$value" in ' + "|".join(_RUNTIME_PROJECTION_CASE_PATTERNS) + ") ""echo 'SkillEvaluator agent workdir/home overlaps an evaluator-controlled runtime projection' >&2; "'exit 78;; esac; }; check_control_path() { value=$1; check_path "$value"; ''if [ -d "$value" ]; then canonical=$(CDPATH= cd -P -- "$value" 2>/dev/null && /bin/pwd -P) || exit 78; '@@ -3020,22 +3053,10 @@ def _validated_agent_workdir(agent_workdir: str | None) -> str | None:or re.fullmatch(r"/[A-Za-z0-9._/-]*", normalized) is None):raise ValueError("agent_workdir must be a normalized absolute POSIX path")- reserved_roots = ("/workspace/input", "/workspace/repo", "/workspace/skills")- if any(normalized == root or normalized.startswith(f"{root}/") for root in reserved_roots):+ if any(normalized == root or normalized.startswith(f"{root}/") for root in _RUNTIME_PROJECTION_ROOTS):raise ValueError("agent_workdir must not be inside an evaluator-controlled runtime projection")parts = tuple(part for part in normalized.split("/") if part)- discovery_parts = (- (".agents", "skills"),- (".claude", "skills"),- (".cline", "skills"),- (".codex", "skills"),- (".config", "goose", "skills"),- (".config", "opencode", "skills"),- (".cursor", "skills"),- (".gemini", "skills"),- (".opencode", "skills"),- (".qwen", "skills"),- )+ discovery_parts = tuple(tuple(relative.split("/")) for relative in _PROJECT_SKILL_RELATIVE_DIRS)if any(parts[index : index + len(candidate)] == candidatefor candidate in discovery_parts@@ -4433,7 +4454,7 @@ def stage_native_harbor_tasks(base_image=base_image,custom_dockerfile_mode=custom_dockerfile_mode,copy_repo=copy_repo,- repo_context_exclude_paths=(*repo_context_exclude_paths, output_dir),+ repo_context_exclude_paths=(*repo_context_exclude_paths, output_dir, private_root),runtime_env=runtime_env,verifier_env=verifier_env,pre_agent_setup=pre_agent_setup,@@ -4682,7 +4703,7 @@ def generate_harbor_tasks(base_image=base_image,custom_dockerfile_mode=custom_dockerfile_mode,copy_repo=copy_repo,- repo_context_exclude_paths=(*repo_context_exclude_paths, output_dir),+ repo_context_exclude_paths=(*repo_context_exclude_paths, output_dir, private_root),runtime_env=runtime_env,verifier_env=verifier_env,pre_agent_setup=pre_agent_setup,diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.pyindex a3c402ee..57fea093 100644--- a/src/skillevaluator/tier3/harbor/collector.py+++ b/src/skillevaluator/tier3/harbor/collector.py@@ -870,12 +870,46 @@ def _extract_rewards(job_dir: Path) -> list[dict[str, Any]]:"""Extract reward.json from all trials in a job directory."""rewards: list[dict[str, Any]] = []scored_trial_roots: set[Path] = set()+ authoritative_trial_roots: set[Path] = set()++ # Native multi-step Harbor tasks can persist an authoritative aggregate at+ # the trial root in addition to one reward file per step. Materialize that+ # single logical row first so both averages and pass@k use the same score.+ for result_file in sorted(job_dir.glob("*/result.json")):+ trial_dir = result_file.parent+ if _trial_failure_reason(trial_dir) or _is_agent_runtime_failure_trial(trial_dir):+ continue+ result = _read_json(result_file)+ if not isinstance(result, dict) or not isinstance(result.get("step_results"), list):+ continue+ verifier_result = result.get("verifier_result")+ if not isinstance(verifier_result, dict) or not isinstance(verifier_result.get("rewards"), dict):+ continue+ data = _reward_from_harbor_result(result)+ if not data:+ continue+ trial_name = str(result.get("trial_name") or trial_dir.name)+ data["_trial_name"] = trial_name+ data["_trial_root_name"] = trial_dir.name+ data["_started_at"] = result.get("started_at")+ if not data.get("entry_id"):+ entry_id = _entry_id_from_harbor_result(result)+ if entry_id:+ data["entry_id"] = entry_id+ traj_file = _reward_trajectory_path(trial_dir, None)+ if traj_file.exists():+ data["_has_trajectory"] = True+ rewards.append(data)+ authoritative_trial_roots.add(trial_dir)+for reward_file in sorted(job_dir.rglob("reward.json")):if reward_file.parent.name == "verifier":try:+ trial_dir, trial_name, step_name = _reward_trial_context(reward_file)+ if trial_dir in authoritative_trial_roots:+ continuedata = json.loads(reward_file.read_text(encoding="utf-8"))_merge_reward_sidecars(data, reward_file.parent)- trial_dir, trial_name, step_name = _reward_trial_context(reward_file)if _trial_failure_reason(trial_dir) or _is_agent_runtime_failure_trial(trial_dir):logger.debug("Skipping reward for failed Harbor trial: %s",@@ -908,7 +942,8 @@ def _extract_rewards(job_dir: Path) -> list[dict[str, Any]]:for result_file in sorted(job_dir.glob("*/result.json")):trial_dir = result_file.parentif (- trial_dir in scored_trial_roots+ trial_dir in authoritative_trial_roots+ or trial_dir in scored_trial_rootsor _trial_failure_reason(trial_dir)or _is_agent_runtime_failure_trial(trial_dir)):@@ -1126,6 +1161,24 @@ def _logical_attempt_rewards(rewards: list[dict[str, Any]]) -> list[dict[str, Anreturn logical+def harbor_job_passed(job_dir: Path, pass_threshold: float) -> bool:+ """Return whether a complete logical attempt meets the pass threshold.++ This deliberately shares collection's failure filtering and multi-step+ reward precedence. A root Harbor ``result.json`` reward is authoritative;+ step rewards are averaged only when Harbor did not persist one.+ """+ job_ok, _ = validate_harbor_job_result(job_dir / "result.json")+ trial_failures = _extract_trial_failures(job_dir)+ if not job_ok and not _can_preserve_partial_rewards(job_dir, trial_failures):+ return False+ rewards, _ = _partition_scoreable_rewards(_extract_rewards(job_dir))+ return any(+ (score := _overall_score(reward)) is not None and score >= pass_threshold+ for reward in _logical_attempt_rewards(rewards)+ )++def _pass_summary(rewards: list[dict[str, Any]],*,diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.pyindex 068e7e77..e208bdad 100644--- a/src/skillevaluator/tier3/harbor/runner.py+++ b/src/skillevaluator/tier3/harbor/runner.py@@ -11,6 +11,7 @@ import osimport reimport shleximport shutil+import statimport subprocessimport tempfileimport time@@ -39,8 +40,12 @@ from skillevaluator.tier3.harbor.adapter import (validate_results_root_location,)from skillevaluator.tier3.harbor.artifact_retention import HarborArtifactLifecycle, RetentionOutcome-from skillevaluator.tier3.harbor.collector import collect_harbor_results, validate_harbor_job_result-from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, overall_score, score_definition+from skillevaluator.tier3.harbor.collector import (+ collect_harbor_results,+ harbor_job_passed,+ validate_harbor_job_result,+)+from skillevaluator.tier3.harbor.metrics import DEFAULT_METRICS, score_definitionfrom skillevaluator.tier3.harbor.progress import (NullProgressReporter,ProgressEvent,@@ -53,6 +58,7 @@ from skillevaluator.tier3.harbor.progress import (from skillevaluator.tier3.harbor.secure_copy import copytree_securefrom skillevaluator.tier3.harbor.secure_docker_environment import SECURE_DOCKER_ENV_IMPORT_PATHfrom skillevaluator.tier3.output_provenance import mark_generated_output_root+from skillevaluator.tier3.results_location import publish_latest_resultsfrom skillevaluator.tier3_environments import DEFAULT_ENV_MODE, ENV_MODE_LOCAL, HARBOR_ENV_MODESlogger = logging.getLogger(__name__)@@ -1162,20 +1168,8 @@ def _validate_harbor_job_result(def _job_passed(job_dir: Path, pass_threshold: float) -> bool:- """Return True when any reward in a one-task Harbor job reaches threshold."""- for reward_file in sorted(job_dir.rglob("reward.json")):- if reward_file.parent.name != "verifier":- continue- try:- reward = json.loads(reward_file.read_text(encoding="utf-8"))- except (json.JSONDecodeError, OSError):- continue- if not isinstance(reward, dict):- continue- score = overall_score(reward)- if score is not None and score >= pass_threshold:- return True- return False+ """Use collector-authoritative logical-attempt semantics for early stop."""+ return harbor_job_passed(job_dir, pass_threshold)def _attempt_job_stats(@@ -1228,6 +1222,31 @@ def _attempt_job_stats(return total, completed, errored, evals_out+def _job_path_is_link_or_reparse(path: Path, metadata: os.stat_result) -> bool:+ """Return whether an attempt-job root is a symlink, junction, or reparse point."""+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if stat.S_ISLNK(metadata.st_mode) or bool(getattr(metadata, "st_file_attributes", 0) & reparse_flag):+ return True+ is_junction = getattr(path, "is_junction", None)+ if not callable(is_junction):+ return False+ try:+ return bool(is_junction())+ except (OSError, RuntimeError):+ return True+++def _job_root_fingerprint(metadata: os.stat_result) -> tuple[int, int, int, int, int, int]:+ return (+ metadata.st_dev,+ metadata.st_ino,+ metadata.st_mode,+ metadata.st_nlink,+ metadata.st_mtime_ns,+ metadata.st_ctime_ns,+ )++def _merge_attempt_jobs(job_dirs: list[Path], aggregate_dir: Path) -> None:"""Merge per-attempt Harbor jobs into the job directory shape collection expects.@@ -1235,61 +1254,115 @@ def _merge_attempt_jobs(job_dirs: list[Path], aggregate_dir: Path) -> None:per-attempt Harbor ``result.json`` statistics are combined so the mergedjob still satisfies :func:`validate_harbor_job_result`."""- if aggregate_dir.exists():- shutil.rmtree(aggregate_dir)- aggregate_dir.mkdir(parents=True, exist_ok=True)-- total_trials = 0- completed_trials = 0- errored_trials = 0- merged_evals: dict[str, dict[str, Any]] = {}+ aggregate_path = Path(os.path.abspath(aggregate_dir)) # noqa: PTH100 -- compare lexical publication roots+ source_paths: list[tuple[str, Path, Path, tuple[int, int, int, int, int, int]]] = []for job_dir in job_dirs:- if not job_dir.is_dir():+ job_path = Path(os.path.abspath(job_dir)) # noqa: PTH100 -- reject overlap before temp creation+ if not os.path.lexists(job_path):continue- renamed: dict[str, str] = {}- for child in sorted(job_dir.iterdir()):- if not child.is_dir():+ try:+ metadata = job_path.lstat()+ except OSError as exc:+ raise ValueError(f"cannot inspect attempt Harbor job root: {job_path}") from exc+ if _job_path_is_link_or_reparse(job_path, metadata) or not stat.S_ISDIR(metadata.st_mode):+ raise ValueError(f"attempt Harbor job root must be a non-linked directory: {job_path}")+ try:+ job_resolved = job_path.resolve(strict=True)+ except (OSError, RuntimeError) as exc:+ raise ValueError(f"cannot resolve attempt Harbor job root: {job_path}") from exc+ aggregate_resolved = aggregate_path.resolve(strict=False)+ if (+ aggregate_resolved == job_resolved+ or aggregate_resolved.is_relative_to(job_resolved)+ or job_resolved.is_relative_to(aggregate_resolved)+ ):+ raise ValueError("aggregate Harbor job directory must not overlap an attempt job directory")+ source_paths.append((job_path.name, job_path, job_resolved, _job_root_fingerprint(metadata)))++ aggregate_path.parent.mkdir(parents=True, exist_ok=True)+ with tempfile.TemporaryDirectory(+ prefix=f".{aggregate_path.name}-merge-",+ dir=aggregate_path.parent,+ ) as private_root_raw:+ private_root = Path(private_root_raw)+ snapshot_root = private_root / "attempt-jobs"+ snapshot_root.mkdir()+ staged_aggregate = private_root / "aggregate"+ staged_aggregate.mkdir()++ snapshots: list[tuple[str, Path]] = []+ for index, (job_name, job_path, job_resolved, expected_fingerprint) in enumerate(source_paths):+ snapshot = snapshot_root / f"{index:04d}-{job_name}"+ try:+ before = job_path.lstat()+ except OSError as exc:+ raise ValueError(f"attempt Harbor job root changed before snapshot: {job_path}") from exc+ if _job_path_is_link_or_reparse(job_path, before) or _job_root_fingerprint(before) != expected_fingerprint:+ raise ValueError(f"attempt Harbor job root changed before snapshot: {job_path}")+ copytree_secure(job_path, snapshot, allowed_root=job_resolved)+ try:+ after = job_path.lstat()+ except OSError as exc:+ raise ValueError(f"attempt Harbor job root changed during snapshot: {job_path}") from exc+ if _job_path_is_link_or_reparse(job_path, after) or _job_root_fingerprint(after) != expected_fingerprint:+ raise ValueError(f"attempt Harbor job root changed during snapshot: {job_path}")+ snapshots.append((job_name, snapshot))++ total_trials = 0+ completed_trials = 0+ errored_trials = 0+ merged_evals: dict[str, dict[str, Any]] = {}+ for job_name, job_dir in snapshots:+ renamed: dict[str, str] = {}+ for child in sorted(job_dir.iterdir()):+ if not child.is_dir():+ continue+ dest = staged_aggregate / f"{job_name}__{child.name}"+ suffix = 2+ while dest.exists():+ dest = staged_aggregate / f"{job_name}__{child.name}-{suffix}"+ suffix += 1+ copytree_secure(child, dest, allowed_root=job_dir)+ renamed[child.name] = dest.name++ stats = _attempt_job_stats(job_dir)+ if stats is None:continue- dest = aggregate_dir / f"{job_dir.name}__{child.name}"- suffix = 2- while dest.exists():- dest = aggregate_dir / f"{job_dir.name}__{child.name}-{suffix}"- suffix += 1- copytree_secure(child, dest, allowed_root=job_dir)- renamed[child.name] = dest.name-- stats = _attempt_job_stats(job_dir)- if stats is None:- continue- job_total, job_completed, job_errored, job_evals = stats- total_trials += job_total- completed_trials += job_completed- errored_trials += job_errored- for eval_name, (eval_trials, eval_errors, reward_stats) in job_evals.items():- merged = merged_evals.setdefault(eval_name, {"n_trials": 0, "n_errors": 0, "reward_stats": {}})- merged["n_trials"] += eval_trials- merged["n_errors"] += eval_errors- for metric, buckets in reward_stats.items():- merged_buckets = merged["reward_stats"].setdefault(metric, {})- for bucket, trial_names in buckets.items():- merged_buckets.setdefault(bucket, []).extend(- renamed.get(name, f"{job_dir.name}__{name}") for name in trial_names- )+ job_total, job_completed, job_errored, job_evals = stats+ total_trials += job_total+ completed_trials += job_completed+ errored_trials += job_errored+ for eval_name, (eval_trials, eval_errors, reward_stats) in job_evals.items():+ merged = merged_evals.setdefault(eval_name, {"n_trials": 0, "n_errors": 0, "reward_stats": {}})+ merged["n_trials"] += eval_trials+ merged["n_errors"] += eval_errors+ for metric, buckets in reward_stats.items():+ merged_buckets = merged["reward_stats"].setdefault(metric, {})+ for bucket, trial_names in buckets.items():+ merged_buckets.setdefault(bucket, []).extend(+ renamed.get(name, f"{job_name}__{name}") for name in trial_names+ )- (aggregate_dir / "result.json").write_text(- json.dumps(- {- "n_total_trials": total_trials,- "stats": {- "n_trials": completed_trials,- "n_errors": errored_trials,- "evals": merged_evals,+ (staged_aggregate / "result.json").write_text(+ json.dumps(+ {+ "n_total_trials": total_trials,+ "stats": {+ "n_trials": completed_trials,+ "n_errors": errored_trials,+ "evals": merged_evals,+ },},- },- indent=2,- ),- encoding="utf-8",- )+ indent=2,+ ),+ encoding="utf-8",+ )+ copytree_secure(+ staged_aggregate,+ aggregate_path,+ replace_existing=aggregate_path.exists(),+ allowed_root=private_root,+ )def _run_stop_on_pass_variant(@@ -2178,13 +2251,7 @@ def _run_harbor_eval_impl(else:reporter.emit(ProgressEvent(stage="report", state="complete", detail="result and HTML reports written"))- latest = root / "latest"- try:- if latest.is_symlink() or latest.exists():- latest.unlink()- latest.symlink_to(run_id)- except OSError:- pass+ publish_latest_results(root, run_id)return resultsdiff --git a/src/skillevaluator/tier3/results_location.py b/src/skillevaluator/tier3/results_location.pyindex c6c21bb3..9d62af99 100644--- a/src/skillevaluator/tier3/results_location.py+++ b/src/skillevaluator/tier3/results_location.py@@ -7,9 +7,12 @@ from __future__ import annotationsimport jsonimport os+import statimport subprocess+from contextlib import suppressfrom datetime import datetimefrom pathlib import Path+from uuid import uuid4ENV_RESULTS_DIR = "SKILLEVALUATOR_RESULTS_DIR"_RUN_TIMESTAMP_FORMATS = (("%Y%m%d_%H%M%S", 15), ("%Y-%m-%d_%H%M%S", 17))@@ -103,32 +106,110 @@ def _run_timestamp(name: str) -> datetime | None:return None-def _newest_completed_run(root: Path) -> Path | None:- """Return the newest complete timestamped run without relying on symlinks."""+def _path_is_link_or_reparse(path: Path, metadata: os.stat_result) -> bool:+ """Return whether a result path is a symlink, junction, or reparse point."""+ reparse_flag = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)+ if stat.S_ISLNK(metadata.st_mode) or bool(getattr(metadata, "st_file_attributes", 0) & reparse_flag):+ return True+ is_junction = getattr(path, "is_junction", None)+ if not callable(is_junction):+ return False+ try:+ return bool(is_junction())+ except (OSError, RuntimeError):+ return True+++def run_directory_sort_key(+ candidate: Path,+ *,+ require_completed_result: bool = False,+) -> tuple[datetime, int, str] | None:+ """Return shared newest-first ordering metadata for a result directory.++ Timestamp-shaped directories are current runs and are visible only after+ their final ``result.json`` identifies the directory's run id. Historical+ non-timestamp summary directories remain available to compare workflows.+ """+ if candidate.name.startswith((".", "_")) or candidate.name == "latest":+ return Nonetry:- children = root.iterdir()+ candidate_metadata = candidate.lstat()+ if _path_is_link_or_reparse(candidate, candidate_metadata) or not stat.S_ISDIR(candidate_metadata.st_mode):+ return Noneexcept OSError:return None- completed: list[tuple[datetime, int, str, Path]] = []+ timestamp = _run_timestamp(candidate.name)+ is_current_run = timestamp is not None+ if not is_current_run:+ if require_completed_result:+ return None+ timestamp = datetime.min # noqa: DTZ901 -- result directory timestamps are intentionally timezone-free++ completed = False+ completion_mtime = -1try:- for candidate in children:- timestamp = _run_timestamp(candidate.name)- if timestamp is None or candidate.name.startswith((".", "_")) or candidate.is_symlink():- continue- try:- if not candidate.is_dir():- continue- result_path = candidate / "result.json"- result = json.loads(result_path.read_text(encoding="utf-8"))- completion_mtime = result_path.stat().st_mtime_ns- except (FileNotFoundError, json.JSONDecodeError, OSError):- continue- if isinstance(result, dict) and result.get("run_id") == candidate.name:- completed.append((timestamp, completion_mtime, candidate.name, candidate))- except OSError:+ result_path = candidate / "result.json"+ before = result_path.lstat()+ if _path_is_link_or_reparse(result_path, before) or not stat.S_ISREG(before.st_mode) or before.st_nlink != 1:+ return None+ result = json.loads(result_path.read_text(encoding="utf-8"))+ after = result_path.lstat()+ if (+ _path_is_link_or_reparse(result_path, after)+ or not stat.S_ISREG(after.st_mode)+ or after.st_nlink != 1+ or (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns)+ != (after.st_dev, after.st_ino, after.st_size, after.st_mtime_ns)+ ):+ return None+ completion_mtime = after.st_mtime_ns+ completed = isinstance(result, dict) and result.get("run_id") == candidate.name+ except (FileNotFoundError, json.JSONDecodeError, OSError):+ pass+ if (is_current_run or require_completed_result) and not completed:return None- return max(completed, default=(None, -1, "", None), key=lambda item: (item[0], item[1], item[2]))[3]+ if not completed:+ completion_mtime = -1+ return timestamp, completion_mtime, candidate.name+++def ordered_run_directories(root: Path, *, completed_only: bool = False) -> list[Path]:+ """Return result directories in shared newest-first order."""+ try:+ candidates = root.iterdir()+ except OSError:+ return []++ ordered: list[tuple[tuple[datetime, int, str], Path]] = []+ try:+ for candidate in candidates:+ key = run_directory_sort_key(candidate, require_completed_result=completed_only)+ if key is not None:+ ordered.append((key, candidate))+ except OSError:+ return []+ ordered.sort(key=lambda item: item[0], reverse=True)+ return [candidate for _, candidate in ordered]+++def _newest_completed_run(root: Path) -> Path | None:+ """Return the newest complete timestamped run without relying on symlinks."""+ return next(iter(ordered_run_directories(root, completed_only=True)), None)+++def publish_latest_results(root: Path, run_id: str) -> bool:+ """Atomically replace ``latest`` with a relative symlink to ``run_id``."""+ temporary = root / f".latest-{os.getpid()}-{uuid4().hex}.tmp"+ try:+ temporary.symlink_to(run_id)+ os.replace(temporary, root / "latest") # noqa: PTH105 -- explicit atomic replacement is the contract+ except OSError:+ with suppress(OSError):+ temporary.unlink()+ return False+ return Truedef resolve_latest_results(@@ -143,14 +224,36 @@ def resolve_latest_results(cli_results_dir,environ=environ,)+ first_missing_latest: Path | None = Nonefor root in roots:latest = root / "latest"- if latest.exists():- return latest+ if not os.path.lexists(latest) and first_missing_latest is None:+ first_missing_latest = latest+ if latest.is_symlink():+ try:+ link_target = latest.readlink()+ if link_target.is_absolute() or len(link_target.parts) != 1 or link_target.parts[0] in {"", ".", ".."}:+ raise ValueError("latest must name one relative run directory")+ resolved_root = root.resolve(strict=True)+ target = latest.resolve(strict=True)+ except (OSError, RuntimeError, ValueError):+ pass+ else:+ if (+ link_target.name == target.name+ and target.parent == resolved_root+ and run_directory_sort_key(target, require_completed_result=True) is not None+ ):+ return latestfallback = _newest_completed_run(root)if fallback is not None:return fallback- return roots[0] / "latest"+ if first_missing_latest is not None:+ return first_missing_latest+ while True:+ unavailable = roots[0] / f".latest-unavailable-{uuid4().hex}"+ if not os.path.lexists(unavailable):+ return unavailabledef resolve_explicit_or_latest_results(diff --git a/tests/reporting/test_reporters.py b/tests/reporting/test_reporters.pyindex 3ce6f146..c0702afe 100644--- a/tests/reporting/test_reporters.py+++ b/tests/reporting/test_reporters.py@@ -684,7 +684,9 @@ class TestTier3HarborCanonicalPayload:def test_failed_run_produces_false_agent_eval_result(self, tmp_path: Path) -> None:skill = tmp_path / "demo"skill.mkdir()- run_dir = tmp_path / "results" / "demo" / "latest"+ results_root = tmp_path / "results" / "demo"+ run_id = "20260709_120000"+ run_dir = results_root / run_idsummary = run_dir / "codex" / "with-skill" / "summary.json"summary.parent.mkdir(parents=True)summary.write_text(@@ -700,6 +702,8 @@ class TestTier3HarborCanonicalPayload:),encoding="utf-8",)+ (run_dir / "result.json").write_text(json.dumps({"run_id": run_id}), encoding="utf-8")+ (results_root / "latest").symlink_to(run_id)result = agent_eval_result_from_run(skill,diff --git a/tests/test_evaluation_service.py b/tests/test_evaluation_service.pyindex 247ed166..5e8b9812 100644--- a/tests/test_evaluation_service.py+++ b/tests/test_evaluation_service.py@@ -664,7 +664,8 @@ def test_report_discovery_handles_timestamped_results(tmp_path: Path) -> None:run_dir = results_root / "myskill" / "2026-06-18_120000"run_dir.mkdir(parents=True)(run_dir / "report.html").write_text("<html></html>", encoding="utf-8")- (results_root / "myskill" / "latest").symlink_to(run_dir)+ (run_dir / "result.json").write_text(json.dumps({"run_id": run_dir.name}), encoding="utf-8")+ (results_root / "myskill" / "latest").symlink_to(run_dir.name)service = EvaluationService()latest = service.discover_latest_results(skill, results_dir=results_root)diff --git a/tests/test_harbor_adapter_safety.py b/tests/test_harbor_adapter_safety.pyindex 753fabd5..fe0c5b0e 100644--- a/tests/test_harbor_adapter_safety.py+++ b/tests/test_harbor_adapter_safety.py@@ -5,6 +5,7 @@from __future__ import annotations+import importlibimport jsonimport osimport subprocess@@ -147,6 +148,79 @@ def test_copy_repo_excludes_sensitive_files_without_git(tmp_path: Path) -> None:_assert_sensitive_repo_files_are_excluded(repo, skill, tmp_path / "plain-task" / "environment")[email protected]("tracked", [False, True], ids=["plain", "git"])+def test_copy_repo_prunes_excluded_output_before_any_file_inspection(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ tracked: bool,+) -> None:+ repo = tmp_path / "repo"+ skill = repo / "skill"+ skill.mkdir(parents=True)+ (skill / "SKILL.md").write_text("# Test skill\n", encoding="utf-8")+ (repo / "README.md").write_text("safe\n", encoding="utf-8")+ excluded = repo / "custom-results"+ excluded.mkdir()+ (excluded / "secret.json").write_text('{"ground_truth": "private"}', encoding="utf-8")+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "canary.txt").write_text("host canary", encoding="utf-8")+ _symlink_or_skip(excluded / "latest", outside, target_is_directory=True)+ _symlink_or_skip(excluded / "dangling", tmp_path / "missing")++ if tracked:+ subprocess.run(["git", "init", "-q", str(repo)], check=True)+ subprocess.run(["git", "-C", str(repo), "add", "-f", "--", "."], check=True)++ if hasattr(os, "mkfifo"):+ os.mkfifo(excluded / "blocked.fifo")+ unreadable = excluded / "unreadable"+ unreadable.mkdir()+ (unreadable / "private.txt").write_text("private", encoding="utf-8")+ unreadable.chmod(0)++ original_is_file = Path.is_file++ def guarded_is_file(path: Path) -> bool:+ try:+ path.absolute().relative_to(excluded.absolute())+ except ValueError:+ return original_is_file(path)+ raise AssertionError(f"excluded output was inspected: {path}")++ monkeypatch.setattr(Path, "is_file", guarded_is_file)+ env_dir = tmp_path / "task" / "environment"+ env_dir.mkdir(parents=True)+ try:+ metadata = _stage_repo_context(+ env_dir,+ source_skill_path=skill,+ mode="full",+ excluded_roots=(excluded,),+ )+ finally:+ unreadable.chmod(0o700)++ assert (env_dir / "repo" / "README.md").read_text(encoding="utf-8") == "safe\n"+ assert not (env_dir / "repo" / excluded.relative_to(repo)).exists()+ assert all(not Path(item["source"]).is_relative_to(excluded) for item in metadata["files"])+++def test_copy_repo_still_rejects_nonexcluded_file_symlink(tmp_path: Path) -> None:+ repo = tmp_path / "repo"+ skill = repo / "skill"+ skill.mkdir(parents=True)+ (skill / "SKILL.md").write_text("# Test skill\n", encoding="utf-8")+ source = repo / "source.txt"+ source.write_text("canary", encoding="utf-8")+ _symlink_or_skip(repo / "linked-source.txt", source)+ env_dir = tmp_path / "task" / "environment"+ env_dir.mkdir(parents=True)++ with pytest.raises(ValueError, match=r"symlink|reparse"):+ _stage_repo_context(env_dir, source_skill_path=skill, mode="full")++def _symlink_or_skip(link: Path, target: Path, *, target_is_directory: bool = False) -> None:try:link.symlink_to(target, target_is_directory=target_is_directory)@@ -328,6 +402,53 @@ def test_custom_grader_rejects_non_regular_candidate(tmp_path: Path) -> None:_copy_custom_grader(tmp_path / "task", skill, "custom_only")+def test_custom_grader_rejects_hardlinked_candidate(tmp_path: Path) -> None:+ skill = tmp_path / "skill"+ grader = skill / "evals" / "grader.py"+ grader.parent.mkdir(parents=True)+ grader.write_text("safe grader", encoding="utf-8")+ outside_alias = tmp_path / "grader-alias.py"+ try:+ outside_alias.hardlink_to(grader)+ except OSError as exc: # pragma: no cover - filesystem policy+ pytest.skip(f"hardlinks unavailable on this host: {exc}")+ task_dir = tmp_path / "task"++ with pytest.raises(ValueError, match=r"hard.?link|multiple links"):+ _copy_custom_grader(task_dir, skill, "custom_only")++ assert grader.read_text(encoding="utf-8") == "safe grader"+ assert not (task_dir / "tests" / "grader.py").exists()+++def test_custom_grader_rejects_source_replacement_after_validation(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ secure_copy = importlib.import_module("skillevaluator.tier3.harbor.secure_copy")+ skill = tmp_path / "skill"+ grader = skill / "evals" / "grader.py"+ grader.parent.mkdir(parents=True)+ grader.write_text("validated grader", encoding="utf-8")+ task_dir = tmp_path / "task"+ original = secure_copy._build_file_manifest++ def validate_then_replace(source: Path, allowed_root: Path):+ manifest = original(source, allowed_root)+ if Path(source) == grader.resolve():+ grader.unlink()+ grader.write_text("replacement grader", encoding="utf-8")+ return manifest++ monkeypatch.setattr(secure_copy, "_build_file_manifest", validate_then_replace)++ with pytest.raises(ValueError, match="source changed after validation"):+ _copy_custom_grader(task_dir, skill, "custom_only")++ assert grader.read_text(encoding="utf-8") == "replacement grader"+ assert not (task_dir / "tests" / "grader.py").exists()++@pytest.mark.parametrize("candidate", _GRADER_CANDIDATES, ids=str)def test_custom_grader_candidates_copy_regular_files(tmp_path: Path, candidate: Path) -> None:skill = tmp_path / "skill"diff --git a/tests/test_harbor_runner_status.py b/tests/test_harbor_runner_status.pyindex 73b47448..a1c9ff51 100644--- a/tests/test_harbor_runner_status.py+++ b/tests/test_harbor_runner_status.py@@ -5,6 +5,7 @@from __future__ import annotations+import importlibimport jsonimport sysimport threading@@ -13,7 +14,7 @@ from pathlib import Pathimport pytest-from skillevaluator.tier3.harbor import runner+from skillevaluator.tier3.harbor import collector, runner@pytest.mark.parametrize("configured_concurrency", [1, 3, 4])@@ -168,6 +169,224 @@ def test_stop_on_pass_preserves_nvidia_build_agent_import_path(_UNSAFE_LINK = r"symlink|reparse"[email protected]("link_kind", ["directory", "dangling"])+def test_merge_attempt_jobs_rejects_linked_whole_job_root(tmp_path: Path, link_kind: str) -> None:+ target = tmp_path / "real-job"+ if link_kind == "directory":+ target.mkdir()+ job_link = tmp_path / "attempt-001"+ job_link.symlink_to(target, target_is_directory=True)+ aggregate_dir = tmp_path / "aggregate"++ with pytest.raises(ValueError, match=r"non-linked|symlink|reparse"):+ runner._merge_attempt_jobs([job_link], aggregate_dir)++ assert not aggregate_dir.exists()+++def test_merge_attempt_jobs_rejects_mocked_reparse_whole_job_root(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ job_dir = tmp_path / "attempt-001"+ job_dir.mkdir()+ detect_link = runner._job_path_is_link_or_reparse++ def mocked_reparse(path: Path, metadata: object) -> bool:+ return path == job_dir or detect_link(path, metadata)++ monkeypatch.setattr(runner, "_job_path_is_link_or_reparse", mocked_reparse)++ with pytest.raises(ValueError, match="non-linked"):+ runner._merge_attempt_jobs([job_dir], tmp_path / "aggregate")+++def test_merge_attempt_jobs_rejects_non_directory_whole_job_root(tmp_path: Path) -> None:+ job_file = tmp_path / "attempt-001"+ job_file.write_text("not a job", encoding="utf-8")++ with pytest.raises(ValueError, match="non-linked directory"):+ runner._merge_attempt_jobs([job_file], tmp_path / "aggregate")++[email protected]("artifact_kind", ["symlink", "hardlink"])+def test_merge_attempt_jobs_rejects_forged_root_result(tmp_path: Path, artifact_kind: str) -> None:+ job_dir = tmp_path / "attempt-001"+ job_dir.mkdir()+ forged = tmp_path / "forged-result.json"+ forged.write_text('{"n_total_trials": 999, "stats": {}}', encoding="utf-8")+ result = job_dir / "result.json"+ try:+ if artifact_kind == "symlink":+ result.symlink_to(forged)+ else:+ result.hardlink_to(forged)+ except OSError as exc: # pragma: no cover - filesystem policy+ pytest.skip(f"{artifact_kind} creation unavailable: {exc}")++ with pytest.raises(ValueError, match=r"symlink|reparse|hard.?link|multiple links"):+ runner._merge_attempt_jobs([job_dir], tmp_path / "aggregate")+++def test_merge_attempt_jobs_rejects_root_result_source_swap(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ secure_copy = importlib.import_module("skillevaluator.tier3.harbor.secure_copy")+ job_dir = tmp_path / "attempt-001"+ job_dir.mkdir()+ result = job_dir / "result.json"+ result.write_text('{"n_total_trials": 1, "stats": {}}', encoding="utf-8")+ aggregate_dir = tmp_path / "aggregate"+ aggregate_dir.mkdir()+ marker = aggregate_dir / "keep.txt"+ marker.write_text("old aggregate", encoding="utf-8")+ original = secure_copy._build_tree_manifest++ def validate_then_replace(source: Path, *args: object, **kwargs: object):+ manifest = original(source, *args, **kwargs)+ if Path(source).resolve() == job_dir.resolve():+ result.unlink()+ result.write_text('{"n_total_trials": 999, "stats": {}}', encoding="utf-8")+ return manifest++ monkeypatch.setattr(secure_copy, "_build_tree_manifest", validate_then_replace)++ with pytest.raises(ValueError, match="source changed after validation"):+ runner._merge_attempt_jobs([job_dir], aggregate_dir)++ assert marker.read_text(encoding="utf-8") == "old aggregate"+++def test_merge_attempt_jobs_rejects_regular_root_directory_replacement(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ job_dir = tmp_path / "attempt-001"+ job_dir.mkdir()+ (job_dir / "result.json").write_text('{"n_total_trials": 1, "stats": {}}', encoding="utf-8")+ aggregate_dir = tmp_path / "aggregate"+ aggregate_dir.mkdir()+ marker = aggregate_dir / "keep.txt"+ marker.write_text("old aggregate", encoding="utf-8")+ original_copy = runner.copytree_secure+ replaced = False++ def replace_root_then_copy(source: Path, destination: Path, **kwargs: object) -> None:+ nonlocal replaced+ if not replaced and Path(source) == job_dir:+ replaced = True+ job_dir.rename(tmp_path / "original-job")+ job_dir.mkdir()+ (job_dir / "result.json").write_text('{"n_total_trials": 999, "stats": {}}', encoding="utf-8")+ original_copy(source, destination, **kwargs)++ monkeypatch.setattr(runner, "copytree_secure", replace_root_then_copy)++ with pytest.raises(ValueError, match="root changed during snapshot"):+ runner._merge_attempt_jobs([job_dir], aggregate_dir)++ assert marker.read_text(encoding="utf-8") == "old aggregate"+++def _write_multistep_attempt_job(+ job_dir: Path,+ *,+ root_score: float,+ step_scores: tuple[float, ...],+ failed: bool = False,+) -> Path:+ trial = job_dir / "case-001_attempt001"+ for index, score in enumerate(step_scores, start=1):+ verifier = trial / "steps" / f"step-{index}" / "verifier"+ verifier.mkdir(parents=True)+ (verifier / "reward.json").write_text(json.dumps({"overall": score}), encoding="utf-8")+ result: dict[str, object] = {+ "trial_name": trial.name,+ "task_name": "case-001",+ "verifier_result": {"rewards": {"overall": root_score}},+ "step_results": [+ {"step_name": f"step-{index}", "verifier_result": {"rewards": {"overall": score}}}+ for index, score in enumerate(step_scores, start=1)+ ],+ }+ if failed:+ result["exception_info"] = {+ "exception_type": "TaskFailure",+ "exception_message": "attempt crashed",+ }+ (trial / "result.json").write_text(json.dumps(result), encoding="utf-8")+ _write_successful_job_result(job_dir, trial.name)+ return trial+++def _write_successful_job_result(job_dir: Path, trial_name: str) -> None:+ (job_dir / "result.json").write_text(+ json.dumps(+ {+ "n_total_trials": 1,+ "stats": {+ "n_trials": 1,+ "n_errors": 0,+ "evals": {+ "demo": {+ "n_trials": 1,+ "n_errors": 0,+ "reward_stats": {"overall": {"1.0": [trial_name]}},+ }+ },+ },+ }+ ),+ encoding="utf-8",+ )+++def test_job_passed_uses_authoritative_multistep_root_reward(tmp_path: Path) -> None:+ job_dir = tmp_path / "job"+ _write_multistep_attempt_job(job_dir, root_score=0.5, step_scores=(1.0, 0.0))++ assert runner._job_passed(job_dir, 0.75) is False+ rewards = collector._extract_rewards(job_dir)+ assert len(rewards) == 1+ assert collector._average_overall(rewards) == 0.5+++def test_job_passed_accepts_passing_authoritative_multistep_root_reward(tmp_path: Path) -> None:+ job_dir = tmp_path / "job"+ _write_multistep_attempt_job(job_dir, root_score=0.8, step_scores=(0.0, 0.0))++ assert runner._job_passed(job_dir, 0.75) is True+++def test_job_passed_rejects_failed_trial_even_with_passing_rewards(tmp_path: Path) -> None:+ job_dir = tmp_path / "job"+ _write_multistep_attempt_job(job_dir, root_score=1.0, step_scores=(1.0,), failed=True)++ assert runner._job_passed(job_dir, 0.75) is False+++def test_job_passed_rejects_failed_job_result_even_with_passing_reward(tmp_path: Path) -> None:+ job_dir = tmp_path / "job"+ _write_multistep_attempt_job(job_dir, root_score=1.0, step_scores=(1.0,))+ job_result = json.loads((job_dir / "result.json").read_text(encoding="utf-8"))+ job_result["stats"]["n_errors"] = 1+ (job_dir / "result.json").write_text(json.dumps(job_result), encoding="utf-8")++ assert runner._job_passed(job_dir, 0.75) is False+++def test_job_passed_preserves_legacy_single_step_reward(tmp_path: Path) -> None:+ job_dir = tmp_path / "job"+ trial_name = "case-001_attempt001"+ verifier = job_dir / trial_name / "verifier"+ verifier.mkdir(parents=True)+ (verifier / "reward.json").write_text(json.dumps({"overall": 0.9}), encoding="utf-8")+ _write_successful_job_result(job_dir, trial_name)++ assert runner._job_passed(job_dir, 0.75) is True++def test_merge_attempt_jobs_rejects_symlinked_trial_directory(tmp_path: Path) -> None:outside = tmp_path / "outside-trial"outside.mkdir()@@ -255,6 +474,89 @@ def test_merge_attempt_jobs_preserves_regular_trial_artifacts(tmp_path: Path) ->assert merged_result["stats"]["evals"]["demo"]["reward_stats"]["reward"]["1.0"] == [merged_trial.name]+def test_merge_attempt_jobs_ignores_tmpdir_inside_attempt_job(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ job_dir = tmp_path / "attempt-001"+ trial_dir = job_dir / "case-001__trial"+ trial_dir.mkdir(parents=True)+ (trial_dir / "artifact.txt").write_text("expected", encoding="utf-8")+ monkeypatch.setattr(runner.tempfile, "tempdir", str(job_dir))+ aggregate_dir = tmp_path / "aggregate"++ runner._merge_attempt_jobs([job_dir], aggregate_dir)++ assert (aggregate_dir / f"{job_dir.name}__{trial_dir.name}" / "artifact.txt").read_text() == "expected"+ assert not list(tmp_path.glob(".aggregate-merge-*"))+++def test_merge_attempt_jobs_preserves_existing_aggregate_on_unsafe_source(tmp_path: Path) -> None:+ outside = tmp_path / "outside"+ outside.mkdir()+ safe_job = tmp_path / "attempt-001"+ safe_trial = safe_job / "case-001__trial"+ safe_trial.mkdir(parents=True)+ (safe_trial / "safe.txt").write_text("staged first", encoding="utf-8")+ unsafe_job = tmp_path / "attempt-002"+ unsafe_trial = unsafe_job / "case-001__trial"+ unsafe_trial.mkdir(parents=True)+ (unsafe_trial / "unsafe").symlink_to(outside, target_is_directory=True)+ aggregate_dir = tmp_path / "aggregate"+ aggregate_dir.mkdir()+ marker = aggregate_dir / "keep.txt"+ marker.write_text("old aggregate", encoding="utf-8")++ with pytest.raises(ValueError, match=_UNSAFE_LINK):+ runner._merge_attempt_jobs([safe_job, unsafe_job], aggregate_dir)++ assert marker.read_text(encoding="utf-8") == "old aggregate"+ assert not (aggregate_dir / f"{safe_job.name}__{safe_trial.name}").exists()+ assert not (aggregate_dir / f"{unsafe_job.name}__{unsafe_trial.name}").exists()+ assert not list(tmp_path.glob(".aggregate-merge-*"))+++def test_merge_attempt_jobs_preserves_existing_aggregate_when_private_staging_fails(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ job_dir = tmp_path / "attempt-001"+ job_dir.mkdir()+ aggregate_dir = tmp_path / "aggregate"+ aggregate_dir.mkdir()+ marker = aggregate_dir / "keep.txt"+ marker.write_text("old aggregate", encoding="utf-8")++ def fail_private_staging(*_args: object, **_kwargs: object) -> None:+ raise OSError("injected temp failure")++ monkeypatch.setattr(runner.tempfile, "TemporaryDirectory", fail_private_staging)++ with pytest.raises(OSError, match="injected temp failure"):+ runner._merge_attempt_jobs([job_dir], aggregate_dir)++ assert marker.read_text(encoding="utf-8") == "old aggregate"++[email protected]("relationship", ["aggregate-in-job", "job-in-aggregate"])+def test_merge_attempt_jobs_rejects_source_destination_overlap(tmp_path: Path, relationship: str) -> None:+ if relationship == "aggregate-in-job":+ job_dir = tmp_path / "attempt-001"+ job_dir.mkdir()+ aggregate_dir = job_dir / "aggregate"+ else:+ aggregate_dir = tmp_path / "aggregate"+ job_dir = aggregate_dir / "attempt-001"+ job_dir.mkdir(parents=True)+ marker = job_dir / "keep.txt"+ marker.write_text("source", encoding="utf-8")++ with pytest.raises(ValueError, match="must not overlap"):+ runner._merge_attempt_jobs([job_dir], aggregate_dir)++ assert marker.read_text(encoding="utf-8") == "source"++def _run(monkeypatch: pytest.MonkeyPatch,jobs_dir: Path,diff --git a/tests/test_harbor_runtime_skill_isolation.py b/tests/test_harbor_runtime_skill_isolation.pyindex 612b2c4b..e8128fda 100644--- a/tests/test_harbor_runtime_skill_isolation.py+++ b/tests/test_harbor_runtime_skill_isolation.py@@ -440,6 +440,40 @@ def test_copy_repo_excludes_configured_in_repo_output_root(tmp_path: Path) -> Noassert not (task / "environment" / "repo" / output_dir.name).exists()[email protected]("stager", ["generated", "native"])+def test_copy_repo_excludes_private_in_repo_staging_root(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ stager: str,+) -> None:+ repo, target, references_dir, workspace = _write_projection_fixture(tmp_path)+ private_canary = "PRIVATE-STAGING-CANARY"+ entries = json.loads((target / "evals" / "evals.json").read_text(encoding="utf-8"))+ entries[0]["ground_truth"] = private_canary+ (target / "evals" / "evals.json").write_text(json.dumps(entries), encoding="utf-8")+ if stager == "native":+ _write_minimal_native_task(target)+ in_repo_temp_root = repo / "tmp"+ in_repo_temp_root.mkdir()+ monkeypatch.setattr(tempfile, "tempdir", os.fspath(in_repo_temp_root))+ stager_fn = generate_harbor_tasks if stager == "generated" else stage_native_harbor_tasks++ task = stager_fn(+ target,+ tmp_path / f"{stager}-private-root",+ reference_skills_dir=references_dir,+ workspace_skill_paths=[workspace],+ copy_repo=True,+ )[0]++ environment = task / "environment"+ readable_environment = "\n".join(+ path.read_text(encoding="utf-8", errors="ignore") for path in environment.rglob("*") if path.is_file()+ )+ assert private_canary not in readable_environment+ assert not (environment / "repo" / in_repo_temp_root.relative_to(repo)).exists()++def test_runtime_skill_projection_excludes_shared_in_skill_output_root(tmp_path: Path) -> None:_, target, references_dir, workspace = _write_projection_fixture(tmp_path)output_root = target / "Custom-Results"@@ -1254,6 +1288,49 @@ def test_linked_repo_context_excludes_skill_evals_but_keeps_unrelated_evals(tmp_assert (staged_repo / "docs" / "evals" / "keep.txt").is_file()[email protected]("stager", ["generated", "native"])+def test_linked_repo_context_prunes_excluded_artifacts_before_resolving(+ tmp_path: Path,+ stager: str,+) -> None:+ repo, target, references_dir, workspace = _write_projection_fixture(tmp_path)+ excluded = repo / "custom-results"+ excluded.mkdir()+ try:+ (excluded / "loop").symlink_to("loop")+ (excluded / "dangling").symlink_to("missing")+ except OSError as exc: # pragma: no cover - host policy, primarily native Windows+ pytest.skip(f"symlinks unavailable on this host: {exc}")+ if hasattr(os, "mkfifo"):+ os.mkfifo(excluded / "artifact.fifo")+ unreadable = excluded / "unreadable.txt"+ unreadable.write_text("private", encoding="utf-8")+ unreadable.chmod(0)+ links = "\n".join(+ f"[{name}](../custom-results/{name})" for name in ("loop", "dangling", "artifact.fifo", "unreadable.txt")+ )+ (target / "SKILL.md").write_text(f"# Target\n\n{links}\n", encoding="utf-8")+ if stager == "native":+ _write_minimal_native_task(target)+ stage = stage_native_harbor_tasks+ else:+ stage = generate_harbor_tasks++ try:+ task = stage(+ target,+ tmp_path / f"{stager}-linked-excluded",+ reference_skills_dir=references_dir,+ workspace_skill_paths=[workspace],+ copy_repo=False,+ repo_context_exclude_paths=(excluded,),+ )[0]+ finally:+ unreadable.chmod(0o600)++ assert not (task / "environment" / "repo" / excluded.relative_to(repo)).exists()++@pytest.mark.parametrize("files_value", [[], ["evals/files/selected.txt"]])@pytest.mark.parametrize("source", ["INPUT/", "Input/fixture.txt"])def test_custom_dockerfile_rejects_noncanonical_input_case(@@ -1566,6 +1643,10 @@ def test_generated_tasks_reject_unsafe_agent_workdir(tmp_path: Path, agent_workd"/workspace/input/subdir","/workspace/repo/subdir","/workspace/skills",+ "/workspace/.gemini/extensions/nested",+ "/etc/codex/skills/nested",+ "/logs/agent/sessions/skills/nested",+ "/opt/project/.claude/commands/hidden","/opt/project/.claude/skills/hidden","/opt/project/.cline/skills/hidden","/opt/project/.config/goose/skills/hidden",diff --git a/tests/test_results_location.py b/tests/test_results_location.pyindex 29beabb1..464fc828 100644--- a/tests/test_results_location.py+++ b/tests/test_results_location.py@@ -7,8 +7,12 @@ from __future__ import annotationsimport jsonimport os+from concurrent.futures import ThreadPoolExecutorfrom pathlib import Path+import pytest++from skillevaluator.tier3 import results_locationfrom skillevaluator.tier3.results_location import external_results_root, resolve_latest_results@@ -64,6 +68,59 @@ def test_latest_results_same_timestamp_uses_completion_mtime(tmp_path: Path) ->assert resolved == completed_later+def test_latest_results_same_completion_time_uses_deterministic_name_order(tmp_path: Path) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ cli_results_dir = tmp_path / "results"+ root = external_results_root(cli_results_dir, skill_path)+ lexically_first = _write_completed_run(root, "20260705_130000_111_aaaaaaaaaaaa")+ lexically_last = _write_completed_run(root, "20260705_130000_999_ffffffffffff")+ os.utime(lexically_first / "result.json", ns=(100, 100))+ os.utime(lexically_last / "result.json", ns=(100, 100))++ resolved = resolve_latest_results(skill_path, cli_results_dir, environ={})++ assert resolved == lexically_last+++def test_publish_latest_results_is_atomic_under_concurrency(tmp_path: Path) -> None:+ publisher = getattr(results_location, "publish_latest_results", None)+ assert callable(publisher), "results_location must expose a shared latest-link publisher"+ root = tmp_path / "results"+ run_ids = [f"20260705_130000_{index:03d}_aaaaaaaaaaaa" for index in range(8)]+ for run_id in run_ids:+ (root / run_id).mkdir(parents=True)++ with ThreadPoolExecutor(max_workers=8) as executor:+ published = list(executor.map(lambda run_id: publisher(root, run_id), run_ids))+ if not any(published): # pragma: no cover - Windows installations without symlink privileges+ pytest.skip("symlink creation is unavailable on this host")++ latest = root / "latest"+ assert latest.is_symlink()+ assert str(latest.readlink()) in run_ids+ assert not list(root.glob(".latest-*.tmp"))+++def test_publish_latest_results_preserves_real_directory_and_cleans_temp_link(tmp_path: Path) -> None:+ publisher = getattr(results_location, "publish_latest_results", None)+ assert callable(publisher), "results_location must expose a shared latest-link publisher"+ root = tmp_path / "results"+ latest = root / "latest"+ latest.mkdir(parents=True)+ marker = latest / "keep.txt"+ marker.write_text("keep", encoding="utf-8")+ run_id = "20260705_130000_111_aaaaaaaaaaaa"+ (root / run_id).mkdir()++ publisher(root, run_id)++ assert latest.is_dir()+ assert not latest.is_symlink()+ assert marker.read_text(encoding="utf-8") == "keep"+ assert not list(root.glob(".latest-*.tmp"))++def test_latest_results_fallback_ignores_hidden_partial_and_malformed_directories(tmp_path: Path) -> None:skill_path = tmp_path / "demo"skill_path.mkdir()@@ -88,3 +145,158 @@ def test_latest_results_fallback_ignores_hidden_partial_and_malformed_directorieresolved = resolve_latest_results(skill_path, cli_results_dir, environ={})assert resolved == expected+++def _symlink_or_skip(link: Path, target: Path) -> None:+ try:+ link.symlink_to(target)+ except OSError as exc: # pragma: no cover - host policy, primarily native Windows+ pytest.skip(f"symlinks unavailable on this host: {exc}")+++def test_latest_results_prefers_valid_relative_latest_link(tmp_path: Path) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ cli_results_dir = tmp_path / "results"+ root = external_results_root(cli_results_dir, skill_path)+ selected = _write_completed_run(root, "20260705_120000")+ _write_completed_run(root, "20260705_130000")+ latest = root / "latest"+ _symlink_or_skip(latest, Path(selected.name))++ assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == latest+++ "latest_kind",+ ["directory", "dangling", "escaping", "incomplete", "legacy", "absolute", "nested-alias"],+)+def test_latest_results_ignores_invalid_latest_pointer_and_falls_back(+ tmp_path: Path,+ latest_kind: str,+) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ cli_results_dir = tmp_path / "results"+ root = external_results_root(cli_results_dir, skill_path)+ older = _write_completed_run(root, "20260705_120000")+ expected = _write_completed_run(root, "20260705_130000")+ latest = root / "latest"++ if latest_kind == "directory":+ latest.mkdir()+ elif latest_kind == "dangling":+ _symlink_or_skip(latest, Path("missing-run"))+ elif latest_kind == "escaping":+ outside = _write_completed_run(tmp_path / "outside", "20260705_140000")+ _symlink_or_skip(latest, outside)+ elif latest_kind == "incomplete":+ (root / "20260705_140000").mkdir()+ _symlink_or_skip(latest, Path("20260705_140000"))+ elif latest_kind == "legacy":+ legacy = root / "legacy-run"+ legacy.mkdir()+ (legacy / "result.json").write_text(json.dumps({"run_id": legacy.name}), encoding="utf-8")+ _symlink_or_skip(latest, Path(legacy.name))+ elif latest_kind == "absolute":+ _symlink_or_skip(latest, older.resolve())+ else:+ (root / "alias").mkdir()+ _symlink_or_skip(latest, Path("alias") / ".." / older.name)++ assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == expected++[email protected]("latest_kind", ["directory", "escaping", "incomplete"])+def test_invalid_latest_without_completed_run_returns_safe_absent_path(+ tmp_path: Path,+ latest_kind: str,+) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ cli_results_dir = tmp_path / "results"+ root = external_results_root(cli_results_dir, skill_path)+ root.mkdir(parents=True)+ latest = root / "latest"+ if latest_kind == "directory":+ latest.mkdir()+ elif latest_kind == "escaping":+ outside = _write_completed_run(tmp_path / "outside", "20260705_140000")+ _symlink_or_skip(latest, outside)+ else:+ partial = root / "20260705_140000"+ partial.mkdir()+ _symlink_or_skip(latest, Path(partial.name))++ resolved = resolve_latest_results(skill_path, cli_results_dir, environ={})++ assert resolved != latest+ assert not os.path.lexists(resolved)+ assert resolved.parent != latest+ assert not resolved.resolve(strict=False).is_relative_to((tmp_path / "outside").resolve())+++def test_all_invalid_latest_entries_return_collision_checked_hidden_sentinel(tmp_path: Path) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ cli_results_dir = tmp_path / "results"+ primary_root = external_results_root(cli_results_dir, skill_path)+ legacy_root = skill_path / "evals" / "results"+ for root in (primary_root, legacy_root):+ (root / "latest").mkdir(parents=True)++ resolved = resolve_latest_results(skill_path, cli_results_dir, environ={})++ assert resolved.parent == primary_root+ assert resolved.name.startswith(".latest-unavailable-")+ assert not os.path.lexists(resolved)++[email protected]("artifact_kind", ["symlink", "fifo", "hardlink"])+def test_latest_results_fallback_rejects_unsafe_result_artifact(tmp_path: Path, artifact_kind: str) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ cli_results_dir = tmp_path / "results"+ root = external_results_root(cli_results_dir, skill_path)+ expected = _write_completed_run(root, "20260705_120000")+ unsafe = root / "20260705_130000"+ unsafe.mkdir()+ result_path = unsafe / "result.json"+ source = tmp_path / "result-source.json"+ source.write_text(json.dumps({"run_id": unsafe.name}), encoding="utf-8")+ try:+ if artifact_kind == "symlink":+ result_path.symlink_to(source)+ elif artifact_kind == "fifo":+ if not hasattr(os, "mkfifo"):+ pytest.skip("FIFO creation is unavailable on this host")+ os.mkfifo(result_path)+ else:+ result_path.hardlink_to(source)+ except OSError as exc: # pragma: no cover - filesystem policy+ pytest.skip(f"{artifact_kind} creation is unavailable on this host: {exc}")++ assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == expected++[email protected]("reparse_kind", ["run-directory", "result"])+def test_latest_results_rejects_windows_reparse_candidates(+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+ reparse_kind: str,+) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ cli_results_dir = tmp_path / "results"+ root = external_results_root(cli_results_dir, skill_path)+ expected = _write_completed_run(root, "20260705_120000")+ unsafe = _write_completed_run(root, "20260705_130000")+ marked = unsafe if reparse_kind == "run-directory" else unsafe / "result.json"+ detect_link = results_location._path_is_link_or_reparse++ def mock_windows_reparse(path: Path, metadata: os.stat_result) -> bool:+ return path == marked or detect_link(path, metadata)++ monkeypatch.setattr(results_location, "_path_is_link_or_reparse", mock_windows_reparse)++ assert resolve_latest_results(skill_path, cli_results_dir, environ={}) == expecteddiff --git a/tests/test_tier3_compare.py b/tests/test_tier3_compare.pyindex e11f6509..7085e5db 100644--- a/tests/test_tier3_compare.py+++ b/tests/test_tier3_compare.py@@ -6,13 +6,19 @@from __future__ import annotationsimport json+import osfrom pathlib import Path-from typing import TYPE_CHECKING++import pytestfrom skillevaluator.tier3.commands import compare_results-if TYPE_CHECKING:- import pytest++def _complete_current_run(run_dir: Path) -> None:+ (run_dir / "result.json").write_text(+ json.dumps({"run_id": run_dir.name, "agents": {}}),+ encoding="utf-8",+ )def test_compare_rejects_partial_scores_from_failed_summary(tmp_path: Path) -> None:@@ -33,6 +39,7 @@ def test_compare_rejects_partial_scores_from_failed_summary(tmp_path: Path) -> N),encoding="utf-8",)+ _complete_current_run(summary_dir.parents[1])assert compare_results(skill_path, results_dir=results_root) == 1@@ -55,6 +62,7 @@ def test_compare_ignores_failed_baseline_scores(json.dumps({"execution_status": status, "scores": {"security": score}}),encoding="utf-8",)+ _complete_current_run(agent_dir.parent)assert compare_results(skill_path, results_dir=results_root) == 0assert "lift" not in capsys.readouterr().out.lower()@@ -80,6 +88,7 @@ def test_compare_never_pairs_baseline_from_a_different_timestamp(json.dumps({"execution_status": status, "scores": {"security": score}}),encoding="utf-8",)+ _complete_current_run(newest.parent)older = skill_results / "20260709_010000" / "opencode" / "with-skill"older.mkdir(parents=True)@@ -87,6 +96,156 @@ def test_compare_never_pairs_baseline_from_a_different_timestamp(json.dumps({"execution_status": "succeeded", "scores": {"security": 1.0}}),encoding="utf-8",)+ _complete_current_run(older.parents[1])assert compare_results(skill_path, results_dir=results_root) == 0assert "lift" not in capsys.readouterr().out.lower()+++def test_compare_same_timestamp_unique_runs_uses_result_completion_time(+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ skill_results = tmp_path / "results" / "demo"+ lexically_later = "20260709_010000_999_ffffffffffff"+ completed_later = "20260709_010000_111_aaaaaaaaaaaa"++ for run_id, score, completed_ns in (+ (lexically_later, 0.1, 100),+ (completed_later, 0.9, 200),+ ):+ run_dir = skill_results / run_id+ summary_dir = run_dir / "opencode" / "with-skill"+ summary_dir.mkdir(parents=True)+ (summary_dir / "summary.json").write_text(+ json.dumps({"execution_status": "succeeded", "scores": {"security": score}}),+ encoding="utf-8",+ )+ result_path = run_dir / "result.json"+ result_path.write_text(json.dumps({"run_id": run_id, "agents": {}}), encoding="utf-8")+ os.utime(result_path, ns=(completed_ns, completed_ns))++ assert compare_results(skill_path, results_dir=tmp_path / "results") == 0+ output = capsys.readouterr().out+ assert completed_later in output+ assert lexically_later not in output++[email protected]("partial_kind", ["missing", "malformed", "mismatched"])+def test_compare_ignores_newer_partial_timestamp_run(+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+ partial_kind: str,+) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ skill_results = tmp_path / "results" / "demo"+ older = skill_results / "20260709_010000"+ older_summary = older / "opencode" / "with-skill" / "summary.json"+ older_summary.parent.mkdir(parents=True)+ older_summary.write_text(+ json.dumps({"execution_status": "succeeded", "scores": {"security": 0.8}}),+ encoding="utf-8",+ )+ _complete_current_run(older)++ newer = skill_results / "20260709_020000"+ newer_summary = newer / "opencode" / "with-skill" / "summary.json"+ newer_summary.parent.mkdir(parents=True)+ newer_summary.write_text(+ json.dumps({"execution_status": "succeeded", "scores": {"security": 0.1}}),+ encoding="utf-8",+ )+ if partial_kind == "malformed":+ (newer / "result.json").write_text("{not json", encoding="utf-8")+ elif partial_kind == "mismatched":+ (newer / "result.json").write_text(json.dumps({"run_id": "different"}), encoding="utf-8")++ assert compare_results(skill_path, results_dir=tmp_path / "results") == 0+ output = capsys.readouterr().out+ assert older.name in output+ assert newer.name not in output+++def test_compare_retains_non_timestamp_legacy_summary_directory(+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ legacy = tmp_path / "results" / "demo" / "legacy-run"+ summary = legacy / "opencode" / "with-skill" / "summary.json"+ summary.parent.mkdir(parents=True)+ summary.write_text(+ json.dumps({"execution_status": "succeeded", "scores": {"security": 0.7}}),+ encoding="utf-8",+ )++ assert compare_results(skill_path, results_dir=tmp_path / "results") == 0+ assert legacy.name in capsys.readouterr().out++[email protected]("primary_kind", ["empty", "partial", "non-object"])+def test_compare_falls_back_from_unusable_primary_root_to_valid_legacy_root(+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+ primary_kind: str,+) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ primary = tmp_path / "results" / skill_path.name+ primary.mkdir(parents=True)+ if primary_kind == "partial":+ partial = primary / "20260709_020000" / "codex" / "with-skill"+ partial.mkdir(parents=True)+ (partial / "summary.json").write_text(+ json.dumps({"execution_status": "succeeded", "scores": {"security": 0.1}}),+ encoding="utf-8",+ )+ elif primary_kind == "non-object":+ completed = primary / "20260709_020000"+ summary = completed / "codex" / "with-skill" / "summary.json"+ summary.parent.mkdir(parents=True)+ summary.write_text("[]\n", encoding="utf-8")+ _complete_current_run(completed)++ legacy = skill_path / "evals" / "results" / "legacy-run" / "opencode" / "with-skill"+ legacy.mkdir(parents=True)+ (legacy / "summary.json").write_text(+ json.dumps({"execution_status": "succeeded", "scores": {"security": 0.9}}),+ encoding="utf-8",+ )++ assert compare_results(skill_path, results_dir=tmp_path / "results") == 0+ output = capsys.readouterr().out+ assert "opencode" in output+ assert "legacy-run" in output+++def test_compare_never_mixes_agents_across_candidate_roots(+ tmp_path: Path,+ capsys: pytest.CaptureFixture[str],+) -> None:+ skill_path = tmp_path / "demo"+ skill_path.mkdir()+ primary_run = tmp_path / "results" / "demo" / "20260709_020000"+ primary = primary_run / "codex" / "with-skill"+ primary.mkdir(parents=True)+ (primary / "summary.json").write_text(+ json.dumps({"execution_status": "succeeded", "scores": {"security": 0.8}}),+ encoding="utf-8",+ )+ _complete_current_run(primary_run)+ legacy = skill_path / "evals" / "results" / "legacy-run" / "opencode" / "with-skill"+ legacy.mkdir(parents=True)+ (legacy / "summary.json").write_text(+ json.dumps({"execution_status": "succeeded", "scores": {"security": 0.9}}),+ encoding="utf-8",+ )++ assert compare_results(skill_path, results_dir=tmp_path / "results") == 0+ output = capsys.readouterr().out+ assert "codex" in output+ assert "opencode" not in outputdiff --git a/tests/test_tier3_progress.py b/tests/test_tier3_progress.pyindex 94e62d32..a13f71a6 100644--- a/tests/test_tier3_progress.py+++ b/tests/test_tier3_progress.py@@ -723,6 +723,25 @@ def test_runner_reserves_unique_run_directories_concurrently(tmp_path: Path) ->assert all((run_dir / ".skillevaluator-generated-output").is_file() for run_dir in run_dirs)+def test_runner_publishes_latest_through_shared_atomic_helper(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path: Path,+) -> None:+ runner, skill = _stub_runner(monkeypatch, tmp_path)+ published: list[tuple[Path, str]] = []+ monkeypatch.setattr(+ runner,+ "publish_latest_results",+ lambda root, run_id: published.append((root, run_id)),+ raising=False,+ )+ results_root = tmp_path / "results"++ result = runner.run_harbor_eval(skill, ["codex"], output_dir=results_root)++ assert published == [(results_root, Path(result["run_dir"]).name)]++def test_runner_persists_compact_feedback_to_result_json(monkeypatch: pytest.MonkeyPatch,tmp_path: Path,diff --git a/tests/tier3/test_generate_dataset_results.py b/tests/tier3/test_generate_dataset_results.pyindex 5020a3e5..cde672e4 100644--- a/tests/tier3/test_generate_dataset_results.py+++ b/tests/tier3/test_generate_dataset_results.py@@ -21,10 +21,15 @@ def test_discover_trajectories_uses_env_results_root(tmp_path, monkeypatch):skill = tmp_path / "my-skill"skill.mkdir()results_root = tmp_path / "external-results"- trial = results_root / "my-skill" / "latest" / "claude-code" / "with-skill" / "trials" / "case-001"+ skill_results = results_root / "my-skill"+ run_id = "20260709_120000"+ run_dir = skill_results / run_id+ trial = run_dir / "claude-code" / "with-skill" / "trials" / "case-001"trial.mkdir(parents=True)trajectory = {"steps": [{"type": "assistant", "content": "done"}]}trial.joinpath("trajectory.json").write_text(json.dumps(trajectory), encoding="utf-8")+ (run_dir / "result.json").write_text(json.dumps({"run_id": run_id}), encoding="utf-8")+ (skill_results / "latest").symlink_to(run_id)monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(results_root))@@ -36,10 +41,15 @@ def test_discover_trajectories_results_dir_overrides_env(tmp_path, monkeypatch):skill.mkdir()env_root = tmp_path / "env-results"cli_root = tmp_path / "cli-results"- trial = cli_root / "my-skill" / "latest" / "claude-code" / "with-skill" / "trials" / "case-001"+ skill_results = cli_root / "my-skill"+ run_id = "20260709_120000"+ run_dir = skill_results / run_id+ trial = run_dir / "claude-code" / "with-skill" / "trials" / "case-001"trial.mkdir(parents=True)trajectory = {"steps": [{"type": "assistant", "content": "done"}]}trial.joinpath("trajectory.json").write_text(json.dumps(trajectory), encoding="utf-8")+ (run_dir / "result.json").write_text(json.dumps({"run_id": run_id}), encoding="utf-8")+ (skill_results / "latest").symlink_to(run_id)monkeypatch.setenv("SKILLEVALUATOR_RESULTS_DIR", str(env_root))