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): ground negative-control insights

rookepoole829ea30e416b
diff --git a/src/skillevaluator/evaluation/insights_judge.py b/src/skillevaluator/evaluation/insights_judge.py
index 63278d39..8bc3ed41 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 re
from typing import Any
from skillevaluator.constants import (
@@ -44,6 +45,21 @@ _VALID_RECOMMENDATION_CATEGORIES = {
"Improve",
"Action",
}
+_NEGATIVE_CONTROL_CLAIM_PHRASES = (
+ "unintended skill application",
+ "unexpected skill application",
+ "unintended skill activation",
+ "unexpected skill activation",
+ "scope misalignment",
+ "overfitting",
+ "overfit",
+)
+_IRRELEVANT_CASE_REMOVAL_RE = re.compile(
+ r"\b(?:exclude|remove|drop|delete|eliminate)\b.{0,80}"
+ r"\b(?:irrelevant|unrelated|out[- ]of[- ]scope)\b.{0,80}"
+ r"\b(?:case|cases|test|tests|query|queries|prompt|prompts|dataset)\b",
+ re.IGNORECASE,
+)
_SYSTEM_PROMPT = """\
@@ -69,6 +85,9 @@ NEGATIVE-CONTROL INTERPRETATION:
- A dataset case whose expected_skill is null is an intentional negative
control: the agent should complete the unrelated task without activating
the evaluated skill.
+- An explicit should_trigger value takes precedence over expected_skill, just
+ as it does in the runtime grader. Otherwise, a falsey expected_skill marks a
+ negative control; a case with neither routing field is unlabeled.
- A successful negative-control case is correct routing behavior. Do not infer
unintended skill application, scope misalignment, or overfitting merely
because the agent answered the unrelated task correctly.
@@ -78,6 +97,11 @@ 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.
+- Any conclusion or recommendation alleging unintended skill use, scope
+ misalignment, overfitting, or removal of an irrelevant case MUST include the
+ affected case ids in evidence_case_ids. Such a claim is valid only when the
+ supplied context shows failed routing or explicit invocation evidence for at
+ least one of those negative-control cases.
Your job is to produce ADDITIONAL, contextual insights:
@@ -100,10 +124,10 @@ this exact schema:
{{
\"conclusions\": [
- {{\"title\": \"<short title>\", \"message\": \"<1-2 sentences>\", \"severity\": \"pass|warn|fail\"}}
+ {{\"title\": \"<short title>\", \"message\": \"<1-2 sentences>\", \"severity\": \"pass|warn|fail\", \"evidence_case_ids\": [\"<case id>\"]}}
],
\"recommendations\": [
- {{\"category\": \"<one of the allowed categories>\", \"title\": \"<short title>\", \"message\": \"<one imperative sentence>\", \"severity\": \"pass|warn|fail\"}}
+ {{\"category\": \"<one of the allowed categories>\", \"title\": \"<short title>\", \"message\": \"<one imperative sentence>\", \"severity\": \"pass|warn|fail\", \"evidence_case_ids\": [\"<case id>\"]}}
]
}}
""".format(
@@ -145,36 +169,94 @@ def _summarize_evaluators(evaluators: dict) -> dict:
return out
-def _summarize_trials(trials: list[dict]) -> list[dict]:
- """Pick a representative slice of trials for the prompt."""
- if not trials:
- return []
+def _case_routing(case: dict) -> tuple[str, bool | None]:
+ """Mirror the runtime grader's routing precedence for prompt metadata."""
+ if "should_trigger" in case:
+ should_trigger = bool(case.get("should_trigger"))
+ elif "expected_skill" in case:
+ should_trigger = bool(case.get("expected_skill"))
+ else:
+ return "unlabeled", None
+ return ("skill_activation", True) if should_trigger else ("negative_control", False)
+
+
+def _summarize_case(case: dict) -> dict:
+ case_type, skill_expected_to_activate = _case_routing(case)
+ expected_behavior = case.get("expected_behavior")
+ if isinstance(expected_behavior, list):
+ expected_behavior = [str(item)[:300] for item in expected_behavior[:5]]
+ elif isinstance(expected_behavior, str):
+ expected_behavior = expected_behavior[:300]
+ else:
+ expected_behavior = None
+
+ return {
+ "id": case.get("id"),
+ "case_type": case_type,
+ "skill_expected_to_activate": skill_expected_to_activate,
+ "question": (case.get("question") or "")[:300],
+ "ground_truth": (case.get("ground_truth") or "")[:300],
+ "expected_skill": case.get("expected_skill"),
+ "should_trigger": case.get("should_trigger") if "should_trigger" in case else None,
+ "expected_script": case.get("expected_script"),
+ "expected_behavior": expected_behavior,
+ }
+
+
+def _case_lookup(dataset: list[dict]) -> dict[str, dict]:
+ lookup: dict[str, dict] = {}
+ for case in dataset or []:
+ if not isinstance(case, dict) or case.get("id") is None:
+ continue
+ lookup.setdefault(str(case["id"]), case)
+ return lookup
- # Sort by overall score so failures and successes both appear.
- def _key(t: dict) -> float:
- overall = t.get("overall")
- return overall if isinstance(overall, (int, float)) else 0.5
- sorted_trials = sorted(trials, key=_key)
- chosen: list[dict] = sorted_trials[:3] + sorted_trials[-3:]
- seen: set[str] = set()
+def _summarize_trials(trials: list[dict], cases_by_id: dict[str, dict] | None = None) -> list[dict]:
+ """Pick a representative slice without collapsing agents or attempts."""
+ if not trials:
+ return []
+ cases_by_id = cases_by_id or {}
+
+ def _key(indexed_trial: tuple[int, dict]) -> tuple[float, int]:
+ index, trial = indexed_trial
+ overall = trial.get("overall")
+ score = overall if isinstance(overall, (int, float)) else 0.5
+ return score, index
+
+ 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:]
+
+ attempt_counts: dict[tuple[str, str], int] = {}
+ attempts_by_index: dict[int, int | str] = {}
+ for index, trial in indexed_trials:
+ identity = (str(trial.get("agent") or ""), str(trial.get("entry_id") or ""))
+ attempt_counts[identity] = attempt_counts.get(identity, 0) + 1
+ attempts_by_index[index] = trial.get("attempt") or attempt_counts[identity]
+
+ seen_indices: set[int] = set()
compact: list[dict] = []
- for trial in chosen:
- tid = str(trial.get("trial_id") or trial.get("entry_id") or "")
- if tid in seen:
+ for index, trial in chosen:
+ if index in seen_indices:
continue
- seen.add(tid)
+ seen_indices.add(index)
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"),
- "entry_id": trial.get("entry_id"),
+ "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 len(compact) >= 6:
@@ -184,39 +266,23 @@ def _summarize_trials(trials: list[dict]) -> list[dict]:
def _summarize_dataset(dataset: list[dict]) -> list[dict]:
"""Trim dataset cases to the question + ground truth (plus id)."""
- summary: list[dict] = []
- for case in (dataset or [])[:5]:
- if "expected_skill" not in case:
- case_type = "unlabeled"
- skill_expected_to_activate = None
- elif case.get("expected_skill") is None:
- case_type = "negative_control"
- skill_expected_to_activate = False
- else:
- case_type = "skill_activation"
- skill_expected_to_activate = True
-
- expected_behavior = case.get("expected_behavior")
- if isinstance(expected_behavior, list):
- expected_behavior = [str(item)[:300] for item in expected_behavior[:5]]
- elif isinstance(expected_behavior, str):
- expected_behavior = expected_behavior[:300]
- else:
- expected_behavior = None
+ return [_summarize_case(case) for case in (dataset or [])[:5] if isinstance(case, dict)]
- summary.append(
- {
- "id": case.get("id"),
- "case_type": case_type,
- "skill_expected_to_activate": skill_expected_to_activate,
- "question": (case.get("question") or "")[:300],
- "ground_truth": (case.get("ground_truth") or "")[:300],
- "expected_skill": case.get("expected_skill"),
- "expected_script": case.get("expected_script"),
- "expected_behavior": expected_behavior,
- }
- )
- return summary
+
+def _dataset_for_sampled_trials(trials: list[dict], dataset: list[dict]) -> list[dict]:
+ """Keep one copy of every case joined to a sampled trial, in trial order."""
+ summary: list[dict] = []
+ seen: set[str] = set()
+ for trial in trials:
+ case = trial.get("case")
+ if not isinstance(case, dict) or case.get("id") is None:
+ continue
+ case_id = str(case["id"])
+ if case_id in seen:
+ continue
+ seen.add(case_id)
+ summary.append(case)
+ return summary or _summarize_dataset(dataset)
def _coerce_severity(value: Any) -> str:
@@ -235,6 +301,81 @@ def _coerce_category(value: Any) -> str:
return "Action"
+def _requires_negative_control_evidence(item: dict) -> bool:
+ text = f"{item.get('title') or ''} {item.get('message') or ''}"[:2_000]
+ lowered = text.casefold()
+ return any(phrase in lowered for phrase in _NEGATIVE_CONTROL_CLAIM_PHRASES) or bool(
+ _IRRELEVANT_CASE_REMOVAL_RE.search(text)
+ )
+
+
+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] = {}
+ 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)
+ if should_trigger is False:
+ evidence[case_id] = False
+
+ 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:
+ 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:
+ evidence[case_id] = True
+ return evidence, known_case_ids
+
+
+def _referenced_case_ids(item: dict, known_case_ids: set[str]) -> set[str]:
+ references: set[str] = set()
+ raw_references = item.get("evidence_case_ids")
+ if isinstance(raw_references, list):
+ references.update(str(value) for value in raw_references[:10] if value is not None)
+
+ 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 _unsupported_negative_control_claim(
+ item: dict,
+ grounding: tuple[dict[str, bool], set[str]],
+) -> bool:
+ evidence, known_case_ids = grounding
+ if not evidence or not _requires_negative_control_evidence(item):
+ return False
+
+ references = _referenced_case_ids(item, known_case_ids)
+ if not references or any(case_id not in known_case_ids for case_id in references):
+ return True
+
+ negative_references = references.intersection(evidence)
+ if not negative_references:
+ return False
+ return not any(evidence[case_id] for case_id in negative_references)
+
+
class InsightsJudge(LLMClient):
"""LLM judge that produces additional conclusions and recommendations."""
@@ -248,6 +389,8 @@ class InsightsJudge(LLMClient):
def create_user_prompt(self, **kwargs: Any) -> str:
canonical: dict = kwargs.get("canonical") or {}
deterministic: dict = kwargs.get("deterministic") or {}
+ dataset = canonical.get("dataset") or []
+ trials = _summarize_trials(canonical.get("trials") or [], _case_lookup(dataset))
prompt: dict = {
"skill": {
@@ -261,8 +404,8 @@ class InsightsJudge(LLMClient):
},
"dimensions": _summarize_dimensions(canonical.get("dimensions") or []),
"best_agent_evaluators": _summarize_evaluators(canonical.get("evaluators") or {}),
- "trials": _summarize_trials(canonical.get("trials") or []),
- "dataset": _summarize_dataset(canonical.get("dataset") or []),
+ "trials": trials,
+ "dataset": _dataset_for_sampled_trials(trials, dataset),
"deterministic_observations": {
"conclusions": [
{
@@ -282,7 +425,7 @@ class InsightsJudge(LLMClient):
+ json.dumps(prompt, indent=2, default=str)
)
- def parse_response(self, response_text: str, **_kwargs: Any) -> dict:
+ def parse_response(self, response_text: str, **kwargs: Any) -> dict:
content = response_text.strip().lstrip("\ufeff")
if content.startswith("```"):
content = content.split("\n", 1)[1]
@@ -290,11 +433,15 @@ class InsightsJudge(LLMClient):
data = json.loads(content)
if not isinstance(data, dict):
raise ValueError(f"Expected JSON object, got {type(data).__name__}")
+ canonical = kwargs.get("canonical") if isinstance(kwargs.get("canonical"), dict) else {}
+ grounding = _negative_control_grounding(canonical)
conclusions: list[dict] = []
for item in (data.get("conclusions") or [])[:INSIGHTS_JUDGE_MAX_CONCLUSIONS]:
if not isinstance(item, dict):
continue
+ if _unsupported_negative_control_claim(item, grounding):
+ continue
title = (item.get("title") or "").strip()
message = (item.get("message") or "").strip()
if not title and not message:
@@ -312,6 +459,8 @@ class InsightsJudge(LLMClient):
for item in (data.get("recommendations") or [])[:INSIGHTS_JUDGE_MAX_RECOMMENDATIONS]:
if not isinstance(item, dict):
continue
+ if _unsupported_negative_control_claim(item, grounding):
+ continue
title = (item.get("title") or "").strip()
message = (item.get("message") or "").strip()
if not title and not message:
diff --git a/tests/evaluation/test_judges.py b/tests/evaluation/test_judges.py
index f033a713..0985bf7b 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.tier3.dataset_utils import normalize_dataset_entries
@pytest.fixture
@@ -153,3 +154,247 @@ class TestInsightsJudgeNegativeControls:
assert "explicit execution evidence" in prompt
assert "invocation evidence is absent or ambiguous" in prompt
assert "Do not recommend removing an unrelated negative-control case" in prompt
+
+ def test_prompt_uses_runtime_should_trigger_precedence_for_agentskills_cases(self) -> None:
+ dataset = normalize_dataset_entries(
+ {
+ "skill_name": "calculator",
+ "evals": [
+ {
+ "id": "negative-001",
+ "prompt": "Answer without the calculator skill.",
+ "should_trigger": False,
+ },
+ {
+ "id": "positive-001",
+ "prompt": "Use the calculator skill.",
+ },
+ ],
+ }
+ )
+
+ prompt = InsightsJudge().create_user_prompt(canonical={"dataset": dataset}, deterministic={})
+ context = json.loads(prompt.split("\n\n", 1)[1])
+
+ assert [case["case_type"] for case in context["dataset"]] == [
+ "negative_control",
+ "skill_activation",
+ ]
+ assert [case["skill_expected_to_activate"] for case in context["dataset"]] == [False, True]
+
+ @pytest.mark.parametrize(
+ "case",
+ [
+ {"id": "negative-null", "expected_skill": None},
+ {"id": "negative-empty", "expected_skill": ""},
+ {"id": "negative-explicit", "expected_skill": "calculator", "should_trigger": False},
+ ],
+ )
+ def test_prompt_uses_runtime_routing_semantics_for_legacy_cases(self, case: dict) -> None:
+ prompt = InsightsJudge().create_user_prompt(canonical={"dataset": [case]}, deterministic={})
+ context = json.loads(prompt.split("\n\n", 1)[1])
+
+ assert context["dataset"][0]["case_type"] == "negative_control"
+ 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)
+ ] + [
+ {
+ "id": "negative-006",
+ "expected_skill": None,
+ "expected_behavior": ["Do not invoke the calculator skill"],
+ }
+ ]
+ trials = [
+ {
+ "agent": "codex",
+ "entry_id": case["id"],
+ "overall": index / 10,
+ "scores": {"skill_execution": 1.0},
+ }
+ for index, case in enumerate(dataset, start=1)
+ ]
+
+ prompt = InsightsJudge().create_user_prompt(
+ canonical={"dataset": dataset, "trials": trials},
+ deterministic={},
+ )
+ context = json.loads(prompt.split("\n\n", 1)[1])
+
+ sampled = next(trial for trial in context["trials"] if trial["entry_id"] == "negative-006")
+ assert sampled["case"]["case_type"] == "negative_control"
+ assert sampled["case"]["expected_behavior"] == ["Do not invoke the calculator skill"]
+ assert "negative-006" in {case["id"] for case in context["dataset"]}
+
+ def test_trial_sampling_preserves_multi_agent_and_attempt_identity_without_trial_ids(self) -> None:
+ trials = [
+ {"agent": "codex", "entry_id": "shared", "trial_id": None, "overall": 0.1},
+ {"agent": "codex", "entry_id": "shared", "trial_id": None, "overall": 0.2},
+ {"agent": "claude-code", "entry_id": "shared", "trial_id": None, "overall": 0.3},
+ ]
+
+ prompt = InsightsJudge().create_user_prompt(
+ canonical={"dataset": [{"id": "shared", "expected_skill": "calculator"}], "trials": trials},
+ deterministic={},
+ )
+ sampled = json.loads(prompt.split("\n\n", 1)[1])["trials"]
+
+ assert [(trial["agent"], trial["attempt"]) for trial in sampled] == [
+ ("codex", 1),
+ ("codex", 2),
+ ("claude-code", 1),
+ ]
+
+ def test_build_insights_suppresses_original_unsupported_negative_control_findings(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "title": "Unintended Skill Application",
+ "message": (
+ "The agent correctly answers the unit conversion query but the skill isn't designed "
+ "for such tasks, indicating scope misalignment."
+ ),
+ "severity": "warn",
+ }
+ ],
+ "recommendations": [
+ {
+ "category": "Test",
+ "title": "Exclude Irrelevant Cases",
+ "message": (
+ "Remove unit conversion test cases from the dataset as they fall outside the skill's "
+ "intended scope."
+ ),
+ "severity": "warn",
+ }
+ ],
+ }
+ )
+ canonical = {
+ "dataset": [{"id": "negative-001", "expected_skill": None}],
+ "trials": [
+ {
+ "agent": "codex",
+ "entry_id": "negative-001",
+ "overall": 1.0,
+ "scores": {"skill_execution": 1.0, "skill_routing": 1.0},
+ }
+ ],
+ }
+
+ monkeypatch.setattr(InsightsJudge, "completions", lambda *_args, **_kwargs: response)
+
+ parsed = build_insights(canonical, {"conclusions": [], "suggestions": []})
+
+ assert parsed == {"conclusions": [], "recommendations": []}
+
+ def test_parse_preserves_negative_control_warning_with_failed_routing_evidence(self) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "title": "Unintended Skill Application",
+ "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": [
+ {
+ "agent": "codex",
+ "entry_id": "negative-001",
+ "scores": {"skill_execution": 0.0},
+ }
+ ],
+ }
+
+ parsed = InsightsJudge().parse_response(response, canonical=canonical)
+
+ assert parsed["conclusions"] == [
+ {
+ "title": "Unintended Skill Application",
+ "message": "The evaluated skill was invoked for negative-001.",
+ "severity": "fail",
+ "source": "llm",
+ }
+ ]
+
+ @pytest.mark.parametrize("evidence_case_ids", [["negative-001"], ["fabricated-999"]])
+ def test_parse_rejects_special_claim_without_grounding(
+ self,
+ evidence_case_ids: list[str],
+ ) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "title": "Scope Misalignment",
+ "message": "The evaluated skill activated outside its intended scope.",
+ "severity": "warn",
+ "evidence_case_ids": evidence_case_ids,
+ }
+ ],
+ "recommendations": [],
+ }
+ )
+ canonical = {
+ "dataset": [{"id": "negative-001", "expected_skill": None}],
+ "trials": [
+ {
+ "entry_id": "negative-001",
+ "scores": {"skill_execution": 1.0},
+ }
+ ],
+ }
+
+ assert InsightsJudge().parse_response(response, canonical=canonical)["conclusions"] == []
+
+ def test_parse_preserves_unrelated_insights_and_nonremoval_test_improvements(self) -> None:
+ response = json.dumps(
+ {
+ "conclusions": [
+ {
+ "title": "Efficiency Regression",
+ "message": "Token use increased by 25% for positive-001.",
+ "severity": "warn",
+ }
+ ],
+ "recommendations": [
+ {
+ "category": "Improve",
+ "title": "Clarify Assertions",
+ "message": "Remove ambiguity from test cases by making expected outputs explicit.",
+ "severity": "warn",
+ }
+ ],
+ }
+ )
+ canonical = {
+ "dataset": [
+ {"id": "negative-001", "expected_skill": None},
+ {"id": "positive-001", "expected_skill": "calculator"},
+ ],
+ "trials": [
+ {
+ "entry_id": "negative-001",
+ "scores": {"skill_execution": 1.0},
+ }
+ ],
+ }
+
+ parsed = InsightsJudge().parse_response(response, canonical=canonical)
+
+ assert [item["title"] for item in parsed["conclusions"]] == ["Efficiency Regression"]
+ assert [item["title"] for item in parsed["recommendations"]] == ["Clarify Assertions"]