Skip to content

Multi-tier framework for evaluating AI agent skills and plugins with quality gates, security scanning, harness compatibility checks, semantic overlap detection, synthetic evaluation dataset generation, and live agent evaluation that measures how skills affect agent behavior. Ships reusable CI templates that bring every check to any repository.

Share trace evidence, applicable scores and security checks (#258)

Christopher Kevin239e3213d014
diff --git a/ci/publish_reports.py b/ci/publish_reports.py
index 2fa20911..55c1633e 100644
--- a/ci/publish_reports.py
+++ b/ci/publish_reports.py
@@ -157,7 +157,9 @@ def validate_summary(summary: dict) -> None:
raise PublicationError("A skill's verdict contradicts its process evidence.")
if not row["passed"] and row["overall_status"] == "passed":
raise PublicationError("A failed skill cannot claim a passing status.")
- if bool(row["incomplete_scans"]) != (row["overall_status"] == "incomplete"):
+ if (row["overall_status"] == "incomplete" and not row["incomplete_scans"]) or (
+ row["incomplete_scans"] and row["overall_status"] not in {"failed", "incomplete"}
+ ):
raise PublicationError("A skill's status contradicts its scanner completeness evidence.")
if row["overall_status"] != "error":
if any(not _integer(row.get(key)) for key in ("total_validators", "total_errors", "total_warnings")):
@@ -203,6 +205,8 @@ def validate_summary(summary: dict) -> None:
if skipped
else "passed"
if expected
+ else "failed"
+ if any(row["overall_status"] == "failed" for row in rows)
else "incomplete"
if incomplete
else "failed"
@@ -238,6 +242,15 @@ def validate_report(report: dict, row: dict) -> None:
report.get("incomplete_scans")
):
raise PublicationError("A per-skill report contains invalid completeness evidence.")
+ # Establish statuses from the typed findings and scanner evidence, rather
+ # than trusting matching rollups supplied by an untrusted artifact.
+ from skillevaluator.reporting.retained import RetainedReportError, retained_results
+ from skillevaluator.reporting.run_status import resolve_run_status
+
+ try:
+ retained = retained_results(report, copy_metadata=False)
+ except RetainedReportError as exc:
+ raise PublicationError("A per-skill report contains invalid retained evidence.") from exc
incomplete = []
totals = {"errors": 0, "warnings": 0, "critical_count": 0, "high_count": 0, "medium_count": 0, "low_count": 0}
for result in results:
@@ -245,7 +258,7 @@ def validate_report(report: dict, row: dict) -> None:
if type(result.get("passed")) is not bool or status not in {"passed", "failed", "incomplete", "skipped"}:
raise PublicationError("A validator has an invalid verdict.")
scans = result.get("incomplete_scans")
- if not _scanner_list(scans) or (status == "incomplete") != bool(scans):
+ if not _scanner_list(scans):
raise PublicationError("A validator has contradictory scanner completeness evidence.")
if result["passed"] != (status in {"passed", "skipped"}):
raise PublicationError("A validator has contradictory pass and status fields.")
@@ -257,7 +270,7 @@ def validate_report(report: dict, row: dict) -> None:
totals[key] += counts[key]
incomplete = list(dict.fromkeys(incomplete))
all_passed = all(result["passed"] for result in results)
- status = "incomplete" if incomplete else "passed" if all_passed else "failed"
+ status = resolve_run_status(retained).headline.value
if (report["overall_passed"], report["overall_status"], report["incomplete_scans"]) != (
all_passed,
status,
diff --git a/ci/run_tier1.py b/ci/run_tier1.py
index b24207df..4408ebfb 100644
--- a/ci/run_tier1.py
+++ b/ci/run_tier1.py
@@ -246,6 +246,8 @@ def _summary(skills: list[dict], error: str | None = None) -> dict:
"overall_passed": bool(skills) and passed == len(skills) and error is None,
"overall_status": "error"
if error
+ else "failed"
+ if any(item["overall_status"] == "failed" for item in skills)
else "incomplete"
if incomplete
else "passed"
diff --git a/src/skillevaluator/deduplication/intra_skill/semantic_clustering.py b/src/skillevaluator/deduplication/intra_skill/semantic_clustering.py
index 78180eb6..206390e6 100644
--- a/src/skillevaluator/deduplication/intra_skill/semantic_clustering.py
+++ b/src/skillevaluator/deduplication/intra_skill/semantic_clustering.py
@@ -101,6 +101,10 @@ def build_clusters(
raise ValueError("Content scalar comparison work exceeds the configured limit")
units = [normalize_embedding_vector(chunk.embedding, dimension, allow_zero=True) for chunk in chunks]
+ def siblings(i: int, j: int) -> bool:
+ group = chunks[i].split_group
+ return group is not None and group == chunks[j].split_group
+
uf = UnionFind(n)
pair_scores: dict[tuple[int, int], float] = {}
diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.py
index 4ed6185f..0bcaf344 100644
--- a/src/skillevaluator/evaluation/tier3_report.py
+++ b/src/skillevaluator/evaluation/tier3_report.py
@@ -1659,7 +1659,23 @@ def _judge_aware_lift(
recorded = recorded if isinstance(recorded, dict) else {}
from skillevaluator.tier3.harbor.metrics import not_applicable_list
- paired_contract = isinstance(recorded.get("basis"), dict) or any(
+ basis = recorded.get("basis")
+ aggregate_only = all(
+ key not in info for key in ("rewards", "rewards_baseline", "rewards_complete", "rewards_baseline_complete")
+ )
+ unchanged_basis = (
+ isinstance(basis, dict)
+ and type(basis.get("excluded_case_entries")) is int
+ and basis["excluded_case_entries"] == 0
+ and basis.get("excluded_cases") == []
+ and basis.get("excluded_metrics") == []
+ and basis.get("excluded_cases_truncated") is False
+ )
+ # Live collector results can contain only aggregate metric maps. With no
+ # exclusions their comparison is recomputed from those maps below. Saved
+ # runs always carry explicit reward-completeness fields, so missing saved
+ # evidence never takes this aggregate-only path.
+ paired_contract = (isinstance(basis, dict) and not (aggregate_only and unchanged_basis)) or any(
not_applicable_list(info.get(f"_not_applicable_hint_{arm}")) or _arm_not_applicable(info, arm)
for arm in ("with_skill", "without_skill")
)
@@ -1773,6 +1789,34 @@ def _judge_aware_lift(
return rebuilt
+def _mixed_logical_overall_lift(conditions: list[list[dict[str, Any]]]) -> dict[str, float] | None:
+ """Compare complete mixed rewards only when both arms scored the same case contracts."""
+ from skillevaluator.tier3.harbor.collector import _average_overall, _entry_id
+ from skillevaluator.tier3.harbor.metrics import metric_is_not_applicable, metric_set_for_reward
+
+ cohorts = []
+ for rewards in conditions:
+ by_case: dict[str, set[tuple[Any, ...]]] = {}
+ for reward in rewards:
+ case = _entry_id(reward)
+ if case in {"", "unknown"}:
+ return None
+ _, metrics = metric_set_for_reward(reward)
+ contract = (
+ metrics,
+ tuple(metric for metric in metrics if metric_is_not_applicable(reward, metric)),
+ bool(reward.get("_logical_mixed_contracts")),
+ )
+ by_case.setdefault(case, set()).add(contract)
+ cohorts.append(by_case)
+ if not cohorts[0] or cohorts[0] != cohorts[1]:
+ return None
+ with_score, baseline_score = (_average_overall(rewards) for rewards in conditions)
+ if with_score is None or baseline_score is None:
+ return None
+ return {"with_skill": with_score, "without_skill": baseline_score, "delta": round(with_score - baseline_score, 4)}
+
+
def _build_agent(
name: str,
info: dict[str, Any],
@@ -1802,6 +1846,11 @@ def _build_agent(
not never_activated and set(with_metrics) == set(baseline_metrics) and len(condition_policies) == 1
)
lift_data = info.get("lift") if isinstance(info.get("lift"), dict) else {}
+ comparison_unavailable = (
+ info.get("comparison_unavailable") is True
+ or info.get("comparison_complete") is False
+ or lift_data.get("comparison_unavailable") is True
+ )
with_quality_available = _condition_quality_available(info, "with_skill")
baseline_quality_available = _condition_quality_available(info, "without_skill")
if not with_quality_available:
@@ -1937,11 +1986,9 @@ def _build_agent(
4,
)
if judge_lift is not None:
- overall_lift = (
- _lift_value("overall", judge_lift)
- if comparable_scores and not (with_mixed_contract or baseline_mixed_contract)
- else None
- )
+ overall_lift = _lift_value("overall", judge_lift) if comparable_scores else None
+ if comparison_unavailable:
+ overall_lift = None
trials = _normalize_trials(info.get("rewards") or [], with_metrics)
baseline_trials = _normalize_trials(info.get("rewards_baseline") or [], baseline_metrics)
diff --git a/src/skillevaluator/reporting/benchmark.py b/src/skillevaluator/reporting/benchmark.py
index 7fefc2fa..013f520f 100644
--- a/src/skillevaluator/reporting/benchmark.py
+++ b/src/skillevaluator/reporting/benchmark.py
@@ -49,6 +49,7 @@ from skillevaluator.reporting.base import (
unrecognized_tier2_results,
)
from skillevaluator.reporting.run_status import resolve_run_status
+from skillevaluator.reporting.tier3_scope import completed_agent_result, validate_report_scope
from skillevaluator.source_identity import evaluated_source_revision, recorded_evaluated_source
from skillevaluator.tier3_environments import HARBOR_ENV_MODES
@@ -170,15 +171,23 @@ class BenchmarkReporter(ReporterBase):
lines: list[str] = [
f"# Skill Benchmark: {skill_name}",
"",
- (f"> **Tier 3 completed-agent result: {completed['verdict'].upper()}**" if completed
- else "> **Tier 3: No complete agent result**") if self.report_scope == "tier3" else _verdict_callout(status),
+ (
+ f"> **Tier 3 completed-agent result: {completed['verdict'].upper()}**"
+ if completed
+ else "> **Tier 3: No complete agent result**"
+ )
+ if self.report_scope == "tier3"
+ else _verdict_callout(status),
"",
]
if self.report_scope == "tier3":
- lines.extend([
- "Publication: **NOT ASSESSED**. This report covers Tier 3 only; Tiers 1 and 2 are not covered by this report.",
- "The verdict describes with-skill quality; lift is a separate baseline comparison.", "",
- ])
+ lines.extend(
+ [
+ "Publication: **NOT ASSESSED**. This report covers Tier 3 only; Tiers 1 and 2 are not covered by this report.",
+ "The verdict describes with-skill quality; lift is a separate baseline comparison.",
+ "",
+ ]
+ )
elif status == "PASS":
self._render_publication_recommendation(lines, results)
elif status == "FAIL":
@@ -218,11 +227,17 @@ class BenchmarkReporter(ReporterBase):
f"score **{completed['score']:.4f}** ({completed['score'] * 100:.2f}%)."
)
if completed["lift"] is not None:
- lines.append(f"Same-agent comparable lift: **{completed['lift']:+.4f}** ({completed['lift'] * 100:+.2f} percentage points).")
+ lines.append(
+ f"Same-agent comparable lift: **{completed['lift']:+.4f}** ({completed['lift'] * 100:+.2f} percentage points)."
+ )
if completed["needs_attention"]:
- lines.append("**Needs attention:** other execution failures remain. This completed-agent result does not certify the whole run.")
+ lines.append(
+ "**Needs attention:** other execution failures remain. This completed-agent result does not certify the whole run."
+ )
if completed["recovered_attempts"]:
- lines.append(f"Recovered timeout attempts: {completed['recovered_attempts']}; failed history is retained and excluded from scoring.")
+ lines.append(
+ f"Recovered timeout attempts: {completed['recovered_attempts']}; failed history is retained and excluded from scoring."
+ )
lines.append("")
self._render_metadata(
lines,
diff --git a/src/skillevaluator/reporting/html.py b/src/skillevaluator/reporting/html.py
index db35231e..b706372d 100644
--- a/src/skillevaluator/reporting/html.py
+++ b/src/skillevaluator/reporting/html.py
@@ -74,6 +74,7 @@ from skillevaluator.reporting.base import (
from skillevaluator.reporting.harbor_viewer import normalize_agent_eval_harbor_links
from skillevaluator.reporting.presentation import success_is_not_applicable
from skillevaluator.reporting.run_status import Status, resolve_run_status, result_status
+from skillevaluator.reporting.tier3_scope import completed_agent_result, validate_report_scope
if TYPE_CHECKING:
from skillevaluator.models import ValidationResult
@@ -3089,7 +3090,8 @@ class HTMLReporter(ReporterBase):
publication_status=publication.status,
publication_reasons=publication.reasons,
tier3_effective_status=(
- completed_agent["verdict"] if self.report_scope == "tier3" and completed_agent
+ completed_agent["verdict"]
+ if self.report_scope == "tier3" and completed_agent
else publication.tier3.status
),
total_validators=total_validators,
diff --git a/src/skillevaluator/reporting/retained.py b/src/skillevaluator/reporting/retained.py
index aed79c1f..406925e2 100644
--- a/src/skillevaluator/reporting/retained.py
+++ b/src/skillevaluator/reporting/retained.py
@@ -16,6 +16,7 @@ from typing import Any
from skillevaluator.models import Finding, SuccessDetail, ValidationResult, ValidationSummary
from skillevaluator.reporting.base import is_cleanly_skipped, is_tier2_result, is_tier3_result, passes_required_gate
from skillevaluator.reporting.html import HTMLReporter
+from skillevaluator.reporting.run_status import resolve_run_status, result_status
class RetainedReportError(ValueError):
@@ -215,6 +216,9 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid
if "skipped" in row:
_require(type(row["skipped"]) is bool, "skipped must be boolean")
metadata["skipped"] = row["skipped"]
+ if "confirmed_failure" in row:
+ _require(type(row["confirmed_failure"]) is bool, "confirmed_failure must be boolean")
+ metadata["confirmed_failure"] = row["confirmed_failure"]
if row.get("skip_reason") is not None:
metadata["skip_reason"] = _text(row["skip_reason"], "skip_reason")
_typed_metadata(metadata)
@@ -228,6 +232,11 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid
metadata=metadata,
**{key: _strings(legacy.get(key), f"legacy.{key}") for key in ("errors", "warnings", "messages")},
)
+ if metadata.get("confirmed_failure"):
+ _require(
+ not result.passed and result.summary.errors > 0 and bool(result.errors),
+ "Confirmed failure requires failing diagnostics",
+ )
_require(
not is_tier2_result(result) and not is_tier3_result(result) and "tier3" not in row,
"Only retained Tier 1 reports are supported",
@@ -245,7 +254,7 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid
for key in ("overall_score", "score"):
if key in quality:
_require(type(quality[key]) in (int, float) and 0 <= quality[key] <= 100, "Invalid quality score")
- expected_status = "skipped" if metadata.get("skipped") and result.passed else result.status
+ expected_status = result_status(result).value
_require(row.get("status", expected_status) == expected_status, "Result status contradicts evidence")
verdict_consistent = (
is_cleanly_skipped(result)
@@ -260,11 +269,7 @@ def retained_results(payload: dict, *, copy_metadata: bool = True) -> list[Valid
and payload["overall_passed"] == all(passes_required_gate(r) for r in results),
"Overall verdict contradicts retained results",
)
- overall = (
- "incomplete"
- if any(r.is_incomplete for r in results)
- else ("passed" if all(passes_required_gate(r) for r in results) else "failed")
- )
+ overall = resolve_run_status(results).headline.value
if "overall_status" in payload:
_require(payload["overall_status"] == overall, "Overall status contradicts retained results")
if "total_validators" in payload:
diff --git a/src/skillevaluator/tier3/eval_core/checks.py b/src/skillevaluator/tier3/eval_core/checks.py
index 80ca131d..59069922 100644
--- a/src/skillevaluator/tier3/eval_core/checks.py
+++ b/src/skillevaluator/tier3/eval_core/checks.py
@@ -1592,9 +1592,7 @@ def _rm_shell_tokens(command_text: str) -> tuple[list[str], list[str]] | None:
word_start = False
index = end + 1
continue
- if (quote != "'" and text.startswith("${", index)) or (
- quote is None and text.startswith("((", index)
- ):
+ if (quote != "'" and text.startswith("${", index)) or (quote is None and text.startswith("((", index)):
nested_syntax = True
if char == "`" and quote != "'":
if nested_syntax:
@@ -1693,6 +1691,7 @@ def _rm_wrapped_command_index(words: list[str], start: int) -> int | None:
def _rm_xargs_context(tokens: list[str], rm_index: int) -> bool | None:
"""True for an xargs child rm, False for its option values/help, else unknown."""
+
def boundary(token: str) -> bool:
return token in _SHELL_SEPARATORS or bool(re.fullmatch(r"[;&|(){}]+", token))
@@ -1734,13 +1733,26 @@ def _rm_xargs_context(tokens: list[str], rm_index: int) -> bool | None:
return False
if option.startswith("--"):
name, equals, _ = option.partition("=")
- if name in {"--arg-file", "--delimiter", "--max-args", "--max-chars", "--max-procs",
- "--process-slot-var"}:
+ if name in {
+ "--arg-file",
+ "--delimiter",
+ "--max-args",
+ "--max-chars",
+ "--max-procs",
+ "--process-slot-var",
+ }:
cursor += 1 if equals else 2
elif name in {"--replace", "--eof", "--max-lines"}:
cursor += 1 # These long options accept only attached optional values.
- elif option in {"--null", "--no-run-if-empty", "--interactive", "--verbose", "--exit",
- "--open-tty", "--show-limits"}:
+ elif option in {
+ "--null",
+ "--no-run-if-empty",
+ "--interactive",
+ "--verbose",
+ "--exit",
+ "--open-tty",
+ "--show-limits",
+ }:
cursor += 1
else:
return target >= cursor
@@ -1988,9 +2000,12 @@ def _rm_symlink_call_seen(executable: str, source: str) -> bool:
if call.func.attr not in {"run", "call", "check_call", "check_output", "Popen"} or not call.args:
continue
argv = call.args[0]
- if isinstance(argv, (ast.List, ast.Tuple)) and argv.elts and all(
- isinstance(arg, ast.Constant) and isinstance(arg.value, str) for arg in argv.elts
- ) and _rm_symbolic_link_command([arg.value for arg in argv.elts], 0):
+ if (
+ isinstance(argv, (ast.List, ast.Tuple))
+ and argv.elts
+ and all(isinstance(arg, ast.Constant) and isinstance(arg.value, str) for arg in argv.elts)
+ and _rm_symbolic_link_command([arg.value for arg in argv.elts], 0)
+ ):
return True
return False
strings = r"'(?:\\.|[^'\\])*'|\"(?:\\.|[^\"\\])*\""
@@ -2012,7 +2027,7 @@ def _rm_symlink_fallback(command_text: str) -> bool:
start = 0
index = 0
while index <= len(shell):
- char = shell[index:index + 1]
+ char = shell[index : index + 1]
if char == "\\" and quote != "'":
index += 2
continue
@@ -2028,7 +2043,11 @@ def _rm_symlink_fallback(command_text: str) -> bool:
parsed = _rm_shell_tokens(shell[start:index])
if parsed and parsed[0]:
command = _rm_wrapped_command_index(parsed[0], 0)
- if command is not None and command < len(parsed[0]) and _rm_symbolic_link_command(parsed[0], command):
+ if (
+ command is not None
+ and command < len(parsed[0])
+ and _rm_symbolic_link_command(parsed[0], command)
+ ):
return True
start = index + 1
index += 1
@@ -2089,11 +2108,7 @@ def _rm_symlink_creation_seen(command_text: str, _depth: int = 0) -> bool:
def _rm_tmp_operand_is_exempt(operand: str, *, symlink_seen: bool) -> bool:
"""Preserve lexical /tmp cleanup unless the trace gives link evidence."""
- if (
- not operand.startswith("/")
- or operand.startswith("//")
- or any(char in operand for char in "$`{")
- ):
+ if not operand.startswith("/") or operand.startswith("//") or any(char in operand for char in "$`{"):
return False
if not symlink_seen:
if any(char in operand for char in "*?[") and ".." in operand.split("/"):
@@ -2124,11 +2139,13 @@ def _rm_xargs_fallback(command_text: str) -> bool:
"""Retain detection on parser/budget failures with bounded linear work."""
candidate = command_text.replace("\\\r\n", "").replace("\\\n", "")
candidate = candidate.translate({ord("'"): None, ord('"'): None, ord("\\"): None})
- return bool(re.search(
- r"\bxargs\b[^\n;&|]{0,512}\brm\s+(?:--(?:recursive|force)\b|-\S*[rRf])",
- candidate,
- re.IGNORECASE,
- ))
+ return bool(
+ re.search(
+ r"\bxargs\b[^\n;&|]{0,512}\brm\s+(?:--(?:recursive|force)\b|-\S*[rRf])",
+ candidate,
+ re.IGNORECASE,
+ )
+ )
def _rm_targets_fallback(command_text: str, _depth: int, *, _symlink_seen: bool = False) -> bool:
@@ -2145,7 +2162,7 @@ def _rm_targets_fallback(command_text: str, _depth: int, *, _symlink_seen: bool
start = max(text.rfind(char, 0, match.start()) for char in "\n;&|") + 1
tail = text[start : start + 65_537]
separator = re.search(r"[\n;&|]", tail)
- fragment = tail[:separator.start()] if separator else tail
+ fragment = tail[: separator.start()] if separator else tail
if len(fragment) > 65_536 or fragment == command_text:
return True
if _rm_targets_outside_tmp(fragment, _depth + 1, _symlink_seen=_symlink_seen):
@@ -2174,7 +2191,7 @@ def _rm_sequential_commands(command_text: str, tokens: list[str]) -> list[str] |
elif char in "'\"":
quote = char
elif char in "(){}|&`":
- if command_text[index:index + 2] not in {"&&", "||"}:
+ if command_text[index : index + 2] not in {"&&", "||"}:
return None
commands.append(command_text[start:index])
index += 2
@@ -2208,8 +2225,14 @@ def _rm_targets_outside_tmp(
if _depth > 3:
return _rm_xargs_fallback(command_text) if _xargs_only else True
if len(command_text) > 65_536:
- return _rm_xargs_fallback(command_text) if _xargs_only else _rm_targets_fallback(
- command_text, _depth, _symlink_seen=_symlink_seen or _rm_symlink_creation_seen(command_text),
+ return (
+ _rm_xargs_fallback(command_text)
+ if _xargs_only
+ else _rm_targets_fallback(
+ command_text,
+ _depth,
+ _symlink_seen=_symlink_seen or _rm_symlink_creation_seen(command_text),
+ )
)
if _xargs_only and "xargs" not in command_text.casefold():
if "\\" not in command_text and "'" not in command_text and '"' not in command_text:
@@ -2220,13 +2243,25 @@ def _rm_targets_outside_tmp(
return False
tokenized = _rm_shell_tokens(command_text)
if tokenized is None:
- return _rm_xargs_fallback(command_text) if _xargs_only else _rm_targets_fallback(
- command_text, _depth, _symlink_seen=_symlink_seen or _rm_symlink_creation_seen(command_text),
+ return (
+ _rm_xargs_fallback(command_text)
+ if _xargs_only
+ else _rm_targets_fallback(
+ command_text,
+ _depth,
+ _symlink_seen=_symlink_seen or _rm_symlink_creation_seen(command_text),
+ )
)
tokens, payloads = tokenized
if len(tokens) > 4096:
- return _rm_xargs_fallback(command_text) if _xargs_only else _rm_targets_fallback(
- command_text, _depth, _symlink_seen=_symlink_seen or _rm_symlink_creation_seen(command_text),
+ return (
+ _rm_xargs_fallback(command_text)
+ if _xargs_only
+ else _rm_targets_fallback(
+ command_text,
+ _depth,
+ _symlink_seen=_symlink_seen or _rm_symlink_creation_seen(command_text),
+ )
)
commands = _rm_sequential_commands(command_text, tokens)
if commands is not None and len(commands) > 1:
@@ -2239,20 +2274,30 @@ def _rm_targets_outside_tmp(
# Within compounds, loops, functions, traps and background work, textual
# order cannot establish execution order. Keep the conservative policy.
command_index = _rm_wrapped_command_index(tokens, 0)
- inline_shell = command_index is not None and command_index < len(tokens) and (
- _shell_executable(tokens[command_index]) in _SHELL_COMMAND_INTERPRETERS
- and _rm_inline_code(_shell_executable(tokens[command_index]), tokens, command_index) is not None
+ inline_shell = (
+ command_index is not None
+ and command_index < len(tokens)
+ and (
+ _shell_executable(tokens[command_index]) in _SHELL_COMMAND_INTERPRETERS
+ and _rm_inline_code(_shell_executable(tokens[command_index]), tokens, command_index) is not None
+ )
)
if commands is None or not inline_shell:
_symlink_seen |= _rm_symlink_creation_seen(command_text)
for payload in payloads:
if re.search(r"\brm\s+-", payload) and _rm_targets_outside_tmp(
- payload, _depth + 1, _xargs_only=_xargs_only, _symlink_seen=_symlink_seen,
+ payload,
+ _depth + 1,
+ _xargs_only=_xargs_only,
+ _symlink_seen=_symlink_seen,
):
return True
for index, token in enumerate(tokens):
if re.search(r"\brm\s+-", token) and _rm_targets_outside_tmp(
- token, _depth + 1, _xargs_only=_xargs_only, _symlink_seen=_symlink_seen,
+ token,
+ _depth + 1,
+ _xargs_only=_xargs_only,
+ _symlink_seen=_symlink_seen,
):
return True
if not re.search(r"\brm$", token):
@@ -2391,9 +2436,14 @@ def check_security(
continue
if (
pattern.search(action_text_lower)
- or (label == "rm -rf" and _rm_targets_outside_tmp(
- action_text, _xargs_only=True, _symlink_seen=symlink_seen,
- ))
+ or (
+ label == "rm -rf"
+ and _rm_targets_outside_tmp(
+ action_text,
+ _xargs_only=True,
+ _symlink_seen=symlink_seen,
+ )
+ )
) and (label != "rm -rf" or _rm_targets_outside_tmp(action_text, _symlink_seen=symlink_seen)):
findings.append(
_security_finding(
diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py
index dd92c03a..4a20bf05 100644
--- a/src/skillevaluator/tier3/harbor/collector.py
+++ b/src/skillevaluator/tier3/harbor/collector.py
@@ -5054,9 +5054,12 @@ def _shared_metric_scorer(
fallback: set[str],
expected_id_set: set[str] | None,
) -> Callable[[dict[str, Any]], float | None]:
- """Score a trial as the mean of the metrics both arms scored for its case."""
+ """Apply the trial's score policy to the metrics both arms can compare."""
def score(reward: dict[str, Any]) -> float | None:
+ own_score = _overall_score(reward)
+ if own_score is None:
+ return None
_, metrics = metric_set_for_reward(reward)
if not metrics:
return own_score
@@ -5070,10 +5073,9 @@ def _shared_metric_scorer(
if reward.get("_logical_attempt_sentinel") is _LOGICAL_ATTEMPT_SENTINEL and reward.get(
"_logical_mixed_contracts"
):
- # A custom-only attempt, or one whose steps mix metric contracts, has only its overall.
- return _overall_score(reward)
- shared = shared_by_case.get(_entry_id(reward, expected_id_set), fallback)
- values: list[float] = []
+ # A mixed-step overall cannot be reconstructed on a smaller basis.
+ return None
+ scores: dict[str, float] = {}
for metric in metrics:
if metric not in shared:
continue
@@ -5118,8 +5120,12 @@ def _shared_metric_pass_lift(
control_scored = _case_scored_metrics(control_rewards, expected_id_set)
paired_cases = set(treatment_scored) & set(control_scored)
shared_by_case = {case: treatment_scored[case] & control_scored[case] for case in paired_cases}
+ judge_mixed = _judge_mixed_cases(treatment_rewards, control_rewards, expected_id_set)
+ for metric, cases in judge_mixed.items():
+ for case in cases & paired_cases:
+ shared_by_case[case].discard(metric)
fallback = set().union(*treatment_scored.values()) & set().union(*control_scored.values())
- one_arm_only = set().union(*(treatment_scored[case] ^ control_scored[case] for case in paired_cases))
+ excluded_metrics = set(judge_mixed).union(*(treatment_scored[case] ^ control_scored[case] for case in paired_cases))
scorer = _shared_metric_scorer(shared_by_case, fallback, expected_id_set)
summaries = [
_pass_summary(
@@ -5142,11 +5148,12 @@ def _shared_metric_pass_lift(
"passed_cases_delta": int(treatment.get("passed_cases", 0)) - int(control.get("passed_cases", 0)),
"paired_comparison": _paired_pass_comparison(treatment, control),
"basis": PASS_LIFT_BASIS_SHARED_METRICS,
- # Metrics only one arm scored (for example the skill metrics of the arm with the skill).
+ # Metrics one arm did not score, or whose judge models differed on some cases.
"excluded_metrics": [
- *(metric for metric in DISPLAY_METRICS if metric in one_arm_only),
- *sorted(one_arm_only - set(DISPLAY_METRICS)),
+ *(metric for metric in DISPLAY_METRICS if metric in excluded_metrics),
+ *sorted(excluded_metrics - set(DISPLAY_METRICS)),
],
+ **({"judge_mixed_cases": {metric: len(cases) for metric, cases in judge_mixed.items()}} if judge_mixed else {}),
"with_skill_passed_cases": int(treatment.get("passed_cases", 0)),
"without_skill_passed_cases": int(control.get("passed_cases", 0)),
"total_cases": int(treatment.get("total_cases", 0)),
diff --git a/src/skillevaluator/tier3/harbor/runner.py b/src/skillevaluator/tier3/harbor/runner.py
index 2058d297..9c22831e 100644
--- a/src/skillevaluator/tier3/harbor/runner.py
+++ b/src/skillevaluator/tier3/harbor/runner.py
@@ -1213,9 +1213,7 @@ def _backend_may_forward(name: str) -> bool:
upper = name.upper()
if upper in _HARBOR_BASE_ENV_VARS or upper in _BACKEND_ALLOWED_SHARED_HOST_ENV:
return True
- other_backend_secret = any(
- upper in names and is_sensitive_key(upper) for names in _HARBOR_ENV_MODE_VARS.values()
- )
+ other_backend_secret = any(upper in names and is_sensitive_key(upper) for names in _HARBOR_ENV_MODE_VARS.values())
return not (
upper in _OPERATOR_OWNED_AGENT_ENV
or upper in _RUNTIME_ENV_HOST_CONTROL_NAMES
@@ -1868,9 +1866,9 @@ def build_harbor_run_command(
command.extend(["--override-storage-mb", str(override_storage_mb)])
for name, value in sorted((verifier_env or {}).items()):
str_val = str(value)
- if (is_operator_owned_or_provider_secret(name) or _is_sensitive_environment_kwarg_name(name)) and not re.fullmatch(
- r"\$\{[A-Za-z_][A-Za-z0-9_]*\}", str_val
- ):
+ if (
+ is_operator_owned_or_provider_secret(name) or _is_sensitive_environment_kwarg_name(name)
+ ) and not re.fullmatch(r"\$\{[A-Za-z_][A-Za-z0-9_]*\}", str_val):
raise ValueError(
f"Sensitive key detected in verifier_env: {name}. "
"Credentials and operator-owned settings must use ${VAR} placeholder indirection."
@@ -3372,7 +3370,9 @@ def _agent_import_path(provider: ProviderConfig, agent: str, env_mode: str) -> s
try:
compatible = issubclass(import_symbol(selected), import_symbol(required))
except (ImportError, TypeError, ValueError) as exc:
- raise ValueError(f"Custom execution backend '{env_mode}' agent wrapper {selected} could not be checked: {exc}") from None
+ raise ValueError(
+ f"Custom execution backend '{env_mode}' agent wrapper {selected} could not be checked: {exc}"
+ ) from None
if not compatible:
raise ValueError(
f"Custom execution backend '{env_mode}' runs {agent} with {selected}, but the {provider.provider} "
@@ -4916,9 +4916,8 @@ def _run_harbor_eval_impl(
disposition = credential_probe_disposition(selected_provider, probe, env_mode=env_mode)
if probe.ok and disposition == CredentialProbeDisposition.DEGRADED:
safe_detail = "model catalog access does not verify runtime credentials for this endpoint"
- elif (
- disposition == CredentialProbeDisposition.DEGRADED
- and is_unverified_gke_vertex_auth_probe(selected_provider, probe, env_mode=env_mode)
+ elif disposition == CredentialProbeDisposition.DEGRADED and is_unverified_gke_vertex_auth_probe(
+ selected_provider, probe, env_mode=env_mode
):
safe_detail = GKE_HOST_UNVERIFIED_VERTEX_AUTH_DETAIL
credential_validation_targets.append(
diff --git a/tests/ci/test_publish_reports.py b/tests/ci/test_publish_reports.py
index a1771f84..4fe5df54 100644
--- a/tests/ci/test_publish_reports.py
+++ b/tests/ci/test_publish_reports.py
@@ -119,6 +119,28 @@ def test_only_json_is_loaded_and_html_is_ignored():
assert list(reports) == ["skill-001"]
+def test_incomplete_scanner_cannot_invent_a_confirmed_failure():
+ from skillevaluator.models import ValidationResult
+ from skillevaluator.reporting.json_reporter import JSONReporter
+
+ result = ValidationResult(validator_name="Security", metadata={"incomplete_scans": ["semgrep"]})
+ result.add_error("Scanner execution did not complete")
+ data = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
+ data["results"][0]["status"] = "failed"
+ data["overall_status"] = "failed"
+ row = {
+ **summary()["skills"][0],
+ "overall_status": "failed",
+ "passed": False,
+ "exit_code": 1,
+ "incomplete_scans": ["semgrep"],
+ "total_errors": data["total_errors"],
+ "severity_counts": data["severity_counts"],
+ }
+ with pytest.raises(publisher.PublicationError):
+ publisher.validate_report(data, row)
+
+
@pytest.mark.parametrize(
"name", ["../summary.json", "/summary.json", "a/../../summary.json", "C:\\summary.json", "a\\summary.json"]
)
diff --git a/tests/ci/test_release_image.py b/tests/ci/test_release_image.py
index 5cc6933d..2664d988 100644
--- a/tests/ci/test_release_image.py
+++ b/tests/ci/test_release_image.py
@@ -88,6 +88,7 @@ def test_release_shell_never_pushes_an_existing_or_unverified_tag(tmp_path, scen
docker.write_text(
"#!/bin/sh\n"
'printf "%s\\n" "$*" >> "$COMMAND_LOG"\n'
+ 'if [ "$1" = login ]; then cat >/dev/null; fi\n'
'if [ "$1" = inspect ]; then\n'
' if [ "$SCENARIO" = wrong-revision ]; then printf "bad-revision\\n"; else printf "%s\\n" "$GITHUB_SHA"; fi\n'
"fi\n"
diff --git a/tests/ci/test_run_tier1.py b/tests/ci/test_run_tier1.py
index 093e4c93..432afdb3 100644
--- a/tests/ci/test_run_tier1.py
+++ b/tests/ci/test_run_tier1.py
@@ -71,6 +71,8 @@ def payload(passed=True, status="passed", incomplete=None, findings=1):
)
if status == "incomplete":
results[0].metadata["incomplete_scans"] = incomplete or ["semgrep"]
+ if not passed and not findings:
+ results[0].add_error("Scanner execution did not complete")
return json.loads(JSONReporter(include_timestamp=False).render_all(results))
@@ -488,7 +490,7 @@ def test_incomplete_runtime_rollup_is_not_mislabeled_as_inconsistent_evidence(tm
workspace,
reports,
{"SKILL_PATHS": "skills"},
- execute=fake_cli([(1, payload(False, "incomplete", ["semgrep"]))], []),
+ execute=fake_cli([(1, payload(False, "incomplete", ["semgrep"], findings=0))], []),
)
== 1
)
@@ -501,6 +503,51 @@ def test_incomplete_runtime_rollup_is_not_mislabeled_as_inconsistent_evidence(tm
assert "Report evidence is missing or inconsistent" not in compact
+def test_confirmed_failure_and_incomplete_scanner_survive_retained_publication(tmp_path):
+ import ci.publish_reports as publisher
+
+ from skillevaluator.reporting.retained import retained_results
+
+ workspace = tmp_path / "workspace"
+ skill(workspace, "skills/a")
+ report = payload(False, "incomplete", ["semgrep"])
+ assert report["overall_status"] == "failed"
+ assert report["results"][0]["status"] == "failed"
+ assert retained_results(report)[0].is_incomplete
+ reports = tmp_path / "reports"
+ assert runner.run(workspace, reports, {"SKILL_PATHS": "skills"}, execute=fake_cli([(1, report)], [])) == 1
+ summary = json.loads((reports / "summary.json").read_text())
+ row = summary["skills"][0]
+ assert row["overall_status"] == "failed"
+ assert row["incomplete_scans"] == ["semgrep"]
+ assert row.get("error") is None
+ assert (summary["failed"], summary["incomplete"]) == (1, 0)
+ publisher.validate_summary(summary)
+ artifact = io.BytesIO()
+ with zipfile.ZipFile(artifact, "w") as archive:
+ archive.write(reports / "summary.json", "summary.json")
+ archive.write(reports / "skill-001/skillevaluator-tier1.json", "skill-001/skillevaluator-tier1.json")
+ retained, children = publisher.read_artifact(artifact.getvalue())
+ assert retained["skills"][0]["overall_status"] == "failed"
+ assert children["skill-001"]["results"][0]["incomplete_scans"] == ["semgrep"]
+
+
+def test_confirmed_skill_failure_precedes_another_skills_incomplete_scan(tmp_path):
+ import ci.publish_reports as publisher
+
+ workspace = tmp_path / "workspace"
+ skill(workspace, "skills/a")
+ skill(workspace, "skills/b")
+ reports = tmp_path / "reports"
+ responses = [(1, payload(False)), (1, payload(False, "incomplete", ["semgrep"], findings=0))]
+ assert runner.run(workspace, reports, {"SKILL_PATHS": "skills"}, execute=fake_cli(responses, [])) == 1
+ summary = json.loads((reports / "summary.json").read_text())
+ assert summary["overall_status"] == "failed"
+ assert [row["overall_status"] for row in summary["skills"]] == ["failed", "incomplete"]
+ assert (summary["failed"], summary["incomplete"]) == (2, 1)
+ publisher.validate_summary(summary)
+
+
def repository_git(workspace, *arguments):
return subprocess.check_output(
["git", "-C", str(workspace), "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgSign=false", *arguments],
diff --git a/tests/reporting/test_applicability_saved_runs.py b/tests/reporting/test_applicability_saved_runs.py
index 4c043c03..e2e56b86 100644
--- a/tests/reporting/test_applicability_saved_runs.py
+++ b/tests/reporting/test_applicability_saved_runs.py
@@ -6,6 +6,8 @@ from __future__ import annotations
import json
+import pytest
+
from skillevaluator.evaluation.tier3_report import build_agent_eval_payload
from skillevaluator.tier3.harbor.metrics import (
DEFAULT_METRIC_SET,
@@ -100,6 +102,54 @@ def test_saved_run_retains_validated_na_and_recomputes_tampered_basis(tmp_path):
assert agent["lift"] == 0.1
+def test_matching_saved_basis_and_metric_lifts_cannot_authorize_a_tampered_overall(tmp_path):
+ from skillevaluator.tier3.harbor.collector import _compute_lift
+
+ root = _run(tmp_path)
+ loaded = load_agent_data(root)["codex"]
+ assert loaded["rewards_complete"] is loaded["rewards_baseline_complete"] is True
+ cached = _compute_lift(
+ loaded["with_skill"],
+ loaded["without_skill"],
+ loaded["rewards"],
+ loaded["rewards_baseline"],
+ score_policy=DEFAULT_SCORE_POLICY,
+ )
+ assert cached["overall"]["delta"] == 0.1
+ # The basis and every per-metric value remain exactly as rebuilt from the
+ # complete rewards. Only the cached headline delta has been changed.
+ cached["overall"]["delta"] = 0.99
+ (root / "codex/lift.json").write_text(json.dumps(cached))
+ assert _report(root)["agents"]["codex"]["lift"] == 0.1
+
+
+ "unavailable",
+ [
+ {"comparison_unavailable": True},
+ {"comparison_complete": False},
+ {"lift": {"comparison_unavailable": True}},
+ ],
+)
+def test_explicit_unavailable_comparison_suppresses_aggregate_overall_lift(unavailable):
+ from skillevaluator.evaluation.tier3_report import _build_agent
+
+ agent = _build_agent(
+ "codex",
+ {
+ "execution_status": "succeeded",
+ "with_skill": dict.fromkeys(DEFAULT_METRICS, 0.8),
+ "without_skill": dict.fromkeys(DEFAULT_METRICS, 0.6),
+ **unavailable,
+ },
+ list(DEFAULT_METRICS),
+ list(DEFAULT_METRICS),
+ None,
+ DEFAULT_SCORE_POLICY,
+ )
+ assert agent["lift"] is None
+
+
def test_numeric_contradictions_override_tampered_aggregate_na_markers(tmp_path):
root = _run(tmp_path)
path = root / "codex/with-skill/summary.json"
@@ -123,6 +173,77 @@ def test_new_basis_comparison_is_unavailable_when_rewards_are_incomplete(tmp_pat
assert not agent.get("lift_basis")
+def test_incomplete_saved_full_metric_basis_cannot_fall_back_to_aggregate_scores(tmp_path):
+ root = _run(tmp_path)
+ for condition in ("with-skill", "without-skill"):
+ directory = root / "codex" / condition
+ scores = dict.fromkeys(DEFAULT_METRICS, 1.0)
+ summary = json.loads((directory / "summary.json").read_text())
+ summary.update(scores=scores, not_applicable_metrics=[], dimensions=dimension_scores(scores))
+ (directory / "summary.json").write_text(json.dumps(summary))
+ for path in (directory / "trials").glob("*/reward.json"):
+ row = json.loads(path.read_text())
+ row.update(scores, details={})
+ path.write_text(json.dumps(row))
+ (root / "codex/lift.json").write_text(
+ json.dumps(
+ {
+ "overall": {"delta": 0.99},
+ "basis": {
+ "excluded_case_entries": 0,
+ "excluded_cases": [],
+ "excluded_metrics": [],
+ "excluded_cases_truncated": False,
+ },
+ }
+ )
+ )
+ (root / "codex/with-skill/trials/b/reward.json").unlink()
+ assert _report(root)["agents"]["codex"]["lift"] is None
+
+
+def test_complete_mixed_saved_run_rebuilds_logical_lift_and_rejects_different_case_cohorts(tmp_path):
+ from skillevaluator.tier3.harbor.metrics import CUSTOM_ONLY_METRIC_SET
+
+ for condition, standard_score in (("with-skill", 1.0), ("without-skill", 0.6)):
+ directory = tmp_path / "codex" / condition
+ directory.mkdir(parents=True)
+ scores = dict.fromkeys(DEFAULT_METRICS, standard_score)
+ summary = {
+ "scores": scores,
+ "metrics": list(DEFAULT_METRICS),
+ "score_policy": DEFAULT_SCORE_POLICY,
+ "num_trials": 2,
+ "num_reward_rows": 2,
+ "mixed_metric_contracts": True,
+ "execution_status": "succeeded",
+ "overall_score": standard_score / 2,
+ }
+ (directory / "summary.json").write_text(json.dumps(summary))
+ rows = [
+ {**scores, "entry_id": "a", "trial_id": "a", "metric_set": DEFAULT_METRIC_SET},
+ {"entry_id": "b", "trial_id": "b", "metric_set": CUSTOM_ONLY_METRIC_SET, "overall": 0.0},
+ ]
+ for row in rows:
+ trial = directory / "trials" / row["entry_id"]
+ trial.mkdir(parents=True)
+ (trial / "reward.json").write_text(json.dumps(row))
+ (tmp_path / "codex/lift.json").write_text(
+ json.dumps(
+ {
+ "overall": {"delta": 0.99},
+ "basis": {"pairing": "same_cases_per_metric"},
+ }
+ )
+ )
+ assert _report(tmp_path)["agents"]["codex"]["lift"] == 0.2
+ path = tmp_path / "codex/without-skill/trials/b/reward.json"
+ row = json.loads(path.read_text())
+ row["entry_id"] = "different-case"
+ path.write_text(json.dumps(row))
+ assert _report(tmp_path)["agents"]["codex"]["lift"] is None
+
+
def test_default_dimensions_require_every_applicable_metric_even_with_cached_scores():
from skillevaluator.evaluation.tier3_report import _build_agent
diff --git a/tests/reporting/test_retained_html.py b/tests/reporting/test_retained_html.py
index 5d593583..fcea487f 100644
--- a/tests/reporting/test_retained_html.py
+++ b/tests/reporting/test_retained_html.py
@@ -77,10 +77,10 @@ def test_render_explicit_identity_never_inspects_artifact_paths(payload):
assert "name_consistency" in rendered
-def test_incomplete_remains_incomplete(payload):
- payload["results"][0]["incomplete_scans"] = ["semgrep"]
- payload["results"][0]["status"] = "incomplete"
- payload["overall_status"] = "incomplete"
+def test_incomplete_remains_incomplete():
+ result = ValidationResult(validator_name="Security", metadata={"incomplete_scans": ["semgrep"]})
+ result.add_error("Scanner execution did not complete")
+ payload = json.loads(JSONReporter(include_timestamp=False).render_all([result]))
rows = retained_results(payload)
assert rows[0].is_incomplete
assert not json.loads(JSONReporter(include_timestamp=False).render_all(rows))["overall_passed"]
diff --git a/tests/tier3/test_judge_failure_artifacts.py b/tests/tier3/test_judge_failure_artifacts.py
index d0939f5e..c4206a61 100644
--- a/tests/tier3/test_judge_failure_artifacts.py
+++ b/tests/tier3/test_judge_failure_artifacts.py
@@ -158,7 +158,13 @@ def test_character_facts_keep_numeric_dataset_answers_scoreable(tmp_path, monkey
assert "evaluation_errors" not in rich
assert numeric == original_reward
assert numeric["accuracy"] == numeric["goal_accuracy"] == 0.0
- assert overall_score(numeric) is not None
+ assert overall_score(rich) == numeric["overall"]
+ # Numeric transport omits N/A metrics; only the rich sidecar establishes
+ # their applicability. A numeric reward alone must remain unscoreable.
+ assert overall_score(numeric) is None
+ collected = dict(numeric)
+ collector._merge_reward_sidecars(collected, verifier.VERIFIER_DIR)
+ assert overall_score(collected) == numeric["overall"]
def test_verifier_main_fails_closed_after_collecting_every_required_judge(