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.
Python agent-evaluationagent-pluginsagent-securityagent-skillsagentic-aibenchmarkci-templatesclaude-codecodexevaluateevaluationharnesspluginplugin-evaluationsecurity-scannerskill-evalskill-evaluationskill-evaluatorskill-gap-analysisskills
feat(ci): check benchmark cards against the expected source identity (#340)
Narendran Raghavan52c78cbfbbbe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5bba55bd..b145db94 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -291,6 +291,15 @@ All notable changes to SkillEvaluator are documented in this file.upgrade, or not matched by the LLM stage, are reported instead of silentlysuppressing nothing; fingerprints only match static-only runs.+- `scripts/ci/check_public_benchmarks.py` accepts `--expected-source-repository`,+ `--expected-source-revision` and `--expected-evaluator-container-revision`,+ so a publishing pipeline can check that each card names the source it asked+ to evaluate. A card of any verdict fails when the matching `Evaluated source`,+ `Evaluated source revision` or `Evaluator container revision` line is+ missing, `not recorded`, malformed, duplicated or different. Values are+ compared in the canonical form the card records, and any of these options+ implies `--require-files`. Without them the scan is unchanged.+### Changed- Shared LLM calls and the Harbor verifier retry HTTP 408, 429, and every 5xxdiff --git a/docs/benchmark-rollout.mdx b/docs/benchmark-rollout.mdxindex 5304c67e..e5a0dada 100644--- a/docs/benchmark-rollout.mdx+++ b/docs/benchmark-rollout.mdx@@ -165,6 +165,39 @@ skillevaluator validate ./my-skill \--evaluator-container-revision ghcr.io/nvidia/skillevaluator@sha256:0117bc2e...```+A pipeline that publishes cards for a requested source can also check that each+card names that source, so a stale card or one generated for another commit+fails before it is signed or copied:++```bash+uv run python scripts/ci/check_public_benchmarks.py \+ --require-source-provenance \+ --expected-source-repository NVIDIA/NVFlare \+ --expected-source-revision 2263a2ebdab903e87f7e7c0a001d22c3a926a9cf \+ --expected-evaluator-container-revision ghcr.io/nvidia/skillevaluator@sha256:0117bc2e... \+ ./benchmark-backfill/example-skill+```++Each `--expected-*` option is optional and checks one metadata line of every+scanned card, whatever its verdict: `Evaluated source`,+`Evaluated source revision` or `Evaluator container revision`. The line must+appear once in `Evaluation Metadata` and hold the same value; a missing line, a+`not recorded` placeholder, a malformed value, a duplicate or a different value+fails the scan. Only a plain one-line list item counts as that line, which is+how SkillEvaluator renders it. An item that holds a link or inline HTML, or+continues onto a second line, is treated as missing and reported as not+recorded. Only top-level items are read: a nested list item is ignored, not+counted as a duplicate. A value padded with spaces inside its code span is not+canonical. The expected values use the same forms as the `validate`+options above, and a malformed expected value stops the scan with a usage+error. Hex digits in the source revision are compared without regard to case.+Repository names and evaluator container revisions must match the card+exactly, so give a container digest or implementation commit in lower case and+the registry host as the card records it. The card's revision line is the+commit when one was supplied and the content digest otherwise, so pass the+same kind of revision the run received. Any `--expected-*` option also implies+`--require-files`.+A `PASS` card must also record its `Source digest` and `Tier 3 run ID`, so a`PASS` card rendered by an earlier release fails the scan until it isregenerated. Earlier `FAIL`, `NEUTRAL`, and `INCOMPLETE` cards without thosediff --git a/scripts/ci/check_public_benchmarks.py b/scripts/ci/check_public_benchmarks.pyindex 2d05e1bf..0b7c704b 100644--- a/scripts/ci/check_public_benchmarks.py+++ b/scripts/ci/check_public_benchmarks.py@@ -28,6 +28,7 @@ from urllib.parse import unquote as url_unquotefrom markdown_it import MarkdownItfrom skillevaluator.publication_text import publication_confusable_skeleton, publication_identity_present+from skillevaluator.source_identity import evaluated_source_revision, normalized_evaluated_sourceif TYPE_CHECKING:from markdown_it.token import Token@@ -299,6 +300,69 @@ _PASS_SOURCE_PROVENANCE_RULES = (("Evaluator container revision", _valid_pass_container_revision),)+# Card label, ExpectedSource attribute and the accepted shape, in card order.+_EXPECTED_SOURCE_FIELDS = (+ ("Evaluated source", "repository", "an owner/name repository"),+ ("Evaluated source revision", "revision", "a full Git commit or a sha256, sha384 or sha512 digest"),+ (+ "Evaluator container revision",+ "evaluator_container_revision",+ "a full Git commit or a container reference with a tag or digest",+ ),+)+++def _normalized_identity_value(field: str, value: str) -> str | None:+ """Return one card identity value in ``source_identity``'s canonical spelling.++ Both the expectation and the card go through the library's normalizer, so a+ hex revision written in upper case still matches and a value the library+ would never publish matches nothing.+ """+ if field == "Evaluated source revision":+ # The card's revision line is the commit when the run supplied one and+ # the content digest otherwise; a value can only take one of the shapes.+ return (+ evaluated_source_revision(normalized_evaluated_source({"commit": value, "content_digest": value})) or None+ )+ key = "repository" if field == "Evaluated source" else "evaluator_container_revision"+ normalized = normalized_evaluated_source({key: value})+ return normalized[key] if normalized else None+++@dataclass(frozen=True)+class ExpectedSource:+ """The source identity a publishing pipeline asked to evaluate.++ Each attribute names one card line. A card scanned against an expectation+ must record each named line exactly once, with the same canonical value, so+ a stale card or one generated for another source cannot be published under+ this request. An attribute left as ``None`` is not checked.+ """++ repository: str | None = None+ revision: str | None = None+ evaluator_container_revision: str | None = None++ def __post_init__(self) -> None:+ for field, attribute, shape in _EXPECTED_SOURCE_FIELDS:+ value = getattr(self, attribute)+ if value is None:+ continue+ normalized = _normalized_identity_value(field, value) if isinstance(value, str) else None+ if normalized is None:+ raise ValueError(f"expected {field.lower()} must be {shape}: {value!r}")+ object.__setattr__(self, attribute, normalized)++ def fields(self) -> tuple[tuple[str, str], ...]:+ """Return ``(card label, canonical value)`` for every expected line."""+ return tuple(+ (field, value)+ for field, attribute, _shape in _EXPECTED_SOURCE_FIELDS+ if (value := getattr(self, attribute)) is not None+ )++_TIER_COMPLETION_STATUSES = {1: frozenset({"PASSED", "PASSED WITH OBSERVATIONS"}),2: frozenset({"PASSED", "PASSED WITH OBSERVATIONS"}),@@ -537,7 +601,9 @@ class _HTMLAttributeParser(HTMLParser):self.values.extend(value for _name, value in attrs if value is not None)alt = next((value for name, value in attrs if name.casefold() == "alt"), None)line = self.getpos()[0]- self.events.append(("start", normalized_tag, _html_element_is_visually_hidden(normalized_tag, attrs), alt, line))+ self.events.append(+ ("start", normalized_tag, _html_element_is_visually_hidden(normalized_tag, attrs), alt, line)+ )attribute_names = {name.casefold() for name, _value in attrs}if (normalized_tag in _AMBIGUOUS_HTML_RENDERING_TAGS@@ -696,7 +762,12 @@ def benchmark_files(roots: list[Path]) -> list[Path]:return sorted(found)-def scan_file(path: Path, *, require_source_provenance: bool = False) -> list[Offender]:+def scan_file(+ path: Path,+ *,+ require_source_provenance: bool = False,+ expected_source: ExpectedSource | None = None,+) -> list[Offender]:try:if path.stat().st_size > _MAX_BENCHMARK_BYTES:return [Offender(path, 1, f"BENCHMARK.md exceeds {_MAX_BENCHMARK_BYTES:,} bytes")]@@ -760,8 +831,7 @@ def scan_file(path: Path, *, require_source_provenance: bool = False) -> list[Ofif environment_field is not None:candidate_lines = (*candidate_lines,- "- Environment: "- + publication_confusable_skeleton(environment_field.group("value")),+ "- Environment: " + publication_confusable_skeleton(environment_field.group("value")),)if any(pattern.search(candidate_line) for candidate_line in candidate_lines):offenders.append(Offender(path, line_number, reason))@@ -771,14 +841,15 @@ def scan_file(path: Path, *, require_source_provenance: bool = False) -> list[Ofif reason not in {"retired product identity", "internal environment identity"}:continueif (- pattern.search(semantic_document)- or pattern.search(publication_confusable_skeleton(semantic_document))+ pattern.search(semantic_document) or pattern.search(publication_confusable_skeleton(semantic_document))) and not any(offender.reason == reason for offender in offenders):offenders.append(Offender(path, 1, reason))_check_required_headings(path, text, offenders)_check_metadata_semantics(path, text, offenders, require_source_provenance=require_source_provenance)_check_verdict_tier_consistency(path, text, offenders, require_source_provenance=require_source_provenance)+ if expected_source is not None:+ _check_expected_source(path, text, offenders, expected_source)_check_score_transitions(path, text, offenders)_check_untrusted_structural_headings(path, text, offenders)_check_html_rendering_safety(path, text, offenders)@@ -1768,10 +1839,7 @@ def _contains_disallowed_category_c(value: str, *, allow_layout_whitespace: bool"""Return whether text contains a disallowed control or line separator."""return any((not allow_layout_whitespace or character not in {"\n", "\r", "\t"})- and (- unicodedata.category(character).startswith("C")- or unicodedata.category(character) in {"Zl", "Zp"}- )+ and (unicodedata.category(character).startswith("C") or unicodedata.category(character) in {"Zl", "Zp"})for character in value)@@ -1891,6 +1959,48 @@ def _check_source_provenance(path: Path, text: str, offenders: list[Offender]) -offenders.append(Offender(path, line_number, f"publication PASS without recorded {field.lower()}"))+def _check_expected_source(path: Path, text: str, offenders: list[Offender], expected: ExpectedSource) -> None:+ """Reject a card that does not name the source the publishing pipeline requested.++ This applies to every verdict: a FAIL card for another commit is as wrong+ to publish under this request as a PASS card.++ Only a plain one-line list item counts as the field's line, which is how+ the reporter renders it. ``_metadata_list_items`` leaves out an item with a+ link, image or inline HTML, or one that continues onto a second line, so+ such a line is reported as not recorded rather than as not canonical. The+ strict provenance scan treats it as missing too. Only top-level items are+ read, so a nested item is ignored rather than counted as a duplicate. The parser stays strict on+ purpose: a link or inline HTML can make the visible value differ from the+ raw text.+ """+ metadata_lines = _metadata_section_lines(text)+ fallback_line = metadata_lines[0][0] if metadata_lines else 1+ for field, expected_value in expected.fields():+ name = field.lower()+ matches = _metadata_field_matches(metadata_lines, field)+ line_number = matches[0][0] if matches else fallback_line+ if len(matches) > 1:+ offenders.append(Offender(path, line_number, f"{name} recorded more than once, so it cannot match"))+ continue+ value = matches[0][1] if matches else ""+ if not value or _NOT_RECORDED_VALUE.fullmatch(value):+ offenders.append(Offender(path, line_number, f"{name} not recorded, but an expected value was given"))+ continue+ # The line is there but holds something the library would never render,+ # so point the operator at the malformed value rather than a missing line.+ recorded = _code_span_value(value)+ # Padding inside the code span is never rendered, and a parser that reads+ # the raw value would not see the canonical identity.+ if recorded is not None and recorded != recorded.strip():+ recorded = None+ normalized = _normalized_identity_value(field, recorded) if recorded is not None else None+ if normalized is None:+ offenders.append(Offender(path, line_number, f"{name} is not a canonical value, so it cannot match"))+ elif normalized != expected_value:+ offenders.append(Offender(path, line_number, f"{name} does not match the expected value"))++def _check_pass_provenance(path: Path, text: str, offenders: list[Offender]) -> None:"""Reject PASS cards that replace required provenance with legacy placeholders."""metadata_lines = _metadata_section_lines(text)@@ -1939,6 +2049,7 @@ def find_offenders(roots: list[Path],*,require_source_provenance: bool = False,+ expected_source: ExpectedSource | None = None,) -> tuple[list[Path], list[Offender]]:files: set[Path] = set()offenders: list[Offender] = []@@ -1952,7 +2063,11 @@ def find_offenders(offenders.extend(offenderfor path in sorted_files- for offender in scan_file(path, require_source_provenance=require_source_provenance)+ for offender in scan_file(+ path,+ require_source_provenance=require_source_provenance,+ expected_source=expected_source,+ ))return sorted_files, offenders@@ -1976,14 +2091,45 @@ def _parser() -> argparse.ArgumentParser:action="store_true",help="Fail PASS cards that do not record an evaluated source repository and revision",)+ parser.add_argument(+ "--expected-source-repository",+ metavar="OWNER/NAME",+ help="Fail cards whose Evaluated source is missing or names another repository; implies --require-files",+ )+ parser.add_argument(+ "--expected-source-revision",+ metavar="REVISION",+ help=(+ "Fail cards whose Evaluated source revision is missing or differs (a full Git commit or a "+ "sha256/sha384/sha512 digest); implies --require-files"+ ),+ )+ parser.add_argument(+ "--expected-evaluator-container-revision",+ metavar="REFERENCE",+ help="Fail cards whose Evaluator container revision is missing or differs; implies --require-files",+ )return parserdef main(argv: list[str] | None = None) -> int:- args = _parser().parse_args(argv)+ parser = _parser()+ args = parser.parse_args(argv)+ expected_values = {+ "repository": args.expected_source_repository,+ "revision": args.expected_source_revision,+ "evaluator_container_revision": args.expected_evaluator_container_revision,+ }+ expected_source = None+ if any(value is not None for value in expected_values.values()):+ try:+ expected_source = ExpectedSource(**expected_values)+ except ValueError as error:+ parser.error(str(error))files, offenders = find_offenders(args.paths,require_source_provenance=args.require_source_provenance,+ expected_source=expected_source,)if offenders:@@ -1991,7 +2137,9 @@ def main(argv: list[str] | None = None) -> int:for offender in offenders:print(f" {offender}")return 1- if args.require_files and not files:+ # An expectation exists to bind a card to a request, so finding no card to+ # bind is a failure rather than a vacuous pass.+ if (args.require_files or expected_source is not None) and not files:print("Public benchmark scan FAILED: no BENCHMARK.md files found.")return 1diff --git a/tests/test_benchmark_rollout_docs.py b/tests/test_benchmark_rollout_docs.pyindex 197ca092..3af9b3f2 100644--- a/tests/test_benchmark_rollout_docs.py+++ b/tests/test_benchmark_rollout_docs.py@@ -31,6 +31,29 @@ def test_rollout_runbook_covers_safe_backfill_and_freshness() -> None:assert "without completed required Tier 1, Tier 2," in runbook+def test_rollout_runbook_documents_the_expected_source_options() -> None:+ runbook = " ".join((REPO / "docs/benchmark-rollout.mdx").read_text(encoding="utf-8").split())++ for flag in (+ "--expected-source-repository",+ "--expected-source-revision",+ "--expected-evaluator-container-revision",+ ):+ assert flag in runbook+ assert "`--expected-*` option also implies `--require-files`" in runbook+ # Only the source revision is case-folded; repository names and container+ # revisions are compared exactly, so the runbook must not promise more.+ assert "Hex digits in the source revision are compared without regard to case." in runbook+ assert "Hex digits are compared without regard to case" not in runbook+ assert "Repository names and evaluator container revisions must match the card exactly" in runbook+ # The gate reads only plain one-line metadata items; anything else counts as missing.+ assert "Only a plain one-line list item counts as that line" in runbook+ assert (+ "An item that holds a link or inline HTML, or continues onto a second line, "+ "is treated as missing and reported as not recorded."+ ) in runbook++def test_ci_runs_benchmark_gate_with_project_dependencies() -> None:workflow = (REPO / ".github/workflows/ci.yml").read_text(encoding="utf-8")diff --git a/tests/test_benchmark_source_provenance.py b/tests/test_benchmark_source_provenance.pyindex 4d89bb33..a6f05fd6 100644--- a/tests/test_benchmark_source_provenance.py+++ b/tests/test_benchmark_source_provenance.py@@ -520,6 +520,282 @@ class TestReporterGateRoundTrip:assert [o.reason for o in benchmark_gate.scan_file(path, require_source_provenance=True)] == []+_REPOSITORY = "NVIDIA/demo_skills"+++def _expected(**overrides: str | None) -> benchmark_gate.ExpectedSource:+ values: dict[str, str | None] = {+ "repository": _REPOSITORY,+ "revision": _COMMIT_A,+ "evaluator_container_revision": _CONTAINER,+ }+ values.update(overrides)+ return benchmark_gate.ExpectedSource(**values)+++def _scan_expected(+ tmp_path: Path,+ card: str,+ expected: benchmark_gate.ExpectedSource,+ *,+ require: bool = True,+) -> list[str]:+ path = tmp_path / "BENCHMARK.md"+ path.write_text(card, encoding="utf-8")+ offenders = benchmark_gate.scan_file(path, require_source_provenance=require, expected_source=expected)+ return [offender.reason for offender in offenders]+++def _recorded_lines(**values: str) -> str:+ """Return the three identity lines with any of them replaced by ``values``."""+ lines = {+ "Evaluated source": f"`{_REPOSITORY}`",+ "Evaluated source revision": f"`{_COMMIT_A}`",+ "Evaluator container revision": f"`{_CONTAINER}`",+ }+ lines.update(values)+ return "".join(f"- {field}: {value}\n" for field, value in lines.items())+++class TestExpectedSourceBinding:+ """A publishing pipeline can bind a card to the source it asked to evaluate."""++ def test_the_recorded_card_matches_its_request(self, tmp_path: Path) -> None:+ assert _recorded_lines() == _RECORDED+ assert _scan_expected(tmp_path, _pass_card(_RECORDED), _expected()) == []+ assert _scan_expected(tmp_path, _pass_card(_RECORDED), _expected(), require=False) == []++ @pytest.mark.parametrize(+ ("override", "reason"),+ [+ ({"repository": "NVIDIA/other_skills"}, "evaluated source does not match the expected value"),+ ({"revision": _COMMIT_B}, "evaluated source revision does not match the expected value"),+ ({"revision": _DIGEST}, "evaluated source revision does not match the expected value"),+ (+ {"evaluator_container_revision": "ghcr.io/nvidia/skillevaluator@sha256:" + "1" * 64},+ "evaluator container revision does not match the expected value",+ ),+ ],+ )+ def test_a_card_for_another_source_fails(self, tmp_path: Path, override: dict[str, str], reason: str) -> None:+ assert _scan_expected(tmp_path, _pass_card(_RECORDED), _expected(**override)) == [reason]++ def test_a_repository_differing_only_in_case_is_another_repository(self, tmp_path: Path) -> None:+ """The library merges identities case-sensitively, so the gate compares them the same way."""+ reasons = _scan_expected(tmp_path, _pass_card(_RECORDED), _expected(repository=_REPOSITORY.lower()))+ assert reasons == ["evaluated source does not match the expected value"]++ @pytest.mark.parametrize("source_lines", [_NOT_RECORDED, _ABSENT])+ def test_a_card_without_the_identity_fails_the_expectation(self, tmp_path: Path, source_lines: str) -> None:+ reasons = _scan_expected(tmp_path, _pass_card(source_lines), _expected(), require=False)+ assert reasons == [+ "evaluated source not recorded, but an expected value was given",+ "evaluated source revision not recorded, but an expected value was given",+ "evaluator container revision not recorded, but an expected value was given",+ ]++ @pytest.mark.parametrize(+ ("field", "value"),+ [+ ("Evaluated source", "`not a repository`"),+ ("Evaluated source", f"{_REPOSITORY}"),+ ("Evaluated source", f"`{_REPOSITORY}` (fork)"),+ ("Evaluated source", f"``{_REPOSITORY}``"),+ ("Evaluated source", f"` {_REPOSITORY} `"),+ ("Evaluated source", f"`{_REPOSITORY}\u00a0`"),+ ("Evaluated source", f"`\t{_REPOSITORY}`"),+ ("Evaluated source revision", f"` {_COMMIT_A} `"),+ ("Evaluated source revision", f"`{_COMMIT_A[:12]}`"),+ ("Evaluator container revision", "`ghcr.io/nvidia/skillevaluator`"),+ ],+ )+ def test_a_malformed_recorded_value_never_matches(self, tmp_path: Path, field: str, value: str) -> None:+ """A present but malformed line is named as such, not reported as a missing line."""+ card = _pass_card(_recorded_lines(**{field: value}))+ reasons = _scan_expected(tmp_path, card, _expected(), require=False)+ assert reasons == [f"{field.lower()} is not a canonical value, so it cannot match"]++ @pytest.mark.parametrize(+ "value",+ [+ f"[`{_REPOSITORY}`](https://example.com)",+ f"`{_REPOSITORY}` <span></span>",+ f"`{_REPOSITORY}`\n continued",+ ],+ ids=["link", "inline-html", "continuation-line"],+ )+ def test_only_a_plain_one_line_item_is_read(self, tmp_path: Path, value: str) -> None:+ """An item with a link, inline HTML or a second line is missing, as the runbook says.++ The strict provenance scan reads the same items, so both checks treat it as missing.+ """+ card = _pass_card(_recorded_lines(**{"Evaluated source": value}))+ assert _scan_expected(tmp_path, card, _expected(), require=False) == [+ "evaluated source not recorded, but an expected value was given"+ ]+ assert _scan(tmp_path, card, require=True) == [+ "missing metadata field: - Evaluated source:",+ "publication PASS without recorded evaluated source",+ ]++ @pytest.mark.parametrize("value", [_UNRECORDED, "not recorded", ""])+ def test_a_placeholder_or_empty_line_is_reported_as_not_recorded(self, tmp_path: Path, value: str) -> None:+ card = _pass_card(_recorded_lines(**{"Evaluated source revision": value}))+ reasons = _scan_expected(tmp_path, card, _expected(), require=False)+ assert reasons == ["evaluated source revision not recorded, but an expected value was given"]++ def test_a_duplicated_line_cannot_match(self, tmp_path: Path) -> None:+ card = _pass_card(_RECORDED + f"- Evaluated source revision: `{_COMMIT_B}`\n")+ reasons = _scan_expected(tmp_path, card, _expected(), require=False)+ assert reasons == ["evaluated source revision recorded more than once, so it cannot match"]++ def test_only_the_metadata_line_counts(self, tmp_path: Path) -> None:+ """A matching value elsewhere on the card does not stand in for the metadata line."""+ decoy = (+ f"\n```text\n- Evaluated source revision: `{_COMMIT_A}`\n```\n"+ f"\n<!-- - Evaluated source: `{_REPOSITORY}` -->\n"+ )+ card = _pass_card(_NOT_RECORDED) + decoy+ reasons = _scan_expected(tmp_path, card, _expected(evaluator_container_revision=None), require=False)+ assert reasons == [+ "evaluated source not recorded, but an expected value was given",+ "evaluated source revision not recorded, but an expected value was given",+ ]++ def test_hex_case_does_not_cause_a_false_mismatch(self, tmp_path: Path) -> None:+ upper_card = _pass_card(_recorded_lines(**{"Evaluated source revision": f"`{_COMMIT_A.upper()}`"}))+ assert _scan_expected(tmp_path, upper_card, _expected(), require=False) == []+ assert _scan_expected(tmp_path, _pass_card(_RECORDED), _expected(revision=_COMMIT_A.upper())) == []++ def test_container_revisions_are_compared_exactly(self, tmp_path: Path) -> None:+ """Only the source revision is case-folded, as the runbook says."""+ for container in (+ "ghcr.io/nvidia/skillevaluator@sha256:" + ("0117bc2e" * 8).upper(),+ _COMMIT_B.upper(),+ ):+ with pytest.raises(ValueError, match="expected evaluator container revision must be"):+ benchmark_gate.ExpectedSource(evaluator_container_revision=container)+ upper_host = "GHCR.io" + _CONTAINER.removeprefix("ghcr.io")+ card = _pass_card(_recorded_lines(**{"Evaluator container revision": f"`{upper_host}`"}))+ assert _scan_expected(tmp_path, card, _expected(), require=False) == [+ "evaluator container revision does not match the expected value"+ ]+ assert _scan_expected(tmp_path, card, _expected(evaluator_container_revision=upper_host), require=False) == []++ def test_a_content_digest_revision_is_matched(self, tmp_path: Path) -> None:+ card = _pass_card(_recorded_lines(**{"Evaluated source revision": f"`{_DIGEST}`"}))+ assert _scan_expected(tmp_path, card, _expected(revision=_DIGEST.upper())) == []+ assert _scan_expected(tmp_path, card, _expected(revision=_COMMIT_A)) == [+ "evaluated source revision does not match the expected value"+ ]++ def test_an_unset_field_is_not_checked(self, tmp_path: Path) -> None:+ card = _pass_card(_recorded_lines(**{"Evaluated source revision": f"`{_COMMIT_B}`"}))+ expected = benchmark_gate.ExpectedSource(repository=_REPOSITORY)+ assert expected.fields() == (("Evaluated source", _REPOSITORY),)+ assert _scan_expected(tmp_path, card, expected) == []++ def test_a_non_pass_card_for_another_source_also_fails(self, tmp_path: Path) -> None:+ card = _card({"repository": _REPOSITORY, "commit": _COMMIT_B, "evaluator_container_revision": _CONTAINER})+ assert "Overall verdict: INCOMPLETE" in card+ path = tmp_path / "BENCHMARK.md"+ path.write_text(card, encoding="utf-8")+ baseline = {offender.reason for offender in benchmark_gate.scan_file(path)}+ reasons = {offender.reason for offender in benchmark_gate.scan_file(path, expected_source=_expected())}+ assert reasons - baseline == {"evaluated source revision does not match the expected value"}++ @pytest.mark.parametrize(+ "source",+ [+ {"repository": _REPOSITORY, "commit": _COMMIT_A, "evaluator_container_revision": _CONTAINER},+ {"repository": "some-org/repo.name", "content_digest": _DIGEST, "evaluator_container_revision": _COMMIT_B},+ ],+ )+ def test_a_rendered_card_matches_the_identity_it_was_given(self, tmp_path: Path, source: dict[str, str]) -> None:+ card = _card(source)+ path = tmp_path / "BENCHMARK.md"+ path.write_text(card, encoding="utf-8")+ expected = benchmark_gate.ExpectedSource(+ repository=source["repository"],+ revision=source.get("commit") or source["content_digest"],+ evaluator_container_revision=source["evaluator_container_revision"],+ )+ baseline = benchmark_gate.scan_file(path)+ assert benchmark_gate.scan_file(path, expected_source=expected) == baseline++ @pytest.mark.parametrize(+ "values",+ [+ {"repository": "not a repository"},+ {"repository": "https://github.com/NVIDIA/demo_skills"},+ {"revision": _COMMIT_A[:7]},+ {"revision": "sha256:" + "ab" * 16},+ {"evaluator_container_revision": "ghcr.io/nvidia/skillevaluator"},+ {"repository": 42},+ ],+ )+ def test_a_non_canonical_expectation_is_refused(self, values: dict[str, object]) -> None:+ with pytest.raises(ValueError, match="must be"):+ benchmark_gate.ExpectedSource(**values)++ def test_the_expectation_is_stored_in_canonical_form(self) -> None:+ expected = benchmark_gate.ExpectedSource(repository=f" {_REPOSITORY} ", revision=_DIGEST.upper())+ assert expected.repository == _REPOSITORY+ assert expected.revision == _DIGEST+ assert expected.evaluator_container_revision is None+++class TestExpectedSourceEntryPoints:+ """The expectation has to survive main() and find_offenders(), not just scan_file()."""++ _FLAGS = (+ "--expected-source-repository",+ _REPOSITORY,+ "--expected-source-revision",+ _COMMIT_A,+ "--expected-evaluator-container-revision",+ _CONTAINER,+ )++ def _write(self, tmp_path: Path, card: str) -> Path:+ (tmp_path / "BENCHMARK.md").write_text(card, encoding="utf-8")+ return tmp_path++ def test_main_accepts_the_requested_card(self, tmp_path: Path) -> None:+ root = self._write(tmp_path, _pass_card(_RECORDED))+ assert benchmark_gate.main(["--require-source-provenance", *self._FLAGS, str(root)]) == 0++ def test_main_rejects_a_card_for_another_commit(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ root = self._write(tmp_path, _pass_card(_RECORDED))+ assert benchmark_gate.main(["--expected-source-revision", _COMMIT_B, str(root)]) == 1+ assert "evaluated source revision does not match the expected value" in capsys.readouterr().out++ def test_main_rejects_a_card_without_the_identity(self, tmp_path: Path) -> None:+ root = self._write(tmp_path, _pass_card(_NOT_RECORDED))+ assert benchmark_gate.main([str(root)]) == 0+ assert benchmark_gate.main(["--expected-source-repository", _REPOSITORY, str(root)]) == 1++ def test_an_expectation_requires_a_card(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ assert benchmark_gate.main([str(tmp_path)]) == 0+ capsys.readouterr()+ assert benchmark_gate.main(["--expected-source-revision", _COMMIT_A, str(tmp_path)]) == 1+ assert "no BENCHMARK.md files found" in capsys.readouterr().out++ def test_a_non_canonical_flag_is_a_usage_error(self, tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None:+ root = self._write(tmp_path, _pass_card(_RECORDED))+ with pytest.raises(SystemExit) as raised:+ benchmark_gate.main(["--expected-source-revision", _COMMIT_A[:7], str(root)])+ assert raised.value.code == 2+ assert "expected evaluated source revision must be" in capsys.readouterr().err++ def test_find_offenders_propagates_the_expectation(self, tmp_path: Path) -> None:+ root = self._write(tmp_path, _pass_card(_RECORDED))+ _files, offenders = benchmark_gate.find_offenders([root], expected_source=_expected(revision=_COMMIT_B))+ assert [offender.reason for offender in offenders] == [+ "evaluated source revision does not match the expected value"+ ]++class TestIdentityResolution:"""Two orchestration channels, resolved per field and never silently reconciled."""