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.

fix(tier3): preserve trusted negative-control evidence

Christopher Kevin1cd1c07cc477
diff --git a/src/skillevaluator/evaluation/insights_judge.py b/src/skillevaluator/evaluation/insights_judge.py
index a29ec17f..63e96218 100644
--- a/src/skillevaluator/evaluation/insights_judge.py
+++ b/src/skillevaluator/evaluation/insights_judge.py
@@ -17,6 +17,7 @@ deterministic conclusions and recommendations from
from __future__ import annotations
import json
+import math
import re
from typing import Any
@@ -50,6 +51,18 @@ _VALID_CLAIM_TYPES = {
"negative_control_failure",
"dataset_case_removal",
}
+_MAX_GROUNDED_CLAIM_TEXT_CHARS = 2_000
+_NEGATIVE_CONTROL_SEMANTIC_PATTERNS = (
+ re.compile(r"\bnegative[\s-]*control\b", re.IGNORECASE),
+ re.compile(r"\b(?:scope[\s-]*(?:drift|misalignment)|capability[\s-]*overreach)\b", re.IGNORECASE),
+ re.compile(r"\b(?:unintended|unnecessary|unnecessarily)\b.{0,48}\b(?:skill|capability)\b", re.IGNORECASE),
+ re.compile(
+ r"\b(?:skill|capability)\b.{0,48}\b(?:over[\s-]*(?:applied|used)|overreach|overfitting)\b", re.IGNORECASE
+ ),
+ re.compile(
+ r"\b(?:unrelated|out[\s-]*of[\s-]*scope)\b.{0,48}\b(?:work|task|request|skill|capability)\b", re.IGNORECASE
+ ),
+)
_SYSTEM_PROMPT = """\
@@ -87,18 +100,21 @@ NEGATIVE-CONTROL INTERPRETATION:
when invocation evidence is absent or ambiguous, do not issue the warning.
- Do not recommend removing an unrelated negative-control case merely because
it is outside the skill's scope; that is what the case is designed to test.
-- Every conclusion and recommendation MUST include a claim_type and an
- evidence_case_ids list. Use claim_type "general" only for observations that
- do not concern negative-control routing or removal of a dataset case. Use
+- Every conclusion and recommendation MUST include a claim_type and a
+ non-empty evidence_case_ids list containing 1-10 unique known case ids. The
+ title and message together must name every evidence case id and no other case
+ id. General claims may cite only skill-activation cases. Use claim_type
+ "general" only for observations that do not concern negative-control routing
+ or removal of a dataset case. Use
claim_type "negative_control_failure" for unintended skill use, scope
misalignment, or overfitting involving a negative control. Use claim_type
"dataset_case_removal" for any recommendation to remove a case from the
dataset.
-- A negative_control_failure or dataset_case_removal claim MUST identify every
- affected case in evidence_case_ids. Negative-control claims are valid only
- when the supplied context shows failed routing or explicit invocation
- evidence for at least one identified negative-control case. Do not label a
- negative-control claim as general.
+- A negative_control_failure claim MUST identify every affected case in
+ evidence_case_ids and is valid only when the supplied context shows failed
+ routing or explicit invocation evidence for every identified negative-control
+ case. A dataset_case_removal claim must not cite a negative control. Do not
+ label a negative-control claim as general.
Your job is to produce ADDITIONAL, contextual insights:
@@ -223,7 +239,25 @@ def _summarize_trials(trials: list[dict], cases_by_id: dict[str, dict] | None =
indexed_trials = [(index, trial) for index, trial in enumerate(trials) if isinstance(trial, dict)]
sorted_trials = sorted(indexed_trials, key=_key)
- chosen = sorted_trials[:3] + sorted_trials[-3:]
+
+ def _has_trusted_negative_failure(indexed_trial: tuple[int, dict]) -> bool:
+ _index, trial = indexed_trial
+ entry_id = trial.get("entry_id")
+ case = cases_by_id.get(str(entry_id)) if entry_id is not None else None
+ if not isinstance(case, dict) or _case_routing(case)[1] is not False:
+ return False
+ if trial.get("invocation_evidence_source") != "trajectory":
+ return False
+ skill_invoked = trial.get("skill_invoked") if type(trial.get("skill_invoked")) is bool else None
+ routing_passed = trial.get("routing_passed") if type(trial.get("routing_passed")) is bool else None
+ if skill_invoked is not None and routing_passed is not None:
+ return routing_passed is (not skill_invoked) and skill_invoked
+ if skill_invoked is not None:
+ return skill_invoked
+ return routing_passed is False
+
+ priority = [trial for trial in indexed_trials if _has_trusted_negative_failure(trial)]
+ chosen = priority + sorted_trials[:3] + sorted_trials[-3:]
attempt_counts: dict[tuple[str, str], int] = {}
attempts_by_index: dict[int, int | str] = {}
@@ -241,21 +275,26 @@ def _summarize_trials(trials: list[dict], cases_by_id: dict[str, dict] | None =
scores = trial.get("scores") or {}
entry_id = trial.get("entry_id")
case = cases_by_id.get(str(entry_id)) if entry_id is not None else None
- compact.append(
- {
- "agent": trial.get("agent"),
- "trial_id": trial.get("trial_id"),
- "entry_id": entry_id,
- "attempt": attempts_by_index[index],
- "overall": trial.get("overall"),
- "scores": {k: v for k, v in scores.items() if v is not None},
- "baseline_overall": trial.get("baseline_overall"),
- "lift_scores": trial.get("lift_scores") or {},
- "warnings": (trial.get("warnings") or [])[:3],
- "error_recovery": trial.get("error_recovery") or {},
- "case": _summarize_case(case) if case is not None else None,
- }
- )
+ entry = {
+ "agent": trial.get("agent"),
+ "trial_id": trial.get("trial_id"),
+ "entry_id": entry_id,
+ "attempt": attempts_by_index[index],
+ "overall": trial.get("overall"),
+ "scores": {k: v for k, v in scores.items() if v is not None},
+ "baseline_overall": trial.get("baseline_overall"),
+ "lift_scores": trial.get("lift_scores") or {},
+ "warnings": (trial.get("warnings") or [])[:3],
+ "error_recovery": trial.get("error_recovery") or {},
+ "case": _summarize_case(case) if case is not None else None,
+ }
+ if trial.get("invocation_evidence_source") == "trajectory":
+ for key in ("skill_invoked", "routing_passed"):
+ if type(trial.get(key)) is bool:
+ entry[key] = trial[key]
+ if "skill_invoked" in entry or "routing_passed" in entry:
+ entry["invocation_evidence_source"] = "trajectory"
+ compact.append(entry)
if len(compact) >= 6:
break
return compact
@@ -298,86 +337,141 @@ def _coerce_category(value: Any) -> str:
return "Action"
-def _negative_control_grounding(canonical: dict) -> tuple[dict[str, bool], set[str]]:
- """Return negative cases mapped to whether invocation/routing failure exists."""
- known_case_ids: set[str] = set()
- evidence: dict[str, bool] = {}
+def _strict_bool(value: Any) -> bool | None:
+ return value if type(value) is bool else None
+
+
+def _finite_numeric(value: Any) -> float | None:
+ if not isinstance(value, int | float) or isinstance(value, bool):
+ return None
+ try:
+ numeric = float(value)
+ except OverflowError:
+ return None
+ return numeric if math.isfinite(numeric) else None
+
+
+def _trial_negative_control_failure(trial: dict) -> bool | None:
+ """Interpret one trial, preferring strict invocation evidence over legacy scores."""
+ if trial.get("invocation_evidence_source") == "trajectory":
+ skill_invoked = _strict_bool(trial.get("skill_invoked"))
+ routing_passed = _strict_bool(trial.get("routing_passed"))
+ if skill_invoked is not None and routing_passed is not None:
+ if routing_passed is not (not skill_invoked):
+ return None
+ return skill_invoked
+ if skill_invoked is not None:
+ return skill_invoked
+ if routing_passed is not None:
+ return not routing_passed
+
+ scores = trial.get("scores") if isinstance(trial.get("scores"), dict) else {}
+ numeric_scores = [
+ numeric
+ for value in (
+ scores.get("skill_execution"),
+ scores.get("skill_routing"),
+ trial.get("skill_execution"),
+ trial.get("skill_routing"),
+ )
+ if (numeric := _finite_numeric(value)) is not None
+ ]
+ if not numeric_scores:
+ return None
+ return any(score < 1.0 for score in numeric_scores)
+
+
+def _negative_control_grounding(canonical: dict) -> tuple[dict[str, bool | None], dict[str, str]]:
+ """Return per-case routing type and grounded negative-control failure state."""
+ case_types: dict[str, str] = {}
+ trial_states: dict[str, list[bool | None]] = {}
for case in canonical.get("dataset") or []:
if not isinstance(case, dict) or case.get("id") is None:
continue
case_id = str(case["id"])
- known_case_ids.add(case_id)
- _case_type, should_trigger = _case_routing(case)
+ case_type, should_trigger = _case_routing(case)
+ case_types[case_id] = case_type
if should_trigger is False:
- evidence[case_id] = False
+ trial_states[case_id] = []
for trial in canonical.get("trials") or []:
if not isinstance(trial, dict) or trial.get("entry_id") is None:
continue
case_id = str(trial["entry_id"])
- if case_id not in evidence:
+ if case_id not in trial_states:
continue
- scores = trial.get("scores") if isinstance(trial.get("scores"), dict) else {}
- routing_scores = [
- scores.get("skill_execution"),
- scores.get("skill_routing"),
- trial.get("skill_execution"),
- trial.get("skill_routing"),
- ]
- failed_routing = any(
- isinstance(score, int | float) and not isinstance(score, bool) and score < 1.0
- for score in routing_scores
- )
- explicit_invocation = trial.get("skill_invoked") is True or trial.get("routing_passed") is False
- if failed_routing or explicit_invocation:
+ trial_states[case_id].append(_trial_negative_control_failure(trial))
+
+ evidence: dict[str, bool | None] = {}
+ for case_id, states in trial_states.items():
+ if any(state is True for state in states):
evidence[case_id] = True
- return evidence, known_case_ids
+ elif not states or any(state is None for state in states):
+ evidence[case_id] = None
+ else:
+ evidence[case_id] = False
+ return evidence, case_types
-def _declared_case_ids(item: dict) -> set[str] | None:
+def _declared_case_ids(item: dict) -> list[str] | None:
raw_references = item.get("evidence_case_ids")
- if not isinstance(raw_references, list) or len(raw_references) > 10:
+ if not isinstance(raw_references, list) or not 1 <= len(raw_references) <= 10:
return None
if any(not isinstance(value, str) or not value.strip() for value in raw_references):
return None
- return {value.strip() for value in raw_references}
+ references = [value.strip() for value in raw_references]
+ return references if len(references) == len(set(references)) else None
-def _text_case_ids(item: dict, known_case_ids: set[str]) -> set[str]:
+def _claim_text(item: dict) -> str | None:
+ text = f"{item.get('title') or ''} {item.get('message') or ''}"
+ return text if len(text) <= _MAX_GROUNDED_CLAIM_TEXT_CHARS else None
+
+
+def _text_case_ids(text: str, known_case_ids: set[str]) -> set[str]:
references: set[str] = set()
- text = f"{item.get('title') or ''} {item.get('message') or ''}"[:2_000]
for case_id in known_case_ids:
if re.search(rf"(?<![\w-]){re.escape(case_id)}(?![\w-])", text, re.IGNORECASE):
references.add(case_id)
return references
+def _has_negative_control_semantics(text: str) -> bool:
+ return any(pattern.search(text) for pattern in _NEGATIVE_CONTROL_SEMANTIC_PATTERNS)
+
+
def _claim_is_grounded(
item: dict,
- grounding: tuple[dict[str, bool], set[str]],
+ grounding: tuple[dict[str, bool | None], dict[str, str]],
) -> bool:
- evidence, known_case_ids = grounding
+ evidence, case_types = grounding
claim_type = item.get("claim_type")
if claim_type not in _VALID_CLAIM_TYPES:
return False
declared_case_ids = _declared_case_ids(item)
- if declared_case_ids is None or not declared_case_ids.issubset(known_case_ids):
+ if declared_case_ids is None:
+ return False
+ declared_set = set(declared_case_ids)
+ known_case_ids = set(case_types)
+ if not declared_set.issubset(known_case_ids):
return False
- if not _text_case_ids(item, known_case_ids).issubset(declared_case_ids):
+ claim_text = _claim_text(item)
+ if claim_text is None or _text_case_ids(claim_text, known_case_ids) != declared_set:
return False
- negative_case_ids = declared_case_ids.intersection(evidence)
+ declared_types = [case_types[case_id] for case_id in declared_case_ids]
if claim_type == "general":
- return not negative_case_ids
-
- if not declared_case_ids:
- return False
- if claim_type == "negative_control_failure" and declared_case_ids != negative_case_ids:
- return False
+ return not _has_negative_control_semantics(claim_text) and all(
+ case_type == "skill_activation" for case_type in declared_types
+ )
+ if claim_type == "dataset_case_removal":
+ return all(case_type != "negative_control" for case_type in declared_types)
- return not negative_case_ids or any(evidence[case_id] for case_id in negative_case_ids)
+ return all(case_type == "negative_control" for case_type in declared_types) and all(
+ evidence.get(case_id) is True for case_id in declared_case_ids
+ )
class InsightsJudge(LLMClient):
@@ -452,10 +546,12 @@ class InsightsJudge(LLMClient):
continue
conclusions.append(
{
+ "claim_type": item["claim_type"],
"title": title or "Insight",
"message": message or title,
"severity": _coerce_severity(item.get("severity")),
"source": "llm",
+ "evidence_case_ids": _declared_case_ids(item),
}
)
@@ -471,11 +567,13 @@ class InsightsJudge(LLMClient):
continue
recommendations.append(
{
+ "claim_type": item["claim_type"],
"title": title or message[:60],
"message": message or title,
"category": _coerce_category(item.get("category")),
"severity": _coerce_severity(item.get("severity")),
"source": "llm",
+ "evidence_case_ids": _declared_case_ids(item),
}
)
diff --git a/src/skillevaluator/evaluation/tier3_report.py b/src/skillevaluator/evaluation/tier3_report.py
index 1a880c2a..27dee2ef 100644
--- a/src/skillevaluator/evaluation/tier3_report.py
+++ b/src/skillevaluator/evaluation/tier3_report.py
@@ -749,6 +749,10 @@ def build_agent_eval_payload(
use_llm_judge=use_llm_judge and overall_score is not None,
)
if evidence_links:
+ payload["conclusions"] = _attach_harbor_evidence_to_conclusions(
+ payload.get("conclusions") or [],
+ evidence_links,
+ )
payload["recommendations"] = _attach_harbor_evidence_to_recommendations(
payload.get("recommendations") or [],
evidence_links,
@@ -1699,11 +1703,30 @@ def _normalize_trials(rewards: list[dict[str, Any]], metrics: list[str]) -> list
``_normalize_harbor_trials`` so the ported Trials tab (per-evaluator
drill-down, token/steps charts, warnings) renders identically.
"""
+ # Import lazily: ``skillevaluator.tier3`` imports report construction through
+ # its command module, so importing Harbor metrics at module load time creates
+ # a collector-first circular import.
+ from skillevaluator.tier3.harbor.metrics import (
+ DEFAULT_METRIC_SET,
+ LEGACY_METRIC_SET,
+ metric_set_for_reward,
+ metric_value,
+ )
+
out: list[dict[str, Any]] = []
for reward in rewards:
if not isinstance(reward, dict):
continue
- scores = {m: numeric for m in metrics if (numeric := _finite_float(reward.get(m))) is not None}
+ declared_metric_set = reward.get("metric_set") or reward.get("metric_set_version")
+ standard_metric_sets = {DEFAULT_METRIC_SET, LEGACY_METRIC_SET}
+ metric_set, standard_metrics = metric_set_for_reward(reward)
+ is_declared_custom = bool(declared_metric_set) and str(declared_metric_set) not in standard_metric_sets
+ scores = {
+ m: numeric
+ for m in metrics
+ if not (is_declared_custom and m in {"skill_execution", "skill_routing"})
+ if (numeric := _finite_float(reward.get(m))) is not None
+ }
trial: dict[str, Any] = {
"trial_id": reward.get("trial_id"),
"entry_id": reward.get("entry_id"),
@@ -1722,6 +1745,18 @@ def _normalize_trials(rewards: list[dict[str, Any]], metrics: list[str]) -> list
trial["warnings"] = list(reward["warnings"])
if reward.get("error_recovery"):
trial["error_recovery"] = reward["error_recovery"]
+ is_standard_reward = (
+ (not declared_metric_set or str(declared_metric_set) in standard_metric_sets)
+ and metric_set in standard_metric_sets
+ and "skill_execution" in standard_metrics
+ and metric_value(reward, "skill_execution") is not None
+ )
+ if is_standard_reward and reward.get("invocation_evidence_source") == "trajectory":
+ for key in ("skill_invoked", "routing_passed"):
+ if type(reward.get(key)) is bool:
+ trial[key] = reward[key]
+ if "skill_invoked" in trial or "routing_passed" in trial:
+ trial["invocation_evidence_source"] = "trajectory"
harbor_viewer = _normalize_harbor_viewer_metadata(reward.get("harbor_viewer"))
if harbor_viewer:
trial["harbor_viewer"] = harbor_viewer
@@ -2071,9 +2106,37 @@ def _attach_harbor_evidence_to_recommendations(
linked.append(recommendation)
continue
entry = dict(recommendation)
- evidence = entry.get("evidence")
- if not isinstance(evidence, dict) or not _safe_harbor_viewer_url(evidence.get("url")):
- entry["evidence"] = evidence_links[min(index, len(evidence_links) - 1)]
+ evidence = _grounded_or_positional_evidence(entry, entry.get("evidence"), evidence_links, index)
+ if evidence is None:
+ entry.pop("evidence", None)
+ else:
+ entry["evidence"] = evidence
+ linked.append(entry)
+ return linked
+
+
+def _attach_harbor_evidence_to_conclusions(
+ conclusions: list[dict[str, Any]],
+ evidence_links: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ if not conclusions or not evidence_links:
+ return conclusions
+
+ linked: list[dict[str, Any]] = []
+ for conclusion in conclusions:
+ if not isinstance(conclusion, dict):
+ linked.append(conclusion)
+ continue
+ entry = dict(conclusion)
+ case_ids = _evidence_case_ids(entry)
+ if case_ids:
+ evidence = _case_matched_evidence(case_ids, evidence_links)
+ if evidence is None:
+ entry.pop("evidence", None)
+ else:
+ entry["evidence"] = evidence
+ elif not _valid_evidence(entry.get("evidence")):
+ entry.pop("evidence", None)
linked.append(entry)
return linked
@@ -2091,13 +2154,56 @@ def _attach_harbor_evidence_to_suggestions_v2(
linked.append(suggestion)
continue
entry = dict(suggestion)
- evidence = entry.get("harbor_evidence") or entry.get("evidence")
- if not isinstance(evidence, dict) or not _safe_harbor_viewer_url(evidence.get("url")):
- entry["harbor_evidence"] = evidence_links[min(index, len(evidence_links) - 1)]
+ existing = entry.get("harbor_evidence") or entry.get("evidence")
+ evidence = _grounded_or_positional_evidence(entry, existing, evidence_links, index)
+ if evidence is None:
+ entry.pop("harbor_evidence", None)
+ else:
+ entry["harbor_evidence"] = evidence
linked.append(entry)
return linked
+def _valid_evidence(evidence: object) -> bool:
+ return isinstance(evidence, dict) and _safe_harbor_viewer_url(evidence.get("url")) is not None
+
+
+def _evidence_case_ids(item: dict[str, Any]) -> list[str]:
+ case_ids = item.get("evidence_case_ids")
+ if not isinstance(case_ids, list):
+ return []
+ return [case_id.strip() for case_id in case_ids if isinstance(case_id, str) and case_id.strip()]
+
+
+def _case_matched_evidence(
+ case_ids: list[str],
+ evidence_links: list[dict[str, Any]],
+) -> dict[str, Any] | None:
+ for case_id in case_ids:
+ for evidence in evidence_links:
+ if (
+ isinstance(evidence, dict)
+ and str(evidence.get("entry_id") or "") == case_id
+ and _safe_harbor_viewer_url(evidence.get("url"))
+ ):
+ return evidence
+ return None
+
+
+def _grounded_or_positional_evidence(
+ item: dict[str, Any],
+ existing: object,
+ evidence_links: list[dict[str, Any]],
+ index: int,
+) -> dict[str, Any] | None:
+ case_ids = _evidence_case_ids(item)
+ if case_ids:
+ return _case_matched_evidence(case_ids, evidence_links)
+ if _valid_evidence(existing):
+ return existing
+ return evidence_links[min(index, len(evidence_links) - 1)]
+
+
# ---------------------------------------------------------------------------
# Insights (Insights tab): deterministic conclusions + recommendations
# ---------------------------------------------------------------------------
diff --git a/src/skillevaluator/reporting/harbor_viewer.py b/src/skillevaluator/reporting/harbor_viewer.py
index 23a5d8cc..1a7eff03 100644
--- a/src/skillevaluator/reporting/harbor_viewer.py
+++ b/src/skillevaluator/reporting/harbor_viewer.py
@@ -90,6 +90,10 @@ def normalize_agent_eval_harbor_links(agent_eval: dict[str, Any]) -> dict[str, A
normalized.get("recommendations"),
evidence_keys=("evidence",),
)
+ normalized["conclusions"] = _sanitize_items_with_evidence(
+ normalized.get("conclusions"),
+ evidence_keys=("evidence",),
+ )
normalized["suggestions_v2"] = _sanitize_items_with_evidence(
normalized.get("suggestions_v2"),
evidence_keys=("harbor_evidence", "evidence"),
diff --git a/src/skillevaluator/reporting/templates/report.html.j2 b/src/skillevaluator/reporting/templates/report.html.j2
index 3eb38601..010088a2 100644
--- a/src/skillevaluator/reporting/templates/report.html.j2
+++ b/src/skillevaluator/reporting/templates/report.html.j2
@@ -3203,6 +3203,9 @@
<span class="t3-insight-source insight-source-{{ source }}">{{ source }}</span>
</div>
<div class="t3-sug-body">{{ conclusion.message }}</div>
+ {% if conclusion.evidence and conclusion.evidence.url %}
+ <a class="t3-evidence-link" href="{{ conclusion.evidence.url }}" target="_blank" rel="noopener">View {{ conclusion.evidence.label or 'evidence' }}</a>
+ {% endif %}
</div>
<div class="t3-sug-actions">
<button class="t3-copy-btn" onclick='tier3CopyText(this, {{ ((conclusion.title ~ ': ' ~ conclusion.message) | tojson) }})'>Copy</button>
diff --git a/src/skillevaluator/tier3/eval_core/checks.py b/src/skillevaluator/tier3/eval_core/checks.py
index 7f050334..be9c3604 100644
--- a/src/skillevaluator/tier3/eval_core/checks.py
+++ b/src/skillevaluator/tier3/eval_core/checks.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import re
import shlex
+from fnmatch import fnmatchcase
from typing import Any
WASTE_INDICATORS = [
@@ -104,7 +105,7 @@ ACCEPTABLE_ALTERNATE_SCORE = 0.75
# Tool argument field names used across agents for file paths.
# Claude Code uses ``file_path`` for Read/Write, ``path`` for Glob.
# Other agents use ``path`` or ``raw``. ATIF synthetic trajectories use ``raw``.
-_PATH_ARG_KEYS = ("file_path", "path", "raw")
+_PATH_ARG_KEYS = ("file_path", "path", "filename", "target_file", "raw")
def _extract_path(tool_call: dict[str, Any]) -> str:
@@ -147,6 +148,48 @@ def _is_execution_action(action: str) -> bool:
return any(hint in action_lower for hint in _EXECUTION_TOOL_HINTS)
+def _is_file_read_action(action: str) -> bool:
+ action_lower = str(action).strip().casefold()
+ return "read" in action_lower or any(
+ action_lower == name or action_lower.endswith((f"__{name}", f".{name}", f"/{name}", f":{name}"))
+ for name in ("open", "open_file", "grep", "egrep", "fgrep")
+ )
+
+
+def _lexical_path_components(value: Any) -> list[str]:
+ """Normalize separators and dot segments without touching the filesystem."""
+ components: list[str] = []
+ for component in str(value).replace("\\", "/").strip().strip("'\"<>").split("/"):
+ if not component or component == ".":
+ continue
+ if component == "..":
+ if components and components[-1] != "..":
+ components.pop()
+ else:
+ components.append(component)
+ continue
+ components.append(component)
+ return components
+
+
+def _references_exact_target_artifact(value: Any, target_skill: str, *, artifact: str) -> bool:
+ """Return whether one lexical path references an exact target artifact."""
+ target = str(target_skill).strip()
+ if not target or artifact not in {"skill", "scripts"}:
+ return False
+ components = _lexical_path_components(value)
+ target_key = target.casefold()
+ for index, component in enumerate(components[:-1]):
+ if component.casefold() != target_key:
+ continue
+ child = components[index + 1].casefold()
+ if artifact == "skill" and child == "skill.md" and index + 2 == len(components):
+ return True
+ if artifact == "scripts" and child == "scripts":
+ return True
+ return False
+
+
# Shell utilities an agent may use to view a SKILL.md file. Covers agents that
# read via their shell exec tool rather than a native Read tool -- e.g. Codex,
# which reaches a SKILL.md with sed/head as readily as cat. grep/egrep/fgrep are
@@ -154,14 +197,16 @@ def _is_execution_action(action: str) -> bool:
# the `grep SKILL config.json` false positive), and omitting them also avoids a
# `pgrep` substring collision with a `grep ` entry.
_FILE_READ_VERBS = {"cat", "sed", "head", "tail", "awk", "less", "more", "nl", "bat"}
-_SHELL_SEPARATORS = {"&&", "||", ";", "|"}
+_SHELL_SEPARATORS = {"&&", "||", ";", "|", "&"}
_SHELL_ASSIGNMENT_RE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
+_SHELL_VARIABLE_RE = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))")
_OUTPUT_REDIRECTS = {">", ">>", ">|", "&>", "&>>"}
_HEREDOC_REDIRECTS = {"<<", "<<<"}
def _shell_tokens(cmd: Any) -> list[str]:
- lexer = shlex.shlex(str(cmd), posix=True, punctuation_chars=True)
+ normalized = str(cmd).replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ; ")
+ lexer = shlex.shlex(normalized, posix=True, punctuation_chars=True)
lexer.whitespace_split = True
lexer.commenters = ""
try:
@@ -174,15 +219,24 @@ def _shell_tokens(cmd: Any) -> list[str]:
def _skill_md_arg(arg: str, assignments: dict[str, str]) -> bool:
- value = str(arg).lstrip("<>")
- if value.startswith("${") and value.endswith("}"):
- value = assignments.get(value[2:-1], value)
- elif value.startswith("$"):
- value = assignments.get(value[1:], value)
- value_l = value.lower()
+ value = _resolved_shell_arg(arg, assignments)
+ value_l = value.replace("\\", "/").lower()
return value_l == "skill.md" or value_l.endswith("/skill.md")
+def _resolved_shell_arg(arg: str, assignments: dict[str, str]) -> str:
+ value = str(arg).lstrip("<>")
+ for _ in range(2):
+ resolved = _SHELL_VARIABLE_RE.sub(
+ lambda match: assignments.get(match.group(1) or match.group(2), match.group(0)),
+ value,
+ )
+ if resolved == value:
+ break
+ value = resolved
+ return value
+
+
def _is_output_redirect(token: str) -> bool:
token = str(token)
return token in _OUTPUT_REDIRECTS or any(token.endswith(op) for op in _OUTPUT_REDIRECTS)
@@ -247,6 +301,332 @@ def _cmd_reads_skill_md(cmd) -> bool:
return False
+_SCRIPT_INTERPRETERS = {"bash", "dash", "node", "perl", "python", "python3", "ruby", "sh", "zsh"}
+_SHELL_COMMAND_INTERPRETERS = {"bash", "dash", "sh", "zsh"}
+_INERT_SHELL_PRODUCERS = {"echo", "printf"}
+_MAX_SHELL_REFERENCE_CHARS = 32_768
+_MAX_SHELL_REFERENCE_TOKENS = 256
+_MAX_SHELL_REFERENCE_DEPTH = 3
+_MAX_SHELL_WRAPPERS = 8
+
+
+def _shell_substitution_payloads(command_text: str) -> tuple[list[str], bool]:
+ """Extract active command/process substitutions without evaluating shell text."""
+
+ def _group_end(start: int) -> int | None:
+ depth = 1
+ quote: str | None = None
+ index = start + 1
+ while index < len(command_text):
+ char = command_text[index]
+ if char == "\\" and quote != "'":
+ index += 2
+ continue
+ if char == "'" and quote != '"':
+ quote = None if quote == "'" else "'"
+ elif char == '"' and quote != "'":
+ quote = None if quote == '"' else '"'
+ elif quote is None:
+ if char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ if depth == 0:
+ return index
+ index += 1
+ return None
+
+ payloads: list[str] = []
+ quote: str | None = None
+ index = 0
+ while index < len(command_text):
+ char = command_text[index]
+ if char == "\\" and quote != "'":
+ index += 2
+ continue
+ if char == "'" and quote != '"':
+ quote = None if quote == "'" else "'"
+ index += 1
+ continue
+ if char == '"' and quote != "'":
+ quote = None if quote == '"' else '"'
+ index += 1
+ continue
+ if quote != "'" and char in {"$", "<"} and index + 1 < len(command_text) and command_text[index + 1] == "(":
+ end = _group_end(index + 1)
+ if end is None:
+ return payloads, True
+ payloads.append(command_text[index + 2 : end])
+ index = end + 1
+ continue
+ if quote != "'" and char == "`":
+ end = index + 1
+ while end < len(command_text):
+ if command_text[end] == "\\":
+ end += 2
+ continue
+ if command_text[end] == "`":
+ break
+ end += 1
+ if end >= len(command_text):
+ return payloads, True
+ payloads.append(command_text[index + 1 : end])
+ index = end + 1
+ continue
+ index += 1
+ return payloads, False
+
+
+def _path_with_shell_cwd(value: str, current_directory: str | None) -> str:
+ value = str(value)
+ if not current_directory or not value or value.startswith(("/", "\\")) or re.match(r"^[A-Za-z]:[\\/]", value):
+ return value
+ return f"{current_directory.rstrip('/\\')}/{value}"
+
+
+def _possibly_references_target_directory(value: Any, target_skill: str) -> bool:
+ target_key = str(target_skill).strip().casefold()
+ if not target_key:
+ return False
+ for component in _lexical_path_components(value):
+ component_key = component.casefold()
+ if component_key == target_key:
+ return True
+ if any(marker in component for marker in "*?[") and fnmatchcase(target_key, component_key):
+ return True
+ return False
+
+
+def _mentions_skill_artifact(value: Any) -> bool:
+ normalized = str(value).replace("\\", "/").casefold()
+ return "skill.md" in normalized or "/scripts/" in normalized
+
+
+def _command_input_args(command: list[str], cmd_idx: int, assignments: dict[str, str]) -> list[str]:
+ args: list[str] = []
+ skip_next = False
+ for arg in command[cmd_idx + 1 :]:
+ if skip_next:
+ skip_next = False
+ continue
+ if _is_heredoc_redirect(arg):
+ break
+ if _is_output_redirect(arg):
+ skip_next = True
+ continue
+ args.append(_resolved_shell_arg(arg, assignments))
+ return args
+
+
+def _shell_executable(value: str) -> str:
+ return str(value).replace("\\", "/").rsplit("/", 1)[-1].casefold()
+
+
+def _unwrap_shell_command(
+ command: list[str],
+ cmd_idx: int,
+ assignments: dict[str, str],
+) -> int | None:
+ """Skip bounded env/command/exec wrappers and return the real command index."""
+ for _ in range(_MAX_SHELL_WRAPPERS):
+ if cmd_idx >= len(command):
+ return cmd_idx
+ executable = _shell_executable(_resolved_shell_arg(command[cmd_idx], assignments))
+ if executable == "env":
+ cmd_idx += 1
+ while cmd_idx < len(command):
+ token = _resolved_shell_arg(command[cmd_idx], assignments)
+ if token == "--":
+ cmd_idx += 1
+ break
+ assignment = _SHELL_ASSIGNMENT_RE.match(token)
+ if assignment:
+ assignments[assignment.group(1)] = assignment.group(2)
+ cmd_idx += 1
+ continue
+ if token in {"-u", "--unset", "-C", "--chdir"}:
+ cmd_idx += 2
+ continue
+ if token.startswith("-"):
+ cmd_idx += 1
+ continue
+ break
+ continue
+ if executable == "command":
+ cmd_idx += 1
+ if cmd_idx < len(command) and command[cmd_idx] == "--":
+ cmd_idx += 1
+ while cmd_idx < len(command) and str(command[cmd_idx]).startswith("-"):
+ if command[cmd_idx] in {"-v", "-V"}:
+ return len(command)
+ cmd_idx += 1
+ continue
+ if executable == "exec":
+ cmd_idx += 1
+ while cmd_idx < len(command) and str(command[cmd_idx]).startswith("-"):
+ option = str(command[cmd_idx])
+ cmd_idx += 1
+ if option == "-a":
+ cmd_idx += 1
+ continue
+ if executable == "timeout":
+ cmd_idx += 1
+ while cmd_idx < len(command) and str(command[cmd_idx]).startswith("-"):
+ option = str(command[cmd_idx])
+ cmd_idx += 1
+ if option in {"-k", "--kill-after", "-s", "--signal"}:
+ cmd_idx += 1
+ if cmd_idx < len(command):
+ cmd_idx += 1 # duration
+ continue
+ if executable == "nice":
+ cmd_idx += 1
+ if cmd_idx < len(command) and command[cmd_idx] in {"-n", "--adjustment"}:
+ cmd_idx += 2
+ elif cmd_idx < len(command) and re.fullmatch(r"-\d+", str(command[cmd_idx])):
+ cmd_idx += 1
+ continue
+ return cmd_idx
+ return None
+
+
+def _shell_c_payload(command: list[str], cmd_idx: int, assignments: dict[str, str]) -> str | None:
+ for index in range(cmd_idx + 1, len(command) - 1):
+ option = _resolved_shell_arg(command[index], assignments)
+ if option.startswith("-") and "c" in option[1:]:
+ payload_index = index + 1
+ if command[payload_index] == "--":
+ payload_index += 1
+ if payload_index < len(command):
+ return _resolved_shell_arg(command[payload_index], assignments)
+ return None
+
+
+def _cmd_references_exact_target(cmd: Any, target_skill: str, *, _depth: int = 0) -> bool | None:
+ """Detect a target reference, returning ``None`` when a parser bound is hit."""
+ command_text = str(cmd)
+ if _depth >= _MAX_SHELL_REFERENCE_DEPTH or len(command_text) > _MAX_SHELL_REFERENCE_CHARS:
+ return None
+ saw_unknown = False
+ substitutions, malformed_substitution = _shell_substitution_payloads(command_text)
+ if malformed_substitution:
+ saw_unknown = True
+ for payload in substitutions:
+ nested_reference = _cmd_references_exact_target(payload, target_skill, _depth=_depth + 1)
+ if nested_reference is True:
+ return True
+ if nested_reference is None:
+ saw_unknown = True
+ tokens = _shell_tokens(cmd)
+ if len(tokens) > _MAX_SHELL_REFERENCE_TOKENS:
+ return None
+ assignments: dict[str, str] = {}
+ current_directory: str | None = None
+ idx = 0
+ while idx < len(tokens):
+ if tokens[idx] in _SHELL_SEPARATORS:
+ idx += 1
+ continue
+ end = idx
+ while end < len(tokens) and tokens[end] not in _SHELL_SEPARATORS:
+ end += 1
+ command = tokens[idx:end]
+ cmd_idx = 0
+ while cmd_idx < len(command):
+ assignment = _SHELL_ASSIGNMENT_RE.match(command[cmd_idx])
+ if not assignment:
+ break
+ assignments[assignment.group(1)] = assignment.group(2)
+ cmd_idx += 1
+ if (
+ cmd_idx < len(command)
+ and command[cmd_idx] == "("
+ and command[-1] == ")"
+ and any(value.endswith("$") for value in assignments.values())
+ ):
+ nested_reference = _cmd_references_exact_target(
+ shlex.join(command[cmd_idx + 1 : -1]),
+ target_skill,
+ _depth=_depth + 1,
+ )
+ if nested_reference is True:
+ return True
+ if nested_reference is None:
+ saw_unknown = True
+ idx = end + 1
+ continue
+ unwrapped_idx = _unwrap_shell_command(command, cmd_idx, assignments)
+ if unwrapped_idx is None:
+ saw_unknown = True
+ idx = end + 1
+ continue
+ cmd_idx = unwrapped_idx
+ if cmd_idx < len(command):
+ executable_path = _path_with_shell_cwd(
+ _resolved_shell_arg(command[cmd_idx], assignments),
+ current_directory,
+ )
+ executable = _shell_executable(executable_path)
+ input_args = _command_input_args(command, cmd_idx, assignments)
+ effective_input_args = [_path_with_shell_cwd(arg, current_directory) for arg in input_args]
+ if executable == "cd":
+ directory = next((arg for arg in input_args if arg and not arg.startswith("-")), None)
+ if directory is None:
+ saw_unknown = True
+ else:
+ current_directory = _path_with_shell_cwd(directory, current_directory)
+ idx = end + 1
+ continue
+ if (
+ executable in _FILE_READ_VERBS
+ and _command_reads_skill_md_arg(command, cmd_idx, assignments)
+ and any(
+ _references_exact_target_artifact(arg, target_skill, artifact="skill")
+ for arg in effective_input_args
+ )
+ ):
+ return True
+ if executable in _SHELL_COMMAND_INTERPRETERS:
+ payload = _shell_c_payload(command, cmd_idx, assignments)
+ if payload is not None:
+ nested_reference = _cmd_references_exact_target(payload, target_skill, _depth=_depth + 1)
+ if nested_reference is True:
+ return True
+ if nested_reference is None:
+ saw_unknown = True
+ idx = end + 1
+ continue
+ directly_executes_target = _references_exact_target_artifact(
+ executable_path,
+ target_skill,
+ artifact="scripts",
+ )
+ interpreter_executes_target = (
+ executable in _SCRIPT_INTERPRETERS or re.fullmatch(r"python\d+(?:\.\d+)*", executable) is not None
+ ) and any(
+ _references_exact_target_artifact(arg, target_skill, artifact="scripts") for arg in effective_input_args
+ )
+ sources_target = executable in {".", "source"} and any(
+ _references_exact_target_artifact(arg, target_skill, artifact="scripts") for arg in effective_input_args
+ )
+ if directly_executes_target or interpreter_executes_target or sources_target:
+ return True
+ if executable not in _INERT_SHELL_PRODUCERS and any(
+ _references_exact_target_artifact(str(token).strip("()"), target_skill, artifact=artifact)
+ for token in command
+ for artifact in ("skill", "scripts")
+ ):
+ saw_unknown = True
+ if (
+ executable not in _INERT_SHELL_PRODUCERS
+ and any(_possibly_references_target_directory(token, target_skill) for token in effective_input_args)
+ and any(_mentions_skill_artifact(token) for token in effective_input_args)
+ ):
+ saw_unknown = True
+ idx = end + 1
+ return None if saw_unknown else False
+
+
def _normalize_skill_names(value: Any) -> list[str]:
"""Normalize dataset-provided skill name fields into a de-duplicated list."""
if value is None:
@@ -299,6 +679,15 @@ def resolve_acceptable_skills(entry: dict[str, Any], expected_skill: str | None
return _accepted_skill_names(expected_skill or entry.get("expected_skill"), raw)
+def resolve_should_trigger(entry: dict[str, Any]) -> bool | None:
+ """Resolve routing while preserving legacy unlabeled cases as ``None``."""
+ if "should_trigger" in entry:
+ return bool(entry.get("should_trigger"))
+ if "expected_skill" in entry:
+ return bool(entry.get("expected_skill"))
+ return None
+
+
def _match_skill_name(observed: str, expected: str, *, fuzzy: bool = False) -> bool:
if not observed or not expected:
return False
@@ -983,26 +1372,39 @@ def check_negative_case(
"""Check that the agent did NOT activate the tested skill (negative case)."""
if skill_tool_names:
for s in skill_tool_names:
- if skill_under_test.lower() in s.lower():
+ if str(s).strip().casefold() == str(skill_under_test).strip().casefold():
return {
"passed": False,
"score": 0.0,
"reason": f"Incorrectly activated {skill_under_test} via Skill tool",
}
+ saw_unknown = False
for tc in tool_calls:
- action = tc.get("action", "")
+ action = str(tc.get("action", ""))
- if "read" in action.lower():
+ if _is_file_read_action(action):
path = _extract_path(tc)
- if skill_under_test in path and "SKILL.md" in path:
+ if not path:
+ saw_unknown = True
+ continue
+ if _references_exact_target_artifact(path, skill_under_test, artifact="skill"):
return {"passed": False, "score": 0.0, "reason": f"Incorrectly read {skill_under_test}/SKILL.md"}
elif _is_execution_action(action):
cmd = _command_text(tc)
- if skill_under_test in cmd:
+ target_reference = _cmd_references_exact_target(cmd, skill_under_test)
+ if target_reference is True:
return {"passed": False, "score": 0.0, "reason": f"Incorrectly executed {skill_under_test} scripts"}
+ if target_reference is None:
+ saw_unknown = True
+ if saw_unknown:
+ return {
+ "passed": None,
+ "score": 0.0,
+ "reason": f"Could not safely determine whether {skill_under_test} was triggered",
+ }
return {"passed": True, "score": 1.0, "reason": f"Correctly did not trigger {skill_under_test}"}
@@ -1223,8 +1625,10 @@ def score_skill_execution(
tool_calls: list[dict[str, Any]],
expected_skill: str,
expected_script: str | None = None,
- should_trigger: bool = True,
+ should_trigger: bool | None = True,
*,
+ evaluated_skill: str | None = None,
+ require_evaluated_skill: bool = False,
skill_tool_names: list[str] | None = None,
acceptable_skills: Any = None,
) -> dict[str, Any]:
@@ -1232,8 +1636,19 @@ def score_skill_execution(
Returns ``{"score": float, "details": dict}`` with per-check results.
"""
+ if should_trigger is None:
+ return {"score": 1.0, "details": {"message": "No expected_skill -- skipped"}}
+
if not should_trigger:
- skill_under_test = expected_skill
+ if require_evaluated_skill and not evaluated_skill:
+ return {
+ "score": 0.0,
+ "details": {
+ "message": "Explicit negative case is missing trusted evaluated_skill identity",
+ "should_trigger": False,
+ },
+ }
+ skill_under_test = evaluated_skill or expected_skill
if not skill_under_test:
return {"score": 1.0, "details": {"message": "Negative case, no skill identified"}}
if not tool_calls:
diff --git a/src/skillevaluator/tier3/harbor/adapter.py b/src/skillevaluator/tier3/harbor/adapter.py
index 6ce446a4..1d15bef4 100644
--- a/src/skillevaluator/tier3/harbor/adapter.py
+++ b/src/skillevaluator/tier3/harbor/adapter.py
@@ -1905,11 +1905,18 @@ def _write_entry_json(
workspace_skill_names: list[str] | None = None,
grading_mode: str = "default",
custom_grader: bool = False,
+ evaluated_skill: str | None = None,
) -> None:
tests_dir = task_dir / "tests"
tests_dir.mkdir(parents=True, exist_ok=True)
+ trusted_identity: dict[str, str] = {}
+ if grading_mode in ("default", "default_plus_custom"):
+ if not evaluated_skill:
+ raise ValueError("SkillEvaluator default grading requires a trusted evaluated skill identity")
+ trusted_identity["evaluated_skill"] = evaluated_skill
entry_with_flag = {
**entry,
+ **trusted_identity,
"has_skill": has_skill,
"skill_workspace_mode": workspace_mode,
"workspace_skill_names": workspace_skill_names or [],
@@ -4657,6 +4664,7 @@ def _stage_native_harbor_tasks_into(
workspace_skill_names=workspace_skill_names,
grading_mode=grading_mode,
custom_grader=custom_grader,
+ evaluated_skill=skill_path.name,
)
_write_test_sh(task_dir, grading_mode=grading_mode, custom_grader=custom_grader)
elif custom_grader:
@@ -5006,6 +5014,7 @@ def _generate_harbor_tasks_into(
workspace_skill_names=workspace_skill_names,
grading_mode=grading_mode,
custom_grader=custom_grader,
+ evaluated_skill=(skill_path.name if grading_mode in ("default", "default_plus_custom") else None),
)
_write_test_sh(task_dir, grading_mode=grading_mode, custom_grader=custom_grader)
diff --git a/src/skillevaluator/tier3/harbor/collector.py b/src/skillevaluator/tier3/harbor/collector.py
index fc97b1d5..9a3bc51c 100644
--- a/src/skillevaluator/tier3/harbor/collector.py
+++ b/src/skillevaluator/tier3/harbor/collector.py
@@ -18,6 +18,8 @@ import stat
from pathlib import Path
from typing import Any
+from skillevaluator.tier3.eval_core.atif_helpers import extract_tool_calls_as_dicts, get_skill_tool_calls
+from skillevaluator.tier3.eval_core.checks import check_negative_case
from skillevaluator.tier3.harbor.metrics import (
DEFAULT_METRIC_SET,
DEFAULT_METRICS,
@@ -2221,11 +2223,149 @@ def _annotate_security_attribution(
return summary
+def _is_standard_skill_execution_reward(reward: dict[str, Any]) -> bool:
+ """Return whether the reward carries a usable canonical standard score."""
+ standard_metric_sets = {DEFAULT_METRIC_SET, LEGACY_METRIC_SET}
+ declared_metric_set = reward.get("metric_set") or reward.get("metric_set_version")
+ if declared_metric_set and str(declared_metric_set) not in standard_metric_sets:
+ return False
+ metric_set, metrics = metric_set_for_reward(reward)
+ return (
+ metric_set in standard_metric_sets
+ and "skill_execution" in metrics
+ and metric_value(reward, "skill_execution") is not None
+ )
+
+
+def _trajectory_skill_invoked(trajectory: Any, skill_name: str) -> bool | None:
+ """Derive target invocation from one readable ATIF trajectory."""
+ if not isinstance(trajectory, dict):
+ return None
+ steps = trajectory.get("steps")
+ if not isinstance(steps, list) or not steps or any(not isinstance(step, dict) for step in steps):
+ return None
+ agent_steps = [step for step in steps if step.get("source") == "agent"]
+ if not agent_steps:
+ return None
+ for step in agent_steps:
+ tool_calls = step.get("tool_calls")
+ if not isinstance(tool_calls, list):
+ return None
+ for tool_call in tool_calls:
+ if (
+ not isinstance(tool_call, dict)
+ or not isinstance(tool_call.get("function_name"), str)
+ or not tool_call["function_name"].strip()
+ or not isinstance(tool_call.get("arguments"), dict)
+ ):
+ return None
+ try:
+ agent_trajectory = {**trajectory, "steps": agent_steps}
+ tool_calls = extract_tool_calls_as_dicts(agent_trajectory)
+ skill_tool_names = get_skill_tool_calls(agent_trajectory)
+ negative_check = check_negative_case(tool_calls, skill_name, skill_tool_names=skill_tool_names)
+ except (AttributeError, TypeError, ValueError):
+ return None
+ passed = negative_check.get("passed")
+ return not passed if isinstance(passed, bool) else None
+
+
+def _authoritative_step_names(trial_root: Path) -> tuple[bool, list[str] | None]:
+ """Return ordered authoritative Harbor step names, if this is multi-step."""
+ result_path = trial_root / "result.json"
+ steps_path = trial_root / "steps"
+ try:
+ result_path.lstat()
+ result_artifact_present = True
+ except FileNotFoundError:
+ result_artifact_present = False
+ except OSError:
+ return True, None
+ try:
+ steps_path.lstat()
+ steps_layout_present = True
+ except FileNotFoundError:
+ steps_layout_present = False
+ except OSError:
+ return True, None
+
+ result = _read_json(result_path)
+ if not isinstance(result, dict):
+ return (True, None) if result_artifact_present or steps_layout_present else (False, None)
+ if "step_results" not in result:
+ if steps_layout_present:
+ return True, None
+ return False, None
+ step_results = result.get("step_results")
+ if not isinstance(step_results, list) or not step_results:
+ return True, None
+
+ names: list[str] = []
+ for step in step_results:
+ if not isinstance(step, dict):
+ return True, None
+ step_name = step.get("step_name")
+ if not isinstance(step_name, str) or not step_name or step_name in names:
+ return True, None
+ names.append(step_name)
+ return True, names
+
+
+def _trusted_trial_skill_invoked(
+ trial_root: Path,
+ step_name: str | None,
+ skill_name: str,
+) -> bool | None:
+ """Derive trusted invocation without falling back across logical steps."""
+ if step_name:
+ safe_step_paths = {path.parent.parent.name: path for path in _ordered_step_trajectory_paths(trial_root)}
+ trajectory_path = safe_step_paths.get(step_name)
+ return _trajectory_skill_invoked(_read_json(trajectory_path), skill_name) if trajectory_path else None
+
+ is_multi_step, authoritative_names = _authoritative_step_names(trial_root)
+ if is_multi_step:
+ if authoritative_names is None:
+ return None
+ safe_step_paths = {path.parent.parent.name: path for path in _ordered_step_trajectory_paths(trial_root)}
+ saw_unknown = False
+ for authoritative_name in authoritative_names:
+ trajectory_path = safe_step_paths.get(authoritative_name)
+ invoked = _trajectory_skill_invoked(_read_json(trajectory_path), skill_name) if trajectory_path else None
+ if invoked is True:
+ return True
+ if invoked is None:
+ saw_unknown = True
+ return None if saw_unknown else False
+
+ return _trajectory_skill_invoked(_read_json(trial_root / "agent" / "trajectory.json"), skill_name)
+
+
+def _add_trusted_invocation_evidence(
+ clean_reward: dict[str, Any],
+ source_reward: dict[str, Any],
+ trial_root: Path | None,
+ skill_name: str,
+) -> None:
+ """Replace verifier-authored routing evidence on standard rewards only."""
+ if not _is_standard_skill_execution_reward(source_reward):
+ return
+ for key in ("skill_invoked", "routing_passed", "invocation_evidence_source"):
+ clean_reward.pop(key, None)
+ if trial_root is None:
+ return
+ invoked = _trusted_trial_skill_invoked(trial_root, source_reward.get("_step_name"), skill_name)
+ if invoked is None:
+ return
+ clean_reward["skill_invoked"] = invoked
+ clean_reward["invocation_evidence_source"] = "trajectory"
+
+
def _save_trials(
rewards: list[dict[str, Any]],
trials_dir: Path,
job_dir: Path | None,
*,
+ skill_name: str,
agent: str,
variant: str,
agent_model: str | None = None,
@@ -2250,6 +2390,7 @@ def _save_trials(
reward["_trajectory_summary"] = _summarize_trajectory_file(src_traj)
clean_reward = {k: v for k, v in reward.items() if not k.startswith("_")}
+ _add_trusted_invocation_evidence(clean_reward, reward, trial_src, skill_name)
# Persist the physical attempt identity so bounded report readers can keep
# fallback multi-step rows for diagnostics without weighting a logical
# Harbor trial once per step. This also populates the canonical report's
@@ -2615,6 +2756,7 @@ def collect_harbor_results(
with_collected_rewards,
agent_dir / "with-skill" / "trials",
with_job_dir,
+ skill_name=skill_name,
agent=agent,
variant="with_skill",
agent_model=agent_model,
@@ -2774,6 +2916,7 @@ def collect_harbor_results(
without_collected_rewards,
agent_dir / "without-skill" / "trials",
without_job_dir,
+ skill_name=skill_name,
agent=agent,
variant="without_skill",
agent_model=agent_model,
@@ -2930,6 +3073,7 @@ def collect_harbor_results(
with_rewards,
agent_dir / "with-skill" / "trials",
with_job_dir,
+ skill_name=skill_name,
agent=agent,
variant="with_skill",
agent_model=agent_model,
diff --git a/src/skillevaluator/tier3/harbor/templates/eval.py b/src/skillevaluator/tier3/harbor/templates/eval.py
index fa5ceafb..54ff6a7b 100644
--- a/src/skillevaluator/tier3/harbor/templates/eval.py
+++ b/src/skillevaluator/tier3/harbor/templates/eval.py
@@ -33,6 +33,7 @@ import sys
import unicodedata
import urllib.error
import urllib.request
+from fnmatch import fnmatchcase
from pathlib import Path
from typing import Any
from urllib.parse import quote, unquote_to_bytes, urlparse, urlsplit
@@ -1866,7 +1867,7 @@ def _salvage_behavior_results(text):
# Tool argument field names used across agents for file paths.
# Claude Code uses ``file_path`` for Read/Write; other agents use ``path`` or ``raw``.
-_PATH_ARG_KEYS = ("file_path", "path", "raw")
+_PATH_ARG_KEYS = ("file_path", "path", "filename", "target_file", "raw")
def _extract_path(tc):
@@ -1909,6 +1910,48 @@ def _is_execution_action(action):
return any(hint in action_lower for hint in _EXECUTION_TOOL_HINTS)
+def _is_file_read_action(action):
+ action_lower = str(action).strip().casefold()
+ return "read" in action_lower or any(
+ action_lower == name or action_lower.endswith((f"__{name}", f".{name}", f"/{name}", f":{name}"))
+ for name in ("open", "open_file", "grep", "egrep", "fgrep")
+ )
+
+
+def _lexical_path_components(value):
+ """Normalize separators and dot segments without touching the filesystem."""
+ components = []
+ for component in str(value).replace("\\", "/").strip().strip("'\"<>").split("/"):
+ if not component or component == ".":
+ continue
+ if component == "..":
+ if components and components[-1] != "..":
+ components.pop()
+ else:
+ components.append(component)
+ continue
+ components.append(component)
+ return components
+
+
+def _references_exact_target_artifact(value, target_skill, *, artifact):
+ """Return whether one lexical path references an exact target artifact."""
+ target = str(target_skill).strip()
+ if not target or artifact not in {"skill", "scripts"}:
+ return False
+ components = _lexical_path_components(value)
+ target_key = target.casefold()
+ for index, component in enumerate(components[:-1]):
+ if component.casefold() != target_key:
+ continue
+ child = components[index + 1].casefold()
+ if artifact == "skill" and child == "skill.md" and index + 2 == len(components):
+ return True
+ if artifact == "scripts" and child == "scripts":
+ return True
+ return False
+
+
# Shell utilities an agent may use to view a SKILL.md file. Covers agents that
# read via their shell exec tool rather than a native Read tool -- e.g. Codex,
# which reaches a SKILL.md with sed/head as readily as cat. grep/egrep/fgrep are
@@ -1916,14 +1959,16 @@ def _is_execution_action(action):
# the `grep SKILL config.json` false positive), and omitting them also avoids a
# `pgrep` substring collision with a `grep ` entry.
_FILE_READ_VERBS = {"cat", "sed", "head", "tail", "awk", "less", "more", "nl", "bat"}
-_SHELL_SEPARATORS = {"&&", "||", ";", "|"}
+_SHELL_SEPARATORS = {"&&", "||", ";", "|", "&"}
_SHELL_ASSIGNMENT_RE = re.compile(r"^([A-Za-z_][A-Za-z0-9_]*)=(.*)$")
+_SHELL_VARIABLE_RE = re.compile(r"\$(?:\{([A-Za-z_][A-Za-z0-9_]*)\}|([A-Za-z_][A-Za-z0-9_]*))")
_OUTPUT_REDIRECTS = {">", ">>", ">|", "&>", "&>>"}
_HEREDOC_REDIRECTS = {"<<", "<<<"}
def _shell_tokens(cmd):
- lexer = shlex.shlex(str(cmd), posix=True, punctuation_chars=True)
+ normalized = str(cmd).replace("\r\n", "\n").replace("\r", "\n").replace("\n", " ; ")
+ lexer = shlex.shlex(normalized, posix=True, punctuation_chars=True)
lexer.whitespace_split = True
lexer.commenters = ""
try:
@@ -1936,15 +1981,24 @@ def _shell_tokens(cmd):
def _skill_md_arg(arg, assignments):
- value = str(arg).lstrip("<>")
- if value.startswith("${") and value.endswith("}"):
- value = assignments.get(value[2:-1], value)
- elif value.startswith("$"):
- value = assignments.get(value[1:], value)
- value_l = value.lower()
+ value = _resolved_shell_arg(arg, assignments)
+ value_l = value.replace("\\", "/").lower()
return value_l == "skill.md" or value_l.endswith("/skill.md")
+def _resolved_shell_arg(arg, assignments):
+ value = str(arg).lstrip("<>")
+ for _ in range(2):
+ resolved = _SHELL_VARIABLE_RE.sub(
+ lambda match: assignments.get(match.group(1) or match.group(2), match.group(0)),
+ value,
+ )
+ if resolved == value:
+ break
+ value = resolved
+ return value
+
+
def _is_output_redirect(token):
token = str(token)
return token in _OUTPUT_REDIRECTS or any(token.endswith(op) for op in _OUTPUT_REDIRECTS)
@@ -2009,6 +2063,328 @@ def _cmd_reads_skill_md(cmd) -> bool:
return False
+_SCRIPT_INTERPRETERS = {"bash", "dash", "node", "perl", "python", "python3", "ruby", "sh", "zsh"}
+_SHELL_COMMAND_INTERPRETERS = {"bash", "dash", "sh", "zsh"}
+_INERT_SHELL_PRODUCERS = {"echo", "printf"}
+_MAX_SHELL_REFERENCE_CHARS = 32_768
+_MAX_SHELL_REFERENCE_TOKENS = 256
+_MAX_SHELL_REFERENCE_DEPTH = 3
+_MAX_SHELL_WRAPPERS = 8
+
+
+def _shell_substitution_payloads(command_text):
+ """Extract active command/process substitutions without evaluating shell text."""
+
+ def _group_end(start):
+ depth = 1
+ quote = None
+ index = start + 1
+ while index < len(command_text):
+ char = command_text[index]
+ if char == "\\" and quote != "'":
+ index += 2
+ continue
+ if char == "'" and quote != '"':
+ quote = None if quote == "'" else "'"
+ elif char == '"' and quote != "'":
+ quote = None if quote == '"' else '"'
+ elif quote is None:
+ if char == "(":
+ depth += 1
+ elif char == ")":
+ depth -= 1
+ if depth == 0:
+ return index
+ index += 1
+ return None
+
+ payloads = []
+ quote = None
+ index = 0
+ while index < len(command_text):
+ char = command_text[index]
+ if char == "\\" and quote != "'":
+ index += 2
+ continue
+ if char == "'" and quote != '"':
+ quote = None if quote == "'" else "'"
+ index += 1
+ continue
+ if char == '"' and quote != "'":
+ quote = None if quote == '"' else '"'
+ index += 1
+ continue
+ if quote != "'" and char in {"$", "<"} and index + 1 < len(command_text) and command_text[index + 1] == "(":
+ end = _group_end(index + 1)
+ if end is None:
+ return payloads, True
+ payloads.append(command_text[index + 2 : end])
+ index = end + 1
+ continue
+ if quote != "'" and char == "`":
+ end = index + 1
+ while end < len(command_text):
+ if command_text[end] == "\\":
+ end += 2
+ continue
+ if command_text[end] == "`":
+ break
+ end += 1
+ if end >= len(command_text):
+ return payloads, True
+ payloads.append(command_text[index + 1 : end])
+ index = end + 1
+ continue
+ index += 1
+ return payloads, False
+
+
+def _path_with_shell_cwd(value, current_directory):
+ value = str(value)
+ if not current_directory or not value or value.startswith(("/", "\\")) or re.match(r"^[A-Za-z]:[\\/]", value):
+ return value
+ return f"{current_directory.rstrip('/\\')}/{value}"
+
+
+def _possibly_references_target_directory(value, target_skill):
+ target_key = str(target_skill).strip().casefold()
+ if not target_key:
+ return False
+ for component in _lexical_path_components(value):
+ component_key = component.casefold()
+ if component_key == target_key:
+ return True
+ if any(marker in component for marker in "*?[") and fnmatchcase(target_key, component_key):
+ return True
+ return False
+
+
+def _mentions_skill_artifact(value):
+ normalized = str(value).replace("\\", "/").casefold()
+ return "skill.md" in normalized or "/scripts/" in normalized
+
+
+def _command_input_args(command, cmd_idx, assignments):
+ args = []
+ skip_next = False
+ for arg in command[cmd_idx + 1 :]:
+ if skip_next:
+ skip_next = False
+ continue
+ if _is_heredoc_redirect(arg):
+ break
+ if _is_output_redirect(arg):
+ skip_next = True
+ continue
+ args.append(_resolved_shell_arg(arg, assignments))
+ return args
+
+
+def _shell_executable(value):
+ return str(value).replace("\\", "/").rsplit("/", 1)[-1].casefold()
+
+
+def _unwrap_shell_command(command, cmd_idx, assignments):
+ """Skip bounded env/command/exec wrappers and return the real command index."""
+ for _ in range(_MAX_SHELL_WRAPPERS):
+ if cmd_idx >= len(command):
+ return cmd_idx
+ executable = _shell_executable(_resolved_shell_arg(command[cmd_idx], assignments))
+ if executable == "env":
+ cmd_idx += 1
+ while cmd_idx < len(command):
+ token = _resolved_shell_arg(command[cmd_idx], assignments)
+ if token == "--":
+ cmd_idx += 1
+ break
+ assignment = _SHELL_ASSIGNMENT_RE.match(token)
+ if assignment:
+ assignments[assignment.group(1)] = assignment.group(2)
+ cmd_idx += 1
+ continue
+ if token in {"-u", "--unset", "-C", "--chdir"}:
+ cmd_idx += 2
+ continue
+ if token.startswith("-"):
+ cmd_idx += 1
+ continue
+ break
+ continue
+ if executable == "command":
+ cmd_idx += 1
+ if cmd_idx < len(command) and command[cmd_idx] == "--":
+ cmd_idx += 1
+ while cmd_idx < len(command) and str(command[cmd_idx]).startswith("-"):
+ if command[cmd_idx] in {"-v", "-V"}:
+ return len(command)
+ cmd_idx += 1
+ continue
+ if executable == "exec":
+ cmd_idx += 1
+ while cmd_idx < len(command) and str(command[cmd_idx]).startswith("-"):
+ option = str(command[cmd_idx])
+ cmd_idx += 1
+ if option == "-a":
+ cmd_idx += 1
+ continue
+ if executable == "timeout":
+ cmd_idx += 1
+ while cmd_idx < len(command) and str(command[cmd_idx]).startswith("-"):
+ option = str(command[cmd_idx])
+ cmd_idx += 1
+ if option in {"-k", "--kill-after", "-s", "--signal"}:
+ cmd_idx += 1
+ if cmd_idx < len(command):
+ cmd_idx += 1
+ continue
+ if executable == "nice":
+ cmd_idx += 1
+ if cmd_idx < len(command) and command[cmd_idx] in {"-n", "--adjustment"}:
+ cmd_idx += 2
+ elif cmd_idx < len(command) and re.fullmatch(r"-\d+", str(command[cmd_idx])):
+ cmd_idx += 1
+ continue
+ return cmd_idx
+ return None
+
+
+def _shell_c_payload(command, cmd_idx, assignments):
+ for index in range(cmd_idx + 1, len(command) - 1):
+ option = _resolved_shell_arg(command[index], assignments)
+ if option.startswith("-") and "c" in option[1:]:
+ payload_index = index + 1
+ if command[payload_index] == "--":
+ payload_index += 1
+ if payload_index < len(command):
+ return _resolved_shell_arg(command[payload_index], assignments)
+ return None
+
+
+def _cmd_references_exact_target(cmd, target_skill, _depth=0):
+ """Detect a target reference, returning None when a parser bound is hit."""
+ command_text = str(cmd)
+ if _depth >= _MAX_SHELL_REFERENCE_DEPTH or len(command_text) > _MAX_SHELL_REFERENCE_CHARS:
+ return None
+ saw_unknown = False
+ substitutions, malformed_substitution = _shell_substitution_payloads(command_text)
+ if malformed_substitution:
+ saw_unknown = True
+ for payload in substitutions:
+ nested_reference = _cmd_references_exact_target(payload, target_skill, _depth=_depth + 1)
+ if nested_reference is True:
+ return True
+ if nested_reference is None:
+ saw_unknown = True
+ tokens = _shell_tokens(cmd)
+ if len(tokens) > _MAX_SHELL_REFERENCE_TOKENS:
+ return None
+ assignments = {}
+ current_directory = None
+ idx = 0
+ while idx < len(tokens):
+ if tokens[idx] in _SHELL_SEPARATORS:
+ idx += 1
+ continue
+ end = idx
+ while end < len(tokens) and tokens[end] not in _SHELL_SEPARATORS:
+ end += 1
+ command = tokens[idx:end]
+ cmd_idx = 0
+ while cmd_idx < len(command):
+ assignment = _SHELL_ASSIGNMENT_RE.match(command[cmd_idx])
+ if not assignment:
+ break
+ assignments[assignment.group(1)] = assignment.group(2)
+ cmd_idx += 1
+ if (
+ cmd_idx < len(command)
+ and command[cmd_idx] == "("
+ and command[-1] == ")"
+ and any(value.endswith("$") for value in assignments.values())
+ ):
+ nested_reference = _cmd_references_exact_target(
+ shlex.join(command[cmd_idx + 1 : -1]),
+ target_skill,
+ _depth=_depth + 1,
+ )
+ if nested_reference is True:
+ return True
+ if nested_reference is None:
+ saw_unknown = True
+ idx = end + 1
+ continue
+ unwrapped_idx = _unwrap_shell_command(command, cmd_idx, assignments)
+ if unwrapped_idx is None:
+ saw_unknown = True
+ idx = end + 1
+ continue
+ cmd_idx = unwrapped_idx
+ if cmd_idx < len(command):
+ executable_path = _path_with_shell_cwd(
+ _resolved_shell_arg(command[cmd_idx], assignments),
+ current_directory,
+ )
+ executable = _shell_executable(executable_path)
+ input_args = _command_input_args(command, cmd_idx, assignments)
+ effective_input_args = [_path_with_shell_cwd(arg, current_directory) for arg in input_args]
+ if executable == "cd":
+ directory = next((arg for arg in input_args if arg and not arg.startswith("-")), None)
+ if directory is None:
+ saw_unknown = True
+ else:
+ current_directory = _path_with_shell_cwd(directory, current_directory)
+ idx = end + 1
+ continue
+ if (
+ executable in _FILE_READ_VERBS
+ and _command_reads_skill_md_arg(command, cmd_idx, assignments)
+ and any(
+ _references_exact_target_artifact(arg, target_skill, artifact="skill")
+ for arg in effective_input_args
+ )
+ ):
+ return True
+ if executable in _SHELL_COMMAND_INTERPRETERS:
+ payload = _shell_c_payload(command, cmd_idx, assignments)
+ if payload is not None:
+ nested_reference = _cmd_references_exact_target(payload, target_skill, _depth=_depth + 1)
+ if nested_reference is True:
+ return True
+ if nested_reference is None:
+ saw_unknown = True
+ idx = end + 1
+ continue
+ directly_executes_target = _references_exact_target_artifact(
+ executable_path,
+ target_skill,
+ artifact="scripts",
+ )
+ interpreter_executes_target = (
+ executable in _SCRIPT_INTERPRETERS or re.fullmatch(r"python\d+(?:\.\d+)*", executable) is not None
+ ) and any(
+ _references_exact_target_artifact(arg, target_skill, artifact="scripts") for arg in effective_input_args
+ )
+ sources_target = executable in {".", "source"} and any(
+ _references_exact_target_artifact(arg, target_skill, artifact="scripts") for arg in effective_input_args
+ )
+ if directly_executes_target or interpreter_executes_target or sources_target:
+ return True
+ if executable not in _INERT_SHELL_PRODUCERS and any(
+ _references_exact_target_artifact(str(token).strip("()"), target_skill, artifact=artifact)
+ for token in command
+ for artifact in ("skill", "scripts")
+ ):
+ saw_unknown = True
+ if (
+ executable not in _INERT_SHELL_PRODUCERS
+ and any(_possibly_references_target_directory(token, target_skill) for token in effective_input_args)
+ and any(_mentions_skill_artifact(token) for token in effective_input_args)
+ ):
+ saw_unknown = True
+ idx = end + 1
+ return None if saw_unknown else False
+
+
def _normalize_skill_names(value):
if value is None:
return []
@@ -2057,6 +2433,15 @@ def _resolve_acceptable_skills(entry, expected_skill=None):
return _accepted_skill_names(expected_skill or entry.get("expected_skill"), raw)
+def resolve_should_trigger(entry):
+ """Resolve routing while preserving legacy unlabeled cases as ``None``."""
+ if "should_trigger" in entry:
+ return bool(entry.get("should_trigger"))
+ if "expected_skill" in entry:
+ return bool(entry.get("expected_skill"))
+ return None
+
+
def _match_skill_name(observed, expected, fuzzy=False):
if not observed or not expected:
return False
@@ -2520,22 +2905,35 @@ def check_workflow_order(tool_calls, skill_tool_names=None, expected_skill=None)
def check_negative_case(tool_calls, skill_under_test, skill_tool_names=None):
if skill_tool_names:
for s in skill_tool_names:
- if skill_under_test.lower() in s.lower():
+ if str(s).strip().casefold() == str(skill_under_test).strip().casefold():
return {
"passed": False,
"score": 0.0,
"reason": f"Incorrectly activated {skill_under_test} via Skill tool",
}
+ saw_unknown = False
for tc in tool_calls:
- action = tc.get("action", "")
- if "read" in action.lower():
+ action = str(tc.get("action", ""))
+ if _is_file_read_action(action):
path = _extract_path(tc)
- if skill_under_test in path and "SKILL.md" in path:
+ if not path:
+ saw_unknown = True
+ continue
+ if _references_exact_target_artifact(path, skill_under_test, artifact="skill"):
return {"passed": False, "score": 0.0, "reason": f"Incorrectly read {skill_under_test}/SKILL.md"}
elif _is_execution_action(action):
cmd = _command_text(tc)
- if skill_under_test in cmd:
+ target_reference = _cmd_references_exact_target(cmd, skill_under_test)
+ if target_reference is True:
return {"passed": False, "score": 0.0, "reason": f"Incorrectly executed {skill_under_test} scripts"}
+ if target_reference is None:
+ saw_unknown = True
+ if saw_unknown:
+ return {
+ "passed": None,
+ "score": 0.0,
+ "reason": f"Could not safely determine whether {skill_under_test} was triggered",
+ }
return {"passed": True, "score": 1.0, "reason": f"Correctly did not trigger {skill_under_test}"}
@@ -2797,6 +3195,76 @@ def check_tool_efficiency(tool_calls, expected_skill=None, expected_script=None)
}
+def score_skill_execution(
+ tool_calls,
+ expected_skill,
+ expected_script=None,
+ should_trigger=True,
+ *,
+ evaluated_skill=None,
+ require_evaluated_skill=False,
+ skill_tool_names=None,
+ acceptable_skills=None,
+):
+ if should_trigger is None:
+ return {"score": 1.0, "details": {"message": "No expected_skill -- skipped"}}
+
+ if not should_trigger:
+ if require_evaluated_skill and not evaluated_skill:
+ return {
+ "score": 0.0,
+ "details": {
+ "message": "Explicit negative case is missing trusted evaluated_skill identity",
+ "should_trigger": False,
+ },
+ }
+ skill_under_test = evaluated_skill or expected_skill
+ if not skill_under_test:
+ return {"score": 1.0, "details": {"message": "Negative case, no skill identified"}}
+ if not tool_calls:
+ neg = {"passed": True, "score": 1.0, "reason": "No tool calls"}
+ else:
+ neg = check_negative_case(tool_calls, skill_under_test, skill_tool_names=skill_tool_names)
+ return {"score": neg["score"], "details": {"negative_check": neg, "should_trigger": False}}
+
+ if not expected_skill:
+ return {"score": 1.0, "details": {"message": "No expected_skill -- skipped"}}
+
+ if not tool_calls:
+ return {"score": 0.0, "details": {"message": "No tool calls in trajectory"}}
+
+ checks = {}
+ scores = []
+
+ r = check_activation(
+ tool_calls,
+ expected_skill,
+ skill_tool_names=skill_tool_names,
+ acceptable_skills=acceptable_skills,
+ )
+ checks["activation"] = r
+ scores.append(r["score"])
+
+ r = check_script_execution(tool_calls, expected_script)
+ checks["script_execution"] = r
+ scores.append(r["score"])
+
+ r = check_workflow_order(
+ tool_calls,
+ skill_tool_names=skill_tool_names,
+ expected_skill=expected_skill,
+ )
+ checks["workflow_order"] = r
+ scores.append(r["score"])
+
+ r = check_error_recovery(tool_calls, expected_script)
+ checks["error_recovery"] = r
+ scores.append(r["score"])
+
+ avg = sum(scores) / len(scores) if scores else 0.0
+ return {"score": round(avg, 4), "details": checks}
+
+
# ── LLM Judge: Accuracy (5-criterion) ────────────────────────────────────────
@@ -3208,7 +3676,8 @@ def main():
expected_skill = entry.get("expected_skill") or ""
expected_script = entry.get("expected_script") or ""
- should_trigger = entry.get("should_trigger", bool(expected_skill))
+ should_trigger = resolve_should_trigger(entry)
+ evaluated_skill = entry.get("evaluated_skill") or ""
acceptable_skills = _resolve_acceptable_skills(entry, expected_skill)
expected_behavior = entry.get("expected_behavior", [])
question = entry.get("question", "")
@@ -3242,47 +3711,18 @@ def main():
details["security"] = security_result
# ── Eval 2: skill_execution ──────────────────────────────────────────
- if not should_trigger:
- skill_under_test = expected_skill
- if not skill_under_test:
- se_score = 1.0
- details["skill_execution"] = {"message": "Negative case, no skill identified"}
- elif not tool_calls:
- neg = {"passed": True, "score": 1.0, "reason": "No tool calls"}
- se_score = 1.0
- details["skill_execution"] = {"negative_check": neg}
- else:
- neg = check_negative_case(tool_calls, skill_under_test, skill_tool_names=skill_tools)
- se_score = neg["score"]
- details["skill_execution"] = {"negative_check": neg}
- elif not expected_skill:
- se_score = 1.0
- details["skill_execution"] = {"message": "No expected_skill -- skipped"}
- elif not tool_calls:
- se_score = 0.0
- details["skill_execution"] = {"message": "No tool calls in trajectory"}
- else:
- checks = {}
- scores = []
- r = check_activation(
- tool_calls,
- expected_skill,
- skill_tool_names=skill_tools,
- acceptable_skills=acceptable_skills,
- )
- checks["activation"] = r
- scores.append(r["score"])
- r = check_script_execution(tool_calls, expected_script)
- checks["script_execution"] = r
- scores.append(r["score"])
- r = check_workflow_order(tool_calls, skill_tool_names=skill_tools, expected_skill=expected_skill)
- checks["workflow_order"] = r
- scores.append(r["score"])
- r = check_error_recovery(tool_calls, expected_script)
- checks["error_recovery"] = r
- scores.append(r["score"])
- se_score = round(sum(scores) / len(scores), 4)
- details["skill_execution"] = checks
+ skill_execution_result = score_skill_execution(
+ tool_calls,
+ expected_skill,
+ expected_script,
+ should_trigger,
+ evaluated_skill=evaluated_skill,
+ require_evaluated_skill=True,
+ skill_tool_names=skill_tools,
+ acceptable_skills=acceptable_skills,
+ )
+ se_score = skill_execution_result["score"]
+ details["skill_execution"] = skill_execution_result["details"]
# ── Eval 3: skill_efficiency ─────────────────────────────────────────
if not should_trigger or not expected_skill:
diff --git a/tests/evaluation/test_judges.py b/tests/evaluation/test_judges.py
index 9db9f18b..859b74bf 100644
--- a/tests/evaluation/test_judges.py
+++ b/tests/evaluation/test_judges.py
@@ -21,6 +21,7 @@ from skillevaluator.evaluation import (
compute_dimensions,
compute_dimensions_deterministic,
)
+from skillevaluator.evaluation.tier3_report import _normalize_trials
from skillevaluator.tier3.dataset_utils import normalize_dataset_entries
from skillevaluator.tier3.harbor.metrics import DIMENSION_DEFINITIONS
@@ -165,6 +166,9 @@ class TestInsightsJudgeNegativeControls:
assert "Do not recommend removing an unrelated negative-control case" in prompt
assert 'claim_type "negative_control_failure"' in prompt
assert "evidence_case_ids list" in prompt
+ assert "non-empty" in prompt
+ assert "name every evidence case id" in prompt
+ assert "general claims may cite only skill-activation cases" in prompt.lower()
def test_prompt_uses_runtime_should_trigger_precedence_for_agentskills_cases(self) -> None:
dataset = normalize_dataset_entries(
@@ -209,10 +213,7 @@ class TestInsightsJudgeNegativeControls:
assert context["dataset"][0]["skill_expected_to_activate"] is False
def test_sampled_trial_keeps_matching_case_metadata_beyond_first_five(self) -> None:
- dataset = [
- {"id": f"positive-{index:03d}", "expected_skill": "calculator"}
- for index in range(1, 6)
- ] + [
+ dataset = [{"id": f"positive-{index:03d}", "expected_skill": "calculator"} for index in range(1, 6)] + [
{
"id": "negative-006",
"expected_skill": None,
@@ -259,6 +260,35 @@ class TestInsightsJudgeNegativeControls:
("claude-code", 1),
]
+ def test_trial_sampling_prioritizes_trusted_negative_control_failure_evidence(self) -> None:
+ dataset = [{"id": f"positive-{index}", "expected_skill": "calculator"} for index in range(8)]
+ dataset[4] = {"id": "negative-4", "expected_skill": None}
+ trials = [
+ {
+ "entry_id": case["id"],
+ "overall": index / 10,
+ "scores": {"skill_execution": 1.0},
+ }
+ for index, case in enumerate(dataset)
+ ]
+ trials[4].update(
+ {
+ "skill_invoked": True,
+ "invocation_evidence_source": "trajectory",
+ }
+ )
+
+ prompt = InsightsJudge().create_user_prompt(
+ canonical={"dataset": dataset, "trials": trials},
+ deterministic={},
+ )
+ sampled = json.loads(prompt.split("\n\n", 1)[1])["trials"]
+
+ evidence_trial = next(trial for trial in sampled if trial["entry_id"] == "negative-4")
+ assert len(sampled) == 6
+ assert evidence_trial["skill_invoked"] is True
+ assert evidence_trial["invocation_evidence_source"] == "trajectory"
+
def test_build_insights_suppresses_original_unsupported_negative_control_findings(
self,
monkeypatch: pytest.MonkeyPatch,
@@ -336,10 +366,12 @@ class TestInsightsJudgeNegativeControls:
assert parsed["conclusions"] == [
{
+ "claim_type": "negative_control_failure",
"title": "Unintended Skill Application",
"message": "The evaluated skill was invoked for negative-001.",
"severity": "fail",
"source": "llm",
+ "evidence_case_ids": ["negative-001"],
}
]
@@ -454,7 +486,7 @@ class TestInsightsJudgeNegativeControls:
"claim_type": "general",
"category": "Improve",
"title": "Clarify Assertions",
- "message": "Remove ambiguity from test cases by making expected outputs explicit.",
+ "message": "Remove ambiguity from positive-001 by making its expected output explicit.",
"severity": "warn",
"evidence_case_ids": ["positive-001"],
}
@@ -478,3 +510,331 @@ class TestInsightsJudgeNegativeControls:
assert [item["title"] for item in parsed["conclusions"]] == ["Efficiency Regression"]
assert [item["title"] for item in parsed["recommendations"]] == ["Clarify Assertions"]
+
+ def test_parse_rejects_original_general_claim_with_empty_evidence_ids(self) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "general",
+ "title": "Unintended Skill Application",
+ "message": "The evaluated skill was unnecessarily used.",
+ "severity": "warn",
+ "evidence_case_ids": [],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {"dataset": [{"id": "negative-001", "expected_skill": None}]}
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ @pytest.mark.parametrize(
+ ("title", "message"),
+ [
+ (
+ "Efficiency positive-001",
+ "The skill was unnecessarily over-applied to unrelated negative-control work.",
+ ),
+ (
+ "Capability overreach positive-001",
+ "The evaluated capability was unnecessarily used for unrelated work, indicating scope drift.",
+ ),
+ ],
+ )
+ def test_parse_rejects_general_claim_with_negative_control_semantics(
+ self,
+ title: str,
+ message: str,
+ ) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "general",
+ "title": title,
+ "message": message,
+ "severity": "warn",
+ "evidence_case_ids": ["positive-001"],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {
+ "dataset": [
+ {"id": "positive-001", "expected_skill": "calculator"},
+ {"id": "negative-001", "expected_skill": None},
+ ]
+ }
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ def test_parse_rejects_case_ids_hidden_beyond_the_grounding_text_bound(self) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "general",
+ "title": "Efficiency positive-001",
+ "message": ("x" * 2_100) + " negative-001",
+ "severity": "warn",
+ "evidence_case_ids": ["positive-001"],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {
+ "dataset": [
+ {"id": "positive-001", "expected_skill": "calculator"},
+ {"id": "negative-001", "expected_skill": None},
+ ]
+ }
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ @pytest.mark.parametrize(
+ ("evidence_case_ids", "message"),
+ [
+ (["positive-001"], "Token use increased."),
+ (["positive-001", "positive-001"], "Token use increased for positive-001."),
+ (["fabricated-999"], "Token use increased for fabricated-999."),
+ ],
+ )
+ def test_parse_requires_exact_unique_known_case_ids_named_in_prose(
+ self,
+ evidence_case_ids: list[str],
+ message: str,
+ ) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "general",
+ "title": "Efficiency regression",
+ "message": message,
+ "severity": "warn",
+ "evidence_case_ids": evidence_case_ids,
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {"dataset": [{"id": "positive-001", "expected_skill": "calculator"}]}
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ @pytest.mark.parametrize(
+ ("trial", "accepted"),
+ [
+ ({"skill_invoked": True}, True),
+ ({"routing_passed": False}, True),
+ ({"skill_invoked": False}, False),
+ ({"routing_passed": True}, False),
+ ({"skill_invoked": True, "routing_passed": False}, True),
+ ({"skill_invoked": False, "routing_passed": True}, False),
+ ({"skill_invoked": True, "routing_passed": True, "scores": {"skill_execution": 0.0}}, False),
+ ({"skill_invoked": False, "routing_passed": False, "scores": {"skill_execution": 0.0}}, False),
+ ({"scores": {"skill_execution": 0.0}}, True),
+ ({"scores": {"skill_execution": 1.0}}, False),
+ ],
+ )
+ def test_parse_negative_control_uses_strict_evidence_before_legacy_numeric_fallback(
+ self,
+ trial: dict,
+ accepted: bool,
+ ) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "negative_control_failure",
+ "title": "Unintended invocation in negative-001",
+ "message": "The evaluated skill was invoked for negative-001.",
+ "severity": "fail",
+ "evidence_case_ids": ["negative-001"],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {
+ "dataset": [{"id": "negative-001", "expected_skill": None}],
+ "trials": [
+ {
+ "entry_id": "negative-001",
+ **(
+ {"invocation_evidence_source": "trajectory"}
+ if "skill_invoked" in trial or "routing_passed" in trial
+ else {}
+ ),
+ **trial,
+ }
+ ],
+ }
+
+ parsed = InsightsJudge().parse_response(response, canonical=canonical)["conclusions"]
+
+ assert bool(parsed) is accepted
+ if accepted:
+ assert parsed[0]["claim_type"] == "negative_control_failure"
+ assert parsed[0]["evidence_case_ids"] == ["negative-001"]
+
+ def test_parse_requires_every_cited_negative_control_to_have_failure_evidence(self) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "negative_control_failure",
+ "title": "Failures in negative-001 and negative-002",
+ "message": "The skill was invoked for negative-001 and negative-002.",
+ "severity": "fail",
+ "evidence_case_ids": ["negative-001", "negative-002"],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {
+ "dataset": [
+ {"id": "negative-001", "expected_skill": None},
+ {"id": "negative-002", "expected_skill": None},
+ ],
+ "trials": [
+ {
+ "entry_id": "negative-001",
+ "skill_invoked": True,
+ "invocation_evidence_source": "trajectory",
+ },
+ {
+ "entry_id": "negative-002",
+ "skill_invoked": False,
+ "invocation_evidence_source": "trajectory",
+ },
+ ],
+ }
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ @pytest.mark.parametrize("source", [None, "custom-verifier"])
+ def test_parse_does_not_trust_direct_or_custom_spoofed_invocation_booleans(
+ self,
+ source: str | None,
+ ) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "negative_control_failure",
+ "title": "Unintended invocation in negative-001",
+ "message": "The evaluated skill was invoked for negative-001.",
+ "severity": "fail",
+ "evidence_case_ids": ["negative-001"],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ trial = {
+ "entry_id": "negative-001",
+ "skill_invoked": True,
+ "routing_passed": False,
+ "scores": {"skill_execution": 1.0},
+ }
+ if source is not None:
+ trial["invocation_evidence_source"] = source
+ canonical = {
+ "dataset": [{"id": "negative-001", "expected_skill": None}],
+ "trials": [trial],
+ }
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ def test_parse_does_not_use_explicit_custom_metric_as_legacy_routing_grounding(self) -> None:
+ trials = _normalize_trials(
+ [
+ {
+ "entry_id": "negative-001",
+ "metric_set": "custom-only",
+ "overall": 0.8,
+ "skill_execution": 0.25,
+ }
+ ],
+ ["skill_execution"],
+ )
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "negative_control_failure",
+ "title": "Unintended invocation in negative-001",
+ "message": "The evaluated skill was invoked for negative-001.",
+ "severity": "fail",
+ "evidence_case_ids": ["negative-001"],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {
+ "dataset": [{"id": "negative-001", "expected_skill": None}],
+ "trials": trials,
+ }
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ def test_parse_treats_overflowing_legacy_numeric_evidence_as_unknown(self) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "negative_control_failure",
+ "title": "Unintended invocation in negative-001",
+ "message": "The evaluated skill was invoked for negative-001.",
+ "severity": "fail",
+ "evidence_case_ids": ["negative-001"],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {
+ "dataset": [{"id": "negative-001", "expected_skill": None}],
+ "trials": [
+ {
+ "entry_id": "negative-001",
+ "scores": {"skill_execution": 10**10_000},
+ }
+ ],
+ }
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ def test_parse_preserves_ordered_grounding_for_positive_general_claim(self) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "claim_type": "general",
+ "title": "Positive evidence positive-002",
+ "message": "Efficiency improved in positive-001 and positive-002.",
+ "severity": "pass",
+ "evidence_case_ids": ["positive-002", "positive-001"],
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {
+ "dataset": [
+ {"id": "positive-001", "expected_skill": "calculator"},
+ {"id": "positive-002", "expected_skill": "calculator"},
+ ]
+ }
+
+ parsed = InsightsJudge().parse_response(response, canonical=canonical)["conclusions"]
+
+ assert parsed[0]["claim_type"] == "general"
+ assert parsed[0]["evidence_case_ids"] == ["positive-002", "positive-001"]
diff --git a/tests/reporting/test_unified_tier3_report.py b/tests/reporting/test_unified_tier3_report.py
index b6168e88..4e2854cf 100644
--- a/tests/reporting/test_unified_tier3_report.py
+++ b/tests/reporting/test_unified_tier3_report.py
@@ -12,8 +12,12 @@ from pathlib import Path
import pytest
from skillevaluator.evaluation.tier3_report import (
+ _attach_harbor_evidence_to_conclusions,
+ _attach_harbor_evidence_to_recommendations,
+ _attach_harbor_evidence_to_suggestions_v2,
_evaluator_cards,
_metric_evidence,
+ _normalize_trials,
_raw_trial_rewards,
_ReportBudget,
agent_eval_result_from_directory,
@@ -146,6 +150,88 @@ def _embedded_tier3_payload(html: str) -> dict:
return json.loads(body)
+def test_normalize_trials_preserves_only_trusted_standard_invocation_evidence() -> None:
+ standard, custom_spoof, untrusted = _normalize_trials(
+ [
+ {
+ "entry_id": "standard",
+ "metric_set": "skill-evaluator-default-v2",
+ "skill_execution": 0.0,
+ "skill_invoked": True,
+ "routing_passed": False,
+ "invocation_evidence_source": "trajectory",
+ },
+ {
+ "entry_id": "custom",
+ "metric_set": "custom-only",
+ "overall": 1.0,
+ "skill_execution": 0.0,
+ "skill_invoked": True,
+ "routing_passed": False,
+ "invocation_evidence_source": "trajectory",
+ },
+ {
+ "entry_id": "untrusted",
+ "metric_set": "skill-evaluator-default-v2",
+ "skill_execution": 0.0,
+ "skill_invoked": 1,
+ "routing_passed": 0,
+ "invocation_evidence_source": "reward",
+ },
+ ],
+ list(DEFAULT_METRICS),
+ )
+
+ assert standard["skill_invoked"] is True
+ assert standard["routing_passed"] is False
+ assert standard["invocation_evidence_source"] == "trajectory"
+ assert "skill_execution" not in custom_spoof["scores"]
+ for trial in (custom_spoof, untrusted):
+ assert "skill_invoked" not in trial
+ assert "routing_passed" not in trial
+ assert "invocation_evidence_source" not in trial
+
+
+def test_case_grounded_harbor_links_win_over_positional_fallback() -> None:
+ evidence_links = [
+ {"url": "https://harbor.example.test/case-1", "entry_id": "case-1", "label": "case-1"},
+ {"url": "https://harbor.example.test/case-2", "entry_id": "case-2", "label": "case-2"},
+ ]
+ recommendations = _attach_harbor_evidence_to_recommendations(
+ [
+ {
+ "title": "Fix case-2",
+ "evidence_case_ids": ["case-2"],
+ "evidence": evidence_links[0],
+ }
+ ],
+ evidence_links,
+ )
+ suggestions = _attach_harbor_evidence_to_suggestions_v2(
+ [{"recommendation": "Fix case-2", "evidence_case_ids": ["case-2"]}],
+ evidence_links,
+ )
+ conclusions = _attach_harbor_evidence_to_conclusions(
+ [{"title": "Failure in case-2", "evidence_case_ids": ["case-2"]}],
+ evidence_links,
+ )
+
+ assert conclusions[0]["evidence"]["entry_id"] == "case-2"
+ assert recommendations[0]["evidence"]["entry_id"] == "case-2"
+ assert suggestions[0]["harbor_evidence"]["entry_id"] == "case-2"
+
+
+def test_conclusions_without_case_grounding_do_not_receive_positional_evidence() -> None:
+ evidence_links = [{"url": "https://harbor.example.test/case-1", "entry_id": "case-1", "label": "case-1"}]
+
+ conclusions = _attach_harbor_evidence_to_conclusions(
+ [{"title": "Aggregate result", "message": "No case-specific claim"}],
+ evidence_links,
+ )
+
+ assert "evidence" not in conclusions[0]
+
+
def test_package_loader_reads_template_resources_as_utf8(monkeypatch: pytest.MonkeyPatch) -> None:
class TemplateResource:
def joinpath(self, _path: str) -> TemplateResource:
diff --git a/tests/test_harbor_adapter_safety.py b/tests/test_harbor_adapter_safety.py
index 64756099..09811bfd 100644
--- a/tests/test_harbor_adapter_safety.py
+++ b/tests/test_harbor_adapter_safety.py
@@ -483,3 +483,75 @@ def test_task_modes_reject_custom_grader_symlink_before_copy(tmp_path: Path, tas
stage_native_harbor_tasks(skill, output_dir, with_skill=False, grading_mode="custom_only")
assert not (output_dir / "case-001" / "tests" / "grader.py").exists()
+
+
[email protected]("grading_mode", ("default", "default_plus_custom"))
[email protected]("task_source", ("generated", "native"))
+def test_standard_grading_stages_trusted_evaluated_skill_after_authored_entry(
+ tmp_path: Path,
+ grading_mode: str,
+ task_source: str,
+) -> None:
+ skill = tmp_path / "trusted-target"
+ evals_dir = skill / "evals"
+ evals_dir.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("# Trusted target\n", encoding="utf-8")
+ entry = {
+ "id": "case-001",
+ "question": "Do not use the target skill",
+ "expected_skill": None,
+ "evaluated_skill": "authored-spoof",
+ }
+ (evals_dir / "evals.json").write_text(json.dumps([entry]), encoding="utf-8")
+
+ output_dir = tmp_path / "tasks"
+ if task_source == "generated":
+ generate_harbor_tasks(skill, output_dir, with_skill=False, grading_mode=grading_mode)
+ else:
+ native_task = evals_dir / "harbor" / "case-001"
+ native_task.mkdir(parents=True)
+ (native_task / "task.toml").write_text(
+ 'schema_version = "1.3"\n\n[task]\nname = "nvidia/case-001"\n\n[environment]\n',
+ encoding="utf-8",
+ )
+ stage_native_harbor_tasks(skill, output_dir, with_skill=False, grading_mode=grading_mode)
+
+ staged = json.loads((output_dir / "case-001" / "tests" / "entry.json").read_text(encoding="utf-8"))
+
+ assert staged["evaluated_skill"] == skill.name
+
+
[email protected]("task_source", ("generated", "native"))
[email protected]("authored_value", (None, "authored-value"))
+def test_custom_only_staging_does_not_inject_or_overwrite_evaluated_skill(
+ tmp_path: Path,
+ task_source: str,
+ authored_value: str | None,
+) -> None:
+ skill = tmp_path / "trusted-target"
+ evals_dir = skill / "evals"
+ evals_dir.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("# Trusted target\n", encoding="utf-8")
+ entry = {"id": "case-001", "question": "Run custom grading"}
+ if authored_value is not None:
+ entry["evaluated_skill"] = authored_value
+ (evals_dir / "evals.json").write_text(json.dumps([entry]), encoding="utf-8")
+ (evals_dir / "grader.py").write_text("def grade():\n return 1\n", encoding="utf-8")
+
+ output_dir = tmp_path / "tasks"
+ if task_source == "generated":
+ generate_harbor_tasks(skill, output_dir, with_skill=False, grading_mode="custom_only")
+ else:
+ native_task = evals_dir / "harbor" / "case-001"
+ native_task.mkdir(parents=True)
+ (native_task / "task.toml").write_text(
+ 'schema_version = "1.3"\n\n[task]\nname = "nvidia/case-001"\n\n[environment]\n',
+ encoding="utf-8",
+ )
+ stage_native_harbor_tasks(skill, output_dir, with_skill=False, grading_mode="custom_only")
+ staged = json.loads((output_dir / "case-001" / "tests" / "entry.json").read_text(encoding="utf-8"))
+
+ if authored_value is None:
+ assert "evaluated_skill" not in staged
+ else:
+ assert staged["evaluated_skill"] == authored_value
diff --git a/tests/test_harbor_negative_control_evidence.py b/tests/test_harbor_negative_control_evidence.py
new file mode 100644
index 00000000..7a381dfc
--- /dev/null
+++ b/tests/test_harbor_negative_control_evidence.py
@@ -0,0 +1,734 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Trusted negative-control invocation evidence collected from Harbor ATIF."""
+
+from __future__ import annotations
+
+import json
+import shlex
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+from skillevaluator.tier3.harbor.collector import collect_harbor_results
+
+STANDARD_REWARD = {
+ "security": 0.9,
+ "skill_execution": 0.4,
+ "skill_efficiency": 0.8,
+ "accuracy": 0.7,
+ "goal_accuracy": 0.6,
+ "behavior_check": 0.5,
+}
+
+
+def _nested_shell_command(command: str, depth: int) -> str:
+ for _ in range(depth):
+ command = shlex.join(["bash", "-c", command])
+ return command
+
+
+def _trajectory(*, skill: str | None = None) -> dict[str, Any]:
+ tool_calls = []
+ if skill is not None:
+ tool_calls.append(
+ {
+ "tool_call_id": "call-1",
+ "function_name": "Read",
+ "arguments": {"file_path": f"/workspace/skills/{skill}/SKILL.md"},
+ }
+ )
+ return {
+ "schema_version": "ATIF-v1.2",
+ "steps": [
+ {
+ "step_id": 1,
+ "source": "agent",
+ "message": "done",
+ "tool_calls": tool_calls,
+ "observation": {"results": []},
+ }
+ ],
+ }
+
+
+def _write_job_result(job_dir: Path, trial_names: list[str]) -> None:
+ job_dir.mkdir(parents=True, exist_ok=True)
+ (job_dir / "result.json").write_text(
+ json.dumps(
+ {
+ "n_total_trials": len(trial_names),
+ "stats": {
+ "n_trials": len(trial_names),
+ "n_errors": 0,
+ "evals": {
+ "agent__model___harbor-tasks": {
+ "n_trials": len(trial_names),
+ "n_errors": 0,
+ "reward_stats": {"reward": {"0.1": trial_names}},
+ }
+ },
+ },
+ }
+ ),
+ encoding="utf-8",
+ )
+
+
+def _write_trial(
+ jobs_dir: Path,
+ *,
+ variant: str,
+ trial_name: str,
+ reward: dict[str, Any],
+ trajectory: dict[str, Any] | str | None,
+) -> Path:
+ trial_dir = jobs_dir / f"demo-opencode-{variant}" / trial_name
+ verifier_dir = trial_dir / "verifier"
+ verifier_dir.mkdir(parents=True)
+ (verifier_dir / "reward.json").write_text(json.dumps(reward), encoding="utf-8")
+ if trajectory is not None:
+ agent_dir = trial_dir / "agent"
+ agent_dir.mkdir()
+ serialized = trajectory if isinstance(trajectory, str) else json.dumps(trajectory)
+ (agent_dir / "trajectory.json").write_text(serialized, encoding="utf-8")
+ return trial_dir
+
+
+def _collect(tmp_path: Path, *, skip_baseline: bool = True, expected_trials: int = 1) -> dict[str, Any]:
+ return collect_harbor_results(
+ skill_name="demo",
+ agents=["opencode"],
+ output_dir=tmp_path / "results",
+ jobs_dir=tmp_path / "jobs",
+ skip_baseline=skip_baseline,
+ expected_cases=expected_trials,
+ expected_trials=expected_trials,
+ )
+
+
+def _persisted_reward(tmp_path: Path, variant: str, trial_name: str) -> dict[str, Any]:
+ condition = "with-skill" if variant == "with" else "without-skill"
+ path = tmp_path / "results" / "opencode" / condition / "trials" / trial_name / "reward.json"
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def test_collect_persists_target_invocation_for_both_single_step_variants(tmp_path: Path) -> None:
+ jobs_dir = tmp_path / "jobs"
+ for variant, observed_skill in (("with", "demo"), ("without", "unrelated")):
+ trial_name = f"case-{variant}_attempt001"
+ _write_trial(
+ jobs_dir,
+ variant=variant,
+ trial_name=trial_name,
+ reward=dict(STANDARD_REWARD),
+ trajectory=_trajectory(skill=observed_skill),
+ )
+ _write_job_result(jobs_dir / f"demo-opencode-{variant}", [trial_name])
+
+ result = _collect(tmp_path, skip_baseline=False)
+
+ with_reward = _persisted_reward(tmp_path, "with", "case-with_attempt001")
+ without_reward = _persisted_reward(tmp_path, "without", "case-without_attempt001")
+ assert with_reward["skill_invoked"] is True
+ assert without_reward["skill_invoked"] is False
+ assert with_reward["invocation_evidence_source"] == "trajectory"
+ assert without_reward["invocation_evidence_source"] == "trajectory"
+ assert "routing_passed" not in with_reward
+ assert "routing_passed" not in without_reward
+ assert result["agents"]["opencode"]["with_skill"]["skill_execution"] == 0.4
+ assert result["agents"]["opencode"]["without_skill"]["skill_execution"] == 0.4
+ for variant, trial_name in (("with-skill", "case-with_attempt001"), ("without-skill", "case-without_attempt001")):
+ trial_dir = tmp_path / "results" / "opencode" / variant / "trials" / trial_name
+ assert {path.name for path in trial_dir.iterdir()} == {"reward.json", "trajectory.json"}
+
+
+def test_collect_persists_native_skill_tool_invocation(tmp_path: Path) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "native-skill_attempt001"
+ trajectory = _trajectory()
+ trajectory["steps"][0]["tool_calls"] = [
+ {
+ "tool_call_id": "call-1",
+ "function_name": "Skill",
+ "arguments": {"skill": "demo"},
+ }
+ ]
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=dict(STANDARD_REWARD),
+ trajectory=trajectory,
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ _collect(tmp_path)
+
+ reward = _persisted_reward(tmp_path, "with", trial_name)
+ assert reward["skill_invoked"] is True
+ assert reward["invocation_evidence_source"] == "trajectory"
+
+
[email protected]("variant", ("with", "without"))
+ ("fragments", "expected_invoked"),
+ [
+ (
+ (
+ ("prepare", _trajectory(skill="demo")),
+ ("finish", _trajectory(skill="unrelated")),
+ ),
+ True,
+ ),
+ (
+ (
+ ("prepare", _trajectory(skill="unrelated")),
+ ("finish", _trajectory()),
+ ),
+ False,
+ ),
+ (
+ (
+ ("prepare", _trajectory(skill="unrelated")),
+ ("missing", None),
+ ("malformed", "{not-json"),
+ ),
+ None,
+ ),
+ ],
+ ids=("any-step-invoked", "all-readable-not-invoked", "missing-and-malformed-unknown"),
+)
+def test_collect_derives_authoritative_multistep_invocation_for_both_variants(
+ tmp_path: Path,
+ variant: str,
+ fragments: tuple[tuple[str, dict[str, Any] | str | None], ...],
+ expected_invoked: bool | None,
+) -> None:
+ jobs_dir = tmp_path / "jobs"
+ job_dir = jobs_dir / f"demo-opencode-{variant}"
+ trial_name = f"case-multi-{variant}_attempt001"
+ trial_dir = job_dir / trial_name
+ step_results = []
+ for step_name, trajectory in fragments:
+ if trajectory is not None:
+ agent_dir = trial_dir / "steps" / step_name / "agent"
+ agent_dir.mkdir(parents=True)
+ serialized = trajectory if isinstance(trajectory, str) else json.dumps(trajectory)
+ (agent_dir / "trajectory.json").write_text(serialized, encoding="utf-8")
+ step_results.append(
+ {
+ "step_name": step_name,
+ "verifier_result": {"rewards": dict(STANDARD_REWARD)},
+ }
+ )
+ (trial_dir / "result.json").write_text(
+ json.dumps(
+ {
+ "trial_name": trial_name,
+ "task_name": "case-multi",
+ "verifier_result": {"rewards": dict(STANDARD_REWARD)},
+ "step_results": step_results,
+ }
+ ),
+ encoding="utf-8",
+ )
+ _write_job_result(job_dir, [trial_name])
+
+ _collect(tmp_path, skip_baseline=variant == "with")
+
+ reward = _persisted_reward(tmp_path, variant, trial_name)
+ if expected_invoked is None:
+ assert "skill_invoked" not in reward
+ assert "invocation_evidence_source" not in reward
+ else:
+ assert reward["skill_invoked"] is expected_invoked
+ assert reward["invocation_evidence_source"] == "trajectory"
+
+
+ "trial_result",
+ [None, "{not-json", "{}"],
+ ids=("missing-result", "malformed-result", "no-step-results"),
+)
+def test_collect_does_not_certify_root_non_invocation_when_step_layout_is_ambiguous(
+ tmp_path: Path,
+ trial_result: str | None,
+) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "ambiguous-steps_attempt001"
+ trial_dir = _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=dict(STANDARD_REWARD),
+ trajectory=_trajectory(),
+ )
+ step_agent_dir = trial_dir / "steps" / "invoke" / "agent"
+ step_agent_dir.mkdir(parents=True)
+ (step_agent_dir / "trajectory.json").write_text(json.dumps(_trajectory(skill="demo")), encoding="utf-8")
+ if trial_result is not None:
+ (trial_dir / "result.json").write_text(trial_result, encoding="utf-8")
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ assert "skill_invoked" not in persisted
+ assert "invocation_evidence_source" not in persisted
+
+
+def test_collect_replaces_spoofed_standard_evidence_and_leaves_unreadable_unknown(tmp_path: Path) -> None:
+ jobs_dir = tmp_path / "jobs"
+ spoofed = {
+ **STANDARD_REWARD,
+ "skill_invoked": True,
+ "routing_passed": True,
+ "invocation_evidence_source": "reward",
+ }
+ trajectories: tuple[tuple[str, dict[str, Any] | str | None], ...] = (
+ ("readable_attempt001", _trajectory(skill="unrelated")),
+ ("missing_attempt001", None),
+ ("malformed_attempt001", "{not-json"),
+ )
+ for trial_name, trajectory in trajectories:
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=dict(spoofed),
+ trajectory=trajectory,
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [name for name, _ in trajectories])
+
+ result = _collect(tmp_path, expected_trials=3)
+
+ readable = _persisted_reward(tmp_path, "with", "readable_attempt001")
+ assert readable["skill_invoked"] is False
+ assert readable["invocation_evidence_source"] == "trajectory"
+ assert "routing_passed" not in readable
+ for trial_name in ("missing_attempt001", "malformed_attempt001"):
+ reward = _persisted_reward(tmp_path, "with", trial_name)
+ assert "skill_invoked" not in reward
+ assert "routing_passed" not in reward
+ assert "invocation_evidence_source" not in reward
+ assert result["agents"]["opencode"]["with_skill"]["skill_execution"] == 0.4
+ assert result["agents"]["opencode"]["num_trials_with"] == 3
+
+
[email protected]("metric_set", ("skill-evaluator-default-v1", "skill-evaluator-default-v2"))
+def test_collect_replaces_spoofed_evidence_for_nested_standard_metrics(tmp_path: Path, metric_set: str) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "nested-standard_attempt001"
+ nested_reward = {
+ "metric_set": metric_set,
+ "metrics": {name: {"score": score} for name, score in STANDARD_REWARD.items()},
+ "skill_invoked": True,
+ "routing_passed": True,
+ "invocation_evidence_source": "reward",
+ }
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=nested_reward,
+ trajectory=_trajectory(skill="unrelated"),
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ result = _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ assert persisted["metrics"] == nested_reward["metrics"]
+ assert persisted["skill_invoked"] is False
+ assert persisted["invocation_evidence_source"] == "trajectory"
+ assert "routing_passed" not in persisted
+ assert result["agents"]["opencode"]["with_skill"]["skill_execution"] == 0.4
+
+
+ ("command", "expected_invoked"),
+ [
+ ("cat /workspace/skills/demo/SKILL.md", True),
+ ("cat /workspace/skills/demo/./SKILL.md", True),
+ ("cat /workspace/skills/demo//SKILL.md", True),
+ ("cat /workspace/skills/'demo'/SKILL.md", True),
+ (r"cat 'C:\skills\demo\SKILL.md'", True),
+ ("python /workspace/skills/demo/scripts/run.py", True),
+ ("cat /workspace/skills/demo-helper/SKILL.md", False),
+ ("printf demo", False),
+ ("echo /workspace/skills/demo/SKILL.md", False),
+ ("printf /workspace/skills/demo/SKILL.md", False),
+ ("echo /workspace/skills/demo/scripts/run.py", False),
+ ("printf ignored\ncat /workspace/skills/demo/SKILL.md", True),
+ ("echo ignored\npython /workspace/skills/demo/scripts/run.py", True),
+ ("/usr/bin/env python /workspace/skills/demo/scripts/run.py", True),
+ ("bash -c 'python /workspace/skills/demo/scripts/run.py'", True),
+ ("dash -c 'cat /workspace/skills/demo/SKILL.md'", True),
+ ("sh -c 'cat /workspace/skills/demo/SKILL.md'", True),
+ ("zsh -c 'command cat /workspace/skills/demo/SKILL.md'", True),
+ ("command cat /workspace/skills/demo/SKILL.md", True),
+ ("command env MODE=test cat /workspace/skills/demo/SKILL.md", True),
+ ("env MODE=test cat /workspace/skills/demo/SKILL.md", True),
+ ("env -i python /workspace/skills/demo/scripts/run.py", True),
+ ("source /workspace/skills/demo/scripts/run.sh", True),
+ (". /workspace/skills/demo/scripts/run.sh", True),
+ ("exec /workspace/skills/demo/scripts/run.sh", True),
+ ("exec python /workspace/skills/demo/scripts/run.py", True),
+ ("CONTENT=$(cat /workspace/skills/demo/SKILL.md)", True),
+ ("timeout 10 cat /workspace/skills/demo/SKILL.md", True),
+ ("nice python /workspace/skills/demo/scripts/run.py", True),
+ ("echo prep & cat /workspace/skills/demo/SKILL.md", True),
+ ('echo "$(cat /workspace/skills/demo/SKILL.md)"', True),
+ ("echo $(cat /workspace/skills/demo/SKILL.md)", True),
+ ('printf %s "$(cat /workspace/skills/demo/SKILL.md)"', True),
+ ("echo <(cat /workspace/skills/demo/SKILL.md)", True),
+ ("echo `cat /workspace/skills/demo/SKILL.md`", True),
+ ("P=/workspace/skills/demo; cat $P/SKILL.md", True),
+ ('P=/workspace/skills/demo; cat "${P}/SKILL.md"', True),
+ ("cd /workspace/skills/demo && cat SKILL.md", True),
+ ("sh -c -- 'cat /workspace/skills/demo/SKILL.md'", True),
+ ("bash -c -- 'python /workspace/skills/demo/scripts/run.py'", True),
+ ("bash -c 'echo /workspace/skills/demo/SKILL.md'", False),
+ ("dash -c 'echo /workspace/skills/demo/SKILL.md'", False),
+ ("bash -c 'echo /workspace/skills/demo/scripts/run.py'", False),
+ ("env -- echo /workspace/skills/demo/scripts/run.py", False),
+ ("env echo /workspace/skills/demo/scripts/run.py", False),
+ ("echo 'note\ncat /workspace/skills/demo/SKILL.md'", False),
+ ("echo /workspace/skills/demo/SKILL.md\nprintf /workspace/skills/demo/scripts/run.py", False),
+ ("CONTENT=$(printf /workspace/skills/demo/SKILL.md)", False),
+ ("timeout 10 echo /workspace/skills/demo/SKILL.md", False),
+ ("nice echo /workspace/skills/demo/scripts/run.py", False),
+ ("echo '$(cat /workspace/skills/demo/SKILL.md)'", False),
+ ("echo '`cat /workspace/skills/demo/SKILL.md`'", False),
+ ("P=/workspace/skills/demo; echo $P/SKILL.md", False),
+ ("cd /workspace/skills/demo && echo SKILL.md", False),
+ ],
+)
+def test_collect_shell_invocation_requires_exact_target_artifact_path(
+ tmp_path: Path,
+ command: str,
+ expected_invoked: bool,
+) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "shell_attempt001"
+ trajectory = _trajectory()
+ trajectory["steps"][0]["tool_calls"] = [
+ {
+ "tool_call_id": "call-1",
+ "function_name": "exec_command",
+ "arguments": {"cmd": command},
+ }
+ ]
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=dict(STANDARD_REWARD),
+ trajectory=trajectory,
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ assert persisted["skill_invoked"] is expected_invoked
+ assert persisted["invocation_evidence_source"] == "trajectory"
+
+
+ "command",
+ [
+ "echo " + " ".join(f"padding-{index}" for index in range(255)) + "; cat /skills/demo/SKILL.md",
+ "echo " + ("x" * 32_768) + "\ncat /skills/demo/SKILL.md",
+ _nested_shell_command("cat /skills/demo/SKILL.md", 3),
+ "mystery-wrapper cat /skills/demo/SKILL.md",
+ "cat /workspace/skills/dem?/SKILL.md",
+ "find /workspace/skills/demo -name SKILL.md -exec cat {} ';'",
+ "python -c \"print(open('/workspace/skills/demo/SKILL.md').read())\"",
+ ],
+ ids=(
+ "token-cap",
+ "character-cap",
+ "recursion-cap",
+ "unsupported-wrapper",
+ "glob-expansion",
+ "find-expansion",
+ "python-inline-open",
+ ),
+)
+def test_collect_omits_invocation_evidence_when_shell_parser_hits_a_bound(tmp_path: Path, command: str) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "bounded-shell_attempt001"
+ trajectory = _trajectory()
+ trajectory["steps"][0]["tool_calls"] = [
+ {
+ "tool_call_id": "call-1",
+ "function_name": "exec_command",
+ "arguments": {"cmd": command},
+ }
+ ]
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=dict(STANDARD_REWARD),
+ trajectory=trajectory,
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ assert "skill_invoked" not in persisted
+ assert "invocation_evidence_source" not in persisted
+
+
+ ("trajectory", "expected_invoked"),
+ [
+ ({"steps": []}, None),
+ ({"steps": [{"source": "user", "message": "request"}]}, None),
+ ({"steps": ["malformed"]}, None),
+ ({"steps": [{"source": "agent"}]}, None),
+ ({"steps": [{"source": "agent", "tool_calls": {}}]}, None),
+ ({"steps": [{"source": "agent", "tool_calls": [None]}]}, None),
+ ({"steps": [{"source": "agent", "tool_calls": [{}]}]}, None),
+ ({"steps": [{"source": "agent", "tool_calls": [{"function_name": " ", "arguments": {}}]}]}, None),
+ (
+ {
+ "steps": [
+ {
+ "source": "agent",
+ "tool_calls": [{"function_name": "Read", "arguments": "/skills/demo/SKILL.md"}],
+ }
+ ]
+ },
+ None,
+ ),
+ (
+ {
+ "steps": [
+ {"source": "agent", "tool_calls": []},
+ {"source": "agent", "tool_calls": [{"function_name": "Read", "arguments": []}]},
+ ]
+ },
+ None,
+ ),
+ (
+ {
+ "steps": [
+ {"source": "user", "message": "request"},
+ {"source": "agent", "message": "done", "tool_calls": []},
+ ]
+ },
+ False,
+ ),
+ ({"steps": [{"source": "agent", "message": "done", "tool_calls": []}]}, False),
+ ],
+ ids=(
+ "empty",
+ "user-only",
+ "malformed-step",
+ "missing-tool-calls",
+ "mapping-tool-calls",
+ "non-mapping-call",
+ "empty-call",
+ "blank-function-name",
+ "string-arguments",
+ "later-malformed-agent-call",
+ "valid-user-and-agent",
+ "valid-agent-no-tools",
+ ),
+)
+def test_collect_requires_structurally_valid_agent_trajectory_before_certifying_non_invocation(
+ tmp_path: Path,
+ trajectory: dict[str, Any],
+ expected_invoked: bool | None,
+) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "trajectory-shape_attempt001"
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=dict(STANDARD_REWARD),
+ trajectory=trajectory,
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ if expected_invoked is None:
+ assert "skill_invoked" not in persisted
+ assert "invocation_evidence_source" not in persisted
+ else:
+ assert persisted["skill_invoked"] is expected_invoked
+ assert persisted["invocation_evidence_source"] == "trajectory"
+
+
+ ("function_name", "arguments", "expected_invoked"),
+ [
+ ("open_file", {"file_path": "/workspace/skills/demo/SKILL.md"}, True),
+ ("mcp__filesystem__open_file", {"path": "/workspace/skills/demo/SKILL.md"}, True),
+ ("Grep", {"path": "/workspace/skills/demo/SKILL.md", "pattern": "name"}, True),
+ ("Read", {"filename": "/workspace/skills/demo/SKILL.md"}, True),
+ ("Read", {}, None),
+ ],
+)
+def test_collect_native_file_tool_evidence_is_exact_or_unknown(
+ tmp_path: Path,
+ function_name: str,
+ arguments: dict[str, Any],
+ expected_invoked: bool | None,
+) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "native-file-tool_attempt001"
+ trajectory = _trajectory()
+ trajectory["steps"][0]["tool_calls"] = [
+ {
+ "tool_call_id": "call-1",
+ "function_name": function_name,
+ "arguments": arguments,
+ }
+ ]
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=dict(STANDARD_REWARD),
+ trajectory=trajectory,
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ if expected_invoked is None:
+ assert "skill_invoked" not in persisted
+ assert "invocation_evidence_source" not in persisted
+ else:
+ assert persisted["skill_invoked"] is expected_invoked
+ assert persisted["invocation_evidence_source"] == "trajectory"
+
+
+def test_collect_ignores_non_agent_skill_tool_calls(tmp_path: Path) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "non-agent-skill-call_attempt001"
+ trajectory = {
+ "schema_version": "ATIF-v1.2",
+ "steps": [
+ {
+ "step_id": 1,
+ "source": "user",
+ "message": "Use demo",
+ "tool_calls": [
+ {
+ "tool_call_id": "call-user",
+ "function_name": "Skill",
+ "arguments": {"skill": "demo"},
+ }
+ ],
+ },
+ {
+ "step_id": 2,
+ "source": "agent",
+ "message": "Done",
+ "tool_calls": [],
+ },
+ ],
+ }
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=dict(STANDARD_REWARD),
+ trajectory=trajectory,
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ assert persisted["skill_invoked"] is False
+ assert persisted["invocation_evidence_source"] == "trajectory"
+
+
+def test_collect_leaves_custom_only_reward_and_artifacts_unchanged(tmp_path: Path) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "custom_attempt001"
+ custom_reward = {
+ "entry_id": "custom",
+ "overall": 0.75,
+ "custom_metrics": {"skill_execution": 0.25, "quality": 0.8},
+ "details": {"skill_execution": {"note": "custom data"}},
+ "skill_invoked": "verifier-owned",
+ "routing_passed": "verifier-owned",
+ "invocation_evidence_source": "custom-verifier",
+ }
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=custom_reward,
+ trajectory=_trajectory(skill="demo"),
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ result = _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ for key in ("custom_metrics", "details", "skill_invoked", "routing_passed", "invocation_evidence_source"):
+ assert persisted[key] == custom_reward[key]
+ agent = result["agents"]["opencode"]
+ assert agent["with_skill"] == {}
+ assert agent["custom_with_skill"] == {"quality": 0.8}
+ summary = json.loads(
+ (tmp_path / "results" / "opencode" / "with-skill" / "summary.json").read_text(encoding="utf-8")
+ )
+ assert summary["overall_score"] == 0.75
+ trial_dir = tmp_path / "results" / "opencode" / "with-skill" / "trials" / trial_name
+ assert {path.name for path in trial_dir.iterdir()} == {"reward.json", "trajectory.json"}
+
+
+ "custom_score_fields",
+ [
+ {"skill_execution": 0.25, "quality": 0.8},
+ {"custom_metrics": {"skill_execution": 0.25, "quality": 0.8}},
+ ],
+ ids=("top-level", "nested"),
+)
+def test_collect_respects_explicit_custom_metric_set_with_standard_named_metric(
+ tmp_path: Path,
+ custom_score_fields: dict[str, Any],
+) -> None:
+ jobs_dir = tmp_path / "jobs"
+ trial_name = "explicit_custom_attempt001"
+ custom_reward = {
+ "entry_id": "custom",
+ "metric_set": "custom-only",
+ "overall": 0.75,
+ **custom_score_fields,
+ "skill_invoked": "custom-verifier-value",
+ "routing_passed": "custom-verifier-value",
+ "invocation_evidence_source": "custom-verifier",
+ }
+ _write_trial(
+ jobs_dir,
+ variant="with",
+ trial_name=trial_name,
+ reward=custom_reward,
+ trajectory=_trajectory(),
+ )
+ _write_job_result(jobs_dir / "demo-opencode-with", [trial_name])
+
+ _collect(tmp_path)
+
+ persisted = _persisted_reward(tmp_path, "with", trial_name)
+ for key, expected in custom_reward.items():
+ assert persisted[key] == expected
diff --git a/tests/tier3/test_judge_failure_artifacts.py b/tests/tier3/test_judge_failure_artifacts.py
index 563ae65a..e38d1775 100644
--- a/tests/tier3/test_judge_failure_artifacts.py
+++ b/tests/tier3/test_judge_failure_artifacts.py
@@ -78,6 +78,7 @@ def _load_verifier(tmp_path: Path) -> ModuleType:
"ground_truth": "The task is complete.",
"expected_behavior": ["Complete the task"],
"should_trigger": False,
+ "evaluated_skill": "demo",
"has_skill": True,
}
),
diff --git a/tests/tier3/test_negative_control_invocation_evidence.py b/tests/tier3/test_negative_control_invocation_evidence.py
new file mode 100644
index 00000000..a6536483
--- /dev/null
+++ b/tests/tier3/test_negative_control_invocation_evidence.py
@@ -0,0 +1,516 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+# SPDX-License-Identifier: Apache-2.0
+
+"""Trusted invocation evidence for Tier 3 negative-control cases."""
+
+from __future__ import annotations
+
+import importlib.util
+import json
+import shlex
+from pathlib import Path
+
+import pytest
+
+from skillevaluator.tier3.eval_core import checks as shared_checks
+
+
+def _load_template():
+ template_path = Path(__file__).parents[2] / "src/skillevaluator/tier3/harbor/templates/eval.py"
+ spec = importlib.util.spec_from_file_location("harbor_eval_negative_control", template_path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+TEMPLATE = _load_template()
+
+
+def _nested_shell_command(command: str, depth: int) -> str:
+ for _ in range(depth):
+ command = shlex.join(["bash", "-c", command])
+ return command
+
+
+ ("entry", "expected"),
+ [
+ ({"expected_skill": "target", "should_trigger": False}, False),
+ ({"expected_skill": None, "should_trigger": True}, True),
+ ({"expected_skill": "target"}, True),
+ ({"expected_skill": None}, False),
+ ({}, None),
+ ],
+)
+def test_routing_tri_state_preserves_explicit_precedence_and_legacy_unlabeled(entry, expected) -> None:
+ assert shared_checks.resolve_should_trigger(entry) is expected
+ assert TEMPLATE.resolve_should_trigger(entry) is expected
+
+
+TARGET_READ = [
+ {
+ "action": "Read",
+ "action_input": {"file_path": "/workspace/skills/trusted-target/SKILL.md"},
+ "observation": "# Trusted target",
+ }
+]
+OTHER_READ = [
+ {
+ "action": "Read",
+ "action_input": {"file_path": "/workspace/skills/other/SKILL.md"},
+ "observation": "# Other",
+ }
+]
+
+
+ ("tool_calls", "skill_tool_names", "expected_passed"),
+ [
+ ([], ["demo"], False),
+ ([], ["DEMO"], False),
+ ([], ["demo-helper"], True),
+ (
+ [
+ {
+ "action": "Read",
+ "action_input": {"file_path": "/workspace/skills/demo/SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {
+ "action": "Read",
+ "action_input": {"file_path": "/workspace/skills/demo-helper/SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {
+ "action": "Read",
+ "action_input": {"file_path": "/workspace/skills/demo/subdir/SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {
+ "action": "Read",
+ "action_input": {"file_path": "/workspace/skills/demo/SKILL.md/notes"},
+ "observation": "",
+ }
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {
+ "action": "Read",
+ "action_input": {"file_path": "/workspace/skills/other/../demo/./SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "cat /workspace/skills/demo/SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "cat /workspace/skills/demo/./SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "cat /workspace/skills/demo//SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "cat /workspace/skills/'demo'/SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": r"cat 'C:\skills\demo\SKILL.md'"},
+ "observation": "",
+ }
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "python /workspace/skills/demo/scripts/run.py"},
+ "observation": "",
+ }
+ ],
+ None,
+ False,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "echo /workspace/skills/demo/SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "printf /workspace/skills/demo/SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "echo /workspace/skills/demo/scripts/run.py"},
+ "observation": "",
+ }
+ ],
+ None,
+ True,
+ ),
+ (
+ [
+ {
+ "action": "exec_command",
+ "action_input": {"cmd": "cat /workspace/skills/demo-helper/SKILL.md"},
+ "observation": "",
+ }
+ ],
+ None,
+ True,
+ ),
+ (
+ [{"action": "exec_command", "action_input": {"cmd": "printf demo"}, "observation": ""}],
+ None,
+ True,
+ ),
+ ],
+)
+def test_negative_case_requires_exact_target_reference(tool_calls, skill_tool_names, expected_passed) -> None:
+ shared = shared_checks.check_negative_case(tool_calls, "demo", skill_tool_names=skill_tool_names)
+ template = TEMPLATE.check_negative_case(tool_calls, "demo", skill_tool_names=skill_tool_names)
+
+ assert shared == template
+ assert shared["passed"] is expected_passed
+
+
+ ("action", "arguments", "expected_passed"),
+ [
+ ("open_file", {"file_path": "/workspace/skills/demo/SKILL.md"}, False),
+ ("mcp__filesystem__open_file", {"path": "/workspace/skills/demo/SKILL.md"}, False),
+ ("Grep", {"path": "/workspace/skills/demo/SKILL.md", "pattern": "name"}, False),
+ ("Read", {"filename": "/workspace/skills/demo/SKILL.md"}, False),
+ ("Read", {}, None),
+ ("Read", {"file_path": "/workspace/skills/other/SKILL.md"}, True),
+ ],
+)
+def test_negative_case_native_file_tools_are_exact_or_unknown(action, arguments, expected_passed) -> None:
+ tool_calls = [{"action": action, "action_input": arguments, "observation": ""}]
+
+ shared = shared_checks.check_negative_case(tool_calls, "demo")
+ template = TEMPLATE.check_negative_case(tool_calls, "demo")
+
+ assert shared == template
+ assert shared["passed"] is expected_passed
+
+
+ ("command", "expected_passed"),
+ [
+ ("printf ignored\ncat /workspace/skills/demo/SKILL.md", False),
+ ("echo ignored\npython /workspace/skills/demo/scripts/run.py", False),
+ ("/usr/bin/env python /workspace/skills/demo/scripts/run.py", False),
+ ("bash -c 'python /workspace/skills/demo/scripts/run.py'", False),
+ ("dash -c 'cat /workspace/skills/demo/SKILL.md'", False),
+ ("sh -c 'cat /workspace/skills/demo/SKILL.md'", False),
+ ("zsh -c 'command cat /workspace/skills/demo/SKILL.md'", False),
+ ("command cat /workspace/skills/demo/SKILL.md", False),
+ ("command env MODE=test cat /workspace/skills/demo/SKILL.md", False),
+ ("env MODE=test cat /workspace/skills/demo/SKILL.md", False),
+ ("env -i python /workspace/skills/demo/scripts/run.py", False),
+ ("source /workspace/skills/demo/scripts/run.sh", False),
+ (". /workspace/skills/demo/scripts/run.sh", False),
+ ("exec /workspace/skills/demo/scripts/run.sh", False),
+ ("exec python /workspace/skills/demo/scripts/run.py", False),
+ ("CONTENT=$(cat /workspace/skills/demo/SKILL.md)", False),
+ ("timeout 10 cat /workspace/skills/demo/SKILL.md", False),
+ ("nice python /workspace/skills/demo/scripts/run.py", False),
+ ("echo prep & cat /workspace/skills/demo/SKILL.md", False),
+ ('echo "$(cat /workspace/skills/demo/SKILL.md)"', False),
+ ("echo $(cat /workspace/skills/demo/SKILL.md)", False),
+ ('printf %s "$(cat /workspace/skills/demo/SKILL.md)"', False),
+ ("echo <(cat /workspace/skills/demo/SKILL.md)", False),
+ ("echo `cat /workspace/skills/demo/SKILL.md`", False),
+ ("P=/workspace/skills/demo; cat $P/SKILL.md", False),
+ ('P=/workspace/skills/demo; cat "${P}/SKILL.md"', False),
+ ("cd /workspace/skills/demo && cat SKILL.md", False),
+ ("sh -c -- 'cat /workspace/skills/demo/SKILL.md'", False),
+ ("bash -c -- 'python /workspace/skills/demo/scripts/run.py'", False),
+ ("bash -c 'echo /workspace/skills/demo/SKILL.md'", True),
+ ("dash -c 'echo /workspace/skills/demo/SKILL.md'", True),
+ ("bash -c 'echo /workspace/skills/demo/scripts/run.py'", True),
+ ("env -- echo /workspace/skills/demo/scripts/run.py", True),
+ ("env echo /workspace/skills/demo/scripts/run.py", True),
+ ("echo 'note\ncat /workspace/skills/demo/SKILL.md'", True),
+ ("echo /workspace/skills/demo/SKILL.md\nprintf /workspace/skills/demo/scripts/run.py", True),
+ ("CONTENT=$(printf /workspace/skills/demo/SKILL.md)", True),
+ ("timeout 10 echo /workspace/skills/demo/SKILL.md", True),
+ ("nice echo /workspace/skills/demo/scripts/run.py", True),
+ ("echo '$(cat /workspace/skills/demo/SKILL.md)'", True),
+ ("echo '`cat /workspace/skills/demo/SKILL.md`'", True),
+ ("P=/workspace/skills/demo; echo $P/SKILL.md", True),
+ ("cd /workspace/skills/demo && echo SKILL.md", True),
+ ],
+)
+def test_negative_case_shell_parser_handles_wrappers_and_multiline_commands(command, expected_passed) -> None:
+ tool_calls = [{"action": "exec_command", "action_input": {"cmd": command}, "observation": ""}]
+
+ shared = shared_checks.check_negative_case(tool_calls, "demo")
+ template = TEMPLATE.check_negative_case(tool_calls, "demo")
+
+ assert shared == template
+ assert shared["passed"] is expected_passed
+
+
+ "command",
+ [
+ "echo " + " ".join(f"padding-{index}" for index in range(255)) + "; cat /skills/demo/SKILL.md",
+ "echo " + ("x" * 32_768) + "\ncat /skills/demo/SKILL.md",
+ _nested_shell_command("cat /skills/demo/SKILL.md", 3),
+ "mystery-wrapper cat /skills/demo/SKILL.md",
+ "cat /workspace/skills/dem?/SKILL.md",
+ "find /workspace/skills/demo -name SKILL.md -exec cat {} ';'",
+ "python -c \"print(open('/workspace/skills/demo/SKILL.md').read())\"",
+ ],
+ ids=(
+ "token-cap",
+ "character-cap",
+ "recursion-cap",
+ "unsupported-wrapper",
+ "glob-expansion",
+ "find-expansion",
+ "python-inline-open",
+ ),
+)
+def test_negative_case_shell_parser_caps_are_unknown(command: str) -> None:
+ tool_calls = [{"action": "exec_command", "action_input": {"cmd": command}, "observation": ""}]
+
+ shared = shared_checks.check_negative_case(tool_calls, "demo")
+ template = TEMPLATE.check_negative_case(tool_calls, "demo")
+
+ assert shared == template
+ assert shared["passed"] is None
+ assert shared["score"] == 0.0
+
+
+ ("tool_calls", "expected_score"),
+ [(TARGET_READ, 0.0), (OTHER_READ, 1.0), ([], 1.0)],
+)
+def test_explicit_negative_scores_only_trusted_target_invocation(tool_calls, expected_score) -> None:
+ kwargs = {
+ "tool_calls": tool_calls,
+ "expected_skill": "authored-spoof",
+ "should_trigger": False,
+ "evaluated_skill": "trusted-target",
+ }
+
+ shared = shared_checks.score_skill_execution(**kwargs)
+ template = TEMPLATE.score_skill_execution(**kwargs)
+
+ assert shared == template
+ assert shared["score"] == expected_score
+
+
+def test_explicit_negative_without_trusted_identity_fails_closed() -> None:
+ kwargs = {
+ "tool_calls": OTHER_READ,
+ "expected_skill": "",
+ "should_trigger": False,
+ "evaluated_skill": "",
+ "require_evaluated_skill": True,
+ }
+
+ shared = shared_checks.score_skill_execution(**kwargs)
+ template = TEMPLATE.score_skill_execution(**kwargs)
+
+ assert shared == template
+ assert shared["score"] == 0.0
+ assert "trusted evaluated_skill" in shared["details"]["message"]
+
+
+def test_legacy_direct_negative_uses_expected_skill_compatibly() -> None:
+ kwargs = {
+ "tool_calls": [],
+ "expected_skill": "demo",
+ "should_trigger": False,
+ }
+
+ shared = shared_checks.score_skill_execution(**kwargs)
+ template = TEMPLATE.score_skill_execution(**kwargs)
+
+ assert shared == template
+ assert shared["score"] == 1.0
+ assert shared["details"]["negative_check"]["score"] == 1.0
+
+
+def test_legacy_unlabeled_case_retains_skip_pass_behavior() -> None:
+ kwargs = {
+ "tool_calls": TARGET_READ,
+ "expected_skill": "",
+ "should_trigger": None,
+ "evaluated_skill": "",
+ }
+
+ shared = shared_checks.score_skill_execution(**kwargs)
+ template = TEMPLATE.score_skill_execution(**kwargs)
+
+ assert shared == template
+ assert shared["score"] == 1.0
+ assert "skipped" in shared["details"]["message"].lower()
+
+
+def test_positive_scoring_ignores_evaluated_skill_and_remains_unchanged() -> None:
+ kwargs = {
+ "tool_calls": TARGET_READ,
+ "expected_skill": "trusted-target",
+ "should_trigger": True,
+ }
+
+ baseline = shared_checks.score_skill_execution(**kwargs)
+ with_unrelated_identity = shared_checks.score_skill_execution(**kwargs, evaluated_skill="different-target")
+ template = TEMPLATE.score_skill_execution(**kwargs, evaluated_skill="different-target")
+
+ assert with_unrelated_identity == baseline
+ assert template == baseline
+ assert baseline["score"] == 1.0
+
+
[email protected]("include_trusted_identity", (True, False), ids=("trusted", "missing-fail-closed"))
+def test_template_main_scores_standard_negative_fail_closed(tmp_path, monkeypatch, include_trusted_identity) -> None:
+ entry_path = tmp_path / "entry.json"
+ trajectory_path = tmp_path / "trajectory.json"
+ reward_json = tmp_path / "reward.json"
+ rich_reward_json = tmp_path / "skill_evaluator_reward.json"
+ reward_txt = tmp_path / "reward.txt"
+ entry = {
+ "id": "negative-001",
+ "question": "Answer without using the target skill",
+ "expected_skill": None,
+ }
+ if include_trusted_identity:
+ entry["evaluated_skill"] = "trusted-target"
+ entry_path.write_text(json.dumps(entry), encoding="utf-8")
+ trajectory_path.write_text(
+ json.dumps(
+ {
+ "steps": [
+ {
+ "source": "agent",
+ "message": "Done",
+ "tool_calls": [
+ {
+ "tool_call_id": "read-1",
+ "function_name": "Read",
+ "arguments": {"file_path": "/workspace/skills/trusted-target/SKILL.md"},
+ }
+ ],
+ "observation": {"results": [{"source_call_id": "read-1", "content": "# Trusted target"}]},
+ }
+ ]
+ }
+ ),
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(TEMPLATE, "ENTRY_PATH", entry_path)
+ monkeypatch.setattr(TEMPLATE, "ATIF_PATH", trajectory_path)
+ monkeypatch.setattr(TEMPLATE, "REWARD_JSON", reward_json)
+ monkeypatch.setattr(TEMPLATE, "SKILL_EVALUATOR_REWARD_JSON", rich_reward_json)
+ monkeypatch.setattr(TEMPLATE, "REWARD_TXT", reward_txt)
+
+ def passing_judge(*_args, **_kwargs):
+ return {"score": 1.0}
+
+ monkeypatch.setattr(TEMPLATE, "judge_accuracy", passing_judge)
+ monkeypatch.setattr(TEMPLATE, "judge_goal_accuracy", passing_judge)
+ monkeypatch.setattr(TEMPLATE, "judge_behavior_check", passing_judge)
+
+ TEMPLATE.main()
+
+ result = json.loads(rich_reward_json.read_text(encoding="utf-8"))
+ harbor_reward = json.loads(reward_json.read_text(encoding="utf-8"))
+ expected_reward_keys = {*TEMPLATE.DISPLAY_METRICS, "overall"}
+ expected_overall = round(
+ sum(float(result.get(metric, 0.0) or 0.0) for metric in TEMPLATE.DISPLAY_METRICS)
+ / len(TEMPLATE.DISPLAY_METRICS),
+ 4,
+ )
+
+ assert result["skill_execution"] == 0.0
+ if include_trusted_identity:
+ assert result["details"]["skill_execution"]["negative_check"]["score"] == 0.0
+ else:
+ assert "trusted evaluated_skill" in result["details"]["skill_execution"]["message"]
+ assert set(harbor_reward) == expected_reward_keys
+ assert all(isinstance(value, (int, float)) and not isinstance(value, bool) for value in harbor_reward.values())
+ assert harbor_reward["skill_execution"] == 0.0
+ assert harbor_reward["overall"] == expected_overall
+ assert float(reward_txt.read_text(encoding="utf-8")) == expected_overall