Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,15 @@ All notable changes to SkillEvaluator are documented in this file.

### Changed

- Tier 3 LLM suggestions and insight recommendations now keep only evidence
references the run recorded (cited references that don't resolve are
dropped rather than shown as evidence) and keep one copy of a repeated
suggestion. Insight recommendations that restate a deterministic one, or
that loosen, relax, or lower an expectation, assertion, ground truth, or
pass threshold, are dropped. Both prompts ask for distinct actions and
label untested causes, such as switching to a different model, as
hypotheses or experiments.

- Align terminal grade and lift colors across compact, full, and direct Tier 3
reports; displayed zero lift is neutral. Narrow terminals stack complete
condition score/bar groups. Full-report Details retain successful quality and
Expand Down
5 changes: 4 additions & 1 deletion docs/reports.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -811,7 +811,10 @@ Both paths speak the same dialect: standalone `tier3 evaluate` and
`validate --tier3` share one HTML renderer for `report.html`, and both embed
the Tier 3 payload at schema version `2.0`. In that payload, conclusions and
recommendations written by the LLM carry `source: "llm"` and name the model
that wrote them as `model`. For a Claude 5.5 or later model on the native
that wrote them as `model`. LLM recommendations that restate a deterministic
one, or that loosen an expectation, assertion, ground truth, or pass threshold,
are dropped, and LLM suggestions keep only evidence references the run
recorded. For a Claude 5.5 or later model on the native
Claude API this is the model the reply names, which can be the server-side
refusal fallback model rather than the configured model. Otherwise it is the
configured model, unless a server-side `fallback` block in the reply names
Expand Down
30 changes: 30 additions & 0 deletions src/skillevaluator/evaluation/insights_judge.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@
)


_WEAKENING_PATTERN = re.compile(
r"\b(?:loosen|relax|weaken|lower|soften)\w*\b.{0,40}"
Comment thread
chrisknvidia marked this conversation as resolved.
Resolved
r"\b(?:expect\w*|assertions?|ground[\s_-]*truth|pass[\s_-]*threshold|threshold|requirements?|criteria)\b",
re.IGNORECASE,
)


_SYSTEM_PROMPT = """\
You are an expert Skill Quality Reviewer summarising a Tier 3 (live agent)
evaluation of an Agent Skill.
Expand Down Expand Up @@ -128,6 +135,14 @@
RECOMMENDATIONS (up to {max_recommendations}): concrete, actionable next
steps for the skill author. Each must be one short imperative sentence.
Tag each with a category from this set: {categories}.
- Make each recommendation a distinct action; do not restate a
deterministic recommendation or another recommendation in other words.
- Never recommend loosening, relaxing, or lowering an expectation,
assertion, ground truth, or pass threshold so that a failing agent passes.
- Recommend a different agent or model only when the supplied trials compare
agents; otherwise phrase it as an experiment to try ("Try ... to test
whether ..."). Phrase any cause the evidence does not establish the same
way.

SEVERITY: tag every conclusion and recommendation with one of:
- \"pass\" - positive observation / low-effort recommendation
Expand Down Expand Up @@ -439,6 +454,14 @@ def _text_case_ids(text: str, known_case_ids: set[str]) -> set[str]:
return references


def _weakens_requirements(text: str) -> bool:
return bool(_WEAKENING_PATTERN.search(text))


def _normalized_text(text: object) -> str:
return " ".join(str(text or "").lower().split())


def _has_negative_control_semantics(text: str) -> bool:
return any(pattern.search(text) for pattern in _NEGATIVE_CONTROL_SEMANTIC_PATTERNS)

Expand Down Expand Up @@ -562,6 +585,8 @@ def parse_response(self, response_text: str, **kwargs: Any) -> dict:
}
)

deterministic = kwargs.get("deterministic") if isinstance(kwargs.get("deterministic"), dict) else {}
seen_messages = {_normalized_text(text) for text in deterministic.get("suggestions") or []}
recommendations: list[dict] = []
for item in (data.get("recommendations") or [])[:INSIGHTS_JUDGE_MAX_RECOMMENDATIONS]:
if not isinstance(item, dict):
Expand All @@ -572,6 +597,11 @@ def parse_response(self, response_text: str, **kwargs: Any) -> dict:
message = (item.get("message") or "").strip()
if not title and not message:
continue
if _weakens_requirements(f"{title} {message}"):
continue
if (key := _normalized_text(message or title)) in seen_messages:
continue
seen_messages.add(key)
recommendations.append(
{
"claim_type": item["claim_type"],
Expand Down
52 changes: 35 additions & 17 deletions src/skillevaluator/tier3/harbor/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,18 @@ def _resolve_evidence_ref(ref: Any, lookup: dict[str, dict[str, Any]]) -> dict[s
return _bounded_evidence_ref({"source": source, "json_pointer": pointer, "kind": "evidence"})


def _recorded_evidence_refs(raw_refs: list[Any], lookup: dict[str, dict[str, Any]]) -> list[dict[str, Any]]:
"""Resolve LLM-cited references, keeping only those the run recorded, once each."""
resolved: list[dict[str, Any]] = []
seen: set[str] = set()
for ref in raw_refs:
key = _compact_evidence_ref(ref) if isinstance(ref, dict) else str(ref)[:1024]
if key in lookup and key not in seen:
Comment thread
chrisknvidia marked this conversation as resolved.
Resolved
seen.add(key)
resolved.append(_resolve_evidence_ref(key, lookup))
return resolved


def _generate_suggestions_structured(
skill_name: str,
findings: list[dict[str, Any]],
Expand All @@ -644,8 +656,9 @@ def _generate_suggestions_structured(
(cheap, reliable). After parsing the LLM response each string ref is
resolved against a lookup built from ``rewards[*]["details"][metric]["evidence_refs"]``
so that the richer dict fields (``kind``, ``path``, ``excerpt``) are
preserved. Unresolvable strings fall back to a minimal dict with
``kind="evidence"``. Callers that consume ``suggestions_v2[*].evidence_refs``
preserved. References the run did not record are dropped, so a
suggestion never cites evidence that does not exist, and repeated
suggestions are kept once. Callers that consume ``suggestions_v2[*].evidence_refs``
(including the SkillEvaluator report template) therefore always receive dicts rather
than plain strings.
"""
Expand Down Expand Up @@ -712,6 +725,10 @@ def _generate_suggestions_structured(

Keep each suggestion to 1-2 sentences. Be concrete — reference specific files, commands, or sections.
If the failures are purely environmental (e.g. CLI not installed in container), say so directly.
Give distinct suggestions; do not repeat one fix in different words.
Do not suggest loosening, removing, or rewriting an eval expectation just so the agent passes; change a case only when the evidence shows the expectation itself is wrong.
When the evidence does not establish a cause (for example, that a different model would do better), start the suggestion with "Hypothesis:" and say how to test it.
Cite only evidence references listed above; references the run did not record are dropped.

Respond with ONLY a JSON array of objects {{"suggestion": "...", "dimension": "<metric>", "evidence_refs": ["trajectory.json#/steps/N", ...]}}, no other text."""

Expand All @@ -729,25 +746,26 @@ def _generate_suggestions_structured(
parsed = _extract_json(content) if content else None
if isinstance(parsed, list):
result: list[dict[str, Any]] = []
seen: set[str] = set()
for item in parsed[:4]:
if isinstance(item, dict):
text = str(item.get("suggestion", ""))[:_MAX_FINDING_TEXT_CHARS]
raw_refs = list(item.get("evidence_refs") or [])[:_MAX_FINDING_EVIDENCE_REFS]
resolved_refs = [_resolve_evidence_ref(r, ref_lookup) for r in raw_refs]
result.append(
{
"suggestion": str(item.get("suggestion", ""))[:_MAX_FINDING_TEXT_CHARS],
"dimension": str(item.get("dimension", ""))[:256],
"evidence_refs": resolved_refs,
}
)
entry = {
"suggestion": text,
"dimension": str(item.get("dimension", ""))[:256],
"evidence_refs": _recorded_evidence_refs(raw_refs, ref_lookup),
}
elif isinstance(item, str):
result.append(
{
"suggestion": item[:_MAX_FINDING_TEXT_CHARS],
"dimension": "",
"evidence_refs": [],
}
)
text = item[:_MAX_FINDING_TEXT_CHARS]
entry = {"suggestion": text, "dimension": "", "evidence_refs": []}
else:
continue
key = " ".join(text.lower().split())
if not key or key in seen:
continue
seen.add(key)
result.append(entry)
if result:
return result
if isinstance(parsed, dict) and "suggestions" in parsed:
Expand Down
59 changes: 59 additions & 0 deletions tests/evaluation/test_judges.py
Original file line number Diff line number Diff line change
Expand Up @@ -849,3 +849,62 @@ def test_regressed_dimension_reasoning_names_the_weakest_signal() -> None:

assert regressed[-1] == "Weakest signal: goal_accuracy 0.25."
assert improved[-1] == "Strongest signal: behavior_check 0.81."


class TestInsightsJudgeRecommendationQuality:
@staticmethod
def _recommendation(message: str, title: str = "Next step") -> dict:
return {
"claim_type": "general",
"category": "Improve",
"title": title,
"message": message,
"severity": "warn",
"evidence_case_ids": ["positive-001"],
}

def _parse(self, *messages: str, deterministic: dict | None = None) -> list[str]:
response = json.dumps(
{
"conclusions": [],
"recommendations": [self._recommendation(message) for message in messages],
}
)
parsed = InsightsJudge().parse_response(
response,
canonical={"dataset": [{"id": "positive-001", "expected_skill": "calculator"}], "trials": []},
deterministic=deterministic or {},
)
return [item["message"] for item in parsed["recommendations"]]

@pytest.mark.parametrize(
"message",
[
"Loosen the expected output of positive-001 so the agent passes.",
"Relax the assertions for positive-001.",
"Lower the pass threshold for positive-001 to 0.3.",
"Soften positive-001's ground truth to accept partial answers.",
],
)
def test_drops_advice_that_weakens_requirements(self, message: str) -> None:
assert self._parse(message) == []

def test_keeps_advice_that_clarifies_requirements(self) -> None:
message = "Make the expected output of positive-001 explicit in evals.json."
assert self._parse(message) == [message]

def test_drops_repeats_of_deterministic_and_earlier_recommendations(self) -> None:
first = "Document the rounding rule that positive-001 depends on in SKILL.md."
repeated = "Add a units example for positive-001 to SKILL.md."
assert self._parse(
first,
first.upper(),
repeated,
deterministic={"suggestions": ["add a units example for positive-001 to SKILL.md."]},
) == [first]

def test_prompt_requires_distinct_actions_and_experiments_for_untested_causes(self) -> None:
prompt = InsightsJudge().get_system_prompt()
assert "do not restate a\n deterministic recommendation" in prompt
assert "Never recommend loosening, relaxing, or lowering an expectation" in prompt
assert "Recommend a different agent or model only when the supplied trials compare" in prompt
49 changes: 39 additions & 10 deletions tests/tier3/test_suggestion_grounding.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,25 +426,54 @@ def test_suggestions_evidence_refs_resolved_to_full_dict(monkeypatch):
assert "excerpt" in refs[0]


def test_suggestions_evidence_refs_unresolvable_string_fallback(monkeypatch):
"""Unresolvable string ref is parsed into a minimal dict with kind='evidence'."""
def test_suggestions_drop_evidence_refs_the_run_did_not_record(monkeypatch):
"""A cited ref that the run did not record is dropped instead of rendered as evidence."""
monkeypatch.setattr(
"skillevaluator.tier3.eval_core.llm_judge.call_public_llm",
lambda _prompt, **_kw: (
'[{"suggestion": "Fix something", "dimension": "goal_accuracy",'
' "evidence_refs": ["trajectory.json#/steps/999"]}]',
' "evidence_refs": ["trajectory.json#/steps/999", "trajectory.json#/steps/14",'
' "trajectory.json#/steps/14", {"source": "made-up.json", "json_pointer": "/x"}]}]',
None,
),
)
reward = _reward_multi_metric(0.1)
findings = report._extract_findings([reward])
objs = report._generate_suggestions_structured("demo", findings, [reward])
assert objs
refs = objs[0]["evidence_refs"]
assert refs and isinstance(refs[0], dict), f"expected dict fallback, got {refs!r}"
assert refs[0]["source"] == "trajectory.json"
assert refs[0]["json_pointer"] == "/steps/999"
assert refs[0]["kind"] == "evidence"
[obj] = report._generate_suggestions_structured("demo", findings, [reward])
assert [ref["json_pointer"] for ref in obj["evidence_refs"]] == ["/steps/14"]
assert obj["evidence_refs"][0]["kind"] == "tool_call"


def test_suggestions_keep_one_copy_of_a_repeated_suggestion(monkeypatch):
monkeypatch.setattr(
"skillevaluator.tier3.eval_core.llm_judge.call_public_llm",
lambda _prompt, **_kw: (
'[{"suggestion": "Install jq in evals/environment/Dockerfile.", "dimension": "goal_accuracy"},'
' {"suggestion": "install jq in evals/environment/Dockerfile.", "dimension": "security"},'
' "Document the output format in SKILL.md."]',
None,
),
)
reward = _reward_multi_metric(0.1)
objs = report._generate_suggestions_structured("demo", report._extract_findings([reward]), [reward])
assert [obj["suggestion"] for obj in objs] == [
"Install jq in evals/environment/Dockerfile.",
"Document the output format in SKILL.md.",
]


def test_suggestion_prompt_guards_requirements_and_labels_hypotheses(monkeypatch):
prompts = []
monkeypatch.setattr(
"skillevaluator.tier3.eval_core.llm_judge.call_public_llm",
lambda prompt, **_kw: (prompts.append(prompt), ("[]", None))[1],
)
reward = _reward_multi_metric(0.1)
report._generate_suggestions_structured("demo", report._extract_findings([reward]), [reward])
[prompt] = prompts
assert "Do not suggest loosening, removing, or rewriting an eval expectation just so the agent passes" in prompt
assert 'start the suggestion with "Hypothesis:"' in prompt
assert "Give distinct suggestions" in prompt


def test_suggestions_evidence_refs_lookup_uses_all_metrics(monkeypatch):
Expand Down
Loading