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): report missing tools as environment problems, not skill defects (#379)
Christopher Kevina41d5a71c7b9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 91ee0d40..fa9ec850 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -85,6 +85,11 @@ All notable changes to SkillEvaluator are documented in this file.### Changed+- Tier 3 reports missing skill runtime dependencies as environment problems,+ with declaration and custom Dockerfile guidance. Unrecovered environment+ failures leave the trial UNSCORED instead of reducing the skill's score;+ recovered environment failures carry no deduction.+- Document per-arm Tier 3 dimension applicability and test how N/A baselinemetrics are handled in Overall scores and Skill Lift comparisons.diff --git a/docs/agents-and-sandboxes.mdx b/docs/agents-and-sandboxes.mdxindex a2f7aa74..81baa5a0 100644--- a/docs/agents-and-sandboxes.mdx+++ b/docs/agents-and-sandboxes.mdx@@ -529,6 +529,15 @@ agent process killed is the classic out-of-memory symptom; raise### Custom Dockerfiles+Declare system tools in `scripts/apt-packages.txt` and Python packages in+`scripts/requirements.txt` anywhere under the skill directory. These files are+auto-installed only when there is no custom `evals/environment/Dockerfile`.+With a custom Dockerfile, install those dependencies there yourself. A required+tool or module that is unavailable makes the case `environment_invalid` and+UNSCORED, not a skill defect; the report names the missing dependency and fix.+When an import or executable name differs from its package name, the report+asks you to install the package that provides it or ship it with the skill.+When a skill ships its own `evals/environment/Dockerfile`,`--custom-dockerfile-mode` decides how it combines with the eval image:diff --git a/docs/tier3-live-evaluation.mdx b/docs/tier3-live-evaluation.mdxindex 6107ca02..875f2df3 100644--- a/docs/tier3-live-evaluation.mdx+++ b/docs/tier3-live-evaluation.mdx@@ -780,6 +780,23 @@ evaluator provider. `custom_only` runs none of them.The three LLM judges return verdicts only, and the verifier computes thescores. A `score` field in a judge reply is ignored.+Error recovery distinguishes skill files, agent command errors, and missing+runtime dependencies. Missing tools/modules declared by or used by the skill+are environment problems: recovered failures have no deduction, while an+unrecovered environment failure without an unrecovered skill fault marks the+case `environment_invalid`. `skill_execution` then returns no score, the+verifier skips the judges, and the collector leaves the trial UNSCORED+(excluded from skill score averages). Any unrecovered skill fault in the same+trial is scored as a skill failure instead. Agent-only failures remain+unscored with the environment issue, and are included in its reason and+`evaluation_errors`. Reports include the missing name and dependency+declaration/installation guidance. Declare system tools in+`scripts/apt-packages.txt`, Python packages in `scripts/requirements.txt`, or+install them in `evals/environment/Dockerfile`. Agent-chosen tools the skill+does not use remain agent errors. Missing files inside the skill remain skill+defects (0.25 deduction if recovered); real unrecovered skill/agent failures+still score zero.+- `accuracy` is passing criteria divided by five. The criteria grade theoutcome: `ACTION_CORRECT`, `FACTUALLY_ACCURATE`, `TASK_ADDRESSED`,`ACTIONABLE`, and `FORMAT_FOLLOWED` (the response follows any output formatdiff --git a/src/skillevaluator/tier3/eval_core/checks.py b/src/skillevaluator/tier3/eval_core/checks.pyindex 1b2ee49d..bb6b358c 100644--- a/src/skillevaluator/tier3/eval_core/checks.py+++ b/src/skillevaluator/tier3/eval_core/checks.py@@ -4516,11 +4516,125 @@ def check_workflow_order(return {"passed": False, "score": 0.0, "reason": "Agent did not follow expected order"}+def _classify_execution_failure(+ command: str, observation: str, expected_script: str | None, context: dict[str, Any] | None+) -> dict[str, Any]:+ context = context or {}+ result = {"fault": "agent", "fault_kind": "command_error"}+ paths = [str(p).rstrip("/") for p in context.get("skill_dirs", []) if p]++ def skill_path(path: str) -> bool:+ return bool(expected_script and (path == expected_script or path.endswith("/" + expected_script))) or any(+ path.startswith(root + "/") for root in paths+ )++ file_match = re.search(r"(?:FileNotFoundError:[^\n]*|can't open file)\s*['\"]([^'\"]+)['\"]", observation)+ if file_match is None:+ file_match = re.search(r"(?:^|\s)([^\s:'\"]+): No such file or directory", observation, re.MULTILINE)+ if file_match and skill_path(file_match.group(1)):+ return {+ "fault": "skill",+ "fault_kind": "missing_skill_file",+ "missing": file_match.group(1),+ "missing_kind": "file",+ }++ module = re.search(r"(?:ModuleNotFoundError|ImportError): No module named\s+['\"]?([\w.-]+)", observation)+ subprocess_executable = None+ if re.search(r"(?:subprocess\.py|_execute_child)", observation):+ subprocess_executable = re.search(+ r"FileNotFoundError:[^\n]*No such file or directory:\s*['\"]([^/'\"\\]+)['\"]", observation+ )+ missing = (+ module.group(1).split(".")[0] if module else (subprocess_executable.group(1) if subprocess_executable else None)+ )+ kind = "python_module" if module else "executable"+ if module and missing in context.get("skill_modules", []):+ return {"fault": "skill", "fault_kind": "missing_skill_file", "missing": missing, "missing_kind": kind}+ if not missing:+ patterns = (+ r"(?:^|\n)(?:/[^\s:]+/)?(?:bash|sh):\s*(?:(?:line\s+)?\d+:\s*)?([^\s:]+): (?:command )?not found",+ r"^[^\s:]+: (?:line )?\d+: ([^\s:]+): (?:command )?not found",+ r"zsh: command not found: ([^\s]+)",+ r"env: ['\"\u2018]?([^\s'\"\u2019]+)['\"\u2019]?: No such file or directory",+ r'exec: "([^\"]+)": executable file not found in \$PATH',+ )+ for pattern in patterns:+ if match := re.search(pattern, observation):+ missing = match.group(1)+ break+ if not missing:+ return result+ if skill_path(missing):+ return {"fault": "skill", "fault_kind": "missing_skill_file", "missing": missing, "missing_kind": "file"}++ def normalized(name: str) -> str:+ match = re.match(r"[A-Za-z0-9_.-]+", name.strip())+ return match.group().lower().replace("-", "_") if match else ""++ dependencies = context.get("pip", []) if module else context.get("apt", [])+ aliases = {+ "yaml": "pyyaml",+ "pil": "pillow",+ "bs4": "beautifulsoup4",+ "docx": "python-docx",+ "pdftotext": "poppler-utils",+ }+ declared_names = {normalized(str(name)) for name in dependencies}+ declared = normalized(missing) in declared_names or normalized(aliases.get(missing.lower(), "")) in declared_names+ used = bool(re.search(r"(?<![\w-])" + re.escape(missing) + r"(?![\w-])", context.get("skill_text", "")))+ used = (+ used or missing in context.get("script_imports", []) or _command_executes_skill(command, expected_script, paths)+ )+ result = {"fault": "agent", "fault_kind": "agent_tool_choice", "missing": missing, "missing_kind": kind}+ if declared or used:+ declaration = "scripts/requirements.txt" if module else "scripts/apt-packages.txt"+ guidance = (+ f"{missing} is declared but not installed in the evaluation environment. "+ if declared+ else (+ f"Install the package that provides {missing}, or ship it with the skill. "+ if module and missing in context.get("script_imports", [])+ else f"Declare {missing} in {declaration}, or install it in evals/environment/Dockerfile. "+ )+ )+ guidance += (+ "With a custom evals/environment/Dockerfile, dependency files are not auto-installed; install it there."+ )+ result.update(+ fault="environment",+ fault_kind="declared_dependency_unavailable" if declared else "undeclared_dependency",+ guidance=guidance,+ )+ return result+++def _command_executes_skill(command: str, expected_script: str | None, paths: list[str]) -> bool:+ if expected_script and _cmd_executes_script(command, expected_script) is True:+ return True+ try:+ tokens = shlex.split(command)+ except ValueError:+ return False+ interpreters = {"bash", "sh", "zsh", "python", "python2", "python3", "node", "ruby", "perl", "php"}+ candidates = tokens[:1]+ candidates.extend(+ tokens[index + 1] for index, token in enumerate(tokens[:-1]) if token.rsplit("/", 1)[-1].lower() in interpreters+ )+ return any(+ bool((expected_script or paths) and token.removeprefix("./").startswith("scripts/"))+ or any(token.startswith(root + "/") for root in paths)+ for token in candidates+ )++def check_error_recovery(tool_calls: list[dict[str, Any]],expected_script: str | None = None,+ *,+ dependency_context: dict[str, Any] | None = None,) -> dict[str, Any]:- """Detect error-retry patterns and attribute fault to skill vs agent.+ """Detect error-retry patterns and attribute skill, agent, or environment faults.Scans bash/execute tool calls for commands that failed (non-zero exit orerror keywords in observation) followed by a similar command that@@ -4536,6 +4650,8 @@ def check_error_recovery("corrections": [],"skill_faults": 0,"agent_faults": 0,+ "environment_faults": 0,+ "environment_issues": [],}exec_actions = {"bash", "execute", "run_code", "run"}@@ -4589,7 +4705,7 @@ def check_error_recovery(r"|^\s*(?:\w*(?:error|exception)|timeout|connectionrefused)\s*$"rf"|^\s*\w*(?:Error|Exception)\s*:{not_annotation}|traceback\s*\(most recent call last\)"r"|\bstatus\s*=\s*(?:failed|error)\b"- r"|\b(?:command not found|no such file(?: or directory)?|permission denied)\b"+ r"|\b(?:command not found|executable file not found|no such file(?: or directory)?|permission denied)\b"r"|\b(?:connection refused|connectionrefused|timed out)\b|:\s*not found\b"# Test and build failures (pytest, unittest, jest and go test summaries,# tsc, npm) and OpenCode's note for a command stopped at its timeout.@@ -4598,16 +4714,6 @@ def check_error_recovery(r"|\bbash tool terminated command after exceeding timeout\b",re.IGNORECASE | re.MULTILINE,)- skill_fault_keywords = [- "no such file",- "filenotfounderror",- "not found",- "command not found",- "config",- "missing",- "invalid path",- "modulenotfounderror",- ]quiet_probe_programs = {"grep", "egrep", "fgrep", "rg", "test", "[", "[[", "diff", "cmp", "which"}devnull_redirect_re = re.compile(@@ -4742,10 +4848,6 @@ def check_error_recovery(program1, program2 = (re.sub(r"[\d.]+$", "", words[0].rsplit("/", 1)[-1]) for words in (words1, words2))return (bool(program1) and program1 == program2) or words1[0] in words2 or words2[0] in words1- def _is_skill_fault(error_obs: str) -> bool:- obs_lower = error_obs.lower()- return any(kw in obs_lower for kw in skill_fault_keywords)-failed = [_is_failure(call) for _, call in exec_calls]# A benign negative query is not a successful retry of an earlier error.succeeded = [not failed[i] and _exit_status(call) in (None, 0) for i, (_, call) in enumerate(exec_calls)]@@ -4762,14 +4864,14 @@ def check_error_recovery(cmd = _cmd_text(call)obs = str(call.get("observation", ""))- fault = "skill" if _is_skill_fault(obs) else "agent"+ attribution = _classify_execution_failure(cmd, obs, expected_script, dependency_context)# Record every observed failure, whether or not it is later recovered.# Previously only recovered failures (corrections) were tracked, so an# unrecovered failure was silently scored as first-attempt clean.failure: dict[str, Any] = {"failed_cmd": cmd[:200],"error": obs[:300],- "fault": fault,+ **attribution,"recovered": False,}failures.append(failure)@@ -4790,7 +4892,7 @@ def check_error_recovery("failed_cmd": cmd[:200],"retry_cmd": retry_cmd[:200],"error": obs[:300],- "fault": fault,+ **attribution,"steps_to_fix": retry_idx - orig_idx,})@@ -4801,7 +4903,11 @@ def check_error_recovery(first_attempt_clean = len(failures) == 0skill_faults = sum(1 for f in failures if f["fault"] == "skill")agent_faults = sum(1 for f in failures if f["fault"] == "agent")- unrecovered_failures = [f for f in failures if not f["recovered"]]+ environment_issues = [f for f in failures if f["fault"] == "environment"]+ environment_invalid = any(not f["recovered"] for f in environment_issues) and not any(+ not f["recovered"] and f["fault"] == "skill" for f in failures+ )+ unrecovered_failures = [f for f in failures if not f["recovered"] and f["fault"] != "environment"]if first_attempt_clean:score = 1.0@@ -4817,8 +4923,21 @@ def check_error_recovery(score = max(0.5, 1.0 - (agent_faults * 0.1))reason = f"{agent_faults} agent error(s), no skill defects"+ if environment_invalid:+ reason = "Environment invalid: " + "; ".join(+ dict.fromkeys(+ [+ *(f["guidance"] for f in environment_issues if not f["recovered"]),+ *(f["failed_cmd"] for f in unrecovered_failures),+ ]+ )+ )+return {- "passed": first_attempt_clean or (skill_faults == 0 and not unrecovered_failures),+ **({"status": "environment_invalid"} if environment_invalid else {}),+ "passed": None+ if environment_invalid+ else first_attempt_clean or (skill_faults == 0 and not unrecovered_failures),"score": round(score, 4),"reason": reason,"first_attempt_clean": first_attempt_clean,@@ -4827,6 +4946,8 @@ def check_error_recovery("unrecovered_failures": unrecovered_failures,"skill_faults": skill_faults,"agent_faults": agent_faults,+ "environment_faults": len(environment_issues),+ "environment_issues": environment_issues,}@@ -5389,12 +5510,15 @@ def score_skill_execution(require_evaluated_skill: bool = False,skill_tool_names: list[str] | None = None,acceptable_skills: Any = None,+ dependency_context: dict[str, Any] | None = None,) -> dict[str, Any]:"""Compute execution credit, requiring activation for positive cases.Activated or unresolved cases retain the average of sub-checks. A definiteactivation failure receives no execution credit, while retaining all checkdetails for diagnosis. Negative and unlabeled cases use their own rules.+ An unrecovered environment failure returns score None, excluding the case+ from scoring rather than averaging environment failures into skill credit."""expected_script = normalize_optional_reference(expected_script)if should_trigger is None:@@ -5448,8 +5572,10 @@ def score_skill_execution(checks["workflow_order"] = rscores.append(r["score"])- r = check_error_recovery(tool_calls, expected_script)+ r = check_error_recovery(tool_calls, expected_script, dependency_context=dependency_context)checks["error_recovery"] = r+ if r.get("status") == "environment_invalid":+ return {"score": None, "status": "environment_invalid", "details": checks}scores.append(r["score"])# Nonapplicable script/recovery checks must not create execution creditdiff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.pyindex 9d5db65b..fe61af90 100644--- a/src/skillevaluator/tier3/harbor/collector.py+++ b/src/skillevaluator/tier3/harbor/collector.py@@ -4425,7 +4425,11 @@ def _unscoreable_reward_reason(reward: dict[str, Any]) -> str:safe_metric = _safe_diagnostic_text(metric, max_len=64)safe_reason = _safe_diagnostic_text(reason, max_len=512)if safe_reason:- parts.append(f"{safe_metric or 'judge'}: {safe_reason}")+ parts.append(+ f"[environment] {safe_reason}"+ if metric == "environment"+ else f"{safe_metric or 'judge'}: {safe_reason}"+ )elif isinstance(errors, list):parts.extend(_safe_diagnostic_text(reason, max_len=512) for reason in errors[: len(DEFAULT_METRICS)])parts = [part for part in parts if part]@@ -4436,7 +4440,12 @@ def _unscoreable_reward_reason(reward: dict[str, Any]) -> str:if not parts:return fallback- return _safe_diagnostic_text("Required judge evaluation failed: " + "; ".join(parts), max_len=2048)+ prefix = (+ "Evaluation environment invalid: "+ if isinstance(errors, dict) and "environment" in errors+ else "Required judge evaluation failed: "+ )+ return _safe_diagnostic_text(prefix + "; ".join(parts), max_len=2048)def _strip_attempt_suffix(value: str) -> str:diff --git a/src/skillevaluator/tier3/harbor/report.py b/src/skillevaluator/tier3/harbor/report.pyindex a6801d39..13bcbb2a 100644--- a/src/skillevaluator/tier3/harbor/report.py+++ b/src/skillevaluator/tier3/harbor/report.py@@ -469,6 +469,8 @@ def _collect_fail_reasons(metric: str, trials: list[dict[str, Any]]) -> list[strfor check_name, check_data in detail.items():if isinstance(check_data, dict) and not check_data.get("passed", True):reason = _bounded_reason_text(check_data.get("reason")) or f"{str(check_name)[:480]} failed"+ if check_data.get("status") == "environment_invalid":+ reason = "[environment] " + reasonreasons.append(reason)if isinstance(check_data, dict) and check_name == "error_recovery":corrections = check_data.get("corrections")@@ -477,7 +479,7 @@ def _collect_fail_reasons(metric: str, trials: list[dict[str, Any]]) -> list[strcontinuefault = _bounded_reason_text(corr.get("fault")) or "unknown"err = _bounded_reason_text(corr.get("error"), max_len=100)- reasons.append(f"[{fault} fault] {err}")+ reasons.append(f"[environment] {err}" if fault == "environment" else f"[{fault} fault] {err}")elif metric == "skill_efficiency":for check_name, check_data in detail.items():@@ -705,6 +707,7 @@ ERROR RECOVERY ISSUES:EVIDENCE REFERENCES (cite the relevant compact reference exactly in your suggestions):{evidence_block}+Treat [environment] issues as evaluation setup problems, not skill defects. Recommend dependency declarations or installation in evals/environment/Dockerfile, not skill behavior changes.Based on these results, provide exactly 3-4 specific, actionable suggestions for the skill developer to improve their skill. Focus on:1. What the developer should fix in their skill (SKILL.md, scripts, config)2. What they should add to evals/environment/ (Dockerfile, docker-compose) if tools are missingdiff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.pyindex 2f959caf..47b88cad 100644--- a/src/skillevaluator/tier3/harbor/templates/eval.py+++ b/src/skillevaluator/tier3/harbor/templates/eval.py@@ -3778,6 +3778,67 @@ def write_reward_outputs(result, overall):REWARD_TXT.write_text(str(sanitized_overall))+def _dependency_context(skill: str, *, skills_root: Path = Path("/workspace/skills")) -> dict[str, Any]:+ """Read bounded dependency evidence from the evaluator-staged skill."""+ context: dict[str, Any] = {+ "apt": [],+ "pip": [],+ "skill_text": "",+ "skill_dirs": [],+ "skill_modules": set(),+ "script_imports": set(),+ }+ if not skill or skill in {".", ".."} or Path(skill).name != skill:+ return context+ root = skills_root / skill+ if not root.is_dir():+ return context+ context["skill_dirs"] = [+ str(root),+ f"/root/.claude/skills/{skill}",+ f"/root/.agents/skills/{skill}",+ f"/root/.config/opencode/skills/{skill}",+ f"/etc/codex/skills/{skill}",+ ]+ remaining = 1024 * 1024+ for index, path in enumerate(root.rglob("*")):+ if index >= 4096 or remaining <= 0:+ break+ if path.is_symlink() or not path.is_file() or not path.resolve().is_relative_to(root.resolve()):+ continue+ relative = path.relative_to(root)+ if path.suffix == ".py":+ context["skill_modules"].add(path.stem)+ context["skill_modules"].update(relative.parts[:-1])+ if path.name == "__init__.py":+ context["skill_modules"].add(path.parent.name)+ dependency = path.parent.name == "scripts" and path.name in {"requirements.txt", "apt-packages.txt"}+ if not dependency and path.name.lower() != "skill.md" and "scripts" not in relative.parts:+ continue+ try:+ with path.open("rb") as stream:+ data = stream.read(min(remaining, 128 * 1024))+ except OSError:+ continue+ remaining -= len(data)+ content = data.decode("utf-8", errors="replace")+ if dependency:+ key = "pip" if path.name == "requirements.txt" else "apt"+ context[key].extend(+ line.split("#", 1)[0].strip()+ for line in content.splitlines()+ if line.strip() and not line.lstrip().startswith(("#", "-"))+ )+ else:+ context["skill_text"] += "\n" + content+ if "scripts" in relative.parts and path.suffix == ".py":+ imports = re.finditer(r"(?m)^\s*(?:from\s+([\w.]+)\s+import\b|import\s+([\w.]+))", content)+ context["script_imports"].update((match.group(1) or match.group(2)).split(".")[0] for match in imports)+ context["skill_modules"] = sorted(context["skill_modules"])+ context["script_imports"] = sorted(context["script_imports"])+ return context++def main():entry = json.loads(ENTRY_PATH.read_text(encoding="utf-8"))traj, traj_meta = load_trajectory_with_fallback(ATIF_PATH, ATIF_PATH.parent)@@ -3872,9 +3933,26 @@ def main():require_evaluated_skill=True,skill_tool_names=skill_tools,acceptable_skills=acceptable_skills,+ dependency_context=_dependency_context(evaluated_skill or expected_skill),)se_score = skill_execution_result["score"]details["skill_execution"] = skill_execution_result["details"]+ if skill_execution_result.get("status") == "environment_invalid":+ recovery = skill_execution_result["details"]["error_recovery"]+ write_reward_outputs(+ {+ "evaluation_status": "failed",+ "evaluation_errors": {"environment": recovery["reason"]},+ "environment_issues": recovery["environment_issues"],+ "entry_id": entry.get("id"),+ "metric_set": DEFAULT_METRIC_SET,+ "score_policy": DEFAULT_SCORE_POLICY,+ "details": details,+ },+ 0.0,+ )+ logger.error("[environment] %s", recovery["reason"])+ raise SystemExit(1)else:se_score = Nonedetails["skill_execution"] = _skill_metric_not_applicable()diff --git a/tests/test_harbor_unscored_grading_policy.py b/tests/test_harbor_unscored_grading_policy.pyindex 9c15dfd1..040d0968 100644--- a/tests/test_harbor_unscored_grading_policy.py+++ b/tests/test_harbor_unscored_grading_policy.py@@ -79,6 +79,45 @@ def _write_scored_job(job_dir: Path, reward: dict[str, object]) -> None:_write_json(job_dir / "case-001__attempt" / "verifier" / "reward.json", reward)+def test_environment_invalid_trial_is_unscored_with_reason(tmp_path):+ jobs = tmp_path / "jobs"+ job = jobs / "demo-codex-with"+ _write_scored_job(job, {"overall": 0.0})+ _write_json(+ job / "case-001__attempt" / "verifier" / "skill_evaluator_reward.json",+ {+ "evaluation_status": "failed",+ "evaluation_errors": {+ "environment": "jq is unavailable; declare it in scripts/apt-packages.txt or install in evals/environment/Dockerfile"+ },+ "environment_issues": [+ {+ "fault": "environment",+ "fault_kind": "undeclared_dependency",+ "missing": "jq",+ "missing_kind": "executable",+ "recovered": False,+ }+ ],+ },+ )+ result = collect_harbor_results(+ "demo",+ ["codex"],+ tmp_path / "results",+ jobs,+ skip_baseline=True,+ expected_cases=1,+ expected_case_ids=["case-001"],+ )+ assert result["scored_attempts"] == 0+ assert result["agents"]["codex"]["with_skill"] == {}+ (failure,) = result["agents"]["codex"]["trial_failures"]["with_skill"]+ assert "[environment]" in failure["reason"]+ assert "jq" in failure["reason"]+ assert "scripts/apt-packages.txt" in failure["reason"]++@pytest.mark.parametrize("grading_mode", [None, "default", "default_plus_custom", "custom_only"])@pytest.mark.parametrize("skip_baseline", [True, False])def test_failed_conditions_keep_requested_grading_policy(diff --git a/tests/tier3/test_error_recovery.py b/tests/tier3/test_error_recovery.pyindex 5f642abe..f5d1fbdb 100644--- a/tests/tier3/test_error_recovery.py+++ b/tests/tier3/test_error_recovery.py@@ -12,7 +12,7 @@ from __future__ import annotationsimport pytestfrom skillevaluator.tier3.eval_core.atif_helpers import extract_tool_calls_as_dicts-from skillevaluator.tier3.eval_core.checks import check_error_recovery+from skillevaluator.tier3.eval_core.checks import check_error_recovery, score_skill_executionfrom skillevaluator.tier3.harbor.report import _collect_fail_reasonsfrom skillevaluator.tier3.harbor.templates import eval as eval_template@@ -42,6 +42,189 @@ def _codex_output(exit_code: int, output: str = "") -> str:)+ "diagnostic,missing,kind",+ [+ ("bash: jq: command not found", "jq", "executable"),+ ("bash: line 1: jq: command not found", "jq", "executable"),+ ("sh: 1: jq: not found", "jq", "executable"),+ ("/bin/sh: jq: not found", "jq", "executable"),+ ("zsh: command not found: jq", "jq", "executable"),+ ("env: 'jq': No such file or directory", "jq", "executable"),+ ('exec: "jq": executable file not found in $PATH', "jq", "executable"),+ ("ModuleNotFoundError: No module named 'Some_Package.sub'", "Some_Package", "python_module"),+ ("ImportError: No module named Some_Package", "Some_Package", "python_module"),+ ],+)[email protected]("source", ["declared", "skill_text", "script", "agent"])[email protected]("recovered", [True, False])+def test_dependency_attribution(checker, diagnostic, missing, kind, source, recovered):+ context = {"apt": ["JQ=1.0"], "pip": ["some-package[extra]>=1"]} if source == "declared" else {}+ if source == "skill_text":+ context["skill_text"] = f"Run {missing} to finish"+ calls = [_call("python scripts/task.py", diagnostic)]+ if recovered:+ calls.append(_call("python scripts/task.py", "exit code 0"))+ result = checker(+ calls, expected_script="scripts/task.py" if source == "script" else None, dependency_context=context+ )+ failure = result["failures"][0]+ assert failure["missing"] == missing+ assert failure["missing_kind"] == kind+ assert failure["recovered"] is recovered+ if source == "agent":+ assert failure["fault_kind"] == "agent_tool_choice"+ assert result["agent_faults"] == 1+ assert result["score"] == (0.9 if recovered else 0.0)+ else:+ assert failure["fault"] == "environment"+ assert failure["fault_kind"] == (+ "declared_dependency_unavailable" if source == "declared" else "undeclared_dependency"+ )+ assert result["environment_faults"] == 1+ assert result["skill_faults"] == result["agent_faults"] == 0+ assert result["score"] == 1.0+ assert result["passed"] is (True if recovered else None)+ assert (result.get("status") == "environment_invalid") is not recovered+ assert "evals/environment/Dockerfile" in failure["guidance"]+++def test_skill_path_and_non_skill_file(checker):+ context = {"skill_dirs": ["/workspace/skills/demo"]}+ for path, fault in [("/workspace/skills/demo/scripts/run.py", "skill"), ("/input/missing.csv", "agent")]:+ result = checker(+ [_call("python run.py", f"FileNotFoundError: [Errno 2] No such file or directory: '{path}'")],+ dependency_context=context,+ )+ assert result["failures"][0]["fault"] == fault+ assert result["failures"][0]["fault_kind"] == ("missing_skill_file" if fault == "skill" else "command_error")+ assert result["score"] == 0.0+++def test_environment_does_not_hide_real_failure(checker):+ result = checker(+ [_call("jq", "bash: jq: command not found"), _call("python task.py", "ValueError: invalid input")],+ dependency_context={"apt": ["jq"]},+ )+ assert result["status"] == "environment_invalid"+ assert result["score"] == 0.0+ assert result["agent_faults"] == 1+++ "diagnostic",+ [+ "scripts/extract.sh: line 3: pdftotext: command not found",+ "/root/.claude/skills/demo/scripts/extract.sh: 3: pdftotext: not found",+ ],+)+def test_skill_script_missing_executable_is_environment_failure(checker, diagnostic):+ result = checker(+ [_call("bash scripts/extract.sh", diagnostic)],+ expected_script="scripts/extract.sh",+ dependency_context={"skill_text": "Use pdftotext", "skill_dirs": ["/workspace/skills/demo"]},+ )+ assert result["environment_faults"] == 1+ assert result["failures"][0]["missing"] == "pdftotext"+++def test_subprocess_file_not_found_is_missing_executable_but_open_is_not(checker):+ context = {"skill_text": "Use pdftotext", "skill_dirs": ["/workspace/skills/demo"]}+ result = checker(+ [+ _call(+ "python scripts/extract.py",+ 'Traceback: File ".../subprocess.py", line 1950, in _execute_child\n'+ "FileNotFoundError: [Errno 2] No such file or directory: 'pdftotext'",+ )+ ],+ expected_script="scripts/extract.py",+ dependency_context=context,+ )+ assert result["failures"][0]["missing"] == "pdftotext"+ assert result["failures"][0]["missing_kind"] == "executable"+ open_result = checker([_call("python scripts/extract.py", "FileNotFoundError: 'input.json'")])+ assert open_result["failures"][0]["fault_kind"] == "command_error"+++def test_skill_path_as_tool_argument_does_not_mean_skill_uses_tool(checker):+ result = checker(+ [_call("tree /workspace/skills/demo/", "bash: line 1: tree: command not found")],+ dependency_context={"skill_dirs": ["/workspace/skills/demo"], "skill_text": "Run scripts/run.py"},+ )+ assert result["failures"][0]["fault_kind"] == "agent_tool_choice"+++def test_skill_modules_and_package_aliases_are_classified(checker):+ module = checker(+ [+ _call(+ "python /workspace/skills/demo/scripts/run.py", "ModuleNotFoundError: No module named 'scripts.helpers'"+ )+ ],+ expected_script="scripts/run.py",+ dependency_context={"skill_modules": ["scripts", "helpers"]},+ )+ assert module["failures"][0]["fault_kind"] == "missing_skill_file"+ alias = checker(+ [_call("python scripts/run.py", "ModuleNotFoundError: No module named 'yaml'")],+ dependency_context={"pip": ["PyYAML>=6"]},+ )+ assert alias["failures"][0]["fault_kind"] == "declared_dependency_unavailable"+ imported = checker(+ [_call("python scripts/run.py", "ModuleNotFoundError: No module named 'rasterio'")],+ dependency_context={"script_imports": ["rasterio"]},+ )+ assert "Install the package that provides rasterio" in imported["failures"][0]["guidance"]+++def test_dependency_context_records_modules_provided_by_skill(tmp_path):+ skill = tmp_path / "demo"+ scripts = skill / "scripts"+ scripts.mkdir(parents=True)+ (scripts / "__init__.py").write_text("")+ (scripts / "helpers.py").write_text("def summarize(): pass\n")+ (scripts / "run.py").write_text("from rasterio import open\n")+ context = eval_template._dependency_context("demo", skills_root=tmp_path)+ assert {"scripts", "helpers"} <= set(context["skill_modules"])+ assert "rasterio" in context["script_imports"]+++def test_environment_failure_reason_retains_agent_failure(checker):+ result = checker(+ [+ _call("jq --version", "bash: jq: command not found"),+ _call("python task.py", "ValueError: invalid input"),+ ],+ dependency_context={"apt": ["jq"]},+ )+ assert result["status"] == "environment_invalid"+ assert "python task.py" in result["reason"]+++def test_skill_fault_overrides_environment_in_score(checker):+ calls = [+ _call("jq --version", "bash: jq: command not found"),+ _call(+ "python /workspace/skills/demo/scripts/run.py",+ "FileNotFoundError: can't open file '/workspace/skills/demo/scripts/run.py'",+ ),+ ]+ recovery = checker(+ calls, expected_script="/workspace/skills/demo/scripts/run.py", dependency_context={"apt": ["jq"]}+ )+ scored = score_skill_execution(+ calls,+ "demo",+ expected_script="/workspace/skills/demo/scripts/run.py",+ skill_tool_names=["demo"],+ dependency_context={"apt": ["jq"], "skill_dirs": ["/workspace/skills/demo"]},+ )+ assert recovery["skill_faults"] == 1+ assert recovery.get("status") != "environment_invalid"+ assert scored["score"] is not None++def test_failure_with_no_retry_is_not_first_attempt_clean(checker):"""A failure that is never retried must not score 1.0 / passed-clean."""result = checker([_call("pytest tests/test_api.py -x", "ERROR: test_create_user failed\nexit code 1")])@@ -99,7 +282,7 @@ def test_unrecovered_failure_after_earlier_success(checker):assert result["score"] == 0.0assert len(result["failures"]) == 1assert len(result["unrecovered_failures"]) == 1- assert result["unrecovered_failures"][0]["fault"] == "skill"+ assert result["unrecovered_failures"][0]["fault"] == "agent"assert "make build" in result["reason"]@@ -116,8 +299,8 @@ def test_unrecovered_failure_after_earlier_recovery(checker):assert [f["failed_cmd"] for f in result["unrecovered_failures"]] == ["make build"]assert result["score"] == 0.0assert result["passed"] is False- assert result["skill_faults"] == 1- assert result["agent_faults"] == 1+ assert result["skill_faults"] == 0+ assert result["agent_faults"] == 2@pytest.mark.parametrize(@@ -169,7 +352,9 @@ def test_failure_detection_agrees(checker, observation):def test_unrecovered_skill_fault_report_reason(checker):- result = checker([_call("make build", "gcc: error: missing.c: No such file or directory")])+ result = checker(+ [_call("make build", "gcc: error: missing.c: No such file or directory")], expected_script="missing.c"+ )assert result["passed"] is Falseassert result["skill_faults"] == 1assert result["agent_faults"] == 0@@ -181,9 +366,10 @@ def test_unrecovered_skill_fault_report_reason(checker):def test_recovered_skill_fault_counted_once(checker):result = checker([- _call("make build", "No such file or directory"),+ _call("make build", "missing.c: No such file or directory"),_call("make build", "done"),- ]+ ],+ expected_script="missing.c",)assert result["skill_faults"] == 1assert result["score"] == 0.75diff --git a/tests/tier3/test_judge_failure_artifacts.py b/tests/tier3/test_judge_failure_artifacts.pyindex b9e2b3e2..cb71479f 100644--- a/tests/tier3/test_judge_failure_artifacts.py+++ b/tests/tier3/test_judge_failure_artifacts.py@@ -170,6 +170,64 @@ def test_character_facts_keep_numeric_dataset_answers_scoreable(tmp_path, monkeyassert overall_score(collected) == numeric["overall"]+def test_staged_dependency_context_is_bounded(tmp_path):+ verifier = _load_verifier(tmp_path)+ root = tmp_path / "skills" / "demo"+ scripts = root / "nested" / "scripts"+ scripts.mkdir(parents=True)+ (root / "SKILL.md").write_text("Use jq")+ (scripts / "apt-packages.txt").write_text("# tools\njq=1.7 # JSON\n")+ (scripts / "requirements.txt").write_text("Some-Package[extra]>=1\n")+ (scripts / "run.py").write_text("x" * (128 * 1024) + "excluded_tail")+ (scripts / "outside.py").symlink_to(verifier.ENTRY_PATH)+ context = verifier._dependency_context("demo", skills_root=root.parent)+ assert context["apt"] == ["jq=1.7"]+ assert context["pip"] == ["Some-Package[extra]>=1"]+ assert "Use jq" in context["skill_text"]+ assert "excluded_tail" not in context["skill_text"]+ assert "judge-artifact-case" not in context["skill_text"]+ assert verifier._dependency_context("../demo", skills_root=root.parent)["skill_text"] == ""+ assert verifier._dependency_context("absent", skills_root=root.parent)["apt"] == []++[email protected]("declared", [True, False])+def test_missing_dependency_is_unscored_before_judging(tmp_path, monkeypatch, declared):+ verifier = _load_verifier(tmp_path)+ entry = json.loads(verifier.ENTRY_PATH.read_text())+ entry.update(expected_skill="demo", evaluated_skill="demo", should_trigger=True, expected_script="scripts/run.py")+ verifier.ENTRY_PATH.write_text(json.dumps(entry))+ if declared:+ monkeypatch.setattr(verifier, "_dependency_context", lambda _skill: {"apt": ["jq"]})+ monkeypatch.setattr(+ verifier,+ "extract_tool_calls_as_dicts",+ lambda _traj: [+ {+ "action": "bash",+ "action_input": {"command": "python scripts/run.py"},+ "observation": "bash: line 1: jq: command not found\nexit code 127",+ }+ ],+ )+ monkeypatch.setattr(verifier, "_call_required_judge", lambda *_a, **_kw: pytest.fail("Judge must not run"))+ with pytest.raises(SystemExit, match="1"):+ verifier.main()+ sidecar = json.loads(verifier.SKILL_EVALUATOR_REWARD_JSON.read_text())+ assert sidecar["evaluation_status"] == "failed"+ assert "jq" in sidecar["evaluation_errors"]["environment"]+ assert sidecar["environment_issues"][0]["fault_kind"] == (+ "declared_dependency_unavailable" if declared else "undeclared_dependency"+ )+ collected = json.loads(verifier.REWARD_JSON.read_text())+ collector._merge_reward_sidecars(collected, verifier.VERIFIER_DIR)+ assert overall_score(collected) is None+ reason = collector._unscoreable_reward_reason(collected)+ assert "[environment]" in reason+ assert "jq" in reason+ assert "evals/environment/Dockerfile" in reason+ assert "judge evaluation failed" not in reason++def test_verifier_main_fails_closed_after_collecting_every_required_judge(tmp_path: Path,monkeypatch: pytest.MonkeyPatch,