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.

feat(llm): record the answering model on --llm-verify verdicts and Tier 2 duplicate findings (#455)

Narendran Raghavan517b8396a9e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6ad875ab..68f5e1e4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -114,6 +114,19 @@ All notable changes to SkillEvaluator are documented in this file.
provenance and source hashes, and compute custom lift only on matched
case/attempt pairs, without assigning standard scores or claiming execution.
+- Tier 2 context deduplication and `--llm-verify` name the model that
+ answered. On the native Claude API, a server-side fallback model can answer
+ in place of a configured Claude 5.5 or later model. A duplicate finding
+ records the model that gave its verdict as `llm_model_used`, with
+ `llm_provider`, in its metadata, and the Tier 2 `llm_analysis` object adds
+ `models_used`, every model that gave a cluster's verdict.
+ `llm_analysis.model` stays the configured model, and an `llm_refused`
+ finding still names the configured model as `llm_model`. Each finding that
+ gets an `--llm-verify` verdict records `llm_provider` and `llm_model_used`
+ as well, including a verdict kept from a reply cut off at the output-token
+ limit. A model name that is not a plain identifier, such as a URL or a key,
+ reads `unresolved`.
+
- Show per-agent evidence volume next to Tier 3 scores: distinct cases, planned
and scored attempts, execution and judge failures, and per-arm counts when a
baseline ran. Flag limited case coverage or incomplete attempt coverage;
diff --git a/docs/tier1-validation.mdx b/docs/tier1-validation.mdx
index 14dc18fa..21ef2a06 100644
--- a/docs/tier1-validation.mdx
+++ b/docs/tier1-validation.mdx
@@ -97,7 +97,7 @@ for skills. Its Tier 1 LLM checks still run only when requested.
skillevaluator validate ./my-skill --tiers 1 --llm --llm-verify
```
- Confirmed findings keep their original severity. High-confidence false positives stay visible but are downgraded to INFO and carry verification metadata explaining the review. Static scanning always runs first — if a requested LLM stage is unavailable or returns unusable evidence, the run does not silently turn green. `security-scan` and `pii-scan` accept `--llm-verify` too.
+ Confirmed findings keep their original severity. High-confidence false positives stay visible but are downgraded to INFO and carry verification metadata explaining the review. Each finding that gets a verdict names the provider and model that gave it as `llm_provider` and `llm_model_used` in its JSON metadata. For a Claude 5.5 or later model on the native Claude API, the model is the one the reply names; otherwise it is the configured model, unless a server-side `fallback` block in the reply names another model. Verdicts kept from a reply cut off at the output-token limit name the model that wrote that reply. Static scanning always runs first — if a requested LLM stage is unavailable or returns unusable evidence, the run does not silently turn green. `security-scan` and `pii-scan` accept `--llm-verify` too.
HTML, Markdown, and terminal reports show the recorded verification verdict, confidence, and reasoning beside each finding, together with its reported severity.
</Steps>
diff --git a/docs/tier2-deduplication.mdx b/docs/tier2-deduplication.mdx
index f6c16fcd..e26fd3e1 100644
--- a/docs/tier2-deduplication.mdx
+++ b/docs/tier2-deduplication.mdx
@@ -244,6 +244,19 @@ rerun with another chat model (`--llm-model` or `SKILL_EVAL_LLM_MODEL`). To make
a refusal block `validate`, raise `CONTENT_DEDUP.llm_refused` to `high` in a
[policy overlay](tier1-validation.mdx#validation-profiles-and-policies).
+The JSON report's `llm_analysis` names the configured `provider` and `model`.
+A server-side fallback model can answer a cluster in the configured model's
+place: on the native Claude API, a Claude 5.5 or later model's refusal is
+answered by the fallback model in the same call. So `llm_analysis.models_used`
+lists every model that gave a cluster's verdict (it is absent when none did),
+and each duplicate finding names the model that gave its verdict as
+`llm_model_used`, with `llm_provider`, in its metadata. A model name that is
+not a plain identifier, such as a URL or a key, reads `unresolved`. An
+`llm_refused` finding has no answering model and keeps naming the configured
+one as `llm_model`. A cluster whose analysis fails gives no verdict, so no
+model is listed for it, and the blocking error for failed clusters names the
+configured model.
+
## Compare skills across a collection
`similarity-check` recursively discovers skill manifests, embeds each skill's
diff --git a/src/skillevaluator/deduplication/intra_skill/intra_skill_validator.py b/src/skillevaluator/deduplication/intra_skill/intra_skill_validator.py
index b4356c5d..3653b037 100644
--- a/src/skillevaluator/deduplication/intra_skill/intra_skill_validator.py
+++ b/src/skillevaluator/deduplication/intra_skill/intra_skill_validator.py
@@ -37,7 +37,7 @@ from skillevaluator.deduplication.utils.chunker import ContentChunk, chunk_file
from skillevaluator.deduplication.utils.skill_collector import CollectedFile, SkillCollectionError, collect_files
from skillevaluator.embedding.client import EmbeddingClient, SimilarityConfigError, validate_embedding_vector
from skillevaluator.inference import LLMClient, LLMClientError, LLMClientRefusedError
-from skillevaluator.inference.diagnostics import llm_failure_diagnostic, safe_llm_labels
+from skillevaluator.inference.diagnostics import llm_failure_diagnostic, safe_llm_labels, safe_llm_model
from skillevaluator.models.result import Finding, Severity, ValidationResult
from skillevaluator.utils.tier2_paths import safe_path_label
from skillevaluator.validators.base import ValidatorBase
@@ -422,6 +422,17 @@ class IntraSkillValidator(ValidatorBase):
"clusters_failed": failed_count,
"failures": [{"count": count, "diagnostic": diagnostic} for diagnostic, count in sorted(failures.items())],
}
+ # "model" above stays the configured model. A server-side fallback can
+ # answer some clusters in its place, so name every model that answered.
+ models_used = sorted(
+ {
+ safe_llm_model(verdict.model)
+ for _, verdict, _ in cluster_results
+ if verdict is not None and verdict.model is not None
+ }
+ )
+ if models_used:
+ result.metadata["llm_analysis"]["models_used"] = models_used
if refused_count:
logger.warning(
"LLM declined to classify %d of %d content clusters (provider: %s; model: %s); "
@@ -496,6 +507,13 @@ class IntraSkillValidator(ValidatorBase):
"reasoning": verdict.reasoning,
"confidence": verdict.confidence,
"source_files": distinct_files,
+ # The model that gave this verdict, which can be a
+ # server-side fallback rather than the configured model.
+ **(
+ {"llm_provider": provider, "llm_model_used": safe_llm_model(verdict.model)}
+ if verdict.model is not None
+ else {}
+ ),
},
)
)
diff --git a/src/skillevaluator/deduplication/intra_skill/llm_analyzer.py b/src/skillevaluator/deduplication/intra_skill/llm_analyzer.py
index caad964a..28a66ab1 100644
--- a/src/skillevaluator/deduplication/intra_skill/llm_analyzer.py
+++ b/src/skillevaluator/deduplication/intra_skill/llm_analyzer.py
@@ -203,6 +203,10 @@ def analyze_cluster(client: LLMClient, cluster: ContentCluster) -> LLMVerdict:
``VALID_VERDICTS``, a confidence that is not a number from 0 to 1, or a
rationale or suggestion that is not a bounded string raises
:class:`~skillevaluator.inference.LLMClientError`.
+
+ The verdict's ``model`` is the client's ``model_used`` right after the
+ call. The client keeps it per thread, so concurrent clusters keep their
+ own answering model.
"""
user_prompt = build_user_prompt(cluster)
data = client.extract_json_from_response(
@@ -211,7 +215,12 @@ def analyze_cluster(client: LLMClient, cluster: ContentCluster) -> LLMVerdict:
response_schema=VERDICT_JSON_SCHEMA,
schema_name="dedup_verdict",
)
- return parse_bounded_llm_verdict(data, valid_verdicts=VALID_VERDICTS, context="Content deduplication LLM")
+ return parse_bounded_llm_verdict(
+ data,
+ valid_verdicts=VALID_VERDICTS,
+ context="Content deduplication LLM",
+ model=getattr(client, "model_used", None),
+ )
def verdict_to_severity(verdict: LLMVerdict) -> Severity:
diff --git a/src/skillevaluator/inference/client.py b/src/skillevaluator/inference/client.py
index 86f40fa6..02207697 100644
--- a/src/skillevaluator/inference/client.py
+++ b/src/skillevaluator/inference/client.py
@@ -529,7 +529,9 @@ class LLMClient:
request for a Claude 5.5 or later model, which asks for server-side
fallback, also reads the reply's top-level ``model`` when there is no
block. Otherwise it is the configured model. ``None`` before a call
- succeeds and after a call fails.
+ succeeds and after a call fails, except that :meth:`process` names the
+ model that wrote a reply cut off at the output-token limit when it
+ keeps that reply's complete entries.
"""
return getattr(self._call_state, "model_used", None)
@@ -832,7 +834,13 @@ class LLMClient:
raise
return _extract_choice_content(response)
- content = retry_call_with_backoff(_invoke_provider, config=self._retry_config)
+ try:
+ content = retry_call_with_backoff(_invoke_provider, config=self._retry_config)
+ except LLMClientTruncatedError as exc:
+ # The partial reply still came from a known model; a caller that
+ # keeps its complete entries can name that model.
+ exc.model_used = answered_by
+ raise
self._call_state.model_used = answered_by
return content
@@ -896,7 +904,8 @@ class LLMClient:
receive a usable result, and ``last_failure`` records a bounded
diagnostic of the cause. When ``salvage_truncated_response`` is set,
a reply cut off at the token limit is parsed for its complete entries
- instead, and ``last_failure`` still records the truncation.
+ instead, ``last_failure`` still records the truncation, and
+ :attr:`model_used` names the model that wrote the reply.
"""
self.last_failure = None
try:
@@ -916,9 +925,14 @@ class LLMClient:
if isinstance(exc, LLMClientTruncatedError) and exc.content and self.salvage_truncated_response:
logger.warning("LLM reply was truncated (%s) - keeping its complete entries", self.last_failure)
try:
- return self.parse_response(exc.content, **kwargs)
+ salvaged = self.parse_response(exc.content, **kwargs)
except Exception:
pass
+ else:
+ # The kept entries came from this model, which can be a
+ # server-side fallback rather than the configured model.
+ self._call_state.model_used = exc.model_used
+ return salvaged
logger.warning("LLM call failed (%s) - using fallback response", self.last_failure)
return self.get_fallback_response(**kwargs)
diff --git a/src/skillevaluator/inference/types.py b/src/skillevaluator/inference/types.py
index a6da03f4..cd79b318 100644
--- a/src/skillevaluator/inference/types.py
+++ b/src/skillevaluator/inference/types.py
@@ -27,12 +27,14 @@ class LLMClientRefusedError(LLMClientError):
class LLMClientTruncatedError(LLMClientError):
"""Raised when a response stops at the output-token limit.
- ``content`` keeps the partial text for callers that can salvage it.
+ ``content`` keeps the partial text for callers that can salvage it, and
+ ``model_used`` names the model that wrote it when the client knows it.
"""
- def __init__(self, message: str, content: str = "") -> None:
+ def __init__(self, message: str, content: str = "", model_used: str | None = None) -> None:
super().__init__(message)
self.content = content
+ self.model_used = model_used
LLMConfigError = LLMClientError
@@ -46,6 +48,10 @@ class LLMVerdict:
confidence: float
reasoning: str
suggestion: str
+ # The model that answered, as the client reported it: the configured model,
+ # or a server-side fallback model that answered in its place. ``None`` when
+ # the client named no model.
+ model: str | None = None
def require_bounded_llm_string(value: object, label: str, *, max_chars: int) -> str:
@@ -75,7 +81,13 @@ def _require_unit_interval(value: object, label: str) -> float:
return number
-def parse_bounded_llm_verdict(data: object, *, valid_verdicts: Collection[str], context: str) -> LLMVerdict:
+def parse_bounded_llm_verdict(
+ data: object,
+ *,
+ valid_verdicts: Collection[str],
+ context: str,
+ model: object = None,
+) -> LLMVerdict:
"""Turn a parsed Tier 2 LLM reply into a verdict with checked, bounded fields.
The reply must be a JSON object whose ``verdict`` is one of
@@ -84,6 +96,10 @@ def parse_bounded_llm_verdict(data: object, *, valid_verdicts: Collection[str],
strings of at most ``TIER2_LLM_MAX_RESPONSE_SCALAR_CHARS`` characters. A
missing confidence reads as 0 and a missing text field as empty. Any other
reply raises :class:`LLMClientError`.
+
+ ``model`` names the model that answered and is kept only when it is a
+ string. It is stored as given; reports pass it through
+ :func:`~skillevaluator.inference.diagnostics.safe_llm_model`.
"""
if not isinstance(data, Mapping):
raise LLMClientError(f"{context} response must be a JSON object")
@@ -107,4 +123,10 @@ def parse_bounded_llm_verdict(data: object, *, valid_verdicts: Collection[str],
f"{context} suggestion",
max_chars=TIER2_LLM_MAX_RESPONSE_SCALAR_CHARS,
)
- return LLMVerdict(verdict=verdict, confidence=confidence, reasoning=reasoning, suggestion=suggestion)
+ return LLMVerdict(
+ verdict=verdict,
+ confidence=confidence,
+ reasoning=reasoning,
+ suggestion=suggestion,
+ model=model if isinstance(model, str) else None,
+ )
diff --git a/src/skillevaluator/validators/security.py b/src/skillevaluator/validators/security.py
index 2b9305fe..5189cbd1 100644
--- a/src/skillevaluator/validators/security.py
+++ b/src/skillevaluator/validators/security.py
@@ -4909,6 +4909,7 @@ class SecurityValidator(ValidatorBase):
return
from skillevaluator.inference import FindingVerifier
+ from skillevaluator.inference.diagnostics import safe_llm_labels
logger.info(f"Running LLM verification on {len(findings)} finding(s)")
verifier = FindingVerifier()
@@ -4920,6 +4921,13 @@ class SecurityValidator(ValidatorBase):
result.add_message(f"LLM finding verification was skipped (no verdicts returned{cause})")
return
+ # The provider and model that gave the verdicts: the configured model,
+ # or a server-side fallback model that answered in its place.
+ model_labels: dict[str, str] = {}
+ if verifier.model_used is not None:
+ provider, model = safe_llm_labels(verifier.provider, verifier.model_used)
+ model_labels = {"llm_provider": provider, "llm_model_used": model}
+
suppressed = 0
verified = 0
for idx, finding in enumerate(findings):
@@ -4944,6 +4952,7 @@ class SecurityValidator(ValidatorBase):
finding.metadata["llm_verdict"] = verdict
finding.metadata["llm_confidence"] = confidence
finding.metadata["llm_reasoning"] = reasoning
+ finding.metadata.update(model_labels)
if finding_verification_policy.should_downgrade(verdict, confidence):
finding.severity = finding_verification_policy.DOWNGRADE_SEVERITY
diff --git a/tests/deduplication/intra_skill/test_intra_llm_analyzer.py b/tests/deduplication/intra_skill/test_intra_llm_analyzer.py
index f60a5553..b18dec0c 100644
--- a/tests/deduplication/intra_skill/test_intra_llm_analyzer.py
+++ b/tests/deduplication/intra_skill/test_intra_llm_analyzer.py
@@ -618,6 +618,52 @@ class TestAnalyzeCluster:
analyze_cluster(mock_client, make_cluster())
+_DUPLICATE_REPLY = {"verdict": "DUPLICATE", "confidence": 0.9, "rationale": "Same content", "suggestion": "Remove one"}
+
+
+class TestAnsweringModel:
+ """The verdict names the model that answered, which can be a server-side fallback."""
+
+ def test_verdict_records_the_model_that_answered(self, make_cluster) -> None:
+ mock_client = MagicMock(spec=LLMClient)
+ mock_client.extract_json_from_response.return_value = dict(_DUPLICATE_REPLY)
+ mock_client.model_used = "claude-opus-4-8"
+
+ result = analyze_cluster(mock_client, make_cluster())
+
+ assert result.model == "claude-opus-4-8"
+ assert (result.verdict, result.confidence) == ("DUPLICATE", 0.9)
+
+ def test_model_is_kept_as_the_client_named_it(self, make_cluster) -> None:
+ # Reports sanitize the model; the verdict keeps what the client said.
+ mock_client = MagicMock(spec=LLMClient)
+ mock_client.extract_json_from_response.return_value = dict(_DUPLICATE_REPLY)
+ mock_client.model_used = "https://proxy.example.test/v1"
+
+ assert analyze_cluster(mock_client, make_cluster()).model == "https://proxy.example.test/v1"
+
+ @pytest.mark.parametrize("model_used", [None, 42, ["claude-opus-4-8"]], ids=["none", "number", "list"])
+ def test_verdict_names_no_model_unless_the_client_gives_a_string(self, make_cluster, model_used: object) -> None:
+ mock_client = MagicMock(spec=LLMClient)
+ mock_client.extract_json_from_response.return_value = dict(_DUPLICATE_REPLY)
+ mock_client.model_used = model_used
+
+ assert analyze_cluster(mock_client, make_cluster()).model is None
+
+ def test_client_without_model_used_gives_no_model(self, make_cluster) -> None:
+ class Client:
+ def extract_json_from_response(self, *_args, **_kwargs):
+ return {"verdict": "INTENTIONAL_DETAIL", "confidence": 0.8}
+
+ result = analyze_cluster(Client(), make_cluster())
+
+ assert result == LLMVerdict("INTENTIONAL_DETAIL", 0.8, "", "")
+ assert result.model is None
+
+ def test_positional_verdict_has_no_model(self) -> None:
+ assert LLMVerdict("DUPLICATE", 0.9, "r", "s").model is None
+
+
class TestVerdictToSeverity:
def test_duplicate_high_confidence(self) -> None:
v = LLMVerdict("DUPLICATE", 0.9, "r", "s")
diff --git a/tests/deduplication/intra_skill/test_intra_skill_validator.py b/tests/deduplication/intra_skill/test_intra_skill_validator.py
index 26dc9064..ada4d165 100644
--- a/tests/deduplication/intra_skill/test_intra_skill_validator.py
+++ b/tests/deduplication/intra_skill/test_intra_skill_validator.py
@@ -8,7 +8,9 @@ from __future__ import annotations
import json
import logging
import math
+import threading
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import patch
import pytest
@@ -20,7 +22,7 @@ from skillevaluator.deduplication.intra_skill.llm_analyzer import SYSTEM_PROMPT,
from skillevaluator.deduplication.intra_skill.semantic_clustering import ContentCluster
from skillevaluator.deduplication.utils.chunker import ContentChunk
from skillevaluator.embedding.client import MAX_EMBEDDING_VECTOR_DIMENSION, SimilarityConfigError
-from skillevaluator.inference import LLMClientError, LLMClientRefusedError, LLMVerdict
+from skillevaluator.inference import LLMClient, LLMClientError, LLMClientRefusedError, LLMVerdict
from skillevaluator.models.result import Severity
from skillevaluator.reporting.json_reporter import JSONReporter
@@ -1410,3 +1412,220 @@ class TestIntraSkillValidatorValidate:
v = IntraSkillValidator(embedding_model="custom/embed", llm_model="custom/llm")
assert v._embedding_model == "custom/embed"
assert v._llm_model == "custom/llm"
+
+
+def _section_skill(tmp_path: Path, letters: str) -> Path:
+ """A skill with one 200-character section per letter, in SKILL.md."""
+ skill_dir = tmp_path / "skill"
+ skill_dir.mkdir()
+ (skill_dir / "SKILL.md").write_text(
+ "\n".join(f"## Section {letter}\n{letter.lower() * 200}" for letter in letters), encoding="utf-8"
+ )
+ return skill_dir
+
+
+# Sections A/B and C/D of a four-section skill form two clusters.
+_TWO_CLUSTER_VECTORS = [[1.0, 0.0], [1.0, 0.0], [0.0, 1.0], [0.0, 1.0]]
+
+
+def _configure_llm(mock_llm, provider: str = "anthropic", model: str = "claude-opus-5-5") -> None:
+ mock_llm.return_value._resolved_config.return_value = SimpleNamespace(provider=provider, model=model)
+
+
+class TestAnsweringModelProvenance:
+ """A verdict names the model that answered, which can be a server-side fallback model."""
+
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.analyze_cluster")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.LLMClient")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.EmbeddingClient")
+ def test_duplicate_finding_names_the_model_that_answered(
+ self, mock_embed, mock_llm, mock_analyze, tmp_path: Path
+ ) -> None:
+ skill_dir = _section_skill(tmp_path, "AB")
+ mock_embed.return_value.embed.return_value = [[1.0, 0.0], [1.0, 0.0]]
+ _configure_llm(mock_llm)
+ mock_analyze.return_value = LLMVerdict("DUPLICATE", 0.9, "Same content", "Remove one", model="claude-opus-4-8")
+
+ result = IntraSkillValidator().validate(skill_dir)
+
+ assert result.status == "failed"
+ [finding] = result.findings
+ assert (finding.check_name, finding.severity) == ("duplicate", Severity.HIGH)
+ assert finding.metadata["llm_provider"] == "anthropic"
+ assert finding.metadata["llm_model_used"] == "claude-opus-4-8"
+ analysis = result.metadata["llm_analysis"]
+ # "model" stays the configured model; "models_used" names the models that answered.
+ assert analysis["model"] == "claude-opus-5-5"
+ assert analysis["models_used"] == ["claude-opus-4-8"]
+ data = json.loads(JSONReporter(include_timestamp=False).render(result))
+ assert data["findings"][0]["metadata"]["llm_model_used"] == "claude-opus-4-8"
+ assert data["llm_analysis"]["model"] == "claude-opus-5-5"
+ assert data["llm_analysis"]["models_used"] == ["claude-opus-4-8"]
+
+ @pytest.mark.parametrize(
+ "answered_by",
+ ["https://proxy.example.test/v1", "sk-test", "model with spaces"],
+ ids=["url", "key-like", "spaces"],
+ )
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.analyze_cluster")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.LLMClient")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.EmbeddingClient")
+ def test_unsafe_answering_model_is_reported_as_unresolved(
+ self, mock_embed, mock_llm, mock_analyze, tmp_path: Path, answered_by: str
+ ) -> None:
+ skill_dir = _section_skill(tmp_path, "AB")
+ mock_embed.return_value.embed.return_value = [[1.0, 0.0], [1.0, 0.0]]
+ _configure_llm(mock_llm)
+ mock_analyze.return_value = LLMVerdict("DUPLICATE", 0.9, "Same content", "Remove one", model=answered_by)
+
+ result = IntraSkillValidator().validate(skill_dir)
+
+ [finding] = result.findings
+ assert finding.metadata["llm_model_used"] == "unresolved"
+ assert result.metadata["llm_analysis"]["models_used"] == ["unresolved"]
+ assert answered_by not in JSONReporter(include_timestamp=False).render(result)
+
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.analyze_cluster")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.LLMClient")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.EmbeddingClient")
+ def test_verdict_without_a_model_adds_no_model_fields(
+ self, mock_embed, mock_llm, mock_analyze, tmp_path: Path
+ ) -> None:
+ skill_dir = _section_skill(tmp_path, "AB")
+ mock_embed.return_value.embed.return_value = [[1.0, 0.0], [1.0, 0.0]]
+ _configure_llm(mock_llm)
+ mock_analyze.return_value = LLMVerdict("DUPLICATE", 0.9, "Same content", "Remove one")
+
+ result = IntraSkillValidator().validate(skill_dir)
+
+ [finding] = result.findings
+ assert set(finding.metadata) == {"reasoning", "confidence", "source_files"}
+ assert "models_used" not in result.metadata["llm_analysis"]
+ assert result.metadata["llm_analysis"]["model"] == "claude-opus-5-5"
+
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.analyze_cluster")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.LLMClient")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.EmbeddingClient")
+ def test_refusal_advisory_keeps_the_configured_model_beside_a_fallback_verdict(
+ self, mock_embed, mock_llm, mock_analyze, tmp_path: Path
+ ) -> None:
+ skill_dir = _section_skill(tmp_path, "ABCD")
+ mock_embed.return_value.embed.return_value = _TWO_CLUSTER_VECTORS
+ _configure_llm(mock_llm)
+
+ def analyze(_client, cluster):
+ if any("Section A" in member.heading for member in cluster.members):
+ return LLMVerdict("DUPLICATE", 0.9, "Same content", "Remove one", model="claude-opus-4-8")
+ raise LLMClientRefusedError("private provider refusal text")
+
+ mock_analyze.side_effect = analyze
+ result = IntraSkillValidator().validate(skill_dir)
+
+ by_check = {finding.check_name: finding for finding in result.findings}
+ assert set(by_check) == {"duplicate", "llm_refused"}
+ assert by_check["duplicate"].metadata["llm_model_used"] == "claude-opus-4-8"
+ # A refusal has no answering model; its advisory still names the configured one.
+ assert by_check["llm_refused"].metadata == {
+ "source_files": ["SKILL.md"],
+ "llm_provider": "anthropic",
+ "llm_model": "claude-opus-5-5",
+ }
+ analysis = result.metadata["llm_analysis"]
+ assert (analysis["clusters_completed"], analysis["clusters_refused"]) == (1, 1)
+ assert analysis["models_used"] == ["claude-opus-4-8"]
+
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.analyze_cluster")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.LLMClient")
+ @patch("skillevaluator.deduplication.intra_skill.intra_skill_validator.EmbeddingClient")
+ def test_failed_cluster_adds_no_model_beside_a_fallback_verdict(
+ self, mock_embed, mock_llm, mock_analyze, tmp_path: Path
+ ) -> None:
+ skill_dir = _section_skill(tmp_path, "ABCD")
+ mock_embed.return_value.embed.return_value = _TWO_CLUSTER_VECTORS
+ _configure_llm(mock_llm)
+
+ def analyze(_client, cluster):
+ if any("Section A" in member.heading for member in cluster.members):
+ return LLMVerdict("DUPLICATE", 0.9, "Same content", "Remove one", model="claude-opus-4-8")
+ raise RuntimeError("private provider response")
+
+ mock_analyze.side_effect = analyze
+ result = IntraSkillValidator().validate(skill_dir)
+
+ assert result.status == "incomplete"
+ [finding] = result.findings
+ assert finding.metadata["llm_model_used"] == "claude-opus-4-8"
+ analysis = result.metadata["llm_analysis"]
+ assert (analysis["clusters_completed"], analysis["clusters_failed"]) == (1, 1)
+ assert analysis["models_used"] == ["claude-opus-4-8"]
+ assert "(provider: anthropic; model: claude-opus-5-5)" in result.errors[0]
+
+ def test_concurrent_clusters_keep_their_own_answering_model(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Through the real client: each worker thread reads the model that answered its own call."""
+ pytest.importorskip("anthropic")
+ httpx = pytest.importorskip("httpx")
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "anthropic")
+ monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "claude-opus-5-5")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ for name in ("SKILL_EVAL_LLM_BASE_URL", "ANTHROPIC_BASE_URL"):
+ monkeypatch.delenv(name, raising=False)
+ skill_dir = _section_skill(tmp_path, "ABCD")
+ reply = json.dumps(
+ {"verdict": "DUPLICATE", "confidence": 0.9, "rationale": "Same content", "suggestion": "Remove one"}
+ )
+
+ def handler(request):
+ prompt = json.loads(request.content)["messages"][0]["content"]
+ content = [{"type": "text", "text": reply}]
+ answered_by = "claude-opus-5-5"
+ if "Section A" in prompt:
+ # The configured model refused and the fallback answered in the same call.
+ answered_by = "claude-opus-4-8"
+ content.insert(
+ 0, {"type": "fallback", "from": {"model": "claude-opus-5-5"}, "to": {"model": answered_by}}
+ )
+ return httpx.Response(
+ 200,
+ json={
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": answered_by,
+ "content": content,
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+ },
+ )
+
+ # Both calls finish before either cluster reads its answering model, so
+ # one label shared by the threads would give both clusters the same model.
+ both_answered = threading.Barrier(2, timeout=30)
+
+ class BarrierClient(LLMClient):
+ def extract_json_from_response(self, *args, **kwargs):
+ data = super().extract_json_from_response(*args, **kwargs)
+ both_answered.wait()
+ return data
+
+ with (
+ httpx.Client(transport=httpx.MockTransport(handler)) as http_client,
+ patch.object(
+ intra_skill_validator, "LLMClient", lambda **kwargs: BarrierClient(http_client=http_client, **kwargs)
+ ),
+ patch.object(intra_skill_validator, "EmbeddingClient") as mock_embed,
+ ):
+ mock_embed.return_value.embed.return_value = _TWO_CLUSTER_VECTORS
+ result = IntraSkillValidator().validate(skill_dir)
+
+ assert result.status == "failed"
+ assert result.incomplete_scans == []
+ models = {"Section A" in finding.message: finding.metadata["llm_model_used"] for finding in result.findings}
+ assert models == {True: "claude-opus-4-8", False: "claude-opus-5-5"}
+ assert {finding.metadata["llm_provider"] for finding in result.findings} == {"anthropic"}
+ analysis = result.metadata["llm_analysis"]
+ assert analysis["clusters_completed"] == 2
+ assert (analysis["provider"], analysis["model"]) == ("anthropic", "claude-opus-5-5")
+ assert analysis["models_used"] == ["claude-opus-4-8", "claude-opus-5-5"]
diff --git a/tests/inference/test_llm_client.py b/tests/inference/test_llm_client.py
index 2394c8d9..79090c22 100644
--- a/tests/inference/test_llm_client.py
+++ b/tests/inference/test_llm_client.py
@@ -1447,6 +1447,13 @@ def _anthropic_fallback_response(text: str, served_by: object):
return response
+def _anthropic_truncated_fallback_response(text: str):
+ """Return a reply cut off at the token limit, written by the server-side fallback model."""
+ response = _anthropic_response(text, stop_reason="max_tokens")
+ response.content.insert(0, SimpleNamespace(type="fallback", to={"model": ANTHROPIC_REFUSAL_FALLBACK_MODEL}))
+ return response
+
+
class TestModelProvenance:
def test_model_used_names_the_configured_model_after_a_success_only(self, monkeypatch: pytest.MonkeyPatch) -> None:
_use_provider(monkeypatch, "openai", CHAT_DEFAULT_OPENAI)
@@ -1654,3 +1661,92 @@ class TestModelProvenance:
assert {dimension["model"] for dimension in written} == {CHAT_DEFAULT_OPENAI}
assert not any("model" in dimension for dimension in deterministic)
+
+ @pytest.mark.parametrize(
+ ("provider", "model", "make_response", "expected"),
+ [
+ (
+ "openai",
+ CHAT_DEFAULT_OPENAI,
+ lambda: _openai_choice_response('{"partial": ', finish_reason="length"),
+ CHAT_DEFAULT_OPENAI,
+ ),
+ (
+ "anthropic",
+ "claude-opus-5-5",
+ lambda: _anthropic_truncated_fallback_response('{"partial": '),
+ ANTHROPIC_REFUSAL_FALLBACK_MODEL,
+ ),
+ ],
+ ids=["openai-configured", "anthropic-fallback"],
+ )
+ def test_truncation_error_names_the_model_that_wrote_the_partial_reply(
+ self, monkeypatch: pytest.MonkeyPatch, provider: str, model: str, make_response, expected: str
+ ) -> None:
+ _use_provider(monkeypatch, provider, model)
+ sdk = MagicMock()
+ sdk.chat.completions.create.return_value = make_response()
+ sdk.messages.create.return_value = make_response()
+ client = LLMClient()
+
+ with (
+ patch("openai.OpenAI", return_value=sdk),
+ patch("anthropic.Anthropic", return_value=sdk),
+ pytest.raises(LLMClientTruncatedError) as exc_info,
+ ):
+ client.completions("system", "user")
+
+ assert exc_info.value.model_used == expected
+ # The call itself failed, so the client still names no model for it.
+ assert client.model_used is None
+
+ def test_verdicts_kept_from_a_truncated_reply_name_the_model_that_wrote_it(
+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+ ) -> None:
+ _use_provider(monkeypatch, "anthropic", "claude-opus-5-5")
+ reply = (
+ '{"index": 0, "verdict": "false_positive", "confidence": "high", "rationale": "Test card."}\n'
+ '{"index": 1, "verdict": "true_pos'
+ )
+ mock_anthropic = MagicMock()
+ mock_anthropic.messages.create.return_value = _anthropic_truncated_fallback_response(reply)
+ verifier = FindingVerifier()
+
+ with patch("anthropic.Anthropic", return_value=mock_anthropic):
+ verdicts = verifier.process(findings=[], skill_path=tmp_path)
+
+ assert sorted(verdicts) == [0]
+ assert verifier.last_failure is not None
+ assert "output-token limit" in verifier.last_failure
+ assert verifier.model == "claude-opus-5-5"
+ assert verifier.model_used == ANTHROPIC_REFUSAL_FALLBACK_MODEL
+
+ @pytest.mark.parametrize("salvage", [False, True], ids=["salvage-off", "salvage-fails"])
+ def test_a_truncated_reply_that_is_not_kept_names_no_model(
+ self, monkeypatch: pytest.MonkeyPatch, salvage: bool
+ ) -> None:
+ class Client(LLMClient):
+ salvage_truncated_response = salvage
+
+ def get_system_prompt(self) -> str:
+ return "system"
+
+ def create_user_prompt(self, **_kwargs) -> str:
+ return "user"
+
+ def parse_response(self, _response_text: str, **_kwargs) -> str:
+ raise ValueError("no complete entries")
+
+ def get_fallback_response(self, **_kwargs) -> str:
+ return "fallback"
+
+ _use_provider(monkeypatch, "anthropic", "claude-opus-5-5")
+ mock_anthropic = MagicMock()
+ mock_anthropic.messages.create.return_value = _anthropic_truncated_fallback_response("partial")
+
+ with patch("anthropic.Anthropic", return_value=mock_anthropic):
+ client = Client()
+ assert client.process() == "fallback"
+
+ assert client.last_failure is not None
+ assert client.model_used is None
diff --git a/tests/validators/test_security.py b/tests/validators/test_security.py
index 1b66c228..c413b135 100644
--- a/tests/validators/test_security.py
+++ b/tests/validators/test_security.py
@@ -5983,6 +5983,269 @@ assert cap is not None and get_max_output_tokens(model) <= cap, (cap, get_max_ou
assert result.metadata["incomplete_scans"] == ["llm-verification"]
assert f"LLM finding verification was skipped (no verdicts returned: {cause})" in result.messages
+ def test_llm_verdicts_name_the_model_that_answered(self, tmp_path: Path) -> None:
+ """A verdict from a server-side fallback model is labeled with that model and its provider."""
+ result = ValidationResult()
+ for index in range(3):
+ result.add_structured_finding(
+ Finding(
+ category="PII",
+ severity=Severity.HIGH,
+ check_name=f"finding-{index}",
+ message=f"Finding {index}",
+ file_path="SKILL.md",
+ ),
+ is_error=True,
+ )
+
+ with patch("skillevaluator.inference.FindingVerifier") as verifier_cls:
+ verifier_cls.return_value.verify.return_value = {
+ 0: {"verdict": "false_positive", "confidence": "high", "rationale": "Documentation example."},
+ 1: {"verdict": "true_positive", "confidence": "high", "rationale": "Real address."},
+ }
+ verifier_cls.return_value.provider = "anthropic"
+ verifier_cls.return_value.model_used = "claude-opus-4-8"
+ verifier_cls.return_value.last_failure = None
+ SecurityValidator(verify_llm=True)._verify_findings_with_llm(result, tmp_path)
+
+ by_check = {finding.check_name: finding for finding in result.findings}
+ labels = {"llm_provider": "anthropic", "llm_model_used": "claude-opus-4-8"}
+ assert by_check["finding-0"].severity == Severity.INFO
+ assert by_check["finding-0"].metadata.items() >= labels.items()
+ assert by_check["finding-1"].severity == Severity.HIGH
+ assert by_check["finding-1"].metadata.items() >= labels.items()
+ # A finding the verifier returned no verdict for names no provider or model either.
+ assert not by_check["finding-2"].metadata.keys() & labels.keys()
+
+ @pytest.mark.parametrize(
+ ("provider", "model_used", "expected"),
+ [
+ (
+ "anthropic",
+ "https://proxy.example.test/v1",
+ {"llm_provider": "anthropic", "llm_model_used": "unresolved"},
+ ),
+ ("anthropic", "sk-test", {"llm_provider": "anthropic", "llm_model_used": "unresolved"}),
+ (
+ "https://proxy.example.test",
+ "claude-opus-4-8",
+ {"llm_provider": "unresolved", "llm_model_used": "claude-opus-4-8"},
+ ),
+ ("anthropic", None, {}),
+ ],
+ ids=["url-model", "key-like-model", "url-provider", "no-model"],
+ )
+ def test_llm_verdict_labels_are_sanitized_or_left_out(
+ self, tmp_path: Path, provider: str, model_used: str | None, expected: dict[str, str]
+ ) -> None:
+ result = ValidationResult()
+ result.add_structured_finding(
+ Finding(category="PII", severity=Severity.HIGH, check_name="email", message="Email", file_path="SKILL.md"),
+ is_error=True,
+ )
+
+ with patch("skillevaluator.inference.FindingVerifier") as verifier_cls:
+ verifier_cls.return_value.verify.return_value = {
+ 0: {"verdict": "true_positive", "confidence": "high", "rationale": "Real address."}
+ }
+ verifier_cls.return_value.provider = provider
+ verifier_cls.return_value.model_used = model_used
+ verifier_cls.return_value.last_failure = None
+ SecurityValidator(verify_llm=True)._verify_findings_with_llm(result, tmp_path)
+
+ metadata = result.findings[0].metadata
+ assert metadata["llm_verdict"] == "true_positive"
+ assert {key: metadata[key] for key in ("llm_provider", "llm_model_used") if key in metadata} == expected
+ reported = json.dumps(metadata)
+ for raw, label in ((provider, "llm_provider"), (model_used, "llm_model_used")):
+ if expected.get(label) == "unresolved":
+ assert raw not in reported
+
+ @pytest.mark.parametrize(
+ ("provider", "configured", "reply_model", "fallback_block", "expected"),
+ [
+ ("anthropic", "claude-opus-5-5", "claude-opus-4-8", True, "claude-opus-4-8"),
+ ("anthropic", "claude-opus-5-5", "claude-opus-5-5", False, "claude-opus-5-5"),
+ ("anthropic", "claude-opus-5-5", "claude-opus-5-5-20261101", False, "claude-opus-5-5-20261101"),
+ ("openai", "gpt-5.4-mini", "gpt-5.4-mini-snapshot", False, "gpt-5.4-mini"),
+ ],
+ ids=["anthropic-fallback", "anthropic-configured", "anthropic-reply-names-model", "openai-configured"],
+ )
+ def test_llm_verify_through_the_client_names_the_answering_model(
+ self,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ provider: str,
+ configured: str,
+ reply_model: str,
+ fallback_block: bool,
+ expected: str,
+ ) -> None:
+ """The real verifier reports the model a Claude 5.5 reply names, and the configured model on OpenAI."""
+ pytest.importorskip(provider)
+ httpx = pytest.importorskip("httpx")
+ from skillevaluator.inference.finding_verifier import FindingVerifier
+
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", provider)
+ monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", configured)
+ monkeypatch.setenv("OPENAI_API_KEY", "test-key")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ for name in ("SKILL_EVAL_LLM_BASE_URL", "OPENAI_BASE_URL", "ANTHROPIC_BASE_URL"):
+ monkeypatch.delenv(name, raising=False)
+ (tmp_path / "SKILL.md").write_text("# Example\n\nExample text.\n", encoding="utf-8")
+ result = ValidationResult()
+ result.add_structured_finding(
+ Finding(category="PII", severity=Severity.HIGH, check_name="email", message="Email", file_path="SKILL.md"),
+ is_error=True,
+ )
+ reply = json.dumps(
+ {"index": 0, "verdict": "false_positive", "confidence": "high", "rationale": "Documentation example."}
+ )
+
+ def handler(request):
+ usage = {"input_tokens": 1, "output_tokens": 1}
+ if provider == "openai":
+ return httpx.Response(
+ 200,
+ json={
+ "id": "chatcmpl-test",
+ "object": "chat.completion",
+ "created": 0,
+ "model": reply_model,
+ "choices": [
+ {"index": 0, "message": {"role": "assistant", "content": reply}, "finish_reason": "stop"}
+ ],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ },
+ )
+ content = [{"type": "text", "text": reply}]
+ if fallback_block:
+ content.insert(0, {"type": "fallback", "from": {"model": configured}, "to": {"model": reply_model}})
+ return httpx.Response(
+ 200,
+ json={
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": reply_model,
+ "content": content,
+ "stop_reason": "end_turn",
+ "stop_sequence": None,
+ "usage": usage,
+ },
+ )
+
+ with (
+ httpx.Client(transport=httpx.MockTransport(handler)) as http_client,
+ patch("skillevaluator.inference.FindingVerifier", lambda: FindingVerifier(http_client=http_client)),
+ ):
+ SecurityValidator(verify_llm=True)._verify_findings_with_llm(result, tmp_path)
+
+ [finding] = result.findings
+ assert (finding.metadata["llm_verdict"], finding.severity) == ("false_positive", Severity.INFO)
+ assert finding.metadata["llm_provider"] == provider
+ assert finding.metadata["llm_model_used"] == expected
+
+ def test_llm_verify_docs_state_the_answering_model_rule_of_rubric_evaluation(self) -> None:
+ """Both labels come from the same client, so the two docs paragraphs state one rule."""
+ page = Path(__file__).parents[2] / "docs" / "tier1-validation.mdx"
+ paragraphs = [" ".join(block.split()) for block in page.read_text(encoding="utf-8").split("\n\n")]
+ [verify] = [text for text in paragraphs if "`llm_model_used`" in text and "`--llm-verify`" in text]
+ [rubric] = [text for text in paragraphs if "`llm_model_used`" in text and "`rubric_eval`" in text]
+ rule = (
+ "For a Claude 5.5 or later model on the native Claude API, the model is the one the reply names; "
+ "otherwise it is the configured model, unless a server-side `fallback` block in the reply names "
+ "another model."
+ )
+
+ assert rule in rubric
+ assert rule in verify
+ assert "Verdicts kept from a reply cut off at the output-token limit name the model that wrote that reply." in (
+ verify
+ )
+
+ def test_llm_verify_names_the_fallback_model_for_verdicts_kept_from_a_truncated_reply(
+ self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """A fallback model's reply cut off at the token limit still labels the verdicts kept from it."""
+ pytest.importorskip("anthropic")
+ httpx = pytest.importorskip("httpx")
+ from skillevaluator.inference.finding_verifier import FindingVerifier
+
+ monkeypatch.setenv("SKILL_EVAL_LLM_PROVIDER", "anthropic")
+ monkeypatch.setenv("SKILL_EVAL_LLM_MODEL", "claude-opus-5-5")
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key")
+ for name in ("SKILL_EVAL_LLM_BASE_URL", "OPENAI_BASE_URL", "ANTHROPIC_BASE_URL"):
+ monkeypatch.delenv(name, raising=False)
+ (tmp_path / "SKILL.md").write_text("# Example\n\nExample text.\n", encoding="utf-8")
+ result = ValidationResult()
+ for index in range(2):
+ result.add_structured_finding(
+ Finding(
+ category="PII",
+ severity=Severity.HIGH,
+ check_name=f"finding-{index}",
+ message=f"Finding {index}",
+ file_path="SKILL.md",
+ ),
+ is_error=True,
+ )
+ complete = json.dumps(
+ {"index": 0, "verdict": "false_positive", "confidence": "high", "rationale": "Documentation example."}
+ )
+ reply = complete + '\n{"index": 1, "verdict": "true_pos'
+
+ def handler(request):
+ return httpx.Response(
+ 200,
+ json={
+ "id": "msg_test",
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-opus-4-8",
+ "content": [
+ {"type": "fallback", "from": {"model": "claude-opus-5-5"}, "to": {"model": "claude-opus-4-8"}},
+ {"type": "text", "text": reply},
+ ],
+ "stop_reason": "max_tokens",
+ "stop_sequence": None,
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+ },
+ )
+
+ with (
+ httpx.Client(transport=httpx.MockTransport(handler)) as http_client,
+ patch("skillevaluator.inference.FindingVerifier", lambda: FindingVerifier(http_client=http_client)),
+ ):
+ SecurityValidator(verify_llm=True)._verify_findings_with_llm(result, tmp_path)
+
+ by_check = {finding.check_name: finding for finding in result.findings}
+ downgraded = by_check["finding-0"]
+ assert (downgraded.severity, downgraded.metadata["downgraded"]) == (Severity.INFO, True)
+ assert downgraded.metadata["llm_provider"] == "anthropic"
+ assert downgraded.metadata["llm_model_used"] == "claude-opus-4-8"
+ # The cut-off verdict is not kept, so that finding stays unverified and unlabeled.
+ assert by_check["finding-1"].severity == Severity.HIGH
+ assert not any(key.startswith("llm_") for key in by_check["finding-1"].metadata)
+ assert result.metadata["incomplete_scans"] == ["llm-verification"]
+
+ def test_importing_the_security_validator_leaves_the_llm_client_unloaded(self) -> None:
+ """--llm-verify loads the LLM client only when it runs."""
+ script = (
+ "import sys\n"
+ "import skillevaluator.validators.security\n"
+ "print(sorted(name for name in sys.modules if name.startswith('skillevaluator.inference')))\n"
+ )
+ completed = subprocess.run(
+ [sys.executable, "-c", script],
+ capture_output=True,
+ text=True,
+ timeout=120,
+ check=True,
+ )
+
+ assert completed.stdout.strip() == "[]"
+
def test_validate_security_only(self, sample_skill_dir: Path):
"""Test validate_security_only method runs only skillspector scan."""
validator = SecurityValidator()